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
2d2e1a54123e12cac27d66005e8c1f8fb71901ff
aa3f8992ef7806974bc1ffd468baa0c79f4d6643
/tests/lean/run/imp_curly.lean
53ab9a813e87e1094b5d690784aebb8aef029dd4
[ "Apache-2.0" ]
permissive
codyroux/lean
7f8dff750722c5382bdd0a9a9275dc4bb2c58dd3
0cca265db19f7296531e339192e9b9bae4a31f8b
refs/heads/master
1,610,909,964,159
1,407,084,399,000
1,416,857,075,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
263
lean
import data.nat.basic open nat theorem zero_left (n : ℕ) : 0 + n = n := nat.induction_on n !add.zero_right (take m IH, show 0 + succ m = succ m, from calc 0 + succ m = succ (0 + m) : add.succ_right ... = succ m : IH)
11cdb310d88e52c498cf8778290162fdb5cc54bf
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/dynamics/fixed_points/basic.lean
e25efac5199295c5efb461793c8d85936c2cdf2f
[ "Apache-2.0" ]
permissive
alreadydone/mathlib
dc0be621c6c8208c581f5170a8216c5ba6721927
c982179ec21091d3e102d8a5d9f5fe06c8fafb73
refs/heads/master
1,685,523,275,196
1,670,184,141,000
1,670,184,141,000
287,574,545
0
0
Apache-2.0
1,670,290,714,000
1,597,421,623,000
Lean
UTF-8
Lean
false
false
6,500
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 data.set.function import logic.function.iterate import group_theory.perm.basic /-! # Fixed points of a self-map In this file we define * the predicate `is_fixed_pt f x := f x = x`; * the set `fixed_points f` of fixed points of a self-map `f`. We also prove some simple lemmas about `is_fixed_pt` and `∘`, `iterate`, and `semiconj`. ## Tags fixed point -/ universes u v variables {α : Type u} {β : Type v} {f fa g : α → α} {x y : α} {fb : β → β} {m n k : ℕ} {e : α ≃ α} namespace function /-- A point `x` is a fixed point of `f : α → α` if `f x = x`. -/ def is_fixed_pt (f : α → α) (x : α) := f x = x /-- Every point is a fixed point of `id`. -/ lemma is_fixed_pt_id (x : α) : is_fixed_pt id x := (rfl : _) namespace is_fixed_pt instance [h : decidable_eq α] {f : α → α} {x : α} : decidable (is_fixed_pt f x) := h (f x) x /-- If `x` is a fixed point of `f`, then `f x = x`. This is useful, e.g., for `rw` or `simp`.-/ protected lemma eq (hf : is_fixed_pt f x) : f x = x := hf /-- If `x` is a fixed point of `f` and `g`, then it is a fixed point of `f ∘ g`. -/ protected lemma comp (hf : is_fixed_pt f x) (hg : is_fixed_pt g x) : is_fixed_pt (f ∘ g) x := calc f (g x) = f x : congr_arg f hg ... = x : hf /-- If `x` is a fixed point of `f`, then it is a fixed point of `f^[n]`. -/ protected lemma iterate (hf : is_fixed_pt f x) (n : ℕ) : is_fixed_pt (f^[n]) x := iterate_fixed hf n /-- If `x` is a fixed point of `f ∘ g` and `g`, then it is a fixed point of `f`. -/ lemma left_of_comp (hfg : is_fixed_pt (f ∘ g) x) (hg : is_fixed_pt g x) : is_fixed_pt f x := calc f x = f (g x) : congr_arg f hg.symm ... = x : hfg /-- If `x` is a fixed point of `f` and `g` is a left inverse of `f`, then `x` is a fixed point of `g`. -/ lemma to_left_inverse (hf : is_fixed_pt f x) (h : left_inverse g f) : is_fixed_pt g x := calc g x = g (f x) : congr_arg g hf.symm ... = x : h x /-- If `g` (semi)conjugates `fa` to `fb`, then it sends fixed points of `fa` to fixed points of `fb`. -/ protected lemma map {x : α} (hx : is_fixed_pt fa x) {g : α → β} (h : semiconj g fa fb) : is_fixed_pt fb (g x) := calc fb (g x) = g (fa x) : (h.eq x).symm ... = g x : congr_arg g hx protected lemma apply {x : α} (hx : is_fixed_pt f x) : is_fixed_pt f (f x) := by convert hx lemma preimage_iterate {s : set α} (h : is_fixed_pt (set.preimage f) s) (n : ℕ) : is_fixed_pt (set.preimage (f^[n])) s := by { rw set.preimage_iterate_eq, exact h.iterate n, } end is_fixed_pt @[simp] lemma injective.is_fixed_pt_apply_iff (hf : injective f) {x : α} : is_fixed_pt f (f x) ↔ is_fixed_pt f x := ⟨λ h, hf h.eq, is_fixed_pt.apply⟩ /-- The set of fixed points of a map `f : α → α`. -/ def fixed_points (f : α → α) : set α := {x : α | is_fixed_pt f x} instance fixed_points.decidable [decidable_eq α] (f : α → α) (x : α) : decidable (x ∈ fixed_points f) := is_fixed_pt.decidable @[simp] lemma mem_fixed_points : x ∈ fixed_points f ↔ is_fixed_pt f x := iff.rfl lemma mem_fixed_points_iff {α : Type*} {f : α → α} {x : α} : x ∈ fixed_points f ↔ f x = x := by refl @[simp] lemma fixed_points_id : fixed_points (@id α) = set.univ := set.ext $ λ _, by simpa using is_fixed_pt_id _ lemma fixed_points_subset_range : fixed_points f ⊆ set.range f := λ x hx, ⟨x, hx⟩ /-- If `g` semiconjugates `fa` to `fb`, then it sends fixed points of `fa` to fixed points of `fb`. -/ lemma semiconj.maps_to_fixed_pts {g : α → β} (h : semiconj g fa fb) : set.maps_to g (fixed_points fa) (fixed_points fb) := λ x hx, hx.map h /-- Any two maps `f : α → β` and `g : β → α` are inverse of each other on the sets of fixed points of `f ∘ g` and `g ∘ f`, respectively. -/ lemma inv_on_fixed_pts_comp (f : α → β) (g : β → α) : set.inv_on f g (fixed_points $ f ∘ g) (fixed_points $ g ∘ f) := ⟨λ x, id, λ x, id⟩ /-- Any map `f` sends fixed points of `g ∘ f` to fixed points of `f ∘ g`. -/ lemma maps_to_fixed_pts_comp (f : α → β) (g : β → α) : set.maps_to f (fixed_points $ g ∘ f) (fixed_points $ f ∘ g) := λ x hx, hx.map $ λ x, rfl /-- Given two maps `f : α → β` and `g : β → α`, `g` is a bijective map between the fixed points of `f ∘ g` and the fixed points of `g ∘ f`. The inverse map is `f`, see `inv_on_fixed_pts_comp`. -/ lemma bij_on_fixed_pts_comp (f : α → β) (g : β → α) : set.bij_on g (fixed_points $ f ∘ g) (fixed_points $ g ∘ f) := (inv_on_fixed_pts_comp f g).bij_on (maps_to_fixed_pts_comp g f) (maps_to_fixed_pts_comp f g) /-- If self-maps `f` and `g` commute, then they are inverse of each other on the set of fixed points of `f ∘ g`. This is a particular case of `function.inv_on_fixed_pts_comp`. -/ lemma commute.inv_on_fixed_pts_comp (h : commute f g) : set.inv_on f g (fixed_points $ f ∘ g) (fixed_points $ f ∘ g) := by simpa only [h.comp_eq] using inv_on_fixed_pts_comp f g /-- If self-maps `f` and `g` commute, then `f` is bijective on the set of fixed points of `f ∘ g`. This is a particular case of `function.bij_on_fixed_pts_comp`. -/ lemma commute.left_bij_on_fixed_pts_comp (h : commute f g) : set.bij_on f (fixed_points $ f ∘ g) (fixed_points $ f ∘ g) := by simpa only [h.comp_eq] using bij_on_fixed_pts_comp g f /-- If self-maps `f` and `g` commute, then `g` is bijective on the set of fixed points of `f ∘ g`. This is a particular case of `function.bij_on_fixed_pts_comp`. -/ lemma commute.right_bij_on_fixed_pts_comp (h : commute f g) : set.bij_on g (fixed_points $ f ∘ g) (fixed_points $ f ∘ g) := by simpa only [h.comp_eq] using bij_on_fixed_pts_comp f g end function namespace equiv.is_fixed_pt protected lemma symm (h : function.is_fixed_pt e x) : function.is_fixed_pt e.symm x := h.to_left_inverse e.left_inverse_symm protected lemma zpow (h : function.is_fixed_pt e x) (n : ℤ) : function.is_fixed_pt ⇑(e^n) x := begin cases n, { rw [int.of_nat_eq_coe, zpow_coe_nat, ← equiv.perm.iterate_eq_pow], exact h.iterate n, }, { change function.is_fixed_pt ⇑(e^(-(↑(n + 1) : ℤ))) x, rw [zpow_neg, zpow_coe_nat, ← inv_pow, ← equiv.perm.iterate_eq_pow, equiv.perm.inv_def], exact (equiv.is_fixed_pt.symm h).iterate (n + 1), }, end end equiv.is_fixed_pt
e479c54afcf74120e669c386c871cfda8986a9fc
367134ba5a65885e863bdc4507601606690974c1
/src/analysis/calculus/local_extr.lean
c25b68036b7599458bdf900df3af53d0cf9c6f14
[ "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
16,938
lean
/- Copyright (c) 2019 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudryashov -/ import topology.local_extr import analysis.calculus.deriv /-! # Local extrema of smooth functions ## Main definitions In a real normed space `E` we define `pos_tangent_cone_at (s : set E) (x : E)`. This would be the same as `tangent_cone_at ℝ≥0 s x` if we had a theory of normed semifields. This set is used in the proof of Fermat's Theorem (see below), and can be used to formalize [Lagrange multipliers](https://en.wikipedia.org/wiki/Lagrange_multiplier) and/or [Karush–Kuhn–Tucker conditions](https://en.wikipedia.org/wiki/Karush–Kuhn–Tucker_conditions). ## Main statements For each theorem name listed below, we also prove similar theorems for `min`, `extr` (if applicable)`, and `(f)deriv` instead of `has_fderiv`. * `is_local_max_on.has_fderiv_within_at_nonpos` : `f' y ≤ 0` whenever `a` is a local maximum of `f` on `s`, `f` has derivative `f'` at `a` within `s`, and `y` belongs to the positive tangent cone of `s` at `a`. * `is_local_max_on.has_fderiv_within_at_eq_zero` : In the settings of the previous theorem, if both `y` and `-y` belong to the positive tangent cone, then `f' y = 0`. * `is_local_max.has_fderiv_at_eq_zero` : [Fermat's Theorem](https://en.wikipedia.org/wiki/Fermat's_theorem_(stationary_points)), the derivative of a differentiable function at a local extremum point equals zero. * `exists_has_deriv_at_eq_zero` : [Rolle's Theorem](https://en.wikipedia.org/wiki/Rolle's_theorem): given a function `f` continuous on `[a, b]` and differentiable on `(a, b)`, there exists `c ∈ (a, b)` such that `f' c = 0`. ## Implementation notes For each mathematical fact we prove several versions of its formalization: * for maxima and minima; * using `has_fderiv*`/`has_deriv*` or `fderiv*`/`deriv*`. For the `fderiv*`/`deriv*` versions we omit the differentiability condition whenever it is possible due to the fact that `fderiv` and `deriv` are defined to be zero for non-differentiable functions. ## References * [Fermat's Theorem](https://en.wikipedia.org/wiki/Fermat's_theorem_(stationary_points)); * [Rolle's Theorem](https://en.wikipedia.org/wiki/Rolle's_theorem); * [Tangent cone](https://en.wikipedia.org/wiki/Tangent_cone); ## Tags local extremum, Fermat's Theorem, Rolle's Theorem -/ universes u v open filter set open_locale topological_space classical section vector_space variables {E : Type u} [normed_group E] [normed_space ℝ E] {f : E → ℝ} {a : E} {f' : E →L[ℝ] ℝ} /-- "Positive" tangent cone to `s` at `x`; the only difference from `tangent_cone_at` is that we require `c n → ∞` instead of `∥c n∥ → ∞`. One can think about `pos_tangent_cone_at` as `tangent_cone_at nnreal` but we have no theory of normed semifields yet. -/ def pos_tangent_cone_at (s : set E) (x : E) : set E := {y : E | ∃(c : ℕ → ℝ) (d : ℕ → E), (∀ᶠ n in at_top, x + d n ∈ s) ∧ (tendsto c at_top at_top) ∧ (tendsto (λn, c n • d n) at_top (𝓝 y))} lemma pos_tangent_cone_at_mono : monotone (λ s, pos_tangent_cone_at s a) := begin rintros s t hst y ⟨c, d, hd, hc, hcd⟩, exact ⟨c, d, mem_sets_of_superset hd $ λ h hn, hst hn, hc, hcd⟩ end lemma mem_pos_tangent_cone_at_of_segment_subset {s : set E} {x y : E} (h : segment x y ⊆ s) : y - x ∈ pos_tangent_cone_at s x := begin let c := λn:ℕ, (2:ℝ)^n, let d := λn:ℕ, (c n)⁻¹ • (y-x), refine ⟨c, d, filter.univ_mem_sets' (λn, h _), tendsto_pow_at_top_at_top_of_one_lt one_lt_two, _⟩, show x + d n ∈ segment x y, { rw segment_eq_image', refine ⟨(c n)⁻¹, ⟨_, _⟩, rfl⟩, exacts [inv_nonneg.2 (pow_nonneg zero_le_two _), inv_le_one (one_le_pow_of_one_le one_le_two _)] }, show tendsto (λ n, c n • d n) at_top (𝓝 (y - x)), { convert tendsto_const_nhds, ext n, simp only [d, smul_smul], rw [mul_inv_cancel, one_smul], exact pow_ne_zero _ two_ne_zero } end lemma mem_pos_tangent_cone_at_of_segment_subset' {s : set E} {x y : E} (h : segment x (x + y) ⊆ s) : y ∈ pos_tangent_cone_at s x := by simpa only [add_sub_cancel'] using mem_pos_tangent_cone_at_of_segment_subset h lemma pos_tangent_cone_at_univ : pos_tangent_cone_at univ a = univ := eq_univ_of_forall $ λ x, mem_pos_tangent_cone_at_of_segment_subset' (subset_univ _) /-- If `f` has a local max on `s` at `a`, `f'` is the derivative of `f` at `a` within `s`, and `y` belongs to the positive tangent cone of `s` at `a`, then `f' y ≤ 0`. -/ lemma is_local_max_on.has_fderiv_within_at_nonpos {s : set E} (h : is_local_max_on f s a) (hf : has_fderiv_within_at f f' s a) {y} (hy : y ∈ pos_tangent_cone_at s a) : f' y ≤ 0 := begin rcases hy with ⟨c, d, hd, hc, hcd⟩, have hc' : tendsto (λ n, ∥c n∥) at_top at_top, from tendsto_at_top_mono (λ n, le_abs_self _) hc, refine le_of_tendsto (hf.lim at_top hd hc' hcd) _, replace hd : tendsto (λ n, a + d n) at_top (𝓝[s] (a + 0)), from tendsto_inf.2 ⟨tendsto_const_nhds.add (tangent_cone_at.lim_zero _ hc' hcd), by rwa tendsto_principal⟩, rw [add_zero] at hd, replace h : ∀ᶠ n in at_top, f (a + d n) ≤ f a, from mem_map.1 (hd h), replace hc : ∀ᶠ n in at_top, 0 ≤ c n, from mem_map.1 (hc (mem_at_top (0:ℝ))), filter_upwards [h, hc], simp only [smul_eq_mul, mem_preimage, subset_def], assume n hnf hn, exact mul_nonpos_of_nonneg_of_nonpos hn (sub_nonpos.2 hnf) end /-- If `f` has a local max on `s` at `a` and `y` belongs to the positive tangent cone of `s` at `a`, then `f' y ≤ 0`. -/ lemma is_local_max_on.fderiv_within_nonpos {s : set E} (h : is_local_max_on f s a) {y} (hy : y ∈ pos_tangent_cone_at s a) : (fderiv_within ℝ f s a : E → ℝ) y ≤ 0 := if hf : differentiable_within_at ℝ f s a then h.has_fderiv_within_at_nonpos hf.has_fderiv_within_at hy else by { rw fderiv_within_zero_of_not_differentiable_within_at hf, refl } /-- If `f` has a local max on `s` at `a`, `f'` is a derivative of `f` at `a` within `s`, and both `y` and `-y` belong to the positive tangent cone of `s` at `a`, then `f' y ≤ 0`. -/ lemma is_local_max_on.has_fderiv_within_at_eq_zero {s : set E} (h : is_local_max_on f s a) (hf : has_fderiv_within_at f f' s a) {y} (hy : y ∈ pos_tangent_cone_at s a) (hy' : -y ∈ pos_tangent_cone_at s a) : f' y = 0 := le_antisymm (h.has_fderiv_within_at_nonpos hf hy) $ by simpa using h.has_fderiv_within_at_nonpos hf hy' /-- If `f` has a local max on `s` at `a` and both `y` and `-y` belong to the positive tangent cone of `s` at `a`, then `f' y = 0`. -/ lemma is_local_max_on.fderiv_within_eq_zero {s : set E} (h : is_local_max_on f s a) {y} (hy : y ∈ pos_tangent_cone_at s a) (hy' : -y ∈ pos_tangent_cone_at s a) : (fderiv_within ℝ f s a : E → ℝ) y = 0 := if hf : differentiable_within_at ℝ f s a then h.has_fderiv_within_at_eq_zero hf.has_fderiv_within_at hy hy' else by { rw fderiv_within_zero_of_not_differentiable_within_at hf, refl } /-- If `f` has a local min on `s` at `a`, `f'` is the derivative of `f` at `a` within `s`, and `y` belongs to the positive tangent cone of `s` at `a`, then `0 ≤ f' y`. -/ lemma is_local_min_on.has_fderiv_within_at_nonneg {s : set E} (h : is_local_min_on f s a) (hf : has_fderiv_within_at f f' s a) {y} (hy : y ∈ pos_tangent_cone_at s a) : 0 ≤ f' y := by simpa using h.neg.has_fderiv_within_at_nonpos hf.neg hy /-- If `f` has a local min on `s` at `a` and `y` belongs to the positive tangent cone of `s` at `a`, then `0 ≤ f' y`. -/ lemma is_local_min_on.fderiv_within_nonneg {s : set E} (h : is_local_min_on f s a) {y} (hy : y ∈ pos_tangent_cone_at s a) : (0:ℝ) ≤ (fderiv_within ℝ f s a : E → ℝ) y := if hf : differentiable_within_at ℝ f s a then h.has_fderiv_within_at_nonneg hf.has_fderiv_within_at hy else by { rw [fderiv_within_zero_of_not_differentiable_within_at hf], refl } /-- If `f` has a local max on `s` at `a`, `f'` is a derivative of `f` at `a` within `s`, and both `y` and `-y` belong to the positive tangent cone of `s` at `a`, then `f' y ≤ 0`. -/ lemma is_local_min_on.has_fderiv_within_at_eq_zero {s : set E} (h : is_local_min_on f s a) (hf : has_fderiv_within_at f f' s a) {y} (hy : y ∈ pos_tangent_cone_at s a) (hy' : -y ∈ pos_tangent_cone_at s a) : f' y = 0 := by simpa using h.neg.has_fderiv_within_at_eq_zero hf.neg hy hy' /-- If `f` has a local min on `s` at `a` and both `y` and `-y` belong to the positive tangent cone of `s` at `a`, then `f' y = 0`. -/ lemma is_local_min_on.fderiv_within_eq_zero {s : set E} (h : is_local_min_on f s a) {y} (hy : y ∈ pos_tangent_cone_at s a) (hy' : -y ∈ pos_tangent_cone_at s a) : (fderiv_within ℝ f s a : E → ℝ) y = 0 := if hf : differentiable_within_at ℝ f s a then h.has_fderiv_within_at_eq_zero hf.has_fderiv_within_at hy hy' else by { rw fderiv_within_zero_of_not_differentiable_within_at hf, refl } /-- Fermat's Theorem: the derivative of a function at a local minimum equals zero. -/ lemma is_local_min.has_fderiv_at_eq_zero (h : is_local_min f a) (hf : has_fderiv_at f f' a) : f' = 0 := begin ext y, apply (h.on univ).has_fderiv_within_at_eq_zero hf.has_fderiv_within_at; rw pos_tangent_cone_at_univ; apply mem_univ end /-- Fermat's Theorem: the derivative of a function at a local minimum equals zero. -/ lemma is_local_min.fderiv_eq_zero (h : is_local_min f a) : fderiv ℝ f a = 0 := if hf : differentiable_at ℝ f a then h.has_fderiv_at_eq_zero hf.has_fderiv_at else fderiv_zero_of_not_differentiable_at hf /-- Fermat's Theorem: the derivative of a function at a local maximum equals zero. -/ lemma is_local_max.has_fderiv_at_eq_zero (h : is_local_max f a) (hf : has_fderiv_at f f' a) : f' = 0 := neg_eq_zero.1 $ h.neg.has_fderiv_at_eq_zero hf.neg /-- Fermat's Theorem: the derivative of a function at a local maximum equals zero. -/ lemma is_local_max.fderiv_eq_zero (h : is_local_max f a) : fderiv ℝ f a = 0 := if hf : differentiable_at ℝ f a then h.has_fderiv_at_eq_zero hf.has_fderiv_at else fderiv_zero_of_not_differentiable_at hf /-- Fermat's Theorem: the derivative of a function at a local extremum equals zero. -/ lemma is_local_extr.has_fderiv_at_eq_zero (h : is_local_extr f a) : has_fderiv_at f f' a → f' = 0 := h.elim is_local_min.has_fderiv_at_eq_zero is_local_max.has_fderiv_at_eq_zero /-- Fermat's Theorem: the derivative of a function at a local extremum equals zero. -/ lemma is_local_extr.fderiv_eq_zero (h : is_local_extr f a) : fderiv ℝ f a = 0 := h.elim is_local_min.fderiv_eq_zero is_local_max.fderiv_eq_zero end vector_space section real variables {f : ℝ → ℝ} {f' : ℝ} {a b : ℝ} /-- Fermat's Theorem: the derivative of a function at a local minimum equals zero. -/ lemma is_local_min.has_deriv_at_eq_zero (h : is_local_min f a) (hf : has_deriv_at f f' a) : f' = 0 := by simpa using continuous_linear_map.ext_iff.1 (h.has_fderiv_at_eq_zero (has_deriv_at_iff_has_fderiv_at.1 hf)) 1 /-- Fermat's Theorem: the derivative of a function at a local minimum equals zero. -/ lemma is_local_min.deriv_eq_zero (h : is_local_min f a) : deriv f a = 0 := if hf : differentiable_at ℝ f a then h.has_deriv_at_eq_zero hf.has_deriv_at else deriv_zero_of_not_differentiable_at hf /-- Fermat's Theorem: the derivative of a function at a local maximum equals zero. -/ lemma is_local_max.has_deriv_at_eq_zero (h : is_local_max f a) (hf : has_deriv_at f f' a) : f' = 0 := neg_eq_zero.1 $ h.neg.has_deriv_at_eq_zero hf.neg /-- Fermat's Theorem: the derivative of a function at a local maximum equals zero. -/ lemma is_local_max.deriv_eq_zero (h : is_local_max f a) : deriv f a = 0 := if hf : differentiable_at ℝ f a then h.has_deriv_at_eq_zero hf.has_deriv_at else deriv_zero_of_not_differentiable_at hf /-- Fermat's Theorem: the derivative of a function at a local extremum equals zero. -/ lemma is_local_extr.has_deriv_at_eq_zero (h : is_local_extr f a) : has_deriv_at f f' a → f' = 0 := h.elim is_local_min.has_deriv_at_eq_zero is_local_max.has_deriv_at_eq_zero /-- Fermat's Theorem: the derivative of a function at a local extremum equals zero. -/ lemma is_local_extr.deriv_eq_zero (h : is_local_extr f a) : deriv f a = 0 := h.elim is_local_min.deriv_eq_zero is_local_max.deriv_eq_zero end real section Rolle variables (f f' : ℝ → ℝ) {a b : ℝ} /-- A continuous function on a closed interval with `f a = f b` takes either its maximum or its minimum value at a point in the interior of the interval. -/ lemma exists_Ioo_extr_on_Icc (hab : a < b) (hfc : continuous_on f (Icc a b)) (hfI : f a = f b) : ∃ c ∈ Ioo a b, is_extr_on f (Icc a b) c := begin have ne : (Icc a b).nonempty, from nonempty_Icc.2 (le_of_lt hab), -- Consider absolute min and max points obtain ⟨c, cmem, cle⟩ : ∃ c ∈ Icc a b, ∀ x ∈ Icc a b, f c ≤ f x, from compact_Icc.exists_forall_le ne hfc, obtain ⟨C, Cmem, Cge⟩ : ∃ C ∈ Icc a b, ∀ x ∈ Icc a b, f x ≤ f C, from compact_Icc.exists_forall_ge ne hfc, by_cases hc : f c = f a, { by_cases hC : f C = f a, { have : ∀ x ∈ Icc a b, f x = f a, from λ x hx, le_antisymm (hC ▸ Cge x hx) (hc ▸ cle x hx), -- `f` is a constant, so we can take any point in `Ioo a b` rcases exists_between hab with ⟨c', hc'⟩, refine ⟨c', hc', or.inl _⟩, assume x hx, rw [mem_set_of_eq, this x hx, ← hC], exact Cge c' ⟨le_of_lt hc'.1, le_of_lt hc'.2⟩ }, { refine ⟨C, ⟨lt_of_le_of_ne Cmem.1 $ mt _ hC, lt_of_le_of_ne Cmem.2 $ mt _ hC⟩, or.inr Cge⟩, exacts [λ h, by rw h, λ h, by rw [h, hfI]] } }, { refine ⟨c, ⟨lt_of_le_of_ne cmem.1 $ mt _ hc, lt_of_le_of_ne cmem.2 $ mt _ hc⟩, or.inl cle⟩, exacts [λ h, by rw h, λ h, by rw [h, hfI]] } end /-- A continuous function on a closed interval with `f a = f b` has a local extremum at some point of the corresponding open interval. -/ lemma exists_local_extr_Ioo (hab : a < b) (hfc : continuous_on f (Icc a b)) (hfI : f a = f b) : ∃ c ∈ Ioo a b, is_local_extr f c := let ⟨c, cmem, hc⟩ := exists_Ioo_extr_on_Icc f hab hfc hfI in ⟨c, cmem, hc.is_local_extr $ Icc_mem_nhds cmem.1 cmem.2⟩ /-- Rolle's Theorem `has_deriv_at` version -/ lemma exists_has_deriv_at_eq_zero (hab : a < b) (hfc : continuous_on f (Icc a b)) (hfI : f a = f b) (hff' : ∀ x ∈ Ioo a b, has_deriv_at f (f' x) x) : ∃ c ∈ Ioo a b, f' c = 0 := let ⟨c, cmem, hc⟩ := exists_local_extr_Ioo f hab hfc hfI in ⟨c, cmem, hc.has_deriv_at_eq_zero $ hff' c cmem⟩ /-- Rolle's Theorem `deriv` version -/ lemma exists_deriv_eq_zero (hab : a < b) (hfc : continuous_on f (Icc a b)) (hfI : f a = f b) : ∃ c ∈ Ioo a b, deriv f c = 0 := let ⟨c, cmem, hc⟩ := exists_local_extr_Ioo f hab hfc hfI in ⟨c, cmem, hc.deriv_eq_zero⟩ variables {f f'} {l : ℝ} /-- Rolle's Theorem, a version for a function on an open interval: if `f` has derivative `f'` on `(a, b)` and has the same limit `l` at `𝓝[Ioi a] a` and `𝓝[Iio b] b`, then `f' c = 0` for some `c ∈ (a, b)`. -/ lemma exists_has_deriv_at_eq_zero' (hab : a < b) (hfa : tendsto f (𝓝[Ioi a] a) (𝓝 l)) (hfb : tendsto f (𝓝[Iio b] b) (𝓝 l)) (hff' : ∀ x ∈ Ioo a b, has_deriv_at f (f' x) x) : ∃ c ∈ Ioo a b, f' c = 0 := begin have : continuous_on f (Ioo a b) := λ x hx, (hff' x hx).continuous_at.continuous_within_at, have hcont := continuous_on_Icc_extend_from_Ioo hab this hfa hfb, obtain ⟨c, hc, hcextr⟩ : ∃ c ∈ Ioo a b, is_local_extr (extend_from (Ioo a b) f) c, { apply exists_local_extr_Ioo _ hab hcont, rw eq_lim_at_right_extend_from_Ioo hab hfb, exact eq_lim_at_left_extend_from_Ioo hab hfa }, use [c, hc], apply (hcextr.congr _).has_deriv_at_eq_zero (hff' c hc), rw eventually_eq_iff_exists_mem, exact ⟨Ioo a b, Ioo_mem_nhds hc.1 hc.2, extend_from_extends this⟩ end /-- Rolle's Theorem, a version for a function on an open interval: if `f` has the same limit `l` at `𝓝[Ioi a] a` and `𝓝[Iio b] b`, then `deriv f c = 0` for some `c ∈ (a, b)`. This version does not require differentiability of `f` because we define `deriv f c = 0` whenever `f` is not differentiable at `c`. -/ lemma exists_deriv_eq_zero' (hab : a < b) (hfa : tendsto f (𝓝[Ioi a] a) (𝓝 l)) (hfb : tendsto f (𝓝[Iio b] b) (𝓝 l)) : ∃ c ∈ Ioo a b, deriv f c = 0 := classical.by_cases (assume h : ∀ x ∈ Ioo a b, differentiable_at ℝ f x, show ∃ c ∈ Ioo a b, deriv f c = 0, from exists_has_deriv_at_eq_zero' hab hfa hfb (λ x hx, (h x hx).has_deriv_at)) (assume h : ¬∀ x ∈ Ioo a b, differentiable_at ℝ f x, have h : ∃ x, x ∈ Ioo a b ∧ ¬differentiable_at ℝ f x, by { push_neg at h, exact h }, let ⟨c, hc, hcdiff⟩ := h in ⟨c, hc, deriv_zero_of_not_differentiable_at hcdiff⟩) end Rolle
2f86644f92dcacac1bb2d25e9580d3df0478fdb8
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/tactic/core.lean
845f0254d8fc33a3b180c30649c60d6985765025
[ "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
100,025
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 control.basic import data.dlist.basic import meta.expr import system.io import tactic.binder_matching import tactic.interactive_expr import tactic.lean_core_docs import tactic.project_dir universe u attribute [derive [has_reflect, decidable_eq]] tactic.transparency -- Rather than import data.prod.lex here, we can get away with defining the order by hand. instance : has_lt pos := { lt := λ x y, x.line < y.line ∨ x.line = y.line ∧ x.column < y.column } namespace tactic /-- Reflexivity conversion: given `e` returns `(e, ⊢ e = e)` -/ meta def refl_conv (e : expr) : tactic (expr × expr) := do p ← mk_eq_refl e, return (e, p) /-- Turns a conversion tactic into one that always succeeds, where failure is interpreted as a proof by reflexivity. -/ meta def or_refl_conv (tac : expr → tactic (expr × expr)) (e : expr) : tactic (expr × expr) := tac e <|> refl_conv e /-- Transitivity conversion: given two conversions (which take an expression `e` and returns `(e', ⊢ e = e')`), produces another conversion that combines them with transitivity, treating failures as reflexivity conversions. -/ meta def trans_conv (t₁ t₂ : expr → tactic (expr × expr)) (e : expr) : tactic (expr × expr) := (do (e₁, p₁) ← t₁ e, (do (e₂, p₂) ← t₂ e₁, p ← mk_eq_trans p₁ p₂, return (e₂, p)) <|> return (e₁, p₁)) <|> t₂ e end tactic open tactic namespace expr /-- 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] /-- Convert a list of expressions to an expression denoting the list of those expressions. -/ meta def of_list (α : expr) : list expr → tactic expr | [] := tactic.mk_app ``list.nil [α] | (x :: xs) := do exs ← of_list xs, tactic.mk_app ``list.cons [α, x, exs] /-- 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 name /-- `pre.contains_sorry_aux nm` checks whether `sorry` occurs in the value of the declaration `nm` or (recusively) in any declarations occurring in the value of `nm` with namespace `pre`. Auxiliary function for `name.contains_sorry`. -/ meta def contains_sorry_aux (pre : name) : name → tactic bool | nm := do env ← get_env, decl ← get_decl nm, ff ← return decl.value.contains_sorry | return tt, (decl.value.list_names_with_prefix pre).mfold ff $ λ n b, if b then return tt else n.contains_sorry_aux /-- `nm.contains_sorry` checks whether `sorry` occurs in the value of the declaration `nm` or in any declarations `nm._proof_i` (or to be more precise: any declaration in namespace `nm`). See also `expr.contains_sorry`. -/ meta def contains_sorry (nm : name) : tactic bool := nm.contains_sorry_aux nm end name namespace interaction_monad open result variables {σ : Type} {α : Type u} /-- `get_state` returns the underlying state inside an interaction monad, from within that monad. -/ -- Note that this is a generalization of `tactic.read` in core. meta def get_state : interaction_monad σ σ := λ state, success state state /-- `set_state` sets the underlying state inside an interaction monad, from within that monad. -/ -- Note that this is a generalization of `tactic.write` in core. meta def set_state (state : σ) : interaction_monad σ unit := λ _, success () state /-- `run_with_state state tac` applies `tac` to the given state `state` and returns the result, subsequently restoring the original state. If `tac` fails, then `run_with_state` does too. -/ meta def run_with_state (state : σ) (tac : interaction_monad σ α) : interaction_monad σ α := λ s, match tac state with | success val _ := success val s | exception fn pos _ := exception fn pos s end end interaction_monad namespace format /-- `join' [a,b,c]` produces the format object `abc`. It differs from `format.join` by using `format.nil` instead of `""` for the empty list. -/ meta def join' (xs : list format) : format := xs.foldl compose nil /-- `intercalate x [a, b, c]` produces the format object `a.x.b.x.c`, where `.` represents `format.join`. -/ meta def intercalate (x : format) : list format → format := join' ∘ list.intersperse x /-- `soft_break` is similar to `line`. Whereas in `group (x ++ line ++ y ++ line ++ z)` the result either fits on one line or in three, `x ++ soft_break ++ y ++ soft_break ++ z` each line break is decided independently -/ meta def soft_break : format := group line /-- Format a list as a comma separated list, without any brackets. -/ meta def comma_separated {α : Type*} [has_to_format α] : list α → format | [] := nil | xs := group (nest 1 $ intercalate ("," ++ soft_break) $ xs.map to_fmt) end format section format open format /-- format a `list` by separating elements with `soft_break` instead of `line` -/ meta def list.to_line_wrap_format {α : Type u} [has_to_format α] (l : list α) : format := bracket "[" "]" (comma_separated l) end format namespace tactic open function export interaction_monad (get_state set_state run_with_state) /-- Private work function for `add_local_consts_as_local_hyps`: given `mappings : list (expr × expr)` corresponding to pairs `(var, hyp)` of variables and the local hypothesis created as a result and `(var :: rest) : list expr` of more local variables we examine `var` to see if it contains any other variables in `rest`. If it does, we put it to the back of the queue and recurse. If it does not, then we perform replacements inside the type of `var` using the `mappings`, create a new associate local hypothesis, add this to the list of mappings, and recurse. We are done once all local hypotheses have been processed. If the list of passed local constants have types which depend on one another (which can only happen by hand-crafting the `expr`s manually), this function will loop forever. -/ private meta def add_local_consts_as_local_hyps_aux : list (expr × expr) → list expr → tactic (list (expr × expr)) | mappings [] := return mappings | mappings (var :: rest) := do /- Determine if `var` contains any local variables in the lift `rest`. -/ let is_dependent := var.local_type.fold ff $ λ e n b, if b then b else e ∈ rest, /- If so, then skip it---add it to the end of the variable queue. -/ if is_dependent then add_local_consts_as_local_hyps_aux mappings (rest ++ [var]) else do /- Otherwise, replace all of the local constants referenced by the type of `var` with the respective new corresponding local hypotheses as recorded in the list `mappings`. -/ let new_type := var.local_type.replace_subexprs mappings, /- Introduce a new local new local hypothesis `hyp` for `var`, with the correct type. -/ hyp ← assertv var.local_pp_name new_type (var.local_const_set_type new_type), /- Process the next variable in the queue, with the mapping list updated to include the local hypothesis which we just created. -/ add_local_consts_as_local_hyps_aux ((var, hyp) :: mappings) rest /-- `add_local_consts_as_local_hyps vars` add the given list `vars` of `expr.local_const`s to the tactic state. This is harder than it sounds, since the list of local constants which we have been passed can have dependencies between their types. For example, suppose we have two local constants `n : ℕ` and `h : n = 3`. Then we cannot blindly add `h` as a local hypothesis, since we need the `n` to which it refers to be the `n` created as a new local hypothesis, not the old local constant `n` with the same name. Of course, these dependencies can be nested arbitrarily deep. If the list of passed local constants have types which depend on one another (which can only happen by hand-crafting the `expr`s manually), this function will loop forever. -/ meta def add_local_consts_as_local_hyps (vars : list expr) : tactic (list (expr × expr)) := /- The `list.reverse` below is a performance optimisation since the list of available variables reported by the system is often mostly the reverse of the order in which they are dependent. -/ add_local_consts_as_local_hyps_aux [] vars.reverse.dedup private meta def get_expl_pi_arity_aux : expr → tactic nat | (expr.pi n bi d b) := do m ← mk_fresh_name, let l := expr.local_const m n bi d, new_b ← whnf (expr.instantiate_var b l), r ← get_expl_pi_arity_aux new_b, if bi = binder_info.default then return (r + 1) else return r | e := return 0 /-- Compute the arity of explicit arguments of `type`. -/ meta def get_expl_pi_arity (type : expr) : tactic nat := whnf type >>= get_expl_pi_arity_aux /-- Compute the arity of explicit arguments of `fn`'s type. -/ meta def get_expl_arity (fn : expr) : tactic nat := infer_type fn >>= get_expl_pi_arity private meta def get_app_fn_args_whnf_aux (md : transparency) (unfold_ginductive : bool) : list expr → expr → tactic (expr × list expr) := λ args e, do e ← whnf e md unfold_ginductive, match e with | (expr.app t u) := get_app_fn_args_whnf_aux (u :: args) t | _ := pure (e, args) end /-- For `e = f x₁ ... xₙ`, `get_app_fn_args_whnf e` returns `(f, [x₁, ..., xₙ])`. `e` is normalised as necessary; for example: ``` get_app_fn_args_whnf `(let f := g x in f y) = (`(g), [`(x), `(y)]) ``` The returned expression is in whnf, but the arguments are generally not. -/ meta def get_app_fn_args_whnf (e : expr) (md := semireducible) (unfold_ginductive := tt) : tactic (expr × list expr) := get_app_fn_args_whnf_aux md unfold_ginductive [] e /-- `get_app_fn_whnf e md unfold_ginductive` is like `expr.get_app_fn e` but `e` is normalised as necessary (with transparency `md`). `unfold_ginductive` controls whether constructors of generalised inductive types are unfolded. The returned expression is in whnf. -/ meta def get_app_fn_whnf : expr → opt_param _ semireducible → opt_param _ tt → tactic expr | e md unfold_ginductive := do e ← whnf e md unfold_ginductive, match e with | (expr.app f _) := get_app_fn_whnf f md unfold_ginductive | _ := pure e end /-- `get_app_fn_const_whnf e md unfold_ginductive` expects that `e = C x₁ ... xₙ`, where `C` is a constant, after normalisation with transparency `md`. If so, the name of `C` is returned. Otherwise the tactic fails. `unfold_ginductive` controls whether constructors of generalised inductive types are unfolded. -/ meta def get_app_fn_const_whnf (e : expr) (md := semireducible) (unfold_ginductive := tt) : tactic name := do f ← get_app_fn_whnf e md unfold_ginductive, match f with | (expr.const n _) := pure n | _ := fail format! "expected a constant (possibly applied to some arguments), but got:\n{e}" end /-- `get_app_args_whnf e md unfold_ginductive` is like `expr.get_app_args e` but `e` is normalised as necessary (with transparency `md`). `unfold_ginductive` controls whether constructors of generalised inductive types are unfolded. The returned expressions are not necessarily in whnf. -/ meta def get_app_args_whnf (e : expr) (md := semireducible) (unfold_ginductive := tt) : tactic (list expr) := prod.snd <$> get_app_fn_args_whnf e md unfold_ginductive /-- `pis loc_consts f` is used to create a pi expression whose body is `f`. `loc_consts` should be a list of local constants. The function will abstract these local constants from `f` and bind them with pi binders. For example, if `a, b` are local constants with types `Ta, Tb`, ``pis [a, b] `(f a b)`` will return the expression `Π (a : Ta) (b : Tb), f a b`. -/ meta def pis : list expr → expr → tactic expr | (e@(expr.local_const uniq pp info _) :: es) f := do t ← infer_type e, f' ← pis es f, pure $ expr.pi pp info t (expr.abstract_local f' uniq) | _ f := pure f /-- `lambdas loc_consts f` is used to create a lambda expression whose body is `f`. `loc_consts` should be a list of local constants. The function will abstract these local constants from `f` and bind them with lambda binders. For example, if `a, b` are local constants with types `Ta, Tb`, ``lambdas [a, b] `(f a b)`` will return the expression `λ (a : Ta) (b : Tb), f a b`. -/ meta def lambdas : list expr → expr → tactic expr | (e@(expr.local_const uniq pp info _) :: es) f := do t ← infer_type e, f' ← lambdas es f, pure $ expr.lam pp info t (expr.abstract_local f' uniq) | _ f := pure f /-- Given an expression `f` (likely a binary operation) and a further expression `x`, calling `list_binary_operands f x` breaks `x` apart into successions of applications of `f` until this can no longer be done and returns a list of the leaves of the process. This matches `f` up to semireducible unification. In particular, it will match applications of the same polymorphic function with different type-class arguments. E.g., if `i1` and `i2` are both instances of `has_add T` and `e := has_add.add T i1 x (has_add.add T i2 y z)`, then ``list_binary_operands `((+) : T → T → T) e`` returns `[x, y, z]`. For example: ```lean #eval list_binary_operands `(@has_add.add ℕ _) `(3 + (4 * 5 + 6) + 7 / 3) >>= tactic.trace -- [3, 4 * 5, 6, 7 / 3] #eval list_binary_operands `(@list.append ℕ) `([1, 2] ++ [3, 4] ++ (1 :: [])) >>= tactic.trace -- [[1, 2], [3, 4], [1]] ``` -/ meta def list_binary_operands (f : expr) : expr → tactic (list expr) | x@(expr.app (expr.app g a) b) := do some _ ← try_core (unify f g) | pure [x], as ← list_binary_operands a, bs ← list_binary_operands b, pure (as ++ bs) | a := pure [a] -- 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*) [reflected _ α] (e : expr) : tactic α := mk_app ``id [e] >>= eval_expr α /-- `mk_fresh_name` returns identifiers starting with underscores, which are not legal when emitted by tactic programs. `mk_user_fresh_name` turns the useful source of random names provided by `mk_fresh_name` into names which are usable by tactic programs. The returned name has four components which are all strings. -/ meta def mk_user_fresh_name : tactic name := do nm ← mk_fresh_name, return $ `user__ ++ nm.pop_prefix.sanitize_name ++ `user__ /-- `has_attribute' attr_name decl_name` checks whether `decl_name` exists and has attribute `attr_name`. -/ meta def has_attribute' (attr_name decl_name : name) : tactic bool := succeeds (has_attribute attr_name decl_name) /-- Checks whether the name is a simp lemma -/ meta def is_simp_lemma : name → tactic bool := has_attribute' `simp /-- Checks whether the name is an instance. -/ meta def is_instance : name → tactic bool := has_attribute' `instance /-- `local_decls` returns a dictionary mapping names to their corresponding declarations. Covers all declarations from the current file. -/ meta def local_decls : tactic (name_map declaration) := do e ← tactic.get_env, let xs := e.fold native.mk_rb_map (λ d s, if environment.in_current_file e d.to_name then s.insert d.to_name d else s), pure xs /-- `get_decls_from` returns a dictionary mapping names to their corresponding declarations. Covers all declarations the files listed in `fs`, with the current file listed as `none`. The path of the file names is expected to be relative to the root of the project (i.e. the location of `leanpkg.toml` when it is present); e.g. `"src/tactic/core.lean"` Possible issue: `get_decls_from` uses `get_cwd`, the current working directory, which may not always point at the root of the project. It would work better if it searched for the root directory or, better yet, if Lean exposed its path information. -/ meta def get_decls_from (fs : list (option string)) : tactic (name_map declaration) := do root ← unsafe_run_io $ io.env.get_cwd, let fs := fs.map (option.map $ λ path, root ++ "/" ++ path), err ← unsafe_run_io $ (fs.filter_map id).mfilter $ (<$>) bnot ∘ io.fs.file_exists, guard (err = []) <|> fail format!"File not found: {err}", e ← tactic.get_env, let xs := e.fold native.mk_rb_map (λ d s, let source := e.decl_olean d.to_name in if source ∈ fs ∧ (source = none → e.in_current_file d.to_name) then s.insert d.to_name d else s), pure xs /-- If `{nm}_{n}` doesn't exist in the environment, returns that, otherwise tries `{nm}_{n+1}` -/ meta def get_unused_decl_name_aux (e : environment) (nm : name) : ℕ → tactic name | n := let nm' := nm.append_suffix ("_" ++ to_string n) in if e.contains nm' then get_unused_decl_name_aux (n+1) else return nm' /-- Return a name which doesn't already exist in the environment. If `nm` doesn't exist, it returns that, otherwise it tries `nm_2`, `nm_3`, ... -/ meta def get_unused_decl_name (nm : name) : tactic name := get_env >>= λ e, if e.contains nm then get_unused_decl_name_aux e nm 2 else return nm /-- Returns a pair `(e, t)`, where `e ← mk_const d.to_name`, and `t = d.type` but with universe params updated to match the fresh universe metavariables in `e`. This should have the same effect as just ```lean do e ← mk_const d.to_name, t ← infer_type e, return (e, t) ``` but is hopefully faster. -/ meta def decl_mk_const (d : declaration) : tactic (expr × expr) := do subst ← d.univ_params.mmap $ λ u, prod.mk u <$> mk_meta_univ, let e : expr := expr.const d.to_name (prod.snd <$> subst), return (e, d.type.instantiate_univ_params subst) /-- Replace every universe metavariable in an expression with a universe parameter. (This is useful when making new declarations.) -/ meta def replace_univ_metas_with_univ_params (e : expr) : tactic expr := do e.list_univ_meta_vars.enum.mmap (λ n, do let n' := (`u).append_suffix ("_" ++ to_string (n.1+1)), unify (expr.sort (level.mvar n.2)) (expr.sort (level.param n'))), instantiate_mvars e /-- `mk_local n` creates a dummy local variable with name `n`. The type of this local constant is a constant with name `n`, so it is very unlikely to be a meaningful expression. -/ meta def mk_local (n : name) : expr := expr.local_const n n binder_info.default (expr.const n []) /-- `mk_psigma [x,y,z]`, with `[x,y,z]` list of local constants of types `x : tx`, `y : ty x` and `z : tz x y`, creates an expression of sigma type: `⟨x,y,z⟩ : Σ' (x : tx) (y : ty x), tz x y`. -/ meta def mk_psigma : list expr → tactic expr | [] := mk_const ``punit | [x@(expr.local_const _ _ _ _)] := pure x | (x@(expr.local_const _ _ _ _) :: xs) := do y ← mk_psigma xs, α ← infer_type x, β ← infer_type y, t ← lambdas [x] β >>= instantiate_mvars, r ← mk_mapp ``psigma.mk [α,t], pure $ r x y | _ := fail "mk_psigma expects a list of local constants" /-- Update the type of a local constant or metavariable. For local constants and metavariables obtained via, for example, `tactic.get_local`, the type stored in the expression is not necessarily the same as the type returned by `infer_type`. This tactic, given a local constant or metavariable, updates the stored type to match the output of `infer_type`. If the input is not a local constant or metavariable, `update_type` does nothing. -/ meta def update_type : expr → tactic expr | e@(expr.local_const ppname uname binfo _) := expr.local_const ppname uname binfo <$> infer_type e | e@(expr.mvar ppname uname _) := expr.mvar ppname uname <$> infer_type e | e := pure e /-- `elim_gen_prod n e _ ns` with `e` an expression of type `psigma _`, applies `cases` on `e` `n` times and uses `ns` to name the resulting variables. Returns a triple: list of new variables, remaining term and unused variable names. -/ meta def elim_gen_prod : nat → expr → list expr → list name → tactic (list expr × expr × list name) | 0 e hs ns := return (hs.reverse, e, ns) | (n + 1) e hs ns := do t ← infer_type e, if t.is_app_of `eq then return (hs.reverse, e, ns) else do [(_, [h, h'], _)] ← cases_core e (ns.take 1), elim_gen_prod n h' (h :: hs) (ns.drop 1) private meta def elim_gen_sum_aux : nat → expr → list expr → tactic (list expr × expr) | 0 e hs := return (hs, e) | (n + 1) e hs := do [(_, [h], _), (_, [h'], _)] ← induction e [], swap, elim_gen_sum_aux n h' (h::hs) /-- `elim_gen_sum n e` applies cases on `e` `n` times. `e` is assumed to be a local constant whose type is a (nested) sum `⊕`. Returns the list of local constants representing the components of `e`. -/ meta def elim_gen_sum (n : nat) (e : expr) : tactic (list expr) := do (hs, h') ← elim_gen_sum_aux n e [], gs ← get_goals, set_goals $ (gs.take (n+1)).reverse ++ gs.drop (n+1), return $ hs.reverse ++ [h'] /-- Given `elab_def`, a tactic to solve the current goal, `extract_def n trusted elab_def` will create an auxiliary definition named `n` and use it to close the goal. If `trusted` is false, it will be a meta definition. -/ meta def extract_def (n : name) (trusted : bool) (elab_def : tactic unit) : tactic unit := do cxt ← list.map expr.to_implicit_local_const <$> local_context, t ← target, (eqns,d) ← solve_aux t elab_def, d ← instantiate_mvars d, t' ← pis cxt t, d' ← lambdas cxt d, let univ := t'.collect_univ_params, add_decl $ declaration.defn n univ t' d' (reducibility_hints.regular 1 tt) trusted, applyc n /-- Attempts to close the goal with `dec_trivial`. -/ meta def exact_dec_trivial : tactic unit := `[exact dec_trivial] /-- Runs a tactic for a result, reverting the state after completion. -/ meta def retrieve {α} (tac : tactic α) : tactic α := λ s, result.cases_on (tac s) (λ a s', result.success a s) result.exception /-- Runs a tactic for a result, reverting the state after completion or error. -/ meta def retrieve' {α} (tac : tactic α) : tactic α := λ s, result.cases_on (tac s) (λ a s', result.success a s) (λ msg pos s', result.exception msg pos s) /-- Repeat a tactic at least once, calling it recursively on all subgoals, until it fails. This tactic fails if the first invocation fails. -/ meta def repeat1 (t : tactic unit) : tactic unit := t; repeat t /-- `iterate_range m n t`: Repeat the given tactic at least `m` times and at most `n` times or until `t` fails. Fails if `t` does not run at least `m` times. -/ meta def iterate_range : ℕ → ℕ → tactic unit → tactic unit | 0 0 t := skip | 0 (n+1) t := try (t >> iterate_range 0 n t) | (m+1) n t := t >> iterate_range m (n-1) t /-- Given a tactic `tac` that takes an expression and returns a new expression and a proof of equality, use that tactic to change the type of the hypotheses listed in `hs`, as well as the goal if `tgt = tt`. Returns `tt` if any types were successfully changed. -/ meta def replace_at (tac : expr → tactic (expr × expr)) (hs : list expr) (tgt : bool) : tactic bool := do to_remove ← hs.mfilter $ λ h, do { h_type ← infer_type h, succeeds $ do (new_h_type, pr) ← tac h_type, assert h.local_pp_name new_h_type, mk_eq_mp pr h >>= tactic.exact }, goal_simplified ← succeeds $ do { guard tgt, (new_t, pr) ← target >>= tac, replace_target new_t pr }, to_remove.mmap' (λ h, try (clear h)), return (¬ to_remove.empty ∨ goal_simplified) /-- `revert_after e` reverts all local constants after local constant `e`. -/ meta def revert_after (e : expr) : tactic ℕ := do l ← local_context, [pos] ← return $ l.indexes_of e | pp e >>= λ s, fail format!"No such local constant {s}", let l := l.drop pos.succ, -- all local hypotheses after `e` revert_lst l /-- `revert_target_deps` reverts all local constants on which the target depends (recursively). Returns the number of local constants that have been reverted. -/ meta def revert_target_deps : tactic ℕ := do tgt ← target, ctx ← local_context, l ← ctx.mfilter (kdepends_on tgt), n ← revert_lst l, if l = [] then return n else do m ← revert_target_deps, return (m + n) /-- `generalize' e n` generalizes the target with respect to `e`. It creates a new local constant with name `n` of the same type as `e` and replaces all occurrences of `e` by `n`. `generalize'` is similar to `generalize` but also succeeds when `e` does not occur in the goal, in which case it just calls `assert`. In contrast to `generalize` it already introduces the generalized variable. -/ meta def generalize' (e : expr) (n : name) : tactic expr := (generalize e n >> intro n) <|> note n none e /-- `intron_no_renames n` calls `intro` `n` times, using the pretty-printing name provided by the binder to name the new local constant. Unlike `intron`, it does not rename introduced constants if the names shadow existing constants. -/ meta def intron_no_renames : ℕ → tactic unit | 0 := pure () | (n+1) := do expr.pi pp_n _ _ _ ← target, intro pp_n, intron_no_renames n /-- `get_univ_level t` returns the universe level of a type `t` -/ meta def get_univ_level (t : expr) (md := semireducible) (unfold_ginductive := tt) : tactic level := do expr.sort u ← infer_type t >>= λ s, whnf s md unfold_ginductive | fail "get_univ_level: argument is not a type", return u /-! ### Various tactics related to local definitions (local constants of the form `x : α := t`) We call `t` the value of `x`. -/ /-- `local_def_value e` returns the value of the expression `e`, assuming that `e` has been defined locally using a `let` expression. Otherwise it fails. -/ meta def local_def_value (e : expr) : tactic expr := pp e >>= λ s, -- running `pp` here, because we cannot access it in the `type_context` monad. tactic.unsafe.type_context.run $ do lctx <- tactic.unsafe.type_context.get_local_context, some ldecl <- return $ lctx.get_local_decl e.local_uniq_name | tactic.unsafe.type_context.fail format!"No such hypothesis {s}.", some let_val <- return ldecl.value | tactic.unsafe.type_context.fail format!"Variable {e} is not a local definition.", return let_val /-- `is_local_def e` succeeds when `e` is a local definition (a local constant of the form `e : α := t`) and otherwise fails. -/ meta def is_local_def (e : expr) : tactic unit := do ctx ← unsafe.type_context.get_local_context.run, (some decl) ← pure $ ctx.get_local_decl e.local_uniq_name | fail format!"is_local_def: {e} is not a local constant", when decl.value.is_none $ fail format!"is_local_def: {e} is not a local definition" /-- Returns the local definitions from the context. A local definition is a local constant of the form `e : α := t`. The local definitions are returned in the order in which they appear in the context. -/ meta def local_defs : tactic (list expr) := do ctx ← unsafe.type_context.get_local_context.run, ctx' ← local_context, ctx'.mfilter $ λ h, do (some decl) ← pure $ ctx.get_local_decl h.local_uniq_name | fail format!"local_defs: local {h} not found in the local context", pure decl.value.is_some /-- like `split_on_p p xs`, `partition_local_deps_aux vs xs acc` searches for matches in `xs` (using membership to `vs` instead of a predicate) and breaks `xs` when matches are found. whereas `split_on_p p xs` removes the matches, `partition_local_deps_aux vs xs acc` includes them in the following partition. Also, `partition_local_deps_aux vs xs acc` discards the partition running up to the first match. -/ private def partition_local_deps_aux {α} [decidable_eq α] (vs : list α) : list α → list α → list (list α) | [] acc := [acc.reverse] | (l :: ls) acc := if l ∈ vs then acc.reverse :: partition_local_deps_aux ls [l] else partition_local_deps_aux ls (l :: acc) /-- `partition_local_deps vs`, with `vs` a list of local constants, reorders `vs` in the order they appear in the local context together with the variables that follow them. If local context is `[a,b,c,d,e,f]`, and that we call `partition_local_deps [d,b]`, we get `[[d,e,f], [b,c]]`. The head of each list is one of the variables given as a parameter. -/ meta def partition_local_deps (vs : list expr) : tactic (list (list expr)) := do ls ← local_context, pure (partition_local_deps_aux vs ls []).tail.reverse /-- `clear_value [e₀, e₁, e₂, ...]` clears the body of the local definitions `e₀`, `e₁`, `e₂`, ... changing them into regular hypotheses. A hypothesis `e : α := t` is changed to `e : α`. The order of locals `e₀`, `e₁`, `e₂` does not matter as a permutation will be chosen so as to preserve type correctness. This tactic is called `clearbody` in Coq. -/ meta def clear_value (vs : list expr) : tactic unit := do ls ← partition_local_deps vs, ls.mmap' $ λ vs, do { revert_lst vs, (expr.elet v t d b) ← target | fail format!"Cannot clear the body of {vs.head}. It is not a local definition.", let e := expr.pi v binder_info.default t b, type_check e <|> fail format!"Cannot clear the body of {vs.head}. The resulting goal is not type correct.", g ← mk_meta_var e, h ← note `h none g, tactic.exact $ h d, gs ← get_goals, set_goals $ g :: gs }, ls.reverse.mmap' $ λ vs, intro_lst $ vs.map expr.local_pp_name /-- `context_has_local_def` is true iff there is at least one local definition in the context. -/ meta def context_has_local_def : tactic bool := do ctx ← local_context, ctx.many (succeeds ∘ local_def_value) /-- `context_upto_hyp_has_local_def h` is true iff any of the hypotheses in the context up to and including `h` is a local definition. -/ meta def context_upto_hyp_has_local_def (h : expr) : tactic bool := do ff ← succeeds (local_def_value h) | pure tt, ctx ← local_context, let ctx := ctx.take_while (≠ h), ctx.many (succeeds ∘ local_def_value) /-- If the expression `h` is a local variable with type `x = t` or `t = x`, where `x` is a local constant, `tactic.subst' h` substitutes `x` by `t` everywhere in the main goal and then clears `h`. If `h` is another local variable, then we find a local constant with type `h = t` or `t = h` and substitute `t` for `h`. This is like `tactic.subst`, but fails with a nicer error message if the substituted variable is a local definition. It is trickier to fix this in core, since `tactic.is_local_def` is in mathlib. -/ meta def subst' (h : expr) : tactic unit := do e ← do { -- we first find the variable being substituted away t ← infer_type h, let (f, args) := t.get_app_fn_args, if (f.const_name = `eq ∨ f.const_name = `heq) then do { let lhs := args.inth 1, let rhs := args.ilast, if rhs.is_local_constant then return rhs else if lhs.is_local_constant then return lhs else fail "subst tactic failed, hypothesis '{h.local_pp_name}' is not of the form (x = t) or (t = x)." } else return h }, success_if_fail (is_local_def e) <|> fail format!("Cannot substitute variable {e.local_pp_name}, " ++ "it is a local definition. If you really want to do this, use `clear_value` first."), subst h /-- A variant of `simplify_bottom_up`. Given a tactic `post` for rewriting subexpressions, `simp_bottom_up post e` tries to rewrite `e` starting at the leaf nodes. Returns the resulting expression and a proof of equality. -/ meta def simp_bottom_up' (post : expr → tactic (expr × expr)) (e : expr) (cfg : simp_config := {}) : tactic (expr × expr) := prod.snd <$> simplify_bottom_up () (λ _, (<$>) (prod.mk ()) ∘ post) e cfg /-- Caches unary type classes on a type `α : Type.{univ}`. -/ meta structure instance_cache := (α : expr) (univ : level) (inst : name_map expr) /-- Creates an `instance_cache` for the type `α`. -/ meta def mk_instance_cache (α : expr) : tactic instance_cache := do u ← mk_meta_univ, infer_type α >>= unify (expr.sort (level.succ u)), u ← get_univ_assignment u, return ⟨α, u, mk_name_map⟩ namespace instance_cache /-- If `n` is the name of a type class with one parameter, `get c n` tries to find an instance of `n c.α` by checking the cache `c`. If there is no entry in the cache, it tries to find the instance via type class resolution, and updates the cache. -/ meta def get (c : instance_cache) (n : name) : tactic (instance_cache × expr) := match c.inst.find n with | some i := return (c, i) | none := do e ← mk_app n [c.α] >>= mk_instance, return (⟨c.α, c.univ, c.inst.insert n e⟩, e) end open expr /-- If `e` is a `pi` expression that binds an instance-implicit variable of type `n`, `append_typeclasses e c l` searches `c` for an instance `p` of type `n` and returns `p :: l`. -/ meta def append_typeclasses : expr → instance_cache → list expr → tactic (instance_cache × list expr) | (pi _ binder_info.inst_implicit (app (const n _) (var _)) body) c l := do (c, p) ← c.get n, return (c, p :: l) | _ c l := return (c, l) /-- Creates the application `n c.α p l`, where `p` is a type class instance found in the cache `c`. -/ meta def mk_app (c : instance_cache) (n : name) (l : list expr) : tactic (instance_cache × expr) := do d ← get_decl n, (c, l) ← append_typeclasses d.type.binding_body c l, return (c, (expr.const n [c.univ]).mk_app (c.α :: l)) /-- `c.of_nat n` creates the `c.α`-valued numeral expression corresponding to `n`. -/ protected meta def of_nat (c : instance_cache) (n : ℕ) : tactic (instance_cache × expr) := if n = 0 then c.mk_app ``has_zero.zero [] else do (c, ai) ← c.get ``has_add, (c, oi) ← c.get ``has_one, (c, one) ← c.mk_app ``has_one.one [], return (c, n.binary_rec one $ λ b n e, if n = 0 then one else cond b ((expr.const ``bit1 [c.univ]).mk_app [c.α, oi, ai, e]) ((expr.const ``bit0 [c.univ]).mk_app [c.α, ai, e])) /-- `c.of_int n` creates the `c.α`-valued numeral expression corresponding to `n`. The output is either a numeral or the negation of a numeral. -/ protected meta def of_int (c : instance_cache) : ℤ → tactic (instance_cache × expr) | (n : ℕ) := c.of_nat n | -[1+ n] := do (c, e) ← c.of_nat (n+1), c.mk_app ``has_neg.neg [e] end instance_cache /-- A variation on `assert` where a (possibly incomplete) proof of the assertion is provided as a parameter. ``(h,gs) ← local_proof `h p tac`` creates a local `h : p` and use `tac` to (partially) construct a proof for it. `gs` is the list of remaining goals in the proof of `h`. The benefits over assert are: - unlike with ``h ← assert `h p, tac`` , `h` cannot be used by `tac`; - when `tac` does not complete the proof of `h`, returning the list of goals allows one to write a tactic using `h` and with the confidence that a proof will not boil over to goals left over from the proof of `h`, unlike what would be the case when using `tactic.swap`. -/ meta def local_proof (h : name) (p : expr) (tac₀ : tactic unit) : tactic (expr × list expr) := focus1 $ do h' ← assert h p, [g₀,g₁] ← get_goals, set_goals [g₀], tac₀, gs ← get_goals, set_goals [g₁], return (h', gs) /-- `var_names e` returns a list of the unique names of the initial pi bindings in `e`. -/ meta def var_names : expr → list name | (expr.pi n _ _ b) := n :: var_names b | _ := [] /-- When `struct_n` is the name of a structure type, `subobject_names struct_n` returns two lists of names `(instances, fields)`. The names in `instances` are the projections from `struct_n` to the structures that it extends (assuming it was defined with `old_structure_cmd false`). The names in `fields` are the standard fields of `struct_n`. -/ meta def subobject_names (struct_n : name) : tactic (list name × list name) := do env ← get_env, c ← match env.constructors_of struct_n with | [c] := pure c | [] := if env.is_inductive struct_n then fail format!"{struct_n} does not have constructors" else fail format!"{struct_n} is not an inductive type" | _ := fail "too many constructors" end, vs ← var_names <$> (mk_const c >>= infer_type), fields ← env.structure_fields struct_n, return $ fields.partition (λ fn, ↑("_" ++ fn.to_string) ∈ vs) private meta def expanded_field_list' : name → tactic (dlist $ name × name) | struct_n := do (so,fs) ← subobject_names struct_n, ts ← so.mmap (λ n, do (_, e) ← mk_const (n.update_prefix struct_n) >>= infer_type >>= open_pis, expanded_field_list' $ e.get_app_fn.const_name), return $ dlist.join ts ++ dlist.of_list (fs.map $ prod.mk struct_n) open functor function /-- `expanded_field_list struct_n` produces a list of the names of the fields of the structure named `struct_n`. These are returned as pairs of names `(prefix, name)`, where the full name of the projection is `prefix.name`. `struct_n` cannot be a synonym for a `structure`, it must be itself a `structure` -/ meta def expanded_field_list (struct_n : name) : tactic (list $ name × name) := dlist.to_list <$> expanded_field_list' struct_n /-- Return a list of all type classes which can be instantiated for the given expression. -/ meta def get_classes (e : expr) : tactic (list name) := attribute.get_instances `class >>= list.mfilter (λ n, succeeds $ mk_app n [e] >>= mk_instance) /-- Finds an instance of an implication `cond → tgt`. Returns a pair of a local constant `e` of type `cond`, and an instance of `tgt` that can mention `e`. The local constant `e` is added as an hypothesis to the tactic state, but should not be used, since it has been "proven" by a metavariable. -/ meta def mk_conditional_instance (cond tgt : expr) : tactic (expr × expr) := do f ← mk_meta_var cond, e ← assertv `c cond f, swap, reset_instance_cache, inst ← mk_instance tgt, return (e, inst) open nat /-- Create a list of `n` fresh metavariables. -/ meta def mk_mvar_list : ℕ → tactic (list expr) | 0 := pure [] | (succ n) := (::) <$> mk_mvar <*> mk_mvar_list n /-- Returns the only goal, or fails if there isn't just one goal. -/ meta def get_goal : tactic expr := do gs ← get_goals, match gs with | [a] := return a | [] := fail "there are no goals" | _ := fail "there are too many goals" end /-- `iterate_at_most_on_all_goals n t`: repeat the given tactic at most `n` times on all goals, or until it fails. Always succeeds. -/ meta def iterate_at_most_on_all_goals : nat → tactic unit → tactic unit | 0 tac := trace "maximal iterations reached" | (succ n) tac := tactic.all_goals' $ (do tac, iterate_at_most_on_all_goals n tac) <|> skip /-- `iterate_at_most_on_subgoals n t`: repeat the tactic `t` at most `n` times on the first goal and on all subgoals thus produced, or until it fails. Fails iff `t` fails on current goal. -/ meta def iterate_at_most_on_subgoals : nat → tactic unit → tactic unit | 0 tac := trace "maximal iterations reached" | (succ n) tac := focus1 (do tac, iterate_at_most_on_all_goals n tac) /-- This makes sure that the execution of the tactic does not change the tactic state. This can be helpful while using rewrite, apply, or expr munging. Remember to instantiate your metavariables before you're done! -/ meta def lock_tactic_state {α} (t : tactic α) : tactic α | s := match t s with | result.success a s' := result.success a s | result.exception msg pos s' := result.exception msg pos s end /-- `apply_list l`, for `l : list (tactic expr)`, tries to apply one of the lemmas generated by the tactics in `l` to 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 /-- Given the name of a user attribute, produces a list of `tactic expr`s, each of which is the application of `i_to_expr_for_apply` to a declaration with that attribute. -/ meta def resolve_attribute_expr_list (attr_name : name) : tactic (list (tactic expr)) := do l ← attribute.get_instances attr_name, list.map i_to_expr_for_apply <$> list.reverse <$> l.mmap (λ n, do c ← (mk_const n), return (pexpr.of_expr c)) /--`apply_rules args attrs n`: apply the lists of rules `args` (given as pexprs) and `attrs` (given as names of attributes) and the tactic `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 (args : list pexpr) (attrs : list name) (n : nat) (opt : apply_cfg) : tactic unit := do attr_exprs ← lock_tactic_state $ attrs.mfoldl (λ l n, list.append l <$> resolve_attribute_expr_list n) [], let args_exprs := args.map i_to_expr_for_apply ++ attr_exprs, -- `args_exprs` is 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. iterate_at_most_on_subgoals n (assumption <|> apply_list_expr opt args_exprs) /-- `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 `sorry`", 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) /-- A simple check: `check_target_changes tac` applies tactic `tac` and fails if the main target before applying the tactic `tac` unifies with one of the goals produced by the tactic itself. Useful to make sure that the tactic `tac` is actually making progress. -/ meta def check_target_changes (tac : tactic α) : tactic α := focus1 $ do t ← target, x ← tac, gs ← get_goals >>= list.mmap infer_type, (success_if_fail $ gs.mfirst $ unify t) <|> fail "Goal did not change", pure x /-- 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 /-- A version of `lean.parser.many` that requires at least `n` items -/ meta def repeat_at_least {α : Type} (p : lean.parser α) : ℕ → lean.parser (list α) | 0 := many p | (n + 1) := list.cons <$> p <*> repeat_at_least n /-- A version of `lean.parser.sep_by` that allows trailing delimiters, but requires at least one item. Like `lean.parser.sep_by`, as a result of the `lean.parser` monad not being pure, this is only well-behaved if `p` and `s` are backtrackable; which in practice means they must not consume the input when they do not have a match. -/ meta def sep_by_trailing {α : Type} (s : lean.parser unit) (p : lean.parser α) : lean.parser (list α) := do fst ← p, some () ← optional s | pure [fst], some rest ← optional sep_by_trailing | pure [fst], pure (fst :: rest) /-- `emit_command_here str` behaves as if the string `str` were placed as a user command at the current line. -/ meta def emit_command_here (str : string) : lean.parser string := do (_, left) ← with_input command_like str, return left /-- Inner recursion for `emit_code_here`. -/ meta def emit_code_here_aux : string → ℕ → lean.parser unit | str slen := do left ← emit_command_here str, let llen := left.length, when (llen < slen ∧ llen ≠ 0) (emit_code_here_aux left llen) /-- `emit_code_here str` behaves as if the string `str` were placed at the current location in source code. -/ meta def emit_code_here (s : string) : lean.parser unit := emit_code_here_aux s s.length /-- `run_parser p` is like `run_cmd` but for the parser monad. It executes parser `p` at the top level, giving access to operations like `emit_code_here`. -/ @[user_command] meta def run_parser_cmd (_ : interactive.parse $ tk "run_parser") : lean.parser unit := do e ← lean.parser.pexpr 0, p ← eval_pexpr (lean.parser unit) e, p add_tactic_doc { name := "run_parser", category := doc_category.cmd, decl_names := [``run_parser_cmd], tags := ["parsing"] } /-- `get_current_namespace` returns the current namespace (it could be `name.anonymous`). This function deserves a C++ implementation in core lean, and will fail if it is not called from the body of a command (i.e. anywhere else that the `lean.parser` monad can be invoked). -/ meta def get_current_namespace : lean.parser name := do env ← get_env, n ← tactic.mk_user_fresh_name, emit_code_here $ sformat!"def {n} := ()", nfull ← tactic.resolve_constant n, set_env env, 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. The `aggressive` argument controls whether the instance is added globally, where it has low priority, or in the local context, where it has very high priority. -/ meta def classical (aggressive : bool := ff) : tactic unit := if aggressive then do h ← get_unused_name `_inst, mk_const `classical.prop_decidable >>= note h none, reset_instance_cache else do -- Turn on the `prop_decidable` instance. `9` is what we use in the `classical` locale tactic.set_basic_attribute `instance `classical.prop_decidable ff (some 9) open expr /-- `mk_comp v e` checks whether `e` is a sequence of nested applications `f (g (h v))`, and if so, returns the expression `f ∘ g ∘ h`. -/ meta def mk_comp (v : expr) : expr → tactic expr | (app f e) := if e = v then pure f else do guard (¬ v.occurs f) <|> fail "bad guard", e' ← mk_comp e >>= instantiate_mvars, f ← instantiate_mvars f, mk_mapp ``function.comp [none,none,none,f,e'] | e := do guard (e = v), t ← infer_type e, mk_mapp ``id [t] /-- Given two expressions `e₀` and `e₁`, return the expression `` `(%%e₀ ↔ %%e₁)``. -/ meta def mk_iff (e₀ : expr) (e₁ : expr) : expr := `(%%e₀ ↔ %%e₁) /-- From a lemma of the shape `∀ x, f (g x) = h x` derive an auxiliary lemma of the form `f ∘ g = h` for reasoning about higher-order functions. -/ meta def mk_higher_order_type : expr → tactic expr | (pi n bi d b@(pi _ _ _ _)) := do v ← mk_local_def n d, let b' := (b.instantiate_var v), (pi n bi d ∘ flip abstract_local v.local_uniq_name) <$> mk_higher_order_type b' | (pi n bi d b) := do v ← mk_local_def n d, let b' := (b.instantiate_var v), (l,r) ← match_eq b' <|> fail format!"not an equality {b'}", l' ← mk_comp v l, r' ← mk_comp v r, mk_app ``eq [l',r'] | e := failed open lean.parser interactive.types /-- A user attribute that applies to lemmas of the shape `∀ x, f (g x) = h x`. It derives an auxiliary lemma of the form `f ∘ g = h` for reasoning about higher-order functions. -/ @[user_attribute] meta def higher_order_attr : user_attribute unit (option name) := { name := `higher_order, parser := optional ident, descr := "From a lemma of the shape `∀ x, f (g x) = h x` derive an auxiliary lemma of the form `f ∘ g = h` for reasoning about higher-order functions.", after_set := some $ λ lmm _ _, do env ← get_env, decl ← env.get lmm, let num := decl.univ_params.length, let lvls := (list.iota num).map (`l).append_after, let l : expr := expr.const lmm $ lvls.map level.param, t ← infer_type l >>= instantiate_mvars, t' ← mk_higher_order_type t, (_,pr) ← solve_aux t' $ do { intros, applyc ``_root_.funext, intro1, applyc lmm; assumption }, pr ← instantiate_mvars pr, lmm' ← higher_order_attr.get_param lmm, lmm' ← (flip name.update_prefix lmm.get_prefix <$> lmm') <|> pure lmm.add_prime, add_decl $ declaration.thm lmm' lvls t' (pure pr), copy_attribute `simp lmm lmm', copy_attribute `functor_norm lmm lmm' } add_tactic_doc { name := "higher_order", category := doc_category.attr, decl_names := [`tactic.higher_order_attr], tags := ["lemma derivation"] } attribute [higher_order map_comp_pure] map_pure /-- Copies a definition into the `tactic.interactive` namespace to make it usable in proof scripts. It allows one to write ```lean @[interactive] meta def my_tactic := ... ``` instead of ```lean meta def my_tactic := ... run_cmd add_interactive [``my_tactic] ``` -/ @[user_attribute] meta def interactive_attr : user_attribute := { name := `interactive, descr := "Put a definition in the `tactic.interactive` namespace to make it usable in proof scripts.", after_set := some $ λ tac _ _, add_interactive [tac] } add_tactic_doc { name := "interactive", category := doc_category.attr, decl_names := [``tactic.interactive_attr], tags := ["environment"] } /-- Use `refine` to partially discharge the goal, or call `fconstructor` and try again. -/ private meta def use_aux (h : pexpr) : tactic unit := (focus1 (refine h >> done)) <|> (fconstructor >> use_aux) /-- Similar to `existsi`, `use l` will use entries in `l` to instantiate existential obligations at the beginning of a target. Unlike `existsi`, the pexprs in `l` are elaborated with respect to the expected type. ```lean example : ∃ x : ℤ, x = x := by tactic.use ``(42) ``` See the doc string for `tactic.interactive.use` for more information. -/ protected meta def use (l : list pexpr) : tactic unit := focus1 $ seq' (l.mmap' $ λ h, use_aux h <|> fail format!"failed to instantiate goal with {h}") instantiate_mvars_in_target /-- `clear_aux_decl_aux l` clears all expressions in `l` that represent aux decls from the local context. -/ meta def clear_aux_decl_aux : list expr → tactic unit | [] := skip | (e::l) := do cond e.is_aux_decl (tactic.clear e) skip, clear_aux_decl_aux l /-- `clear_aux_decl` clears all expressions from the local context that represent aux decls. -/ meta def clear_aux_decl : tactic unit := local_context >>= clear_aux_decl_aux /-- `apply_at_aux e et [] h ht` (with `et` the type of `e` and `ht` the type of `h`) finds a list of expressions `vs` and returns `(e.mk_args (vs ++ [h]), vs)`. -/ meta def apply_at_aux (arg t : expr) : list expr → expr → expr → tactic (expr × list expr) | vs e (pi n bi d b) := do { v ← mk_meta_var d, apply_at_aux (v :: vs) (e v) (b.instantiate_var v) } <|> (e arg, vs) <$ unify d t | vs e _ := failed /-- `apply_at e h` applies implication `e` on hypothesis `h` and replaces `h` with the result. -/ meta def apply_at (e h : expr) : tactic unit := do ht ← infer_type h, et ← infer_type e, (h', gs') ← apply_at_aux h ht [] e et, note h.local_pp_name none h', clear h, gs' ← gs'.mfilter is_assigned, (g :: gs) ← get_goals, set_goals (g :: gs' ++ gs) /-- `symmetry_hyp h` applies `symmetry` on hypothesis `h`. -/ meta def symmetry_hyp (h : expr) (md := semireducible) : tactic unit := do tgt ← infer_type h, env ← get_env, let r := get_app_fn tgt, match env.symm_for (const_name r) with | (some symm) := do s ← mk_const symm, apply_at s h | none := fail "symmetry tactic failed, target is not a relation application with the expected property." end /-- `setup_tactic_parser` is a user command that opens the namespaces used in writing interactive tactics, and declares the local postfix notation `?` for `optional` and `*` for `many`. It does *not* use the `namespace` command, so it will typically be used after `namespace tactic.interactive`. -/ @[user_command] meta def setup_tactic_parser_cmd (_ : interactive.parse $ tk "setup_tactic_parser") : lean.parser unit := emit_code_here " open _root_.lean open _root_.lean.parser open _root_.interactive _root_.interactive.types local postfix (name := parser.optional) `?`:9001 := optional local postfix (name := parser.many) *:9001 := many . " /-- `finally tac finalizer` runs `tac` first, then runs `finalizer` even if `tac` fails. `finally tac finalizer` fails if either `tac` or `finalizer` fails. -/ meta def finally {β} (tac : tactic α) (finalizer : tactic β) : tactic α := λ s, match tac s with | (result.success r s') := (finalizer >> pure r) s' | (result.exception msg p s') := (finalizer >> result.exception msg p) s' end /-- `on_exception handler tac` runs `tac` first, and then runs `handler` only if `tac` failed. -/ meta def on_exception {β} (handler : tactic β) (tac : tactic α) : tactic α | s := match tac s with | result.exception msg p s' := (handler *> result.exception msg p) s' | ok := ok end /-- `decorate_error add_msg tac` prepends `add_msg` to an exception produced by `tac` -/ meta def decorate_error (add_msg : string) (tac : tactic α) : tactic α | s := match tac s with | result.exception msg p s := let msg (_ : unit) : format := match msg with | some msg := add_msg ++ format.line ++ msg () | none := add_msg end in result.exception msg p s | ok := ok end /-- Applies tactic `t`. If it succeeds, revert the state, and return the value. If it fails, returns the error message. -/ meta def retrieve_or_report_error {α : Type u} (t : tactic α) : tactic (α ⊕ string) := λ s, match t s with | (interaction_monad.result.success a s') := result.success (sum.inl a) s | (interaction_monad.result.exception msg' _ s') := result.success (sum.inr (msg'.iget ()).to_string) s end /-- Applies tactic `t`. If it succeeds, return the value. If it fails, returns the error message. -/ meta def try_or_report_error {α : Type u} (t : tactic α) : tactic (α ⊕ string) := λ s, match t s with | (interaction_monad.result.success a s') := result.success (sum.inl a) s' | (interaction_monad.result.exception msg' _ s') := result.success (sum.inr (msg'.iget ()).to_string) s end /-- This tactic succeeds if `t` succeeds or fails with message `msg` such that `p msg` is `tt`. -/ meta def succeeds_or_fails_with_msg {α : Type} (t : tactic α) (p : string → bool) : tactic unit := do x ← retrieve_or_report_error t, match x with | (sum.inl _) := skip | (sum.inr msg) := if p msg then skip else fail msg end add_tactic_doc { name := "setup_tactic_parser", category := doc_category.cmd, decl_names := [`tactic.setup_tactic_parser_cmd], tags := ["parsing", "notation"] } /-- `trace_error msg t` executes the tactic `t`. If `t` fails, traces `msg` and the failure message of `t`. -/ meta def trace_error (msg : string) (t : tactic α) : tactic α | s := match t s with | (result.success r s') := result.success r s' | (result.exception (some msg') p s') := (trace msg >> trace (msg' ()) >> result.exception (some msg') p) s' | (result.exception none p s') := result.exception none p s' end /-- ``trace_if_enabled `n msg`` traces the message `msg` only if tracing is enabled for the name `n`. Create new names registered for tracing with `declare_trace n`. Then use `set_option trace.n true/false` to enable or disable tracing for `n`. -/ meta def trace_if_enabled (n : name) {α : Type u} [has_to_tactic_format α] (msg : α) : tactic unit := when_tracing n (trace msg) /-- ``trace_state_if_enabled `n msg`` prints the tactic state, preceded by the optional string `msg`, only if tracing is enabled for the name `n`. -/ meta def trace_state_if_enabled (n : name) (msg : string := "") : tactic unit := when_tracing n ((if msg = "" then skip else trace msg) >> trace_state) /-- This combinator is for testing purposes. It succeeds if `t` fails with message `msg`, and fails otherwise. -/ meta def success_if_fail_with_msg {α : Type u} (t : tactic α) (msg : string) : tactic unit := λ s, match t s with | (interaction_monad.result.exception msg' _ s') := let expected_msg := (msg'.iget ()).to_string in if msg = expected_msg then result.success () s else mk_exception format!"failure messages didn't match. Expected:\n{expected_msg}" none s | (interaction_monad.result.success a s) := mk_exception "success_if_fail_with_msg combinator failed, given tactic succeeded" none s end /-- Construct a `Try this: refine ...` or `Try this: exact ...` string which would construct `g`. -/ meta def tactic_statement (g : expr) : tactic string := do g ← instantiate_mvars g, g ← head_beta g, r ← pp (replace_mvars g), if g.has_meta_var then return (sformat!"Try this: refine {r}") else return (sformat!"Try this: exact {r}") /-- `with_local_goals gs tac` runs `tac` on the goals `gs` and then restores the initial goals and returns the goals `tac` ended on. -/ meta def with_local_goals {α} (gs : list expr) (tac : tactic α) : tactic (α × list expr) := do gs' ← get_goals, set_goals gs, finally (prod.mk <$> tac <*> get_goals) (set_goals gs') /-- like `with_local_goals` but discards the resulting goals -/ meta def with_local_goals' {α} (gs : list expr) (tac : tactic α) : tactic α := prod.fst <$> with_local_goals gs tac /-- Representation of a proof goal that lends itself to comparison. The following goal: ```lean l₀ : T, l₁ : T ⊢ ∀ v : T, foo ``` is represented as ``` (2, ∀ l₀ l₁ v : T, foo) ``` The number 2 indicates that first the two bound variables of the `∀` are actually local constant. Comparing two such goals with `=` rather than `=ₐ` or `is_def_eq` tells us that proof script should not see the difference between the two. -/ meta def packaged_goal := ℕ × expr /-- proof state made of multiple `goal` meant for comparing the result of running different tactics -/ meta def proof_state := list packaged_goal meta instance goal.inhabited : inhabited packaged_goal := ⟨(0,var 0)⟩ meta instance proof_state.inhabited : inhabited proof_state := (infer_instance : inhabited (list packaged_goal)) /-- create a `packaged_goal` corresponding to the current goal -/ meta def get_packaged_goal : tactic packaged_goal := do ls ← local_context, tgt ← target >>= instantiate_mvars, tgt ← pis ls tgt, pure (ls.length, tgt) /-- `goal_of_mvar g`, with `g` a meta variable, creates a `packaged_goal` corresponding to `g` interpretted as a proof goal -/ meta def goal_of_mvar (g : expr) : tactic packaged_goal := with_local_goals' [g] get_packaged_goal /-- `get_proof_state` lists the user visible goal for each goal of the current state and for each goal, abstracts all of the meta variables of the other gaols. This produces a list of goals in the form of `ℕ × expr` where the `expr` encodes the following proof state: ```lean 2 goals l₁ : t₁, l₂ : t₂, l₃ : t₃ ⊢ tgt₁ ⊢ tgt₂ ``` as ```lean [ (3, ∀ (mv : tgt₁) (mv : tgt₂) (l₁ : t₁) (l₂ : t₂) (l₃ : t₃), tgt₁), (0, ∀ (mv : tgt₁) (mv : tgt₂), tgt₂) ] ``` with 2 goals, the first 2 bound variables encode the meta variable of all the goals, the next 3 (in the first goal) and 0 (in the second goal) are the local constants. This representation allows us to compare goals and proof states while ignoring information like the unique name of local constants and the equality or difference of meta variables that encode the same goal. -/ meta def get_proof_state : tactic proof_state := do gs ← get_goals, gs.mmap $ λ g, do ⟨n,g⟩ ← goal_of_mvar g, g ← gs.mfoldl (λ g v, do g ← kabstract g v reducible ff, pure $ pi `goal binder_info.default `(true) g ) g, pure (n,g) /-- Run `tac` in a disposable proof state and return the state. See `proof_state`, `goal` and `get_proof_state`. -/ meta def get_proof_state_after (tac : tactic unit) : tactic (option proof_state) := try_core $ retrieve $ tac >> get_proof_state open lean _root_.interactive /-- A type alias for `tactic format`, standing for "pretty print format". -/ meta def pformat := tactic format /-- `mk` lifts `fmt : format` to the tactic monad (`pformat`). -/ meta def pformat.mk (fmt : format) : pformat := pure fmt /-- an alias for `pp`. -/ meta def to_pfmt {α} [has_to_tactic_format α] (x : α) : pformat := pp x meta instance pformat.has_to_tactic_format : has_to_tactic_format pformat := ⟨ id ⟩ meta instance : has_append pformat := ⟨ λ x y, (++) <$> x <*> y ⟩ meta instance tactic.has_to_tactic_format [has_to_tactic_format α] : has_to_tactic_format (tactic α) := ⟨ λ x, x >>= to_pfmt ⟩ private meta def parse_pformat : string → list char → parser pexpr | acc [] := pure ``(to_pfmt %%(reflect acc)) | acc ('\n'::s) := do f ← parse_pformat "" s, pure ``(to_pfmt %%(reflect acc) ++ pformat.mk format.line ++ %%f) | acc ('{'::'{'::s) := parse_pformat (acc ++ "{") s | acc ('{'::s) := do (e, s) ← with_input (lean.parser.pexpr 0) s.as_string, '}'::s ← return s.to_list | fail "'}' expected", f ← parse_pformat "" s, pure ``(to_pfmt %%(reflect acc) ++ to_pfmt %%e ++ %%f) | acc (c::s) := parse_pformat (acc.str c) s /-- See `format!` in `init/meta/interactive_base.lean`. The main differences are that `pp` is called instead of `to_fmt` and that we can use arguments of type `tactic α` in the quotations. Now, consider the following: ```lean e ← to_expr ``(3 + 7), trace format!"{e}" -- outputs `has_add.add.{0} nat nat.has_add -- (bit1.{0} nat nat.has_one nat.has_add (has_one.one.{0} nat nat.has_one)) ...` trace pformat!"{e}" -- outputs `3 + 7` ``` The difference is significant. And now, the following is expressible: ```lean e ← to_expr ``(3 + 7), trace pformat!"{e} : {infer_type e}" -- outputs `3 + 7 : ℕ` ``` See also: `trace!` and `fail!` -/ @[user_notation] meta def pformat_macro (_ : parse $ tk "pformat!") (s : string) : parser pexpr := do e ← parse_pformat "" s.to_list, return ``(%%e : pformat) /-- The combination of `pformat` and `fail`. -/ @[user_notation] meta def fail_macro (_ : parse $ tk "fail!") (s : string) : parser pexpr := do e ← pformat_macro () s, pure ``((%%e : pformat) >>= fail) /-- The combination of `pformat` and `trace`. -/ @[user_notation] meta def trace_macro (_ : parse $ tk "trace!") (s : string) : parser pexpr := do e ← pformat_macro () s, pure ``((%%e : pformat) >>= trace) /-- A hackish way to get the `src` directory of any project. Requires as argument any declaration name `n` in that project, and `k`, the number of characters in the path of the file where `n` is declared not part of the `src` directory. Example: For `mathlib_dir_locator` this is the length of `tactic/project_dir.lean`, so `23`. Note: does not work in the file where `n` is declared. -/ meta def get_project_dir (n : name) (k : ℕ) : tactic string := do e ← get_env, s ← e.decl_olean n <|> fail!"Did not find declaration {n}. This command does not work in the file where {n} is declared.", return $ s.popn_back k /-- A hackish way to get the `src` directory of mathlib. -/ meta def get_mathlib_dir : tactic string := get_project_dir `mathlib_dir_locator 23 /-- Checks whether a declaration with the given name is declared in mathlib. If you want to run this tactic many times, you should use `environment.is_prefix_of_file` instead, since it is expensive to execute `get_mathlib_dir` many times. -/ meta def is_in_mathlib (n : name) : tactic bool := do ml ← get_mathlib_dir, e ← get_env, return $ e.is_prefix_of_file ml n /-- Runs a tactic by name. If it is a `tactic string`, return whatever string it returns. If it is a `tactic unit`, return the name. (This is mostly used in invoking "self-reporting tactics", e.g. by `tidy` and `hint`.) -/ meta def name_to_tactic (n : name) : tactic string := do d ← get_decl n, e ← mk_const n, let t := d.type, if (t =ₐ `(tactic unit)) then (eval_expr (tactic unit) e) >>= (λ t, t >> (name.to_string <$> strip_prefix n)) else if (t =ₐ `(tactic string)) then (eval_expr (tactic string) e) >>= (λ t, t) else fail! "name_to_tactic cannot take `{n} as input: its type must be `tactic string` or `tactic unit`" /-- auxiliary function for `apply_under_n_pis` -/ private meta def apply_under_n_pis_aux (func arg : pexpr) : ℕ → ℕ → expr → pexpr | n 0 _ := let vars := ((list.range n).reverse.map (@expr.var ff)), bd := vars.foldl expr.app arg.mk_explicit in func bd | n (k+1) (expr.pi nm bi tp bd) := expr.pi nm bi (pexpr.of_expr tp) (apply_under_n_pis_aux (n+1) k bd) | n (k+1) t := apply_under_n_pis_aux n 0 t /-- Assumes `pi_expr` is of the form `Π x1 ... xn xn+1..., _`. Creates a pexpr of the form `Π x1 ... xn, func (arg x1 ... xn)`. All arguments (implicit and explicit) to `arg` should be supplied. -/ meta def apply_under_n_pis (func arg : pexpr) (pi_expr : expr) (n : ℕ) : pexpr := apply_under_n_pis_aux func arg 0 n pi_expr /-- Assumes `pi_expr` is of the form `Π x1 ... xn, _`. Creates a pexpr of the form `Π x1 ... xn, func (arg x1 ... xn)`. All arguments (implicit and explicit) to `arg` should be supplied. -/ meta def apply_under_pis (func arg : pexpr) (pi_expr : expr) : pexpr := apply_under_n_pis func arg pi_expr pi_expr.pi_arity /-- If `func` is a `pexpr` representing a function that takes an argument `a`, `get_pexpr_arg_arity_with_tgt func tgt` returns the arity of `a`. When `tgt` is a `pi` expr, `func` is elaborated in a context with the domain of `tgt`. Examples: * ```get_pexpr_arg_arity ``(ring) `(true)``` returns 0, since `ring` takes one non-function argument. * ```get_pexpr_arg_arity_with_tgt ``(monad) `(true)``` returns 1, since `monad` takes one argument of type `α → α`. * ```get_pexpr_arg_arity_with_tgt ``(module R) `(Π (R : Type), comm_ring R → true)``` returns 0 -/ meta def get_pexpr_arg_arity_with_tgt (func : pexpr) (tgt : expr) : tactic ℕ := lock_tactic_state $ do mv ← mk_mvar, solve_aux tgt $ intros >> to_expr ``(%%func %%mv), expr.pi_arity <$> (infer_type mv >>= instantiate_mvars) /-- `find_private_decl n none` finds a private declaration named `n` in any of the imported files. `find_private_decl n (some m)` finds a private declaration named `n` in the same file where a declaration named `m` can be found. -/ meta def find_private_decl (n : name) (fr : option name) : tactic name := do env ← get_env, fn ← option_t.run (do fr ← option_t.mk (return fr), d ← monad_lift $ get_decl fr, option_t.mk (return $ env.decl_olean d.to_name) ), let p : string → bool := match fn with | (some fn) := λ x, fn = x | none := λ _, tt end, let xs := env.decl_filter_map (λ d, do fn ← env.decl_olean d.to_name, guard ((`_private).is_prefix_of d.to_name ∧ p fn ∧ d.to_name.update_prefix name.anonymous = n), pure d.to_name), match xs with | [n] := pure n | [] := fail "no such private found" | _ := fail "many matches found" end open lean.parser interactive /-- `import_private foo from bar` finds a private declaration `foo` in the same file as `bar` and creates a local notation to refer to it. `import_private foo` looks for `foo` in all imported files. When possible, make `foo` non-private rather than using this feature. -/ @[user_command] meta def import_private_cmd (_ : parse $ tk "import_private") : lean.parser unit := do n ← ident, fr ← optional (tk "from" *> ident), n ← find_private_decl n fr, c ← resolve_constant n, d ← get_decl n, let c := @expr.const tt c d.univ_levels, new_n ← new_aux_decl_name, add_decl $ declaration.defn new_n d.univ_params d.type c reducibility_hints.abbrev d.is_trusted, let new_not := sformat!"local notation `{n.update_prefix name.anonymous}` := {new_n}", emit_command_here $ new_not, skip . add_tactic_doc { name := "import_private", category := doc_category.cmd, decl_names := [`tactic.import_private_cmd], tags := ["renaming"] } /-- The command `mk_simp_attribute simp_name "description"` creates a simp set with name `simp_name`. Lemmas tagged with `@[simp_name]` will be included when `simp with simp_name` is called. `mk_simp_attribute simp_name none` will use a default description. Appending the command with `with attr1 attr2 ...` will include all declarations tagged with `attr1`, `attr2`, ... in the new simp set. This command is preferred to using ``run_cmd mk_simp_attr `simp_name`` since it adds a doc string to the attribute that is defined. If you need to create a simp set in a file where this command is not available, you should use ```lean run_cmd mk_simp_attr `simp_name run_cmd add_doc_string `simp_attr.simp_name "Description of the simp set here" ``` -/ @[user_command] meta def mk_simp_attribute_cmd (_ : parse $ tk "mk_simp_attribute") : lean.parser unit := do n ← ident, d ← parser.pexpr, d ← to_expr ``(%%d : option string), descr ← eval_expr (option string) d, with_list ← (tk "with" *> many ident) <|> return [], mk_simp_attr n with_list, add_doc_string (name.append `simp_attr n) $ descr.get_or_else $ "simp set for " ++ to_string n add_tactic_doc { name := "mk_simp_attribute", category := doc_category.cmd, decl_names := [`tactic.mk_simp_attribute_cmd], tags := ["simplification"] } /-- Given a user attribute name `attr_name`, `get_user_attribute_name attr_name` returns the name of the declaration that defines this attribute. Fails if there is no user attribute with this name. Example: ``get_user_attribute_name `norm_cast`` returns `` `norm_cast.norm_cast_attr`` -/ meta def get_user_attribute_name (attr_name : name) : tactic name := do ns ← attribute.get_instances `user_attribute, ns.mfirst (λ nm, do d ← get_decl nm, e ← mk_app `user_attribute.name [d.value], attr_nm ← eval_expr name e, guard $ attr_nm = attr_name, return nm) <|> fail!"'{attr_name}' is not a user attribute." /-- A tactic to set either a basic attribute or a user attribute. If the user attribute has a parameter, the default value will be used. This tactic raises an error if there is no `inhabited` instance for the parameter type. -/ meta def set_attribute (attr_name : name) (c_name : name) (persistent := tt) (prio : option nat := none) : tactic unit := do get_decl c_name <|> fail!"unknown declaration {c_name}", s ← try_or_report_error (set_basic_attribute attr_name c_name persistent prio), sum.inr msg ← return s | skip, if msg = (format!"set_basic_attribute tactic failed, '{attr_name}' is not a basic attribute").to_string then do user_attr_nm ← get_user_attribute_name attr_name, user_attr_const ← mk_const user_attr_nm, tac ← eval_pexpr (tactic unit) ``(user_attribute.set %%user_attr_const %%`(c_name) default %%`(persistent)) <|> fail! ("Cannot set attribute @[{attr_name}].\n" ++ "The corresponding user attribute {user_attr_nm} " ++ "has a parameter without a default value.\n" ++ "Solution: provide an `inhabited` instance."), tac else fail msg end tactic /-- `find_defeq red m e` looks for a key in `m` that is defeq to `e` (up to transparency `red`), and returns the value associated with this key if it exists. Otherwise, it fails. -/ meta def list.find_defeq (red : tactic.transparency) {v} (m : list (expr × v)) (e : expr) : tactic (expr × v) := m.mfind $ λ ⟨e', val⟩, tactic.is_def_eq e e' red
3b288e8296d34560514d073d42bf0f7fe0b3fdd0
80cc5bf14c8ea85ff340d1d747a127dcadeb966f
/src/linear_algebra/basic.lean
d144a21587fc3bb355ff27bd421889132a27622b
[ "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
104,683
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.big_operators.pi import algebra.module.pi import algebra.module.prod import algebra.module.submodule import algebra.group.prod import data.finsupp.basic import algebra.pointwise /-! # Linear algebra This file defines the basics of linear algebra. It sets up the "categorical/lattice structure" of modules over a ring, submodules, and linear maps. If `p` and `q` are submodules of a module, `p ≤ q` means that `p ⊆ q`. Many of the relevant definitions, including `module`, `submodule`, and `linear_map`, are found in `src/algebra/module.lean`. ## Main definitions * Many constructors for linear maps, including `prod` and `coprod` * `submodule.span s` is defined to be the smallest submodule containing the set `s`. * If `p` is a submodule of `M`, `submodule.quotient p` is the quotient of `M` with respect to `p`: that is, elements of `M` are identified if their difference is in `p`. This is itself a module. * The kernel `ker` and range `range` of a linear map are submodules of the domain and codomain respectively. * `linear_equiv M M₂`, the type of linear equivalences between `M` and `M₂`, is a structure that extends `linear_map` and `equiv`. * The general linear group is defined to be the group of invertible linear maps from `M` to itself. ## Main statements * The first and second isomorphism laws for modules are proved as `quot_ker_equiv_range` and `quotient_inf_equiv_sup_quotient`. ## Notations * We continue to use the notation `M →ₗ[R] M₂` for the type of linear maps from `M` to `M₂` over the ring `R`. * We introduce the notations `M ≃ₗ M₂` and `M ≃ₗ[R] M₂` for `linear_equiv M M₂`. In the first, the ring `R` is implicit. ## Implementation notes We note that, when constructing linear maps, it is convenient to use operations defined on bundled maps (`prod`, `coprod`, arithmetic operations like `+`) instead of defining a function and proving it is linear. ## Tags linear algebra, vector space, module -/ open function open_locale big_operators reserve infix ` ≃ₗ `:25 universes u v w x y z u' v' w' y' variables {R : Type u} {K : Type u'} {M : Type v} {V : Type v'} {M₂ : Type w} {V₂ : Type w'} variables {M₃ : Type y} {V₃ : Type y'} {M₄ : Type z} {ι : Type x} namespace finsupp lemma smul_sum {α : Type u} {β : Type v} {R : Type w} {M : Type y} [has_zero β] [semiring R] [add_comm_monoid M] [semimodule R M] {v : α →₀ β} {c : R} {h : α → β → M} : c • (v.sum h) = v.sum (λa b, c • h a b) := finset.smul_sum end finsupp section open_locale classical /-- decomposing `x : ι → R` as a sum along the canonical basis -/ lemma pi_eq_sum_univ {ι : Type u} [fintype ι] {R : Type v} [semiring R] (x : ι → R) : x = ∑ i, x i • (λj, if i = j then 1 else 0) := by { ext, simp } end /-! ### Properties of linear maps -/ namespace linear_map section add_comm_monoid variables [semiring R] variables [add_comm_monoid M] [add_comm_monoid M₂] [add_comm_monoid M₃] [add_comm_monoid M₄] variables [semimodule R M] [semimodule R M₂] [semimodule R M₃] [semimodule R M₄] variables (f g : M →ₗ[R] M₂) include R @[simp] theorem comp_id : f.comp id = f := linear_map.ext $ λ x, rfl @[simp] theorem id_comp : id.comp f = f := linear_map.ext $ λ x, rfl theorem comp_assoc (g : M₂ →ₗ[R] M₃) (h : M₃ →ₗ[R] M₄) : (h.comp g).comp f = h.comp (g.comp f) := rfl /-- The restriction of a linear map `f : M → M₂` to a submodule `p ⊆ M` gives a linear map `p → M₂`. -/ def dom_restrict (f : M →ₗ[R] M₂) (p : submodule R M) : p →ₗ[R] M₂ := f.comp p.subtype @[simp] lemma dom_restrict_apply (f : M →ₗ[R] M₂) (p : submodule R M) (x : p) : f.dom_restrict p x = f x := rfl /-- A linear map `f : M₂ → M` whose values lie in a submodule `p ⊆ M` can be restricted to a linear map M₂ → p. -/ def cod_restrict (p : submodule R M) (f : M₂ →ₗ[R] M) (h : ∀c, f c ∈ p) : M₂ →ₗ[R] p := by refine {to_fun := λc, ⟨f c, h c⟩, ..}; intros; apply set_coe.ext; simp @[simp] theorem cod_restrict_apply (p : submodule R M) (f : M₂ →ₗ[R] M) {h} (x : M₂) : (cod_restrict p f h x : M) = f x := rfl @[simp] lemma comp_cod_restrict (p : submodule R M₂) (h : ∀b, f b ∈ p) (g : M₃ →ₗ[R] M) : (cod_restrict p f h).comp g = cod_restrict p (f.comp g) (assume b, h _) := ext $ assume b, rfl @[simp] lemma subtype_comp_cod_restrict (p : submodule R M₂) (h : ∀b, f b ∈ p) : p.subtype.comp (cod_restrict p f h) = f := ext $ assume b, rfl /-- Restrict domain and codomain of an endomorphism. -/ def restrict (f : M →ₗ[R] M) {p : submodule R M} (hf : ∀ x ∈ p, f x ∈ p) : p →ₗ[R] p := { to_fun := λ x, ⟨f x, hf x.1 x.2⟩, map_add' := begin intros, apply set_coe.ext, simp end, map_smul' := begin intros, apply set_coe.ext, simp end } lemma restrict_apply {f : M →ₗ[R] M} {p : submodule R M} (hf : ∀ x ∈ p, f x ∈ p) (x : p) : f.restrict hf x = ⟨f x, hf x.1 x.2⟩ := rfl lemma subtype_comp_restrict {f : M →ₗ[R] M} {p : submodule R M} (hf : ∀ x ∈ p, f x ∈ p) : p.subtype.comp (f.restrict hf) = f.dom_restrict p := rfl lemma restrict_eq_cod_restrict_dom_restrict {f : M →ₗ[R] M} {p : submodule R M} (hf : ∀ x ∈ p, f x ∈ p) : f.restrict hf = (f.dom_restrict p).cod_restrict p (λ x, hf x.1 x.2) := rfl lemma restrict_eq_dom_restrict_cod_restrict {f : M →ₗ[R] M} {p : submodule R M} (hf : ∀ x, f x ∈ p) : f.restrict (λ x _, hf x) = (f.cod_restrict p hf).dom_restrict p := rfl /-- If a function `g` is a left and right inverse of a linear map `f`, then `g` is linear itself. -/ def inverse (g : M₂ → M) (h₁ : left_inverse g f) (h₂ : right_inverse g f) : M₂ →ₗ[R] M := by dsimp [left_inverse, function.right_inverse] at h₁ h₂; exact ⟨g, λ x y, by rw [← h₁ (g (x + y)), ← h₁ (g x + g y)]; simp [h₂], λ a b, by rw [← h₁ (g (a • b)), ← h₁ (a • g b)]; simp [h₂]⟩ /-- The constant 0 map is linear. -/ instance : has_zero (M →ₗ[R] M₂) := ⟨⟨λ _, 0, by simp, by simp⟩⟩ instance : inhabited (M →ₗ[R] M₂) := ⟨0⟩ @[simp] lemma zero_apply (x : M) : (0 : M →ₗ[R] M₂) x = 0 := rfl /-- The sum of two linear maps is linear. -/ instance : has_add (M →ₗ[R] M₂) := ⟨λ f g, ⟨λ b, f b + g b, by simp [add_comm, add_left_comm], by simp [smul_add]⟩⟩ @[simp] lemma add_apply (x : M) : (f + g) x = f x + g x := rfl /-- The type of linear maps is an additive monoid. -/ instance : add_comm_monoid (M →ₗ[R] M₂) := by refine {zero := 0, add := (+), ..}; intros; ext; simp [add_comm, add_left_comm] instance linear_map_apply_is_add_monoid_hom (a : M) : is_add_monoid_hom (λ f : M →ₗ[R] M₂, f a) := { map_add := λ f g, linear_map.add_apply f g a, map_zero := rfl } lemma add_comp (g : M₂ →ₗ[R] M₃) (h : M₂ →ₗ[R] M₃) : (h + g).comp f = h.comp f + g.comp f := rfl lemma comp_add (g : M →ₗ[R] M₂) (h : M₂ →ₗ[R] M₃) : h.comp (f + g) = h.comp f + h.comp g := by { ext, simp } lemma sum_apply (t : finset ι) (f : ι → M →ₗ[R] M₂) (b : M) : (∑ d in t, f d) b = ∑ d in t, f d b := (t.sum_hom (λ g : M →ₗ[R] M₂, g b)).symm /-- `λb, f b • x` is a linear map. -/ def smul_right (f : M₂ →ₗ[R] R) (x : M) : M₂ →ₗ[R] M := ⟨λb, f b • x, by simp [add_smul], by simp [smul_smul]⟩. @[simp] theorem smul_right_apply (f : M₂ →ₗ[R] R) (x : M) (c : M₂) : (smul_right f x : M₂ → M) c = f c • x := rfl instance : has_one (M →ₗ[R] M) := ⟨linear_map.id⟩ instance : has_mul (M →ₗ[R] M) := ⟨linear_map.comp⟩ @[simp] lemma one_app (x : M) : (1 : M →ₗ[R] M) x = x := rfl @[simp] lemma mul_app (A B : M →ₗ[R] M) (x : M) : (A * B) x = A (B x) := rfl @[simp] theorem comp_zero : f.comp (0 : M₃ →ₗ[R] M) = 0 := ext $ assume c, by rw [comp_apply, zero_apply, zero_apply, f.map_zero] @[simp] theorem zero_comp : (0 : M₂ →ₗ[R] M₃).comp f = 0 := rfl @[norm_cast] lemma coe_fn_sum {ι : Type*} (t : finset ι) (f : ι → M →ₗ[R] M₂) : ⇑(∑ i in t, f i) = ∑ i in t, (f i : M → M₂) := add_monoid_hom.map_sum ⟨@to_fun R M M₂ _ _ _ _ _, rfl, λ x y, rfl⟩ _ _ instance : monoid (M →ₗ[R] M) := by refine {mul := (*), one := 1, ..}; { intros, apply linear_map.ext, simp {proj := ff} } section open_locale classical /-- A linear map `f` applied to `x : ι → R` can be computed using the image under `f` of elements of the canonical basis. -/ lemma pi_apply_eq_sum_univ [fintype ι] (f : (ι → R) →ₗ[R] M) (x : ι → R) : f x = ∑ i, x i • (f (λj, if i = j then 1 else 0)) := begin conv_lhs { rw [pi_eq_sum_univ x, f.map_sum] }, apply finset.sum_congr rfl (λl hl, _), rw f.map_smul end end section variables (R M M₂) /-- The first projection of a product is a linear map. -/ def fst : M × M₂ →ₗ[R] M := ⟨prod.fst, λ x y, rfl, λ x y, rfl⟩ /-- The second projection of a product is a linear map. -/ def snd : M × M₂ →ₗ[R] M₂ := ⟨prod.snd, λ x y, rfl, λ x y, rfl⟩ end @[simp] theorem fst_apply (x : M × M₂) : fst R M M₂ x = x.1 := rfl @[simp] theorem snd_apply (x : M × M₂) : snd R M M₂ x = x.2 := rfl /-- The prod of two linear maps is a linear map. -/ def prod (f : M →ₗ[R] M₂) (g : M →ₗ[R] M₃) : M →ₗ[R] M₂ × M₃ := { to_fun := λ x, (f x, g x), map_add' := λ x y, by simp only [prod.mk_add_mk, map_add], map_smul' := λ c x, by simp only [prod.smul_mk, map_smul] } @[simp] theorem prod_apply (f : M →ₗ[R] M₂) (g : M →ₗ[R] M₃) (x : M) : prod f g x = (f x, g x) := rfl @[simp] theorem fst_prod (f : M →ₗ[R] M₂) (g : M →ₗ[R] M₃) : (fst R M₂ M₃).comp (prod f g) = f := by ext; refl @[simp] theorem snd_prod (f : M →ₗ[R] M₂) (g : M →ₗ[R] M₃) : (snd R M₂ M₃).comp (prod f g) = g := by ext; refl @[simp] theorem pair_fst_snd : prod (fst R M M₂) (snd R M M₂) = linear_map.id := by ext; refl section variables (R M M₂) /-- The left injection into a product is a linear map. -/ def inl : M →ₗ[R] M × M₂ := by refine ⟨add_monoid_hom.inl _ _, _, _⟩; intros; simp /-- The right injection into a product is a linear map. -/ def inr : M₂ →ₗ[R] M × M₂ := by refine ⟨add_monoid_hom.inr _ _, _, _⟩; intros; simp end @[simp] theorem inl_apply (x : M) : inl R M M₂ x = (x, 0) := rfl @[simp] theorem inr_apply (x : M₂) : inr R M M₂ x = (0, x) := rfl theorem inl_injective : function.injective (inl R M M₂) := λ _, by simp theorem inr_injective : function.injective (inr R M M₂) := λ _, by simp /-- The coprod function `λ x : M × M₂, f x.1 + g x.2` is a linear map. -/ def coprod (f : M →ₗ[R] M₃) (g : M₂ →ₗ[R] M₃) : M × M₂ →ₗ[R] M₃ := { to_fun := λ x, f x.1 + g x.2, map_add' := λ x y, by simp only [map_add, prod.snd_add, prod.fst_add]; cc, map_smul' := λ x y, by simp only [smul_add, prod.smul_snd, prod.smul_fst, map_smul] } @[simp] theorem coprod_apply (f : M →ₗ[R] M₃) (g : M₂ →ₗ[R] M₃) (x : M) (y : M₂) : coprod f g (x, y) = f x + g y := rfl @[simp] theorem coprod_inl (f : M →ₗ[R] M₃) (g : M₂ →ₗ[R] M₃) : (coprod f g).comp (inl R M M₂) = f := by ext; simp only [map_zero, add_zero, coprod_apply, inl_apply, comp_apply] @[simp] theorem coprod_inr (f : M →ₗ[R] M₃) (g : M₂ →ₗ[R] M₃) : (coprod f g).comp (inr R M M₂) = g := by ext; simp only [map_zero, coprod_apply, inr_apply, zero_add, comp_apply] @[simp] theorem coprod_inl_inr : coprod (inl R M M₂) (inr R M M₂) = linear_map.id := by ext ⟨x, y⟩; simp only [prod.mk_add_mk, add_zero, id_apply, coprod_apply, inl_apply, inr_apply, zero_add] theorem fst_eq_coprod : fst R M M₂ = coprod linear_map.id 0 := by ext ⟨x, y⟩; simp theorem snd_eq_coprod : snd R M M₂ = coprod 0 linear_map.id := by ext ⟨x, y⟩; simp theorem inl_eq_prod : inl R M M₂ = prod linear_map.id 0 := rfl theorem inr_eq_prod : inr R M M₂ = prod 0 linear_map.id := rfl /-- `prod.map` of two linear maps. -/ def prod_map (f : M →ₗ[R] M₃) (g : M₂ →ₗ[R] M₄) : (M × M₂) →ₗ[R] (M₃ × M₄) := (f.comp (fst R M M₂)).prod (g.comp (snd R M M₂)) @[simp] theorem prod_map_apply (f : M →ₗ[R] M₃) (g : M₂ →ₗ[R] M₄) (x) : f.prod_map g x = (f x.1, g x.2) := rfl end add_comm_monoid section add_comm_group variables [semiring R] [add_comm_group M] [add_comm_group M₂] [add_comm_group M₃] [add_comm_group M₄] variables [semimodule R M] [semimodule R M₂] [semimodule R M₃] [semimodule R M₄] variables (f g : M →ₗ[R] M₂) include R /-- The negation of a linear map is linear. -/ instance : has_neg (M →ₗ[R] M₂) := ⟨λ f, ⟨λ b, - f b, by simp [add_comm], by simp⟩⟩ @[simp] lemma neg_apply (x : M) : (- f) x = - f x := rfl @[simp] lemma comp_neg (g : M₂ →ₗ[R] M₃) : g.comp (- f) = - g.comp f := by { ext, simp } /-- The type of linear maps is an additive group. -/ instance : add_comm_group (M →ₗ[R] M₂) := by refine {zero := 0, add := (+), neg := has_neg.neg, ..}; intros; ext; simp [add_comm, add_left_comm] instance linear_map_apply_is_add_group_hom (a : M) : is_add_group_hom (λ f : M →ₗ[R] M₂, f a) := { map_add := λ f g, linear_map.add_apply f g a } @[simp] lemma sub_apply (x : M) : (f - g) x = f x - g x := rfl lemma sub_comp (g : M₂ →ₗ[R] M₃) (h : M₂ →ₗ[R] M₃) : (g - h).comp f = g.comp f - h.comp f := rfl lemma comp_sub (g : M →ₗ[R] M₂) (h : M₂ →ₗ[R] M₃) : h.comp (g - f) = h.comp g - h.comp f := by { ext, simp } end add_comm_group section comm_semiring variables [comm_semiring R] [add_comm_monoid M] [add_comm_monoid M₂] [add_comm_monoid M₃] variables [semimodule R M] [semimodule R M₂] [semimodule R M₃] variables (f g : M →ₗ[R] M₂) include R instance : has_scalar R (M →ₗ[R] M₂) := ⟨λ a f, ⟨λ b, a • f b, by simp [smul_add], by simp [smul_smul, mul_comm]⟩⟩ @[simp] lemma smul_apply (a : R) (x : M) : (a • f) x = a • f x := rfl instance : semimodule R (M →ₗ[R] M₂) := by refine { smul := (•), .. }; intros; ext; simp [smul_add, add_smul, smul_smul] /-- Composition by `f : M₂ → M₃` is a linear map from the space of linear maps `M → M₂` to the space of linear maps `M₂ → M₃`. -/ def comp_right (f : M₂ →ₗ[R] M₃) : (M →ₗ[R] M₂) →ₗ[R] (M →ₗ[R] M₃) := ⟨linear_map.comp f, λ _ _, linear_map.ext $ λ _, f.2 _ _, λ _ _, linear_map.ext $ λ _, f.3 _ _⟩ theorem smul_comp (g : M₂ →ₗ[R] M₃) (a : R) : (a • g).comp f = a • (g.comp f) := rfl theorem comp_smul (g : M₂ →ₗ[R] M₃) (a : R) : g.comp (a • f) = a • (g.comp f) := ext $ assume b, by rw [comp_apply, smul_apply, g.map_smul]; refl /-- Applying a linear map at `v : M`, seen as a linear map from `M →ₗ[R] M₂` to `M₂`. -/ def applyₗ (v : M) : (M →ₗ[R] M₂) →ₗ[R] M₂ := { to_fun := λ f, f v, map_add' := λ f g, f.add_apply g v, map_smul' := λ x f, f.smul_apply x v } end comm_semiring section ring variables [ring R] [add_comm_group M] [semimodule R M] instance endomorphism_ring : ring (M →ₗ[R] M) := by refine {mul := (*), one := 1, ..linear_map.add_comm_group, ..}; { intros, apply linear_map.ext, simp {proj := ff} } @[simp] lemma mul_apply (f g : M →ₗ[R] M) (x : M) : (f * g) x = f (g x) := rfl end ring section comm_ring variables [comm_ring R] [add_comm_group M] [add_comm_group M₂] [add_comm_group M₃] variables [semimodule R M] [semimodule R M₂] [semimodule R M₃] /-- The family of linear maps `M₂ → M` parameterised by `f ∈ M₂ → R`, `x ∈ M`, is linear in `f`, `x`. -/ def smul_rightₗ : (M₂ →ₗ[R] R) →ₗ[R] M →ₗ[R] M₂ →ₗ[R] M := { to_fun := λ f, { to_fun := linear_map.smul_right f, map_add' := λ m m', by { ext, apply smul_add, }, map_smul' := λ c m, by { ext, apply smul_comm, } }, map_add' := λ f f', by { ext, apply add_smul, }, map_smul' := λ c f, by { ext, apply mul_smul, } } @[simp] lemma smul_rightₗ_apply (f : M₂ →ₗ[R] R) (x : M) (c : M₂) : (smul_rightₗ : (M₂ →ₗ R) →ₗ M →ₗ M₂ →ₗ M) f x c = (f c) • x := rfl end comm_ring end linear_map /-! ### Properties of submodules -/ namespace submodule section add_comm_monoid variables [semiring R] [add_comm_monoid M] [add_comm_monoid M₂] [add_comm_monoid M₃] variables [semimodule R M] [semimodule R M₂] [semimodule R M₃] variables (p p' : submodule R M) (q q' : submodule R M₂) variables {r : R} {x y : M} open set instance : partial_order (submodule R M) := { le := λ p p', ∀ ⦃x⦄, x ∈ p → x ∈ p', ..partial_order.lift (coe : submodule R M → set M) coe_injective } variables {p p'} lemma le_def : p ≤ p' ↔ (p : set M) ⊆ p' := iff.rfl lemma le_def' : p ≤ p' ↔ ∀ x ∈ p, x ∈ p' := iff.rfl lemma lt_def : p < p' ↔ (p : set M) ⊂ p' := iff.rfl lemma not_le_iff_exists : ¬ (p ≤ p') ↔ ∃ x ∈ p, x ∉ p' := not_subset lemma exists_of_lt {p p' : submodule R M} : p < p' → ∃ x ∈ p', x ∉ p := exists_of_ssubset lemma lt_iff_le_and_exists : p < p' ↔ p ≤ p' ∧ ∃ x ∈ p', x ∉ p := by rw [lt_iff_le_not_le, not_le_iff_exists] /-- If two submodules `p` and `p'` satisfy `p ⊆ p'`, then `of_le p p'` is the linear map version of this inclusion. -/ def of_le (h : p ≤ p') : p →ₗ[R] p' := p.subtype.cod_restrict p' $ λ ⟨x, hx⟩, h hx @[simp] theorem coe_of_le (h : p ≤ p') (x : p) : (of_le h x : M) = x := rfl theorem of_le_apply (h : p ≤ p') (x : p) : of_le h x = ⟨x, h x.2⟩ := rfl variables (p p') lemma subtype_comp_of_le (p q : submodule R M) (h : p ≤ q) : q.subtype.comp (of_le h) = p.subtype := by { ext ⟨b, hb⟩, refl } /-- 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 section variables (R) @[simp] lemma mem_bot : x ∈ (⊥ : submodule R M) ↔ x = 0 := mem_singleton_iff end lemma nonzero_mem_of_bot_lt {I : submodule R M} (bot_lt : ⊥ < I) : ∃ a : I, a ≠ 0 := begin have h := (submodule.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}, ..submodule.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)) ⟩ 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 universal set is the top element of the lattice of submodules. -/ instance : has_top (submodule R M) := ⟨{ carrier := univ, smul_mem' := λ _ _ _, trivial, .. (⊤ : add_submonoid M)}⟩ @[simp] lemma top_coe : ((⊤ : submodule R M) : set M) = univ := rfl @[simp] lemma mem_top : x ∈ (⊤ : submodule R M) := trivial lemma eq_bot_of_zero_eq_one (zero_eq_one : (0 : R) = 1) : p = ⊥ := by ext x; simp [semimodule.eq_zero_of_zero_eq_one x zero_eq_one] instance : order_top (submodule R M) := { top := ⊤, le_top := λ p x _, trivial, ..submodule.partial_order } 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 := bInter_subset_of_mem private lemma le_Inf' {S : set (submodule R M)} {p} : (∀p' ∈ S, p ≤ p') → p ≤ Inf S := subset_bInter instance : has_inf (submodule R M) := ⟨λ p p', { carrier := p ∩ p', 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, subset_inter, inf_le_left := λ a b, inter_subset_left _ _, inf_le_right := λ a b, inter_subset_right _ _, Sup := λtt, Inf {t | ∀t'∈tt, t' ≤ t}, le_Sup := λ s p hs, le_Inf' $ λ p' hp', hp' _ 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 } instance add_comm_monoid_submodule : add_comm_monoid (submodule R M) := { add := (⊔), add_assoc := λ _ _ _, sup_assoc, zero := ⊥, zero_add := λ _, bot_sup_eq, add_zero := λ _, sup_bot_eq, add_comm := λ _ _, sup_comm } @[simp] lemma add_eq_sup (p q : submodule R M) : p + q = p ⊔ q := rfl @[simp] lemma zero_eq_bot : (0 : submodule R M) = ⊥ := rfl lemma eq_top_iff' {p : submodule R M} : p = ⊤ ↔ ∀ x, x ∈ p := eq_top_iff.trans ⟨λ h x, @h x trivial, λ h x _, h x⟩ lemma bot_ne_top [nontrivial M] : (⊥ : submodule R M) ≠ ⊤ := λ h, let ⟨a, ha⟩ := exists_ne (0 : M) in ha $ (mem_bot R).1 $ (eq_top_iff.1 h) trivial @[simp] theorem inf_coe : (p ⊓ p' : set M) = p ∩ p' := rfl @[simp] theorem mem_inf {p p' : submodule R M} : x ∈ p ⊓ p' ↔ x ∈ p ∧ x ∈ p' := 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 ∈ (⨅ i, p i) ↔ ∀ i, x ∈ p i := by rw [← mem_coe, infi_coe, mem_Inter]; refl theorem disjoint_def {p p' : submodule R M} : disjoint p p' ↔ ∀ x ∈ p, x ∈ p' → x = (0:M) := show (∀ x, x ∈ p ∧ x ∈ p' → x ∈ ({0} : set M)) ↔ _, by simp theorem mem_right_iff_eq_zero_of_disjoint {p p' : submodule R M} (h : disjoint p p') {x : p} : (x:M) ∈ p' ↔ x = 0 := ⟨λ hx, coe_eq_zero.1 $ disjoint_def.1 h x x.2 hx, λ h, h.symm ▸ p'.zero_mem⟩ theorem mem_left_iff_eq_zero_of_disjoint {p p' : submodule R M} (h : disjoint p p') {x : p'} : (x:M) ∈ p ↔ x = 0 := ⟨λ hx, coe_eq_zero.1 $ disjoint_def.1 h x hx x.2, λ h, h.symm ▸ p.zero_mem⟩ /-- The pushforward of a submodule `p ⊆ M` by `f : M → M₂` -/ def map (f : M →ₗ[R] M₂) (p : submodule R M) : submodule R M₂ := { carrier := f '' p, smul_mem' := by rintro a _ ⟨b, hb, rfl⟩; exact ⟨_, p.smul_mem _ hb, f.map_smul _ _⟩, .. p.to_add_submonoid.map f.to_add_monoid_hom } @[simp] lemma map_coe (f : M →ₗ[R] M₂) (p : submodule R M) : (map f p : set M₂) = f '' p := rfl @[simp] lemma mem_map {f : M →ₗ[R] M₂} {p : submodule R M} {x : M₂} : x ∈ map f p ↔ ∃ y, y ∈ p ∧ f y = x := iff.rfl theorem mem_map_of_mem {f : M →ₗ[R] M₂} {p : submodule R M} {r} (h : r ∈ p) : f r ∈ map f p := set.mem_image_of_mem _ h lemma map_id : map linear_map.id p = p := submodule.ext $ λ a, by simp lemma map_comp (f : M →ₗ[R] M₂) (g : M₂ →ₗ[R] M₃) (p : submodule R M) : map (g.comp f) p = map g (map f p) := submodule.coe_injective $ by simp [map_coe]; rw ← image_comp lemma map_mono {f : M →ₗ[R] M₂} {p p' : submodule R M} : p ≤ p' → map f p ≤ map f p' := image_subset _ @[simp] lemma map_zero : map (0 : M →ₗ[R] M₂) p = ⊥ := have ∃ (x : M), x ∈ p := ⟨0, p.zero_mem⟩, ext $ by simp [this, eq_comm] /-- The pullback of a submodule `p ⊆ M₂` along `f : M → M₂` -/ def comap (f : M →ₗ[R] M₂) (p : submodule R M₂) : submodule R M := { carrier := f ⁻¹' p, smul_mem' := λ a x h, by simp [p.smul_mem _ h], .. p.to_add_submonoid.comap f.to_add_monoid_hom } @[simp] lemma comap_coe (f : M →ₗ[R] M₂) (p : submodule R M₂) : (comap f p : set M) = f ⁻¹' p := rfl @[simp] lemma mem_comap {f : M →ₗ[R] M₂} {p : submodule R M₂} : x ∈ comap f p ↔ f x ∈ p := iff.rfl lemma comap_id : comap linear_map.id p = p := submodule.coe_injective rfl lemma comap_comp (f : M →ₗ[R] M₂) (g : M₂ →ₗ[R] M₃) (p : submodule R M₃) : comap (g.comp f) p = comap f (comap g p) := rfl lemma comap_mono {f : M →ₗ[R] M₂} {q q' : submodule R M₂} : q ≤ q' → comap f q ≤ comap f q' := preimage_mono lemma map_le_iff_le_comap {f : M →ₗ[R] M₂} {p : submodule R M} {q : submodule R M₂} : map f p ≤ q ↔ p ≤ comap f q := image_subset_iff lemma gc_map_comap (f : M →ₗ[R] M₂) : galois_connection (map f) (comap f) | p q := map_le_iff_le_comap @[simp] lemma map_bot (f : M →ₗ[R] M₂) : map f ⊥ = ⊥ := (gc_map_comap f).l_bot @[simp] lemma map_sup (f : M →ₗ[R] M₂) : map f (p ⊔ p') = map f p ⊔ map f p' := (gc_map_comap f).l_sup @[simp] lemma map_supr {ι : Sort*} (f : M →ₗ[R] M₂) (p : ι → submodule R M) : map f (⨆i, p i) = (⨆i, map f (p i)) := (gc_map_comap f).l_supr @[simp] lemma comap_top (f : M →ₗ[R] M₂) : comap f ⊤ = ⊤ := rfl @[simp] lemma comap_inf (f : M →ₗ[R] M₂) : comap f (q ⊓ q') = comap f q ⊓ comap f q' := rfl @[simp] lemma comap_infi {ι : Sort*} (f : M →ₗ[R] M₂) (p : ι → submodule R M₂) : comap f (⨅i, p i) = (⨅i, comap f (p i)) := (gc_map_comap f).u_infi @[simp] lemma comap_zero : comap (0 : M →ₗ[R] M₂) q = ⊤ := ext $ by simp lemma map_comap_le (f : M →ₗ[R] M₂) (q : submodule R M₂) : map f (comap f q) ≤ q := (gc_map_comap f).l_u_le _ lemma le_comap_map (f : M →ₗ[R] M₂) (p : submodule R M) : p ≤ comap f (map f p) := (gc_map_comap f).le_u_l _ --TODO(Mario): is there a way to prove this from order properties? lemma map_inf_eq_map_inf_comap {f : M →ₗ[R] M₂} {p : submodule R M} {p' : submodule R M₂} : map f p ⊓ p' = map f (p ⊓ comap f p') := le_antisymm (by rintro _ ⟨⟨x, h₁, rfl⟩, h₂⟩; exact ⟨_, ⟨h₁, h₂⟩, rfl⟩) (le_inf (map_mono inf_le_left) (map_le_iff_le_comap.2 inf_le_right)) lemma map_comap_subtype : map p.subtype (comap p.subtype p') = p ⊓ p' := ext $ λ x, ⟨by rintro ⟨⟨_, h₁⟩, h₂, rfl⟩; exact ⟨h₁, h₂⟩, λ ⟨h₁, h₂⟩, ⟨⟨_, h₁⟩, h₂, rfl⟩⟩ lemma eq_zero_of_bot_submodule : ∀(b : (⊥ : submodule R M)), b = 0 | ⟨b', hb⟩ := subtype.eq $ show b' = 0, from (mem_bot R).1 hb section variables (R) /-- The span of a set `s ⊆ M` is the smallest submodule of M that contains `s`. -/ def span (s : set M) : submodule R M := Inf {p | s ⊆ p} end variables {s t : set M} lemma mem_span : x ∈ span R s ↔ ∀ p : submodule R M, s ⊆ p → x ∈ p := mem_bInter_iff lemma subset_span : s ⊆ span R s := λ x h, mem_span.2 $ λ p hp, hp h lemma span_le {p} : span R s ≤ p ↔ s ⊆ p := ⟨subset.trans subset_span, λ ss x h, mem_span.1 h _ ss⟩ lemma span_mono (h : s ⊆ t) : span R s ≤ span R t := span_le.2 $ subset.trans h subset_span lemma span_eq_of_le (h₁ : s ⊆ p) (h₂ : p ≤ span R s) : span R s = p := le_antisymm (span_le.2 h₁) h₂ @[simp] lemma span_eq : span R (p : set M) = p := span_eq_of_le _ (subset.refl _) subset_span /-- An induction principle for span membership. If `p` holds for 0 and all elements of `s`, and is preserved under addition and scalar multiplication, then `p` holds for all elements of the span of `s`. -/ @[elab_as_eliminator] lemma span_induction {p : M → Prop} (h : x ∈ span R s) (Hs : ∀ x ∈ s, p x) (H0 : p 0) (H1 : ∀ x y, p x → p y → p (x + y)) (H2 : ∀ (a:R) x, p x → p (a • x)) : p x := (@span_le _ _ _ _ _ _ ⟨p, H0, H1, H2⟩).2 Hs h section variables (R M) /-- `span` forms a Galois insertion with the coercion from submodule to set. -/ protected def gi : galois_insertion (@span R M _ _ _) coe := { choice := λ s _, span R s, gc := λ s t, span_le, le_l_u := λ s, subset_span, choice_eq := λ s h, rfl } end @[simp] lemma span_empty : span R (∅ : set M) = ⊥ := (submodule.gi R M).gc.l_bot @[simp] lemma span_univ : span R (univ : set M) = ⊤ := eq_top_iff.2 $ le_def.2 $ subset_span lemma span_union (s t : set M) : span R (s ∪ t) = span R s ⊔ span R t := (submodule.gi R M).gc.l_sup lemma span_Union {ι} (s : ι → set M) : span R (⋃ i, s i) = ⨆ i, span R (s i) := (submodule.gi R M).gc.l_supr @[simp] theorem coe_supr_of_directed {ι} [hι : nonempty ι] (S : ι → submodule R M) (H : directed (≤) S) : ((supr S : submodule R M) : set M) = ⋃ i, S i := begin refine subset.antisymm _ (Union_subset $ le_supr S), suffices : (span R (⋃ i, (S i : set M)) : set M) ⊆ ⋃ (i : ι), ↑(S i), by simpa only [span_Union, span_eq] using this, refine (λ x hx, span_induction hx (λ _, id) _ _ _); simp only [mem_Union, exists_imp_distrib], { exact hι.elim (λ i, ⟨i, (S i).zero_mem⟩) }, { intros x y i hi j hj, rcases H i j with ⟨k, ik, jk⟩, exact ⟨k, add_mem _ (ik hi) (jk hj)⟩ }, { exact λ a x i hi, ⟨i, smul_mem _ a hi⟩ }, end 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 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 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 @[simp] theorem mem_supr_of_directed {ι} [nonempty ι] (S : ι → submodule R M) (H : directed (≤) S) {x} : x ∈ supr S ↔ ∃ i, x ∈ S i := by { rw [← mem_coe, coe_supr_of_directed S H, mem_Union], refl } theorem mem_Sup_of_directed {s : set (submodule R M)} {z} (hs : s.nonempty) (hdir : directed_on (≤) s) : z ∈ Sup s ↔ ∃ y ∈ s, z ∈ y := begin haveI : nonempty s := hs.to_subtype, simp only [Sup_eq_supr', mem_supr_of_directed _ hdir.directed_coe, set_coe.exists, subtype.coe_mk] end section variables {p p'} lemma mem_sup : x ∈ p ⊔ p' ↔ ∃ (y ∈ p) (z ∈ p'), y + z = x := ⟨λ h, begin rw [← span_eq p, ← span_eq p', ← span_union] at h, apply span_induction h, { rintro y (h | h), { exact ⟨y, h, 0, by simp, by simp⟩ }, { exact ⟨0, by simp, y, h, by simp⟩ } }, { exact ⟨0, by simp, 0, by simp⟩ }, { rintro _ _ ⟨y₁, hy₁, z₁, hz₁, rfl⟩ ⟨y₂, hy₂, z₂, hz₂, rfl⟩, exact ⟨_, add_mem _ hy₁ hy₂, _, add_mem _ hz₁ hz₂, by simp [add_assoc]; cc⟩ }, { rintro a _ ⟨y, hy, z, hz, rfl⟩, exact ⟨_, smul_mem _ a hy, _, smul_mem _ a hz, by simp [smul_add]⟩ } end, by rintro ⟨y, hy, z, hz, rfl⟩; exact add_mem _ ((le_sup_left : p ≤ p ⊔ p') hy) ((le_sup_right : p' ≤ p ⊔ p') hz)⟩ lemma mem_sup' : x ∈ p ⊔ p' ↔ ∃ (y : p) (z : p'), (y:M) + z = x := mem_sup.trans $ by simp only [submodule.exists, coe_mk] end lemma mem_span_singleton_self (x : M) : x ∈ span R ({x} : set M) := subset_span rfl lemma nontrivial_span_singleton {x : M} (h : x ≠ 0) : nontrivial (submodule.span R ({x} : set M)) := ⟨begin use [0, x, submodule.mem_span_singleton_self x], intros H, rw [eq_comm, submodule.mk_eq_zero] at H, exact h H end⟩ lemma mem_span_singleton {y : M} : x ∈ span R ({y} : set M) ↔ ∃ a:R, a • y = x := ⟨λ h, begin apply span_induction h, { rintro y (rfl|⟨⟨⟩⟩), exact ⟨1, by simp⟩ }, { exact ⟨0, by simp⟩ }, { rintro _ _ ⟨a, rfl⟩ ⟨b, rfl⟩, exact ⟨a + b, by simp [add_smul]⟩ }, { rintro a _ ⟨b, rfl⟩, exact ⟨a * b, by simp [smul_smul]⟩ } end, by rintro ⟨a, y, rfl⟩; exact smul_mem _ _ (subset_span $ by simp)⟩ lemma span_singleton_eq_range (y : M) : (span R ({y} : set M) : set M) = range ((• y) : R → M) := set.ext $ λ x, mem_span_singleton lemma disjoint_span_singleton {K E : Type*} [division_ring K] [add_comm_group E] [module K E] {s : submodule K E} {x : E} : disjoint s (span K {x}) ↔ (x ∈ s → x = 0) := begin refine disjoint_def.trans ⟨λ H hx, H x hx $ subset_span $ mem_singleton x, _⟩, assume H y hy hyx, obtain ⟨c, hc⟩ := mem_span_singleton.1 hyx, subst y, classical, by_cases hc : c = 0, by simp only [hc, zero_smul], rw [s.smul_mem_iff hc] at hy, rw [H hy, smul_zero] end lemma mem_span_insert {y} : x ∈ span R (insert y s) ↔ ∃ (a:R) (z ∈ span R s), x = a • y + z := begin simp only [← union_singleton, span_union, mem_sup, mem_span_singleton, exists_prop, exists_exists_eq_and], rw [exists_comm], simp only [eq_comm, add_comm, exists_and_distrib_left] end lemma span_insert_eq_span (h : x ∈ span R s) : span R (insert x s) = span R s := span_eq_of_le _ (set.insert_subset.mpr ⟨h, subset_span⟩) (span_mono $ subset_insert _ _) lemma span_span : span R (span R s : set M) = span R s := span_eq _ lemma span_eq_bot : span R (s : set M) = ⊥ ↔ ∀ x ∈ s, (x:M) = 0 := eq_bot_iff.trans ⟨ λ H x h, (mem_bot R).1 $ H $ subset_span h, λ H, span_le.2 (λ x h, (mem_bot R).2 $ H x h)⟩ @[simp] lemma span_singleton_eq_bot : span R ({x} : set M) = ⊥ ↔ x = 0 := span_eq_bot.trans $ by simp @[simp] lemma span_zero : span R (0 : set M) = ⊥ := by rw [←singleton_zero, span_singleton_eq_bot] @[simp] lemma span_image (f : M →ₗ[R] M₂) : span R (f '' s) = map f (span R s) := span_eq_of_le _ (image_subset _ subset_span) $ map_le_iff_le_comap.2 $ span_le.2 $ image_subset_iff.1 subset_span lemma linear_eq_on (s : set M) {f g : M →ₗ[R] M₂} (H : ∀x∈s, f x = g x) {x} (h : x ∈ span R s) : f x = g x := by apply span_induction h H; simp {contextual := tt} lemma linear_map.ext_on {v : ι → M} {f g : M →ₗ[R] M₂} (hv : span R (range v) = ⊤) (h : ∀i, f (v i) = g (v i)) : f = g := begin apply linear_map.ext (λ x, linear_eq_on (range v) _ (eq_top_iff'.1 hv _)), exact (λ y hy, exists.elim (set.mem_range.1 hy) (λ i hi, by rw ←hi; exact h i)) end lemma supr_eq_span {ι : Sort w} (p : ι → submodule R M) : (⨆ (i : ι), p i) = submodule.span R (⋃ (i : ι), ↑(p i)) := le_antisymm (supr_le $ assume i, subset.trans (assume m hm, set.mem_Union.mpr ⟨i, hm⟩) subset_span) (span_le.mpr $ Union_subset_iff.mpr $ assume i m hm, mem_supr_of_mem i hm) lemma span_singleton_le_iff_mem (m : M) (p : submodule R M) : span R {m} ≤ p ↔ m ∈ p := by rw [span_le, singleton_subset_iff, mem_coe] lemma lt_add_iff_not_mem {I : submodule R M} {a : M} : I < I + span R {a} ↔ a ∉ I := begin split, { intro h, by_contra akey, have h1 : I + span R {a} ≤ I, { simp only [add_eq_sup, sup_le_iff], split, { exact le_refl I, }, { exact (span_singleton_le_iff_mem a I).mpr akey, } }, have h2 := gt_of_ge_of_gt h1 h, exact lt_irrefl I h2, }, { intro h, apply lt_iff_le_and_exists.mpr, split, simp only [add_eq_sup, le_sup_left], use a, split, swap, { assumption, }, { have : span R {a} ≤ I + span R{a} := le_sup_right, exact this (mem_span_singleton_self a), } }, end lemma mem_supr {ι : Sort w} (p : ι → submodule R M) {m : M} : (m ∈ ⨆ i, p i) ↔ (∀ N, (∀ i, p i ≤ N) → m ∈ N) := begin rw [← span_singleton_le_iff_mem, le_supr_iff], simp only [span_singleton_le_iff_mem], end /-- The product of two submodules is a submodule. -/ def prod : submodule R (M × M₂) := { carrier := set.prod p q, smul_mem' := by rintro a ⟨x, y⟩ ⟨hx, hy⟩; exact ⟨smul_mem _ a hx, smul_mem _ a hy⟩, .. p.to_add_submonoid.prod q.to_add_submonoid } @[simp] lemma prod_coe : (prod p q : set (M × M₂)) = set.prod p q := rfl @[simp] lemma mem_prod {p : submodule R M} {q : submodule R M₂} {x : M × M₂} : x ∈ prod p q ↔ x.1 ∈ p ∧ x.2 ∈ q := set.mem_prod lemma span_prod_le (s : set M) (t : set M₂) : span R (set.prod s t) ≤ prod (span R s) (span R t) := span_le.2 $ set.prod_mono subset_span subset_span @[simp] lemma prod_top : (prod ⊤ ⊤ : submodule R (M × M₂)) = ⊤ := by ext; simp @[simp] lemma prod_bot : (prod ⊥ ⊥ : submodule R (M × M₂)) = ⊥ := by ext ⟨x, y⟩; simp [prod.zero_eq_mk] lemma prod_mono {p p' : submodule R M} {q q' : submodule R M₂} : p ≤ p' → q ≤ q' → prod p q ≤ prod p' q' := prod_mono @[simp] lemma prod_inf_prod : prod p q ⊓ prod p' q' = prod (p ⊓ p') (q ⊓ q') := coe_injective set.prod_inter_prod @[simp] lemma prod_sup_prod : prod p q ⊔ prod p' q' = prod (p ⊔ p') (q ⊔ q') := begin refine le_antisymm (sup_le (prod_mono le_sup_left le_sup_left) (prod_mono le_sup_right le_sup_right)) _, simp [le_def'], intros xx yy hxx hyy, rcases mem_sup.1 hxx with ⟨x, hx, x', hx', rfl⟩, rcases mem_sup.1 hyy with ⟨y, hy, y', hy', rfl⟩, refine mem_sup.2 ⟨(x, y), ⟨hx, hy⟩, (x', y'), ⟨hx', hy'⟩, rfl⟩ end end add_comm_monoid variables [ring R] [add_comm_group M] [add_comm_group M₂] [add_comm_group M₃] variables [semimodule R M] [semimodule R M₂] [semimodule R M₃] variables (p p' : submodule R M) (q q' : submodule R M₂) variables {r : R} {x y : M} open set lemma mem_span_insert' {y} {s : set M} : x ∈ span R (insert y s) ↔ ∃(a:R), x + a • y ∈ span R s := begin rw mem_span_insert, split, { rintro ⟨a, z, hz, rfl⟩, exact ⟨-a, by simp [hz, add_assoc]⟩ }, { rintro ⟨a, h⟩, exact ⟨-a, _, h, by simp [add_comm, add_left_comm]⟩ } end -- TODO(Mario): Factor through add_subgroup /-- The equivalence relation associated to a submodule `p`, defined by `x ≈ y` iff `y - x ∈ p`. -/ def quotient_rel : setoid M := ⟨λ x y, x - y ∈ p, λ x, by simp, λ x y h, by simpa using neg_mem _ h, λ x y z h₁ h₂, by simpa [sub_eq_add_neg, add_left_comm, add_assoc] using add_mem _ h₁ h₂⟩ /-- The quotient of a module `M` by a submodule `p ⊆ M`. -/ def quotient : Type* := quotient (quotient_rel p) namespace quotient /-- Map associating to an element of `M` the corresponding element of `M/p`, when `p` is a submodule of `M`. -/ def mk {p : submodule R M} : M → quotient p := quotient.mk' @[simp] theorem mk_eq_mk {p : submodule R M} (x : M) : (quotient.mk x : quotient p) = mk x := rfl @[simp] theorem mk'_eq_mk {p : submodule R M} (x : M) : (quotient.mk' x : quotient p) = mk x := rfl @[simp] theorem quot_mk_eq_mk {p : submodule R M} (x : M) : (quot.mk _ x : quotient p) = mk x := rfl protected theorem eq {x y : M} : (mk x : quotient p) = mk y ↔ x - y ∈ p := quotient.eq' instance : has_zero (quotient p) := ⟨mk 0⟩ instance : inhabited (quotient p) := ⟨0⟩ @[simp] theorem mk_zero : mk 0 = (0 : quotient p) := rfl @[simp] theorem mk_eq_zero : (mk x : quotient p) = 0 ↔ x ∈ p := by simpa using (quotient.eq p : mk x = 0 ↔ _) instance : has_add (quotient p) := ⟨λ a b, quotient.lift_on₂' a b (λ a b, mk (a + b)) $ λ a₁ a₂ b₁ b₂ h₁ h₂, (quotient.eq p).2 $ by simpa [sub_eq_add_neg, add_left_comm, add_comm] using add_mem p h₁ h₂⟩ @[simp] theorem mk_add : (mk (x + y) : quotient p) = mk x + mk y := rfl instance : has_neg (quotient p) := ⟨λ a, quotient.lift_on' a (λ a, mk (-a)) $ λ a b h, (quotient.eq p).2 $ by simpa using neg_mem p h⟩ @[simp] theorem mk_neg : (mk (-x) : quotient p) = -mk x := rfl instance : add_comm_group (quotient p) := by refine {zero := 0, add := (+), neg := has_neg.neg, ..}; repeat {rintro ⟨⟩}; simp [-mk_zero, (mk_zero p).symm, -mk_add, (mk_add p).symm, -mk_neg, (mk_neg p).symm]; cc instance : has_scalar R (quotient p) := ⟨λ a x, quotient.lift_on' x (λ x, mk (a • x)) $ λ x y h, (quotient.eq p).2 $ by simpa [smul_sub] using smul_mem p a h⟩ @[simp] theorem mk_smul : (mk (r • x) : quotient p) = r • mk x := rfl instance : semimodule R (quotient p) := semimodule.of_core $ by refine {smul := (•), ..}; repeat {rintro ⟨⟩ <|> intro}; simp [smul_add, add_smul, smul_smul, -mk_add, (mk_add p).symm, -mk_smul, (mk_smul p).symm] lemma mk_surjective : function.surjective (@mk _ _ _ _ _ p) := by { rintros ⟨x⟩, exact ⟨x, rfl⟩ } lemma nontrivial_of_lt_top (h : p < ⊤) : nontrivial (p.quotient) := begin obtain ⟨x, _, not_mem_s⟩ := exists_of_lt h, refine ⟨⟨mk x, 0, _⟩⟩, simpa using not_mem_s end end quotient lemma quot_hom_ext ⦃f g : quotient p →ₗ[R] M₂⦄ (h : ∀ x, f (quotient.mk x) = g (quotient.mk x)) : f = g := linear_map.ext $ λ x, quotient.induction_on' x h end submodule namespace submodule variables [field K] variables [add_comm_group V] [vector_space K V] variables [add_comm_group V₂] [vector_space K V₂] lemma comap_smul (f : V →ₗ[K] V₂) (p : submodule K V₂) (a : K) (h : a ≠ 0) : p.comap (a • f) = p.comap f := by ext b; simp only [submodule.mem_comap, p.smul_mem_iff h, linear_map.smul_apply] lemma map_smul (f : V →ₗ[K] V₂) (p : submodule K V) (a : K) (h : a ≠ 0) : p.map (a • f) = p.map f := le_antisymm begin rw [map_le_iff_le_comap, comap_smul f _ a h, ← map_le_iff_le_comap], exact le_refl _ end begin rw [map_le_iff_le_comap, ← comap_smul f _ a h, ← map_le_iff_le_comap], exact le_refl _ end lemma comap_smul' (f : V →ₗ[K] V₂) (p : submodule K V₂) (a : K) : p.comap (a • f) = (⨅ h : a ≠ 0, p.comap f) := by classical; by_cases a = 0; simp [h, comap_smul] lemma map_smul' (f : V →ₗ[K] V₂) (p : submodule K V) (a : K) : p.map (a • f) = (⨆ h : a ≠ 0, p.map f) := by classical; by_cases a = 0; simp [h, map_smul] end submodule /-! ### Properties of linear maps -/ namespace linear_map section add_comm_monoid variables [semiring R] [add_comm_monoid M] [add_comm_monoid M₂] [add_comm_monoid M₃] variables [semimodule R M] [semimodule R M₂] [semimodule R M₃] include R open submodule @[simp] lemma finsupp_sum {γ} [has_zero γ] (f : M →ₗ[R] M₂) {t : ι →₀ γ} {g : ι → γ → M} : f (t.sum g) = t.sum (λi d, f (g i d)) := f.map_sum theorem map_cod_restrict (p : submodule R M) (f : M₂ →ₗ[R] M) (h p') : submodule.map (cod_restrict p f h) p' = comap p.subtype (p'.map f) := submodule.ext $ λ ⟨x, hx⟩, by simp [subtype.ext_iff_val] theorem comap_cod_restrict (p : submodule R M) (f : M₂ →ₗ[R] M) (hf p') : submodule.comap (cod_restrict p f hf) p' = submodule.comap f (map p.subtype p') := submodule.ext $ λ x, ⟨λ h, ⟨⟨_, hf x⟩, h, rfl⟩, by rintro ⟨⟨_, _⟩, h, ⟨⟩⟩; exact h⟩ /-- The range of a linear map `f : M → M₂` is a submodule of `M₂`. -/ def range (f : M →ₗ[R] M₂) : submodule R M₂ := map f ⊤ theorem range_coe (f : M →ₗ[R] M₂) : (range f : set M₂) = set.range f := set.image_univ @[simp] theorem mem_range {f : M →ₗ[R] M₂} : ∀ {x}, x ∈ range f ↔ ∃ y, f y = x := set.ext_iff.1 (range_coe f) theorem mem_range_self (f : M →ₗ[R] M₂) (x : M) : f x ∈ f.range := mem_range.2 ⟨x, rfl⟩ @[simp] theorem range_id : range (linear_map.id : M →ₗ[R] M) = ⊤ := map_id _ theorem range_comp (f : M →ₗ[R] M₂) (g : M₂ →ₗ[R] M₃) : range (g.comp f) = map g (range f) := map_comp _ _ _ theorem range_comp_le_range (f : M →ₗ[R] M₂) (g : M₂ →ₗ[R] M₃) : range (g.comp f) ≤ range g := by rw range_comp; exact map_mono le_top theorem range_eq_top {f : M →ₗ[R] M₂} : range f = ⊤ ↔ surjective f := by rw [submodule.ext'_iff, range_coe, top_coe, set.range_iff_surjective] lemma range_le_iff_comap {f : M →ₗ[R] M₂} {p : submodule R M₂} : range f ≤ p ↔ comap f p = ⊤ := by rw [range, map_le_iff_le_comap, eq_top_iff] lemma map_le_range {f : M →ₗ[R] M₂} {p : submodule R M} : map f p ≤ range f := map_mono le_top lemma range_coprod (f : M →ₗ[R] M₃) (g : M₂ →ₗ[R] M₃) : (f.coprod g).range = f.range ⊔ g.range := submodule.ext $ λ x, by simp [mem_sup] lemma sup_range_inl_inr : (inl R M M₂).range ⊔ (inr R M M₂).range = ⊤ := begin refine eq_top_iff'.2 (λ x, mem_sup.2 _), rcases x with ⟨x₁, x₂⟩ , have h₁ : prod.mk x₁ (0 : M₂) ∈ (inl R M M₂).range, by simp, have h₂ : prod.mk (0 : M) x₂ ∈ (inr R M M₂).range, by simp, use [⟨x₁, 0⟩, h₁, ⟨0, x₂⟩, h₂], simp end /-- Restrict the codomain of a linear map `f` to `f.range`. -/ @[reducible] def range_restrict (f : M →ₗ[R] M₂) : M →ₗ[R] f.range := f.cod_restrict f.range f.mem_range_self section variables (R) (M) /-- Given an element `x` of a module `M` over `R`, the natural map from `R` to scalar multiples of `x`.-/ def to_span_singleton (x : M) : R →ₗ[R] M := linear_map.id.smul_right x /-- The range of `to_span_singleton x` is the span of `x`.-/ lemma span_singleton_eq_range (x : M) : span R {x} = (to_span_singleton R M x).range := submodule.ext $ λ y, by {refine iff.trans _ mem_range.symm, exact mem_span_singleton } lemma to_span_singleton_one (x : M) : to_span_singleton R M x 1 = x := one_smul _ _ end /-- The kernel of a linear map `f : M → M₂` is defined to be `comap f ⊥`. This is equivalent to the set of `x : M` such that `f x = 0`. The kernel is a submodule of `M`. -/ def ker (f : M →ₗ[R] M₂) : submodule R M := comap f ⊥ @[simp] theorem mem_ker {f : M →ₗ[R] M₂} {y} : y ∈ ker f ↔ f y = 0 := mem_bot R @[simp] theorem ker_id : ker (linear_map.id : M →ₗ[R] M) = ⊥ := rfl @[simp] theorem map_coe_ker (f : M →ₗ[R] M₂) (x : ker f) : f x = 0 := mem_ker.1 x.2 lemma comp_ker_subtype (f : M →ₗ[R] M₂) : f.comp f.ker.subtype = 0 := linear_map.ext $ λ x, suffices f x = 0, by simp [this], mem_ker.1 x.2 theorem ker_comp (f : M →ₗ[R] M₂) (g : M₂ →ₗ[R] M₃) : ker (g.comp f) = comap f (ker g) := rfl theorem ker_le_ker_comp (f : M →ₗ[R] M₂) (g : M₂ →ₗ[R] M₃) : ker f ≤ ker (g.comp f) := by rw ker_comp; exact comap_mono bot_le theorem disjoint_ker {f : M →ₗ[R] M₂} {p : submodule R M} : disjoint p (ker f) ↔ ∀ x ∈ p, f x = 0 → x = 0 := by simp [disjoint_def] lemma disjoint_inl_inr : disjoint (inl R M M₂).range (inr R M M₂).range := by simp [disjoint_def, @eq_comm M 0, @eq_comm M₂ 0] {contextual := tt}; intros; refl theorem ker_eq_bot' {f : M →ₗ[R] M₂} : ker f = ⊥ ↔ (∀ m, f m = 0 → m = 0) := have h : (∀ m ∈ (⊤ : submodule R M), f m = 0 → m = 0) ↔ (∀ m, f m = 0 → m = 0), from ⟨λ h m, h m mem_top, λ h m _, h m⟩, by simpa [h, disjoint] using @disjoint_ker _ _ _ _ _ _ _ _ f ⊤ lemma le_ker_iff_map {f : M →ₗ[R] M₂} {p : submodule R M} : p ≤ ker f ↔ map f p = ⊥ := by rw [ker, eq_bot_iff, map_le_iff_le_comap] lemma ker_cod_restrict (p : submodule R M) (f : M₂ →ₗ[R] M) (hf) : ker (cod_restrict p f hf) = ker f := by rw [ker, comap_cod_restrict, map_bot]; refl lemma range_cod_restrict (p : submodule R M) (f : M₂ →ₗ[R] M) (hf) : range (cod_restrict p f hf) = comap p.subtype f.range := map_cod_restrict _ _ _ _ lemma ker_restrict {p : submodule R M} {f : M →ₗ[R] M} (hf : ∀ x : M, x ∈ p → f x ∈ p) : ker (f.restrict hf) = (f.dom_restrict p).ker := by rw [restrict_eq_cod_restrict_dom_restrict, ker_cod_restrict] lemma map_comap_eq (f : M →ₗ[R] M₂) (q : submodule R M₂) : map f (comap f q) = range f ⊓ q := le_antisymm (le_inf (map_mono le_top) (map_comap_le _ _)) $ by rintro _ ⟨⟨x, _, rfl⟩, hx⟩; exact ⟨x, hx, rfl⟩ lemma map_comap_eq_self {f : M →ₗ[R] M₂} {q : submodule R M₂} (h : q ≤ range f) : map f (comap f q) = q := by rwa [map_comap_eq, inf_eq_right] @[simp] theorem ker_zero : ker (0 : M →ₗ[R] M₂) = ⊤ := eq_top_iff'.2 $ λ x, by simp @[simp] theorem range_zero : range (0 : M →ₗ[R] M₂) = ⊥ := submodule.map_zero _ theorem ker_eq_top {f : M →ₗ[R] M₂} : ker f = ⊤ ↔ f = 0 := ⟨λ h, ext $ λ x, mem_ker.1 $ h.symm ▸ trivial, λ h, h.symm ▸ ker_zero⟩ lemma range_le_bot_iff (f : M →ₗ[R] M₂) : range f ≤ ⊥ ↔ f = 0 := by rw [range_le_iff_comap]; exact ker_eq_top lemma range_le_ker_iff {f : M →ₗ[R] M₂} {g : M₂ →ₗ[R] M₃} : range f ≤ ker g ↔ g.comp f = 0 := ⟨λ h, ker_eq_top.1 $ eq_top_iff'.2 $ λ x, h $ mem_map_of_mem trivial, λ h x hx, mem_ker.2 $ exists.elim hx $ λ y ⟨_, hy⟩, by rw [←hy, ←comp_apply, h, zero_apply]⟩ theorem comap_le_comap_iff {f : M →ₗ[R] M₂} (hf : range f = ⊤) {p p'} : comap f p ≤ comap f p' ↔ p ≤ p' := ⟨λ H x hx, by rcases range_eq_top.1 hf x with ⟨y, hy, rfl⟩; exact H hx, comap_mono⟩ theorem comap_injective {f : M →ₗ[R] M₂} (hf : range f = ⊤) : injective (comap f) := λ p p' h, le_antisymm ((comap_le_comap_iff hf).1 (le_of_eq h)) ((comap_le_comap_iff hf).1 (ge_of_eq h)) theorem map_coprod_prod (f : M →ₗ[R] M₃) (g : M₂ →ₗ[R] M₃) (p : submodule R M) (q : submodule R M₂) : map (coprod f g) (p.prod q) = map f p ⊔ map g q := begin refine le_antisymm _ (sup_le (map_le_iff_le_comap.2 _) (map_le_iff_le_comap.2 _)), { rw le_def', rintro _ ⟨x, ⟨h₁, h₂⟩, rfl⟩, exact mem_sup.2 ⟨_, ⟨_, h₁, rfl⟩, _, ⟨_, h₂, rfl⟩, rfl⟩ }, { exact λ x hx, ⟨(x, 0), by simp [hx]⟩ }, { exact λ x hx, ⟨(0, x), by simp [hx]⟩ } end theorem comap_prod_prod (f : M →ₗ[R] M₂) (g : M →ₗ[R] M₃) (p : submodule R M₂) (q : submodule R M₃) : comap (prod f g) (p.prod q) = comap f p ⊓ comap g q := submodule.ext $ λ x, iff.rfl theorem prod_eq_inf_comap (p : submodule R M) (q : submodule R M₂) : p.prod q = p.comap (linear_map.fst R M M₂) ⊓ q.comap (linear_map.snd R M M₂) := submodule.ext $ λ x, iff.rfl theorem prod_eq_sup_map (p : submodule R M) (q : submodule R M₂) : p.prod q = p.map (linear_map.inl R M M₂) ⊔ q.map (linear_map.inr R M M₂) := by rw [← map_coprod_prod, coprod_inl_inr, map_id] lemma span_inl_union_inr {s : set M} {t : set M₂} : span R (inl R M M₂ '' s ∪ inr R M M₂ '' t) = (span R s).prod (span R t) := by rw [span_union, prod_eq_sup_map, ← span_image, ← span_image]; refl @[simp] lemma ker_prod (f : M →ₗ[R] M₂) (g : M →ₗ[R] M₃) : ker (prod f g) = ker f ⊓ ker g := by rw [ker, ← prod_bot, comap_prod_prod]; refl lemma range_prod_le (f : M →ₗ[R] M₂) (g : M →ₗ[R] M₃) : range (prod f g) ≤ (range f).prod (range g) := begin simp only [le_def', prod_apply, mem_range, mem_coe, mem_prod, exists_imp_distrib], rintro _ x rfl, exact ⟨⟨x, rfl⟩, ⟨x, rfl⟩⟩ end theorem ker_eq_bot_of_injective {f : M →ₗ[R] M₂} (hf : injective f) : ker f = ⊥ := begin have : disjoint ⊤ f.ker, by { rw [disjoint_ker, ← map_zero f], exact λ x hx H, hf H }, simpa [disjoint] end end add_comm_monoid section add_comm_group variables [semiring R] [add_comm_group M] [add_comm_group M₂] [add_comm_group M₃] variables [semimodule R M] [semimodule R M₂] [semimodule R M₃] include R open submodule lemma comap_map_eq (f : M →ₗ[R] M₂) (p : submodule R M) : comap f (map f p) = p ⊔ ker f := begin refine le_antisymm _ (sup_le (le_comap_map _ _) (comap_mono bot_le)), rintro x ⟨y, hy, e⟩, exact mem_sup.2 ⟨y, hy, x - y, by simpa using sub_eq_zero.2 e.symm, by simp⟩ end lemma comap_map_eq_self {f : M →ₗ[R] M₂} {p : submodule R M} (h : ker f ≤ p) : comap f (map f p) = p := by rw [comap_map_eq, sup_of_le_left h] theorem map_le_map_iff (f : M →ₗ[R] M₂) {p p'} : map f p ≤ map f p' ↔ p ≤ p' ⊔ ker f := by rw [map_le_iff_le_comap, comap_map_eq] theorem map_le_map_iff' {f : M →ₗ[R] M₂} (hf : ker f = ⊥) {p p'} : map f p ≤ map f p' ↔ p ≤ p' := by rw [map_le_map_iff, hf, sup_bot_eq] theorem map_injective {f : M →ₗ[R] M₂} (hf : ker f = ⊥) : injective (map f) := λ p p' h, le_antisymm ((map_le_map_iff' hf).1 (le_of_eq h)) ((map_le_map_iff' hf).1 (ge_of_eq h)) theorem map_eq_top_iff {f : M →ₗ[R] M₂} (hf : range f = ⊤) {p : submodule R M} : p.map f = ⊤ ↔ p ⊔ f.ker = ⊤ := by simp_rw [← top_le_iff, ← hf, range, map_le_map_iff] end add_comm_group section ring variables [ring R] [add_comm_group M] [add_comm_group M₂] [add_comm_group M₃] variables [semimodule R M] [semimodule R M₂] [semimodule R M₃] include R open submodule theorem sub_mem_ker_iff {f : M →ₗ[R] M₂} {x y} : x - y ∈ f.ker ↔ f x = f y := by rw [mem_ker, map_sub, sub_eq_zero] theorem disjoint_ker' {f : M →ₗ[R] M₂} {p : submodule R M} : disjoint p (ker f) ↔ ∀ x y ∈ p, f x = f y → x = y := disjoint_ker.trans ⟨λ H x y hx hy h, eq_of_sub_eq_zero $ H _ (sub_mem _ hx hy) (by simp [h]), λ H x h₁ h₂, H x 0 h₁ (zero_mem _) (by simpa using h₂)⟩ theorem inj_of_disjoint_ker {f : M →ₗ[R] M₂} {p : submodule R M} {s : set M} (h : s ⊆ p) (hd : disjoint p (ker f)) : ∀ x y ∈ s, f x = f y → x = y := λ x y hx hy, disjoint_ker'.1 hd _ _ (h hx) (h hy) theorem ker_eq_bot {f : M →ₗ[R] M₂} : ker f = ⊥ ↔ injective f := by simpa [disjoint] using @disjoint_ker' _ _ _ _ _ _ _ _ f ⊤ /-- If the union of the kernels `ker f` and `ker g` spans the domain, then the range of `prod f g` is equal to the product of `range f` and `range g`. -/ lemma range_prod_eq {f : M →ₗ[R] M₂} {g : M →ₗ[R] M₃} (h : ker f ⊔ ker g = ⊤) : range (prod f g) = (range f).prod (range g) := begin refine le_antisymm (f.range_prod_le g) _, simp only [le_def', prod_apply, mem_range, mem_coe, mem_prod, exists_imp_distrib, and_imp, prod.forall], rintros _ _ x rfl y rfl, simp only [prod.mk.inj_iff, ← sub_mem_ker_iff], have : y - x ∈ ker f ⊔ ker g, { simp only [h, mem_top] }, rcases mem_sup.1 this with ⟨x', hx', y', hy', H⟩, refine ⟨x' + x, _, _⟩, { rwa add_sub_cancel }, { rwa [← eq_sub_iff_add_eq.1 H, add_sub_add_right_eq_sub, ← neg_mem_iff, neg_sub, add_sub_cancel'] } end end ring section field variables [field K] variables [add_comm_group V] [vector_space K V] variables [add_comm_group V₂] [vector_space K V₂] lemma ker_smul (f : V →ₗ[K] V₂) (a : K) (h : a ≠ 0) : ker (a • f) = ker f := submodule.comap_smul f _ a h lemma ker_smul' (f : V →ₗ[K] V₂) (a : K) : ker (a • f) = ⨅(h : a ≠ 0), ker f := submodule.comap_smul' f _ a lemma range_smul (f : V →ₗ[K] V₂) (a : K) (h : a ≠ 0) : range (a • f) = range f := submodule.map_smul f _ a h lemma range_smul' (f : V →ₗ[K] V₂) (a : K) : range (a • f) = ⨆(h : a ≠ 0), range f := submodule.map_smul' f _ a end field end linear_map lemma submodule.sup_eq_range [semiring R] [add_comm_monoid M] [semimodule R M] (p q : submodule R M) : p ⊔ q = (p.subtype.coprod q.subtype).range := submodule.ext $ λ x, by simp [submodule.mem_sup, submodule.exists] namespace is_linear_map lemma is_linear_map_add [semiring R] [add_comm_monoid M] [semimodule R M] : is_linear_map R (λ (x : M × M), x.1 + x.2) := begin apply is_linear_map.mk, { intros x y, simp, cc }, { intros x y, simp [smul_add] } end lemma is_linear_map_sub {R M : Type*} [semiring R] [add_comm_group M] [semimodule R M]: is_linear_map R (λ (x : M × M), x.1 - x.2) := begin apply is_linear_map.mk, { intros x y, simp [add_comm, add_left_comm, sub_eq_add_neg] }, { intros x y, simp [smul_sub] } end end is_linear_map namespace submodule section add_comm_monoid variables {T : semiring R} [add_comm_monoid M] [add_comm_monoid M₂] [semimodule R M] [semimodule R M₂] variables (p p' : submodule R M) (q : submodule R M₂) include T open linear_map @[simp] theorem map_top (f : M →ₗ[R] M₂) : map f ⊤ = range f := rfl @[simp] theorem comap_bot (f : M →ₗ[R] M₂) : comap f ⊥ = ker f := rfl @[simp] theorem ker_subtype : p.subtype.ker = ⊥ := ker_eq_bot_of_injective $ λ x y, subtype.ext_val @[simp] theorem range_subtype : p.subtype.range = p := by simpa using map_comap_subtype p ⊤ lemma map_subtype_le (p' : submodule R p) : map p.subtype p' ≤ p := by simpa using (map_mono le_top : map p.subtype p' ≤ p.subtype.range) /-- Under the canonical linear map from a submodule `p` to the ambient space `M`, the image of the maximal submodule of `p` is just `p `. -/ @[simp] lemma map_subtype_top : map p.subtype (⊤ : submodule R p) = p := by simp @[simp] lemma comap_subtype_eq_top {p p' : submodule R M} : comap p.subtype p' = ⊤ ↔ p ≤ p' := eq_top_iff.trans $ map_le_iff_le_comap.symm.trans $ by rw [map_subtype_top] @[simp] lemma comap_subtype_self : comap p.subtype p = ⊤ := comap_subtype_eq_top.2 (le_refl _) @[simp] theorem ker_of_le (p p' : submodule R M) (h : p ≤ p') : (of_le h).ker = ⊥ := by rw [of_le, ker_cod_restrict, ker_subtype] lemma range_of_le (p q : submodule R M) (h : p ≤ q) : (of_le h).range = comap q.subtype p := by rw [← map_top, of_le, linear_map.map_cod_restrict, map_top, range_subtype] @[simp] theorem map_inl : p.map (inl R M M₂) = prod p ⊥ := by { ext ⟨x, y⟩, simp only [and.left_comm, eq_comm, mem_map, prod.mk.inj_iff, inl_apply, mem_bot, exists_eq_left', mem_prod] } @[simp] theorem map_inr : q.map (inr R M M₂) = prod ⊥ q := by ext ⟨x, y⟩; simp [and.left_comm, eq_comm] @[simp] theorem comap_fst : p.comap (fst R M M₂) = prod p ⊤ := by ext ⟨x, y⟩; simp @[simp] theorem comap_snd : q.comap (snd R M M₂) = prod ⊤ q := by ext ⟨x, y⟩; simp @[simp] theorem prod_comap_inl : (prod p q).comap (inl R M M₂) = p := by ext; simp @[simp] theorem prod_comap_inr : (prod p q).comap (inr R M M₂) = q := by ext; simp @[simp] theorem prod_map_fst : (prod p q).map (fst R M M₂) = p := by ext x; simp [(⟨0, zero_mem _⟩ : ∃ x, x ∈ q)] @[simp] theorem prod_map_snd : (prod p q).map (snd R M M₂) = q := by ext x; simp [(⟨0, zero_mem _⟩ : ∃ x, x ∈ p)] @[simp] theorem ker_inl : (inl R M M₂).ker = ⊥ := by rw [ker, ← prod_bot, prod_comap_inl] @[simp] theorem ker_inr : (inr R M M₂).ker = ⊥ := by rw [ker, ← prod_bot, prod_comap_inr] @[simp] theorem range_fst : (fst R M M₂).range = ⊤ := by rw [range, ← prod_top, prod_map_fst] @[simp] theorem range_snd : (snd R M M₂).range = ⊤ := by rw [range, ← prod_top, prod_map_snd] end add_comm_monoid section ring variables {T : ring R} [add_comm_group M] [add_comm_group M₂] [semimodule R M] [semimodule R M₂] variables (p p' : submodule R M) (q : submodule R M₂) include T open linear_map lemma disjoint_iff_comap_eq_bot {p q : submodule R M} : disjoint p q ↔ comap p.subtype q = ⊥ := by rw [eq_bot_iff, ← map_le_map_iff' p.ker_subtype, map_bot, map_comap_subtype, disjoint] /-- If `N ⊆ M` then submodules of `N` are the same as submodules of `M` contained in `N` -/ def map_subtype.rel_iso : submodule R p ≃o {p' : submodule R M // p' ≤ p} := { to_fun := λ p', ⟨map p.subtype p', map_subtype_le p _⟩, inv_fun := λ q, comap p.subtype q, left_inv := λ p', comap_map_eq_self $ by simp, right_inv := λ ⟨q, hq⟩, subtype.ext_val $ by simp [map_comap_subtype p, inf_of_le_right hq], map_rel_iff' := λ p₁ p₂, (map_le_map_iff' (ker_subtype p)).symm } /-- If `p ⊆ M` is a submodule, the ordering of submodules of `p` is embedded in the ordering of submodules of `M`. -/ def map_subtype.order_embedding : submodule R p ↪o submodule R M := (rel_iso.to_rel_embedding $ map_subtype.rel_iso p).trans (subtype.rel_embedding _ _) @[simp] lemma map_subtype_embedding_eq (p' : submodule R p) : map_subtype.order_embedding p p' = map p.subtype p' := rfl /-- The map from a module `M` to the quotient of `M` by a submodule `p` as a linear map. -/ def mkq : M →ₗ[R] p.quotient := ⟨quotient.mk, by simp, by simp⟩ @[simp] theorem mkq_apply (x : M) : p.mkq x = quotient.mk x := rfl /-- The map from the quotient of `M` by a submodule `p` to `M₂` induced by a linear map `f : M → M₂` vanishing on `p`, as a linear map. -/ def liftq (f : M →ₗ[R] M₂) (h : p ≤ f.ker) : p.quotient →ₗ[R] M₂ := ⟨λ x, _root_.quotient.lift_on' x f $ λ a b (ab : a - b ∈ p), eq_of_sub_eq_zero $ by simpa using h ab, by rintro ⟨x⟩ ⟨y⟩; exact f.map_add x y, by rintro a ⟨x⟩; exact f.map_smul a x⟩ @[simp] theorem liftq_apply (f : M →ₗ[R] M₂) {h} (x : M) : p.liftq f h (quotient.mk x) = f x := rfl @[simp] theorem liftq_mkq (f : M →ₗ[R] M₂) (h) : (p.liftq f h).comp p.mkq = f := by ext; refl @[simp] theorem range_mkq : p.mkq.range = ⊤ := eq_top_iff'.2 $ by rintro ⟨x⟩; exact ⟨x, trivial, rfl⟩ @[simp] theorem ker_mkq : p.mkq.ker = p := by ext; simp lemma le_comap_mkq (p' : submodule R p.quotient) : p ≤ comap p.mkq p' := by simpa using (comap_mono bot_le : p.mkq.ker ≤ comap p.mkq p') @[simp] theorem mkq_map_self : map p.mkq p = ⊥ := by rw [eq_bot_iff, map_le_iff_le_comap, comap_bot, ker_mkq]; exact le_refl _ @[simp] theorem comap_map_mkq : comap p.mkq (map p.mkq p') = p ⊔ p' := by simp [comap_map_eq, sup_comm] @[simp] theorem map_mkq_eq_top : map p.mkq p' = ⊤ ↔ p ⊔ p' = ⊤ := by simp only [map_eq_top_iff p.range_mkq, sup_comm, ker_mkq] /-- The map from the quotient of `M` by submodule `p` to the quotient of `M₂` by submodule `q` along `f : M → M₂` is linear. -/ def mapq (f : M →ₗ[R] M₂) (h : p ≤ comap f q) : p.quotient →ₗ[R] q.quotient := p.liftq (q.mkq.comp f) $ by simpa [ker_comp] using h @[simp] theorem mapq_apply (f : M →ₗ[R] M₂) {h} (x : M) : mapq p q f h (quotient.mk x) = quotient.mk (f x) := rfl theorem mapq_mkq (f : M →ₗ[R] M₂) {h} : (mapq p q f h).comp p.mkq = q.mkq.comp f := by ext x; refl theorem comap_liftq (f : M →ₗ[R] M₂) (h) : q.comap (p.liftq f h) = (q.comap f).map (mkq p) := le_antisymm (by rintro ⟨x⟩ hx; exact ⟨_, hx, rfl⟩) (by rw [map_le_iff_le_comap, ← comap_comp, liftq_mkq]; exact le_refl _) theorem map_liftq (f : M →ₗ[R] M₂) (h) (q : submodule R (quotient p)) : q.map (p.liftq f h) = (q.comap p.mkq).map f := le_antisymm (by rintro _ ⟨⟨x⟩, hxq, rfl⟩; exact ⟨x, hxq, rfl⟩) (by rintro _ ⟨x, hxq, rfl⟩; exact ⟨quotient.mk x, hxq, rfl⟩) theorem ker_liftq (f : M →ₗ[R] M₂) (h) : ker (p.liftq f h) = (ker f).map (mkq p) := comap_liftq _ _ _ _ theorem range_liftq (f : M →ₗ[R] M₂) (h) : range (p.liftq f h) = range f := map_liftq _ _ _ _ theorem ker_liftq_eq_bot (f : M →ₗ[R] M₂) (h) (h' : ker f ≤ p) : ker (p.liftq f h) = ⊥ := by rw [ker_liftq, le_antisymm h h', mkq_map_self] /-- The correspondence theorem for modules: there is an order isomorphism between submodules of the quotient of `M` by `p`, and submodules of `M` larger than `p`. -/ def comap_mkq.rel_iso : submodule R p.quotient ≃o {p' : submodule R M // p ≤ p'} := { to_fun := λ p', ⟨comap p.mkq p', le_comap_mkq p _⟩, inv_fun := λ q, map p.mkq q, left_inv := λ p', map_comap_eq_self $ by simp, right_inv := λ ⟨q, hq⟩, subtype.ext_val $ by simpa [comap_map_mkq p], map_rel_iff' := λ p₁ p₂, (comap_le_comap_iff $ range_mkq _).symm } /-- The ordering on submodules of the quotient of `M` by `p` embeds into the ordering on submodules of `M`. -/ def comap_mkq.order_embedding : submodule R p.quotient ↪o submodule R M := (rel_iso.to_rel_embedding $ comap_mkq.rel_iso p).trans (subtype.rel_embedding _ _) @[simp] lemma comap_mkq_embedding_eq (p' : submodule R p.quotient) : comap_mkq.order_embedding p p' = comap p.mkq p' := rfl end ring end submodule namespace linear_map variables [ring R] [add_comm_group M] [add_comm_group M₂] [add_comm_group M₃] variables [module R M] [module R M₂] [module R M₃] lemma range_mkq_comp (f : M →ₗ[R] M₂) : f.range.mkq.comp f = 0 := linear_map.ext $ λ x, by simp lemma ker_le_range_iff {f : M →ₗ[R] M₂} {g : M₂ →ₗ[R] M₃} : g.ker ≤ f.range ↔ f.range.mkq.comp g.ker.subtype = 0 := by rw [←range_le_ker_iff, submodule.ker_mkq, submodule.range_subtype] /-- A monomorphism is injective. -/ lemma ker_eq_bot_of_cancel {f : M →ₗ[R] M₂} (h : ∀ (u v : f.ker →ₗ[R] M), f.comp u = f.comp v → u = v) : f.ker = ⊥ := begin have h₁ : f.comp (0 : f.ker →ₗ[R] M) = 0 := comp_zero _, rw [←submodule.range_subtype f.ker, ←h 0 f.ker.subtype (eq.trans h₁ (comp_ker_subtype f).symm)], exact range_zero end /-- An epimorphism is surjective. -/ lemma range_eq_top_of_cancel {f : M →ₗ[R] M₂} (h : ∀ (u v : M₂ →ₗ[R] f.range.quotient), u.comp f = v.comp f → u = v) : f.range = ⊤ := begin have h₁ : (0 : M₂ →ₗ[R] f.range.quotient).comp f = 0 := zero_comp _, rw [←submodule.ker_mkq f.range, ←h 0 f.range.mkq (eq.trans h₁ (range_mkq_comp _).symm)], exact ker_zero end end linear_map @[simp] lemma linear_map.range_range_restrict [semiring R] [add_comm_monoid M] [add_comm_monoid M₂] [semimodule R M] [semimodule R M₂] (f : M →ₗ[R] M₂) : f.range_restrict.range = ⊤ := by simp [f.range_cod_restrict _] /-! ### Linear equivalences -/ section set_option old_structure_cmd true /-- A linear equivalence is an invertible linear map. -/ @[nolint has_inhabited_instance] structure linear_equiv (R : Type u) (M : Type v) (M₂ : Type w) [semiring R] [add_comm_monoid M] [add_comm_monoid M₂] [semimodule R M] [semimodule R M₂] extends M →ₗ[R] M₂, M ≃ M₂ end attribute [nolint doc_blame] linear_equiv.to_linear_map attribute [nolint doc_blame] linear_equiv.to_equiv infix ` ≃ₗ ` := linear_equiv _ notation M ` ≃ₗ[`:50 R `] ` M₂ := linear_equiv R M M₂ namespace linear_equiv section add_comm_monoid variables [semiring R] [add_comm_monoid M] [add_comm_monoid M₂] [add_comm_monoid M₃] [add_comm_monoid M₄] section variables [semimodule R M] [semimodule R M₂] [semimodule R M₃] include R instance : has_coe (M ≃ₗ[R] M₂) (M →ₗ[R] M₂) := ⟨to_linear_map⟩ -- see Note [function coercion] instance : has_coe_to_fun (M ≃ₗ[R] M₂) := ⟨_, λ f, f.to_fun⟩ @[simp] lemma mk_apply {to_fun inv_fun map_add map_smul left_inv right_inv a} : (⟨to_fun, map_add, map_smul, inv_fun, left_inv, right_inv⟩ : M ≃ₗ[R] M₂) a = to_fun a := rfl lemma to_equiv_injective : function.injective (to_equiv : (M ≃ₗ[R] M₂) → M ≃ M₂) := λ ⟨_, _, _, _, _, _⟩ ⟨_, _, _, _, _, _⟩ h, linear_equiv.mk.inj_eq.mpr (equiv.mk.inj h) end section variables {semimodule_M : semimodule R M} {semimodule_M₂ : semimodule R M₂} variables (e e' : M ≃ₗ[R] M₂) @[simp, norm_cast] theorem coe_coe : ((e : M →ₗ[R] M₂) : M → M₂) = (e : M → M₂) := rfl @[simp] lemma coe_to_equiv : ((e.to_equiv) : M → M₂) = (e : M → M₂) := rfl @[simp] lemma to_fun_apply {m : M} : e.to_fun m = e m := rfl section variables {e e'} @[ext] lemma ext (h : ∀ x, e x = e' x) : e = e' := to_equiv_injective (equiv.ext h) variables [semimodule R M] [semimodule R M₂] lemma eq_of_linear_map_eq {f f' : M ≃ₗ[R] M₂} (h : (f : M →ₗ[R] M₂) = f') : f = f' := begin ext x, change (f : M →ₗ[R] M₂) x = (f' : M →ₗ[R] M₂) x, rw h end end section variables (M R) /-- The identity map is a linear equivalence. -/ @[refl] def refl [semimodule R M] : M ≃ₗ[R] M := { .. linear_map.id, .. equiv.refl M } end @[simp] lemma refl_apply [semimodule R M] (x : M) : refl R M x = x := rfl /-- Linear equivalences are symmetric. -/ @[symm] def symm : M₂ ≃ₗ[R] M := { .. e.to_linear_map.inverse e.inv_fun e.left_inv e.right_inv, .. e.to_equiv.symm } @[simp] lemma inv_fun_apply {m : M₂} : e.inv_fun m = e.symm m := rfl variables {semimodule_M₃ : semimodule R M₃} (e₁ : M ≃ₗ[R] M₂) (e₂ : M₂ ≃ₗ[R] M₃) /-- Linear equivalences are transitive. -/ @[trans] def trans : M ≃ₗ[R] M₃ := { .. e₂.to_linear_map.comp e₁.to_linear_map, .. e₁.to_equiv.trans e₂.to_equiv } /-- A linear equivalence is an additive equivalence. -/ def to_add_equiv : M ≃+ M₂ := { .. e } @[simp] lemma coe_to_add_equiv : ⇑(e.to_add_equiv) = e := rfl @[simp] theorem trans_apply (c : M) : (e₁.trans e₂) c = e₂ (e₁ c) := rfl @[simp] theorem apply_symm_apply (c : M₂) : e (e.symm c) = c := e.6 c @[simp] theorem symm_apply_apply (b : M) : e.symm (e b) = b := e.5 b @[simp] lemma symm_trans_apply (c : M₃) : (e₁.trans e₂).symm c = e₁.symm (e₂.symm c) := rfl @[simp] lemma trans_refl : e.trans (refl R M₂) = e := to_equiv_injective e.to_equiv.trans_refl @[simp] lemma refl_trans : (refl R M).trans e = e := to_equiv_injective e.to_equiv.refl_trans lemma symm_apply_eq {x y} : e.symm x = y ↔ x = e y := e.to_equiv.symm_apply_eq lemma eq_symm_apply {x y} : y = e.symm x ↔ e y = x := e.to_equiv.eq_symm_apply @[simp] lemma trans_symm [semimodule R M] [semimodule R M₂] (f : M ≃ₗ[R] M₂) : f.trans f.symm = linear_equiv.refl R M := by { ext x, simp } @[simp] lemma symm_trans [semimodule R M] [semimodule R M₂] (f : M ≃ₗ[R] M₂) : f.symm.trans f = linear_equiv.refl R M₂ := by { ext x, simp } @[simp, norm_cast] lemma refl_to_linear_map [semimodule R M] : (linear_equiv.refl R M : M →ₗ[R] M) = linear_map.id := rfl @[simp, norm_cast] lemma comp_coe [semimodule R M] [semimodule R M₂] [semimodule R M₃] (f : M ≃ₗ[R] M₂) (f' : M₂ ≃ₗ[R] M₃) : (f' : M₂ →ₗ[R] M₃).comp (f : M →ₗ[R] M₂) = (f.trans f' : M →ₗ[R] M₃) := rfl @[simp] theorem map_add (a b : M) : e (a + b) = e a + e b := e.map_add' a b @[simp] theorem map_zero : e 0 = 0 := e.to_linear_map.map_zero @[simp] theorem map_smul (c : R) (x : M) : e (c • x) = c • e x := e.map_smul' c x @[simp] lemma map_sum {s : finset ι} (u : ι → M) : e (∑ i in s, u i) = ∑ i in s, e (u i) := e.to_linear_map.map_sum @[simp] theorem map_eq_zero_iff {x : M} : e x = 0 ↔ x = 0 := e.to_add_equiv.map_eq_zero_iff theorem map_ne_zero_iff {x : M} : e x ≠ 0 ↔ x ≠ 0 := e.to_add_equiv.map_ne_zero_iff @[simp] theorem symm_symm : e.symm.symm = e := by { cases e, refl } protected lemma bijective : function.bijective e := e.to_equiv.bijective protected lemma injective : function.injective e := e.to_equiv.injective protected lemma surjective : function.surjective e := e.to_equiv.surjective protected lemma image_eq_preimage (s : set M) : e '' s = e.symm ⁻¹' s := e.to_equiv.image_eq_preimage s lemma map_eq_comap {p : submodule R M} : (p.map e : submodule R M₂) = p.comap e.symm := submodule.coe_injective $ by simp [e.image_eq_preimage] /-- A linear equivalence of two modules restricts to a linear equivalence from any submodule of the domain onto the image of the submodule. -/ def of_submodule (p : submodule R M) : p ≃ₗ[R] ↥(p.map ↑e : submodule R M₂) := { inv_fun := λ y, ⟨e.symm y, by { rcases y with ⟨y', hy⟩, rw submodule.mem_map at hy, rcases hy with ⟨x, hx, hxy⟩, subst hxy, simp only [symm_apply_apply, submodule.coe_mk, coe_coe, hx], }⟩, left_inv := λ x, by simp, right_inv := λ y, by { apply set_coe.ext, simp, }, ..((e : M →ₗ[R] M₂).dom_restrict p).cod_restrict (p.map ↑e) (λ x, ⟨x, by simp⟩) } @[simp] lemma of_submodule_apply (p : submodule R M) (x : p) : ↑(e.of_submodule p x) = e x := rfl @[simp] lemma of_submodule_symm_apply (p : submodule R M) (x : (p.map ↑e : submodule R M₂)) : ↑((e.of_submodule p).symm x) = e.symm x := rfl end section prod variables {semimodule_M : semimodule R M} {semimodule_M₂ : semimodule R M₂} variables {semimodule_M₃ : semimodule R M₃} {semimodule_M₄ : semimodule R M₄} variables (e₁ : M ≃ₗ[R] M₂) (e₂ : M₃ ≃ₗ[R] M₄) /-- Product of linear equivalences; the maps come from `equiv.prod_congr`. -/ protected def prod : (M × M₃) ≃ₗ[R] (M₂ × M₄) := { map_add' := λ x y, prod.ext (e₁.map_add _ _) (e₂.map_add _ _), map_smul' := λ c x, prod.ext (e₁.map_smul c _) (e₂.map_smul c _), .. equiv.prod_congr e₁.to_equiv e₂.to_equiv } lemma prod_symm : (e₁.prod e₂).symm = e₁.symm.prod e₂.symm := rfl @[simp] lemma prod_apply (p) : e₁.prod e₂ p = (e₁ p.1, e₂ p.2) := rfl @[simp, norm_cast] lemma coe_prod : (e₁.prod e₂ : (M × M₃) →ₗ[R] (M₂ × M₄)) = (e₁ : M →ₗ[R] M₂).prod_map (e₂ : M₃ →ₗ[R] M₄) := rfl end prod section uncurry variables (V V₂ R) /-- Linear equivalence between a curried and uncurried function. Differs from `tensor_product.curry`. -/ protected def uncurry : (V → V₂ → R) ≃ₗ[R] (V × V₂ → R) := { map_add' := λ _ _, by { ext ⟨⟩, refl }, map_smul' := λ _ _, by { ext ⟨⟩, refl }, .. equiv.arrow_arrow_equiv_prod_arrow _ _ _} @[simp] lemma coe_uncurry : ⇑(linear_equiv.uncurry R V V₂) = uncurry := rfl @[simp] lemma coe_uncurry_symm : ⇑(linear_equiv.uncurry R V V₂).symm = curry := rfl end uncurry section variables {semimodule_M : semimodule R M} {semimodule_M₂ : semimodule R M₂} variables (f : M →ₗ[R] M₂) (g : M₂ →ₗ[R] M) (e : M ≃ₗ[R] M₂) variables (p q : submodule R M) /-- Linear equivalence between two equal submodules. -/ def of_eq (h : p = q) : p ≃ₗ[R] q := { map_smul' := λ _ _, rfl, map_add' := λ _ _, rfl, .. equiv.set.of_eq (congr_arg _ h) } variables {p q} @[simp] lemma coe_of_eq_apply (h : p = q) (x : p) : (of_eq p q h x : M) = x := rfl @[simp] lemma of_eq_symm (h : p = q) : (of_eq p q h).symm = of_eq q p h.symm := rfl /-- A linear equivalence which maps a submodule of one module onto another, restricts to a linear equivalence of the two submodules. -/ def of_submodules (p : submodule R M) (q : submodule R M₂) (h : p.map ↑e = q) : p ≃ₗ[R] q := (e.of_submodule p).trans (linear_equiv.of_eq _ _ h) @[simp] lemma of_submodules_apply {p : submodule R M} {q : submodule R M₂} (h : p.map ↑e = q) (x : p) : ↑(e.of_submodules p q h x) = e x := rfl @[simp] lemma of_submodules_symm_apply {p : submodule R M} {q : submodule R M₂} (h : p.map ↑e = q) (x : q) : ↑((e.of_submodules p q h).symm x) = e.symm x := rfl variable (p) /-- The top submodule of `M` is linearly equivalent to `M`. -/ def of_top (h : p = ⊤) : p ≃ₗ[R] M := { inv_fun := λ x, ⟨x, h.symm ▸ trivial⟩, left_inv := λ ⟨x, h⟩, rfl, right_inv := λ x, rfl, .. p.subtype } @[simp] theorem of_top_apply {h} (x : p) : of_top p h x = x := rfl @[simp] theorem coe_of_top_symm_apply {h} (x : M) : ((of_top p h).symm x : M) = x := rfl theorem of_top_symm_apply {h} (x : M) : (of_top p h).symm x = ⟨x, h.symm ▸ trivial⟩ := rfl /-- If a linear map has an inverse, it is a linear equivalence. -/ def of_linear (h₁ : f.comp g = linear_map.id) (h₂ : g.comp f = linear_map.id) : M ≃ₗ[R] M₂ := { inv_fun := g, left_inv := linear_map.ext_iff.1 h₂, right_inv := linear_map.ext_iff.1 h₁, ..f } @[simp] theorem of_linear_apply {h₁ h₂} (x : M) : of_linear f g h₁ h₂ x = f x := rfl @[simp] theorem of_linear_symm_apply {h₁ h₂} (x : M₂) : (of_linear f g h₁ h₂).symm x = g x := rfl @[simp] protected theorem range : (e : M →ₗ[R] M₂).range = ⊤ := linear_map.range_eq_top.2 e.to_equiv.surjective lemma eq_bot_of_equiv [semimodule R M₂] (e : p ≃ₗ[R] (⊥ : submodule R M₂)) : p = ⊥ := begin refine bot_unique (submodule.le_def'.2 $ assume b hb, (submodule.mem_bot R).2 _), rw [← p.mk_eq_zero hb, ← e.map_eq_zero_iff], apply submodule.eq_zero_of_bot_submodule end @[simp] protected theorem ker : (e : M →ₗ[R] M₂).ker = ⊥ := linear_map.ker_eq_bot_of_injective e.to_equiv.injective end end add_comm_monoid section add_comm_group variables [semiring R] [add_comm_group M] [add_comm_group M₂] [add_comm_group M₃] [add_comm_group M₄] variables {semimodule_M : semimodule R M} {semimodule_M₂ : semimodule R M₂} variables {semimodule_M₃ : semimodule R M₃} {semimodule_M₄ : semimodule R M₄} variables (e e₁ : M ≃ₗ[R] M₂) (e₂ : M₃ ≃ₗ[R] M₄) @[simp] theorem map_neg (a : M) : e (-a) = -e a := e.to_linear_map.map_neg a @[simp] theorem map_sub (a b : M) : e (a - b) = e a - e b := e.to_linear_map.map_sub a b /-- Equivalence given by a block lower diagonal matrix. `e₁` and `e₂` are diagonal square blocks, and `f` is a rectangular block below the diagonal. -/ protected def skew_prod (f : M →ₗ[R] M₄) : (M × M₃) ≃ₗ[R] M₂ × M₄ := { inv_fun := λ p : M₂ × M₄, (e₁.symm p.1, e₂.symm (p.2 - f (e₁.symm p.1))), left_inv := λ p, by simp, right_inv := λ p, by simp, .. ((e₁ : M →ₗ[R] M₂).comp (linear_map.fst R M M₃)).prod ((e₂ : M₃ →ₗ[R] M₄).comp (linear_map.snd R M M₃) + f.comp (linear_map.fst R M M₃)) } @[simp] lemma skew_prod_apply (f : M →ₗ[R] M₄) (x) : e₁.skew_prod e₂ f x = (e₁ x.1, e₂ x.2 + f x.1) := rfl @[simp] lemma skew_prod_symm_apply (f : M →ₗ[R] M₄) (x) : (e₁.skew_prod e₂ f).symm x = (e₁.symm x.1, e₂.symm (x.2 - f (e₁.symm x.1))) := rfl end add_comm_group section ring variables [ring R] [add_comm_group M] [add_comm_group M₂] variables {semimodule_M : semimodule R M} {semimodule_M₂ : semimodule R M₂} variables (f : M →ₗ[R] M₂) (e : M ≃ₗ[R] M₂) /-- An `injective` linear map `f : M →ₗ[R] M₂` defines a linear equivalence between `M` and `f.range`. -/ noncomputable def of_injective (h : f.ker = ⊥) : M ≃ₗ[R] f.range := { .. (equiv.set.range f $ linear_map.ker_eq_bot.1 h).trans (equiv.set.of_eq f.range_coe.symm), .. f.cod_restrict f.range (λ x, f.mem_range_self x) } @[simp] theorem of_injective_apply {h : f.ker = ⊥} (x : M) : ↑(of_injective f h x) = f x := rfl /-- A bijective linear map is a linear equivalence. Here, bijectivity is described by saying that the kernel of `f` is `{0}` and the range is the universal set. -/ noncomputable def of_bijective (hf₁ : f.ker = ⊥) (hf₂ : f.range = ⊤) : M ≃ₗ[R] M₂ := (of_injective f hf₁).trans (of_top _ hf₂) @[simp] theorem of_bijective_apply {hf₁ hf₂} (x : M) : of_bijective f hf₁ hf₂ x = f x := rfl end ring section comm_ring variables [comm_ring R] [add_comm_group M] [add_comm_group M₂] [add_comm_group M₃] variables [semimodule R M] [semimodule R M₂] [semimodule R M₃] open linear_map /-- Multiplying by a unit `a` of the ring `R` is a linear equivalence. -/ def smul_of_unit (a : units R) : M ≃ₗ[R] M := of_linear ((a:R) • 1 : M →ₗ M) (((a⁻¹ : units R) : R) • 1 : M →ₗ M) (by rw [smul_comp, comp_smul, smul_smul, units.mul_inv, one_smul]; refl) (by rw [smul_comp, comp_smul, smul_smul, units.inv_mul, one_smul]; refl) /-- A linear isomorphism between the domains and codomains of two spaces of linear maps gives a linear isomorphism between the two function spaces. -/ def arrow_congr {R M₁ M₂ M₂₁ M₂₂ : Sort*} [comm_ring R] [add_comm_group M₁] [add_comm_group M₂] [add_comm_group M₂₁] [add_comm_group M₂₂] [module R M₁] [module R M₂] [module R M₂₁] [module R M₂₂] (e₁ : M₁ ≃ₗ[R] M₂) (e₂ : M₂₁ ≃ₗ[R] M₂₂) : (M₁ →ₗ[R] M₂₁) ≃ₗ[R] (M₂ →ₗ[R] M₂₂) := { to_fun := λ f, (e₂ : M₂₁ →ₗ[R] M₂₂).comp $ f.comp e₁.symm, inv_fun := λ f, (e₂.symm : M₂₂ →ₗ[R] M₂₁).comp $ f.comp e₁, left_inv := λ f, by { ext x, simp }, right_inv := λ f, by { ext x, simp }, map_add' := λ f g, by { ext x, simp }, map_smul' := λ c f, by { ext x, simp } } @[simp] lemma arrow_congr_apply {R M₁ M₂ M₂₁ M₂₂ : Sort*} [comm_ring R] [add_comm_group M₁] [add_comm_group M₂] [add_comm_group M₂₁] [add_comm_group M₂₂] [module R M₁] [module R M₂] [module R M₂₁] [module R M₂₂] (e₁ : M₁ ≃ₗ[R] M₂) (e₂ : M₂₁ ≃ₗ[R] M₂₂) (f : M₁ →ₗ[R] M₂₁) (x : M₂) : arrow_congr e₁ e₂ f x = e₂ (f (e₁.symm x)) := rfl lemma arrow_congr_comp {N N₂ N₃ : Sort*} [add_comm_group N] [add_comm_group N₂] [add_comm_group N₃] [module R N] [module R N₂] [module R N₃] (e₁ : M ≃ₗ[R] N) (e₂ : M₂ ≃ₗ[R] N₂) (e₃ : M₃ ≃ₗ[R] N₃) (f : M →ₗ[R] M₂) (g : M₂ →ₗ[R] M₃) : arrow_congr e₁ e₃ (g.comp f) = (arrow_congr e₂ e₃ g).comp (arrow_congr e₁ e₂ f) := by { ext, simp only [symm_apply_apply, arrow_congr_apply, linear_map.comp_apply], } lemma arrow_congr_trans {M₁ M₂ M₃ N₁ N₂ N₃ : Sort*} [add_comm_group M₁] [module R M₁] [add_comm_group M₂] [module R M₂] [add_comm_group M₃] [module R M₃] [add_comm_group N₁] [module R N₁] [add_comm_group N₂] [module R N₂] [add_comm_group N₃] [module R N₃] (e₁ : M₁ ≃ₗ[R] M₂) (e₂ : N₁ ≃ₗ[R] N₂) (e₃ : M₂ ≃ₗ[R] M₃) (e₄ : N₂ ≃ₗ[R] N₃) : (arrow_congr e₁ e₂).trans (arrow_congr e₃ e₄) = arrow_congr (e₁.trans e₃) (e₂.trans e₄) := rfl /-- If `M₂` and `M₃` are linearly isomorphic then the two spaces of linear maps from `M` into `M₂` and `M` into `M₃` are linearly isomorphic. -/ def congr_right (f : M₂ ≃ₗ[R] M₃) : (M →ₗ[R] M₂) ≃ₗ (M →ₗ M₃) := arrow_congr (linear_equiv.refl R M) f /-- If `M` and `M₂` are linearly isomorphic then the two spaces of linear maps from `M` and `M₂` to themselves are linearly isomorphic. -/ def conj (e : M ≃ₗ[R] M₂) : (module.End R M) ≃ₗ[R] (module.End R M₂) := arrow_congr e e lemma conj_apply (e : M ≃ₗ[R] M₂) (f : module.End R M) : e.conj f = ((↑e : M →ₗ[R] M₂).comp f).comp e.symm := rfl lemma symm_conj_apply (e : M ≃ₗ[R] M₂) (f : module.End R M₂) : e.symm.conj f = ((↑e.symm : M₂ →ₗ[R] M).comp f).comp e := rfl lemma conj_comp (e : M ≃ₗ[R] M₂) (f g : module.End R M) : e.conj (g.comp f) = (e.conj g).comp (e.conj f) := arrow_congr_comp e e e f g lemma conj_trans (e₁ : M ≃ₗ[R] M₂) (e₂ : M₂ ≃ₗ[R] M₃) : e₁.conj.trans e₂.conj = (e₁.trans e₂).conj := by { ext f x, refl, } @[simp] lemma conj_id (e : M ≃ₗ[R] M₂) : e.conj linear_map.id = linear_map.id := by { ext, simp [conj_apply], } end comm_ring section field variables [field K] [add_comm_group M] [add_comm_group M₂] [add_comm_group M₃] variables [module K M] [module K M₂] [module K M₃] variables (K) (M) open linear_map /-- Multiplying by a nonzero element `a` of the field `K` is a linear equivalence. -/ def smul_of_ne_zero (a : K) (ha : a ≠ 0) : M ≃ₗ[K] M := smul_of_unit $ units.mk0 a ha section noncomputable theory open_locale classical /-- Given a nonzero element `x` of a vector space `M` over a field `K`, the natural map from `K` to the span of `x`, with invertibility check to consider it as an isomorphism.-/ def to_span_nonzero_singleton (x : M) (h : x ≠ 0) : K ≃ₗ[K] (submodule.span K ({x} : set M)) := linear_equiv.trans ( linear_equiv.of_injective (to_span_singleton K M x) begin ext c, split, { intros hc, rw submodule.mem_bot, rw mem_ker at hc, by_contra hc', have : x = 0, calc x = c⁻¹ • (c • x) : by rw [← mul_smul, inv_mul_cancel hc', one_smul] ... = c⁻¹ • ((to_span_singleton K M x) c) : rfl ... = 0 : by rw [hc, smul_zero], tauto }, { rw [mem_ker, submodule.mem_bot], intros h, rw h, simp } end ) (of_eq (to_span_singleton K M x).range (submodule.span K {x}) (span_singleton_eq_range K M x).symm) lemma to_span_nonzero_singleton_one (x : M) (h : x ≠ 0) : to_span_nonzero_singleton K M x h 1 = (⟨x, submodule.mem_span_singleton_self x⟩ : submodule.span K ({x} : set M)) := begin apply submodule.coe_eq_coe.mp, have : ↑(to_span_nonzero_singleton K M x h 1) = to_span_singleton K M x 1 := rfl, rw [this, to_span_singleton_one, submodule.coe_mk], end /-- Given a nonzero element `x` of a vector space `M` over a field `K`, the natural map from the span of `x` to `K`.-/ abbreviation coord (x : M) (h : x ≠ 0) : (submodule.span K ({x} : set M)) ≃ₗ[K] K := (to_span_nonzero_singleton K M x h).symm lemma coord_self (x : M) (h : x ≠ 0) : (coord K M x h) ( ⟨x, submodule.mem_span_singleton_self x⟩ : submodule.span K ({x} : set M)) = 1 := by rw [← to_span_nonzero_singleton_one K M x h, symm_apply_apply] end end field end linear_equiv namespace submodule section semimodule variables [semiring R] [add_comm_monoid M] [semimodule R M] /-- If `s ≤ t`, then we can view `s` as a submodule of `t` by taking the comap of `t.subtype`. -/ def comap_subtype_equiv_of_le {p q : submodule R M} (hpq : p ≤ q) : comap q.subtype p ≃ₗ[R] p := { to_fun := λ x, ⟨x, x.2⟩, inv_fun := λ x, ⟨⟨x, hpq x.2⟩, x.2⟩, left_inv := λ x, by simp only [coe_mk, submodule.eta, coe_coe], right_inv := λ x, by simp only [subtype.coe_mk, submodule.eta, coe_coe], map_add' := λ x y, rfl, map_smul' := λ c x, rfl } end semimodule variables [ring R] [add_comm_group M] [module R M] variables (p : submodule R M) open linear_map /-- If `p = ⊥`, then `M / p ≃ₗ[R] M`. -/ def quot_equiv_of_eq_bot (hp : p = ⊥) : p.quotient ≃ₗ[R] M := linear_equiv.of_linear (p.liftq id $ hp.symm ▸ bot_le) p.mkq (liftq_mkq _ _ _) $ p.quot_hom_ext $ λ x, rfl @[simp] lemma quot_equiv_of_eq_bot_apply_mk (hp : p = ⊥) (x : M) : p.quot_equiv_of_eq_bot hp (quotient.mk x) = x := rfl @[simp] lemma quot_equiv_of_eq_bot_symm_apply (hp : p = ⊥) (x : M) : (p.quot_equiv_of_eq_bot hp).symm x = quotient.mk x := rfl @[simp] lemma coe_quot_equiv_of_eq_bot_symm (hp : p = ⊥) : ((p.quot_equiv_of_eq_bot hp).symm : M →ₗ[R] p.quotient) = p.mkq := rfl variables (q : submodule R M) /-- Quotienting by equal submodules gives linearly equivalent quotients. -/ def quot_equiv_of_eq (h : p = q) : p.quotient ≃ₗ[R] q.quotient := { map_add' := by { rintros ⟨x⟩ ⟨y⟩, refl }, map_smul' := by { rintros x ⟨y⟩, refl }, ..@quotient.congr _ _ (quotient_rel p) (quotient_rel q) (equiv.refl _) $ λ a b, by { subst h, refl } } end submodule namespace submodule variables [comm_ring R] [add_comm_group M] [add_comm_group M₂] [module R M] [module R M₂] variables (p : submodule R M) (q : submodule R M₂) @[simp] lemma mem_map_equiv {e : M ≃ₗ[R] M₂} {x : M₂} : x ∈ p.map (e : M →ₗ[R] M₂) ↔ e.symm x ∈ p := begin rw submodule.mem_map, split, { rintros ⟨y, hy, hx⟩, simp [←hx, hy], }, { intros hx, refine ⟨e.symm x, hx, by simp⟩, }, end lemma comap_le_comap_smul (f : M →ₗ[R] M₂) (c : R) : comap f q ≤ comap (c • f) q := begin rw le_def', intros m h, change c • (f m) ∈ q, change f m ∈ q at h, apply q.smul_mem _ h, end lemma inf_comap_le_comap_add (f₁ f₂ : M →ₗ[R] M₂) : comap f₁ q ⊓ comap f₂ q ≤ comap (f₁ + f₂) q := begin rw le_def', intros m h, change f₁ m + f₂ m ∈ q, change f₁ m ∈ q ∧ f₂ m ∈ q at h, apply q.add_mem h.1 h.2, end /-- Given modules `M`, `M₂` over a commutative ring, together with submodules `p ⊆ M`, `q ⊆ M₂`, the set of maps $\\{f ∈ Hom(M, M₂) | f(p) ⊆ q \\}$ is a submodule of `Hom(M, M₂)`. -/ def compatible_maps : submodule R (M →ₗ[R] M₂) := { carrier := {f | p ≤ comap f q}, zero_mem' := by { change p ≤ comap 0 q, rw comap_zero, refine le_top, }, add_mem' := λ f₁ f₂ h₁ h₂, by { apply le_trans _ (inf_comap_le_comap_add q f₁ f₂), rw le_inf_iff, exact ⟨h₁, h₂⟩, }, smul_mem' := λ c f h, le_trans h (comap_le_comap_smul q f c), } /-- Given modules `M`, `M₂` over a commutative ring, together with submodules `p ⊆ M`, `q ⊆ M₂`, the natural map $\\{f ∈ Hom(M, M₂) | f(p) ⊆ q \\} \to Hom(M/p, M₂/q)$ is linear. -/ def mapq_linear : compatible_maps p q →ₗ[R] p.quotient →ₗ[R] q.quotient := { to_fun := λ f, mapq _ _ f.val f.property, map_add' := λ x y, by { ext m', apply quotient.induction_on' m', intros m, refl, }, map_smul' := λ c f, by { ext m', apply quotient.induction_on' m', intros m, refl, } } end submodule namespace equiv variables [semiring R] [add_comm_monoid M] [semimodule R M] [add_comm_monoid M₂] [semimodule R M₂] /-- An equivalence whose underlying function is linear is a linear equivalence. -/ def to_linear_equiv (e : M ≃ M₂) (h : is_linear_map R (e : M → M₂)) : M ≃ₗ[R] M₂ := { .. e, .. h.mk' e} end equiv namespace linear_map open submodule section isomorphism_laws variables [ring R] [add_comm_group M] [add_comm_group M₂] [add_comm_group M₃] variables [module R M] [module R M₂] [module R M₃] variables (f : M →ₗ[R] M₂) /-- The first isomorphism law for modules. The quotient of `M` by the kernel of `f` is linearly equivalent to the range of `f`. -/ noncomputable def quot_ker_equiv_range : f.ker.quotient ≃ₗ[R] f.range := (linear_equiv.of_injective (f.ker.liftq f $ le_refl _) $ submodule.ker_liftq_eq_bot _ _ _ (le_refl f.ker)).trans (linear_equiv.of_eq _ _ $ submodule.range_liftq _ _ _) @[simp] lemma quot_ker_equiv_range_apply_mk (x : M) : (f.quot_ker_equiv_range (submodule.quotient.mk x) : M₂) = f x := rfl @[simp] lemma quot_ker_equiv_range_symm_apply_image (x : M) (h : f x ∈ f.range) : f.quot_ker_equiv_range.symm ⟨f x, h⟩ = f.ker.mkq x := f.quot_ker_equiv_range.symm_apply_apply (f.ker.mkq x) /-- Canonical linear map from the quotient `p/(p ∩ p')` to `(p+p')/p'`, mapping `x + (p ∩ p')` to `x + p'`, where `p` and `p'` are submodules of an ambient module. -/ def quotient_inf_to_sup_quotient (p p' : submodule R M) : (comap p.subtype (p ⊓ p')).quotient →ₗ[R] (comap (p ⊔ p').subtype p').quotient := (comap p.subtype (p ⊓ p')).liftq ((comap (p ⊔ p').subtype p').mkq.comp (of_le le_sup_left)) begin rw [ker_comp, of_le, comap_cod_restrict, ker_mkq, map_comap_subtype], exact comap_mono (inf_le_inf_right _ le_sup_left) end /-- Second Isomorphism Law : the canonical map from `p/(p ∩ p')` to `(p+p')/p'` as a linear isomorphism. -/ noncomputable def quotient_inf_equiv_sup_quotient (p p' : submodule R M) : (comap p.subtype (p ⊓ p')).quotient ≃ₗ[R] (comap (p ⊔ p').subtype p').quotient := linear_equiv.of_bijective (quotient_inf_to_sup_quotient p p') begin rw [quotient_inf_to_sup_quotient, ker_liftq_eq_bot], rw [ker_comp, ker_mkq], exact λ ⟨x, hx1⟩ hx2, ⟨hx1, hx2⟩ end begin rw [quotient_inf_to_sup_quotient, range_liftq, eq_top_iff'], rintros ⟨x, hx⟩, rcases mem_sup.1 hx with ⟨y, hy, z, hz, rfl⟩, use [⟨y, hy⟩, trivial], apply (submodule.quotient.eq _).2, change y - (y + z) ∈ p', rwa [sub_add_eq_sub_sub, sub_self, zero_sub, neg_mem_iff] end @[simp] lemma coe_quotient_inf_to_sup_quotient (p p' : submodule R M) : ⇑(quotient_inf_to_sup_quotient p p') = quotient_inf_equiv_sup_quotient p p' := rfl @[simp] lemma quotient_inf_equiv_sup_quotient_apply_mk (p p' : submodule R M) (x : p) : quotient_inf_equiv_sup_quotient p p' (submodule.quotient.mk x) = submodule.quotient.mk (of_le (le_sup_left : p ≤ p ⊔ p') x) := rfl lemma quotient_inf_equiv_sup_quotient_symm_apply_left (p p' : submodule R M) (x : p ⊔ p') (hx : (x:M) ∈ p) : (quotient_inf_equiv_sup_quotient p p').symm (submodule.quotient.mk x) = submodule.quotient.mk ⟨x, hx⟩ := (linear_equiv.symm_apply_eq _).2 $ by simp [of_le_apply] @[simp] lemma quotient_inf_equiv_sup_quotient_symm_apply_eq_zero_iff {p p' : submodule R M} {x : p ⊔ p'} : (quotient_inf_equiv_sup_quotient p p').symm (submodule.quotient.mk x) = 0 ↔ (x:M) ∈ p' := (linear_equiv.symm_apply_eq _).trans $ by simp [of_le_apply] lemma quotient_inf_equiv_sup_quotient_symm_apply_right (p p' : submodule R M) {x : p ⊔ p'} (hx : (x:M) ∈ p') : (quotient_inf_equiv_sup_quotient p p').symm (submodule.quotient.mk x) = 0 := quotient_inf_equiv_sup_quotient_symm_apply_eq_zero_iff.2 hx end isomorphism_laws section prod lemma is_linear_map_prod_iso {R M M₂ M₃ : Type*} [comm_semiring R] [add_comm_monoid M] [add_comm_monoid M₂] [add_comm_group M₃] [semimodule R M] [semimodule R M₂] [semimodule R M₃] : is_linear_map R (λ(p : (M →ₗ[R] M₂) × (M →ₗ[R] M₃)), (linear_map.prod p.1 p.2 : (M →ₗ[R] (M₂ × M₃)))) := ⟨λu v, rfl, λc u, rfl⟩ end prod section pi universe i variables [semiring R] [add_comm_monoid M₂] [semimodule R M₂] [add_comm_monoid M₃] [semimodule R M₃] {φ : ι → Type i} [∀i, add_comm_monoid (φ i)] [∀i, semimodule R (φ i)] /-- `pi` construction for linear functions. From a family of linear functions it produces a linear function into a family of modules. -/ def pi (f : Πi, M₂ →ₗ[R] φ i) : M₂ →ₗ[R] (Πi, φ i) := ⟨λc i, f i c, λ c d, funext $ λ i, (f i).map_add _ _, λ c d, funext $ λ i, (f i).map_smul _ _⟩ @[simp] lemma pi_apply (f : Πi, M₂ →ₗ[R] φ i) (c : M₂) (i : ι) : pi f c i = f i c := rfl lemma ker_pi (f : Πi, M₂ →ₗ[R] φ i) : ker (pi f) = (⨅i:ι, ker (f i)) := by ext c; simp [funext_iff]; refl lemma pi_eq_zero (f : Πi, M₂ →ₗ[R] φ i) : pi f = 0 ↔ (∀i, f i = 0) := by simp only [linear_map.ext_iff, pi_apply, funext_iff]; exact ⟨λh a b, h b a, λh a b, h b a⟩ lemma pi_zero : pi (λi, 0 : Πi, M₂ →ₗ[R] φ i) = 0 := by ext; refl lemma pi_comp (f : Πi, M₂ →ₗ[R] φ i) (g : M₃ →ₗ[R] M₂) : (pi f).comp g = pi (λi, (f i).comp g) := rfl /-- The projections from a family of modules are linear maps. -/ def proj (i : ι) : (Πi, φ i) →ₗ[R] φ i := ⟨ λa, a i, assume f g, rfl, assume c f, rfl ⟩ @[simp] lemma proj_apply (i : ι) (b : Πi, φ i) : (proj i : (Πi, φ i) →ₗ[R] φ i) b = b i := rfl lemma proj_pi (f : Πi, M₂ →ₗ[R] φ i) (i : ι) : (proj i).comp (pi f) = f i := ext $ assume c, rfl lemma infi_ker_proj : (⨅i, ker (proj i) : submodule R (Πi, φ i)) = ⊥ := bot_unique $ submodule.le_def'.2 $ assume a h, begin simp only [mem_infi, mem_ker, proj_apply] at h, exact (mem_bot _).2 (funext $ assume i, h i) end section variables (R φ) /-- If `I` and `J` are disjoint index sets, the product of the kernels of the `J`th projections of `φ` is linearly equivalent to the product over `I`. -/ def infi_ker_proj_equiv {I J : set ι} [decidable_pred (λi, i ∈ I)] (hd : disjoint I J) (hu : set.univ ⊆ I ∪ J) : (⨅i ∈ J, ker (proj i) : submodule R (Πi, φ i)) ≃ₗ[R] (Πi:I, φ i) := begin refine linear_equiv.of_linear (pi $ λi, (proj (i:ι)).comp (submodule.subtype _)) (cod_restrict _ (pi $ λi, if h : i ∈ I then proj (⟨i, h⟩ : I) else 0) _) _ _, { assume b, simp only [mem_infi, mem_ker, funext_iff, proj_apply, pi_apply], assume j hjJ, have : j ∉ I := assume hjI, hd ⟨hjI, hjJ⟩, rw [dif_neg this, zero_apply] }, { simp only [pi_comp, comp_assoc, subtype_comp_cod_restrict, proj_pi, dif_pos, subtype.coe_prop], ext b ⟨j, hj⟩, refl }, { ext1 ⟨b, hb⟩, apply subtype.ext, ext j, have hb : ∀i ∈ J, b i = 0, { simpa only [mem_infi, mem_ker, proj_apply] using (mem_infi _).1 hb }, simp only [comp_apply, pi_apply, id_apply, proj_apply, subtype_apply, cod_restrict_apply], split_ifs, { refl }, { exact (hb _ $ (hu trivial).resolve_left h).symm } } end end section variable [decidable_eq ι] /-- `diag i j` is the identity map if `i = j`. Otherwise it is the constant 0 map. -/ def diag (i j : ι) : φ i →ₗ[R] φ j := @function.update ι (λj, φ i →ₗ[R] φ j) _ 0 i id j lemma update_apply (f : Πi, M₂ →ₗ[R] φ i) (c : M₂) (i j : ι) (b : M₂ →ₗ[R] φ i) : (update f i b j) c = update (λi, f i c) i (b c) j := begin by_cases j = i, { rw [h, update_same, update_same] }, { rw [update_noteq h, update_noteq h] } end end section variable [decidable_eq ι] variables (R φ) /-- The standard basis of the product of `φ`. -/ def std_basis (i : ι) : φ i →ₗ[R] (Πi, φ i) := pi (diag i) lemma std_basis_apply (i : ι) (b : φ i) : std_basis R φ i b = update 0 i b := by ext j; rw [std_basis, pi_apply, diag, update_apply]; refl @[simp] lemma std_basis_same (i : ι) (b : φ i) : std_basis R φ i b i = b := by rw [std_basis_apply, update_same] lemma std_basis_ne (i j : ι) (h : j ≠ i) (b : φ i) : std_basis R φ i b j = 0 := by rw [std_basis_apply, update_noteq h]; refl lemma ker_std_basis (i : ι) : ker (std_basis R φ i) = ⊥ := ker_eq_bot_of_injective $ assume f g hfg, have std_basis R φ i f i = std_basis R φ i g i := hfg ▸ rfl, by simpa only [std_basis_same] lemma proj_comp_std_basis (i j : ι) : (proj i).comp (std_basis R φ j) = diag j i := by rw [std_basis, proj_pi] lemma proj_std_basis_same (i : ι) : (proj i).comp (std_basis R φ i) = id := by ext b; simp lemma proj_std_basis_ne (i j : ι) (h : i ≠ j) : (proj i).comp (std_basis R φ j) = 0 := by ext b; simp [std_basis_ne R φ _ _ h] lemma supr_range_std_basis_le_infi_ker_proj (I J : set ι) (h : disjoint I J) : (⨆i∈I, range (std_basis R φ i)) ≤ (⨅i∈J, ker (proj i)) := begin refine (supr_le $ assume i, supr_le $ assume hi, range_le_iff_comap.2 _), simp only [(ker_comp _ _).symm, eq_top_iff, le_def', mem_ker, comap_infi, mem_infi], assume b hb j hj, have : i ≠ j := assume eq, h ⟨hi, eq.symm ▸ hj⟩, rw [proj_std_basis_ne R φ j i this.symm, zero_apply] end lemma infi_ker_proj_le_supr_range_std_basis {I : finset ι} {J : set ι} (hu : set.univ ⊆ ↑I ∪ J) : (⨅ i∈J, ker (proj i)) ≤ (⨆i∈I, range (std_basis R φ i)) := submodule.le_def'.2 begin assume b hb, simp only [mem_infi, mem_ker, proj_apply] at hb, rw ← show ∑ i in I, std_basis R φ i (b i) = b, { ext i, rw [finset.sum_apply, ← std_basis_same R φ i (b i)], refine finset.sum_eq_single i (assume j hjI ne, std_basis_ne _ _ _ _ ne.symm _) _, assume hiI, rw [std_basis_same], exact hb _ ((hu trivial).resolve_left hiI) }, exact sum_mem _ (assume i hiI, mem_supr_of_mem i $ mem_supr_of_mem hiI $ (std_basis R φ i).mem_range_self (b i)) end lemma supr_range_std_basis_eq_infi_ker_proj {I J : set ι} (hd : disjoint I J) (hu : set.univ ⊆ I ∪ J) (hI : set.finite I) : (⨆i∈I, range (std_basis R φ i)) = (⨅i∈J, ker (proj i)) := begin refine le_antisymm (supr_range_std_basis_le_infi_ker_proj _ _ _ _ hd) _, have : set.univ ⊆ ↑hI.to_finset ∪ J, { rwa [hI.coe_to_finset] }, refine le_trans (infi_ker_proj_le_supr_range_std_basis R φ this) (supr_le_supr $ assume i, _), rw [set.finite.mem_to_finset], exact le_refl _ end lemma supr_range_std_basis [fintype ι] : (⨆i:ι, range (std_basis R φ i)) = ⊤ := have (set.univ : set ι) ⊆ ↑(finset.univ : finset ι) ∪ ∅ := by rw [finset.coe_univ, set.union_empty], begin apply top_unique, convert (infi_ker_proj_le_supr_range_std_basis R φ this), exact infi_emptyset.symm, exact (funext $ λi, (@supr_pos _ _ _ (λh, range (std_basis R φ i)) $ finset.mem_univ i).symm) end lemma disjoint_std_basis_std_basis (I J : set ι) (h : disjoint I J) : disjoint (⨆i∈I, range (std_basis R φ i)) (⨆i∈J, range (std_basis R φ i)) := begin refine disjoint.mono (supr_range_std_basis_le_infi_ker_proj _ _ _ _ $ set.disjoint_compl_right I) (supr_range_std_basis_le_infi_ker_proj _ _ _ _ $ set.disjoint_compl_right J) _, simp only [disjoint, submodule.le_def', mem_infi, mem_inf, mem_ker, mem_bot, proj_apply, funext_iff], rintros b ⟨hI, hJ⟩ i, classical, by_cases hiI : i ∈ I, { by_cases hiJ : i ∈ J, { exact (h ⟨hiI, hiJ⟩).elim }, { exact hJ i hiJ } }, { exact hI i hiI } end lemma std_basis_eq_single {a : R} : (λ (i : ι), (std_basis R (λ _ : ι, R) i) a) = λ (i : ι), (finsupp.single i a) := begin ext i j, rw [std_basis_apply, finsupp.single_apply], split_ifs, { rw [h, function.update_same] }, { rw [function.update_noteq (ne.symm h)], refl }, end end end pi section fun_left variables (R M) [semiring R] [add_comm_monoid M] [semimodule R M] variables {m n p : Type*} /-- Given an `R`-module `M` and a function `m → n` between arbitrary types, construct a linear map `(n → M) →ₗ[R] (m → M)` -/ def fun_left (f : m → n) : (n → M) →ₗ[R] (m → M) := mk (∘f) (λ _ _, rfl) (λ _ _, rfl) @[simp] theorem fun_left_apply (f : m → n) (g : n → M) (i : m) : fun_left R M f g i = g (f i) := rfl @[simp] theorem fun_left_id (g : n → M) : fun_left R M _root_.id g = g := rfl theorem fun_left_comp (f₁ : n → p) (f₂ : m → n) : fun_left R M (f₁ ∘ f₂) = (fun_left R M f₂).comp (fun_left R M f₁) := rfl /-- Given an `R`-module `M` and an equivalence `m ≃ n` between arbitrary types, construct a linear equivalence `(n → M) ≃ₗ[R] (m → M)` -/ def fun_congr_left (e : m ≃ n) : (n → M) ≃ₗ[R] (m → M) := linear_equiv.of_linear (fun_left R M e) (fun_left R M e.symm) (ext $ λ x, funext $ λ i, by rw [id_apply, ← fun_left_comp, equiv.symm_comp_self, fun_left_id]) (ext $ λ x, funext $ λ i, by rw [id_apply, ← fun_left_comp, equiv.self_comp_symm, fun_left_id]) @[simp] theorem fun_congr_left_apply (e : m ≃ n) (x : n → M) : fun_congr_left R M e x = fun_left R M e x := rfl @[simp] theorem fun_congr_left_id : fun_congr_left R M (equiv.refl n) = linear_equiv.refl R (n → M) := rfl @[simp] theorem fun_congr_left_comp (e₁ : m ≃ n) (e₂ : n ≃ p) : fun_congr_left R M (equiv.trans e₁ e₂) = linear_equiv.trans (fun_congr_left R M e₂) (fun_congr_left R M e₁) := rfl @[simp] lemma fun_congr_left_symm (e : m ≃ n) : (fun_congr_left R M e).symm = fun_congr_left R M e.symm := rfl end fun_left universe i variables [semiring R] [add_comm_monoid M] [semimodule R M] variables (R M) instance automorphism_group : group (M ≃ₗ[R] M) := { mul := λ f g, g.trans f, one := linear_equiv.refl R M, inv := λ f, f.symm, mul_assoc := λ f g h, by {ext, refl}, mul_one := λ f, by {ext, refl}, one_mul := λ f, by {ext, refl}, mul_left_inv := λ f, by {ext, exact f.left_inv x} } instance automorphism_group.to_linear_map_is_monoid_hom : is_monoid_hom (linear_equiv.to_linear_map : (M ≃ₗ[R] M) → (M →ₗ[R] M)) := { map_one := rfl, map_mul := λ f g, rfl } /-- The group of invertible linear maps from `M` to itself -/ @[reducible] def general_linear_group := units (M →ₗ[R] M) namespace general_linear_group variables {R M} instance : has_coe_to_fun (general_linear_group R M) := by apply_instance /-- An invertible linear map `f` determines an equivalence from `M` to itself. -/ def to_linear_equiv (f : general_linear_group R M) : (M ≃ₗ[R] M) := { inv_fun := f.inv.to_fun, left_inv := λ m, show (f.inv * f.val) m = m, by erw f.inv_val; simp, right_inv := λ m, show (f.val * f.inv) m = m, by erw f.val_inv; simp, ..f.val } /-- An equivalence from `M` to itself determines an invertible linear map. -/ def of_linear_equiv (f : (M ≃ₗ[R] M)) : general_linear_group R M := { val := f, inv := f.symm, val_inv := linear_map.ext $ λ _, f.apply_symm_apply _, inv_val := linear_map.ext $ λ _, f.symm_apply_apply _ } variables (R M) /-- The general linear group on `R` and `M` is multiplicatively equivalent to the type of linear equivalences between `M` and itself. -/ def general_linear_equiv : general_linear_group R M ≃* (M ≃ₗ[R] M) := { to_fun := to_linear_equiv, inv_fun := of_linear_equiv, left_inv := λ f, by { ext, refl }, right_inv := λ f, by { ext, refl }, map_mul' := λ x y, by {ext, refl} } @[simp] lemma general_linear_equiv_to_linear_map (f : general_linear_group R M) : (general_linear_equiv R M f : M →ₗ[R] M) = f := by {ext, refl} end general_linear_group end linear_map
b022843dcf24cc0c3e867c90859bfe24f0fa2346
df561f413cfe0a88b1056655515399c546ff32a5
/4-power-world/l5.lean
07eefbbac3b24279bd38ec90e36b764838faeadc
[]
no_license
nicholaspun/natural-number-game-solutions
31d5158415c6f582694680044c5c6469032c2a06
1e2aed86d2e76a3f4a275c6d99e795ad30cf6df0
refs/heads/main
1,675,123,625,012
1,607,633,548,000
1,607,633,548,000
318,933,860
3
1
null
null
null
null
UTF-8
Lean
false
false
218
lean
lemma pow_add (a m n : mynat) : a ^ (m + n) = a ^ m * a ^ n := begin induction n with k Pk, rw add_zero, rw pow_zero, rw mul_one, refl, rw pow_succ, rw ← mul_assoc, rw ← Pk, rw ← pow_succ, rw add_succ, refl, end
2fa20517607a6b7e9b29623a98330ee1a9564b1f
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/analysis/special_functions/trigonometric/arctan_deriv.lean
7f46be4b3f99d6fe539161aee3436cbb4baca778
[ "Apache-2.0" ]
permissive
alreadydone/mathlib
dc0be621c6c8208c581f5170a8216c5ba6721927
c982179ec21091d3e102d8a5d9f5fe06c8fafb73
refs/heads/master
1,685,523,275,196
1,670,184,141,000
1,670,184,141,000
287,574,545
0
0
Apache-2.0
1,670,290,714,000
1,597,421,623,000
Lean
UTF-8
Lean
false
false
7,623
lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes, Abhimanyu Pallavi Sudhir, Jean Lo, Calle Sönne, Benjamin Davidson -/ import analysis.special_functions.trigonometric.arctan import analysis.special_functions.trigonometric.complex_deriv /-! # Derivatives of the `tan` and `arctan` functions. Continuity and derivatives of the tangent and arctangent functions. -/ noncomputable theory namespace real open set filter open_locale topological_space real lemma has_strict_deriv_at_tan {x : ℝ} (h : cos x ≠ 0) : has_strict_deriv_at tan (1 / (cos x)^2) x := by exact_mod_cast (complex.has_strict_deriv_at_tan (by exact_mod_cast h)).real_of_complex lemma has_deriv_at_tan {x : ℝ} (h : cos x ≠ 0) : has_deriv_at tan (1 / (cos x)^2) x := by exact_mod_cast (complex.has_deriv_at_tan (by exact_mod_cast h)).real_of_complex lemma tendsto_abs_tan_of_cos_eq_zero {x : ℝ} (hx : cos x = 0) : tendsto (λ x, abs (tan x)) (𝓝[≠] x) at_top := begin have hx : complex.cos x = 0, by exact_mod_cast hx, simp only [← complex.abs_of_real, complex.of_real_tan], refine (complex.tendsto_abs_tan_of_cos_eq_zero hx).comp _, refine tendsto.inf complex.continuous_of_real.continuous_at _, exact tendsto_principal_principal.2 (λ y, mt complex.of_real_inj.1) end lemma tendsto_abs_tan_at_top (k : ℤ) : tendsto (λ x, abs (tan x)) (𝓝[≠] ((2 * k + 1) * π / 2)) at_top := tendsto_abs_tan_of_cos_eq_zero $ cos_eq_zero_iff.2 ⟨k, rfl⟩ lemma continuous_at_tan {x : ℝ} : continuous_at tan x ↔ cos x ≠ 0 := begin refine ⟨λ hc h₀, _, λ h, (has_deriv_at_tan h).continuous_at⟩, exact not_tendsto_nhds_of_tendsto_at_top (tendsto_abs_tan_of_cos_eq_zero h₀) _ (hc.norm.tendsto.mono_left inf_le_left) end lemma differentiable_at_tan {x : ℝ} : differentiable_at ℝ tan x ↔ cos x ≠ 0 := ⟨λ h, continuous_at_tan.1 h.continuous_at, λ h, (has_deriv_at_tan h).differentiable_at⟩ @[simp] lemma deriv_tan (x : ℝ) : deriv tan x = 1 / (cos x)^2 := if h : cos x = 0 then have ¬differentiable_at ℝ tan x := mt differentiable_at_tan.1 (not_not.2 h), by simp [deriv_zero_of_not_differentiable_at this, h, sq] else (has_deriv_at_tan h).deriv @[simp] lemma cont_diff_at_tan {n x} : cont_diff_at ℝ n tan x ↔ cos x ≠ 0 := ⟨λ h, continuous_at_tan.1 h.continuous_at, λ h, (complex.cont_diff_at_tan.2 $ by exact_mod_cast h).real_of_complex⟩ lemma has_deriv_at_tan_of_mem_Ioo {x : ℝ} (h : x ∈ Ioo (-(π/2):ℝ) (π/2)) : has_deriv_at tan (1 / (cos x)^2) x := has_deriv_at_tan (cos_pos_of_mem_Ioo h).ne' lemma differentiable_at_tan_of_mem_Ioo {x : ℝ} (h : x ∈ Ioo (-(π/2):ℝ) (π/2)) : differentiable_at ℝ tan x := (has_deriv_at_tan_of_mem_Ioo h).differentiable_at lemma has_strict_deriv_at_arctan (x : ℝ) : has_strict_deriv_at arctan (1 / (1 + x^2)) x := have A : cos (arctan x) ≠ 0 := (cos_arctan_pos x).ne', by simpa [cos_sq_arctan] using tan_local_homeomorph.has_strict_deriv_at_symm trivial (by simpa) (has_strict_deriv_at_tan A) lemma has_deriv_at_arctan (x : ℝ) : has_deriv_at arctan (1 / (1 + x^2)) x := (has_strict_deriv_at_arctan x).has_deriv_at lemma differentiable_at_arctan (x : ℝ) : differentiable_at ℝ arctan x := (has_deriv_at_arctan x).differentiable_at lemma differentiable_arctan : differentiable ℝ arctan := differentiable_at_arctan @[simp] lemma deriv_arctan : deriv arctan = (λ x, 1 / (1 + x^2)) := funext $ λ x, (has_deriv_at_arctan x).deriv lemma cont_diff_arctan {n : ℕ∞} : cont_diff ℝ n arctan := cont_diff_iff_cont_diff_at.2 $ λ x, have cos (arctan x) ≠ 0 := (cos_arctan_pos x).ne', tan_local_homeomorph.cont_diff_at_symm_deriv (by simpa) trivial (has_deriv_at_tan this) (cont_diff_at_tan.2 this) end real section /-! ### Lemmas for derivatives of the composition of `real.arctan` with a differentiable function In this section we register lemmas for the derivatives of the composition of `real.arctan` with a differentiable function, for standalone use and use with `simp`. -/ open real section deriv variables {f : ℝ → ℝ} {f' x : ℝ} {s : set ℝ} lemma has_strict_deriv_at.arctan (hf : has_strict_deriv_at f f' x) : has_strict_deriv_at (λ x, arctan (f x)) ((1 / (1 + (f x)^2)) * f') x := (real.has_strict_deriv_at_arctan (f x)).comp x hf lemma has_deriv_at.arctan (hf : has_deriv_at f f' x) : has_deriv_at (λ x, arctan (f x)) ((1 / (1 + (f x)^2)) * f') x := (real.has_deriv_at_arctan (f x)).comp x hf lemma has_deriv_within_at.arctan (hf : has_deriv_within_at f f' s x) : has_deriv_within_at (λ x, arctan (f x)) ((1 / (1 + (f x)^2)) * f') s x := (real.has_deriv_at_arctan (f x)).comp_has_deriv_within_at x hf lemma deriv_within_arctan (hf : differentiable_within_at ℝ f s x) (hxs : unique_diff_within_at ℝ s x) : deriv_within (λ x, arctan (f x)) s x = (1 / (1 + (f x)^2)) * (deriv_within f s x) := hf.has_deriv_within_at.arctan.deriv_within hxs @[simp] lemma deriv_arctan (hc : differentiable_at ℝ f x) : deriv (λ x, arctan (f x)) x = (1 / (1 + (f x)^2)) * (deriv f x) := hc.has_deriv_at.arctan.deriv end deriv section fderiv variables {E : Type*} [normed_add_comm_group E] [normed_space ℝ E] {f : E → ℝ} {f' : E →L[ℝ] ℝ} {x : E} {s : set E} {n : ℕ∞} lemma has_strict_fderiv_at.arctan (hf : has_strict_fderiv_at f f' x) : has_strict_fderiv_at (λ x, arctan (f x)) ((1 / (1 + (f x)^2)) • f') x := (has_strict_deriv_at_arctan (f x)).comp_has_strict_fderiv_at x hf lemma has_fderiv_at.arctan (hf : has_fderiv_at f f' x) : has_fderiv_at (λ x, arctan (f x)) ((1 / (1 + (f x)^2)) • f') x := (has_deriv_at_arctan (f x)).comp_has_fderiv_at x hf lemma has_fderiv_within_at.arctan (hf : has_fderiv_within_at f f' s x) : has_fderiv_within_at (λ x, arctan (f x)) ((1 / (1 + (f x)^2)) • f') s x := (has_deriv_at_arctan (f x)).comp_has_fderiv_within_at x hf lemma fderiv_within_arctan (hf : differentiable_within_at ℝ f s x) (hxs : unique_diff_within_at ℝ s x) : fderiv_within ℝ (λ x, arctan (f x)) s x = (1 / (1 + (f x)^2)) • (fderiv_within ℝ f s x) := hf.has_fderiv_within_at.arctan.fderiv_within hxs @[simp] lemma fderiv_arctan (hc : differentiable_at ℝ f x) : fderiv ℝ (λ x, arctan (f x)) x = (1 / (1 + (f x)^2)) • (fderiv ℝ f x) := hc.has_fderiv_at.arctan.fderiv lemma differentiable_within_at.arctan (hf : differentiable_within_at ℝ f s x) : differentiable_within_at ℝ (λ x, real.arctan (f x)) s x := hf.has_fderiv_within_at.arctan.differentiable_within_at @[simp] lemma differentiable_at.arctan (hc : differentiable_at ℝ f x) : differentiable_at ℝ (λ x, arctan (f x)) x := hc.has_fderiv_at.arctan.differentiable_at lemma differentiable_on.arctan (hc : differentiable_on ℝ f s) : differentiable_on ℝ (λ x, arctan (f x)) s := λ x h, (hc x h).arctan @[simp] lemma differentiable.arctan (hc : differentiable ℝ f) : differentiable ℝ (λ x, arctan (f x)) := λ x, (hc x).arctan lemma cont_diff_at.arctan (h : cont_diff_at ℝ n f x) : cont_diff_at ℝ n (λ x, arctan (f x)) x := cont_diff_arctan.cont_diff_at.comp x h lemma cont_diff.arctan (h : cont_diff ℝ n f) : cont_diff ℝ n (λ x, arctan (f x)) := cont_diff_arctan.comp h lemma cont_diff_within_at.arctan (h : cont_diff_within_at ℝ n f s x) : cont_diff_within_at ℝ n (λ x, arctan (f x)) s x := cont_diff_arctan.comp_cont_diff_within_at h lemma cont_diff_on.arctan (h : cont_diff_on ℝ n f s) : cont_diff_on ℝ n (λ x, arctan (f x)) s := cont_diff_arctan.comp_cont_diff_on h end fderiv end
0078db3c65f2d6c75acfa38e4539e5c793ead601
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/1275.lean
1777a836f2f16db2fa6d425dda36f876ff3b7379
[ "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
590
lean
import Lean open Lean syntax "👉" (ident <|> "_") : term #check fun x => `(👉 $x) #eval match Unhygienic.run `(👉 _) with | `(👉 $_:ident) => false | `(👉 _) => true | _ => false #eval match Unhygienic.run `(👉 x) with | `(👉 _) => false | `(👉 $_:ident) => true | _ => false syntax "bar" (&"baz" <|> &"boing") : term #check fun x => `(bar $x) #eval match Unhygienic.run `(bar boing) with | `(bar baz) => false | `(bar boing) => true | _ => false #eval match Unhygienic.run `(bar baz) with | `(bar boing) => false | `(bar baz) => true | _ => false
4e51662d1edcc30bea42b489e00957d799d258be
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/123-2.lean
190e28b209dba37bddf09ca09ede43903bfb25b2
[ "Apache-2.0" ]
permissive
leanprover-community/lean
12b87f69d92e614daea8bcc9d4de9a9ace089d0e
cce7990ea86a78bdb383e38ed7f9b5ba93c60ce0
refs/heads/master
1,687,508,156,644
1,684,951,104,000
1,684,951,104,000
169,960,991
457
107
Apache-2.0
1,686,744,372,000
1,549,790,268,000
C++
UTF-8
Lean
false
false
1,931
lean
open function class semiring (R : Type*) extends has_mul R, has_add R, has_one R, has_zero R. class comm_semiring (R : Type*) extends semiring R. class comm_ring (R : Type*) extends comm_semiring R. class has_scalar' (R : Type*) (A : Type*) := (smul : R → A → A) infixr ` • `:73 := has_scalar'.smul structure ring_hom' (M : Type*) (N : Type*) [semiring M] [semiring N] := (to_fun : M → N) (map_one' : to_fun 1 = 1) (map_mul' : ∀ x y, to_fun (x * y) = to_fun x * to_fun y) (map_zero' : to_fun 0 = 0) (map_add' : ∀ x y, to_fun (x + y) = to_fun x + to_fun y) instance (α : Type*) (β : Type*) [semiring α] [semiring β] : has_coe_to_fun (ring_hom' α β) (λ _, α → β) := ⟨λ f, ring_hom'.to_fun (f)⟩ class algebra' (R : Type*) (A : Type*) [comm_semiring R] [semiring A] extends has_scalar' R A, ring_hom' R A := (commutes' : ∀ r x, to_fun r * x = x * to_fun r) (smul_def' : ∀ r x, r • x = to_fun r * x) def algebra_map' (R : Type*) (A : Type*) [comm_semiring R] [semiring A] [algebra' R A] : ring_hom' R A := algebra'.to_ring_hom' structure alg_hom' (R : Type*) (A : Type*) (B : Type*) [comm_semiring R] [semiring A] [semiring B] [algebra' R A] [algebra' R B] extends ring_hom' A B := (commutes' : ∀ r : R, to_fun (algebra_map' R A r) = algebra_map' R B r) variables {R : Type*} {A : Type*} {B : Type*} variables [comm_semiring R] [semiring A] [semiring B] variables [algebra' R A] [algebra' R B] instance : has_coe_to_fun (alg_hom' R A B) (λ _, A → B) := ⟨λ f, f.to_fun⟩ def quot.lift {R : Type} [comm_ring R] {A : Type} [comm_ring A] [algebra' R A] {B : Type*} [comm_ring B] [algebra' R B] {C : Type} [comm_ring C] [algebra' R C] (f : alg_hom' R A B) (hf : surjective f) (g : alg_hom' R A C) (hfg : ∀ a : A, f a = 0 → g a = 0) : alg_hom' R B C := { to_fun := λ b, _, map_one' := _, map_mul' := _, map_zero' := _, map_add' := _, commutes' := _ }
4868fd7c11d43229318dc9a22abc74e31833d26f
86f6f4f8d827a196a32bfc646234b73328aeb306
/examples/logic/unnamed_24.lean
84424f81e8f56c8c54b68e7e97b366062ee5723b
[]
no_license
jamescheuk91/mathematics_in_lean
09f1f87d2b0dce53464ff0cbe592c568ff59cf5e
4452499264e2975bca2f42565c0925506ba5dda3
refs/heads/master
1,679,716,410,967
1,613,957,947,000
1,613,957,947,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
81
lean
import data.real.basic -- BEGIN #check ∀ x : ℝ, 0 ≤ x → abs x = x -- END
0b37d13ddfeb41889b69038833312bbe44bf36d6
562dafcca9e8bf63ce6217723b51f32e89cdcc80
/src/super/defs.lean
6523b50692e96f3be2578ae494203a80ed0cfb90
[]
no_license
digama0/super
660801ef3edab2c046d6a01ba9bbce53e41523e8
976957fe46128e6ef057bc771f532c27cce5a910
refs/heads/master
1,606,987,814,510
1,498,621,778,000
1,498,621,778,000
95,626,306
0
0
null
1,498,621,692,000
1,498,621,692,000
null
UTF-8
Lean
false
false
1,095
lean
/- Copyright (c) 2017 Gabriel Ebner. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Gabriel Ebner -/ import .clause_ops .prover_state open tactic expr monad namespace super meta def try_unfold_one_def (type : expr) : tactic expr := dunfold_expr_core transparency.all type meta def try_unfold_def_left (c : clause) (i : ℕ) : tactic (list clause) := on_left_at c i $ λt, do t' ← try_unfold_one_def t, ht' ← mk_local_def `h t', return [([ht'], ht')] meta def try_unfold_def_right (c : clause) (i : ℕ) : tactic (list clause) := on_right_at c i $ λh, do t' ← try_unfold_one_def h.local_type, hnt' ← mk_local_def `h (imp t' c.local_false), return [([hnt'], app hnt' h)] @[super.inf] meta def unfold_def_inf : inf_decl := inf_decl.mk 40 $ take given, sequence' $ do r ← [try_unfold_def_right, try_unfold_def_left], -- NOTE: we cannot restrict to selected literals here -- as this might prevent factoring, e.g. _n>0_ ∨ is_pos(0) i ← list.range given.c.num_lits, [inf_if_successful 3 given (r given.c i)] end super
7b0bab67785f5f3288f6b43b3e131cdb26c50607
592ee40978ac7604005a4e0d35bbc4b467389241
/Library/generated/mathscheme-lean/Zero.lean
f4cf1a5382c2c8bd3e57b6be9633809aa0ec66cc
[]
no_license
ysharoda/Deriving-Definitions
3e149e6641fae440badd35ac110a0bd705a49ad2
dfecb27572022de3d4aa702cae8db19957523a59
refs/heads/master
1,679,127,857,700
1,615,939,007,000
1,615,939,007,000
229,785,731
4
0
null
null
null
null
UTF-8
Lean
false
false
6,240
lean
import init.data.nat.basic import init.data.fin.basic import data.vector import .Prelude open Staged open nat open fin open vector section Zero structure Zero (A : Type) : Type := (e : A) (op : (A → (A → A))) (leftZero_op_e : (∀ {x : A} , (op e x) = e)) (rightZero_op_e : (∀ {x : A} , (op x e) = e)) open Zero structure Sig (AS : Type) : Type := (eS : AS) (opS : (AS → (AS → AS))) structure Product (A : Type) : Type := (eP : (Prod A A)) (opP : ((Prod A A) → ((Prod A A) → (Prod A A)))) (leftZero_op_eP : (∀ {xP : (Prod A A)} , (opP eP xP) = eP)) (rightZero_op_eP : (∀ {xP : (Prod A A)} , (opP xP eP) = eP)) structure Hom {A1 : Type} {A2 : Type} (Ze1 : (Zero A1)) (Ze2 : (Zero A2)) : Type := (hom : (A1 → A2)) (pres_e : (hom (e Ze1)) = (e Ze2)) (pres_op : (∀ {x1 x2 : A1} , (hom ((op Ze1) x1 x2)) = ((op Ze2) (hom x1) (hom x2)))) structure RelInterp {A1 : Type} {A2 : Type} (Ze1 : (Zero A1)) (Ze2 : (Zero A2)) : Type 1 := (interp : (A1 → (A2 → Type))) (interp_e : (interp (e Ze1) (e Ze2))) (interp_op : (∀ {x1 x2 : A1} {y1 y2 : A2} , ((interp x1 y1) → ((interp x2 y2) → (interp ((op Ze1) x1 x2) ((op Ze2) y1 y2)))))) inductive ZeroTerm : Type | eL : ZeroTerm | opL : (ZeroTerm → (ZeroTerm → ZeroTerm)) open ZeroTerm inductive ClZeroTerm (A : Type) : Type | sing : (A → ClZeroTerm) | eCl : ClZeroTerm | opCl : (ClZeroTerm → (ClZeroTerm → ClZeroTerm)) open ClZeroTerm inductive OpZeroTerm (n : ℕ) : Type | v : ((fin n) → OpZeroTerm) | eOL : OpZeroTerm | opOL : (OpZeroTerm → (OpZeroTerm → OpZeroTerm)) open OpZeroTerm inductive OpZeroTerm2 (n : ℕ) (A : Type) : Type | v2 : ((fin n) → OpZeroTerm2) | sing2 : (A → OpZeroTerm2) | eOL2 : OpZeroTerm2 | opOL2 : (OpZeroTerm2 → (OpZeroTerm2 → OpZeroTerm2)) open OpZeroTerm2 def simplifyCl {A : Type} : ((ClZeroTerm A) → (ClZeroTerm A)) | eCl := eCl | (opCl x1 x2) := (opCl (simplifyCl x1) (simplifyCl x2)) | (sing x1) := (sing x1) def simplifyOpB {n : ℕ} : ((OpZeroTerm n) → (OpZeroTerm n)) | eOL := eOL | (opOL x1 x2) := (opOL (simplifyOpB x1) (simplifyOpB x2)) | (v x1) := (v x1) def simplifyOp {n : ℕ} {A : Type} : ((OpZeroTerm2 n A) → (OpZeroTerm2 n A)) | eOL2 := eOL2 | (opOL2 x1 x2) := (opOL2 (simplifyOp x1) (simplifyOp x2)) | (v2 x1) := (v2 x1) | (sing2 x1) := (sing2 x1) def evalB {A : Type} : ((Zero A) → (ZeroTerm → A)) | Ze eL := (e Ze) | Ze (opL x1 x2) := ((op Ze) (evalB Ze x1) (evalB Ze x2)) def evalCl {A : Type} : ((Zero A) → ((ClZeroTerm A) → A)) | Ze (sing x1) := x1 | Ze eCl := (e Ze) | Ze (opCl x1 x2) := ((op Ze) (evalCl Ze x1) (evalCl Ze x2)) def evalOpB {A : Type} {n : ℕ} : ((Zero A) → ((vector A n) → ((OpZeroTerm n) → A))) | Ze vars (v x1) := (nth vars x1) | Ze vars eOL := (e Ze) | Ze vars (opOL x1 x2) := ((op Ze) (evalOpB Ze vars x1) (evalOpB Ze vars x2)) def evalOp {A : Type} {n : ℕ} : ((Zero A) → ((vector A n) → ((OpZeroTerm2 n A) → A))) | Ze vars (v2 x1) := (nth vars x1) | Ze vars (sing2 x1) := x1 | Ze vars eOL2 := (e Ze) | Ze vars (opOL2 x1 x2) := ((op Ze) (evalOp Ze vars x1) (evalOp Ze vars x2)) def inductionB {P : (ZeroTerm → Type)} : ((P eL) → ((∀ (x1 x2 : ZeroTerm) , ((P x1) → ((P x2) → (P (opL x1 x2))))) → (∀ (x : ZeroTerm) , (P x)))) | pel popl eL := pel | pel popl (opL x1 x2) := (popl _ _ (inductionB pel popl x1) (inductionB pel popl x2)) def inductionCl {A : Type} {P : ((ClZeroTerm A) → Type)} : ((∀ (x1 : A) , (P (sing x1))) → ((P eCl) → ((∀ (x1 x2 : (ClZeroTerm A)) , ((P x1) → ((P x2) → (P (opCl x1 x2))))) → (∀ (x : (ClZeroTerm A)) , (P x))))) | psing pecl popcl (sing x1) := (psing x1) | psing pecl popcl eCl := pecl | psing pecl popcl (opCl x1 x2) := (popcl _ _ (inductionCl psing pecl popcl x1) (inductionCl psing pecl popcl x2)) def inductionOpB {n : ℕ} {P : ((OpZeroTerm n) → Type)} : ((∀ (fin : (fin n)) , (P (v fin))) → ((P eOL) → ((∀ (x1 x2 : (OpZeroTerm n)) , ((P x1) → ((P x2) → (P (opOL x1 x2))))) → (∀ (x : (OpZeroTerm n)) , (P x))))) | pv peol popol (v x1) := (pv x1) | pv peol popol eOL := peol | pv peol popol (opOL x1 x2) := (popol _ _ (inductionOpB pv peol popol x1) (inductionOpB pv peol popol x2)) def inductionOp {n : ℕ} {A : Type} {P : ((OpZeroTerm2 n A) → Type)} : ((∀ (fin : (fin n)) , (P (v2 fin))) → ((∀ (x1 : A) , (P (sing2 x1))) → ((P eOL2) → ((∀ (x1 x2 : (OpZeroTerm2 n A)) , ((P x1) → ((P x2) → (P (opOL2 x1 x2))))) → (∀ (x : (OpZeroTerm2 n A)) , (P x)))))) | pv2 psing2 peol2 popol2 (v2 x1) := (pv2 x1) | pv2 psing2 peol2 popol2 (sing2 x1) := (psing2 x1) | pv2 psing2 peol2 popol2 eOL2 := peol2 | pv2 psing2 peol2 popol2 (opOL2 x1 x2) := (popol2 _ _ (inductionOp pv2 psing2 peol2 popol2 x1) (inductionOp pv2 psing2 peol2 popol2 x2)) def stageB : (ZeroTerm → (Staged ZeroTerm)) | eL := (Now eL) | (opL x1 x2) := (stage2 opL (codeLift2 opL) (stageB x1) (stageB x2)) def stageCl {A : Type} : ((ClZeroTerm A) → (Staged (ClZeroTerm A))) | (sing x1) := (Now (sing x1)) | eCl := (Now eCl) | (opCl x1 x2) := (stage2 opCl (codeLift2 opCl) (stageCl x1) (stageCl x2)) def stageOpB {n : ℕ} : ((OpZeroTerm n) → (Staged (OpZeroTerm n))) | (v x1) := (const (code (v x1))) | eOL := (Now eOL) | (opOL x1 x2) := (stage2 opOL (codeLift2 opOL) (stageOpB x1) (stageOpB x2)) def stageOp {n : ℕ} {A : Type} : ((OpZeroTerm2 n A) → (Staged (OpZeroTerm2 n A))) | (sing2 x1) := (Now (sing2 x1)) | (v2 x1) := (const (code (v2 x1))) | eOL2 := (Now eOL2) | (opOL2 x1 x2) := (stage2 opOL2 (codeLift2 opOL2) (stageOp x1) (stageOp x2)) structure StagedRepr (A : Type) (Repr : (Type → Type)) : Type := (eT : (Repr A)) (opT : ((Repr A) → ((Repr A) → (Repr A)))) end Zero
adc0611ebafa1e6229c63181787e2938a3464656
ec5e5a9dbe7f60fa5784d15211d8bf24ada0825c
/src/LLVMLib.lean
37ec3db0c948ca8f9f4d59281d7f24755d038181
[]
no_license
pnwamk/lean-llvm
fcd9a828e52e80eb197f7d9032b3846f2e09ef74
ebc3bca9a57a6aef29529d46394f560398fb5c9c
refs/heads/master
1,668,418,078,706
1,593,548,643,000
1,593,548,643,000
258,617,753
0
0
null
1,587,760,298,000
1,587,760,298,000
null
UTF-8
Lean
false
false
23,312
lean
import Init.Data.Array import Init.Data.Int import Init.Data.RBMap import Init.System.IO import LeanLLVM.AST import LeanLLVM.PP import LeanLLVM.Parser import LeanLLVM.DataLayout import LeanLLVM.LLVMFFI namespace Option universes u v def mapM {m:Type u → Type v} {α β:Type u} [Applicative m] (f:α → m β) : Option α → m (Option β) | none => pure none | some x => some <$> f x end Option -- Type for pointers -- -- USize compiles to a size_t when unboxed. Technically pointers -- should map to intptr_t instead of size_t, but `size_t` is the -- same size on x86_64. structure Ptr := (val : USize) namespace Ptr protected def toString (x:Ptr) : String := "0x" ++ (Nat.toDigits 16 x.val.toNat).asString instance : HasToString Ptr := ⟨Ptr.toString⟩ end Ptr namespace LLVM @[reducible] def aliasMap := RBMap String TypeDeclBody (λx y => decide (x < y)). @[reducible] def visitMap := RBMap String Unit (λx y => decide (x < y)). @[reducible] def extract (a:Type) : Type := IO.Ref (aliasMap × visitMap) -> IO a. namespace extract instance monad : Monad extract := { bind := λa b mx mf r => mx r >>= λx => mf x r , pure := λa x r => pure x } instance monadExcept : MonadExcept IO.Error extract := { throw := λa err r => throw err , catch := λa m handle r => catch (m r) (λerr => handle err r) } instance mIO : MonadIO extract := { monadLift := λa m r => m } def run {a:Type} (m:extract a) : IO (aliasMap × a) := do r <- IO.mkRef (RBMap.empty, RBMap.empty); a <- m r; (mp,_) <- r.get; pure (mp, a) -- Execute this action when extracting a named structure -- type. This will track the set of already-visited aliases. -- If the named type has previously been visited, this -- action will return true. If false, the type alias definition -- still needs to be converted. It is important to call 'visit' -- on a named type before extracting its definition to break recursive -- cycles in structure definitions. def visit (nm:String) : extract Bool := λref => do (am,vm) <- ref.get; match vm.find? nm with | some () => pure true | none => do let vm' := RBMap.insert vm nm (); ref.set (am, vm'); pure false -- After visiting a named structure type, this action should be -- called to register the body of the named alias. def define (nm:String) (body:TypeDeclBody) : extract Unit := λref => do (am,vm) <- ref.get; let am' := RBMap.insert am nm body; ref.set (am',vm); pure () end extract section open Code def typeIsVoid (tp : FFI.Type_) : IO Bool := do id <- FFI.getTypeTag tp; match id with | TypeID.void => pure true | _ => pure false def throwError {α} (msg:String): extract α := throw (IO.userError msg) partial def extractType : FFI.Type_ → extract LLVMType | tp => do id <- monadLift $ FFI.getTypeTag tp; match id with | TypeID.void => pure $ PrimType.void | TypeID.half => pure $ FloatType.half | TypeID.float => pure $ FloatType.float | TypeID.double => pure $ FloatType.double | TypeID.x86FP80 => pure $ FloatType.x86FP80 | TypeID.fp128 => pure $ FloatType.fp128 | TypeID.ppcFP128 => pure $ FloatType.ppcFP128 | TypeID.label => pure $ PrimType.label | TypeID.metadata => pure $ PrimType.metadata | TypeID.x86mmx => pure $ PrimType.x86mmx | TypeID.token => pure $ PrimType.token | TypeID.integer => monadLift $ (λn => PrimType.integer n) <$> FFI.getIntegerTypeWidth tp | TypeID.function => do dt <- monadLift (FFI.getFunctionTypeData tp); match dt with | some (ret, args, varargs) => do ret' <- extractType ret; args' <- Array.mapM extractType args; pure $ LLVMType.funType ret' args' varargs | none => throwError "expected function type!" | TypeID.struct => do tn <- monadLift $ FFI.getTypeName tp; match tn with -- named struct type, check if we need to traverse the type definition | some nm => do alreadyVisited <- extract.visit nm; -- only recurse into the definition if this is the first time -- we've encountered this named type unless alreadyVisited $ (do opq <- monadLift $ FFI.typeIsOpaque tp; match opq with | true => extract.define nm TypeDeclBody.opaque | false => do dt <- monadLift $ FFI.getStructTypeData tp; match dt with | some (packed, tps) => do tps' <- Array.mapM extractType tps; extract.define nm (TypeDeclBody.defn (LLVMType.struct packed tps')) | none => throwError "expected struct type!"); pure $ LLVMType.alias nm -- literal struct type, recurse into it's definition | none => do dt <- monadLift $ FFI.getStructTypeData tp; match dt with | some (packed, tps) => LLVMType.struct packed <$> Array.mapM extractType tps | none => throwError "expected struct type!" | TypeID.array => do dt <- monadLift (FFI.getSequentialTypeData tp); match dt with | some (n, el) => LLVMType.array n <$> extractType el | none => throwError "expected array type!" | TypeID.pointer => do eltp <- monadLift (FFI.getPointerElementType tp); match eltp with | none => throwError "expected pointer type!" | some x => LLVMType.ptr <$> extractType x | TypeID.vector => do dt <- monadLift (FFI.getSequentialTypeData tp); match dt with | some (n, el) => LLVMType.vector n <$> extractType el | none => throwError "expected vector type!" end def InstrMap := RBMap FFI.Instruction Ident FFI.instructionLt def BBMap := RBMap FFI.BasicBlock BlockLabel FFI.basicBlockLt def BBMap.empty : BBMap := RBMap.empty structure ValueContext := (funArgs : Array (Typed Ident)) (imap : InstrMap) (bmap : BBMap) def ValueContext.empty : ValueContext := { funArgs := Array.empty, imap := RBMap.empty, bmap := RBMap.empty, } def extractArgs (fn : FFI.Function) : extract (Nat × Array (Typed Ident)) := do rawargs <- monadLift (FFI.getFunctionArgs fn); Array.iterateM rawargs (0, Array.empty) $ λ _ a b => do let (mnm, rawtp) := a; let (counter, args) := b; tp <- extractType rawtp; match mnm with | none => pure (counter+1, Array.push args ⟨tp, Ident.anon counter⟩) | some nm => pure (counter, Array.push args ⟨tp, Ident.named nm⟩) def extractBBLabel (bb:FFI.BasicBlock) (c:Nat) : extract (Nat × BlockLabel) := do nm <- monadLift (FFI.getBBName bb); match nm with | none => pure (c+1, ⟨Ident.anon c⟩) | some nm => pure (c , ⟨Ident.named nm⟩) def foo (b:Bool) : IO Nat := do when b $ (do IO.println "Hello"; IO.println "World"); pure 1 def computeInstructionNumbering (rawbb:FFI.BasicBlock) (c0:Nat) (imap0:InstrMap) : extract (Nat × InstrMap) := do instrarr <- monadLift (FFI.getInstructionArray rawbb); Array.iterateM instrarr (c0, imap0) $ λ _ rawi st => do let (c,imap) := st; tp <- monadLift (FFI.getInstructionType rawi); isv <- monadLift (typeIsVoid tp); if isv then pure (c,imap) else do mnm <- monadLift (FFI.getInstructionName rawi); match mnm with | some nm => pure (c, RBMap.insert imap rawi (Ident.named nm)) | none => pure (c+1, RBMap.insert imap rawi (Ident.anon c)) def computeNumberings (c0:Nat) (fn:FFI.Function) : extract (BBMap × InstrMap) := do bbarr <- monadLift (FFI.getBasicBlockArray fn); (_,finalbmap, finalimap) <- Array.iterateM bbarr (c0, BBMap.empty, (RBMap.empty : InstrMap)) $ (λ_ rawbb st => do let (c, bmap, imap) := st; (c', blab) <- extractBBLabel rawbb c; bmap' <- pure (RBMap.insert bmap rawbb blab); (c'', imap') <- computeInstructionNumbering rawbb c' imap; pure (c'',bmap',imap')); pure (finalbmap, finalimap) partial def extractConstant : FFI.Constant -> extract Value | rawc => do let extractTypedConstant (c:FFI.Constant) : extract (Typed Value) := (do tp <- monadLift (FFI.getValueType c) >>= extractType; x <- extractConstant c; pure ⟨tp, x⟩); tag <- monadLift (FFI.getConstantTag rawc); match tag with | Code.Const.ConstantInt => do d <- monadLift (FFI.getConstIntData rawc); match d with | some (_w, v) => pure (Value.integer (Int.ofNat v)) | none => throwError "expected constant integer value" | Code.Const.Function => do nm <- monadLift (FFI.getConstantName rawc); match nm with | some s => pure (Symbol.mk s) | none => throwError "expected function value" | Code.Const.GlobalVariable => do nm <- monadLift (FFI.getConstantName rawc); match nm with | some s => pure (Symbol.mk s) | none => throwError "expected global variable" | Code.Const.ConstantPointerNull => pure Value.null | Code.Const.ConstantDataArray => do md <- monadLift (FFI.getConstArrayData rawc); match md with | none => throwError "expected constant array" | some (elty, cs) => do elty' <- extractType elty; cs' <- cs.mapM extractConstant; pure (Value.array elty' cs') | Code.Const.ConstantExpr => do md <- monadLift (FFI.getConstExprData rawc); match md with | none => throwError "expected constant expression" | some (op, xs) => match op with | Code.Instr.GetElementPtr => do cs <- Array.mapM extractTypedConstant xs; pure $ ConstExpr.gep false none PrimType.void cs | _ => throwError $ "unexpected (or unimplemented) constant instruction opcode: " ++ op.asString | _ => throwError $ "unknown constant value: " ++ tag.asString def extractValue (ctx:ValueContext) (rawv:FFI.Value) : extract Value := do decmp <- monadLift (FFI.decomposeValue rawv); match decmp with | FFI.ValueView.constantView c => extractConstant c | FFI.ValueView.argument n => match Array.get? ctx.funArgs n with | none => throwError "invalid argument value" | some i => pure (Value.ident i.value) | FFI.ValueView.instruction i => match RBMap.find? ctx.imap i with | none => throwError "invalid instruction value" | some i => pure (Value.ident i) | FFI.ValueView.block b => throwError "unimplemented: basic block value" | FFI.ValueView.unknown => throwError "unknown value" def extractBlockLabel (ctx:ValueContext) (bb:FFI.BasicBlock) : extract BlockLabel := match RBMap.find? ctx.bmap bb with | none => throwError "unknown basic block" | some lab => pure lab def extractTypedValue (ctx:ValueContext) (rawv:FFI.Value) : extract (Typed Value) := do tp <- monadLift (FFI.getValueType rawv) >>= extractType; v <- extractValue ctx rawv; pure ⟨tp, v⟩ def extractBinaryOp (rawInstr:FFI.Instruction) (ctx:ValueContext) (f:Typed Value → Value → Instruction) : extract Instruction := do x <- monadLift (FFI.getBinaryOperatorValues rawInstr); match x with | none => throwError "expected binary operation" | some (o1,o2) => do v1 <- extractTypedValue ctx o1; v2 <- extractTypedValue ctx o2; pure (f v1 v2.value) def extractCastOp (rawinstr:FFI.Instruction) (ctx:ValueContext) (f:Typed Value → LLVMType → Instruction) : extract Instruction := do x <- monadLift (FFI.getCastInstData rawinstr); match x with | none => throwError "expected conversion instruction" | some (_op, v) => do tv <- extractTypedValue ctx v; outty <- monadLift (FFI.getInstructionType rawinstr) >>= extractType; pure (f tv outty) def extractICmpOp (n:Code.ICmp) : ICmpOp := match n with | Code.ICmp.eq => ICmpOp.ieq | Code.ICmp.ne => ICmpOp.ine | Code.ICmp.ugt => ICmpOp.iugt | Code.ICmp.uge => ICmpOp.iuge | Code.ICmp.ult => ICmpOp.iult | Code.ICmp.ule => ICmpOp.iule | Code.ICmp.sgt => ICmpOp.isgt | Code.ICmp.sge => ICmpOp.isge | Code.ICmp.slt => ICmpOp.islt | Code.ICmp.sle => ICmpOp.isle def extractInstruction (rawinstr:FFI.Instruction) (ctx:ValueContext) : extract Instruction := do op <- monadLift (FFI.getInstructionOpcode rawinstr); tp <- monadLift (FFI.getInstructionType rawinstr) >>= extractType; match op with -- == terminators == -- return | Code.Instr.Ret => do mv <- monadLift (FFI.getInstructionReturnValue rawinstr); match mv with | none => pure Instruction.retVoid | some v => Instruction.ret <$> extractTypedValue ctx v -- br | Code.Instr.Br => do d <- monadLift (FFI.getBranchInstData rawinstr); match d with | none => throwError "expected branch instruction" | some (FFI.BranchView.unconditional b) => Instruction.jump <$> extractBlockLabel ctx b | some (FFI.BranchView.conditional c t f) => do cv <- extractTypedValue ctx c; tl <- extractBlockLabel ctx t; fl <- extractBlockLabel ctx f; pure (Instruction.br cv tl fl) -- unreachable | Code.Instr.Unreachable => pure Instruction.unreachable -- == binary operators == -- add | Code.Instr.Add => do uov <- monadLift (FFI.hasNoUnsignedWrap rawinstr); sov <- monadLift (FFI.hasNoSignedWrap rawinstr); extractBinaryOp rawinstr ctx (Instruction.arith (ArithOp.add uov sov)) -- fadd | Code.Instr.FAdd => extractBinaryOp rawinstr ctx (Instruction.arith ArithOp.fadd) -- sub | Code.Instr.Sub => do uov <- monadLift (FFI.hasNoUnsignedWrap rawinstr); sov <- monadLift (FFI.hasNoSignedWrap rawinstr); extractBinaryOp rawinstr ctx (Instruction.arith (ArithOp.sub uov sov)) -- fsub | Code.Instr.FSub => extractBinaryOp rawinstr ctx (Instruction.arith ArithOp.fsub) -- mul | Code.Instr.Mul => do uov <- monadLift (FFI.hasNoUnsignedWrap rawinstr); sov <- monadLift (FFI.hasNoSignedWrap rawinstr); extractBinaryOp rawinstr ctx (Instruction.arith (ArithOp.mul uov sov)) -- fmul | Code.Instr.FMul => extractBinaryOp rawinstr ctx (Instruction.arith ArithOp.fmul) -- udiv | Code.Instr.UDiv => do ex <- monadLift (FFI.isExact rawinstr); extractBinaryOp rawinstr ctx (Instruction.arith (ArithOp.udiv ex)) -- sdiv | Code.Instr.SDiv => do ex <- monadLift (FFI.isExact rawinstr); extractBinaryOp rawinstr ctx (Instruction.arith (ArithOp.sdiv ex)) -- fdiv | Code.Instr.FDiv => extractBinaryOp rawinstr ctx (Instruction.arith ArithOp.fdiv) -- urem | Code.Instr.URem => extractBinaryOp rawinstr ctx (Instruction.arith ArithOp.urem) -- srem | Code.Instr.SRem => extractBinaryOp rawinstr ctx (Instruction.arith ArithOp.srem) -- frem | Code.Instr.FRem => extractBinaryOp rawinstr ctx (Instruction.arith ArithOp.frem) -- shl | Code.Instr.Shl => do uov <- monadLift (FFI.hasNoUnsignedWrap rawinstr); sov <- monadLift (FFI.hasNoSignedWrap rawinstr); extractBinaryOp rawinstr ctx (Instruction.bit (BitOp.shl uov sov)) -- lshr | Code.Instr.LShr => do ex <- monadLift (FFI.isExact rawinstr); extractBinaryOp rawinstr ctx (Instruction.bit (BitOp.lshr ex)) -- ashr | Code.Instr.AShr => do ex <- monadLift (FFI.isExact rawinstr); extractBinaryOp rawinstr ctx (Instruction.bit (BitOp.ashr ex)) -- and | Code.Instr.And => extractBinaryOp rawinstr ctx (Instruction.bit BitOp.and) -- or | Code.Instr.Or => extractBinaryOp rawinstr ctx (Instruction.bit BitOp.or) -- xor | Code.Instr.Xor => extractBinaryOp rawinstr ctx (Instruction.bit BitOp.xor) -- alloca | Code.Instr.Alloca => do md ← monadLift (FFI.getAllocaData rawinstr); match md with | none => throwError "Expected alloca instruction" | some (tp, nelts, align) => do tp' <- extractType tp; nelts' <- Option.mapM (extractTypedValue ctx) nelts; pure (Instruction.alloca tp' nelts' align) -- load | Code.Instr.Load => do md ← monadLift (FFI.getLoadData rawinstr); match md with | none => throwError "Expected load instruction" | some (ptr, align) => do ptr' <- extractTypedValue ctx ptr; pure (Instruction.load ptr' none align) -- TODO atomic ordering -- store | Code.Instr.Store => do md ← monadLift (FFI.getStoreData rawinstr); match md with | none => throwError "Expected store instruction" | some (val,ptr,align) => do val' <- extractTypedValue ctx val; ptr' <- extractTypedValue ctx ptr; pure (Instruction.store val' ptr' align) -- GEP | Code.Instr.GetElementPtr => do md <- monadLift (FFI.getGEPData rawinstr); match md with | none => throwError "Expected GEP instruction" | some (inbounds,base,idxes) => do base' <- extractTypedValue ctx base; idxes' <- Array.mapM (extractTypedValue ctx) idxes; pure (Instruction.gep inbounds base' idxes') -- trunc | Code.Instr.Trunc => extractCastOp rawinstr ctx (Instruction.conv ConvOp.trunc) -- zext | Code.Instr.ZExt => extractCastOp rawinstr ctx (Instruction.conv ConvOp.zext) -- sext | Code.Instr.SExt => extractCastOp rawinstr ctx (Instruction.conv ConvOp.sext) -- fptoui | Code.Instr.FPToUI => extractCastOp rawinstr ctx (Instruction.conv ConvOp.fp_to_ui) -- fptosi | Code.Instr.FPToSI => extractCastOp rawinstr ctx (Instruction.conv ConvOp.fp_to_si) -- uitofp | Code.Instr.UIToFP => extractCastOp rawinstr ctx (Instruction.conv ConvOp.ui_to_fp) -- sitofp | Code.Instr.SIToFP => extractCastOp rawinstr ctx (Instruction.conv ConvOp.si_to_fp) -- fptrunc | Code.Instr.FPTrunc => extractCastOp rawinstr ctx (Instruction.conv ConvOp.fp_trunc) -- fpext | Code.Instr.FPExt => extractCastOp rawinstr ctx (Instruction.conv ConvOp.fp_ext) -- ptrtoint | Code.Instr.PtrToInt => extractCastOp rawinstr ctx (Instruction.conv ConvOp.ptr_to_int) -- inttoptr | Code.Instr.IntToPtr => extractCastOp rawinstr ctx (Instruction.conv ConvOp.int_to_ptr) -- bitcast | Code.Instr.BitCast => extractCastOp rawinstr ctx (Instruction.conv ConvOp.bit_cast) -- icmp | Code.Instr.ICmp => do d <- monadLift (FFI.getICmpInstData rawinstr); match d with | none => throwError "expected icmp instruction" | some (code, (v1, v2)) => do let op := extractICmpOp code; o1 <- extractTypedValue ctx v1; o2 <- extractTypedValue ctx v2; pure (Instruction.icmp op o1 o2.value) -- PHI | Code.Instr.PHI => do t <- monadLift (FFI.getInstructionType rawinstr) >>= extractType; d <- monadLift (FFI.getPhiData rawinstr); match d with | none => throwError "expected phi instruction" | some vs => do vs' <- vs.mapM $ λvbb => Prod.mk <$> extractValue ctx vbb.1 <*> extractBlockLabel ctx vbb.2; pure (Instruction.phi t vs') -- call | Code.Instr.Call => do d <- monadLift (FFI.getCallInstData rawinstr); match d with | none => throwError "expected call instruction" | some (tail,retty,funv,args) => do retty' <- extractType retty; let retty'' := match retty' with | LLVMType.prim PrimType.void => none | _ => some retty'; funv' <- extractTypedValue ctx funv; args' <- Array.mapM (extractTypedValue ctx) args; pure (Instruction.call tail retty'' funv'.value args') -- select | Code.Instr.Select => do d <- monadLift (FFI.getSelectInstData rawinstr); match d with | none => throwError "expected select instruction" | some (vc, (vt,ve)) => do c <- extractTypedValue ctx vc; t <- extractTypedValue ctx vt; e <- extractTypedValue ctx ve; pure (Instruction.select c t e.value) | _ => throwError $ "unimplemented instruction opcode: " ++ op.asString def extractStmt (rawinstr:FFI.Instruction) (ctx:ValueContext) : extract Stmt := do i <- extractInstruction rawinstr ctx; pure { assign := RBMap.find? ctx.imap rawinstr, instr := i, metadata := Array.empty, } def extractStatements (bb:FFI.BasicBlock) (ctx:ValueContext) : extract (Array Stmt) := do rawinstrs <- monadLift (FFI.getInstructionArray bb); Array.iterateM rawinstrs Array.empty (λ_ rawinstr stmts => do stmt <- extractStmt rawinstr ctx; pure (Array.push stmts stmt)) def extractBasicBlocks (fn : FFI.Function) (ctx:ValueContext) : extract (Array BasicBlock) := do rawbbs <- monadLift (FFI.getBasicBlockArray fn); Array.iterateM rawbbs Array.empty (λ_ rawbb bs => match RBMap.find? ctx.bmap rawbb with | none => throwError "unknown basic block" | some lab => do stmts <- extractStatements rawbb ctx; pure $ Array.push bs { label := lab, stmts := stmts }) def extractFunction (fn : FFI.Function) : extract Define := do nm <- monadLift (FFI.getFunctionName fn); ret <- monadLift (FFI.getReturnType fn) >>= extractType; (counter, args) <- extractArgs fn; (bmap, imap) <- computeNumberings counter fn; let ctx := { ValueContext . funArgs := args, imap := imap, bmap := bmap }; bbs <- extractBasicBlocks fn ctx; pure { linkage := none, retType := ret, name := ⟨nm⟩, args := args, varArgs := false, attrs := Array.empty, sec := none, gc := none, body := bbs, metadata := Strmap.empty, comdat := none, } def extractDataLayout (m:FFI.Module) : extract (List LayoutSpec) := do dlstr <- monadLift $ FFI.getModuleDataLayoutStr m; match parse.run parse.data_layout dlstr with | Sum.inl (stk, str') => throwError $ "Could not parse data layout string: " ++ dlstr ++ " " ++ stk.repr ++ " " ++ str' | Sum.inr dl => pure dl. def extractGlobal (g:FFI.GlobalVar) : extract Global := do tp <- monadLift (FFI.getValueType g) >>= extractType; match tp with | LLVMType.ptr valtp => do md <- monadLift (FFI.getGlobalVarData g); match md with | none => throwError "Expected global variable" | some (nm, val, align) => do val' <- val.mapM (extractValue ValueContext.empty); let attrs := { GlobalAttrs . linkage := none, visibility := none, const := false }; pure { sym := ⟨nm⟩ , attrs := attrs , type := valtp , value := val' , align := align , metadata := Strmap.empty } | _ => throwError ("Expected pointer type for global but got: " ++ (pp tp).render) def extractModule (m:FFI.Module) : extract Module := do nm <- monadLift (FFI.getModuleIdentifier m); dl <- extractDataLayout m; fns <- monadLift (FFI.getFunctionArray m) >>= Array.mapM extractFunction; gs <- monadLift (FFI.getGlobalArray m) >>= Array.mapM extractGlobal; pure { sourceName := some nm , dataLayout := dl , types := Array.empty -- TODO , namedMD := Array.empty -- TODO , unnamedMD := Array.empty -- TODO , comdat := Strmap.empty -- TODO , globals := gs , declares := Array.empty -- TODO , defines := fns , inlineAsm := Array.empty -- TODO , aliases := Array.empty -- TODO } def toTypeDecl (x:String × TypeDeclBody) : TypeDecl := ⟨x.1, x.2⟩ def loadModule (m:FFI.Module) : IO Module := do (am, mod) <- (extractModule m).run; let tds := List.map toTypeDecl (am.toList); pure { mod with types := tds.toArray } end LLVM
035f9624bd1dc846d58428e7c3338d5ecf135e0e
0003047346476c031128723dfd16fe273c6bc605
/src/group_theory/perm/sign.lean
9416b9afb4076f69fcef8f0c612bdae84a67445c
[ "Apache-2.0" ]
permissive
ChandanKSingh/mathlib
d2bf4724ccc670bf24915c12c475748281d3fb73
d60d1616958787ccb9842dc943534f90ea0bab64
refs/heads/master
1,588,238,823,679
1,552,867,469,000
1,552,867,469,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
32,956
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.fintype universes u v open equiv function fintype finset variables {α : Type u} {β : Type v} namespace equiv.perm def subtype_perm (f : perm α) {p : α → Prop} (h : ∀ x, p x ↔ p (f x)) : perm {x // p x} := ⟨λ x, ⟨f x, (h _).1 x.2⟩, λ x, ⟨f⁻¹ x, (h (f⁻¹ x)).2 $ by simpa using x.2⟩, λ _, by simp, λ _, by simp⟩ @[simp] lemma subtype_perm_one (p : α → Prop) (h : ∀ x, p x ↔ p ((1 : perm α) x)) : @subtype_perm α 1 p h = 1 := equiv.ext _ _ $ λ ⟨_, _⟩, rfl def of_subtype {p : α → Prop} [decidable_pred p] (f : perm (subtype p)) : perm α := ⟨λ x, if h : p x then f ⟨x, h⟩ else x, λ x, if h : p x then f⁻¹ ⟨x, h⟩ else x, λ x, have h : ∀ h : p x, p (f ⟨x, h⟩), from λ h, (f ⟨x, h⟩).2, by simp; split_ifs at *; simp * at *, λ x, have h : ∀ h : p x, p (f⁻¹ ⟨x, h⟩), from λ h, (f⁻¹ ⟨x, h⟩).2, by simp; split_ifs at *; simp * at *⟩ instance of_subtype.is_group_hom {p : α → Prop} [decidable_pred p] : is_group_hom (@of_subtype α p _) := ⟨λ f g, equiv.ext _ _ $ λ x, begin rw [of_subtype, of_subtype, of_subtype], by_cases h : p x, { have h₁ : p (f (g ⟨x, h⟩)), from (f (g ⟨x, h⟩)).2, have h₂ : p (g ⟨x, h⟩), from (g ⟨x, h⟩).2, simp [h, h₁, h₂] }, { simp [h] } end⟩ @[simp] lemma of_subtype_one (p : α → Prop) [decidable_pred p] : @of_subtype α p _ 1 = 1 := is_group_hom.one of_subtype lemma eq_inv_iff_eq {f : perm α} {x y : α} : x = f⁻¹ y ↔ f x = y := by conv {to_lhs, rw [← injective.eq_iff f.bijective.1, apply_inv_self]} lemma inv_eq_iff_eq {f : perm α} {x y : α} : f⁻¹ x = y ↔ x = f y := by rw [eq_comm, eq_inv_iff_eq, eq_comm] def disjoint (f g : perm α) := ∀ x, f x = x ∨ g x = x @[symm] lemma disjoint.symm {f g : perm α} : disjoint f g → disjoint g f := by simp [disjoint, or.comm] lemma disjoint_comm {f g : perm α} : disjoint f g ↔ disjoint g f := ⟨disjoint.symm, disjoint.symm⟩ lemma disjoint_mul_comm {f g : perm α} (h : disjoint f g) : f * g = g * f := equiv.ext _ _ $ λ x, (h x).elim (λ hf, (h (g x)).elim (λ hg, by simp [mul_apply, hf, hg]) (λ hg, by simp [mul_apply, hf, g.bijective.1 hg])) (λ hg, (h (f x)).elim (λ hf, by simp [mul_apply, f.bijective.1 hf, hg]) (λ hf, by simp [mul_apply, hf, hg])) @[simp] lemma disjoint_one_left (f : perm α) : disjoint 1 f := λ _, or.inl rfl @[simp] lemma disjoint_one_right (f : perm α) : disjoint f 1 := λ _, or.inr rfl lemma disjoint_mul_left {f g h : perm α} (H1 : disjoint f h) (H2 : disjoint g h) : disjoint (f * g) h := λ x, by cases H1 x; cases H2 x; simp * lemma disjoint_mul_right {f g h : perm α} (H1 : disjoint f g) (H2 : disjoint f h) : disjoint f (g * h) := by rw disjoint_comm; exact disjoint_mul_left H1.symm H2.symm lemma disjoint_prod_right {f : perm α} (l : list (perm α)) (h : ∀ g ∈ l, disjoint f g) : disjoint f l.prod := begin induction l with g l ih, { exact disjoint_one_right _ }, { rw list.prod_cons; exact disjoint_mul_right (h _ (list.mem_cons_self _ _)) (ih (λ g hg, h g (list.mem_cons_of_mem _ hg))) } end lemma disjoint_prod_perm {l₁ l₂ : list (perm α)} (hl : l₁.pairwise disjoint) (hp : l₁ ~ l₂) : l₁.prod = l₂.prod := begin induction hp, { refl }, { rw [list.prod_cons, list.prod_cons, hp_ih (list.pairwise_cons.1 hl).2] }, { simp [list.prod_cons, disjoint_mul_comm, (mul_assoc _ _ _).symm, *, list.pairwise_cons] at * }, { rw [hp_ih_a hl, hp_ih_a_1 ((list.perm_pairwise (λ x y (h : disjoint x y), disjoint.symm h) hp_a).1 hl)] } end lemma of_subtype_subtype_perm {f : perm α} {p : α → Prop} [decidable_pred p] (h₁ : ∀ x, p x ↔ p (f x)) (h₂ : ∀ x, f x ≠ x → p x) : of_subtype (subtype_perm f h₁) = f := equiv.ext _ _ $ λ x, begin rw [of_subtype, subtype_perm], by_cases hx : p x, { simp [hx] }, { haveI := classical.prop_decidable, simp [hx, not_not.1 (mt (h₂ x) hx)] } end lemma of_subtype_apply_of_not_mem {p : α → Prop} [decidable_pred p] (f : perm (subtype p)) {x : α} (hx : ¬ p x) : of_subtype f x = x := dif_neg hx lemma mem_iff_of_subtype_apply_mem {p : α → Prop} [decidable_pred p] (f : perm (subtype p)) (x : α) : p x ↔ p ((of_subtype f : α → α) x) := if h : p x then by dsimp [of_subtype]; simpa [h] using (f ⟨x, h⟩).2 else by simp [h, of_subtype_apply_of_not_mem f h] @[simp] lemma subtype_perm_of_subtype {p : α → Prop} [decidable_pred p] (f : perm (subtype p)) : subtype_perm (of_subtype f) (mem_iff_of_subtype_apply_mem f) = f := equiv.ext _ _ $ λ ⟨x, hx⟩, by dsimp [subtype_perm, of_subtype]; simp [show p x, from hx] lemma pow_apply_eq_self_of_apply_eq_self {f : perm α} {x : α} (hfx : f x = x) : ∀ n : ℕ, (f ^ n) x = x | 0 := rfl | (n+1) := by rw [pow_succ', mul_apply, hfx, pow_apply_eq_self_of_apply_eq_self] lemma gpow_apply_eq_self_of_apply_eq_self {f : perm α} {x : α} (hfx : f x = x) : ∀ n : ℤ, (f ^ n) x = x | (n : ℕ) := pow_apply_eq_self_of_apply_eq_self hfx n | -[1+ n] := by rw [gpow_neg_succ, inv_eq_iff_eq, pow_apply_eq_self_of_apply_eq_self hfx] lemma pow_apply_eq_of_apply_apply_eq_self {f : perm α} {x : α} (hffx : f (f x) = x) : ∀ n : ℕ, (f ^ n) x = x ∨ (f ^ n) x = f x | 0 := or.inl rfl | (n+1) := (pow_apply_eq_of_apply_apply_eq_self n).elim (λ h, or.inr (by rw [pow_succ, mul_apply, h])) (λ h, or.inl (by rw [pow_succ, mul_apply, h, hffx])) lemma gpow_apply_eq_of_apply_apply_eq_self {f : perm α} {x : α} (hffx : f (f x) = x) : ∀ i : ℤ, (f ^ i) x = x ∨ (f ^ i) x = f x | (n : ℕ) := pow_apply_eq_of_apply_apply_eq_self hffx n | -[1+ n] := by rw [gpow_neg_succ, inv_eq_iff_eq, ← injective.eq_iff f.bijective.1, ← mul_apply, ← pow_succ, eq_comm, inv_eq_iff_eq, ← mul_apply, ← pow_succ', @eq_comm _ x, or.comm]; exact pow_apply_eq_of_apply_apply_eq_self hffx _ variable [decidable_eq α] def support [fintype α] (f : perm α) := univ.filter (λ x, f x ≠ x) @[simp] lemma mem_support [fintype α] {f : perm α} {x : α} : x ∈ f.support ↔ f x ≠ x := by simp [support] def is_swap (f : perm α) := ∃ x y, x ≠ y ∧ f = swap x y lemma swap_mul_eq_mul_swap (f : perm α) (x y : α) : swap x y * f = f * swap (f⁻¹ x) (f⁻¹ y) := equiv.ext _ _ $ λ z, begin simp [mul_apply, swap_apply_def], split_ifs; simp [*, eq_inv_iff_eq] at * <|> cc end lemma mul_swap_eq_swap_mul (f : perm α) (x y : α) : f * swap x y = swap (f x) (f y) * f := by rw [swap_mul_eq_mul_swap, inv_apply_self, inv_apply_self] @[simp] lemma swap_mul_self (i j : α) : equiv.swap i j * equiv.swap i j = 1 := equiv.swap_swap i j @[simp] lemma swap_swap_apply (i j k : α) : equiv.swap i j (equiv.swap i j k) = k := equiv.swap_core_swap_core k i j lemma is_swap_of_subtype {p : α → Prop} [decidable_pred p] {f : perm (subtype p)} (h : is_swap f) : is_swap (of_subtype f) := let ⟨⟨x, hx⟩, ⟨y, hy⟩, hxy⟩ := h in ⟨x, y, by simp at hxy; tauto, equiv.ext _ _ $ λ z, begin rw [hxy.2, of_subtype], simp [swap_apply_def], split_ifs; cc <|> simp * at * end⟩ lemma ne_and_ne_of_swap_mul_apply_ne_self {f : perm α} {x y : α} (hy : (swap x (f x) * f) y ≠ y) : f y ≠ y ∧ y ≠ x := begin simp only [swap_apply_def, mul_apply, injective.eq_iff f.bijective.1] at *, by_cases h : f y = x, { split; intro; simp * at * }, { split_ifs at hy; cc } end lemma support_swap_mul_eq [fintype α] {f : perm α} {x : α} (hffx : f (f x) ≠ x) : (swap x (f x) * f).support = f.support.erase x := have hfx : f x ≠ x, from λ hfx, by simpa [hfx] using hffx, finset.ext.2 $ λ y, ⟨λ hy, have hy' : (swap x (f x) * f) y ≠ y, from mem_support.1 hy, mem_erase.2 ⟨λ hyx, by simp [hyx, mul_apply, *] at *, mem_support.2 $ λ hfy, by simp only [mul_apply, swap_apply_def, hfy] at hy'; split_ifs at hy'; simp * at *⟩, λ hy, by simp only [mem_erase, mem_support, swap_apply_def, mul_apply] at *; intro; split_ifs at *; simp * at *⟩ lemma card_support_swap_mul [fintype α] {f : perm α} {x : α} (hx : f x ≠ x) : (swap x (f x) * f).support.card < f.support.card := finset.card_lt_card ⟨λ z hz, mem_support.2 (ne_and_ne_of_swap_mul_apply_ne_self (mem_support.1 hz)).1, λ h, absurd (h (mem_support.2 hx)) (mt mem_support.1 (by simp))⟩ def swap_factors_aux : Π (l : list α) (f : perm α), (∀ {x}, f x ≠ x → x ∈ l) → {l : list (perm α) // l.prod = f ∧ ∀ g ∈ l, is_swap g} | [] := λ f h, ⟨[], equiv.ext _ _ $ λ x, by rw [list.prod_nil]; exact eq.symm (not_not.1 (mt h (list.not_mem_nil _))), by simp⟩ | (x :: l) := λ f h, if hfx : x = f x then swap_factors_aux l f (λ y hy, list.mem_of_ne_of_mem (λ h : y = x, by simpa [h, hfx.symm] using hy) (h hy)) else let m := swap_factors_aux l (swap x (f x) * f) (λ y hy, have f y ≠ y ∧ y ≠ x, from ne_and_ne_of_swap_mul_apply_ne_self hy, list.mem_of_ne_of_mem this.2 (h this.1)) in ⟨swap x (f x) :: m.1, by rw [list.prod_cons, m.2.1, ← mul_assoc, mul_def (swap x (f x)), swap_swap, ← one_def, one_mul], λ g hg, ((list.mem_cons_iff _ _ _).1 hg).elim (λ h, ⟨x, f x, hfx, h⟩) (m.2.2 _)⟩ /-- `swap_factors` represents a permutation as a product of a list of transpositions. The representation is non unique and depends on the linear order structure. For types without linear order `trunc_swap_factors` can be used -/ def swap_factors [fintype α] [decidable_linear_order α] (f : perm α) : {l : list (perm α) // l.prod = f ∧ ∀ g ∈ l, is_swap g} := swap_factors_aux ((@univ α _).sort (≤)) f (λ _ _, (mem_sort _).2 (mem_univ _)) def trunc_swap_factors [fintype α] (f : perm α) : trunc {l : list (perm α) // l.prod = f ∧ ∀ g ∈ l, is_swap g} := quotient.rec_on_subsingleton (@univ α _).1 (λ l h, trunc.mk (swap_factors_aux l f h)) (show ∀ x, f x ≠ x → x ∈ (@univ α _).1, from λ _ _, mem_univ _) @[elab_as_eliminator] lemma swap_induction_on [fintype α] {P : perm α → Prop} (f : perm α) : P 1 → (∀ f x y, x ≠ y → P f → P (swap x y * f)) → P f := begin cases trunc.out (trunc_swap_factors f) with l hl, induction l with g l ih generalizing f, { simp [hl.1.symm] {contextual := tt} }, { assume h1 hmul_swap, rcases hl.2 g (by simp) with ⟨x, y, hxy⟩, rw [← hl.1, list.prod_cons, hxy.2], exact hmul_swap _ _ _ hxy.1 (ih _ ⟨rfl, λ v hv, hl.2 _ (list.mem_cons_of_mem _ hv)⟩ h1 hmul_swap) } end lemma swap_mul_swap_mul_swap {x y z : α} (hwz: x ≠ y) (hxz : x ≠ z) : swap y z * swap x y * swap y z = swap z x := equiv.ext _ _ $ λ n, by simp only [swap_apply_def, mul_apply]; split_ifs; cc lemma is_conj_swap {w x y z : α} (hwx : w ≠ x) (hyz : y ≠ z) : is_conj (swap w x) (swap y z) := have h : ∀ {y z : α}, y ≠ z → w ≠ z → (swap w y * swap x z) * swap w x * (swap w y * swap x z)⁻¹ = swap y z := λ y z hyz hwz, by rw [mul_inv_rev, swap_inv, swap_inv, mul_assoc (swap w y), mul_assoc (swap w y), ← mul_assoc _ (swap x z), swap_mul_swap_mul_swap hwx hwz, ← mul_assoc, swap_mul_swap_mul_swap hwz.symm hyz.symm], if hwz : w = z then have hwy : w ≠ y, by cc, ⟨swap w z * swap x y, by rw [swap_comm y z, h hyz.symm hwy]⟩ else ⟨swap w y * swap x z, h hyz hwz⟩ /-- set of all pairs (⟨a, b⟩ : Σ a : fin n, fin n) such that b < a -/ def fin_pairs_lt (n : ℕ) : finset (Σ a : fin n, fin n) := (univ : finset (fin n)).sigma (λ a, (range a.1).attach_fin (λ m hm, lt_trans (mem_range.1 hm) a.2)) lemma mem_fin_pairs_lt {n : ℕ} {a : Σ a : fin n, fin n} : a ∈ fin_pairs_lt n ↔ a.2 < a.1 := by simp [fin_pairs_lt, fin.lt_def] def sign_aux {n : ℕ} (a : perm (fin n)) : units ℤ := (fin_pairs_lt n).prod (λ x, if a x.1 ≤ a x.2 then -1 else 1) @[simp] lemma sign_aux_one (n : ℕ) : sign_aux (1 : perm (fin n)) = 1 := begin unfold sign_aux, conv { to_rhs, rw ← @finset.prod_const_one _ (units ℤ) (fin_pairs_lt n) }, exact finset.prod_congr rfl (λ a ha, if_neg (not_le_of_gt (mem_fin_pairs_lt.1 ha))) end def sign_bij_aux {n : ℕ} (f : perm (fin n)) (a : Σ a : fin n, fin n) : Σ a : fin n, fin n := if hxa : f a.2 < f a.1 then ⟨f a.1, f a.2⟩ else ⟨f a.2, f a.1⟩ lemma sign_bij_aux_inj {n : ℕ} {f : perm (fin n)} : ∀ a b : Σ a : fin n, fin n, a ∈ fin_pairs_lt n → b ∈ fin_pairs_lt n → sign_bij_aux f a = sign_bij_aux f b → a = b := λ ⟨a₁, a₂⟩ ⟨b₁, b₂⟩ ha hb h, begin unfold sign_bij_aux at h, rw mem_fin_pairs_lt at *, have : ¬b₁ < b₂ := not_lt_of_ge (le_of_lt hb), split_ifs at h; simp [*, injective.eq_iff f.bijective.1, sigma.mk.inj_eq] at * end lemma sign_bij_aux_surj {n : ℕ} {f : perm (fin n)} : ∀ a ∈ fin_pairs_lt n, ∃ b ∈ fin_pairs_lt n, a = sign_bij_aux f b := λ ⟨a₁, a₂⟩ ha, if hxa : f⁻¹ a₂ < f⁻¹ a₁ then ⟨⟨f⁻¹ a₁, f⁻¹ a₂⟩, mem_fin_pairs_lt.2 hxa, by dsimp [sign_bij_aux]; rw [apply_inv_self, apply_inv_self, dif_pos (mem_fin_pairs_lt.1 ha)]⟩ else ⟨⟨f⁻¹ a₂, f⁻¹ a₁⟩, mem_fin_pairs_lt.2 $ lt_of_le_of_ne (le_of_not_gt hxa) $ λ h, by simpa [mem_fin_pairs_lt, (f⁻¹).bijective.1 h, lt_irrefl] using ha, by dsimp [sign_bij_aux]; rw [apply_inv_self, apply_inv_self, dif_neg (not_lt_of_ge (le_of_lt (mem_fin_pairs_lt.1 ha)))]⟩ lemma sign_bij_aux_mem {n : ℕ} {f : perm (fin n)}: ∀ a : Σ a : fin n, fin n, a ∈ fin_pairs_lt n → sign_bij_aux f a ∈ fin_pairs_lt n := λ ⟨a₁, a₂⟩ ha, begin unfold sign_bij_aux, split_ifs with h, { exact mem_fin_pairs_lt.2 h }, { exact mem_fin_pairs_lt.2 (lt_of_le_of_ne (le_of_not_gt h) (λ h, ne_of_lt (mem_fin_pairs_lt.1 ha) (f.bijective.1 h.symm))) } end @[simp] lemma sign_aux_inv {n : ℕ} (f : perm (fin n)) : sign_aux f⁻¹ = sign_aux f := prod_bij (λ a ha, sign_bij_aux f⁻¹ a) sign_bij_aux_mem (λ ⟨a, b⟩ hab, if h : f⁻¹ b < f⁻¹ a then by rw [sign_bij_aux, dif_pos h, if_neg (not_le_of_gt h), apply_inv_self, apply_inv_self, if_neg (not_le_of_gt $ mem_fin_pairs_lt.1 hab)] else by rw [sign_bij_aux, if_pos (le_of_not_gt h), dif_neg h, apply_inv_self, apply_inv_self, if_pos (le_of_lt $ mem_fin_pairs_lt.1 hab)]) sign_bij_aux_inj sign_bij_aux_surj lemma sign_aux_mul {n : ℕ} (f g : perm (fin n)) : sign_aux (f * g) = sign_aux f * sign_aux g := begin rw ← sign_aux_inv g, unfold sign_aux, rw ← prod_mul_distrib, refine prod_bij (λ a ha, sign_bij_aux g a) sign_bij_aux_mem _ sign_bij_aux_inj sign_bij_aux_surj, rintros ⟨a, b⟩ hab, rw [sign_bij_aux, mul_apply, mul_apply], rw mem_fin_pairs_lt at hab, by_cases h : g b < g a, { rw dif_pos h, simp [not_le_of_gt hab]; congr }, { rw [dif_neg h, inv_apply_self, inv_apply_self, if_pos (le_of_lt hab)], by_cases h₁ : f (g b) ≤ f (g a), { have : f (g b) ≠ f (g a), { rw [ne.def, injective.eq_iff f.bijective.1, injective.eq_iff g.bijective.1]; exact ne_of_lt hab }, rw [if_pos h₁, if_neg (not_le_of_gt (lt_of_le_of_ne h₁ this))], refl }, { rw [if_neg h₁, if_pos (le_of_lt (lt_of_not_ge h₁))], refl } } end instance sign_aux.is_group_hom {n : ℕ} : is_group_hom (@sign_aux n) := ⟨sign_aux_mul⟩ private lemma sign_aux_swap_zero_one {n : ℕ} (hn : 2 ≤ n) : sign_aux (swap (⟨0, lt_of_lt_of_le dec_trivial hn⟩ : fin n) ⟨1, lt_of_lt_of_le dec_trivial hn⟩) = -1 := let zero : fin n := ⟨0, lt_of_lt_of_le dec_trivial hn⟩ in let one : fin n := ⟨1, lt_of_lt_of_le dec_trivial hn⟩ in have hzo : zero < one := dec_trivial, show _ = (finset.singleton (⟨one, zero⟩ : Σ a : fin n, fin n)).prod (λ x : Σ a : fin n, fin n, if (equiv.swap zero one) x.1 ≤ swap zero one x.2 then (-1 : units ℤ) else 1), begin refine eq.symm (prod_subset (λ ⟨x₁, x₂⟩, by simp [mem_fin_pairs_lt, hzo] {contextual := tt}) (λ a ha₁ ha₂, _)), rcases a with ⟨⟨a₁, ha₁⟩, ⟨a₂, ha₂⟩⟩, replace ha₁ : a₂ < a₁ := mem_fin_pairs_lt.1 ha₁, simp only [swap_apply_def], have : ¬ 1 ≤ a₂ → a₂ = 0, from λ h, nat.le_zero_iff.1 (nat.le_of_lt_succ (lt_of_not_ge h)), have : a₁ ≤ 1 → a₁ = 0 ∨ a₁ = 1, from nat.cases_on a₁ (λ _, or.inl rfl) (λ a₁, nat.cases_on a₁ (λ _, or.inr rfl) (λ _ h, absurd h dec_trivial)), split_ifs; simp [*, lt_irrefl, -not_lt, not_le.symm, -not_le, le_refl, fin.lt_def, fin.le_def, nat.zero_le, zero, one, iff.intro fin.veq_of_eq fin.eq_of_veq, nat.le_zero_iff] at *, end lemma sign_aux_swap : ∀ {n : ℕ} {x y : fin n} (hxy : x ≠ y), sign_aux (swap x y) = -1 | 0 := dec_trivial | 1 := dec_trivial | (n+2) := λ x y hxy, have h2n : 2 ≤ n + 2 := dec_trivial, by rw [← is_conj_iff_eq, ← sign_aux_swap_zero_one h2n]; exact is_group_hom.is_conj _ (is_conj_swap hxy dec_trivial) def sign_aux2 : list α → perm α → units ℤ | [] f := 1 | (x::l) f := if x = f x then sign_aux2 l f else -sign_aux2 l (swap x (f x) * f) lemma sign_aux_eq_sign_aux2 {n : ℕ} : ∀ (l : list α) (f : perm α) (e : α ≃ fin n) (h : ∀ x, f x ≠ x → x ∈ l), sign_aux ((e.symm.trans f).trans e) = sign_aux2 l f | [] f e h := have f = 1, from equiv.ext _ _ $ λ y, not_not.1 (mt (h y) (list.not_mem_nil _)), by rw [this, one_def, equiv.trans_refl, equiv.symm_trans, ← one_def, sign_aux_one, sign_aux2] | (x::l) f e h := begin rw sign_aux2, by_cases hfx : x = f x, { rw if_pos hfx, exact sign_aux_eq_sign_aux2 l f _ (λ y (hy : f y ≠ y), list.mem_of_ne_of_mem (λ h : y = x, by simpa [h, hfx.symm] using hy) (h y hy) ) }, { have hy : ∀ y : α, (swap x (f x) * f) y ≠ y → y ∈ l, from λ y hy, have f y ≠ y ∧ y ≠ x, from ne_and_ne_of_swap_mul_apply_ne_self hy, list.mem_of_ne_of_mem this.2 (h _ this.1), have : (e.symm.trans (swap x (f x) * f)).trans e = (swap (e x) (e (f x))) * (e.symm.trans f).trans e, from equiv.ext _ _ (λ z, by rw ← equiv.symm_trans_swap_trans; simp [mul_def]), have hefx : e x ≠ e (f x), from mt (injective.eq_iff e.bijective.1).1 hfx, rw [if_neg hfx, ← sign_aux_eq_sign_aux2 _ _ e hy, this, sign_aux_mul, sign_aux_swap hefx], simp } end def sign_aux3 [fintype α] (f : perm α) {s : multiset α} : (∀ x, x ∈ s) → units ℤ := quotient.hrec_on s (λ l h, sign_aux2 l f) (trunc.induction_on (equiv_fin α) (λ e l₁ l₂ h, function.hfunext (show (∀ x, x ∈ l₁) = ∀ x, x ∈ l₂, by simp [list.mem_of_perm h]) (λ h₁ h₂ _, by rw [← sign_aux_eq_sign_aux2 _ _ e (λ _ _, h₁ _), ← sign_aux_eq_sign_aux2 _ _ e (λ _ _, h₂ _)]))) lemma sign_aux3_mul_and_swap [fintype α] (f g : perm α) (s : multiset α) (hs : ∀ x, x ∈ s) : sign_aux3 (f * g) hs = sign_aux3 f hs * sign_aux3 g hs ∧ ∀ x y, x ≠ y → sign_aux3 (swap x y) hs = -1 := let ⟨l, hl⟩ := quotient.exists_rep s in let ⟨e, _⟩ := trunc.exists_rep (equiv_fin α) in begin clear _let_match _let_match, subst hl, show sign_aux2 l (f * g) = sign_aux2 l f * sign_aux2 l g ∧ ∀ x y, x ≠ y → sign_aux2 l (swap x y) = -1, have hfg : (e.symm.trans (f * g)).trans e = (e.symm.trans f).trans e * (e.symm.trans g).trans e, from equiv.ext _ _ (λ h, by simp [mul_apply]), split, { rw [← sign_aux_eq_sign_aux2 _ _ e (λ _ _, hs _), ← sign_aux_eq_sign_aux2 _ _ e (λ _ _, hs _), ← sign_aux_eq_sign_aux2 _ _ e (λ _ _, hs _), hfg, sign_aux_mul] }, { assume x y hxy, have hexy : e x ≠ e y, from mt (injective.eq_iff e.bijective.1).1 hxy, rw [← sign_aux_eq_sign_aux2 _ _ e (λ _ _, hs _), equiv.symm_trans_swap_trans, sign_aux_swap hexy] } end /-- `sign` of a permutation returns the signature or parity of a permutation, `1` for even permutations, `-1` for odd permutations. It is the unique surjective group homomorphism from `perm α` to the group with two elements.-/ def sign [fintype α] (f : perm α) := sign_aux3 f mem_univ instance sign.is_group_hom [fintype α] : is_group_hom (@sign α _ _) := ⟨λ f g, (sign_aux3_mul_and_swap f g _ mem_univ).1⟩ section sign variable [fintype α] @[simp] lemma sign_mul (f g : perm α) : sign (f * g) = sign f * sign g := is_group_hom.mul sign _ _ @[simp] lemma sign_one : (sign (1 : perm α)) = 1 := is_group_hom.one sign @[simp] lemma sign_refl : sign (equiv.refl α) = 1 := is_group_hom.one sign @[simp] lemma sign_inv (f : perm α) : sign f⁻¹ = sign f := by rw [is_group_hom.inv sign, int.units_inv_eq_self]; apply_instance lemma sign_swap {x y : α} (h : x ≠ y) : sign (swap x y) = -1 := (sign_aux3_mul_and_swap 1 1 _ mem_univ).2 x y h @[simp] lemma sign_swap' {x y : α} : (swap x y).sign = if x = y then 1 else -1 := if H : x = y then by simp [H, swap_self] else by simp [sign_swap H, H] lemma sign_eq_of_is_swap {f : perm α} (h : is_swap f) : sign f = -1 := let ⟨x, y, hxy⟩ := h in hxy.2.symm ▸ sign_swap hxy.1 lemma sign_aux3_symm_trans_trans [decidable_eq β] [fintype β] (f : perm α) (e : α ≃ β) {s : multiset α} {t : multiset β} (hs : ∀ x, x ∈ s) (ht : ∀ x, x ∈ t) : sign_aux3 ((e.symm.trans f).trans e) ht = sign_aux3 f hs := quotient.induction_on₂ t s (λ l₁ l₂ h₁ h₂, show sign_aux2 _ _ = sign_aux2 _ _, from let n := trunc.out (equiv_fin β) in by rw [← sign_aux_eq_sign_aux2 _ _ n (λ _ _, h₁ _), ← sign_aux_eq_sign_aux2 _ _ (e.trans n) (λ _ _, h₂ _)]; exact congr_arg sign_aux (equiv.ext _ _ (λ x, by simp))) ht hs lemma sign_symm_trans_trans [decidable_eq β] [fintype β] (f : perm α) (e : α ≃ β) : sign ((e.symm.trans f).trans e) = sign f := sign_aux3_symm_trans_trans f e mem_univ mem_univ lemma sign_prod_list_swap {l : list (perm α)} (hl : ∀ g ∈ l, is_swap g) : sign l.prod = -1 ^ l.length := have h₁ : l.map sign = list.repeat (-1) l.length := list.eq_repeat.2 ⟨by simp, λ u hu, let ⟨g, hg⟩ := list.mem_map.1 hu in hg.2 ▸ sign_eq_of_is_swap (hl _ hg.1)⟩, by rw [← list.prod_repeat, ← h₁, ← is_group_hom.prod (@sign α _ _)] lemma sign_surjective (hα : 1 < fintype.card α) : function.surjective (sign : perm α → units ℤ) := λ a, (int.units_eq_one_or a).elim (λ h, ⟨1, by simp [h]⟩) (λ h, let ⟨x⟩ := fintype.card_pos_iff.1 (lt_trans zero_lt_one hα) in let ⟨y, hxy⟩ := fintype.exists_ne_of_card_gt_one hα x in ⟨swap y x, by rw [sign_swap hxy, h]⟩ ) lemma eq_sign_of_surjective_hom {s : perm α → units ℤ} [is_group_hom s] (hs : surjective s) : s = sign := have ∀ {f}, is_swap f → s f = -1 := λ f ⟨x, y, hxy, hxy'⟩, hxy'.symm ▸ by_contradiction (λ h, have ∀ f, is_swap f → s f = 1 := λ f ⟨a, b, hab, hab'⟩, by rw [← is_conj_iff_eq, ← or.resolve_right (int.units_eq_one_or _) h, hab']; exact is_group_hom.is_conj _ (is_conj_swap hab hxy), let ⟨g, hg⟩ := hs (-1) in let ⟨l, hl⟩ := trunc.out (trunc_swap_factors g) in have ∀ a ∈ l.map s, a = (1 : units ℤ) := λ a ha, let ⟨g, hg⟩ := list.mem_map.1 ha in hg.2 ▸ this _ (hl.2 _ hg.1), have s l.prod = 1, by rw [is_group_hom.prod s, list.eq_repeat'.2 this, list.prod_repeat, one_pow], by rw [hl.1, hg] at this; exact absurd this dec_trivial), funext $ λ f, let ⟨l, hl₁, hl₂⟩ := trunc.out (trunc_swap_factors f) in have hsl : ∀ a ∈ l.map s, a = (-1 : units ℤ) := λ a ha, let ⟨g, hg⟩ := list.mem_map.1 ha in hg.2 ▸ this (hl₂ _ hg.1), by rw [← hl₁, is_group_hom.prod s, list.eq_repeat'.2 hsl, list.length_map, list.prod_repeat, sign_prod_list_swap hl₂] lemma sign_subtype_perm (f : perm α) {p : α → Prop} [decidable_pred p] (h₁ : ∀ x, p x ↔ p (f x)) (h₂ : ∀ x, f x ≠ x → p x) : sign (subtype_perm f h₁) = sign f := let l := trunc.out (trunc_swap_factors (subtype_perm f h₁)) in have hl' : ∀ g' ∈ l.1.map of_subtype, is_swap g' := λ g' hg', let ⟨g, hg⟩ := list.mem_map.1 hg' in hg.2 ▸ is_swap_of_subtype (l.2.2 _ hg.1), have hl'₂ : (l.1.map of_subtype).prod = f, by rw [← is_group_hom.prod of_subtype l.1, l.2.1, of_subtype_subtype_perm _ h₂], by conv {congr, rw ← l.2.1, skip, rw ← hl'₂}; rw [sign_prod_list_swap l.2.2, sign_prod_list_swap hl', list.length_map] @[simp] lemma sign_of_subtype {p : α → Prop} [decidable_pred p] (f : perm (subtype p)) : sign (of_subtype f) = sign f := have ∀ x, of_subtype f x ≠ x → p x, from λ x, not_imp_comm.1 (of_subtype_apply_of_not_mem f), by conv {to_rhs, rw [← subtype_perm_of_subtype f, sign_subtype_perm _ _ this]} lemma sign_eq_sign_of_equiv [decidable_eq β] [fintype β] (f : perm α) (g : perm β) (e : α ≃ β) (h : ∀ x, e (f x) = g (e x)) : sign f = sign g := have hg : g = (e.symm.trans f).trans e, from equiv.ext _ _ $ by simp [h], by rw [hg, sign_symm_trans_trans] lemma sign_bij [decidable_eq β] [fintype β] {f : perm α} {g : perm β} (i : Π x : α, f x ≠ x → β) (h : ∀ x hx hx', i (f x) hx' = g (i x hx)) (hi : ∀ x₁ x₂ hx₁ hx₂, i x₁ hx₁ = i x₂ hx₂ → x₁ = x₂) (hg : ∀ y, g y ≠ y → ∃ x hx, i x hx = y) : sign f = sign g := calc sign f = sign (@subtype_perm _ f (λ x, f x ≠ x) (by simp)) : eq.symm (sign_subtype_perm _ _ (λ _, id)) ... = sign (@subtype_perm _ g (λ x, g x ≠ x) (by simp)) : sign_eq_sign_of_equiv _ _ (equiv.of_bijective (show function.bijective (λ x : {x // f x ≠ x}, (⟨i x.1 x.2, have f (f x) ≠ f x, from mt (λ h, f.bijective.1 h) x.2, by rw [← h _ x.2 this]; exact mt (hi _ _ this x.2) x.2⟩ : {y // g y ≠ y})), from ⟨λ ⟨x, hx⟩ ⟨y, hy⟩ h, subtype.eq (hi _ _ _ _ (subtype.mk.inj h)), λ ⟨y, hy⟩, let ⟨x, hfx, hx⟩ := hg y hy in ⟨⟨x, hfx⟩, subtype.eq hx⟩⟩)) (λ ⟨x, _⟩, subtype.eq (h x _ _)) ... = sign g : sign_subtype_perm _ _ (λ _, id) def is_cycle (f : perm β) := ∃ x, f x ≠ x ∧ ∀ y, f y ≠ y → ∃ i : ℤ, (f ^ i) x = y lemma is_cycle_swap {x y : α} (hxy : x ≠ y) : is_cycle (swap x y) := ⟨y, by rwa swap_apply_right, λ a (ha : ite (a = x) y (ite (a = y) x a) ≠ a), if hya : y = a then ⟨0, hya⟩ else ⟨1, by rw [gpow_one, swap_apply_def]; split_ifs at *; cc⟩⟩ lemma is_cycle_inv {f : perm β} (hf : is_cycle f) : is_cycle (f⁻¹) := let ⟨x, hx⟩ := hf in ⟨x, by simp [eq_inv_iff_eq, inv_eq_iff_eq, *] at *; cc, λ y hy, let ⟨i, hi⟩ := hx.2 y (by simp [eq_inv_iff_eq, inv_eq_iff_eq, *] at *; cc) in ⟨-i, by rwa [gpow_neg, inv_gpow, inv_inv]⟩⟩ lemma exists_gpow_eq_of_is_cycle {f : perm β} (hf : is_cycle f) {x y : β} (hx : f x ≠ x) (hy : f y ≠ y) : ∃ i : ℤ, (f ^ i) x = y := let ⟨g, hg⟩ := hf in let ⟨a, ha⟩ := hg.2 x hx in let ⟨b, hb⟩ := hg.2 y hy in ⟨b - a, by rw [← ha, ← mul_apply, ← gpow_add, sub_add_cancel, hb]⟩ lemma is_cycle_swap_mul_aux₁ : ∀ (n : ℕ) {b x : α} {f : perm α} (hb : (swap x (f x) * f) b ≠ b) (h : (f ^ n) (f x) = b), ∃ i : ℤ, ((swap x (f x) * f) ^ i) (f x) = b | 0 := λ b x f hb h, ⟨0, h⟩ | (n+1 : ℕ) := λ b x f hb h, if hfbx : f x = b then ⟨0, hfbx⟩ else have f b ≠ b ∧ b ≠ x, from ne_and_ne_of_swap_mul_apply_ne_self hb, have hb' : (swap x (f x) * f) (f⁻¹ b) ≠ f⁻¹ b, by rw [mul_apply, apply_inv_self, swap_apply_of_ne_of_ne this.2 (ne.symm hfbx), ne.def, ← injective.eq_iff f.bijective.1, apply_inv_self]; exact this.1, let ⟨i, hi⟩ := is_cycle_swap_mul_aux₁ n hb' (f.bijective.1 $ by rw [apply_inv_self]; rwa [pow_succ, mul_apply] at h) in ⟨i + 1, by rw [add_comm, gpow_add, mul_apply, hi, gpow_one, mul_apply, apply_inv_self, swap_apply_of_ne_of_ne (ne_and_ne_of_swap_mul_apply_ne_self hb).2 (ne.symm hfbx)]⟩ lemma is_cycle_swap_mul_aux₂ : ∀ (n : ℤ) {b x : α} {f : perm α} (hb : (swap x (f x) * f) b ≠ b) (h : (f ^ n) (f x) = b), ∃ i : ℤ, ((swap x (f x) * f) ^ i) (f x) = b | (n : ℕ) := λ b x f, is_cycle_swap_mul_aux₁ n | -[1+ n] := λ b x f hb h, if hfbx : f⁻¹ x = b then ⟨-1, by rwa [gpow_neg, gpow_one, mul_inv_rev, mul_apply, swap_inv, swap_apply_right]⟩ else if hfbx' : f x = b then ⟨0, hfbx'⟩ else have f b ≠ b ∧ b ≠ x := ne_and_ne_of_swap_mul_apply_ne_self hb, have hb : (swap x (f⁻¹ x) * f⁻¹) (f⁻¹ b) ≠ f⁻¹ b, by rw [mul_apply, swap_apply_def]; split_ifs; simp [inv_eq_iff_eq, eq_inv_iff_eq] at *; cc, let ⟨i, hi⟩ := is_cycle_swap_mul_aux₁ n hb (show (f⁻¹ ^ n) (f⁻¹ x) = f⁻¹ b, by rw [← gpow_coe_nat, ← h, ← mul_apply, ← mul_apply, ← mul_apply, gpow_neg_succ, ← inv_pow, pow_succ', mul_assoc, mul_assoc, inv_mul_self, mul_one, gpow_coe_nat, ← pow_succ', ← pow_succ]) in have h : (swap x (f⁻¹ x) * f⁻¹) (f x) = f⁻¹ x, by rw [mul_apply, inv_apply_self, swap_apply_left], ⟨-i, by rw [← add_sub_cancel i 1, neg_sub, sub_eq_add_neg, gpow_add, gpow_one, gpow_neg, ← inv_gpow, mul_inv_rev, swap_inv, mul_swap_eq_swap_mul, inv_apply_self, swap_comm _ x, gpow_add, gpow_one, mul_apply, mul_apply (_ ^ i), h, hi, mul_apply, apply_inv_self, swap_apply_of_ne_of_ne this.2 (ne.symm hfbx')]⟩ lemma eq_swap_of_is_cycle_of_apply_apply_eq_self {f : perm α} (hf : is_cycle f) {x : α} (hfx : f x ≠ x) (hffx : f (f x) = x) : f = swap x (f x) := equiv.ext _ _ $ λ y, let ⟨z, hz⟩ := hf in let ⟨i, hi⟩ := hz.2 x hfx in if hyx : y = x then by simp [hyx] else if hfyx : y = f x then by simp [hfyx, hffx] else begin rw [swap_apply_of_ne_of_ne hyx hfyx], refine by_contradiction (λ hy, _), cases hz.2 y hy with j hj, rw [← sub_add_cancel j i, gpow_add, mul_apply, hi] at hj, cases gpow_apply_eq_of_apply_apply_eq_self hffx (j - i) with hji hji, { rw [← hj, hji] at hyx, cc }, { rw [← hj, hji] at hfyx, cc } end lemma is_cycle_swap_mul {f : perm α} (hf : is_cycle f) {x : α} (hx : f x ≠ x) (hffx : f (f x) ≠ x) : is_cycle (swap x (f x) * f) := ⟨f x, by simp only [swap_apply_def, mul_apply]; split_ifs; simp [injective.eq_iff f.bijective.1] at *; cc, λ y hy, let ⟨i, hi⟩ := exists_gpow_eq_of_is_cycle hf hx (ne_and_ne_of_swap_mul_apply_ne_self hy).1 in have hi : (f ^ (i - 1)) (f x) = y, from calc (f ^ (i - 1)) (f x) = (f ^ (i - 1) * f ^ (1 : ℤ)) x : by rw [gpow_one, mul_apply] ... = y : by rwa [← gpow_add, sub_add_cancel], is_cycle_swap_mul_aux₂ (i - 1) hy hi⟩ @[simp] lemma support_swap [fintype α] {x y : α} (hxy : x ≠ y) : (swap x y).support = {x, y} := finset.ext.2 $ λ a, by simp [swap_apply_def]; split_ifs; cc lemma card_support_swap [fintype α] {x y : α} (hxy : x ≠ y) : (swap x y).support.card = 2 := show (swap x y).support.card = finset.card ⟨x::y::0, by simp [hxy]⟩, from congr_arg card $ by rw [support_swap hxy]; simp [*, finset.ext]; cc lemma sign_cycle [fintype α] : ∀ {f : perm α} (hf : is_cycle f), sign f = -(-1 ^ f.support.card) | f := λ hf, let ⟨x, hx⟩ := hf in calc sign f = sign (swap x (f x) * (swap x (f x) * f)) : by rw [← mul_assoc, mul_def, mul_def, swap_swap, trans_refl] ... = -(-1 ^ f.support.card) : if h1 : f (f x) = x then have h : swap x (f x) * f = 1, by conv in (f) {rw eq_swap_of_is_cycle_of_apply_apply_eq_self hf hx.1 h1 }; simp [mul_def, one_def], by rw [sign_mul, sign_swap hx.1.symm, h, sign_one, eq_swap_of_is_cycle_of_apply_apply_eq_self hf hx.1 h1, card_support_swap hx.1.symm]; refl else have h : card (support (swap x (f x) * f)) + 1 = card (support f), by rw [← insert_erase (mem_support.2 hx.1), support_swap_mul_eq h1, card_insert_of_not_mem (not_mem_erase _ _)], have wf : card (support (swap x (f x) * f)) < card (support f), from card_support_swap_mul hx.1, by rw [sign_mul, sign_swap hx.1.symm, sign_cycle (is_cycle_swap_mul hf hx.1 h1), ← h]; simp [pow_add] using_well_founded {rel_tac := λ _ _, `[exact ⟨_, measure_wf (λ f, f.support.card)⟩]} end sign end equiv.perm lemma finset.prod_univ_perm [fintype α] [comm_monoid β] {f : α → β} (σ : perm α) : (univ : finset α).prod f = univ.prod (λ z, f (σ z)) := eq.symm $ prod_bij (λ z _, σ z) (λ _ _, mem_univ _) (λ _ _, rfl) (λ _ _ _ _ H, σ.bijective.1 H) (λ b _, ⟨σ⁻¹ b, mem_univ _, by simp⟩) lemma finset.sum_univ_perm [fintype α] [add_comm_monoid β] {f : α → β} (σ : perm α) : (univ : finset α).sum f = univ.sum (λ z, f (σ z)) := @finset.prod_univ_perm _ (multiplicative β) _ _ f σ attribute [to_additive finset.sum_univ_perm] finset.prod_univ_perm
091be107c284d0437602809ad2e8166591656990
2a70b774d16dbdf5a533432ee0ebab6838df0948
/_target/deps/mathlib/src/ring_theory/finiteness.lean
090f8969bfb7923dac26826dfe214e54855681d1
[ "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
12,415
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 ring_theory.noetherian import ring_theory.ideal.operations import ring_theory.algebra_tower /-! # Finiteness conditions in commutative algebra In this file we define several notions of finiteness that are common in commutative algebra. ## Main declarations - `module.finite`, `algebra.finite`, `ring_hom.finite`, `alg_hom.finite` all of these express that some object is finitely generated *as module* over some base ring. - `algebra.finite_type`, `ring_hom.finite_type`, `alg_hom.finite_type` all of these express that some object is finitely generated *as algebra* over some base ring. -/ open function (surjective) open_locale big_operators section module_and_algebra variables (R A B M N : Type*) [comm_ring R] variables [comm_ring A] [algebra R A] [comm_ring B] [algebra R B] variables [add_comm_group M] [module R M] variables [add_comm_group N] [module R N] /-- A module over a commutative ring is `finite` if it is finitely generated as a module. -/ @[class] def module.finite : Prop := (⊤ : submodule R M).fg /-- An algebra over a commutative ring is of `finite_type` if it is finitely generated over the base ring as algebra. -/ @[class] def algebra.finite_type : Prop := (⊤ : subalgebra R A).fg /-- An algebra over a commutative ring is `finitely_presented` if it is the quotient of a polynomial ring in `n` variables by a finitely generated ideal. -/ def algebra.finitely_presented : Prop := ∃ (n : ℕ) (f : mv_polynomial (fin n) R →ₐ[R] A), surjective f ∧ f.to_ring_hom.ker.fg namespace module variables {R M N} lemma finite_def : finite R M ↔ (⊤ : submodule R M).fg := iff.rfl variables (R M N) @[priority 100] -- see Note [lower instance priority] instance is_noetherian.finite [is_noetherian R M] : finite R M := is_noetherian.noetherian ⊤ namespace finite variables {R M N} lemma of_surjective [hM : finite R M] (f : M →ₗ[R] N) (hf : surjective f) : finite R N := by { rw [finite, ← linear_map.range_eq_top.2 hf, ← submodule.map_top], exact submodule.fg_map hM } lemma of_injective [is_noetherian R N] (f : M →ₗ[R] N) (hf : function.injective f) : finite R M := fg_of_injective f $ linear_map.ker_eq_bot.2 hf variables (R) instance self : finite R R := ⟨{1}, by simpa only [finset.coe_singleton] using ideal.span_singleton_one⟩ variables {R} instance prod [hM : finite R M] [hN : finite R N] : finite R (M × N) := begin rw [finite, ← submodule.prod_top], exact submodule.fg_prod hM hN end lemma equiv [hM : finite R M] (e : M ≃ₗ[R] N) : finite R N := of_surjective (e : M →ₗ[R] N) e.surjective section algebra lemma trans [algebra A B] [is_scalar_tower R A B] [hRA : finite R A] [hAB : finite A B] : finite R B := let ⟨s, hs⟩ := hRA, ⟨t, ht⟩ := hAB in submodule.fg_def.2 ⟨set.image2 (•) (↑s : set A) (↑t : set B), set.finite.image2 _ s.finite_to_set t.finite_to_set, by rw [set.image2_smul, submodule.span_smul hs (↑t : set B), ht, submodule.restrict_scalars_top]⟩ @[priority 100] -- see Note [lower instance priority] instance finite_type [hRA : finite R A] : algebra.finite_type R A := subalgebra.fg_of_submodule_fg hRA end algebra end finite end module namespace algebra namespace finite_type lemma self : finite_type R R := ⟨{1}, subsingleton.elim _ _⟩ section open_locale classical protected lemma mv_polynomial (ι : Type*) [fintype ι] : finite_type R (mv_polynomial ι R) := ⟨finset.univ.image mv_polynomial.X, begin rw eq_top_iff, refine λ p, mv_polynomial.induction_on' p (λ u x, finsupp.induction u (subalgebra.algebra_map_mem _ x) (λ i n f hif hn ih, _)) (λ p q ihp ihq, subalgebra.add_mem _ ihp ihq), rw [add_comm, mv_polynomial.monomial_add_single], exact subalgebra.mul_mem _ ih (subalgebra.pow_mem _ (subset_adjoin $ finset.mem_image_of_mem _ $ finset.mem_univ _) _) end⟩ end variables {R A B} lemma of_surjective (hRA : finite_type R A) (f : A →ₐ[R] B) (hf : surjective f) : finite_type R B := begin rw [finite_type] at hRA ⊢, convert subalgebra.fg_map _ f hRA, simpa only [map_top f, @eq_comm _ ⊤, eq_top_iff, alg_hom.mem_range] using hf end lemma equiv (hRA : finite_type R A) (e : A ≃ₐ[R] B) : finite_type R B := hRA.of_surjective e e.surjective lemma trans [algebra A B] [is_scalar_tower R A B] (hRA : finite_type R A) (hAB : finite_type A B) : finite_type R B := fg_trans' hRA hAB /-- An algebra is finitely generated if and only if it is a quotient of a polynomial ring whose variables are indexed by a finset. -/ lemma iff_quotient_mv_polynomial : (finite_type R A) ↔ ∃ (s : finset A) (f : (mv_polynomial {x // x ∈ s} R) →ₐ[R] A), (surjective f) := begin split, { rintro ⟨s, hs⟩, use [s, mv_polynomial.aeval coe], intro x, have hrw : (↑s : set A) = (λ (x : A), x ∈ s.val) := rfl, rw [← set.mem_range, ← alg_hom.coe_range, ← adjoin_eq_range, ← hrw, hs], exact mem_top }, { rintro ⟨s, ⟨f, hsur⟩⟩, exact finite_type.of_surjective (finite_type.mv_polynomial R {x // x ∈ s}) f hsur } end /-- An algebra is finitely generated if and only if it is a quotient of a polynomial ring whose variables are indexed by a fintype. -/ lemma iff_quotient_mv_polynomial' : (finite_type R A) ↔ ∃ (ι : Type u_2) [fintype ι] (f : (mv_polynomial ι R) →ₐ[R] A), (surjective f) := begin split, { rw iff_quotient_mv_polynomial, rintro ⟨s, ⟨f, hsur⟩⟩, use [{x // x ∈ s}, by apply_instance, f, hsur] }, { rintro ⟨ι, ⟨hfintype, ⟨f, hsur⟩⟩⟩, letI : fintype ι := hfintype, exact finite_type.of_surjective (finite_type.mv_polynomial R ι) f hsur } end /-- An algebra is finitely generated if and only if it is a quotient of a polynomial ring in `n` variables. -/ lemma iff_quotient_mv_polynomial'' : (finite_type R A) ↔ ∃ (n : ℕ) (f : (mv_polynomial (fin n) R) →ₐ[R] A), (surjective f) := begin split, { rw iff_quotient_mv_polynomial', rintro ⟨ι, hfintype, ⟨f, hsur⟩⟩, obtain ⟨n, equiv⟩ := @fintype.exists_equiv_fin ι hfintype, replace equiv := mv_polynomial.alg_equiv_of_equiv R (nonempty.some equiv), use [n, alg_hom.comp f equiv.symm, function.surjective.comp hsur (alg_equiv.symm equiv).surjective] }, { rintro ⟨n, ⟨f, hsur⟩⟩, exact finite_type.of_surjective (finite_type.mv_polynomial R (fin n)) f hsur } end /-- A finitely presented algebra is of finite type. -/ lemma of_finitely_presented : finitely_presented R A → finite_type R A := begin rintro ⟨n, f, hf⟩, apply (finite_type.iff_quotient_mv_polynomial'').2, exact ⟨n, f, hf.1⟩ end end finite_type namespace finitely_presented /-- If `e : A ≃ₐ[R] B` and `A` is finitely presented, then so is `B`. -/ lemma equiv (hfp : finitely_presented R A) (e : A ≃ₐ[R] B) : finitely_presented R B := begin obtain ⟨n, f, hf⟩ := hfp, use [n, alg_hom.comp ↑e f], split, { exact function.surjective.comp e.surjective hf.1 }, suffices hker : (alg_hom.comp ↑e f).to_ring_hom.ker = f.to_ring_hom.ker, { rw hker, exact hf.2 }, { have hco : (alg_hom.comp ↑e f).to_ring_hom = ring_hom.comp ↑e.to_ring_equiv f.to_ring_hom, { have h : (alg_hom.comp ↑e f).to_ring_hom = e.to_alg_hom.to_ring_hom.comp f.to_ring_hom := rfl, have h1 : ↑(e.to_ring_equiv) = (e.to_alg_hom).to_ring_hom := rfl, rw [h, h1] }, rw [ring_hom.ker_eq_comap_bot, hco, ← ideal.comap_comap, ← ring_hom.ker_eq_comap_bot, ring_hom.ker_coe_equiv (alg_equiv.to_ring_equiv e), ring_hom.ker_eq_comap_bot] } end /-- The ring of polynomials in finitely many variables is finitely presented. -/ lemma mv_polynomial (ι : Type u_2) [fintype ι] : finitely_presented R (mv_polynomial ι R) := begin obtain ⟨n, equiv⟩ := @fintype.exists_equiv_fin ι _, replace equiv := mv_polynomial.alg_equiv_of_equiv R (nonempty.some equiv), use [n, alg_equiv.to_alg_hom equiv.symm], split, { exact (alg_equiv.symm equiv).surjective }, suffices hinj : function.injective equiv.symm.to_alg_hom.to_ring_hom, { rw [(ring_hom.injective_iff_ker_eq_bot _).1 hinj], exact submodule.fg_bot }, exact (alg_equiv.symm equiv).injective end /-- `R` is finitely presented as `R`-algebra. -/ lemma self : finitely_presented R R := begin letI hempty := mv_polynomial R pempty, exact @equiv R (_root_.mv_polynomial pempty R) R _ _ _ _ _ hempty (mv_polynomial.pempty_alg_equiv R) end end finitely_presented end algebra end module_and_algebra namespace ring_hom variables {A B C : Type*} [comm_ring A] [comm_ring B] [comm_ring C] /-- A ring morphism `A →+* B` is `finite` if `B` is finitely generated as `A`-module. -/ def finite (f : A →+* B) : Prop := by letI : algebra A B := f.to_algebra; exact module.finite A B /-- A ring morphism `A →+* B` is of `finite_type` if `B` is finitely generated as `A`-algebra. -/ def finite_type (f : A →+* B) : Prop := @algebra.finite_type A B _ _ f.to_algebra namespace finite variables (A) lemma id : finite (ring_hom.id A) := module.finite.self A variables {A} lemma of_surjective (f : A →+* B) (hf : surjective f) : f.finite := begin letI := f.to_algebra, exact module.finite.of_surjective (algebra.of_id A B).to_linear_map hf end lemma comp {g : B →+* C} {f : A →+* B} (hg : g.finite) (hf : f.finite) : (g.comp f).finite := @module.finite.trans A B C _ _ f.to_algebra _ (g.comp f).to_algebra g.to_algebra begin fconstructor, intros a b c, simp only [algebra.smul_def, ring_hom.map_mul, mul_assoc], refl end hf hg lemma finite_type {f : A →+* B} (hf : f.finite) : finite_type f := @module.finite.finite_type _ _ _ _ f.to_algebra hf end finite namespace finite_type variables (A) lemma id : finite_type (ring_hom.id A) := algebra.finite_type.self A variables {A} lemma comp_surjective {f : A →+* B} {g : B →+* C} (hf : f.finite_type) (hg : surjective g) : (g.comp f).finite_type := @algebra.finite_type.of_surjective A B C _ _ f.to_algebra _ (g.comp f).to_algebra hf { to_fun := g, commutes' := λ a, rfl, .. g } hg lemma of_surjective (f : A →+* B) (hf : surjective f) : f.finite_type := by { rw ← f.comp_id, exact (id A).comp_surjective hf } lemma comp {g : B →+* C} {f : A →+* B} (hg : g.finite_type) (hf : f.finite_type) : (g.comp f).finite_type := @algebra.finite_type.trans A B C _ _ f.to_algebra _ (g.comp f).to_algebra g.to_algebra begin fconstructor, intros a b c, simp only [algebra.smul_def, ring_hom.map_mul, mul_assoc], refl end hf hg end finite_type end ring_hom namespace alg_hom variables {R A B C : Type*} [comm_ring R] variables [comm_ring A] [comm_ring B] [comm_ring C] variables [algebra R A] [algebra R B] [algebra R C] /-- An algebra morphism `A →ₐ[R] B` is finite if it is finite as ring morphism. In other words, if `B` is finitely generated as `A`-module. -/ def finite (f : A →ₐ[R] B) : Prop := f.to_ring_hom.finite /-- An algebra morphism `A →ₐ[R] B` is of `finite_type` if it is of finite type as ring morphism. In other words, if `B` is finitely generated as `A`-algebra. -/ def finite_type (f : A →ₐ[R] B) : Prop := f.to_ring_hom.finite_type namespace finite variables (R A) lemma id : finite (alg_hom.id R A) := ring_hom.finite.id A variables {R A} lemma comp {g : B →ₐ[R] C} {f : A →ₐ[R] B} (hg : g.finite) (hf : f.finite) : (g.comp f).finite := ring_hom.finite.comp hg hf lemma of_surjective (f : A →ₐ[R] B) (hf : surjective f) : f.finite := ring_hom.finite.of_surjective f hf lemma finite_type {f : A →ₐ[R] B} (hf : f.finite) : finite_type f := ring_hom.finite.finite_type hf end finite namespace finite_type variables (R A) lemma id : finite_type (alg_hom.id R A) := ring_hom.finite_type.id A variables {R A} lemma comp {g : B →ₐ[R] C} {f : A →ₐ[R] B} (hg : g.finite_type) (hf : f.finite_type) : (g.comp f).finite_type := ring_hom.finite_type.comp hg hf lemma comp_surjective {f : A →ₐ[R] B} {g : B →ₐ[R] C} (hf : f.finite_type) (hg : surjective g) : (g.comp f).finite_type := ring_hom.finite_type.comp_surjective hf hg lemma of_surjective (f : A →ₐ[R] B) (hf : surjective f) : f.finite_type := ring_hom.finite_type.of_surjective f hf end finite_type end alg_hom
256d804e488e760ebbaefdd4ebfff53d87de0a2e
61c3861020ef87c6c325fc3c3dcbabf5d6b07985
/cubical/square.lean
ed76cface936f7ec0cea71cc1f9815499bd8b36d
[ "Apache-2.0" ]
permissive
jonas-frey/hott3
a623be2959e8a713c03fa1b0f34bf76a561dfa87
a944051b4eb5919bdc70978ee15fcbb48a824811
refs/heads/master
1,628,408,720,559
1,510,267,042,000
1,510,267,042,000
106,760,764
0
0
null
1,507,856,238,000
1,507,856,238,000
null
UTF-8
Lean
false
false
36,213
lean
/- 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 universes u v w hott_theory namespace hott open eq equiv is_equiv namespace eq variables {A : Type _} {B : Type _} {C : 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₄₄-/ {b : B} {c : C} inductive square {A : Type u} {a₀₀ : A} : Π{a₂₀ a₀₂ a₂₂ : A}, a₀₀ = a₂₀ → a₀₂ = a₂₂ → a₀₀ = a₀₂ → a₂₀ = a₂₂ → Type u | 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₄₃} @[hott, reducible] def ids := @square.ids @[hott, reducible] def idsquare (a : A) := @square.ids A a @[hott] def hrefl (p : a = a') : square idp idp p p := by induction p; exact ids @[hott] def vrefl (p : a = a') : square p p idp idp := by induction p; exact ids @[hott, reducible] def hrfl {p : a = a'} : square idp idp p p := hrefl _ @[hott, reducible] def vrfl {p : a = a'} : square p p idp idp := vrefl _ @[hott] def hdeg_square {p q : a = a'} (r : p = q) : square idp idp p q := by induction r;apply hrefl @[hott] def vdeg_square {p q : a = a'} (r : p = q) : square p q idp idp := by induction r;apply vrefl @[hott, hsimp] def hdeg_square_idp (p : a = a') : hdeg_square (refl p) = hrfl := idp @[hott, hsimp] def vdeg_square_idp (p : a = a') : vdeg_square (refl p) = vrfl := idp @[hott] def hconcat (s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁) (s₃₁ : square p₃₀ p₃₂ p₂₁ p₄₁) : square (p₁₀ ⬝ p₃₀) (p₁₂ ⬝ p₃₂) p₀₁ p₄₁ := by induction s₃₁; exact s₁₁ @[hott] def vconcat (s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁) (s₁₃ : square p₁₂ p₁₄ p₀₃ p₂₃) : square p₁₀ p₁₄ (p₀₁ ⬝ p₀₃) (p₂₁ ⬝ p₂₃) := by induction s₁₃; exact s₁₁ @[hott] def dconcat {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₂₁ @[hott] def hinverse (s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁) : square p₁₀⁻¹ p₁₂⁻¹ p₂₁ p₀₁ := by induction s₁₁;exact ids @[hott] def vinverse (s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁) : square p₁₂ p₁₀ p₀₁⁻¹ p₂₁⁻¹ := by induction s₁₁;exact ids @[hott] def eq_vconcat {p : a₀₀ = a₂₀} (r : p = p₁₀) (s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁) : square p p₁₂ p₀₁ p₂₁ := by induction r; exact s₁₁ @[hott] def vconcat_eq {p : a₀₂ = a₂₂} (s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁) (r : p₁₂ = p) : square p₁₀ p p₀₁ p₂₁ := by induction r; exact s₁₁ @[hott] def eq_hconcat {p : a₀₀ = a₀₂} (r : p = p₀₁) (s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁) : square p₁₀ p₁₂ p p₂₁ := by induction r; exact s₁₁ @[hott] def hconcat_eq {p : a₂₀ = a₂₂} (s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁) (r : p₂₁ = p) : square p₁₀ p₁₂ p₀₁ p := by induction r; exact s₁₁ infix ` ⬝h `:69 := hconcat --type using \tr infix ` ⬝v `:70 := vconcat --type using \tr infixl ` ⬝hp `:71 := hconcat_eq --type using \tr infixl ` ⬝vp `:73 := vconcat_eq --type using \tr infixr ` ⬝ph `:72 := eq_hconcat --type using \tr infixr ` ⬝pv `:74 := eq_vconcat --type using \tr postfix `⁻¹ʰ`:(max+1) := hinverse --type using \-1h postfix `⁻¹ᵛ`:(max+1) := vinverse --type using \-1v @[hott] def transpose (s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁) : square p₀₁ p₂₁ p₁₀ p₁₂ := by induction s₁₁;exact ids @[hott] def aps (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 -/ @[hott] def whisker_tl (p : a = a₀₀) (s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁) : square (p ⬝ p₁₀) p₁₂ (p ⬝ p₀₁) p₂₁ := by induction s₁₁;induction p;constructor @[hott] def whisker_br (p : a₂₂ = a) (s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁) : square p₁₀ (p₁₂ ⬝ p) p₀₁ (p₂₁ ⬝ p) := by induction p;exact s₁₁ @[hott] def whisker_rt (p : a = a₂₀) (s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁) : square (p₁₀ ⬝ p⁻¹) p₁₂ p₀₁ (p ⬝ p₂₁) := by induction s₁₁;induction p;constructor @[hott] def whisker_tr (p : a₂₀ = a) (s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁) : square (p₁₀ ⬝ p) p₁₂ p₀₁ (p⁻¹ ⬝ p₂₁) := by induction s₁₁;induction p;constructor @[hott] def whisker_bl (p : a = a₀₂) (s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁) : square p₁₀ (p ⬝ p₁₂) (p₀₁ ⬝ p⁻¹) p₂₁ := by induction s₁₁;induction p;constructor @[hott] def whisker_lb (p : a₀₂ = a) (s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁) : square p₁₀ (p⁻¹ ⬝ p₁₂) (p₀₁ ⬝ p) p₂₁ := by induction s₁₁;induction p;constructor @[hott] def cancel_tl (p : a = a₀₀) (s₁₁ : square (p ⬝ p₁₀) p₁₂ (p ⬝ p₀₁) p₂₁) : square p₁₀ p₁₂ p₀₁ p₂₁ := by induction p; hsimp at s₁₁; exact s₁₁ @[hott] def cancel_br (p : a₂₂ = a) (s₁₁ : square p₁₀ (p₁₂ ⬝ p) p₀₁ (p₂₁ ⬝ p)) : square p₁₀ p₁₂ p₀₁ p₂₁ := by induction p;exact s₁₁ @[hott] def cancel_rt (p : a = a₂₀) (s₁₁ : square (p₁₀ ⬝ p⁻¹) p₁₂ p₀₁ (p ⬝ p₂₁)) : square p₁₀ p₁₂ p₀₁ p₂₁ := by induction p; hsimp at s₁₁; exact s₁₁ @[hott] def cancel_tr (p : a₂₀ = a) (s₁₁ : square (p₁₀ ⬝ p) p₁₂ p₀₁ (p⁻¹ ⬝ p₂₁)) : square p₁₀ p₁₂ p₀₁ p₂₁ := by induction p; hsimp at s₁₁; exact s₁₁ @[hott] def cancel_bl (p : a = a₀₂) (s₁₁ : square p₁₀ (p ⬝ p₁₂) (p₀₁ ⬝ p⁻¹) p₂₁) : square p₁₀ p₁₂ p₀₁ p₂₁ := by induction p; hsimp at s₁₁; exact s₁₁ @[hott] def cancel_lb (p : a₀₂ = a) (s₁₁ : square p₁₀ (p⁻¹ ⬝ p₁₂) (p₀₁ ⬝ p) p₂₁) : square p₁₀ p₁₂ p₀₁ p₂₁ := by induction p; hsimp at s₁₁; exact s₁₁ @[hott] def 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; hsimp; exact s @[hott] def 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⁻¹; hsimp; exact s @[hott] def 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; hsimp; exact s @[hott] def 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⁻¹; hsimp; exact s @[hott] def 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; hsimp; exact s @[hott] def 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⁻¹; hsimp; exact s @[hott] def 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; hsimp; exact s @[hott] def 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⁻¹; hsimp; exact s @[hott] def 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; hsimp; exact s @[hott] def 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; hsimp; exact s @[hott] def 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; hsimp; exact s @[hott] def 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; hsimp; exact s /- some higher ∞-groupoid operations -/ @[hott] def vconcat_vrfl (s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁) : s₁₁ ⬝v vrefl p₁₂ = s₁₁ := by induction s₁₁; reflexivity @[hott] def hconcat_hrfl (s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁) : s₁₁ ⬝h hrefl p₂₁ = s₁₁ := by induction s₁₁; reflexivity /- equivalences -/ @[hott] def eq_of_square (s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁) : p₁₀ ⬝ p₂₁ = p₀₁ ⬝ p₁₂ := by induction s₁₁; apply idp @[hott] def square_of_eq (r : p₁₀ ⬝ p₂₁ = p₀₁ ⬝ p₁₂) : square p₁₀ p₁₂ p₀₁ p₂₁ := by induction p₁₂; dsimp at r; induction r; induction p₂₁; induction p₁₀; exact ids @[hott] def eq_top_of_square (s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁) : p₁₀ = p₀₁ ⬝ p₁₂ ⬝ p₂₁⁻¹ := by induction s₁₁; apply idp @[hott] def square_of_eq_top (r : p₁₀ = p₀₁ ⬝ p₁₂ ⬝ p₂₁⁻¹) : square p₁₀ p₁₂ p₀₁ p₂₁ := by induction p₂₁; induction p₁₂; dsimp at r;induction r;induction p₁₀;exact ids @[hott] def eq_bot_of_square (s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁) : p₁₂ = p₀₁⁻¹ ⬝ p₁₀ ⬝ p₂₁ := by induction s₁₁; apply idp @[hott] def square_of_eq_bot (r : p₀₁⁻¹ ⬝ p₁₀ ⬝ p₂₁ = p₁₂) : square p₁₀ p₁₂ p₀₁ p₂₁ := by induction p₂₁; induction p₁₀; dsimp at r; induction r; induction p₀₁; exact ids @[hott] def square_equiv_eq (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, dsimp [concat] at s, induction s, induction r, induction t, apply idp}, { intro s, induction s, apply idp}, end @[hott] def hdeg_square_equiv' (p q : a = a') : square idp idp p q ≃ p = q := begin transitivity, {apply square_equiv_eq}, transitivity, {apply eq_equiv_eq_symm}, {apply equiv_eq_closed_right, apply idp_con}, end @[hott] def vdeg_square_equiv' (p q : a = a') : square p q idp idp ≃ p = q := begin transitivity, {apply square_equiv_eq}, {apply equiv_eq_closed_right, apply idp_con}, end @[hott] def eq_of_hdeg_square {p q : a = a'} (s : square idp idp p q) : p = q := to_fun (hdeg_square_equiv' _ _) s @[hott] def eq_of_vdeg_square {p q : a = a'} (s : square p q idp idp) : p = q := to_fun (vdeg_square_equiv' _ _) s @[hott] def 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 @[hott] def 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 @[hott] def -/ @[hott] def hdeg_square_equiv (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 @[hott] def vdeg_square_equiv (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') : (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 -/ @[hott] def eq_pathover {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; λ a, f a = g a] r := begin induction p, apply pathover_idp_of_eq, exact eq_of_vdeg_square s end @[hott] def 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; λ a, b = g a] r := eq_pathover (ap_constant p b ⬝ph s) @[hott] def 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; λ a, a = g a] r := eq_pathover (ap_id p ⬝ph s) @[hott] def 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; λ a, f a = b] r := eq_pathover (s ⬝hp (ap_constant p b)⁻¹) @[hott] def 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; λ a, f a = a] r := eq_pathover (s ⬝hp (ap_id p)⁻¹) @[hott] def square_of_pathover {f g : A → B} {p : a = a'} {q : f a = g a} {r : f a' = g a'} (s : q =[p; λ a, f a = g a] r) : square q r (ap f p) (ap g p) := by induction p;apply vdeg_square;exact (eq_of_pathover_idp s) @[hott] def 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)⁻¹) @[hott] def 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; λ a, a = a₀] r := eq_pathover (ap_id p ⬝ph s ⬝hp (ap_constant p a₀)⁻¹) @[hott] def loop_pathover {p : a = a'} {q : a = a} {r : a' = a'} (s : square q r p p) : q =[p; λ a, a = a] r := eq_pathover (ap_id p ⬝ph s ⬝hp (ap_id p)⁻¹) /- interaction of equivalences with operations on squares -/ @[hott] def eq_pathover_equiv_square {f g : A → B} (p : a = a') (q : f a = g a) (r : f a' = g a') : q =[p; λ a, f a = g a] r ≃ square q r (ap f p) (ap g p) := equiv.MK square_of_pathover eq_pathover begin intro s, induction p, dsimp [square_of_pathover,eq_pathover], transitivity, {apply ap vdeg_square, apply to_right_inv (pathover_idp _ _ _)}, {apply to_left_inv (vdeg_square_equiv _ _)} end begin intro s, induction p, dsimp [square_of_pathover,eq_pathover], transitivity, {apply ap (pathover_idp_of_eq _), apply to_right_inv (vdeg_square_equiv _ _)}, {apply to_left_inv (pathover_idp _ _ _)}, end @[hott] def 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; λ a, f a = g a] r) : square_of_pathover (s' ⬝po s) = s' ⬝pv square_of_pathover s := by induction s;induction s';reflexivity @[hott] def 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; λ a, f a = g a] r) : square_of_pathover (s ⬝op s') = square_of_pathover s ⬝vp s' := by induction s;induction s';reflexivity @[hott] def 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; λ a, f a = g a] q') (s' : q' =[p'; λ a, f a = g a] 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; symmetry; apply vconcat_vrfl @[hott] def eq_of_square_hrfl (p : a = a') : eq_of_square hrfl = idp_con p := by induction p;reflexivity @[hott] def eq_of_square_vrfl (p : a = a') : eq_of_square vrfl = (idp_con p)⁻¹ := by induction p;reflexivity @[hott] def 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 @[hott] def 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 @[hott] def 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₁₁; eq_cases r;reflexivity @[hott] def 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 @[hott] def 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 @[hott] def 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 @[hott] def change_path_eq_pathover {A B : Type _} {a a' : A} {f g : A → B} {p p' : a = a'} (r : p = p') {q : f a = g a} {q' : f a' = g a'} (s : square q q' (ap f p) (ap g p)) : change_path r (eq_pathover s) = eq_pathover ((ap02 f r)⁻¹ ⬝ph s ⬝hp (ap02 g r)) := by induction r; reflexivity @[hott] def eq_hconcat_hdeg_square {A : Type _} {a a' : A} {p₁ p₂ p₃ : a = a'} (q₁ : p₁ = p₂) (q₂ : p₂ = p₃) : q₁ ⬝ph hdeg_square q₂ = hdeg_square (q₁ ⬝ q₂) := by induction q₁; induction q₂; reflexivity @[hott] def hdeg_square_hconcat_eq {A : Type _} {a a' : A} {p₁ p₂ p₃ : a = a'} (q₁ : p₁ = p₂) (q₂ : p₂ = p₃) : hdeg_square q₁ ⬝hp q₂ = hdeg_square (q₁ ⬝ q₂) := by induction q₁; induction q₂; reflexivity @[hott] def eq_hconcat_eq_hdeg_square {A : Type _} {a a' : A} {p₁ p₂ p₃ p₄ : a = a'} (q₁ : p₁ = p₂) (q₂ : p₂ = p₃) (q₃ : p₃ = p₄) : q₁ ⬝ph hdeg_square q₂ ⬝hp q₃ = hdeg_square (q₁ ⬝ q₂ ⬝ q₃) := by induction q₃; apply eq_hconcat_hdeg_square -- @[hott] def 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₁₁ -- @[hott] def 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₁₁ -- @[hott] def 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₁₁ /- recursors for squares where some sides are reflexivity -/ @[hott,elab_as_eliminator] def rec_on_b {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)), begin induction r, induction t, hgeneralize: eq_of_square s = es, dsimp at es, induction es, apply H end, left_inv (square_equiv_eq _ _ _ _).to_fun s ▸ H2 @[hott, elab_as_eliminator] def rec_on_r {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), have H3 : square_of_eq (eq_of_square s) = s, from left_inv (square_equiv_eq _ _ _ _).to_fun s, by rwra [inv_inv, H3] at H2 @[hott, elab_as_eliminator] def rec_on_l {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), have H3 : square_of_eq (eq_of_square s) = s, from left_inv (square_equiv_eq _ _ _ _).to_fun s, by rwra [con_inv_cancel_right, H3] at H2 @[hott, elab_as_eliminator] def rec_on_t {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)⁻¹⁻¹)), by rwra con_inv_cancel_right at H2, have H4 : P (square_of_eq (eq_of_square s)), by hsimp at H3; apply H3, left_inv (square_equiv_eq _ _ _ _).to_fun s ▸ H4 @[hott, elab_as_eliminator] def rec_on_tb {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)), begin induction r, hgeneralize: eq_of_square s = es, dsimp at es, induction es, apply H, end, left_inv (square_equiv_eq _ _ _ _).to_fun s ▸ H2 @[hott, elab_as_eliminator] def rec_on_lr {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), have H3 : square_of_eq (eq_of_square s) = s, from left_inv (square_equiv_eq _ _ _ _).to_fun s, by rwra [inv_inv, H3] at 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 @[hott] def whisker_square (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 -/ @[hott] def 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 @[hott] def 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 @[hott] def is_set.elims [H : is_set A] : square p₁₀ p₁₂ p₀₁ p₂₁ := square_of_eq (is_set.elim _ _) @[hott, instance] def is_trunc_square (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 _ _ _ _) (by apply_instance) -- @[hott] def 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₂₁) @[hott] def square_fill_t : Σ (p : a₀₀ = a₂₀), square p p₁₂ p₀₁ p₂₁ := by induction p₀₁; induction p₂₁; exact ⟨_, vrefl _⟩ @[hott] def square_fill_b : Σ (p : a₀₂ = a₂₂), square p₁₀ p p₀₁ p₂₁ := by induction p₀₁; induction p₂₁; exact ⟨_, vrefl _⟩ @[hott] def square_fill_l : Σ (p : a₀₀ = a₀₂), square p₁₀ p₁₂ p p₂₁ := by induction p₁₀; induction p₁₂; exact ⟨_, hrefl _⟩ @[hott] def 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 @[hott] def 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 @[hott] def 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 @[hott] def 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₁₁) @[hott] def 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 induction r; induction s₁₁; refl @[hott] def 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 induction r; induction s₁₁; refl @[hott] def hp_eq_h {p : a₂₀ = a₂₂} (r : p₂₁ = p) : s₁₁ ⬝hp r = s₁₁ ⬝h hdeg_square r := by induction r; induction s₁₁; refl @[hott] def 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 induction r; induction s₁₁; refl @[hott] def 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 induction r; induction s₁₁; refl @[hott] def vp_eq_v {p : a₀₂ = a₂₂} (r : p₁₂ = p) : s₁₁ ⬝vp r = s₁₁ ⬝v vdeg_square r := by induction r; induction s₁₁; refl @[hott] def natural_square {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) @[hott] def natural_square_tr {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) @[hott] def 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 @[hott] def 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; id] 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, dsimp at s, apply idp_rec_on s, 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) @[hott] def 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; id] 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 : C b), f (m c)) p q r) (apd0111 f p q r) (s c) (s c') := begin induction q, dsimp at r, apply idp_rec_on r, exact hrfl end /- some higher coherence conditions -/ @[hott] theorem whisker_bl_whisker_tl_eq (p : a = a') : whisker_bl p (whisker_tl p ids) = con.right_inv p ⬝ph vrfl := by induction p; reflexivity @[hott] theorem ap_is_constant_natural_square {g : B → C} {f : A → B} (H : Πa, g (f a) = c) (p : a = a') : (ap_is_constant H p)⁻¹ ⬝ph natural_square H p ⬝hp ap_constant p c = whisker_bl (H a') (whisker_tl (H a) ids) := begin induction p, dsimp [ap_is_constant], rwr [inv_inv, whisker_bl_whisker_tl_eq] end @[hott] def inv_ph_eq_of_eq_ph {p : a₀₀ = a₀₂} {r : p₀₁ = p} {s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁} {s₁₁' : square p₁₀ p₁₂ p p₂₁} (t : s₁₁ = r ⬝ph s₁₁') : r⁻¹ ⬝ph s₁₁ = s₁₁' := by induction r; exact t -- the following is used for torus.elim_surf @[hott] theorem whisker_square_aps_eq {f : A → B} {q₁₀ : f a₀₀ = f a₂₀} {q₀₁ : f a₀₀ = f a₀₂} {q₂₁ : f a₂₀ = f a₂₂} {q₁₂ : f a₀₂ = f a₂₂} {r₁₀ : ap f p₁₀ = q₁₀} {r₀₁ : ap f p₀₁ = q₀₁} {r₂₁ : ap f p₂₁ = q₂₁} {r₁₂ : ap f p₁₂ = q₁₂} {s₁₁ : p₁₀ ⬝ p₂₁ = p₀₁ ⬝ p₁₂} {t₁₁ : square q₁₀ q₁₂ q₀₁ q₂₁} (u : square (ap02 f s₁₁) (eq_of_square t₁₁) (ap_con f p₁₀ p₂₁ ⬝ (r₁₀ ◾ r₂₁)) (ap_con f p₀₁ p₁₂ ⬝ (r₀₁ ◾ r₁₂))) : whisker_square r₁₀ r₁₂ r₀₁ r₂₁ (aps f (square_of_eq s₁₁)) = t₁₁ := begin induction r₁₀, induction r₀₁, induction r₁₂, induction r₂₁, induction p₁₂, induction p₁₀, induction p₂₁, dsimp at *, induction s₁₁, dsimp at *, dsimp [square_of_eq], apply eq_of_fn_eq_fn (square_equiv_eq _ _ _ _), dsimp, exact (eq_bot_of_square u)⁻¹ end @[hott] def natural_square_eq {A B : Type _} {a a' : A} {f g : A → B} (p : f ~ g) (q : a = a') : natural_square p q = square_of_pathover (apd p q) := idp @[hott] def eq_of_square_hrfl_hconcat_eq {A : Type _} {a a' : A} {p p' : a = a'} (q : p = p') : eq_of_square (hrfl ⬝hp q⁻¹) = !idp_con ⬝ q := by induction q; induction p; reflexivity @[hott, hsimp] def aps_vrfl {A B : Type _} {a a' : A} (f : A → B) (p : a = a') : aps f (vrefl p) = vrefl (ap f p) := by induction p; reflexivity @[hott, hsimp] def aps_hrfl {A B : Type _} {a a' : A} (f : A → B) (p : a = a') : aps f (hrefl p) = hrefl (ap f p) := by induction p; reflexivity -- should the following two equalities be cubes? @[hott] def natural_square_ap_fn {A B C : Type _} {a a' : A} {g h : A → B} (f : B → C) (p : g ~ h) (q : a = a') : natural_square (λa, ap f (p a)) q = ap_compose f g q ⬝ph (aps f (natural_square p q) ⬝hp (ap_compose f h q)⁻¹) := begin induction q, exact (aps_vrfl _ _).inverse end @[hott] def natural_square_compose {A B C : Type _} {a a' : A} {g g' : B → C} (p : g ~ g') (f : A → B) (q : a = a') : natural_square (λa, p (f a)) q = ap_compose g f q ⬝ph (natural_square p (ap f q) ⬝hp (ap_compose g' f q)⁻¹) := by induction q; reflexivity @[hott] def natural_square_eq2 {A B : Type _} {a a' : A} {f f' : A → B} (p : f ~ f') {q q' : a = a'} (r : q = q') : natural_square p q = ap02 f r ⬝ph (natural_square p q' ⬝hp (ap02 f' r)⁻¹) := by induction r; reflexivity @[hott, hsimp] def natural_square_refl {A B : Type _} {a a' : A} (f : A → B) (q : a = a') : natural_square (homotopy.refl f) q = hrfl := by induction q; reflexivity @[hott] def aps_eq_hconcat {p₀₁'} (f : A → B) (q : p₀₁' = p₀₁) (s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁) : aps f (q ⬝ph s₁₁) = ap02 f q ⬝ph aps f s₁₁ := by induction q; reflexivity @[hott] def aps_hconcat_eq {p₂₁'} (f : A → B) (s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁) (r : p₂₁' = p₂₁) : aps f (s₁₁ ⬝hp r⁻¹) = aps f s₁₁ ⬝hp (ap02 f r)⁻¹ := by induction r; reflexivity @[hott] def aps_hconcat_eq' {p₂₁'} (f : A → B) (s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁) (r : p₂₁ = p₂₁') : aps f (s₁₁ ⬝hp r) = aps f s₁₁ ⬝hp ap02 f r := by induction r; reflexivity @[hott] def aps_square_of_eq (f : A → B) (s : p₁₀ ⬝ p₂₁ = p₀₁ ⬝ p₁₂) : aps f (square_of_eq s) = square_of_eq ((ap_con f p₁₀ p₂₁)⁻¹ ⬝ ap02 f s ⬝ ap_con f p₀₁ p₁₂) := by induction p₁₂; dsimp at *; induction s; induction p₂₁; induction p₁₀; reflexivity @[hott] def aps_eq_hconcat_eq {p₀₁' p₂₁'} (f : A → B) (q : p₀₁' = p₀₁) (s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁) (r : p₂₁' = p₂₁) : aps f (q ⬝ph s₁₁ ⬝hp r⁻¹) = ap02 f q ⬝ph aps f s₁₁ ⬝hp (ap02 f r)⁻¹ := by induction q; induction r; reflexivity end eq end hott
6dd2646b7aa30dba71675c8101fbaf11b07de99d
5d166a16ae129621cb54ca9dde86c275d7d2b483
/library/init/data/array/basic.lean
e5f16a2faf577ddd8268b5f98631a5031ebf022b
[ "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
4,512
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 -/ prelude import init.data.nat universes u w structure array (α : Type u) (n : nat) := (data : fin n → α) def mk_array {α} (n) (v : α) : array α n := {data := λ _, v} namespace array variables {α : Type u} {β : Type w} {n : nat} def nil {α} : array α 0 := {data := λ ⟨x, h⟩, absurd h (nat.not_lt_zero x)} def read (a : array α n) (i : fin n) : α := a.data i def read' [inhabited α] (a : array α n) (i : nat) : α := if h : i < n then a.read ⟨i,h⟩ else default α def write (a : array α n) (i : fin n) (v : α) : array α n := {data := λ j, if i = j then v else a.read j} def write' (a : array α n) (i : nat) (v : α) : array α n := if h : i < n then a.write ⟨i, h⟩ v else a lemma push_back_idx {j n} (h₁ : j < n + 1) (h₂ : j ≠ n) : j < n := nat.lt_of_le_and_ne (nat.le_of_lt_succ h₁) h₂ def push_back (a : array α n) (v : α) : array α (n+1) := {data := λ ⟨j, h₁⟩, if h₂ : j = n then v else a.read ⟨j, push_back_idx h₁ h₂⟩} lemma pop_back_idx {j n} (h : j < n) : j < n + 1 := nat.lt.step h def pop_back (a : array α (n+1)) : array α n := {data := λ ⟨j, h⟩, a.read ⟨j, pop_back_idx h⟩} lemma lt_aux_1 {a b c : nat} (h : a + c < b) : a < b := lt_of_le_of_lt (nat.le_add_right a c) h lemma lt_aux_2 {n} (h : n > 0) : n - 1 < n := have h₁ : 1 > 0, from dec_trivial, nat.sub_lt h h₁ lemma lt_aux_3 {n i} (h : i + 1 < n) : n - 2 - i < n := have n > 0, from lt.trans (nat.zero_lt_succ i) h, have n - 2 < n, from nat.sub_lt this (dec_trivial), lt_of_le_of_lt (nat.sub_le _ _) this @[elab_as_eliminator] theorem write_ind (a : array α n) (i : fin n) (v : α) (C : fin n → α → Sort w) (Hi : C i v) (Hj : ∀j, i ≠ j → C j (a.read j)) (j) : C j ((a.write i v).read j) := show C j (if i = j then v else read a j), from if h : i = j then by rwa [if_pos h, -h] else by rw [if_neg h]; exact Hj j h def foreach_aux (f : fin n → α → α) : Π (i : nat), i ≤ n → array α n → array α n | 0 h a := a | (j+1) h a := let i : fin n := ⟨n - 1 - j, nat.sub_one_sub_lt h⟩ in foreach_aux j (le_of_lt h) (a.write i (f i (a.read i))) def foreach (a : array α n) (f : fin n → α → α) : array α n := foreach_aux f n (le_refl _) a def map (f : α → α) (a : array α n) : array α n := foreach a (λ _, f) def map₂ (f : α → α → α) (a b : array α n) : array α n := foreach b (λ i, f (a.read i)) def iterate_aux (a : array α n) (f : fin n → α → β → β) : Π (i : nat), i ≤ n → β → β | 0 h b := b | (j+1) h b := let i : fin n := ⟨j, h⟩ in f i (a.read i) (iterate_aux j (le_of_lt h) b) def iterate (a : array α n) (b : β) (fn : fin n → α → β → β) : β := iterate_aux a fn n (le_refl _) b def foldl (a : array α n) (b : β) (f : α → β → β) : β := iterate a b (λ _, f) def rev_list (a : array α n) : list α := a.foldl [] (λ v l, v :: l) def foldl_eq_aux (a : array α n) (b : β) (f : α → β → β) : Π (i : nat) (h : i ≤ n), iterate_aux a (λ _, f) i h b = (iterate_aux a (λ _ v l, v :: l) i h []).foldr f b | 0 h := rfl | (j+1) h := congr_arg (f (read a ⟨j, h⟩)) (foldl_eq_aux j _) def foldl_eq (a : array α n) (b : β) (f : α → β → β) : a.foldl b f = a.rev_list.foldr f b := foldl_eq_aux a b f _ _ def rev_iterate_aux (a : array α n) (f : fin n → α → β → β) : Π (i : nat), i ≤ n → β → β | 0 h b := b | (j+1) h b := let i : fin n := ⟨j, h⟩ in rev_iterate_aux j (le_of_lt h) (f i (a.read i) b) def rev_iterate (a : array α n) (b : β) (fn : fin n → α → β → β) : β := rev_iterate_aux a fn n (le_refl _) b def to_list (a : array α n) : list α := a.rev_iterate [] (λ _ v l, v :: l) protected def mem (v : α) (a : array α n) : Prop := ∃i, read a i = v instance : has_mem α (array α n) := ⟨array.mem⟩ theorem read_mem (a : array α n) (i) : read a i ∈ a := exists.intro i rfl instance [has_to_string α] : has_to_string (array α n) := ⟨to_string ∘ to_list⟩ meta instance [has_to_format α] : has_to_format (array α n) := ⟨to_fmt ∘ to_list⟩ meta instance [has_to_tactic_format α] : has_to_tactic_format (array α n) := ⟨tactic.pp ∘ to_list⟩ end array def list.to_array {α} (l : list α) : array α l.length := {data := λ v, l.nth_le v.1 v.2}
1c078e90b4890214c361f8e54d56a119f5ff823f
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/playground/parser/syntax.lean
302aea54926adca41d79848ebb7075112e6953c7
[ "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
10,671
lean
/- Copyright (c) 2018 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Sebastian Ullrich, Leonardo de Moura -/ prelude import init.lean.name init.lean.format init.data.array -- set_option trace.compiler.ir.borrow true -- namespace Lean namespace Parser open Lean /-- A hygiene marker introduced by a macro expansion. -/ @[derive DecidableEq HasFormat] def MacroScope := Nat abbrev MacroScopes := List MacroScope structure SourceInfo := /- Will be inferred after parsing by `Syntax.updateLeading`. During parsing, it is not at all clear what the preceding token was, especially with backtracking. -/ (leading : Substring) (pos : String.Pos) (trailing : Substring) def SourceInfo.updateTrailing : SourceInfo → Substring → SourceInfo | ⟨leading, pos, _⟩ trailing := ⟨leading, pos, trailing⟩ /- Node kind generation -/ def mkUniqIdRef : IO (IO.Ref Nat) := IO.mkRef 0 @[init mkUniqIdRef] constant nextUniqId : IO.Ref Nat := default _ structure SyntaxNodeKind := (name : Name) (id : Nat) instance stxKindInh : Inhabited SyntaxNodeKind := ⟨{name := default _, id := default _}⟩ instance stxKindBeq : BEq SyntaxNodeKind := ⟨λ k₁ k₂, k₁.id == k₂.id⟩ def mkNameToKindTable : IO (IO.Ref (NameMap Nat)) := IO.mkRef {} @[init mkNameToKindTable] constant nameToKindTable : IO.Ref (NameMap Nat) := default _ def nextKind (k : Name) : IO SyntaxNodeKind := do m ← nameToKindTable.get, when (m.contains k) (throw $ IO.userError ("kind '" ++ toString k ++ "' already exists")), id ← nextUniqId.get, nameToKindTable.set (m.insert k id), nextUniqId.set (id+1), pure { name := k, id := id } /- Basic node kinds -/ def mkNullKind : IO SyntaxNodeKind := nextKind `null @[init mkNullKind] constant nullKind : SyntaxNodeKind := default _ def mkChoiceKind : IO SyntaxNodeKind := nextKind `choice @[init mkChoiceKind] constant choiceKind : SyntaxNodeKind := default _ def mkOptionSomeKind : IO SyntaxNodeKind := nextKind `some @[init mkOptionSomeKind] constant optionSomeKind : SyntaxNodeKind := default _ def mkOptionNoneKind : IO SyntaxNodeKind := nextKind `none @[init mkOptionNoneKind] constant optionNoneKind : SyntaxNodeKind := default _ def mkManyKind : IO SyntaxNodeKind := nextKind `many @[init mkManyKind] constant manyKind : SyntaxNodeKind := default _ def mkHoleKind : IO SyntaxNodeKind := nextKind `hole /- Syntax AST -/ inductive Syntax | missing | node (kind : SyntaxNodeKind) (args : Array Syntax) (scopes : MacroScopes) | atom (info : Option SourceInfo) (val : String) | ident (info : Option SourceInfo) (rawVal : Substring) (val : Name) (preresolved : List Name) (scopes : MacroScopes) instance stxInh : Inhabited Syntax := ⟨Syntax.missing⟩ def SyntaxNodeKind.fix : SyntaxNodeKind → IO SyntaxNodeKind | {name := n, ..} := do m ← nameToKindTable.get, match m.find n with | some id := pure {name := n, id := id} | none := throw $ IO.userError ("Error unknown Syntax kind '" ++ toString n ++ "'") partial def Syntax.fixKinds : Syntax → IO Syntax | (Syntax.node k args scopes) := do k ← k.fix, args ← args.mmap Syntax.fixKinds, pure (Syntax.node k args scopes) | other := pure other inductive IsNode : Syntax → Prop | mk (kind : SyntaxNodeKind) (args : Array Syntax) (scopes : MacroScopes) : IsNode (Syntax.node kind args scopes) def SyntaxNode : Type := {s : Syntax // IsNode s } def notIsNodeMissing (h : IsNode Syntax.missing) : False := match h with end def notIsNodeAtom {info val} (h : IsNode (Syntax.atom info val)) : False := match h with end def notIsNodeIdent {info rawVal val preresolved scopes} (h : IsNode (Syntax.ident info rawVal val preresolved scopes)) : False := match h with end def unreachIsNodeMissing {α : Type} (h : IsNode Syntax.missing) : α := False.elim (notIsNodeMissing h) def unreachIsNodeAtom {α : Type} {info val} (h : IsNode (Syntax.atom info val)) : α := False.elim (notIsNodeAtom h) def unreachIsNodeIdent {α : Type} {info rawVal val preresolved scopes} (h : IsNode (Syntax.ident info rawVal val preresolved scopes)) : α := False.elim (match h with end) @[inline] def withArgs {α : Type} (n : SyntaxNode) (fn : Array Syntax → α) : α := match n with | ⟨Syntax.node _ args _, _⟩ := fn args | ⟨Syntax.missing, h⟩ := unreachIsNodeMissing h | ⟨Syntax.atom _ _, h⟩ := unreachIsNodeAtom h | ⟨Syntax.ident _ _ _ _ _, h⟩ := unreachIsNodeIdent h @[inline] def updateArgs (n : SyntaxNode) (fn : Array Syntax → Array Syntax) : Syntax := match n with | ⟨Syntax.node kind args scopes, _⟩ := Syntax.node kind (fn args) scopes | ⟨Syntax.missing, h⟩ := unreachIsNodeMissing h | ⟨Syntax.atom _ _, h⟩ := unreachIsNodeAtom h | ⟨Syntax.ident _ _ _ _ _, h⟩ := unreachIsNodeIdent h -- TODO(Sebastian): exhaustively argue why (if?) this is correct -- The basic idea is List concatenation with elimination of adjacent identical scopes def MacroScopes.flip : MacroScopes → MacroScopes → MacroScopes | ys [] := ys | ys (x::xs) := match MacroScopes.flip ys xs with | y::ys := if x == y then ys else x::y::ys | [] := [x] namespace Syntax def isIdent : Syntax → Bool | (Syntax.ident _ _ _ _ _) := true | _ := false def isOfKind : Syntax → SyntaxNodeKind → Bool | (Syntax.node kind _ _) k := k == kind | other _ := false def flipScopes (scopes : MacroScopes) : Syntax → Syntax | (Syntax.ident info rawVal val pre scopes) := Syntax.ident info rawVal val pre (scopes.flip scopes) | (Syntax.node kind args scopes) := Syntax.node kind args (scopes.flip scopes) | other := other @[inline] def toSyntaxNode {α : Type} (s : Syntax) (base : α) (fn : SyntaxNode → α) : α := match s with | Syntax.node kind args [] := fn ⟨Syntax.node kind args [], IsNode.mk _ _ _⟩ | Syntax.node kind args scopes := fn ⟨Syntax.node kind (args.map (flipScopes scopes)) [], IsNode.mk _ _ _⟩ | other := base local attribute [instance] monadInhabited @[specialize] partial def mreplace {m : Type → Type} [Monad m] (fn : Syntax → m (Option Syntax)) : Syntax → m Syntax | stx@(node kind args scopes) := do o ← fn stx, (match o with | some stx := pure stx | none := do args ← args.mmap mreplace, pure (node kind args scopes)) | stx := do o ← fn stx, pure (o.getOrElse stx) @[inline] def replace {m : Type → Type} [Monad m] (fn : Syntax → m (Option Syntax)) := @mreplace Id _ private def updateInfo : SourceInfo → String.Pos → SourceInfo | {leading := {str := s, startPos := _, stopPos := _}, pos := pos, trailing := trailing} last := {leading := {str := s, startPos := last, stopPos := pos}, pos := pos, trailing := trailing} /- Remark: the State `String.Pos` is the `SourceInfo.trailing.endPos` of the previous token, or the beginning of the String. -/ @[inline] private def updateLeadingAux : Syntax → State String.Pos (Option Syntax) | (atom (some info) val) := do last ← get, set info.trailing.stopPos, let newInfo := updateInfo info last in pure $ some (atom (some newInfo) val) | (ident (some info) rawVal val pre scopes) := do last ← get, set info.trailing.stopPos, let newInfo := updateInfo info last in pure $ some (ident (some newInfo) rawVal val pre scopes) | _ := pure none /-- Set `SourceInfo.leading` according to the trailing stop of the preceding token. The Result is a round-tripping Syntax tree IF, in the input Syntax tree, * all leading stops, atom contents, and trailing starts are correct * trailing stops are between the trailing start and the next leading stop. Remark: after parsing all `SourceInfo.leading` fields are Empty. The Syntax argument is the output produced by the Parser for `source`. This Function "fixes" the `source.leanding` field. Note that, the `SourceInfo.trailing` fields are correct. The implementation of this Function relies on this property. -/ def updateLeading : Syntax → Syntax := λ stx, Prod.fst <$> (mreplace updateLeadingAux stx).run 0 partial def updateTrailing (trailing : Substring) : Syntax → Syntax | (Syntax.atom (some info) val) := Syntax.atom (some (info.updateTrailing trailing)) val | (Syntax.ident (some info) rawVal val pre scopes) := Syntax.ident (some (info.updateTrailing trailing)) rawVal val pre scopes | n@(Syntax.node k args scopes) := if args.size == 0 then n else let i := args.size - 1 in let last := updateTrailing (args.get i) in let args := args.set i last in Syntax.node k args scopes | other := other /-- Retrieve the left-most leaf's info in the Syntax tree. -/ partial def getHeadInfo : Syntax → Option SourceInfo | (atom info _) := info | (ident info _ _ _ _ ) := info | (node _ args _) := args.find getHeadInfo | _ := none def getPos (stx : Syntax) : Option String.Pos := SourceInfo.pos <$> stx.getHeadInfo private def reprintLeaf : Option SourceInfo → String → String | none val := val | (some info) val := info.leading.toString ++ val ++ info.trailing.toString partial def reprint : Syntax → Option String | (atom info val) := reprintLeaf info val | (ident info rawVal _ _ _) := reprintLeaf info rawVal.toString | (node kind args _) := if kind == choiceKind then if args.size == 0 then failure else do s ← reprint (args.get 0), args.mfoldlFrom (λ s stx, do s' ← reprint stx, guard (s == s'), pure s) s 1 else args.mfoldl (λ r stx, do s ← reprint stx, pure $ r ++ s) "" | missing := "" open Lean.Format protected partial def formatStx : Syntax → Format | (atom info val) := format $ repr val | (ident _ _ val pre scopes) := let scopes := pre.map format ++ scopes.reverse.map format in let scopes := match scopes with [] := format "" | _ := bracket "{" (joinSep scopes ", ") "}" in format "`" ++ format val ++ scopes | (node kind args scopes) := let scopes := match scopes with [] := format "" | _ := bracket "{" (joinSep scopes.reverse ", ") "}" in if kind.name = `Lean.Parser.noKind then sbracket $ scopes ++ joinSep (args.toList.map formatStx) line else let shorterName := kind.name.replacePrefix `Lean.Parser Name.anonymous in paren $ joinSep ((format shorterName ++ scopes) :: args.toList.map formatStx) line | missing := "<missing>" instance : HasFormat Syntax := ⟨Syntax.formatStx⟩ instance : ToString Syntax := ⟨toString ∘ format⟩ end Syntax end Parser -- end Lean
cff480c6ab09ebc9f4492fdcb7bf497513a73dde
22e97a5d648fc451e25a06c668dc03ac7ed7bc25
/src/tactic/norm_cast.lean
8a74ded7261060fe6869bf12103ac6b64b26eea5
[ "Apache-2.0" ]
permissive
keeferrowan/mathlib
f2818da875dbc7780830d09bd4c526b0764a4e50
aad2dfc40e8e6a7e258287a7c1580318e865817e
refs/heads/master
1,661,736,426,952
1,590,438,032,000
1,590,438,032,000
266,892,663
0
0
Apache-2.0
1,590,445,835,000
1,590,445,835,000
null
UTF-8
Lean
false
false
25,192
lean
/- Copyright (c) 2019 Paul-Nicolas Madelaine. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Paul-Nicolas Madelaine, Robert Y. Lewis Normalizing casts inside expressions. -/ import tactic.converter.interactive import tactic.hint /-! # A tactic for normalizing casts inside expressions This tactic normalizes casts inside expressions. It can be thought of as a call to the simplifier with a specific set of lemmas to move casts upwards in the expression. It has special handling of numerals and a simple heuristic to help moving casts "past" binary operators. Contrary to simp, it should be safe to use as a non-terminating tactic. The algorithm implemented here is described in the paper <https://lean-forward.github.io/norm_cast/norm_cast.pdf>. ## Important definitions * `tactic.interactive.norm_cast` * `tactic.interactive.push_cast` * `tactic.interactive.exact_mod_cast` * `tactic.interactive.apply_mod_cast` * `tactic.interactive.rw_mod_cast` * `tactic.interactive.assumption_mod_cast` -/ setup_tactic_parser namespace tactic /-- Runs `mk_instance` with a time limit. This is a work around to the fact that in some cases mk_instance times out instead of failing, for example: `has_lift_t ℤ ℕ` `mk_instance_fast` is used when we assume the type class search should end instantly. -/ meta def mk_instance_fast (e : expr) (timeout := 1000) : tactic expr := try_for timeout (mk_instance e) end tactic namespace norm_cast open tactic expr declare_trace norm_cast /-- Output a trace message if `trace.norm_cast` is enabled. -/ meta def trace_norm_cast {α} [has_to_tactic_format α] (msg : string) (a : α) : tactic unit := when_tracing `norm_cast $ do a ← pp a, trace ("[norm_cast] " ++ msg ++ a : format) mk_simp_attribute push_cast "The `push_cast` simp attribute uses `norm_cast` lemmas to move casts toward the leaf nodes of the expression." /-- `label` is a type used to classify `norm_cast` lemmas. * elim lemma: LHS has 0 head coes and ≥ 1 internal coe * move lemma: LHS has 1 head coe and 0 internal coes, RHS has 0 head coes and ≥ 1 internal coes * squash lemma: LHS has ≥ 1 head coes and 0 internal coes, RHS has fewer head coes -/ @[derive [decidable_eq, has_reflect, inhabited]] inductive label | elim : label | move : label | squash : label namespace label /-- Convert `label` into `string`. -/ protected def to_string : label → string | elim := "elim" | move := "move" | squash := "squash" instance : has_to_string label := ⟨label.to_string⟩ instance : has_repr label := ⟨label.to_string⟩ meta instance : has_to_format label := ⟨λ l, l.to_string⟩ /-- Convert `string` into `label`. -/ def of_string : string -> option label | "elim" := some elim | "move" := some move | "squash" := some squash | _ := none end label open label /-- Count how many coercions are at the top of the expression. -/ meta def count_head_coes : expr → ℕ | `(coe %%e) := count_head_coes e + 1 | `(coe_sort %%e) := count_head_coes e + 1 | `(coe_fn %%e) := count_head_coes e + 1 | _ := 0 /-- Count how many coercions are inside the expression, including the top ones. -/ meta def count_coes : expr → tactic ℕ | `(coe %%e) := (+1) <$> count_coes e | `(coe_sort %%e) := (+1) <$> count_coes e | `(coe_fn %%e) := (+1) <$> count_coes e | (app `(coe_fn %%e) x) := (+) <$> count_coes x <*> (+1) <$> count_coes e | (expr.lam n bi t e) := do l ← mk_local' n bi t, count_coes $ e.instantiate_var l | e := do as ← e.get_simp_args, list.sum <$> as.mmap count_coes /-- Count how many coercions are inside the expression, excluding the top ones. -/ private meta def count_internal_coes (e : expr) : tactic ℕ := do ncoes ← count_coes e, pure $ ncoes - count_head_coes e /-- Classifies a declaration of type `ty` as a `norm_cast` rule. -/ meta def classify_type (ty : expr) : tactic label := do (_, ty) ← mk_local_pis ty, (lhs, rhs) ← match ty with | `(%%lhs = %%rhs) := pure (lhs, rhs) | `(%%lhs ↔ %%rhs) := pure (lhs, rhs) | _ := fail "norm_cast: lemma must be = or ↔" end, lhs_coes ← count_coes lhs, when (lhs_coes = 0) $ fail "norm_cast: badly shaped lemma, lhs must contain at least one coe", let lhs_head_coes := count_head_coes lhs, lhs_internal_coes ← count_internal_coes lhs, let rhs_head_coes := count_head_coes rhs, rhs_internal_coes ← count_internal_coes rhs, if lhs_head_coes = 0 then return elim else if lhs_head_coes = 1 then do when (rhs_head_coes ≠ 0) $ fail "norm_cast: badly shaped lemma, rhs can't start with coe", if rhs_internal_coes = 0 then return squash else return move else if rhs_head_coes < lhs_head_coes then do return squash else do fail "norm_cast: badly shaped shaped squash lemma, rhs must have fewer head coes than lhs" /-- The cache for `norm_cast` attribute stores three `simp_lemma` objects. -/ meta structure norm_cast_cache := (up : simp_lemmas) (down : simp_lemmas) (squash : simp_lemmas) /-- Empty `norm_cast_cache`. -/ meta def empty_cache : norm_cast_cache := { up := simp_lemmas.mk, down := simp_lemmas.mk, squash := simp_lemmas.mk, } meta instance : inhabited norm_cast_cache := ⟨empty_cache⟩ /-- `add_elim cache e` adds `e` as an `elim` lemma to `cache`. -/ meta def add_elim (cache : norm_cast_cache) (e : expr) : tactic norm_cast_cache := do new_up ← simp_lemmas.add cache.up e, return { up := new_up, down := cache.down, squash := cache.squash, } /-- `add_move cache e` adds `e` as a `move` lemma to `cache`. -/ meta def add_move (cache : norm_cast_cache) (e : expr) : tactic norm_cast_cache := do ty ← infer_type e, new_up ← cache.up.add e tt, new_down ← simp_lemmas.add cache.down e, return { up := new_up, down := new_down, squash := cache.squash, } /-- `add_squash cache e` adds `e` as an `squash` lemma to `cache`. -/ meta def add_squash (cache : norm_cast_cache) (e : expr) : tactic norm_cast_cache := do new_squash ← simp_lemmas.add cache.squash e, new_down ← simp_lemmas.add cache.down e, return { up := cache.up, down := new_down, squash := new_squash, } /-- The type of the `norm_cast` attribute. The optional label is used to overwrite the classifier. -/ meta def norm_cast_attr_ty : Type := user_attribute norm_cast_cache (option label) /-- Efficient getter for the `@[norm_cast]` attribute parameter that does not call `eval_expr`. See Note [user attribute parameters]. -/ meta def get_label_param (attr : norm_cast_attr_ty) (decl : name) : tactic (option label) := do p ← attr.get_param_untyped decl, match p with | `(none) := pure none | `(some label.elim) := pure label.elim | `(some label.move) := pure label.move | `(some label.squash) := pure label.squash | _ := fail p end /-- `add_lemma cache decl` infers the proper `norm_cast` attribute for `decl` and adds it to `cache`. -/ meta def add_lemma (attr : norm_cast_attr_ty) (cache : norm_cast_cache) (decl : name) : tactic norm_cast_cache := do e ← mk_const decl, param ← get_label_param attr decl, l ← param <|> (infer_type e >>= classify_type), match l with | elim := add_elim cache e | move := add_move cache e | squash := add_squash cache e end -- special lemmas to handle the ≥, > and ≠ operators private lemma ge_from_le {α} [has_le α] : ∀ (x y : α), x ≥ y ↔ y ≤ x := λ _ _, iff.rfl private lemma gt_from_lt {α} [has_lt α] : ∀ (x y : α), x > y ↔ y < x := λ _ _, iff.rfl private lemma ne_from_not_eq {α} : ∀ (x y : α), x ≠ y ↔ ¬(x = y) := λ _ _, iff.rfl /-- `mk_cache names` creates a `norm_cast_cache`. It infers the proper `norm_cast` attributes for names in `names`, and collects the lemmas attributed with specific `norm_cast` attributes. -/ meta def mk_cache (attr : thunk norm_cast_attr_ty) (names : list name) : tactic norm_cast_cache := do -- names has the declarations in reverse order cache ← names.mfoldr (λ name cache, add_lemma (attr ()) cache name) empty_cache, --some special lemmas to handle binary relations let up := cache.up, up ← up.add_simp ``ge_from_le, up ← up.add_simp ``gt_from_lt, up ← up.add_simp ``ne_from_not_eq, let down := cache.down, down ← down.add_simp ``coe_coe, pure { up := up, down := down, squash := cache.squash } /-- The `norm_cast` attribute. -/ @[user_attribute] meta def norm_cast_attr : user_attribute norm_cast_cache (option label) := { name := `norm_cast, descr := "attribute for norm_cast", parser := (do some l ← (label.of_string ∘ to_string) <$> ident, return l) <|> return none, after_set := some (λ decl prio persistent, do param ← get_label_param norm_cast_attr decl, match param with | some l := when (l ≠ elim) $ simp_attr.push_cast.set decl () tt | none := do e ← mk_const decl, ty ← infer_type e, l ← classify_type ty, norm_cast_attr.set decl l persistent prio end), before_unset := some $ λ _ _, tactic.skip, cache_cfg := { mk_cache := mk_cache norm_cast_attr, dependencies := [] } } /-- Classify a declaration as a `norm_cast` rule. -/ meta def make_guess (decl : name) : tactic label := do e ← mk_const decl, ty ← infer_type e, classify_type ty /-- Gets the `norm_cast` classification label for a declaration. Applies the override specified on the attribute, if necessary. -/ meta def get_label (decl : name) : tactic label := do param ← get_label_param norm_cast_attr decl, param <|> make_guess decl end norm_cast namespace tactic.interactive open norm_cast /-- `push_cast` rewrites the expression to move casts toward the leaf nodes. For example, `↑(a + b)` will be written to `↑a + ↑b`. Equivalent to `simp only with push_cast`. Can also be used at hypotheses. -/ meta def push_cast (l : parse location): tactic unit := tactic.interactive.simp none tt [] [`push_cast] l end tactic.interactive namespace norm_cast open tactic expr /-- Prove `a = b` using the given simp set. -/ meta def prove_eq_using (s : simp_lemmas) (a b : expr) : tactic expr := do (a', a_a') ← simplify s [] a {fail_if_unchanged := ff}, (b', b_b') ← simplify s [] b {fail_if_unchanged := ff}, on_exception (trace_norm_cast "failed: " (to_expr ``(%%a' = %%b') >>= pp)) $ is_def_eq a' b' reducible, b'_b ← mk_eq_symm b_b', mk_eq_trans a_a' b'_b /-- Prove `a = b` by simplifying using move and squash lemmas. -/ meta def prove_eq_using_down (a b : expr) : tactic expr := do cache ← norm_cast_attr.get_cache, trace_norm_cast "proving: " (to_expr ``(%%a = %%b) >>= pp), prove_eq_using cache.down a b /-- This is the main heuristic used alongside the elim and move lemmas. The goal is to help casts move past operators by adding intermediate casts. An expression of the shape: op (↑(x : α) : γ) (↑(y : β) : γ) is rewritten to: op (↑(↑(x : α) : β) : γ) (↑(y : β) : γ) when (↑(↑(x : α) : β) : γ) = (↑(x : α) : γ) can be proven with a squash lemma -/ meta def splitting_procedure : expr → tactic (expr × expr) | (app (app op x) y) := (do `(@coe %%α %%δ %%coe1 %%xx) ← return x, `(@coe %%β %%γ %%coe2 %%yy) ← return y, success_if_fail $ is_def_eq α β, is_def_eq δ γ, (do coe3 ← mk_app `has_lift_t [α, β] >>= mk_instance_fast, new_x ← to_expr ``(@coe %%β %%δ %%coe2 (@coe %%α %%β %%coe3 %%xx)), let new_e := app (app op new_x) y, eq_x ← prove_eq_using_down x new_x, pr ← mk_congr_arg op eq_x, pr ← mk_congr_fun pr y, return (new_e, pr) ) <|> (do coe3 ← mk_app `has_lift_t [β, α] >>= mk_instance_fast, new_y ← to_expr ``(@coe %%α %%δ %%coe1 (@coe %%β %%α %%coe3 %%yy)), let new_e := app (app op x) new_y, eq_y ← prove_eq_using_down y new_y, pr ← mk_congr_arg (app op x) eq_y, return (new_e, pr) ) ) <|> (do `(@coe %%α %%β %%coe1 %%xx) ← return x, `(@has_one.one %%β %%h1) ← return y, h2 ← to_expr ``(has_one %%α) >>= mk_instance_fast, new_y ← to_expr ``(@coe %%α %%β %%coe1 (@has_one.one %%α %%h2)), eq_y ← prove_eq_using_down y new_y, let new_e := app (app op x) new_y, pr ← mk_congr_arg (app op x) eq_y, return (new_e, pr) ) <|> (do `(@coe %%α %%β %%coe1 %%xx) ← return x, `(@has_zero.zero %%β %%h1) ← return y, h2 ← to_expr ``(has_zero %%α) >>= mk_instance_fast, new_y ← to_expr ``(@coe %%α %%β %%coe1 (@has_zero.zero %%α %%h2)), eq_y ← prove_eq_using_down y new_y, let new_e := app (app op x) new_y, pr ← mk_congr_arg (app op x) eq_y, return (new_e, pr) ) <|> (do `(@has_one.one %%β %%h1) ← return x, `(@coe %%α %%β %%coe1 %%xx) ← return y, h1 ← to_expr ``(has_one %%α) >>= mk_instance_fast, new_x ← to_expr ``(@coe %%α %%β %%coe1 (@has_one.one %%α %%h1)), eq_x ← prove_eq_using_down x new_x, let new_e := app (app op new_x) y, pr ← mk_congr_arg (lam `x binder_info.default β (app (app op (var 0)) y)) eq_x, return (new_e, pr) ) <|> (do `(@has_zero.zero %%β %%h1) ← return x, `(@coe %%α %%β %%coe1 %%xx) ← return y, h1 ← to_expr ``(has_zero %%α) >>= mk_instance_fast, new_x ← to_expr ``(@coe %%α %%β %%coe1 (@has_zero.zero %%α %%h1)), eq_x ← prove_eq_using_down x new_x, let new_e := app (app op new_x) y, pr ← mk_congr_arg (lam `x binder_info.default β (app (app op (var 0)) y)) eq_x, return (new_e, pr) ) | _ := failed /-- Discharging function used during simplification in the "squash" step. TODO: norm_cast takes a list of expressions to use as lemmas for the discharger TODO: a tactic to print the results the discharger fails to proove -/ private meta def prove : tactic unit := assumption /-- Core rewriting function used in the "squash" step, which moves casts upwards and eliminates them. It tries to rewrite an expression using the elim and move lemmas. On failure, it calls the splitting procedure heuristic. -/ meta def upward_and_elim (s : simp_lemmas) (e : expr) : tactic (expr × expr) := (do r ← mcond (is_prop e) (return `iff) (return `eq), (new_e, pr) ← s.rewrite e prove r, pr ← match r with | `iff := mk_app `propext [pr] | _ := return pr end, return (new_e, pr) ) <|> splitting_procedure e /-! The following auxiliary functions are used to handle numerals. -/ /-- If possible, rewrite `(n : α)` to `((n : ℕ) : α)` where `n` is a numeral and `α ≠ ℕ`. Returns a pair of the new expression and proof that they are equal. -/ meta def numeral_to_coe (e : expr) : tactic (expr × expr) := do α ← infer_type e, success_if_fail $ is_def_eq α `(ℕ), n ← e.to_nat, h1 ← mk_app `has_lift_t [`(ℕ), α] >>= mk_instance_fast, let new_e : expr := reflect n, new_e ← to_expr ``(@coe ℕ %%α %%h1 %%new_e), pr ← prove_eq_using_down e new_e, return (new_e, pr) /-- If possible, rewrite `((n : ℕ) : α)` to `(n : α)` where `n` is a numeral. Returns a pair of the new expression and proof that they are equal. -/ meta def coe_to_numeral (e : expr) : tactic (expr × expr) := do `(@coe ℕ %%α %%h1 %%e') ← return e, n ← e'.to_nat, -- replace e' by normalized numeral is_def_eq (reflect n) e' reducible, let e := e.app_fn (reflect n), new_e ← expr.of_nat α n, pr ← prove_eq_using_down e new_e, return (new_e, pr) /-- A local variant on `simplify_top_down`. -/ private meta def simplify_top_down' {α} (a : α) (pre : α → expr → tactic (α × expr × expr)) (e : expr) (cfg : simp_config := {}) : tactic (α × expr × expr) := ext_simplify_core a cfg simp_lemmas.mk (λ _, failed) (λ a _ _ _ e, do (new_a, new_e, pr) ← pre a e, guard (¬ new_e =ₐ e), return (new_a, new_e, some pr, ff)) (λ _ _ _ _ _, failed) `eq e /-- The core simplification routine of `norm_cast`. -/ meta def derive (e : expr) : tactic (expr × expr) := do cache ← norm_cast_attr.get_cache, e ← instantiate_mvars e, let cfg : simp_config := { zeta := ff, beta := ff, eta := ff, proj := ff, iota := ff, iota_eqn := ff, fail_if_unchanged := ff }, let e0 := e, -- step 1: pre-processing of numerals ((), e1, pr1) ← simplify_top_down' () (λ _ e, prod.mk () <$> numeral_to_coe e) e0 cfg, trace_norm_cast "after numeral_to_coe: " e1, -- step 2: casts are moved upwards and eliminated ((), e2, pr2) ← simplify_bottom_up () (λ _ e, prod.mk () <$> upward_and_elim cache.up e) e1 cfg, trace_norm_cast "after upward_and_elim: " e2, -- step 3: casts are squashed (e3, pr3) ← simplify cache.squash [] e2 cfg, trace_norm_cast "after squashing: " e3, -- step 4: post-processing of numerals ((), e4, pr4) ← simplify_top_down' () (λ _ e, prod.mk () <$> coe_to_numeral e) e3 cfg, trace_norm_cast "after coe_to_numeral: " e4, let new_e := e4, guard (¬ new_e =ₐ e), pr ← mk_eq_trans pr1 pr2, pr ← mk_eq_trans pr pr3, pr ← mk_eq_trans pr pr4, return (new_e, pr) end norm_cast namespace tactic open expr norm_cast /-- `aux_mod_cast e` runs `norm_cast` on `e` and returns the result. If `include_goal` is true, it also normalizes the goal. -/ meta def aux_mod_cast (e : expr) (include_goal : bool := tt) : tactic expr := match e with | local_const _ lc _ _ := do e ← get_local lc, replace_at derive [e] include_goal, get_local lc | e := do t ← infer_type e, e ← assertv `this t e, replace_at derive [e] include_goal, get_local `this end /-- `exact_mod_cast e` runs `norm_cast` on the goal and `e`, and tries to use `e` to close the goal. -/ meta def exact_mod_cast (e : expr) : tactic unit := decorate_error "exact_mod_cast failed:" $ do new_e ← aux_mod_cast e, exact new_e /-- `apply_mod_cast e` runs `norm_cast` on the goal and `e`, and tries to apply `e`. -/ meta def apply_mod_cast (e : expr) : tactic (list (name × expr)) := decorate_error "apply_mod_cast failed:" $ do new_e ← aux_mod_cast e, apply new_e /-- `assumption_mod_cast` runs `norm_cast` on the goal. For each local hypothesis `h`, it also normalizes `h` and tries to use that to close the goal. -/ meta def assumption_mod_cast : tactic unit := decorate_error "assumption_mod_cast failed:" $ do let cfg : simp_config := { fail_if_unchanged := ff, canonize_instances := ff, canonize_proofs := ff, proj := ff }, replace_at derive [] tt, ctx ← local_context, try_lst $ ctx.map (λ h, aux_mod_cast h ff >>= tactic.exact) end tactic namespace tactic.interactive open tactic norm_cast /-- Normalize casts at the given locations by moving them "upwards". As opposed to simp, norm_cast can be used without necessarily closing the goal. -/ meta def norm_cast (loc : parse location) : tactic unit := do ns ← loc.get_locals, tt ← replace_at derive ns loc.include_goal | fail "norm_cast failed to simplify", when loc.include_goal $ try tactic.reflexivity, when loc.include_goal $ try tactic.triv, when (¬ ns.empty) $ try tactic.contradiction /-- Rewrite with the given rules and normalize casts between steps. -/ meta def rw_mod_cast (rs : parse rw_rules) (loc : parse location) : tactic unit := decorate_error "rw_mod_cast failed:" $ do let cfg_norm : simp_config := {}, let cfg_rw : rewrite_cfg := {}, ns ← loc.get_locals, monad.mapm' (λ r : rw_rule, do save_info r.pos, replace_at derive ns loc.include_goal, rw ⟨[r], none⟩ loc {} ) rs.rules, replace_at derive ns loc.include_goal, skip /-- Normalize the goal and the given expression, then close the goal with exact. -/ meta def exact_mod_cast (e : parse texpr) : tactic unit := do e ← i_to_expr e <|> do { ty ← target, e ← i_to_expr_strict ``(%%e : %%ty), pty ← pp ty, ptgt ← pp e, fail ("exact_mod_cast failed, expression type not directly " ++ "inferrable. Try:\n\nexact_mod_cast ...\nshow " ++ to_fmt pty ++ ",\nfrom " ++ ptgt : format) }, tactic.exact_mod_cast e /-- Normalize the goal and the given expression, then apply the expression to the goal. -/ meta def apply_mod_cast (e : parse texpr) : tactic unit := do e ← i_to_expr_for_apply e, concat_tags $ tactic.apply_mod_cast e /-- Normalize the goal and every expression in the local context, then close the goal with assumption. -/ meta def assumption_mod_cast : tactic unit := tactic.assumption_mod_cast end tactic.interactive namespace conv.interactive open conv open norm_cast (derive) /-- the converter version of `norm_cast' -/ meta def norm_cast : conv unit := replace_lhs derive end conv.interactive -- TODO: move this elsewhere? @[norm_cast] lemma ite_cast {α β} [has_lift_t α β] {c : Prop} [decidable c] {a b : α} : ↑(ite c a b) = ite c (↑a : β) (↑b : β) := by by_cases h : c; simp [h] add_hint_tactic "norm_cast at *" /-- The `norm_cast` family of tactics is used to normalize casts inside expressions. It is basically a simp tactic with a specific set of lemmas to move casts upwards in the expression. Therefore it can be used more safely as a non-terminating tactic. It also has special handling of numerals. For instance, given an assumption ```lean a b : ℤ h : ↑a + ↑b < (10 : ℚ) ``` writing `norm_cast at h` will turn `h` into ```lean h : a + b < 10 ``` You can also use `exact_mod_cast`, `apply_mod_cast`, `rw_mod_cast` or `assumption_mod_cast`. Writing `exact_mod_cast h` and `apply_mod_cast h` will normalize the goal and `h` before using `exact h` or `apply h`. Writing `assumption_mod_cast` will normalize the goal and for every expression `h` in the context it will try to normalize `h` and use `exact h`. `rw_mod_cast` acts like the `rw` tactic but it applies `norm_cast` between steps. `push_cast` rewrites the expression to move casts toward the leaf nodes. This uses `norm_cast` lemmas in the forward direction. For example, `↑(a + b)` will be written to `↑a + ↑b`. It is equivalent to `simp only with push_cast`, and can also be used at hypotheses with `push_cast at h`. The implementation and behavior of the `norm_cast` family is described in detail at <https://lean-forward.github.io/norm_cast/norm_cast.pdf>. -/ add_tactic_doc { name := "norm_cast", category := doc_category.tactic, decl_names := [``tactic.interactive.norm_cast, ``tactic.interactive.rw_mod_cast, ``tactic.interactive.apply_mod_cast, ``tactic.interactive.assumption_mod_cast, ``tactic.interactive.exact_mod_cast, ``tactic.interactive.push_cast], tags := ["coercions", "simplification"] } /-- The `norm_cast` attribute should be given to lemmas that describe the behaviour of a coercion in regard to an operator, a relation, or a particular function. It only concerns equality or iff lemmas involving `↑`, `⇑` and `↥`, describing the behavior of the coercion functions. It does not apply to the explicit functions that define the coercions. Examples: ```lean @[norm_cast] theorem coe_nat_inj' {m n : ℕ} : (↑m : ℤ) = ↑n ↔ m = n @[norm_cast] theorem coe_int_denom (n : ℤ) : (n : ℚ).denom = 1 @[norm_cast] theorem cast_id : ∀ n : ℚ, ↑n = n @[norm_cast] theorem coe_nat_add (m n : ℕ) : (↑(m + n) : ℤ) = ↑m + ↑n @[norm_cast] theorem cast_sub [add_group α] [has_one α] {m n} (h : m ≤ n) : ((n - m : ℕ) : α) = n - m @[norm_cast] theorem coe_nat_bit0 (n : ℕ) : (↑(bit0 n) : ℤ) = bit0 ↑n @[norm_cast] theorem cast_coe_nat (n : ℕ) : ((n : ℤ) : α) = n @[norm_cast] theorem cast_one : ((1 : ℚ) : α) = 1 ``` Lemmas tagged with `@[norm_cast]` are classified into three categories: `move`, `elim`, and `squash`. They are classified roughly as follows: * elim lemma: LHS has 0 head coes and ≥ 1 internal coe * move lemma: LHS has 1 head coe and 0 internal coes, RHS has 0 head coes and ≥ 1 internal coes * squash lemma: LHS has ≥ 1 head coes and 0 internal coes, RHS has fewer head coes `norm_cast` uses `move` and `elim` lemmas to factor coercions toward the root of an expression and to cancel them from both sides of an equation or relation. It uses `squash` lemmas to clean up the result. Occasionally you may want to override the automatic classification. You can do this by giving an optional `elim`, `move`, or `squash` parameter to the attribute. ```lean @[simp, norm_cast elim] lemma nat_cast_re (n : ℕ) : (n : ℂ).re = n := by rw [← of_real_nat_cast, of_real_re] ``` Don't do this unless you understand what you are doing. A full description of the tactic, and the use of each lemma category, can be found at <https://lean-forward.github.io/norm_cast/norm_cast.pdf>. -/ add_tactic_doc { name := "norm_cast attributes", category := doc_category.attr, decl_names := [``norm_cast.norm_cast_attr], tags := ["coercions", "simplification"] } -- Lemmas defined in core. attribute [norm_cast] int.nat_abs_of_nat int.coe_nat_sub int.coe_nat_mul int.coe_nat_zero int.coe_nat_one int.coe_nat_add -- Lemmas about nat.succ need to get a low priority, so that they are tried last. -- This is because `nat.succ _` matches `1`, `3`, `x+1`, etc. -- Rewriting would then produce really wrong terms. attribute [norm_cast, priority 500] int.coe_nat_succ
a099ef1f8050fe32825710aa9b9529e80d8e6613
c777c32c8e484e195053731103c5e52af26a25d1
/src/analysis/box_integral/partition/subbox_induction.lean
230dbddcfe4a3db6909c09456a6f90ae82788eb7
[ "Apache-2.0" ]
permissive
kbuzzard/mathlib
2ff9e85dfe2a46f4b291927f983afec17e946eb8
58537299e922f9c77df76cb613910914a479c1f7
refs/heads/master
1,685,313,702,744
1,683,974,212,000
1,683,974,212,000
128,185,277
1
0
null
1,522,920,600,000
1,522,920,600,000
null
UTF-8
Lean
false
false
10,544
lean
/- Copyright (c) 2021 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudryashov -/ import analysis.box_integral.box.subbox_induction import analysis.box_integral.partition.tagged /-! # Induction on subboxes In this file we prove (see `box_integral.tagged_partition.exists_is_Henstock_is_subordinate_homothetic`) that for every box `I` in `ℝⁿ` and a function `r : ℝⁿ → ℝ` positive on `I` there exists a tagged partition `π` of `I` such that * `π` is a Henstock partition; * `π` is subordinate to `r`; * each box in `π` is homothetic to `I` with coefficient of the form `1 / 2 ^ n`. Later we will use this lemma to prove that the Henstock filter is nontrivial, hence the Henstock integral is well-defined. ## Tags partition, tagged partition, Henstock integral -/ namespace box_integral open set metric open_locale classical topology noncomputable theory variables {ι : Type*} [fintype ι] {I J : box ι} namespace prepartition /-- Split a box in `ℝⁿ` into `2 ^ n` boxes by hyperplanes passing through its center. -/ def split_center (I : box ι) : prepartition I := { boxes := finset.univ.map (box.split_center_box_emb I), le_of_mem' := by simp [I.split_center_box_le], pairwise_disjoint := begin rw [finset.coe_map, finset.coe_univ, image_univ], rintro _ ⟨s, rfl⟩ _ ⟨t, rfl⟩ Hne, exact I.disjoint_split_center_box (mt (congr_arg _) Hne) end } @[simp] lemma mem_split_center : J ∈ split_center I ↔ ∃ s, I.split_center_box s = J := by simp [split_center] lemma is_partition_split_center (I : box ι) : is_partition (split_center I) := λ x hx, by simp [hx] lemma upper_sub_lower_of_mem_split_center (h : J ∈ split_center I) (i : ι) : J.upper i - J.lower i = (I.upper i - I.lower i) / 2 := let ⟨s, hs⟩ := mem_split_center.1 h in hs ▸ I.upper_sub_lower_split_center_box s i end prepartition namespace box open prepartition tagged_prepartition /-- Let `p` be a predicate on `box ι`, let `I` be a box. Suppose that the following two properties hold true. * Consider a smaller box `J ≤ I`. The hyperplanes passing through the center of `J` split it into `2 ^ n` boxes. If `p` holds true on each of these boxes, then it true on `J`. * For each `z` in the closed box `I.Icc` there exists a neighborhood `U` of `z` within `I.Icc` such that for every box `J ≤ I` such that `z ∈ J.Icc ⊆ U`, if `J` is homothetic to `I` with a coefficient of the form `1 / 2 ^ m`, then `p` is true on `J`. Then `p I` is true. See also `box_integral.box.subbox_induction_on'` for a version using `box_integral.box.split_center_box` instead of `box_integral.prepartition.split_center`. -/ @[elab_as_eliminator] lemma subbox_induction_on {p : box ι → Prop} (I : box ι) (H_ind : ∀ J ≤ I, (∀ J' ∈ split_center J, p J') → p J) (H_nhds : ∀ z ∈ I.Icc, ∃ (U ∈ 𝓝[I.Icc] z), ∀ (J ≤ I) (m : ℕ), z ∈ J.Icc → J.Icc ⊆ U → (∀ i, J.upper i - J.lower i = (I.upper i - I.lower i) / 2 ^ m) → p J) : p I := begin refine subbox_induction_on' I (λ J hle hs, H_ind J hle $ λ J' h', _) H_nhds, rcases mem_split_center.1 h' with ⟨s, rfl⟩, exact hs s end /-- Given a box `I` in `ℝⁿ` and a function `r : ℝⁿ → (0, ∞)`, there exists a tagged partition `π` of `I` such that * `π` is a Henstock partition; * `π` is subordinate to `r`; * each box in `π` is homothetic to `I` with coefficient of the form `1 / 2 ^ m`. This lemma implies that the Henstock filter is nontrivial, hence the Henstock integral is well-defined. -/ lemma exists_tagged_partition_is_Henstock_is_subordinate_homothetic (I : box ι) (r : (ι → ℝ) → Ioi (0 : ℝ)) : ∃ π : tagged_prepartition I, π.is_partition ∧ π.is_Henstock ∧ π.is_subordinate r ∧ (∀ J ∈ π, ∃ m : ℕ, ∀ i, (J : _).upper i - J.lower i = (I.upper i - I.lower i) / 2 ^ m) ∧ π.distortion = I.distortion := begin refine subbox_induction_on I (λ J hle hJ, _) (λ z hz, _), { choose! πi hP hHen hr Hn Hd using hJ, choose! n hn using Hn, have hP : ((split_center J).bUnion_tagged πi).is_partition, from (is_partition_split_center _).bUnion_tagged hP, have hsub : ∀ (J' ∈ (split_center J).bUnion_tagged πi), ∃ n : ℕ, ∀ i, (J' : _).upper i - J'.lower i = (J.upper i - J.lower i) / 2 ^ n, { intros J' hJ', rcases (split_center J).mem_bUnion_tagged.1 hJ' with ⟨J₁, h₁, h₂⟩, refine ⟨n J₁ J' + 1, λ i, _⟩, simp only [hn J₁ h₁ J' h₂, upper_sub_lower_of_mem_split_center h₁, pow_succ, div_div] }, refine ⟨_, hP, is_Henstock_bUnion_tagged.2 hHen, is_subordinate_bUnion_tagged.2 hr, hsub, _⟩, refine tagged_prepartition.distortion_of_const _ hP.nonempty_boxes (λ J' h', _), rcases hsub J' h' with ⟨n, hn⟩, exact box.distortion_eq_of_sub_eq_div hn }, { refine ⟨I.Icc ∩ closed_ball z (r z), inter_mem_nhds_within _ (closed_ball_mem_nhds _ (r z).coe_prop), _⟩, intros J Hle n Hmem HIcc Hsub, rw set.subset_inter_iff at HIcc, refine ⟨single _ _ le_rfl _ Hmem, is_partition_single _, is_Henstock_single _, (is_subordinate_single _ _).2 HIcc.2, _, distortion_single _ _⟩, simp only [tagged_prepartition.mem_single, forall_eq], refine ⟨0, λ i, _⟩, simp } end end box namespace prepartition open tagged_prepartition finset function /-- Given a box `I` in `ℝⁿ`, a function `r : ℝⁿ → (0, ∞)`, and a prepartition `π` of `I`, there exists a tagged prepartition `π'` of `I` such that * each box of `π'` is included in some box of `π`; * `π'` is a Henstock partition; * `π'` is subordinate to `r`; * `π'` covers exactly the same part of `I` as `π`; * the distortion of `π'` is equal to the distortion of `π`. -/ lemma exists_tagged_le_is_Henstock_is_subordinate_Union_eq {I : box ι} (r : (ι → ℝ) → Ioi (0 : ℝ)) (π : prepartition I) : ∃ π' : tagged_prepartition I, π'.to_prepartition ≤ π ∧ π'.is_Henstock ∧ π'.is_subordinate r ∧ π'.distortion = π.distortion ∧ π'.Union = π.Union := begin have := λ J, box.exists_tagged_partition_is_Henstock_is_subordinate_homothetic J r, choose! πi πip πiH πir hsub πid, clear hsub, refine ⟨π.bUnion_tagged πi, bUnion_le _ _, is_Henstock_bUnion_tagged.2 (λ J _, πiH J), is_subordinate_bUnion_tagged.2 (λ J _, πir J), _, π.Union_bUnion_partition (λ J _, πip J)⟩, rw [distortion_bUnion_tagged], exact sup_congr rfl (λ J _, πid J) end /-- Given a prepartition `π` of a box `I` and a function `r : ℝⁿ → (0, ∞)`, `π.to_subordinate r` is a tagged partition `π'` such that * each box of `π'` is included in some box of `π`; * `π'` is a Henstock partition; * `π'` is subordinate to `r`; * `π'` covers exactly the same part of `I` as `π`; * the distortion of `π'` is equal to the distortion of `π`. -/ def to_subordinate (π : prepartition I) (r : (ι → ℝ) → Ioi (0 : ℝ)) : tagged_prepartition I := (π.exists_tagged_le_is_Henstock_is_subordinate_Union_eq r).some lemma to_subordinate_to_prepartition_le (π : prepartition I) (r : (ι → ℝ) → Ioi (0 : ℝ)) : (π.to_subordinate r).to_prepartition ≤ π := (π.exists_tagged_le_is_Henstock_is_subordinate_Union_eq r).some_spec.1 lemma is_Henstock_to_subordinate (π : prepartition I) (r : (ι → ℝ) → Ioi (0 : ℝ)) : (π.to_subordinate r).is_Henstock := (π.exists_tagged_le_is_Henstock_is_subordinate_Union_eq r).some_spec.2.1 lemma is_subordinate_to_subordinate (π : prepartition I) (r : (ι → ℝ) → Ioi (0 : ℝ)) : (π.to_subordinate r).is_subordinate r := (π.exists_tagged_le_is_Henstock_is_subordinate_Union_eq r).some_spec.2.2.1 @[simp] lemma distortion_to_subordinate (π : prepartition I) (r : (ι → ℝ) → Ioi (0 : ℝ)) : (π.to_subordinate r).distortion = π.distortion := (π.exists_tagged_le_is_Henstock_is_subordinate_Union_eq r).some_spec.2.2.2.1 @[simp] lemma Union_to_subordinate (π : prepartition I) (r : (ι → ℝ) → Ioi (0 : ℝ)) : (π.to_subordinate r).Union = π.Union := (π.exists_tagged_le_is_Henstock_is_subordinate_Union_eq r).some_spec.2.2.2.2 end prepartition namespace tagged_prepartition /-- Given a tagged prepartition `π₁`, a prepartition `π₂` that covers exactly `I \ π₁.Union`, and a function `r : ℝⁿ → (0, ∞)`, returns the union of `π₁` and `π₂.to_subordinate r`. This partition `π` has the following properties: * `π` is a partition, i.e. it covers the whole `I`; * `π₁.boxes ⊆ π.boxes`; * `π.tag J = π₁.tag J` whenever `J ∈ π₁`; * `π` is Henstock outside of `π₁`: `π.tag J ∈ J.Icc` whenever `J ∈ π`, `J ∉ π₁`; * `π` is subordinate to `r` outside of `π₁`; * the distortion of `π` is equal to the maximum of the distortions of `π₁` and `π₂`. -/ def union_compl_to_subordinate (π₁ : tagged_prepartition I) (π₂ : prepartition I) (hU : π₂.Union = I \ π₁.Union) (r : (ι → ℝ) → Ioi (0 : ℝ)) : tagged_prepartition I := π₁.disj_union (π₂.to_subordinate r) (((π₂.Union_to_subordinate r).trans hU).symm ▸ disjoint_sdiff_self_right) lemma is_partition_union_compl_to_subordinate (π₁ : tagged_prepartition I) (π₂ : prepartition I) (hU : π₂.Union = I \ π₁.Union) (r : (ι → ℝ) → Ioi (0 : ℝ)) : is_partition (π₁.union_compl_to_subordinate π₂ hU r) := prepartition.is_partition_disj_union_of_eq_diff ((π₂.Union_to_subordinate r).trans hU) @[simp] lemma union_compl_to_subordinate_boxes (π₁ : tagged_prepartition I) (π₂ : prepartition I) (hU : π₂.Union = I \ π₁.Union) (r : (ι → ℝ) → Ioi (0 : ℝ)) : (π₁.union_compl_to_subordinate π₂ hU r).boxes = π₁.boxes ∪ (π₂.to_subordinate r).boxes := rfl @[simp] lemma Union_union_compl_to_subordinate_boxes (π₁ : tagged_prepartition I) (π₂ : prepartition I) (hU : π₂.Union = I \ π₁.Union) (r : (ι → ℝ) → Ioi (0 : ℝ)) : (π₁.union_compl_to_subordinate π₂ hU r).Union = I := (is_partition_union_compl_to_subordinate _ _ _ _).Union_eq @[simp] lemma distortion_union_compl_to_subordinate (π₁ : tagged_prepartition I) (π₂ : prepartition I) (hU : π₂.Union = I \ π₁.Union) (r : (ι → ℝ) → Ioi (0 : ℝ)) : (π₁.union_compl_to_subordinate π₂ hU r).distortion = max π₁.distortion π₂.distortion := by simp [union_compl_to_subordinate] end tagged_prepartition end box_integral
6dd11ebd23de52ec6379fe1f5b08fd6bf2e07475
82e44445c70db0f03e30d7be725775f122d72f3e
/src/order/rel_iso.lean
e9222c7e9af18947f13ca3a905d70a08f8deb810
[ "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
34,580
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 algebra.group.defs import logic.embedding import order.rel_classes /-! # Relation homomorphisms, embeddings, isomorphisms This file defines relation homomorphisms, embeddings, isomorphisms and order embeddings and isomorphisms. ## Main declarations * `rel_hom`: Relation homomorphism. A `rel_hom r s` is a function `f : α → β` such that `r a b → s (f a) (f b)`. * `rel_embedding`: Relation embedding. A `rel_embedding r s` is an embedding `f : α ↪ β` such that `r a b ↔ s (f a) (f b)`. * `rel_iso`: Relation isomorphism. A `rel_iso r s` is an equivalence `f : α ≃ β` such that `r a b ↔ s (f a) (f b)`. * `order_embedding`: Relation embedding. An `order_embedding α β` is an embedding `f : α ↪ β` such that `a ≤ b ↔ f a ≤ f b`. Defined as an abbreviation of `@rel_embedding α β (≤) (≤)`. * `order_iso`: Relation isomorphism. An `order_iso α β` is an equivalence `f : α ≃ β` such that `a ≤ b ↔ f a ≤ f b`. Defined as an abbreviation of `@rel_iso α β (≤) (≤)`. * `sum_lex_congr`, `prod_lex_congr`: Creates a relation homomorphism between two `sum_lex` or two `prod_lex` from relation homomorphisms between their arguments. ## Notation * `→r`: `rel_hom` * `↪r`: `rel_embedding` * `≃r`: `rel_iso` * `↪o`: `order_embedding` * `≃o`: `order_iso` -/ open function universes u v w variables {α β γ : Type*} {r : α → α → Prop} {s : β → β → Prop} {t : γ → γ → Prop} /-- A relation homomorphism with respect to a given pair of relations `r` and `s` is a function `f : α → β` such that `r a b → s (f a) (f b)`. -/ @[nolint has_inhabited_instance] structure rel_hom {α β : Type*} (r : α → α → Prop) (s : β → β → Prop) := (to_fun : α → β) (map_rel' : ∀ {a b}, r a b → s (to_fun a) (to_fun b)) infix ` →r `:25 := rel_hom namespace rel_hom instance : has_coe_to_fun (r →r s) := ⟨λ _, α → β, λ o, o.to_fun⟩ initialize_simps_projections rel_hom (to_fun → apply) theorem map_rel (f : r →r s) : ∀ {a b}, r a b → s (f a) (f b) := f.map_rel' @[simp] theorem coe_fn_mk (f : α → β) (o) : (@rel_hom.mk _ _ r s f o : α → β) = f := rfl @[simp] theorem coe_fn_to_fun (f : r →r s) : (f.to_fun : α → β) = f := rfl /-- The map `coe_fn : (r →r s) → (α → β)` is injective. We can't use `function.injective` here but mimic its signature by using `⦃e₁ e₂⦄`. -/ theorem coe_fn_inj : ∀ ⦃e₁ e₂ : r →r s⦄, (e₁ : α → β) = e₂ → e₁ = e₂ | ⟨f₁, o₁⟩ ⟨f₂, o₂⟩ h := by { congr, exact h } @[ext] theorem ext ⦃f g : r →r s⦄ (h : ∀ x, f x = g x) : f = g := coe_fn_inj (funext h) theorem ext_iff {f g : r →r s} : f = g ↔ ∀ x, f x = g x := ⟨λ h x, h ▸ rfl, λ h, ext h⟩ /-- Identity map is a relation homomorphism. -/ @[refl, simps] protected def id (r : α → α → Prop) : r →r r := ⟨λ x, x, λ a b x, x⟩ /-- Composition of two relation homomorphisms is a relation homomorphism. -/ @[trans, simps] protected def comp (g : s →r t) (f : r →r s) : r →r t := ⟨λ x, g (f x), λ a b h, g.2 (f.2 h)⟩ /-- A relation homomorphism is also a relation homomorphism between dual relations. -/ protected def swap (f : r →r s) : swap r →r swap s := ⟨f, λ a b, f.map_rel⟩ /-- A function is a relation homomorphism from the preimage relation of `s` to `s`. -/ def preimage (f : α → β) (s : β → β → Prop) : f ⁻¹'o s →r s := ⟨f, λ a b, id⟩ protected theorem is_irrefl : ∀ (f : r →r s) [is_irrefl β s], is_irrefl α r | ⟨f, o⟩ ⟨H⟩ := ⟨λ a h, H _ (o h)⟩ protected theorem is_asymm : ∀ (f : r →r s) [is_asymm β s], is_asymm α r | ⟨f, o⟩ ⟨H⟩ := ⟨λ a b h₁ h₂, H _ _ (o h₁) (o h₂)⟩ protected theorem acc (f : r →r s) (a : α) : acc s (f a) → acc r a := begin generalize h : f a = b, intro ac, induction ac with _ H IH generalizing a, subst h, exact ⟨_, λ a' h, IH (f a') (f.map_rel h) _ rfl⟩ end protected theorem well_founded : ∀ (f : r →r s) (h : well_founded s), well_founded r | f ⟨H⟩ := ⟨λ a, f.acc _ (H _)⟩ lemma map_inf {α β : Type*} [semilattice_inf α] [linear_order β] (a : ((<) : β → β → Prop) →r ((<) : α → α → Prop)) (m n : β) : a (m ⊓ n) = a m ⊓ a n := begin symmetry, cases le_or_lt n m with h, { rw [inf_eq_right.mpr h, inf_eq_right], exact strict_mono.monotone (λ x y, a.map_rel) h, }, { rw [inf_eq_left.mpr (le_of_lt h), inf_eq_left], exact le_of_lt (a.map_rel h), }, end lemma map_sup {α β : Type*} [semilattice_sup α] [linear_order β] (a : ((>) : β → β → Prop) →r ((>) : α → α → Prop)) (m n : β) : a (m ⊔ n) = a m ⊔ a n := begin symmetry, cases le_or_lt m n with h, { rw [sup_eq_right.mpr h, sup_eq_right], exact strict_mono.monotone (λ x y, a.swap.map_rel) h, }, { rw [sup_eq_left.mpr (le_of_lt h), sup_eq_left], exact le_of_lt (a.map_rel h), }, end end rel_hom /-- An increasing function is injective -/ lemma injective_of_increasing (r : α → α → Prop) (s : β → β → Prop) [is_trichotomous α r] [is_irrefl β s] (f : α → β) (hf : ∀ {x y}, r x y → s (f x) (f y)) : injective f := begin intros x y hxy, rcases trichotomous_of r x y with h | h | h, have := hf h, rw hxy at this, exfalso, exact irrefl_of s (f y) this, exact h, have := hf h, rw hxy at this, exfalso, exact irrefl_of s (f y) this end /-- An increasing function is injective -/ lemma rel_hom.injective_of_increasing [is_trichotomous α r] [is_irrefl β s] (f : r →r s) : injective f := injective_of_increasing r s f (λ x y, f.map_rel) theorem surjective.well_founded_iff {f : α → β} (hf : surjective f) (o : ∀ {a b}, r a b ↔ s (f a) (f b)) : well_founded r ↔ well_founded s := iff.intro (begin apply rel_hom.well_founded, refine rel_hom.mk _ _, {exact classical.some hf.has_right_inverse}, intros a b h, apply o.2, convert h, iterate 2 { apply classical.some_spec hf.has_right_inverse }, end) (rel_hom.well_founded ⟨f, λ _ _, o.1⟩) /-- A relation embedding with respect to a given pair of relations `r` and `s` is an embedding `f : α ↪ β` such that `r a b ↔ s (f a) (f b)`. -/ structure rel_embedding {α β : Type*} (r : α → α → Prop) (s : β → β → Prop) extends α ↪ β := (map_rel_iff' : ∀ {a b}, s (to_embedding a) (to_embedding b) ↔ r a b) infix ` ↪r `:25 := rel_embedding /-- An order embedding is an embedding `f : α ↪ β` such that `a ≤ b ↔ (f a) ≤ (f b)`. This definition is an abbreviation of `rel_embedding (≤) (≤)`. -/ abbreviation order_embedding (α β : Type*) [has_le α] [has_le β] := @rel_embedding α β (≤) (≤) infix ` ↪o `:25 := order_embedding /-- The induced relation on a subtype is an embedding under the natural inclusion. -/ definition subtype.rel_embedding {X : Type*} (r : X → X → Prop) (p : X → Prop) : ((subtype.val : subtype p → X) ⁻¹'o r) ↪r r := ⟨embedding.subtype p, λ x y, iff.rfl⟩ theorem preimage_equivalence {α β} (f : α → β) {s : β → β → Prop} (hs : equivalence s) : equivalence (f ⁻¹'o s) := ⟨λ a, hs.1 _, λ a b h, hs.2.1 h, λ a b c h₁ h₂, hs.2.2 h₁ h₂⟩ namespace rel_embedding /-- A relation embedding is also a relation homomorphism -/ def to_rel_hom (f : r ↪r s) : (r →r s) := { to_fun := f.to_embedding.to_fun, map_rel' := λ x y, (map_rel_iff' f).mpr } instance : has_coe (r ↪r s) (r →r s) := ⟨to_rel_hom⟩ -- see Note [function coercion] instance : has_coe_to_fun (r ↪r s) := ⟨λ _, α → β, λ o, o.to_embedding⟩ /-- See Note [custom simps projection]. We need to specify this projection explicitly in this case, because it is a composition of multiple projections. -/ def simps.apply (h : r ↪r s) : α → β := h initialize_simps_projections rel_embedding (to_embedding_to_fun → apply, -to_embedding) @[simp] lemma to_rel_hom_eq_coe (f : r ↪r s) : f.to_rel_hom = f := rfl @[simp] lemma coe_coe_fn (f : r ↪r s) : ((f : r →r s) : α → β) = f := rfl theorem injective (f : r ↪r s) : injective f := f.inj' theorem map_rel_iff (f : r ↪r s) : ∀ {a b}, s (f a) (f b) ↔ r a b := f.map_rel_iff' @[simp] theorem coe_fn_mk (f : α ↪ β) (o) : (@rel_embedding.mk _ _ r s f o : α → β) = f := rfl @[simp] theorem coe_fn_to_embedding (f : r ↪r s) : (f.to_embedding : α → β) = f := rfl /-- The map `coe_fn : (r ↪r s) → (α → β)` is injective. We can't use `function.injective` here but mimic its signature by using `⦃e₁ e₂⦄`. -/ theorem coe_fn_inj : ∀ ⦃e₁ e₂ : r ↪r s⦄, (e₁ : α → β) = e₂ → e₁ = e₂ | ⟨⟨f₁, h₁⟩, o₁⟩ ⟨⟨f₂, h₂⟩, o₂⟩ h := by { congr, exact h } @[ext] theorem ext ⦃f g : r ↪r s⦄ (h : ∀ x, f x = g x) : f = g := coe_fn_inj (funext h) theorem ext_iff {f g : r ↪r s} : f = g ↔ ∀ x, f x = g x := ⟨λ h x, h ▸ rfl, λ h, ext h⟩ /-- Identity map is a relation embedding. -/ @[refl, simps] protected def refl (r : α → α → Prop) : r ↪r r := ⟨embedding.refl _, λ a b, iff.rfl⟩ /-- Composition of two relation embeddings is a relation embedding. -/ @[trans] protected def trans (f : r ↪r s) (g : s ↪r t) : r ↪r t := ⟨f.1.trans g.1, λ a b, by simp [f.map_rel_iff, g.map_rel_iff]⟩ instance (r : α → α → Prop) : inhabited (r ↪r r) := ⟨rel_embedding.refl _⟩ theorem trans_apply (f : r ↪r s) (g : s ↪r t) (a : α) : (f.trans g) a = g (f a) := rfl @[simp] theorem coe_trans (f : r ↪r s) (g : s ↪r t) : ⇑(f.trans g) = g ∘ f := rfl /-- A relation embedding is also a relation embedding between dual relations. -/ protected def swap (f : r ↪r s) : swap r ↪r swap s := ⟨f.to_embedding, λ a b, f.map_rel_iff⟩ /-- If `f` is injective, then it is a relation embedding from the preimage relation of `s` to `s`. -/ def preimage (f : α ↪ β) (s : β → β → Prop) : f ⁻¹'o s ↪r s := ⟨f, λ a b, iff.rfl⟩ theorem eq_preimage (f : r ↪r s) : r = f ⁻¹'o s := by { ext a b, exact f.map_rel_iff.symm } protected theorem is_irrefl (f : r ↪r s) [is_irrefl β s] : is_irrefl α r := ⟨λ a, mt f.map_rel_iff.2 (irrefl (f a))⟩ protected theorem is_refl (f : r ↪r s) [is_refl β s] : is_refl α r := ⟨λ a, f.map_rel_iff.1 $ refl _⟩ protected theorem is_symm (f : r ↪r s) [is_symm β s] : is_symm α r := ⟨λ a b, imp_imp_imp f.map_rel_iff.2 f.map_rel_iff.1 symm⟩ protected theorem is_asymm (f : r ↪r s) [is_asymm β s] : is_asymm α r := ⟨λ a b h₁ h₂, asymm (f.map_rel_iff.2 h₁) (f.map_rel_iff.2 h₂)⟩ protected theorem is_antisymm : ∀ (f : r ↪r s) [is_antisymm β s], is_antisymm α r | ⟨f, o⟩ ⟨H⟩ := ⟨λ a b h₁ h₂, f.inj' (H _ _ (o.2 h₁) (o.2 h₂))⟩ protected theorem is_trans : ∀ (f : r ↪r s) [is_trans β s], is_trans α r | ⟨f, o⟩ ⟨H⟩ := ⟨λ a b c h₁ h₂, o.1 (H _ _ _ (o.2 h₁) (o.2 h₂))⟩ protected theorem is_total : ∀ (f : r ↪r s) [is_total β s], is_total α r | ⟨f, o⟩ ⟨H⟩ := ⟨λ a b, (or_congr o o).1 (H _ _)⟩ protected theorem is_preorder : ∀ (f : r ↪r s) [is_preorder β s], is_preorder α r | f H := by exactI {..f.is_refl, ..f.is_trans} protected theorem is_partial_order : ∀ (f : r ↪r s) [is_partial_order β s], is_partial_order α r | f H := by exactI {..f.is_preorder, ..f.is_antisymm} protected theorem is_linear_order : ∀ (f : r ↪r s) [is_linear_order β s], is_linear_order α r | f H := by exactI {..f.is_partial_order, ..f.is_total} protected theorem is_strict_order : ∀ (f : r ↪r s) [is_strict_order β s], is_strict_order α r | f H := by exactI {..f.is_irrefl, ..f.is_trans} protected theorem is_trichotomous : ∀ (f : r ↪r s) [is_trichotomous β s], is_trichotomous α r | ⟨f, o⟩ ⟨H⟩ := ⟨λ a b, (or_congr o (or_congr f.inj'.eq_iff o)).1 (H _ _)⟩ protected theorem is_strict_total_order' : ∀ (f : r ↪r s) [is_strict_total_order' β s], is_strict_total_order' α r | f H := by exactI {..f.is_trichotomous, ..f.is_strict_order} protected theorem acc (f : r ↪r s) (a : α) : acc s (f a) → acc r a := begin generalize h : f a = b, intro ac, induction ac with _ H IH generalizing a, subst h, exact ⟨_, λ a' h, IH (f a') (f.map_rel_iff.2 h) _ rfl⟩ end protected theorem well_founded : ∀ (f : r ↪r s) (h : well_founded s), well_founded r | f ⟨H⟩ := ⟨λ a, f.acc _ (H _)⟩ protected theorem is_well_order : ∀ (f : r ↪r s) [is_well_order β s], is_well_order α r | f H := by exactI {wf := f.well_founded H.wf, ..f.is_strict_total_order'} /-- To define an relation embedding from an antisymmetric relation `r` to a reflexive relation `s` it suffices to give a function together with a proof that it satisfies `s (f a) (f b) ↔ r a b`. -/ def of_map_rel_iff (f : α → β) [is_antisymm α r] [is_refl β s] (hf : ∀ a b, s (f a) (f b) ↔ r a b) : r ↪r s := { to_fun := f, inj' := λ x y h, antisymm ((hf _ _).1 (h ▸ refl _)) ((hf _ _).1 (h ▸ refl _)), map_rel_iff' := hf } @[simp] lemma of_map_rel_iff_coe (f : α → β) [is_antisymm α r] [is_refl β s] (hf : ∀ a b, s (f a) (f b) ↔ r a b) : ⇑(of_map_rel_iff f hf : r ↪r s) = f := rfl /-- It suffices to prove `f` is monotone between strict relations to show it is a relation embedding. -/ def of_monotone [is_trichotomous α r] [is_asymm β s] (f : α → β) (H : ∀ a b, r a b → s (f a) (f b)) : r ↪r s := begin haveI := @is_asymm.is_irrefl β s _, refine ⟨⟨f, λ a b e, _⟩, λ a b, ⟨λ h, _, H _ _⟩⟩, { refine ((@trichotomous _ r _ a b).resolve_left _).resolve_right _; exact λ h, @irrefl _ s _ _ (by simpa [e] using H _ _ h) }, { refine (@trichotomous _ r _ a b).resolve_right (or.rec (λ e, _) (λ h', _)), { subst e, exact irrefl _ h }, { exact asymm (H _ _ h') h } } end @[simp] theorem of_monotone_coe [is_trichotomous α r] [is_asymm β s] (f : α → β) (H) : (@of_monotone _ _ r s _ _ f H : α → β) = f := rfl /-- Embeddings of partial orders that preserve `<` also preserve `≤`. -/ def order_embedding_of_lt_embedding [partial_order α] [partial_order β] (f : ((<) : α → α → Prop) ↪r ((<) : β → β → Prop)) : α ↪o β := { map_rel_iff' := by { intros, simp [le_iff_lt_or_eq,f.map_rel_iff, f.injective.eq_iff] }, .. f } @[simp] lemma order_embedding_of_lt_embedding_apply [partial_order α] [partial_order β] {f : ((<) : α → α → Prop) ↪r ((<) : β → β → Prop)} {x : α} : order_embedding_of_lt_embedding f x = f x := rfl end rel_embedding namespace order_embedding variables [preorder α] [preorder β] (f : α ↪o β) /-- `<` is preserved by order embeddings of preorders. -/ def lt_embedding : ((<) : α → α → Prop) ↪r ((<) : β → β → Prop) := { map_rel_iff' := by intros; simp [lt_iff_le_not_le, f.map_rel_iff], .. f } @[simp] lemma lt_embedding_apply (x : α) : f.lt_embedding x = f x := rfl @[simp] theorem le_iff_le {a b} : (f a) ≤ (f b) ↔ a ≤ b := f.map_rel_iff @[simp] theorem lt_iff_lt {a b} : f a < f b ↔ a < b := f.lt_embedding.map_rel_iff @[simp] lemma eq_iff_eq {a b} : f a = f b ↔ a = b := f.injective.eq_iff protected theorem monotone : monotone f := λ x y, f.le_iff_le.2 protected theorem strict_mono : strict_mono f := λ x y, f.lt_iff_lt.2 protected theorem acc (a : α) : acc (<) (f a) → acc (<) a := f.lt_embedding.acc a protected theorem well_founded : well_founded ((<) : β → β → Prop) → well_founded ((<) : α → α → Prop) := f.lt_embedding.well_founded protected theorem is_well_order [is_well_order β (<)] : is_well_order α (<) := f.lt_embedding.is_well_order /-- An order embedding is also an order embedding between dual orders. -/ protected def dual : order_dual α ↪o order_dual β := ⟨f.to_embedding, λ a b, f.map_rel_iff⟩ /-- To define an order embedding from a partial order to a preorder it suffices to give a function together with a proof that it satisfies `f a ≤ f b ↔ a ≤ b`. -/ def of_map_rel_iff {α β} [partial_order α] [preorder β] (f : α → β) (hf : ∀ a b, f a ≤ f b ↔ a ≤ b) : α ↪o β := rel_embedding.of_map_rel_iff f hf @[simp] lemma coe_of_map_rel_iff {α β} [partial_order α] [preorder β] {f : α → β} (h) : ⇑(of_map_rel_iff f h) = f := rfl /-- A strictly monotone map from a linear order is an order embedding. --/ def of_strict_mono {α β} [linear_order α] [preorder β] (f : α → β) (h : strict_mono f) : α ↪o β := of_map_rel_iff f (λ _ _, h.le_iff_le) @[simp] lemma coe_of_strict_mono {α β} [linear_order α] [preorder β] {f : α → β} (h : strict_mono f) : ⇑(of_strict_mono f h) = f := rfl /-- Embedding of a subtype into the ambient type as an `order_embedding`. -/ @[simps {fully_applied := ff}] def subtype (p : α → Prop) : subtype p ↪o α := ⟨embedding.subtype p, λ x y, iff.rfl⟩ end order_embedding /-- A relation isomorphism is an equivalence that is also a relation embedding. -/ structure rel_iso {α β : Type*} (r : α → α → Prop) (s : β → β → Prop) extends α ≃ β := (map_rel_iff' : ∀ {a b}, s (to_equiv a) (to_equiv b) ↔ r a b) infix ` ≃r `:25 := rel_iso /-- An order isomorphism is an equivalence such that `a ≤ b ↔ (f a) ≤ (f b)`. This definition is an abbreviation of `rel_iso (≤) (≤)`. -/ abbreviation order_iso (α β : Type*) [has_le α] [has_le β] := @rel_iso α β (≤) (≤) infix ` ≃o `:25 := order_iso namespace rel_iso /-- Convert an `rel_iso` to an `rel_embedding`. This function is also available as a coercion but often it is easier to write `f.to_rel_embedding` than to write explicitly `r` and `s` in the target type. -/ def to_rel_embedding (f : r ≃r s) : r ↪r s := ⟨f.to_equiv.to_embedding, f.map_rel_iff'⟩ instance : has_coe (r ≃r s) (r ↪r s) := ⟨to_rel_embedding⟩ -- see Note [function coercion] instance : has_coe_to_fun (r ≃r s) := ⟨λ _, α → β, λ f, f⟩ @[simp] lemma to_rel_embedding_eq_coe (f : r ≃r s) : f.to_rel_embedding = f := rfl @[simp] lemma coe_coe_fn (f : r ≃r s) : ((f : r ↪r s) : α → β) = f := rfl theorem map_rel_iff (f : r ≃r s) : ∀ {a b}, s (f a) (f b) ↔ r a b := f.map_rel_iff' @[simp] theorem coe_fn_mk (f : α ≃ β) (o : ∀ ⦃a b⦄, s (f a) (f b) ↔ r a b) : (rel_iso.mk f o : α → β) = f := rfl @[simp] theorem coe_fn_to_equiv (f : r ≃r s) : (f.to_equiv : α → β) = f := rfl theorem to_equiv_injective : injective (to_equiv : (r ≃r s) → α ≃ β) | ⟨e₁, o₁⟩ ⟨e₂, o₂⟩ h := by { congr, exact h } /-- The map `coe_fn : (r ≃r s) → (α → β)` is injective. Lean fails to parse `function.injective (λ e : r ≃r s, (e : α → β))`, so we use a trick to say the same. -/ theorem coe_fn_injective : @function.injective (r ≃r s) (α → β) coe_fn := equiv.coe_fn_injective.comp to_equiv_injective @[ext] theorem ext ⦃f g : r ≃r s⦄ (h : ∀ x, f x = g x) : f = g := coe_fn_injective (funext h) theorem ext_iff {f g : r ≃r s} : f = g ↔ ∀ x, f x = g x := ⟨λ h x, h ▸ rfl, λ h, ext h⟩ /-- Inverse map of a relation isomorphism is a relation isomorphism. -/ @[symm] protected def symm (f : r ≃r s) : s ≃r r := ⟨f.to_equiv.symm, λ a b, by erw [← f.map_rel_iff, f.1.apply_symm_apply, f.1.apply_symm_apply]⟩ /-- See Note [custom simps projection]. We need to specify this projection explicitly in this case, because it is a composition of multiple projections. -/ def simps.apply (h : r ≃r s) : α → β := h /-- See Note [custom simps projection]. -/ def simps.symm_apply (h : r ≃r s) : β → α := h.symm initialize_simps_projections rel_iso (to_equiv_to_fun → apply, to_equiv_inv_fun → symm_apply, -to_equiv) /-- Identity map is a relation isomorphism. -/ @[refl, simps apply] protected def refl (r : α → α → Prop) : r ≃r r := ⟨equiv.refl _, λ a b, iff.rfl⟩ /-- Composition of two relation isomorphisms is a relation isomorphism. -/ @[trans, simps apply] protected def trans (f₁ : r ≃r s) (f₂ : s ≃r t) : r ≃r t := ⟨f₁.to_equiv.trans f₂.to_equiv, λ a b, f₂.map_rel_iff.trans f₁.map_rel_iff⟩ instance (r : α → α → Prop) : inhabited (r ≃r r) := ⟨rel_iso.refl _⟩ @[simp] lemma default_def (r : α → α → Prop) : default (r ≃r r) = rel_iso.refl r := rfl /-- a relation isomorphism is also a relation isomorphism between dual relations. -/ protected def swap (f : r ≃r s) : (swap r) ≃r (swap s) := ⟨f.to_equiv, λ _ _, f.map_rel_iff⟩ @[simp] theorem coe_fn_symm_mk (f o) : ((@rel_iso.mk _ _ r s f o).symm : β → α) = f.symm := rfl @[simp] theorem apply_symm_apply (e : r ≃r s) (x : β) : e (e.symm x) = x := e.to_equiv.apply_symm_apply x @[simp] theorem symm_apply_apply (e : r ≃r s) (x : α) : e.symm (e x) = x := e.to_equiv.symm_apply_apply x theorem rel_symm_apply (e : r ≃r s) {x y} : r x (e.symm y) ↔ s (e x) y := by rw [← e.map_rel_iff, e.apply_symm_apply] theorem symm_apply_rel (e : r ≃r s) {x y} : r (e.symm x) y ↔ s x (e y) := by rw [← e.map_rel_iff, e.apply_symm_apply] protected lemma bijective (e : r ≃r s) : bijective e := e.to_equiv.bijective protected lemma injective (e : r ≃r s) : injective e := e.to_equiv.injective protected lemma surjective (e : r ≃r s) : surjective e := e.to_equiv.surjective @[simp] lemma range_eq (e : r ≃r s) : set.range e = set.univ := e.surjective.range_eq @[simp] lemma eq_iff_eq (f : r ≃r s) {a b} : f a = f b ↔ a = b := f.injective.eq_iff /-- Any equivalence lifts to a relation isomorphism between `s` and its preimage. -/ protected def preimage (f : α ≃ β) (s : β → β → Prop) : f ⁻¹'o s ≃r s := ⟨f, λ a b, iff.rfl⟩ /-- A surjective relation embedding is a relation isomorphism. -/ @[simps apply] noncomputable def of_surjective (f : r ↪r s) (H : surjective f) : r ≃r s := ⟨equiv.of_bijective f ⟨f.injective, H⟩, λ a b, f.map_rel_iff⟩ /-- Given relation isomorphisms `r₁ ≃r s₁` and `r₂ ≃r s₂`, construct a relation isomorphism for the lexicographic orders on the sum. -/ def sum_lex_congr {α₁ α₂ β₁ β₂ r₁ r₂ s₁ s₂} (e₁ : @rel_iso α₁ β₁ r₁ s₁) (e₂ : @rel_iso α₂ β₂ r₂ s₂) : sum.lex r₁ r₂ ≃r sum.lex s₁ s₂ := ⟨equiv.sum_congr e₁.to_equiv e₂.to_equiv, λ a b, by cases e₁ with f hf; cases e₂ with g hg; cases a; cases b; simp [hf, hg]⟩ /-- Given relation isomorphisms `r₁ ≃r s₁` and `r₂ ≃r s₂`, construct a relation isomorphism for the lexicographic orders on the product. -/ def prod_lex_congr {α₁ α₂ β₁ β₂ r₁ r₂ s₁ s₂} (e₁ : @rel_iso α₁ β₁ r₁ s₁) (e₂ : @rel_iso α₂ β₂ r₂ s₂) : prod.lex r₁ r₂ ≃r prod.lex s₁ s₂ := ⟨equiv.prod_congr e₁.to_equiv e₂.to_equiv, λ a b, by simp [prod.lex_def, e₁.map_rel_iff, e₂.map_rel_iff]⟩ instance : group (r ≃r r) := { one := rel_iso.refl r, mul := λ f₁ f₂, f₂.trans f₁, inv := rel_iso.symm, mul_assoc := λ f₁ f₂ f₃, rfl, one_mul := λ f, ext $ λ _, rfl, mul_one := λ f, ext $ λ _, rfl, mul_left_inv := λ f, ext f.symm_apply_apply } @[simp] lemma coe_one : ⇑(1 : r ≃r r) = id := rfl @[simp] lemma coe_mul (e₁ e₂ : r ≃r r) : ⇑(e₁ * e₂) = e₁ ∘ e₂ := rfl lemma mul_apply (e₁ e₂ : r ≃r r) (x : α) : (e₁ * e₂) x = e₁ (e₂ x) := rfl @[simp] lemma inv_apply_self (e : r ≃r r) (x) : e⁻¹ (e x) = x := e.symm_apply_apply x @[simp] lemma apply_inv_self (e : r ≃r r) (x) : e (e⁻¹ x) = x := e.apply_symm_apply x end rel_iso namespace order_iso section has_le variables [has_le α] [has_le β] [has_le γ] /-- Reinterpret an order isomorphism as an order embedding. -/ def to_order_embedding (e : α ≃o β) : α ↪o β := e.to_rel_embedding @[simp] lemma coe_to_order_embedding (e : α ≃o β) : ⇑(e.to_order_embedding) = e := rfl protected lemma bijective (e : α ≃o β) : bijective e := e.to_equiv.bijective protected lemma injective (e : α ≃o β) : injective e := e.to_equiv.injective protected lemma surjective (e : α ≃o β) : surjective e := e.to_equiv.surjective @[simp] lemma range_eq (e : α ≃o β) : set.range e = set.univ := e.surjective.range_eq @[simp] lemma apply_eq_iff_eq (e : α ≃o β) {x y : α} : e x = e y ↔ x = y := e.to_equiv.apply_eq_iff_eq /-- Identity order isomorphism. -/ def refl (α : Type*) [has_le α] : α ≃o α := rel_iso.refl (≤) @[simp] lemma coe_refl : ⇑(refl α) = id := rfl lemma refl_apply (x : α) : refl α x = x := rfl @[simp] lemma refl_to_equiv : (refl α).to_equiv = equiv.refl α := rfl /-- Inverse of an order isomorphism. -/ def symm (e : α ≃o β) : β ≃o α := e.symm @[simp] lemma apply_symm_apply (e : α ≃o β) (x : β) : e (e.symm x) = x := e.to_equiv.apply_symm_apply x @[simp] lemma symm_apply_apply (e : α ≃o β) (x : α) : e.symm (e x) = x := e.to_equiv.symm_apply_apply x @[simp] lemma symm_refl (α : Type*) [has_le α] : (refl α).symm = refl α := rfl lemma apply_eq_iff_eq_symm_apply (e : α ≃o β) (x : α) (y : β) : e x = y ↔ x = e.symm y := e.to_equiv.apply_eq_iff_eq_symm_apply theorem symm_apply_eq (e : α ≃o β) {x : α} {y : β} : e.symm y = x ↔ y = e x := e.to_equiv.symm_apply_eq @[simp] lemma symm_symm (e : α ≃o β) : e.symm.symm = e := by { ext, refl } lemma symm_injective : injective (symm : (α ≃o β) → (β ≃o α)) := λ e e' h, by rw [← e.symm_symm, h, e'.symm_symm] @[simp] lemma to_equiv_symm (e : α ≃o β) : e.to_equiv.symm = e.symm.to_equiv := rfl @[simp] lemma symm_image_image (e : α ≃o β) (s : set α) : e.symm '' (e '' s) = s := e.to_equiv.symm_image_image s @[simp] lemma image_symm_image (e : α ≃o β) (s : set β) : e '' (e.symm '' s) = s := e.to_equiv.image_symm_image s lemma image_eq_preimage (e : α ≃o β) (s : set α) : e '' s = e.symm ⁻¹' s := e.to_equiv.image_eq_preimage s @[simp] lemma preimage_symm_preimage (e : α ≃o β) (s : set α) : e ⁻¹' (e.symm ⁻¹' s) = s := e.to_equiv.preimage_symm_preimage s @[simp] lemma symm_preimage_preimage (e : α ≃o β) (s : set β) : e.symm ⁻¹' (e ⁻¹' s) = s := e.to_equiv.symm_preimage_preimage s @[simp] lemma image_preimage (e : α ≃o β) (s : set β) : e '' (e ⁻¹' s) = s := e.to_equiv.image_preimage s @[simp] lemma preimage_image (e : α ≃o β) (s : set α) : e ⁻¹' (e '' s) = s := e.to_equiv.preimage_image s /-- Composition of two order isomorphisms is an order isomorphism. -/ @[trans] def trans (e : α ≃o β) (e' : β ≃o γ) : α ≃o γ := e.trans e' @[simp] lemma coe_trans (e : α ≃o β) (e' : β ≃o γ) : ⇑(e.trans e') = e' ∘ e := rfl lemma trans_apply (e : α ≃o β) (e' : β ≃o γ) (x : α) : e.trans e' x = e' (e x) := rfl @[simp] lemma refl_trans (e : α ≃o β) : (refl α).trans e = e := by { ext x, refl } @[simp] lemma trans_refl (e : α ≃o β) : e.trans (refl β) = e := by { ext x, refl } end has_le open set section le variables [has_le α] [has_le β] [has_le γ] @[simp] lemma le_iff_le (e : α ≃o β) {x y : α} : e x ≤ e y ↔ x ≤ y := e.map_rel_iff lemma le_symm_apply (e : α ≃o β) {x : α} {y : β} : x ≤ e.symm y ↔ e x ≤ y := e.rel_symm_apply lemma symm_apply_le (e : α ≃o β) {x : α} {y : β} : e.symm y ≤ x ↔ y ≤ e x := e.symm_apply_rel end le variables [preorder α] [preorder β] [preorder γ] protected lemma monotone (e : α ≃o β) : monotone e := e.to_order_embedding.monotone protected lemma strict_mono (e : α ≃o β) : strict_mono e := e.to_order_embedding.strict_mono @[simp] lemma lt_iff_lt (e : α ≃o β) {x y : α} : e x < e y ↔ x < y := e.to_order_embedding.lt_iff_lt /-- To show that `f : α → β`, `g : β → α` make up an order isomorphism of linear orders, it suffices to prove `cmp a (g b) = cmp (f a) b`. --/ def of_cmp_eq_cmp {α β} [linear_order α] [linear_order β] (f : α → β) (g : β → α) (h : ∀ (a : α) (b : β), cmp a (g b) = cmp (f a) b) : α ≃o β := have gf : ∀ (a : α), a = g (f a) := by { intro, rw [←cmp_eq_eq_iff, h, cmp_self_eq_eq] }, { to_fun := f, inv_fun := g, left_inv := λ a, (gf a).symm, right_inv := by { intro, rw [←cmp_eq_eq_iff, ←h, cmp_self_eq_eq] }, map_rel_iff' := by { intros, apply le_iff_le_of_cmp_eq_cmp, convert (h _ _).symm, apply gf } } /-- Order isomorphism between two equal sets. -/ def set_congr (s t : set α) (h : s = t) : s ≃o t := { to_equiv := equiv.set_congr h, map_rel_iff' := λ x y, iff.rfl } /-- Order isomorphism between `univ : set α` and `α`. -/ def set.univ : (set.univ : set α) ≃o α := { to_equiv := equiv.set.univ α, map_rel_iff' := λ x y, iff.rfl } end order_iso namespace equiv variables [preorder α] [preorder β] /-- If `e` is an equivalence with monotone forward and inverse maps, then `e` is an order isomorphism. -/ def to_order_iso (e : α ≃ β) (h₁ : monotone e) (h₂ : monotone e.symm) : α ≃o β := ⟨e, λ x y, ⟨λ h, by simpa only [e.symm_apply_apply] using h₂ h, λ h, h₁ h⟩⟩ @[simp] lemma coe_to_order_iso (e : α ≃ β) (h₁ : monotone e) (h₂ : monotone e.symm) : ⇑(e.to_order_iso h₁ h₂) = e := rfl @[simp] lemma to_order_iso_to_equiv (e : α ≃ β) (h₁ : monotone e) (h₂ : monotone e.symm) : (e.to_order_iso h₁ h₂).to_equiv = e := rfl end equiv /-- If a function `f` is strictly monotone on a set `s`, then it defines an order isomorphism between `s` and its image. -/ protected noncomputable def strict_mono_incr_on.order_iso {α β} [linear_order α] [preorder β] (f : α → β) (s : set α) (hf : strict_mono_incr_on f s) : s ≃o f '' s := { to_equiv := hf.inj_on.bij_on_image.equiv _, map_rel_iff' := λ x y, hf.le_iff_le x.2 y.2 } /-- A strictly monotone function from a linear order is an order isomorphism between its domain and its range. -/ protected noncomputable def strict_mono.order_iso {α β} [linear_order α] [preorder β] (f : α → β) (h_mono : strict_mono f) : α ≃o set.range f := { to_equiv := equiv.of_injective f h_mono.injective, map_rel_iff' := λ a b, h_mono.le_iff_le } /-- A strictly monotone surjective function from a linear order is an order isomorphism. -/ noncomputable def strict_mono.order_iso_of_surjective {α β} [linear_order α] [preorder β] (f : α → β) (h_mono : strict_mono f) (h_surj : surjective f) : α ≃o β := (h_mono.order_iso f).trans $ (order_iso.set_congr _ _ h_surj.range_eq).trans order_iso.set.univ /-- `subrel r p` is the inherited relation on a subset. -/ def subrel (r : α → α → Prop) (p : set α) : p → p → Prop := (coe : p → α) ⁻¹'o r @[simp] theorem subrel_val (r : α → α → Prop) (p : set α) {a b} : subrel r p a b ↔ r a.1 b.1 := iff.rfl namespace subrel /-- The relation embedding from the inherited relation on a subset. -/ protected def rel_embedding (r : α → α → Prop) (p : set α) : subrel r p ↪r r := ⟨embedding.subtype _, λ a b, iff.rfl⟩ @[simp] theorem rel_embedding_apply (r : α → α → Prop) (p a) : subrel.rel_embedding r p a = a.1 := rfl instance (r : α → α → Prop) [is_well_order α r] (p : set α) : is_well_order p (subrel r p) := rel_embedding.is_well_order (subrel.rel_embedding r p) end subrel /-- Restrict the codomain of a relation embedding. -/ def rel_embedding.cod_restrict (p : set β) (f : r ↪r s) (H : ∀ a, f a ∈ p) : r ↪r subrel s p := ⟨f.to_embedding.cod_restrict p H, f.map_rel_iff'⟩ @[simp] theorem rel_embedding.cod_restrict_apply (p) (f : r ↪r s) (H a) : rel_embedding.cod_restrict p f H a = ⟨f a, H a⟩ := rfl /-- An order isomorphism is also an order isomorphism between dual orders. -/ protected def order_iso.dual [preorder α] [preorder β] (f : α ≃o β) : order_dual α ≃o order_dual β := ⟨f.to_equiv, λ _ _, f.map_rel_iff⟩ section lattice_isos lemma order_iso.map_bot' [partial_order α] [partial_order β] (f : α ≃o β) {x : α} {y : β} (hx : ∀ x', x ≤ x') (hy : ∀ y', y ≤ y') : f x = y := by { refine le_antisymm _ (hy _), rw [← f.apply_symm_apply y, f.map_rel_iff], apply hx } lemma order_iso.map_bot [order_bot α] [order_bot β] (f : α ≃o β) : f ⊥ = ⊥ := f.map_bot' (λ _, bot_le) (λ _, bot_le) lemma order_iso.map_top' [partial_order α] [partial_order β] (f : α ≃o β) {x : α} {y : β} (hx : ∀ x', x' ≤ x) (hy : ∀ y', y' ≤ y) : f x = y := f.dual.map_bot' hx hy lemma order_iso.map_top [order_top α] [order_top β] (f : α ≃o β) : f ⊤ = ⊤ := f.dual.map_bot lemma order_embedding.map_inf_le [semilattice_inf α] [semilattice_inf β] (f : α ↪o β) (x y : α) : f (x ⊓ y) ≤ f x ⊓ f y := f.monotone.map_inf_le x y lemma order_iso.map_inf [semilattice_inf α] [semilattice_inf β] (f : α ≃o β) (x y : α) : f (x ⊓ y) = f x ⊓ f y := begin refine (f.to_order_embedding.map_inf_le x y).antisymm _, simpa [← f.symm.le_iff_le] using f.symm.to_order_embedding.map_inf_le (f x) (f y) end lemma order_embedding.le_map_sup [semilattice_sup α] [semilattice_sup β] (f : α ↪o β) (x y : α) : f x ⊔ f y ≤ f (x ⊔ y) := f.monotone.le_map_sup x y lemma order_iso.map_sup [semilattice_sup α] [semilattice_sup β] (f : α ≃o β) (x y : α) : f (x ⊔ y) = f x ⊔ f y := f.dual.map_inf x y section bounded_lattice variables [bounded_lattice α] [bounded_lattice β] (f : α ≃o β) include f lemma order_iso.is_compl {x y : α} (h : is_compl x y) : is_compl (f x) (f y) := ⟨by { rw [← f.map_bot, ← f.map_inf, f.map_rel_iff], exact h.1 }, by { rw [← f.map_top, ← f.map_sup, f.map_rel_iff], exact h.2 }⟩ theorem order_iso.is_compl_iff {x y : α} : is_compl x y ↔ is_compl (f x) (f y) := ⟨f.is_compl, λ h, begin rw [← f.symm_apply_apply x, ← f.symm_apply_apply y], exact f.symm.is_compl h, end⟩ lemma order_iso.is_complemented [is_complemented α] : is_complemented β := ⟨λ x, begin obtain ⟨y, hy⟩ := exists_is_compl (f.symm x), rw ← f.symm_apply_apply y at hy, refine ⟨f y, f.symm.is_compl_iff.2 hy⟩, end⟩ theorem order_iso.is_complemented_iff : is_complemented α ↔ is_complemented β := ⟨by { introI, exact f.is_complemented }, by { introI, exact f.symm.is_complemented }⟩ end bounded_lattice end lattice_isos
f5949932b405f550737b3589ba1be37696c44d51
cbb1957fc3e28e502582c54cbce826d666350eda
/folklore/real_axiom.lean
70135047654df0a3335b277402d9479ef61739d7
[ "CC-BY-4.0" ]
permissive
andrejbauer/formalabstracts
9040b172da080406448ad1b0260d550122dcad74
a3b84fd90901ccf4b63eb9f95d4286a8775864d0
refs/heads/master
1,609,476,417,918
1,501,541,742,000
1,501,541,760,000
97,241,872
1
0
null
1,500,042,191,000
1,500,042,191,000
null
UTF-8
Lean
false
false
5,647
lean
/- axiomatic development of the complete ordered field of real numbers in classical logic. At some point this should be replaced with an actual construction. T.Hales, July 15, 2017 -/ import meta_data data.list noncomputable theory namespace real_axiom open classical nat int list vector local attribute [instance] prop_decidable universe u -- TODO: This definition used to be universe-polymorphic, but it looks like unfinished -- does not support parameters so the universe u is unavailable, fix it. unfinished ℝ : Type := { description := "the type real numbers" } unfinished real_of_int : ℤ → ℝ := { description := "the canonical embedding of integers into reals" } -- TODO: properly treat unbounded and empty sets unfinished sup : (set ℝ) → ℝ := { description := "the supremum of a subset of real numbers" } instance real_of_nat_coe : has_coe ℤ ℝ := ⟨ real_of_int ⟩ @[instance] constant real_ordered_field : linear_ordered_field ℝ -- It is not clear why this line is required; but it is. attribute [instance] real_ordered_field def is_upper_bound {α : Type u} [R : linear_ordered_ring α] (S : set α) (r : α) : Prop := (∀ (s : α), s ∈ S → s ≤ r) def has_upper_bound {α : Type u} [R : linear_ordered_ring α] (S : set α) : Prop := (∃ r : α, is_upper_bound S r) def is_least_upper_bound {α : Type u} [R : linear_ordered_ring α] (S : set α) (s : α) := (is_upper_bound S s ∧ (∀ r, is_upper_bound S r → r ≤ s)) class complete_ordered_field (α : Type u) extends discrete_linear_ordered_field α := (sup : (set α) → α) (dedekind_completeness : (∀ (S : set α), (S ≠ ∅) → has_upper_bound S → is_least_upper_bound S (sup S))) unfinished real_dedekind_completeness : (∀ (S : set ℝ), (S ≠ ∅) → has_upper_bound S → is_least_upper_bound S (sup S)) := { description := "the real numbers are Dedekind complete" } unfinished real_zero_inv : linear_ordered_field.inv (0 : ℝ) = 0 := { description := "since all functions are total, we define 1/0=0"} instance real_complete_ordered_field : complete_ordered_field ℝ := { real_axiom.real_ordered_field with sup := sup, dedekind_completeness := real_dedekind_completeness, inv_zero := real_zero_inv, decidable_lt := by apply_instance, decidable_le := by apply_instance, decidable_eq := by apply_instance } unfinished real_archimedean : (∀ x y, x > 0 → y > 0 → ∃ (n : ℕ), y < n*x) := { description := "the real numbers are an archimedean field" } -- why does -x ∈ S fail? -- why does {x | ... } fail? def real_inf (S : set ℝ) : ℝ := - (sup (λ x, S( -x ))) -- extension by zero when x < 0. def real_sqrt (x : ℝ) : ℝ := sup (λ (t : ℝ), (t = 0) ∨ t*t = x) def real_abs (x : ℝ) : ℝ := sup (λ (t : ℝ), t = x ∨ t = -x) def real_max (x : ℝ) y : ℝ := sup (λ (t : ℝ), t = x ∨ t = y) def real_min (x : ℝ) y : ℝ := real_inf (λ (t : ℝ), t = x ∨ t = y) def real_pow : ℝ → ℕ → ℝ | x 0 := (1 : ℝ) | x (succ n) := x * (real_pow x n) local infix `^` := real_pow unfinished pi : ℝ := { description := "the ratio of the circumference and the diameter of a circle" } -- one possible specification of pi unfinished pi_def : (∀ (n : nat), let iota := list.iota n, terms := list.map (λ k, (-1)^(k+1) / (2*k-1)) iota in (real_abs (pi/ 4 - list.sum terms) < 1 / (2*n + 3))) := { description := "alternating series for pi/4 = 1 - 1/3 + 1/5 -..." } inductive extended_real | of_real : ℝ → extended_real | inf : extended_real | neg_inf : extended_real notation `ℝ∞` := extended_real unfinished ext_reals_has_add : has_add ℝ∞ := { description := "extended reals have a + operator" } unfinished ext_reals_has_sub : has_sub ℝ∞ := { description := "extended reals have a - operator" } unfinished ext_reals_has_mul : has_mul ℝ∞ := { description := "extended reals have a * operator" } unfinished ext_reals_has_div : has_div ℝ∞ := { description := "extended reals have a / operator" } unfinished ext_reals_order : order_pair ℝ∞ := { description := "extended reals are ordered" } instance : has_zero ℝ∞ := ⟨extended_real.of_real 0⟩ instance : has_one ℝ∞ := ⟨extended_real.of_real 1⟩ attribute [instance] ext_reals_has_add ext_reals_has_sub ext_reals_has_mul ext_reals_has_div ext_reals_order unfinished ext_reals_mul_spec : extended_real.inf * 0 = 0 := { description := "we specify that ∞ * 0 = 0" } def extended_real.sup (s : set extended_real) : extended_real := if extended_real.inf ∈ s then extended_real.inf else let non_neg_inf := {r | ∃ r' ∈ s, r' = extended_real.of_real r} in extended_real.of_real (complete_ordered_field.sup non_neg_inf) def extended_real.partial_sum (f : ℕ → ℝ∞) (n : ℕ) : ℝ∞ := ((list.iota n).map f).foldr (+) 0 open extended_real def extended_real.countable_sum (f : ℕ → ℝ∞) := if h : (∃ r : ℝ, ∀ ε : ℝ, ε > 0 → ∃ n, of_real (-ε) < extended_real.partial_sum f n - of_real r ∧ extended_real.partial_sum f n - of_real r < of_real ε) then of_real (some h) else inf unfinished countable_sum_spec : ∀ f : ℕ → ℝ∞, ∀ h : (∀ n, f n ≥ 0), (∀ ε : ℝ, ε > 0 → ∃ n, of_real (-ε) < extended_real.partial_sum f n - (extended_real.countable_sum f) ∧ extended_real.partial_sum f n - (extended_real.countable_sum f) < of_real ε) ∨ (∀ r : ℝ, ∃ n, extended_real.partial_sum f n > of_real r) := { description := "If f : ℕ → ℝ∞ is nonnegative, then it has a countable sum in ℝ∞, either a real or ∞" } end real_axiom
fabd33930cc1acc36e1aebc8f862479f1b647034
4727251e0cd73359b15b664c3170e5d754078599
/src/order/category/BoundedOrder.lean
8c359e2282b31f551846e5cce65e190eaa598e05
[ "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,269
lean
/- Copyright (c) 2022 Yaël Dillies. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yaël Dillies -/ import category_theory.category.Bipointed import order.category.PartialOrder import order.hom.bounded /-! # The category of bounded orders This defines `BoundedOrder`, the category of bounded orders. -/ universes u v open category_theory /-- The category of bounded orders with monotone functions. -/ structure BoundedOrder := (to_PartialOrder : PartialOrder) [is_bounded_order : bounded_order to_PartialOrder] namespace BoundedOrder instance : has_coe_to_sort BoundedOrder Type* := induced_category.has_coe_to_sort to_PartialOrder instance (X : BoundedOrder) : partial_order X := X.to_PartialOrder.str attribute [instance] BoundedOrder.is_bounded_order /-- Construct a bundled `BoundedOrder` from a `fintype` `partial_order`. -/ def of (α : Type*) [partial_order α] [bounded_order α] : BoundedOrder := ⟨⟨α⟩⟩ @[simp] lemma coe_of (α : Type*) [partial_order α] [bounded_order α] : ↥(of α) = α := rfl instance : inhabited BoundedOrder := ⟨of punit⟩ instance large_category : large_category.{u} BoundedOrder := { hom := λ X Y, bounded_order_hom X Y, id := λ X, bounded_order_hom.id X, comp := λ X Y Z f g, g.comp f, id_comp' := λ X Y, bounded_order_hom.comp_id, comp_id' := λ X Y, bounded_order_hom.id_comp, assoc' := λ W X Y Z _ _ _, bounded_order_hom.comp_assoc _ _ _ } instance concrete_category : concrete_category BoundedOrder := { forget := ⟨coe_sort, λ X Y, coe_fn, λ X, rfl, λ X Y Z f g, rfl⟩, forget_faithful := ⟨λ X Y, by convert fun_like.coe_injective⟩ } instance has_forget_to_PartialOrder : has_forget₂ BoundedOrder PartialOrder := { forget₂ := { obj := λ X, X.to_PartialOrder, map := λ X Y, bounded_order_hom.to_order_hom } } instance has_forget_to_Bipointed : has_forget₂ BoundedOrder Bipointed := { forget₂ := { obj := λ X, ⟨X, ⊥, ⊤⟩, map := λ X Y f, ⟨f, map_bot f, map_top f⟩ }, forget_comp := rfl } /-- `order_dual` as a functor. -/ @[simps] def dual : BoundedOrder ⥤ BoundedOrder := { obj := λ X, of Xᵒᵈ, map := λ X Y, bounded_order_hom.dual } /-- Constructs an equivalence between bounded orders from an order isomorphism between them. -/ @[simps] def iso.mk {α β : BoundedOrder.{u}} (e : α ≃o β) : α ≅ β := { hom := e, inv := e.symm, hom_inv_id' := by { ext, exact e.symm_apply_apply _ }, inv_hom_id' := by { ext, exact e.apply_symm_apply _ } } /-- The equivalence between `BoundedOrder` and itself induced by `order_dual` both ways. -/ @[simps functor inverse] def dual_equiv : BoundedOrder ≌ BoundedOrder := equivalence.mk dual dual (nat_iso.of_components (λ X, iso.mk $ order_iso.dual_dual X) $ λ X Y f, rfl) (nat_iso.of_components (λ X, iso.mk $ order_iso.dual_dual X) $ λ X Y f, rfl) end BoundedOrder lemma BoundedOrder_dual_comp_forget_to_PartialOrder : BoundedOrder.dual ⋙ forget₂ BoundedOrder PartialOrder = forget₂ BoundedOrder PartialOrder ⋙ PartialOrder.dual := rfl lemma BoundedOrder_dual_comp_forget_to_Bipointed : BoundedOrder.dual ⋙ forget₂ BoundedOrder Bipointed = forget₂ BoundedOrder Bipointed ⋙ Bipointed.swap := rfl
0d943e333ca8e46009cc14b505c7db0ed3a47fef
c777c32c8e484e195053731103c5e52af26a25d1
/src/measure_theory/measure/hausdorff.lean
2b28738a336d312317df5af8bf2415b4ae99139d
[ "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
45,200
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.special_functions.pow import measure_theory.constructions.borel_space import measure_theory.measure.lebesgue import topology.metric_space.holder import topology.metric_space.metric_separated /-! # Hausdorff measure and metric (outer) measures In this file we define the `d`-dimensional Hausdorff measure on an (extended) metric space `X` and the Hausdorff dimension of a set in an (extended) metric space. Let `μ d δ` be the maximal outer measure such that `μ d δ s ≤ (emetric.diam s) ^ d` for every set of diameter less than `δ`. Then the Hausdorff measure `μH[d] s` of `s` is defined as `⨆ δ > 0, μ d δ s`. By Caratheodory theorem `measure_theory.outer_measure.is_metric.borel_le_caratheodory`, this is a Borel measure on `X`. The value of `μH[d]`, `d > 0`, on a set `s` (measurable or not) is given by ``` μH[d] s = ⨆ (r : ℝ≥0∞) (hr : 0 < r), ⨅ (t : ℕ → set X) (hts : s ⊆ ⋃ n, t n) (ht : ∀ n, emetric.diam (t n) ≤ r), ∑' n, emetric.diam (t n) ^ d ``` For every set `s` for any `d < d'` we have either `μH[d] s = ∞` or `μH[d'] s = 0`, see `measure_theory.measure.hausdorff_measure_zero_or_top`. In `topology.metric_space.hausdorff_dimension` we use this fact to define the Hausdorff dimension `dimH` of a set in an (extended) metric space. We also define two generalizations of the Hausdorff measure. In one generalization (see `measure_theory.measure.mk_metric`) we take any function `m (diam s)` instead of `(diam s) ^ d`. In an even more general definition (see `measure_theory.measure.mk_metric'`) we use any function of `m : set X → ℝ≥0∞`. Some authors start with a partial function `m` defined only on some sets `s : set X` (e.g., only on balls or only on measurable sets). This is equivalent to our definition applied to `measure_theory.extend m`. We also define a predicate `measure_theory.outer_measure.is_metric` which says that an outer measure is additive on metric separated pairs of sets: `μ (s ∪ t) = μ s + μ t` provided that `⨅ (x ∈ s) (y ∈ t), edist x y ≠ 0`. This is the property required for the Caratheodory theorem `measure_theory.outer_measure.is_metric.borel_le_caratheodory`, so we prove this theorem for any metric outer measure, then prove that outer measures constructed using `mk_metric'` are metric outer measures. ## Main definitions * `measure_theory.outer_measure.is_metric`: an outer measure `μ` is called *metric* if `μ (s ∪ t) = μ s + μ t` for any two metric separated sets `s` and `t`. A metric outer measure in a Borel extended metric space is guaranteed to satisfy the Caratheodory condition, see `measure_theory.outer_measure.is_metric.borel_le_caratheodory`. * `measure_theory.outer_measure.mk_metric'` and its particular case `measure_theory.outer_measure.mk_metric`: a construction of an outer measure that is guaranteed to be metric. Both constructions are generalizations of the Hausdorff measure. The same measures interpreted as Borel measures are called `measure_theory.measure.mk_metric'` and `measure_theory.measure.mk_metric`. * `measure_theory.measure.hausdorff_measure` a.k.a. `μH[d]`: the `d`-dimensional Hausdorff measure. There are many definitions of the Hausdorff measure that differ from each other by a multiplicative constant. We put `μH[d] s = ⨆ r > 0, ⨅ (t : ℕ → set X) (hts : s ⊆ ⋃ n, t n) (ht : ∀ n, emetric.diam (t n) ≤ r), ∑' n, ⨆ (ht : ¬set.subsingleton (t n)), (emetric.diam (t n)) ^ d`, see `measure_theory.measure.hausdorff_measure_apply'`. In the most interesting case `0 < d` one can omit the `⨆ (ht : ¬set.subsingleton (t n))` part. ## Main statements ### Basic properties * `measure_theory.outer_measure.is_metric.borel_le_caratheodory`: if `μ` is a metric outer measure on an extended metric space `X` (that is, it is additive on pairs of metric separated sets), then every Borel set is Caratheodory measurable (hence, `μ` defines an actual `measure_theory.measure`). See also `measure_theory.measure.mk_metric`. * `measure_theory.measure.hausdorff_measure_mono`: `μH[d] s` is an antitone function of `d`. * `measure_theory.measure.hausdorff_measure_zero_or_top`: if `d₁ < d₂`, then for any `s`, either `μH[d₂] s = 0` or `μH[d₁] s = ∞`. Together with the previous lemma, this means that `μH[d] s` is equal to infinity on some ray `(-∞, D)` and is equal to zero on `(D, +∞)`, where `D` is a possibly infinite number called the *Hausdorff dimension* of `s`; `μH[D] s` can be zero, infinity, or anything in between. * `measure_theory.measure.no_atoms_hausdorff`: Hausdorff measure has no atoms. ### Hausdorff measure in `ℝⁿ` * `measure_theory.hausdorff_measure_pi_real`: for a nonempty `ι`, `μH[card ι]` on `ι → ℝ` equals Lebesgue measure. ## Notations We use the following notation localized in `measure_theory`. - `μH[d]` : `measure_theory.measure.hausdorff_measure d` ## Implementation notes There are a few similar constructions called the `d`-dimensional Hausdorff measure. E.g., some sources only allow coverings by balls and use `r ^ d` instead of `(diam s) ^ d`. While these construction lead to different Hausdorff measures, they lead to the same notion of the Hausdorff dimension. ## TODO * prove that `1`-dimensional Hausdorff measure on `ℝ` equals `volume`; * prove a similar statement for `ℝ × ℝ`. ## References * [Herbert Federer, Geometric Measure Theory, Chapter 2.10][Federer1996] ## Tags Hausdorff measure, measure, metric measure -/ open_locale nnreal ennreal topology big_operators open emetric set function filter encodable finite_dimensional topological_space noncomputable theory variables {ι X Y : Type*} [emetric_space X] [emetric_space Y] namespace measure_theory namespace outer_measure /-! ### Metric outer measures In this section we define metric outer measures and prove Caratheodory theorem: a metric outer measure has the Caratheodory property. -/ /-- We say that an outer measure `μ` in an (e)metric space is *metric* if `μ (s ∪ t) = μ s + μ t` for any two metric separated sets `s`, `t`. -/ def is_metric (μ : outer_measure X) : Prop := ∀ (s t : set X), is_metric_separated s t → μ (s ∪ t) = μ s + μ t namespace is_metric variables {μ : outer_measure X} /-- A metric outer measure is additive on a finite set of pairwise metric separated sets. -/ lemma finset_Union_of_pairwise_separated (hm : is_metric μ) {I : finset ι} {s : ι → set X} (hI : ∀ (i ∈ I) (j ∈ I), i ≠ j → is_metric_separated (s i) (s j)) : μ (⋃ i ∈ I, s i) = ∑ i in I, μ (s i) := begin classical, induction I using finset.induction_on with i I hiI ihI hI, { simp }, simp only [finset.mem_insert] at hI, rw [finset.set_bUnion_insert, hm, ihI, finset.sum_insert hiI], exacts [λ i hi j hj hij, (hI i (or.inr hi) j (or.inr hj) hij), is_metric_separated.finset_Union_right (λ j hj, hI i (or.inl rfl) j (or.inr hj) (ne_of_mem_of_not_mem hj hiI).symm)] end /-- Caratheodory theorem. If `m` is a metric outer measure, then every Borel measurable set `t` is Caratheodory measurable: for any (not necessarily measurable) set `s` we have `μ (s ∩ t) + μ (s \ t) = μ s`. -/ lemma borel_le_caratheodory (hm : is_metric μ) : borel X ≤ μ.caratheodory := begin rw [borel_eq_generate_from_is_closed], refine measurable_space.generate_from_le (λ t ht, μ.is_caratheodory_iff_le.2 $ λ s, _), set S : ℕ → set X := λ n, {x ∈ s | (↑n)⁻¹ ≤ inf_edist x t}, have n0 : ∀ {n : ℕ}, (n⁻¹ : ℝ≥0∞) ≠ 0, from λ n, ennreal.inv_ne_zero.2 (ennreal.nat_ne_top _), have Ssep : ∀ n, is_metric_separated (S n) t, from λ n, ⟨n⁻¹, n0, λ x hx y hy, hx.2.trans $ inf_edist_le_edist_of_mem hy⟩, have Ssep' : ∀ n, is_metric_separated (S n) (s ∩ t), from λ n, (Ssep n).mono subset.rfl (inter_subset_right _ _), have S_sub : ∀ n, S n ⊆ s \ t, from λ n, subset_inter (inter_subset_left _ _) (Ssep n).subset_compl_right, have hSs : ∀ n, μ (s ∩ t) + μ (S n) ≤ μ s, from λ n, calc μ (s ∩ t) + μ (S n) = μ (s ∩ t ∪ S n) : eq.symm $ hm _ _ $ (Ssep' n).symm ... ≤ μ (s ∩ t ∪ s \ t) : by { mono*, exact le_rfl } ... = μ s : by rw [inter_union_diff], have Union_S : (⋃ n, S n) = s \ t, { refine subset.antisymm (Union_subset S_sub) _, rintro x ⟨hxs, hxt⟩, rw mem_iff_inf_edist_zero_of_closed ht at hxt, rcases ennreal.exists_inv_nat_lt hxt with ⟨n, hn⟩, exact mem_Union.2 ⟨n, hxs, hn.le⟩ }, /- Now we have `∀ n, μ (s ∩ t) + μ (S n) ≤ μ s` and we need to prove `μ (s ∩ t) + μ (⋃ n, S n) ≤ μ s`. We can't pass to the limit because `μ` is only an outer measure. -/ by_cases htop : μ (s \ t) = ∞, { rw [htop, add_top, ← htop], exact μ.mono (diff_subset _ _) }, suffices : μ (⋃ n, S n) ≤ ⨆ n, μ (S n), calc μ (s ∩ t) + μ (s \ t) = μ (s ∩ t) + μ (⋃ n, S n) : by rw Union_S ... ≤ μ (s ∩ t) + ⨆ n, μ (S n) : add_le_add le_rfl this ... = ⨆ n, μ (s ∩ t) + μ (S n) : ennreal.add_supr ... ≤ μ s : supr_le hSs, /- It suffices to show that `∑' k, μ (S (k + 1) \ S k) ≠ ∞`. Indeed, if we have this, then for all `N` we have `μ (⋃ n, S n) ≤ μ (S N) + ∑' k, m (S (N + k + 1) \ S (N + k))` and the second term tends to zero, see `outer_measure.Union_nat_of_monotone_of_tsum_ne_top` for details. -/ have : ∀ n, S n ⊆ S (n + 1), from λ n x hx, ⟨hx.1, le_trans (ennreal.inv_le_inv.2 $ nat.cast_le.2 n.le_succ) hx.2⟩, refine (μ.Union_nat_of_monotone_of_tsum_ne_top this _).le, clear this, /- While the sets `S (k + 1) \ S k` are not pairwise metric separated, the sets in each subsequence `S (2 * k + 1) \ S (2 * k)` and `S (2 * k + 2) \ S (2 * k)` are metric separated, so `m` is additive on each of those sequences. -/ rw [← tsum_even_add_odd ennreal.summable ennreal.summable, ennreal.add_ne_top], suffices : ∀ a, (∑' (k : ℕ), μ (S (2 * k + 1 + a) \ S (2 * k + a))) ≠ ∞, from ⟨by simpa using this 0, by simpa using this 1⟩, refine λ r, ne_top_of_le_ne_top htop _, rw [← Union_S, ennreal.tsum_eq_supr_nat, supr_le_iff], intro n, rw [← hm.finset_Union_of_pairwise_separated], { exact μ.mono (Union_subset $ λ i, Union_subset $ λ hi x hx, mem_Union.2 ⟨_, hx.1⟩) }, suffices : ∀ i j, i < j → is_metric_separated (S (2 * i + 1 + r)) (s \ S (2 * j + r)), from λ i _ j _ hij, hij.lt_or_lt.elim (λ h, (this i j h).mono (inter_subset_left _ _) (λ x hx, ⟨hx.1.1, hx.2⟩)) (λ h, (this j i h).symm.mono (λ x hx, ⟨hx.1.1, hx.2⟩) (inter_subset_left _ _)), intros i j hj, have A : ((↑(2 * j + r))⁻¹ : ℝ≥0∞) < (↑(2 * i + 1 + r))⁻¹, by { rw [ennreal.inv_lt_inv, nat.cast_lt], linarith }, refine ⟨(↑(2 * i + 1 + r))⁻¹ - (↑(2 * j + r))⁻¹, by simpa using A, λ x hx y hy, _⟩, have : inf_edist y t < (↑(2 * j + r))⁻¹, from not_le.1 (λ hle, hy.2 ⟨hy.1, hle⟩), rcases inf_edist_lt_iff.mp this with ⟨z, hzt, hyz⟩, have hxz : (↑(2 * i + 1 + r))⁻¹ ≤ edist x z, from le_inf_edist.1 hx.2 _ hzt, apply ennreal.le_of_add_le_add_right hyz.ne_top, refine le_trans _ (edist_triangle _ _ _), refine (add_le_add le_rfl hyz.le).trans (eq.trans_le _ hxz), rw [tsub_add_cancel_of_le A.le] end lemma le_caratheodory [measurable_space X] [borel_space X] (hm : is_metric μ) : ‹measurable_space X› ≤ μ.caratheodory := by { rw @borel_space.measurable_eq X _ _, exact hm.borel_le_caratheodory } end is_metric /-! ### Constructors of metric outer measures In this section we provide constructors `measure_theory.outer_measure.mk_metric'` and `measure_theory.outer_measure.mk_metric` and prove that these outer measures are metric outer measures. We also prove basic lemmas about `map`/`comap` of these measures. -/ /-- Auxiliary definition for `outer_measure.mk_metric'`: given a function on sets `m : set X → ℝ≥0∞`, returns the maximal outer measure `μ` such that `μ s ≤ m s` for any set `s` of diameter at most `r`.-/ def mk_metric'.pre (m : set X → ℝ≥0∞) (r : ℝ≥0∞) : outer_measure X := bounded_by $ extend (λ s (hs : diam s ≤ r), m s) /-- Given a function `m : set X → ℝ≥0∞`, `mk_metric' m` is the supremum of `mk_metric'.pre m r` over `r > 0`. Equivalently, it is the limit of `mk_metric'.pre m r` as `r` tends to zero from the right. -/ def mk_metric' (m : set X → ℝ≥0∞) : outer_measure X := ⨆ r > 0, mk_metric'.pre m r /-- Given a function `m : ℝ≥0∞ → ℝ≥0∞` and `r > 0`, let `μ r` be the maximal outer measure such that `μ s ≤ m (emetric.diam s)` whenever `emetric.diam s < r`. Then `mk_metric m = ⨆ r > 0, μ r`. -/ def mk_metric (m : ℝ≥0∞ → ℝ≥0∞) : outer_measure X := mk_metric' (λ s, m (diam s)) namespace mk_metric' variables {m : set X → ℝ≥0∞} {r : ℝ≥0∞} {μ : outer_measure X} {s : set X} lemma le_pre : μ ≤ pre m r ↔ ∀ s : set X, diam s ≤ r → μ s ≤ m s := by simp only [pre, le_bounded_by, extend, le_infi_iff] lemma pre_le (hs : diam s ≤ r) : pre m r s ≤ m s := (bounded_by_le _).trans $ infi_le _ hs lemma mono_pre (m : set X → ℝ≥0∞) {r r' : ℝ≥0∞} (h : r ≤ r') : pre m r' ≤ pre m r := le_pre.2 $ λ s hs, pre_le (hs.trans h) lemma mono_pre_nat (m : set X → ℝ≥0∞) : monotone (λ k : ℕ, pre m k⁻¹) := λ k l h, le_pre.2 $ λ s hs, pre_le (hs.trans $ by simpa) lemma tendsto_pre (m : set X → ℝ≥0∞) (s : set X) : tendsto (λ r, pre m r s) (𝓝[>] 0) (𝓝 $ mk_metric' m s) := begin rw [← map_coe_Ioi_at_bot, tendsto_map'_iff], simp only [mk_metric', outer_measure.supr_apply, supr_subtype'], exact tendsto_at_bot_supr (λ r r' hr, mono_pre _ hr _) end lemma tendsto_pre_nat (m : set X → ℝ≥0∞) (s : set X) : tendsto (λ n : ℕ, pre m n⁻¹ s) at_top (𝓝 $ mk_metric' m s) := begin refine (tendsto_pre m s).comp (tendsto_inf.2 ⟨ennreal.tendsto_inv_nat_nhds_zero, _⟩), refine tendsto_principal.2 (eventually_of_forall $ λ n, _), simp end lemma eq_supr_nat (m : set X → ℝ≥0∞) : mk_metric' m = ⨆ n : ℕ, mk_metric'.pre m n⁻¹ := begin ext1 s, rw supr_apply, refine tendsto_nhds_unique (mk_metric'.tendsto_pre_nat m s) (tendsto_at_top_supr $ λ k l hkl, mk_metric'.mono_pre_nat m hkl s) end /-- `measure_theory.outer_measure.mk_metric'.pre m r` is a trimmed measure provided that `m (closure s) = m s` for any set `s`. -/ lemma trim_pre [measurable_space X] [opens_measurable_space X] (m : set X → ℝ≥0∞) (hcl : ∀ s, m (closure s) = m s) (r : ℝ≥0∞) : (pre m r).trim = pre m r := begin refine le_antisymm (le_pre.2 $ λ s hs, _) (le_trim _), rw trim_eq_infi, refine (infi_le_of_le (closure s) $ infi_le_of_le subset_closure $ infi_le_of_le measurable_set_closure ((pre_le _).trans_eq (hcl _))), rwa diam_closure end end mk_metric' /-- An outer measure constructed using `outer_measure.mk_metric'` is a metric outer measure. -/ lemma mk_metric'_is_metric (m : set X → ℝ≥0∞) : (mk_metric' m).is_metric := begin rintros s t ⟨r, r0, hr⟩, refine tendsto_nhds_unique_of_eventually_eq (mk_metric'.tendsto_pre _ _) ((mk_metric'.tendsto_pre _ _).add (mk_metric'.tendsto_pre _ _)) _, rw [← pos_iff_ne_zero] at r0, filter_upwards [Ioo_mem_nhds_within_Ioi ⟨le_rfl, r0⟩], rintro ε ⟨ε0, εr⟩, refine bounded_by_union_of_top_of_nonempty_inter _, rintro u ⟨x, hxs, hxu⟩ ⟨y, hyt, hyu⟩, have : ε < diam u, from εr.trans_le ((hr x hxs y hyt).trans $ edist_le_diam_of_mem hxu hyu), exact infi_eq_top.2 (λ h, (this.not_le h).elim) end /-- If `c ∉ {0, ∞}` and `m₁ d ≤ c * m₂ d` for `d < ε` for some `ε > 0` (we use `≤ᶠ[𝓝[≥] 0]` to state this), then `mk_metric m₁ hm₁ ≤ c • mk_metric m₂ hm₂`. -/ lemma mk_metric_mono_smul {m₁ m₂ : ℝ≥0∞ → ℝ≥0∞} {c : ℝ≥0∞} (hc : c ≠ ∞) (h0 : c ≠ 0) (hle : m₁ ≤ᶠ[𝓝[≥] 0] c • m₂) : (mk_metric m₁ : outer_measure X) ≤ c • mk_metric m₂ := begin classical, rcases (mem_nhds_within_Ici_iff_exists_Ico_subset' zero_lt_one).1 hle with ⟨r, hr0, hr⟩, refine λ s, le_of_tendsto_of_tendsto (mk_metric'.tendsto_pre _ s) (ennreal.tendsto.const_mul (mk_metric'.tendsto_pre _ s) (or.inr hc)) (mem_of_superset (Ioo_mem_nhds_within_Ioi ⟨le_rfl, hr0⟩) (λ r' hr', _)), simp only [mem_set_of_eq, mk_metric'.pre, ring_hom.id_apply], rw [←smul_eq_mul, ← smul_apply, smul_bounded_by hc], refine le_bounded_by.2 (λ t, (bounded_by_le _).trans _) _, simp only [smul_eq_mul, pi.smul_apply, extend, infi_eq_if], split_ifs with ht ht, { apply hr, exact ⟨zero_le _, ht.trans_lt hr'.2⟩ }, { simp [h0] } end @[simp] lemma mk_metric_top : (mk_metric (λ _, ∞ : ℝ≥0∞ → ℝ≥0∞) : outer_measure X) = ⊤ := begin simp_rw [mk_metric, mk_metric', mk_metric'.pre, extend_top, bounded_by_top, eq_top_iff], rw le_supr_iff, intros b hb, simpa using hb ⊤, end /-- If `m₁ d ≤ m₂ d` for `d < ε` for some `ε > 0` (we use `≤ᶠ[𝓝[≥] 0]` to state this), then `mk_metric m₁ hm₁ ≤ mk_metric m₂ hm₂`-/ lemma mk_metric_mono {m₁ m₂ : ℝ≥0∞ → ℝ≥0∞} (hle : m₁ ≤ᶠ[𝓝[≥] 0] m₂) : (mk_metric m₁ : outer_measure X) ≤ mk_metric m₂ := by { convert mk_metric_mono_smul ennreal.one_ne_top one_ne_zero _; simp * } lemma isometry_comap_mk_metric (m : ℝ≥0∞ → ℝ≥0∞) {f : X → Y} (hf : isometry f) (H : monotone m ∨ surjective f) : comap f (mk_metric m) = mk_metric m := begin simp only [mk_metric, mk_metric', mk_metric'.pre, induced_outer_measure, comap_supr], refine surjective_id.supr_congr id (λ ε, surjective_id.supr_congr id $ λ hε, _), rw comap_bounded_by _ (H.imp (λ h_mono, _) id), { congr' with s : 1, apply extend_congr, { simp [hf.ediam_image] }, { intros, simp [hf.injective.subsingleton_image_iff, hf.ediam_image] } }, { assume s t hst, simp only [extend, le_infi_iff], assume ht, apply le_trans _ (h_mono (diam_mono hst)), simp only [(diam_mono hst).trans ht, le_refl, cinfi_pos] } end lemma isometry_map_mk_metric (m : ℝ≥0∞ → ℝ≥0∞) {f : X → Y} (hf : isometry f) (H : monotone m ∨ surjective f) : map f (mk_metric m) = restrict (range f) (mk_metric m) := by rw [← isometry_comap_mk_metric _ hf H, map_comap] lemma isometry_equiv_comap_mk_metric (m : ℝ≥0∞ → ℝ≥0∞) (f : X ≃ᵢ Y) : comap f (mk_metric m) = mk_metric m := isometry_comap_mk_metric _ f.isometry (or.inr f.surjective) lemma isometry_equiv_map_mk_metric (m : ℝ≥0∞ → ℝ≥0∞) (f : X ≃ᵢ Y) : map f (mk_metric m) = mk_metric m := by rw [← isometry_equiv_comap_mk_metric _ f, map_comap_of_surjective f.surjective] lemma trim_mk_metric [measurable_space X] [borel_space X] (m : ℝ≥0∞ → ℝ≥0∞) : (mk_metric m : outer_measure X).trim = mk_metric m := begin simp only [mk_metric, mk_metric'.eq_supr_nat, trim_supr], congr' 1 with n : 1, refine mk_metric'.trim_pre _ (λ s, _) _, simp end lemma le_mk_metric (m : ℝ≥0∞ → ℝ≥0∞) (μ : outer_measure X) (r : ℝ≥0∞) (h0 : 0 < r) (hr : ∀ s, diam s ≤ r → μ s ≤ m (diam s)) : μ ≤ mk_metric m := le_supr₂_of_le r h0 $ mk_metric'.le_pre.2 $ λ s hs, hr _ hs end outer_measure /-! ### Metric measures In this section we use `measure_theory.outer_measure.to_measure` and theorems about `measure_theory.outer_measure.mk_metric'`/`measure_theory.outer_measure.mk_metric` to define `measure_theory.measure.mk_metric'`/`measure_theory.measure.mk_metric`. We also restate some lemmas about metric outer measures for metric measures. -/ namespace measure variables [measurable_space X] [borel_space X] /-- Given a function `m : set X → ℝ≥0∞`, `mk_metric' m` is the supremum of `μ r` over `r > 0`, where `μ r` is the maximal outer measure `μ` such that `μ s ≤ m s` for all `s`. While each `μ r` is an *outer* measure, the supremum is a measure. -/ def mk_metric' (m : set X → ℝ≥0∞) : measure X := (outer_measure.mk_metric' m).to_measure (outer_measure.mk_metric'_is_metric _).le_caratheodory /-- Given a function `m : ℝ≥0∞ → ℝ≥0∞`, `mk_metric m` is the supremum of `μ r` over `r > 0`, where `μ r` is the maximal outer measure `μ` such that `μ s ≤ m s` for all sets `s` that contain at least two points. While each `mk_metric'.pre` is an *outer* measure, the supremum is a measure. -/ def mk_metric (m : ℝ≥0∞ → ℝ≥0∞) : measure X := (outer_measure.mk_metric m).to_measure (outer_measure.mk_metric'_is_metric _).le_caratheodory @[simp] lemma mk_metric'_to_outer_measure (m : set X → ℝ≥0∞) : (mk_metric' m).to_outer_measure = (outer_measure.mk_metric' m).trim := rfl @[simp] lemma mk_metric_to_outer_measure (m : ℝ≥0∞ → ℝ≥0∞) : (mk_metric m : measure X).to_outer_measure = outer_measure.mk_metric m := outer_measure.trim_mk_metric m end measure lemma outer_measure.coe_mk_metric [measurable_space X] [borel_space X] (m : ℝ≥0∞ → ℝ≥0∞) : ⇑(outer_measure.mk_metric m : outer_measure X) = measure.mk_metric m := by rw [← measure.mk_metric_to_outer_measure, coe_to_outer_measure] namespace measure variables [measurable_space X] [borel_space X] /-- If `c ∉ {0, ∞}` and `m₁ d ≤ c * m₂ d` for `d < ε` for some `ε > 0` (we use `≤ᶠ[𝓝[≥] 0]` to state this), then `mk_metric m₁ hm₁ ≤ c • mk_metric m₂ hm₂`. -/ lemma mk_metric_mono_smul {m₁ m₂ : ℝ≥0∞ → ℝ≥0∞} {c : ℝ≥0∞} (hc : c ≠ ∞) (h0 : c ≠ 0) (hle : m₁ ≤ᶠ[𝓝[≥] 0] c • m₂) : (mk_metric m₁ : measure X) ≤ c • mk_metric m₂ := begin intros s hs, rw [← outer_measure.coe_mk_metric, coe_smul, ← outer_measure.coe_mk_metric], exact outer_measure.mk_metric_mono_smul hc h0 hle s end @[simp] lemma mk_metric_top : (mk_metric (λ _, ∞ : ℝ≥0∞ → ℝ≥0∞) : measure X) = ⊤ := begin apply to_outer_measure_injective, rw [mk_metric_to_outer_measure, outer_measure.mk_metric_top, to_outer_measure_top], end /-- If `m₁ d ≤ m₂ d` for `d < ε` for some `ε > 0` (we use `≤ᶠ[𝓝[≥] 0]` to state this), then `mk_metric m₁ hm₁ ≤ mk_metric m₂ hm₂`-/ lemma mk_metric_mono {m₁ m₂ : ℝ≥0∞ → ℝ≥0∞} (hle : m₁ ≤ᶠ[𝓝[≥] 0] m₂) : (mk_metric m₁ : measure X) ≤ mk_metric m₂ := by { convert mk_metric_mono_smul ennreal.one_ne_top one_ne_zero _; simp * } /-- A formula for `measure_theory.measure.mk_metric`. -/ lemma mk_metric_apply (m : ℝ≥0∞ → ℝ≥0∞) (s : set X) : mk_metric m s = ⨆ (r : ℝ≥0∞) (hr : 0 < r), ⨅ (t : ℕ → set X) (h : s ⊆ Union t) (h' : ∀ n, diam (t n) ≤ r), ∑' n, ⨆ (h : (t n).nonempty), m (diam (t n)) := begin -- We mostly unfold the definitions but we need to switch the order of `∑'` and `⨅` classical, simp only [← outer_measure.coe_mk_metric, outer_measure.mk_metric, outer_measure.mk_metric', outer_measure.supr_apply, outer_measure.mk_metric'.pre, outer_measure.bounded_by_apply, extend], refine surjective_id.supr_congr (λ r, r) (λ r, supr_congr_Prop iff.rfl $ λ hr, surjective_id.infi_congr _ $ λ t, infi_congr_Prop iff.rfl $ λ ht, _), dsimp, by_cases htr : ∀ n, diam (t n) ≤ r, { rw [infi_eq_if, if_pos htr], congr' 1 with n : 1, simp only [infi_eq_if, htr n, id, if_true, supr_and'] }, { rw [infi_eq_if, if_neg htr], push_neg at htr, rcases htr with ⟨n, hn⟩, refine ennreal.tsum_eq_top_of_eq_top ⟨n, _⟩, rw [supr_eq_if, if_pos, infi_eq_if, if_neg], exact hn.not_le, rcases diam_pos_iff.1 ((zero_le r).trans_lt hn) with ⟨x, hx, -⟩, exact ⟨x, hx⟩ } end lemma le_mk_metric (m : ℝ≥0∞ → ℝ≥0∞) (μ : measure X) (ε : ℝ≥0∞) (h₀ : 0 < ε) (h : ∀ s : set X, diam s ≤ ε → μ s ≤ m (diam s)) : μ ≤ mk_metric m := begin rw [← to_outer_measure_le, mk_metric_to_outer_measure], exact outer_measure.le_mk_metric m μ.to_outer_measure ε h₀ h end /-- To bound the Hausdorff measure (or, more generally, for a measure defined using `measure_theory.measure.mk_metric`) of a set, one may use coverings with maximum diameter tending to `0`, indexed by any sequence of countable types. -/ lemma mk_metric_le_liminf_tsum {β : Type*} {ι : β → Type*} [∀ n, countable (ι n)] (s : set X) {l : filter β} (r : β → ℝ≥0∞) (hr : tendsto r l (𝓝 0)) (t : Π (n : β), ι n → set X) (ht : ∀ᶠ n in l, ∀ i, diam (t n i) ≤ r n) (hst : ∀ᶠ n in l, s ⊆ ⋃ i, t n i) (m : ℝ≥0∞ → ℝ≥0∞) : mk_metric m s ≤ liminf (λ n, ∑' i, m (diam (t n i))) l := begin haveI : Π n, encodable (ι n) := λ n, encodable.of_countable _, simp only [mk_metric_apply], refine supr₂_le (λ ε hε, _), refine le_of_forall_le_of_dense (λ c hc, _), rcases ((frequently_lt_of_liminf_lt (by apply_auto_param) hc).and_eventually ((hr.eventually (gt_mem_nhds hε)).and (ht.and hst))).exists with ⟨n, hn, hrn, htn, hstn⟩, set u : ℕ → set X := λ j, ⋃ b ∈ decode₂ (ι n) j, t n b, refine infi₂_le_of_le u (by rwa Union_decode₂) _, refine infi_le_of_le (λ j, _) _, { rw emetric.diam_Union_mem_option, exact supr₂_le (λ _ _, (htn _).trans hrn.le) }, { calc (∑' (j : ℕ), ⨆ (h : (u j).nonempty), m (diam (u j))) = _ : tsum_Union_decode₂ (λ t : set X, ⨆ (h : t.nonempty), m (diam t)) (by simp) _ ... ≤ ∑' (i : ι n), m (diam (t n i)) : ennreal.tsum_le_tsum (λ b, supr_le $ λ htb, le_rfl) ... ≤ c : hn.le } end /-- To bound the Hausdorff measure (or, more generally, for a measure defined using `measure_theory.measure.mk_metric`) of a set, one may use coverings with maximum diameter tending to `0`, indexed by any sequence of finite types. -/ lemma mk_metric_le_liminf_sum {β : Type*} {ι : β → Type*} [hι : ∀ n, fintype (ι n)] (s : set X) {l : filter β} (r : β → ℝ≥0∞) (hr : tendsto r l (𝓝 0)) (t : Π (n : β), ι n → set X) (ht : ∀ᶠ n in l, ∀ i, diam (t n i) ≤ r n) (hst : ∀ᶠ n in l, s ⊆ ⋃ i, t n i) (m : ℝ≥0∞ → ℝ≥0∞) : mk_metric m s ≤ liminf (λ n, ∑ i, m (diam (t n i))) l := by simpa only [tsum_fintype] using mk_metric_le_liminf_tsum s r hr t ht hst m /-! ### Hausdorff measure and Hausdorff dimension -/ /-- Hausdorff measure on an (e)metric space. -/ def hausdorff_measure (d : ℝ) : measure X := mk_metric (λ r, r ^ d) localized "notation (name := hausdorff_measure) `μH[` d `]` := measure_theory.measure.hausdorff_measure d" in measure_theory lemma le_hausdorff_measure (d : ℝ) (μ : measure X) (ε : ℝ≥0∞) (h₀ : 0 < ε) (h : ∀ s : set X, diam s ≤ ε → μ s ≤ diam s ^ d) : μ ≤ μH[d] := le_mk_metric _ μ ε h₀ h /-- A formula for `μH[d] s`. -/ lemma hausdorff_measure_apply (d : ℝ) (s : set X) : μH[d] s = ⨆ (r : ℝ≥0∞) (hr : 0 < r), ⨅ (t : ℕ → set X) (hts : s ⊆ ⋃ n, t n) (ht : ∀ n, diam (t n) ≤ r), ∑' n, ⨆ (h : (t n).nonempty), (diam (t n)) ^ d := mk_metric_apply _ _ /-- To bound the Hausdorff measure of a set, one may use coverings with maximum diameter tending to `0`, indexed by any sequence of countable types. -/ lemma hausdorff_measure_le_liminf_tsum {β : Type*} {ι : β → Type*} [hι : ∀ n, countable (ι n)] (d : ℝ) (s : set X) {l : filter β} (r : β → ℝ≥0∞) (hr : tendsto r l (𝓝 0)) (t : Π (n : β), ι n → set X) (ht : ∀ᶠ n in l, ∀ i, diam (t n i) ≤ r n) (hst : ∀ᶠ n in l, s ⊆ ⋃ i, t n i) : μH[d] s ≤ liminf (λ n, ∑' i, diam (t n i) ^ d) l := mk_metric_le_liminf_tsum s r hr t ht hst _ /-- To bound the Hausdorff measure of a set, one may use coverings with maximum diameter tending to `0`, indexed by any sequence of finite types. -/ lemma hausdorff_measure_le_liminf_sum {β : Type*} {ι : β → Type*} [hι : ∀ n, fintype (ι n)] (d : ℝ) (s : set X) {l : filter β} (r : β → ℝ≥0∞) (hr : tendsto r l (𝓝 0)) (t : Π (n : β), ι n → set X) (ht : ∀ᶠ n in l, ∀ i, diam (t n i) ≤ r n) (hst : ∀ᶠ n in l, s ⊆ ⋃ i, t n i) : μH[d] s ≤ liminf (λ n, ∑ i, diam (t n i) ^ d) l := mk_metric_le_liminf_sum s r hr t ht hst _ /-- If `d₁ < d₂`, then for any set `s` we have either `μH[d₂] s = 0`, or `μH[d₁] s = ∞`. -/ lemma hausdorff_measure_zero_or_top {d₁ d₂ : ℝ} (h : d₁ < d₂) (s : set X) : μH[d₂] s = 0 ∨ μH[d₁] s = ∞ := begin by_contra' H, suffices : ∀ (c : ℝ≥0), c ≠ 0 → μH[d₂] s ≤ c * μH[d₁] s, { rcases ennreal.exists_nnreal_pos_mul_lt H.2 H.1 with ⟨c, hc0, hc⟩, exact hc.not_le (this c (pos_iff_ne_zero.1 hc0)) }, intros c hc, refine le_iff'.1 (mk_metric_mono_smul ennreal.coe_ne_top (by exact_mod_cast hc) _) s, have : 0 < (c ^ (d₂ - d₁)⁻¹ : ℝ≥0∞), { rw [ennreal.coe_rpow_of_ne_zero hc, pos_iff_ne_zero, ne.def, ennreal.coe_eq_zero, nnreal.rpow_eq_zero_iff], exact mt and.left hc }, filter_upwards [Ico_mem_nhds_within_Ici ⟨le_rfl, this⟩], rintro r ⟨hr₀, hrc⟩, lift r to ℝ≥0 using ne_top_of_lt hrc, rw [pi.smul_apply, smul_eq_mul, ← ennreal.div_le_iff_le_mul (or.inr ennreal.coe_ne_top) (or.inr $ mt ennreal.coe_eq_zero.1 hc)], rcases eq_or_ne r 0 with rfl|hr₀, { rcases lt_or_le 0 d₂ with h₂|h₂, { simp only [h₂, ennreal.zero_rpow_of_pos, zero_le, ennreal.zero_div, ennreal.coe_zero] }, { simp only [h.trans_le h₂, ennreal.div_top, zero_le, ennreal.zero_rpow_of_neg, ennreal.coe_zero] } }, { have : (r : ℝ≥0∞) ≠ 0, by simpa only [ennreal.coe_eq_zero, ne.def] using hr₀, rw [← ennreal.rpow_sub _ _ this ennreal.coe_ne_top], refine (ennreal.rpow_lt_rpow hrc (sub_pos.2 h)).le.trans _, rw [← ennreal.rpow_mul, inv_mul_cancel (sub_pos.2 h).ne', ennreal.rpow_one], exact le_rfl } end /-- Hausdorff measure `μH[d] s` is monotone in `d`. -/ lemma hausdorff_measure_mono {d₁ d₂ : ℝ} (h : d₁ ≤ d₂) (s : set X) : μH[d₂] s ≤ μH[d₁] s := begin rcases h.eq_or_lt with rfl|h, { exact le_rfl }, cases hausdorff_measure_zero_or_top h s with hs hs, { rw hs, exact zero_le _ }, { rw hs, exact le_top } end variables (X) lemma no_atoms_hausdorff {d : ℝ} (hd : 0 < d) : has_no_atoms (hausdorff_measure d : measure X) := begin refine ⟨λ x, _⟩, rw [← nonpos_iff_eq_zero, hausdorff_measure_apply], refine supr₂_le (λ ε ε0, infi₂_le_of_le (λ n, {x}) _ $ infi_le_of_le (λ n, _) _), { exact subset_Union (λ n, {x} : ℕ → set X) 0 }, { simp only [emetric.diam_singleton, zero_le] }, { simp [hd] } end variables {X} @[simp] lemma hausdorff_measure_zero_singleton (x : X) : μH[0] ({x} : set X) = 1 := begin apply le_antisymm, { let r : ℕ → ℝ≥0∞ := λ _, 0, let t : ℕ → unit → set X := λ n _, {x}, have ht : ∀ᶠ n in at_top, ∀ i, diam (t n i) ≤ r n, by simp only [implies_true_iff, eq_self_iff_true, diam_singleton, eventually_at_top, nonpos_iff_eq_zero, exists_const], simpa [liminf_const] using hausdorff_measure_le_liminf_sum 0 {x} r tendsto_const_nhds t ht }, { rw hausdorff_measure_apply, suffices : (1 : ℝ≥0∞) ≤ ⨅ (t : ℕ → set X) (hts : {x} ⊆ ⋃ n, t n) (ht : ∀ n, diam (t n) ≤ 1), ∑' n, ⨆ (h : (t n).nonempty), (diam (t n)) ^ (0 : ℝ), { apply le_trans this _, convert le_supr₂ (1 : ℝ≥0∞) zero_lt_one, refl }, simp only [ennreal.rpow_zero, le_infi_iff], assume t hst h't, rcases mem_Union.1 (hst (mem_singleton x)) with ⟨m, hm⟩, have A : (t m).nonempty := ⟨x, hm⟩, calc (1 : ℝ≥0∞) = ⨆ (h : (t m).nonempty), 1 : by simp only [A, csupr_pos] ... ≤ ∑' n, ⨆ (h : (t n).nonempty), 1 : ennreal.le_tsum _ } end lemma one_le_hausdorff_measure_zero_of_nonempty {s : set X} (h : s.nonempty) : 1 ≤ μH[0] s := begin rcases h with ⟨x, hx⟩, calc (1 : ℝ≥0∞) = μH[0] ({x} : set X) : (hausdorff_measure_zero_singleton x).symm ... ≤ μH[0] s : measure_mono (singleton_subset_iff.2 hx) end lemma hausdorff_measure_le_one_of_subsingleton {s : set X} (hs : s.subsingleton) {d : ℝ} (hd : 0 ≤ d) : μH[d] s ≤ 1 := begin rcases eq_empty_or_nonempty s with rfl|⟨x, hx⟩, { simp only [measure_empty, zero_le] }, { rw (subsingleton_iff_singleton hx).1 hs, rcases eq_or_lt_of_le hd with rfl|dpos, { simp only [le_refl, hausdorff_measure_zero_singleton] }, { haveI := no_atoms_hausdorff X dpos, simp only [zero_le, measure_singleton] } } end end measure open_locale measure_theory open measure /-! ### Hausdorff measure and Lebesgue measure -/ /-- In the space `ι → ℝ`, Hausdorff measure coincides exactly with Lebesgue measure. -/ @[simp] theorem hausdorff_measure_pi_real {ι : Type*} [fintype ι] : (μH[fintype.card ι] : measure (ι → ℝ)) = volume := begin classical, -- it suffices to check that the two measures coincide on products of rational intervals refine (pi_eq_generate_from (λ i, real.borel_eq_generate_from_Ioo_rat.symm) (λ i, real.is_pi_system_Ioo_rat) (λ i, real.finite_spanning_sets_in_Ioo_rat _) _).symm, simp only [mem_Union, mem_singleton_iff], -- fix such a product `s` of rational intervals, of the form `Π (a i, b i)`. intros s hs, choose a b H using hs, obtain rfl : s = λ i, Ioo (a i) (b i), from funext (λ i, (H i).2), replace H := λ i, (H i).1, apply le_antisymm _, -- first check that `volume s ≤ μH s` { have Hle : volume ≤ (μH[fintype.card ι] : measure (ι → ℝ)), { refine le_hausdorff_measure _ _ ∞ ennreal.coe_lt_top (λ s _, _), rw [ennreal.rpow_nat_cast], exact real.volume_pi_le_diam_pow s }, rw [← volume_pi_pi (λ i, Ioo (a i : ℝ) (b i))], exact measure.le_iff'.1 Hle _ }, /- For the other inequality `μH s ≤ volume s`, we use a covering of `s` by sets of small diameter `1/n`, namely cubes with left-most point of the form `a i + f i / n` with `f i` ranging between `0` and `⌈(b i - a i) * n⌉`. Their number is asymptotic to `n^d * Π (b i - a i)`. -/ have I : ∀ i, 0 ≤ (b i : ℝ) - a i := λ i, by simpa only [sub_nonneg, rat.cast_le] using (H i).le, let γ := λ (n : ℕ), (Π (i : ι), fin ⌈((b i : ℝ) - a i) * n⌉₊), let t : Π (n : ℕ), γ n → set (ι → ℝ) := λ n f, set.pi univ (λ i, Icc (a i + f i / n) (a i + (f i + 1) / n)), have A : tendsto (λ (n : ℕ), 1/(n : ℝ≥0∞)) at_top (𝓝 0), by simp only [one_div, ennreal.tendsto_inv_nat_nhds_zero], have B : ∀ᶠ n in at_top, ∀ (i : γ n), diam (t n i) ≤ 1 / n, { apply eventually_at_top.2 ⟨1, λ n hn, _⟩, assume f, apply diam_pi_le_of_le (λ b, _), simp only [real.ediam_Icc, add_div, ennreal.of_real_div_of_pos (nat.cast_pos.mpr hn), le_refl, add_sub_add_left_eq_sub, add_sub_cancel', ennreal.of_real_one, ennreal.of_real_coe_nat] }, have C : ∀ᶠ n in at_top, set.pi univ (λ (i : ι), Ioo (a i : ℝ) (b i)) ⊆ ⋃ (i : γ n), t n i, { apply eventually_at_top.2 ⟨1, λ n hn, _⟩, have npos : (0 : ℝ) < n := nat.cast_pos.2 hn, assume x hx, simp only [mem_Ioo, mem_univ_pi] at hx, simp only [mem_Union, mem_Ioo, mem_univ_pi, coe_coe], let f : γ n := λ i, ⟨⌊(x i - a i) * n⌋₊, begin apply nat.floor_lt_ceil_of_lt_of_pos, { refine (mul_lt_mul_right npos).2 _, simp only [(hx i).right, sub_lt_sub_iff_right] }, { refine mul_pos _ npos, simpa only [rat.cast_lt, sub_pos] using H i } end⟩, refine ⟨f, λ i, ⟨_, _⟩⟩, { calc (a i : ℝ) + ⌊(x i - a i) * n⌋₊ / n ≤ (a i : ℝ) + ((x i - a i) * n) / n : begin refine add_le_add le_rfl ((div_le_div_right npos).2 _), exact nat.floor_le (mul_nonneg (sub_nonneg.2 (hx i).1.le) npos.le), end ... = x i : by field_simp [npos.ne'] }, { calc x i = (a i : ℝ) + ((x i - a i) * n) / n : by field_simp [npos.ne'] ... ≤ (a i : ℝ) + (⌊(x i - a i) * n⌋₊ + 1) / n : add_le_add le_rfl ((div_le_div_right npos).2 (nat.lt_floor_add_one _).le) } }, calc μH[fintype.card ι] (set.pi univ (λ (i : ι), Ioo (a i : ℝ) (b i))) ≤ liminf (λ (n : ℕ), ∑ (i : γ n), diam (t n i) ^ ↑(fintype.card ι)) at_top : hausdorff_measure_le_liminf_sum _ (set.pi univ (λ i, Ioo (a i : ℝ) (b i))) (λ (n : ℕ), 1/(n : ℝ≥0∞)) A t B C ... ≤ liminf (λ (n : ℕ), ∑ (i : γ n), (1/n) ^ (fintype.card ι)) at_top : begin refine liminf_le_liminf _ (by is_bounded_default), filter_upwards [B] with _ hn, apply finset.sum_le_sum (λ i _, _), rw ennreal.rpow_nat_cast, exact pow_le_pow_of_le_left' (hn i) _, end ... = liminf (λ (n : ℕ), ∏ (i : ι), (⌈((b i : ℝ) - a i) * n⌉₊ : ℝ≥0∞) / n) at_top : begin simp only [finset.card_univ, nat.cast_prod, one_mul, fintype.card_fin, finset.sum_const, nsmul_eq_mul, fintype.card_pi, div_eq_mul_inv, finset.prod_mul_distrib, finset.prod_const] end ... = ∏ (i : ι), volume (Ioo (a i : ℝ) (b i)) : begin simp only [real.volume_Ioo], apply tendsto.liminf_eq, refine ennreal.tendsto_finset_prod_of_ne_top _ (λ i hi, _) (λ i hi, _), { apply tendsto.congr' _ ((ennreal.continuous_of_real.tendsto _).comp ((tendsto_nat_ceil_mul_div_at_top (I i)).comp tendsto_coe_nat_at_top_at_top)), apply eventually_at_top.2 ⟨1, λ n hn, _⟩, simp only [ennreal.of_real_div_of_pos (nat.cast_pos.mpr hn), comp_app, ennreal.of_real_coe_nat] }, { simp only [ennreal.of_real_ne_top, ne.def, not_false_iff] } end end end measure_theory /-! ### Hausdorff measure, Hausdorff dimension, and Hölder or Lipschitz continuous maps -/ open_locale measure_theory open measure_theory measure_theory.measure variables [measurable_space X] [borel_space X] [measurable_space Y] [borel_space Y] namespace holder_on_with variables {C r : ℝ≥0} {f : X → Y} {s t : set X} /-- If `f : X → Y` is Hölder continuous on `s` with a positive exponent `r`, then `μH[d] (f '' s) ≤ C ^ d * μH[r * d] s`. -/ lemma hausdorff_measure_image_le (h : holder_on_with C r f s) (hr : 0 < r) {d : ℝ} (hd : 0 ≤ d) : μH[d] (f '' s) ≤ C ^ d * μH[r * d] s := begin -- We start with the trivial case `C = 0` rcases (zero_le C).eq_or_lt with rfl|hC0, { rcases eq_empty_or_nonempty s with rfl|⟨x, hx⟩, { simp only [measure_empty, nonpos_iff_eq_zero, mul_zero, image_empty] }, have : f '' s = {f x}, { have : (f '' s).subsingleton, by simpa [diam_eq_zero_iff] using h.ediam_image_le, exact (subsingleton_iff_singleton (mem_image_of_mem f hx)).1 this }, rw this, rcases eq_or_lt_of_le hd with rfl|h'd, { simp only [ennreal.rpow_zero, one_mul, mul_zero], rw hausdorff_measure_zero_singleton, exact one_le_hausdorff_measure_zero_of_nonempty ⟨x, hx⟩ }, { haveI := no_atoms_hausdorff Y h'd, simp only [zero_le, measure_singleton] } }, -- Now assume `C ≠ 0` { have hCd0 : (C : ℝ≥0∞) ^ d ≠ 0, by simp [hC0.ne'], have hCd : (C : ℝ≥0∞) ^ d ≠ ∞, by simp [hd], simp only [hausdorff_measure_apply, ennreal.mul_supr, ennreal.mul_infi_of_ne hCd0 hCd, ← ennreal.tsum_mul_left], refine supr_le (λ R, supr_le $ λ hR, _), have : tendsto (λ d : ℝ≥0∞, (C : ℝ≥0∞) * d ^ (r : ℝ)) (𝓝 0) (𝓝 0), from ennreal.tendsto_const_mul_rpow_nhds_zero_of_pos ennreal.coe_ne_top hr, rcases ennreal.nhds_zero_basis_Iic.eventually_iff.1 (this.eventually (gt_mem_nhds hR)) with ⟨δ, δ0, H⟩, refine le_supr₂_of_le δ δ0 (infi₂_mono' $ λ t hst, ⟨λ n, f '' (t n ∩ s), _, infi_mono' $ λ htδ, ⟨λ n, (h.ediam_image_inter_le (t n)).trans (H (htδ n)).le, _⟩⟩), { rw [← image_Union, ← Union_inter], exact image_subset _ (subset_inter hst subset.rfl) }, { apply ennreal.tsum_le_tsum (λ n, _), simp only [supr_le_iff, nonempty_image_iff], assume hft, simp only [nonempty.mono ((t n).inter_subset_left s) hft, csupr_pos], rw [ennreal.rpow_mul, ← ennreal.mul_rpow_of_nonneg _ _ hd], exact ennreal.rpow_le_rpow (h.ediam_image_inter_le _) hd } } end end holder_on_with namespace lipschitz_on_with variables {K : ℝ≥0} {f : X → Y} {s t : set X} /-- If `f : X → Y` is `K`-Lipschitz on `s`, then `μH[d] (f '' s) ≤ K ^ d * μH[d] s`. -/ lemma hausdorff_measure_image_le (h : lipschitz_on_with K f s) {d : ℝ} (hd : 0 ≤ d) : μH[d] (f '' s) ≤ K ^ d * μH[d] s := by simpa only [nnreal.coe_one, one_mul] using h.holder_on_with.hausdorff_measure_image_le zero_lt_one hd end lipschitz_on_with namespace lipschitz_with variables {K : ℝ≥0} {f : X → Y} /-- If `f` is a `K`-Lipschitz map, then it increases the Hausdorff `d`-measures of sets at most by the factor of `K ^ d`.-/ lemma hausdorff_measure_image_le (h : lipschitz_with K f) {d : ℝ} (hd : 0 ≤ d) (s : set X) : μH[d] (f '' s) ≤ K ^ d * μH[d] s := (h.lipschitz_on_with s).hausdorff_measure_image_le hd end lipschitz_with /-! ### Antilipschitz maps do not decrease Hausdorff measures and dimension -/ namespace antilipschitz_with variables {f : X → Y} {K : ℝ≥0} {d : ℝ} lemma hausdorff_measure_preimage_le (hf : antilipschitz_with K f) (hd : 0 ≤ d) (s : set Y) : μH[d] (f ⁻¹' s) ≤ K ^ d * μH[d] s := begin rcases eq_or_ne K 0 with rfl|h0, { rcases eq_empty_or_nonempty (f ⁻¹' s) with hs|⟨x, hx⟩, { simp only [hs, measure_empty, zero_le], }, have : f ⁻¹' s = {x}, { haveI : subsingleton X := hf.subsingleton, have : (f ⁻¹' s).subsingleton, from subsingleton_univ.anti (subset_univ _), exact (subsingleton_iff_singleton hx).1 this }, rw this, rcases eq_or_lt_of_le hd with rfl|h'd, { simp only [ennreal.rpow_zero, one_mul, mul_zero], rw hausdorff_measure_zero_singleton, exact one_le_hausdorff_measure_zero_of_nonempty ⟨f x, hx⟩ }, { haveI := no_atoms_hausdorff X h'd, simp only [zero_le, measure_singleton] } }, have hKd0 : (K : ℝ≥0∞) ^ d ≠ 0, by simp [h0], have hKd : (K : ℝ≥0∞) ^ d ≠ ∞, by simp [hd], simp only [hausdorff_measure_apply, ennreal.mul_supr, ennreal.mul_infi_of_ne hKd0 hKd, ← ennreal.tsum_mul_left], refine supr₂_le (λ ε ε0, _), refine le_supr₂_of_le (ε / K) (by simp [ε0.ne']) _, refine le_infi₂ (λ t hst, le_infi $ λ htε, _), replace hst : f ⁻¹' s ⊆ _ := preimage_mono hst, rw preimage_Union at hst, refine infi₂_le_of_le _ hst (infi_le_of_le (λ n, _) _), { exact (hf.ediam_preimage_le _).trans (ennreal.mul_le_of_le_div' $ htε n) }, { refine ennreal.tsum_le_tsum (λ n, supr_le_iff.2 (λ hft, _)), simp only [nonempty_of_nonempty_preimage hft, csupr_pos], rw [← ennreal.mul_rpow_of_nonneg _ _ hd], exact ennreal.rpow_le_rpow (hf.ediam_preimage_le _) hd } end lemma le_hausdorff_measure_image (hf : antilipschitz_with K f) (hd : 0 ≤ d) (s : set X) : μH[d] s ≤ K ^ d * μH[d] (f '' s) := calc μH[d] s ≤ μH[d] (f ⁻¹' (f '' s)) : measure_mono (subset_preimage_image _ _) ... ≤ K ^ d * μH[d] (f '' s) : hf.hausdorff_measure_preimage_le hd (f '' s) end antilipschitz_with /-! ### Isometries preserve the Hausdorff measure and Hausdorff dimension -/ namespace isometry variables {f : X → Y} {d : ℝ} lemma hausdorff_measure_image (hf : isometry f) (hd : 0 ≤ d ∨ surjective f) (s : set X) : μH[d] (f '' s) = μH[d] s := begin simp only [hausdorff_measure, ← outer_measure.coe_mk_metric, ← outer_measure.comap_apply], rw [outer_measure.isometry_comap_mk_metric _ hf (hd.imp_left _)], exact λ hd x y hxy, ennreal.rpow_le_rpow hxy hd end lemma hausdorff_measure_preimage (hf : isometry f) (hd : 0 ≤ d ∨ surjective f) (s : set Y) : μH[d] (f ⁻¹' s) = μH[d] (s ∩ range f) := by rw [← hf.hausdorff_measure_image hd, image_preimage_eq_inter_range] lemma map_hausdorff_measure (hf : isometry f) (hd : 0 ≤ d ∨ surjective f) : measure.map f μH[d] = (μH[d]).restrict (range f) := begin ext1 s hs, rw [map_apply hf.continuous.measurable hs, restrict_apply hs, hf.hausdorff_measure_preimage hd] end end isometry namespace isometry_equiv @[simp] lemma hausdorff_measure_image (e : X ≃ᵢ Y) (d : ℝ) (s : set X) : μH[d] (e '' s) = μH[d] s := e.isometry.hausdorff_measure_image (or.inr e.surjective) s @[simp] lemma hausdorff_measure_preimage (e : X ≃ᵢ Y) (d : ℝ) (s : set Y) : μH[d] (e ⁻¹' s) = μH[d] s := by rw [← e.image_symm, e.symm.hausdorff_measure_image] end isometry_equiv
c6f040bafacd84a3238a5fbccab12b310d06311b
63abd62053d479eae5abf4951554e1064a4c45b4
/src/category_theory/sites/sieves.lean
44d33c297c3336a52bf8bf53cfe1b0d23a045004
[ "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
13,325
lean
/- Copyright (c) 2020 Bhavik Mehta. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Bhavik Mehta, E. W. Ayers -/ import category_theory.over import category_theory.limits.shapes.finite_limits import category_theory.yoneda import order.complete_lattice import data.set.lattice /-! # Theory of sieves - For an object `X` of a category `C`, a `sieve X` is a set of morphisms to `X` which is closed under left-composition. - The complete lattice structure on sieves is given, as well as the Galois insertion given by downward-closing. - A `sieve X` (functorially) induces a presheaf on `C` together with a monomorphism to the yoneda embedding of `X`. ## Tags sieve, pullback -/ universes v u namespace category_theory variables {C : Type u} [category.{v} C] variables {X Y Z : C} (f : Y ⟶ X) /-- A set of arrows all with codomain `X`. -/ @[derive complete_lattice] def presieve (X : C) := Π ⦃Y⦄, set (Y ⟶ X) namespace presieve instance : inhabited (presieve X) := ⟨⊤⟩ /-- Given a set of arrows `S` all with codomain `X`, and a set of arrows with codomain `Y` for each `f : Y ⟶ X` in `S`, produce a set of arrows with codomain `X`: `{ g ≫ f | (f : Y ⟶ X) ∈ S, (g : Z ⟶ Y) ∈ R f }`. -/ def bind (S : presieve X) (R : Π ⦃Y⦄ ⦃f : Y ⟶ X⦄, S f → presieve Y) : presieve X := λ Z h, ∃ (Y : C) (g : Z ⟶ Y) (f : Y ⟶ X) (H : S f), R H g ∧ g ≫ f = h @[simp] lemma bind_comp {S : presieve X} {R : Π ⦃Y : C⦄ ⦃f : Y ⟶ X⦄, S f → presieve Y} {g : Z ⟶ Y} (h₁ : S f) (h₂ : R h₁ g) : bind S R (g ≫ f) := ⟨_, _, _, h₁, h₂, rfl⟩ /-- The singleton presieve. -/ -- Note we can't make this into `has_singleton` because of the out-param. def singleton : presieve X := λ Z g, ∃ (H : Z = Y), eq_to_hom H ≫ f = g @[simp] lemma singleton_eq_iff_domain (f g : Y ⟶ X) : singleton f g ↔ f = g := begin split, { rintro ⟨_, rfl⟩, apply (category.id_comp _).symm }, { rintro rfl, exact ⟨rfl, category.id_comp _⟩ }, end lemma singleton_self : singleton f f := (singleton_eq_iff_domain _ _).2 rfl end presieve /-- For an object `X` of a category `C`, a `sieve X` is a set of morphisms to `X` which is closed under left-composition. -/ structure sieve {C : Type u} [category.{v} C] (X : C) := (arrows : presieve X) (downward_closed' : ∀ {Y Z f} (hf : arrows f) (g : Z ⟶ Y), arrows (g ≫ f)) namespace sieve instance {X : C} : has_coe_to_fun (sieve X) := ⟨_, sieve.arrows⟩ variables {S R : sieve X} @[simp, priority 100] lemma downward_closed (S : sieve X) {f : Y ⟶ X} (hf : S f) (g : Z ⟶ Y) : S (g ≫ f) := S.downward_closed' hf g lemma arrows_ext : Π {R S : sieve X}, R.arrows = S.arrows → R = S | ⟨Ra, _⟩ ⟨Sa, _⟩ rfl := rfl @[ext] protected lemma ext {R S : sieve X} (h : ∀ ⦃Y⦄ (f : Y ⟶ X), R f ↔ S f) : R = S := arrows_ext $ funext $ λ x, funext $ λ f, propext $ h f protected lemma ext_iff {R S : sieve X} : R = S ↔ (∀ ⦃Y⦄ (f : Y ⟶ X), R f ↔ S f) := ⟨λ h Y f, h ▸ iff.rfl, sieve.ext⟩ open lattice /-- The supremum of a collection of sieves: the union of them all. -/ protected def Sup (𝒮 : set (sieve X)) : (sieve X) := { arrows := λ Y, {f | ∃ S ∈ 𝒮, sieve.arrows S f}, downward_closed' := λ Y Z f, by { rintro ⟨S, hS, hf⟩ g, exact ⟨S, hS, S.downward_closed hf _⟩ } } /-- The infimum of a collection of sieves: the intersection of them all. -/ protected def Inf (𝒮 : set (sieve X)) : (sieve X) := { arrows := λ Y, {f | ∀ S ∈ 𝒮, sieve.arrows S f}, downward_closed' := λ Y Z f hf g S H, S.downward_closed (hf S H) g } /-- The union of two sieves is a sieve. -/ protected def union (S R : sieve X) : sieve X := { arrows := λ Y f, S f ∨ R f, downward_closed' := by { rintros Y Z f (h | h) g; simp [h] } } /-- The intersection of two sieves is a sieve. -/ protected def inter (S R : sieve X) : sieve X := { arrows := λ Y f, S f ∧ R f, downward_closed' := by { rintros Y Z f ⟨h₁, h₂⟩ g, simp [h₁, h₂] } } /-- Sieves on an object `X` form a complete lattice. We generate this directly rather than using the galois insertion for nicer definitional properties. -/ instance : complete_lattice (sieve X) := { le := λ S R, ∀ ⦃Y⦄ (f : Y ⟶ X), S f → R f, le_refl := λ S f q, id, le_trans := λ S₁ S₂ S₃ S₁₂ S₂₃ Y f h, S₂₃ _ (S₁₂ _ h), le_antisymm := λ S R p q, sieve.ext (λ Y f, ⟨p _, q _⟩), top := { arrows := λ _, set.univ, downward_closed' := λ Y Z f g h, ⟨⟩ }, bot := { arrows := λ _, ∅, downward_closed' := λ _ _ _ p _, false.elim p }, sup := sieve.union, inf := sieve.inter, Sup := sieve.Sup, Inf := sieve.Inf, le_Sup := λ 𝒮 S hS Y f hf, ⟨S, hS, hf⟩, Sup_le := λ ℰ S hS Y f, by { rintro ⟨R, hR, hf⟩, apply hS R hR _ hf }, Inf_le := λ _ _ hS _ _ h, h _ hS, le_Inf := λ _ _ hS _ _ hf _ hR, hS _ hR _ hf, le_sup_left := λ _ _ _ _, or.inl, le_sup_right := λ _ _ _ _, or.inr, sup_le := λ _ _ _ a b _ _ hf, hf.elim (a _) (b _), inf_le_left := λ _ _ _ _, and.left, inf_le_right := λ _ _ _ _, and.right, le_inf := λ _ _ _ p q _ _ z, ⟨p _ z, q _ z⟩, le_top := λ _ _ _ _, trivial, bot_le := λ _ _ _, false.elim } /-- The maximal sieve always exists. -/ instance sieve_inhabited : inhabited (sieve X) := ⟨⊤⟩ @[simp] lemma mem_Inf {Ss : set (sieve X)} {Y} (f : Y ⟶ X) : Inf Ss f ↔ ∀ (S : sieve X) (H : S ∈ Ss), S f := iff.rfl @[simp] lemma mem_Sup {Ss : set (sieve X)} {Y} (f : Y ⟶ X) : Sup Ss f ↔ ∃ (S : sieve X) (H : S ∈ Ss), S f := iff.rfl @[simp] lemma mem_inter {R S : sieve X} {Y} (f : Y ⟶ X) : (R ⊓ S) f ↔ R f ∧ S f := iff.rfl @[simp] lemma mem_union {R S : sieve X} {Y} (f : Y ⟶ X) : (R ⊔ S) f ↔ R f ∨ S f := iff.rfl @[simp] lemma mem_top (f : Y ⟶ X) : (⊤ : sieve X) f := trivial /-- Generate the smallest sieve containing the given set of arrows. -/ def generate (R : presieve X) : sieve X := { arrows := λ Z f, ∃ Y (h : Z ⟶ Y) (g : Y ⟶ X), R g ∧ h ≫ g = f, downward_closed' := begin rintro Y Z _ ⟨W, g, f, hf, rfl⟩ h, exact ⟨_, h ≫ g, _, hf, by simp⟩, end } lemma mem_generate (R : presieve X) (f : Z ⟶ X) : generate R f ↔ ∃ (Y : C) (h : Z ⟶ Y) (g : Y ⟶ X), R g ∧ h ≫ g = f := iff.rfl /-- Given a collection of arrows with fixed codomain, -/ def bind (S : presieve X) (R : Π ⦃Y⦄ ⦃f : Y ⟶ X⦄, S f → sieve Y) : sieve X := { arrows := S.bind (λ Y f h, R h), downward_closed' := begin rintro Y Z f ⟨W, f, h, hh, hf, rfl⟩ g, exact ⟨_, g ≫ f, _, hh, by simp [hf]⟩, end } open order lattice lemma sets_iff_generate (R : presieve X) (S : sieve X) : generate R ≤ S ↔ R ≤ S := ⟨λ H Y g hg, H _ ⟨_, 𝟙 _, _, hg, category.id_comp _⟩, λ ss Y f, begin rintro ⟨Z, f, g, hg, rfl⟩, exact S.downward_closed (ss Z hg) f, end⟩ /-- Show that there is a galois insertion (generate, set_over). -/ def gi_generate : galois_insertion (generate : presieve X → sieve X) arrows := { gc := sets_iff_generate, choice := λ 𝒢 _, generate 𝒢, choice_eq := λ _ _, rfl, le_l_u := λ S Y f hf, ⟨_, 𝟙 _, _, hf, category.id_comp _⟩ } lemma le_generate (R : presieve X) : R ≤ generate R := gi_generate.gc.le_u_l R /-- If the identity arrow is in a sieve, the sieve is maximal. -/ lemma id_mem_iff_eq_top : S (𝟙 X) ↔ S = ⊤ := ⟨λ h, top_unique $ λ Y f _, by simpa using downward_closed _ h f, λ h, h.symm ▸ trivial⟩ /-- If an arrow set contains a split epi, it generates the maximal sieve. -/ lemma generate_of_contains_split_epi {R : presieve X} (f : Y ⟶ X) [split_epi f] (hf : R f) : generate R = ⊤ := begin rw ← id_mem_iff_eq_top, exact ⟨_, section_ f, f, hf, by simp⟩, end @[simp] lemma generate_of_singleton_split_epi (f : Y ⟶ X) [split_epi f] : generate (presieve.singleton f) = ⊤ := generate_of_contains_split_epi f (presieve.singleton_self _) @[simp] lemma generate_top : generate (⊤ : presieve X) = ⊤ := generate_of_contains_split_epi (𝟙 _) ⟨⟩ /-- Given a morphism `h : Y ⟶ X`, send a sieve S on X to a sieve on Y as the inverse image of S with `_ ≫ h`. That is, `sieve.pullback S h := (≫ h) '⁻¹ S`. -/ def pullback (h : Y ⟶ X) (S : sieve X) : sieve Y := { arrows := λ Y sl, S (sl ≫ h), downward_closed' := λ Z W f g h, by simp [g] } @[simp] lemma mem_pullback (h : Y ⟶ X) {f : Z ⟶ Y} : (S.pullback h) f ↔ S (f ≫ h) := iff.rfl @[simp] lemma pullback_id : S.pullback (𝟙 _) = S := by simp [sieve.ext_iff] @[simp] lemma pullback_top {f : Y ⟶ X} : (⊤ : sieve X).pullback f = ⊤ := top_unique (λ _ g, id) lemma pullback_comp {f : Y ⟶ X} {g : Z ⟶ Y} (S : sieve X) : S.pullback (g ≫ f) = (S.pullback f).pullback g := by simp [sieve.ext_iff] @[simp] lemma pullback_inter {f : Y ⟶ X} (S R : sieve X) : (S ⊓ R).pullback f = S.pullback f ⊓ R.pullback f := by simp [sieve.ext_iff] lemma pullback_eq_top_iff_mem (f : Y ⟶ X) : S f ↔ S.pullback f = ⊤ := by rw [← id_mem_iff_eq_top, mem_pullback, category.id_comp] lemma pullback_eq_top_of_mem (S : sieve X) {f : Y ⟶ X} : S f → S.pullback f = ⊤ := (pullback_eq_top_iff_mem f).1 /-- Push a sieve `R` on `Y` forward along an arrow `f : Y ⟶ X`: `gf : Z ⟶ X` is in the sieve if `gf` factors through some `g : Z ⟶ Y` which is in `R`. -/ def pushforward (f : Y ⟶ X) (R : sieve Y) : sieve X := { arrows := λ Z gf, ∃ g, g ≫ f = gf ∧ R g, downward_closed' := λ Z₁ Z₂ g ⟨j, k, z⟩ h, ⟨h ≫ j, by simp [k], by simp [z]⟩ } @[simp] lemma mem_pushforward_of_comp {R : sieve Y} {Z : C} {g : Z ⟶ Y} (hg : R g) (f : Y ⟶ X) : R.pushforward f (g ≫ f) := ⟨g, rfl, hg⟩ lemma pushforward_comp {f : Y ⟶ X} {g : Z ⟶ Y} (R : sieve Z) : R.pushforward (g ≫ f) = (R.pushforward g).pushforward f := sieve.ext (λ W h, ⟨λ ⟨f₁, hq, hf₁⟩, ⟨f₁ ≫ g, by simpa, f₁, rfl, hf₁⟩, λ ⟨y, hy, z, hR, hz⟩, ⟨z, by rwa reassoc_of hR, hz⟩⟩) lemma galois_connection (f : Y ⟶ X) : galois_connection (sieve.pushforward f) (sieve.pullback f) := λ S R, ⟨λ hR Z g hg, hR _ ⟨g, rfl, hg⟩, λ hS Z g ⟨h, hg, hh⟩, hg ▸ hS h hh⟩ lemma pullback_monotone (f : Y ⟶ X) : monotone (sieve.pullback f) := (galois_connection f).monotone_u lemma pushforward_monotone (f : Y ⟶ X) : monotone (sieve.pushforward f) := (galois_connection f).monotone_l lemma le_pushforward_pullback (f : Y ⟶ X) (R : sieve Y) : R ≤ (R.pushforward f).pullback f := (galois_connection f).le_u_l _ lemma pullback_pushforward_le (f : Y ⟶ X) (R : sieve X) : (R.pullback f).pushforward f ≤ R := (galois_connection f).l_u_le _ lemma pushforward_union {f : Y ⟶ X} (S R : sieve Y) : (S ⊔ R).pushforward f = S.pushforward f ⊔ R.pushforward f := (galois_connection f).l_sup lemma pushforward_le_bind_of_mem (S : presieve X) (R : Π ⦃Y : C⦄ ⦃f : Y ⟶ X⦄, S f → sieve Y) (f : Y ⟶ X) (h : S f) : (R h).pushforward f ≤ bind S R := begin rintro Z _ ⟨g, rfl, hg⟩, exact ⟨_, g, f, h, hg, rfl⟩, end lemma le_pullback_bind (S : presieve X) (R : Π ⦃Y : C⦄ ⦃f : Y ⟶ X⦄, S f → sieve Y) (f : Y ⟶ X) (h : S f) : R h ≤ (bind S R).pullback f := begin rw ← galois_connection f, apply pushforward_le_bind_of_mem, end /-- If `f` is a monomorphism, the pushforward-pullback adjunction on sieves is coreflective. -/ def galois_coinsertion_of_mono (f : Y ⟶ X) [mono f] : galois_coinsertion (sieve.pushforward f) (sieve.pullback f) := begin apply (galois_connection f).to_galois_coinsertion, rintros S Z g ⟨g₁, hf, hg₁⟩, rw cancel_mono f at hf, rwa ← hf, end /-- If `f` is a split epi, the pushforward-pullback adjunction on sieves is reflective. -/ def galois_insertion_of_split_epi (f : Y ⟶ X) [split_epi f] : galois_insertion (sieve.pushforward f) (sieve.pullback f) := begin apply (galois_connection f).to_galois_insertion, intros S Z g hg, refine ⟨g ≫ section_ f, by simpa⟩, end /-- A sieve induces a presheaf. -/ @[simps] def functor (S : sieve X) : Cᵒᵖ ⥤ Type v := { obj := λ Y, {g : Y.unop ⟶ X // S.arrows g}, map := λ Y Z f g, ⟨f.unop ≫ g.1, downward_closed _ g.2 _⟩ } /-- If a sieve S is contained in a sieve T, then we have a morphism of presheaves on their induced presheaves. -/ @[simps] def nat_trans_of_le {S T : sieve X} (h : S ≤ T) : S.functor ⟶ T.functor := { app := λ Y f, ⟨f.1, h _ f.2⟩ }. /-- The natural inclusion from the functor induced by a sieve to the yoneda embedding. -/ @[simps] def functor_inclusion (S : sieve X) : S.functor ⟶ yoneda.obj X := { app := λ Y f, f.1 }. lemma nat_trans_of_le_comm {S T : sieve X} (h : S ≤ T) : nat_trans_of_le h ≫ functor_inclusion _ = functor_inclusion _ := rfl /-- The presheaf induced by a sieve is a subobject of the yoneda embedding. -/ instance functor_inclusion_is_mono : mono (functor_inclusion S) := ⟨λ Z f g h, by { ext Y y, apply congr_fun (nat_trans.congr_app h Y) y }⟩ end sieve end category_theory
ad77fb9fc7f4ff09e95a3681e549c9cee0476a65
56e5b79a7ab4f2c52e6eb94f76d8100a25273cf3
/src/basic/queue.lean
fc8c648c4569b1cb9048f5dcf8f5694710c27801
[ "Apache-2.0" ]
permissive
DyeKuu/lean-tpe-public
3a9968f286ca182723ef7e7d97e155d8cb6b1e70
750ade767ab28037e80b7a80360d213a875038f8
refs/heads/master
1,682,842,633,115
1,621,330,793,000
1,621,330,793,000
368,475,816
0
0
Apache-2.0
1,621,330,745,000
1,621,330,744,000
null
UTF-8
Lean
false
false
4,403
lean
/- Author: E.W.Ayers © 2019. (Potentially buggy) implementation of a priority queue. -/ import .table universe u structure queue (α : Type u) := (l : list α) (r : list α) namespace queue variables {α : Type u} def empty : queue α := ⟨[],[]⟩ instance : has_emptyc (queue α) := ⟨empty⟩ instance : inhabited (queue α) := ⟨empty⟩ def enqueue : α → queue α → queue α | a ⟨l,r⟩ := ⟨l,a::r⟩ def peek : queue α → option α | ⟨h::l,r⟩ := some h | ⟨[],r⟩ := list.olast r def dequeue : queue α → option (α × queue α) | ⟨h::l,r⟩ := some (h, ⟨l,r⟩) | ⟨[], r⟩ := match list.reverse r with | (h::l) := some (h, queue.mk l []) | [] := none end def is_empty : queue α → bool | ⟨[],[]⟩ := tt | _ := ff def foldl {β} (f : β → α → β) : β → queue α → β | b ⟨l,r⟩ := r.foldr (function.swap f) $ l.foldl f b def mfoldl {M} [monad M] {β} (f : β → α → M β) : β → queue α → M β | b ⟨l,r⟩ := l.mfoldl f b >>= λ b, r.mfoldr (function.swap f) b def to_list : queue α → list α | ⟨l,r⟩ := l ++ r.reverse def of_list : list α → queue α | l := ⟨l,[]⟩ def append : queue α → queue α → queue α | ⟨l1,r1⟩ ⟨l2,r2⟩ := ⟨l1,r2 ++ l2.reverse ++ r1⟩ -- assuming the 2nd queue is shorter than 1st queue. instance : has_append (queue α) := ⟨append⟩ private def shunt : queue α → queue α | ⟨l,r⟩ := ⟨l ++ r.reverse, []⟩ protected def map {β} (f : α → β) : queue α → queue β | ⟨l,r⟩ := ⟨f <$> l, f <$> r⟩ instance : functor queue := { map := λ α β, queue.map} -- def traverse {M} [applicative M] {α β} (f : α → M β) (q : queue α) : M (queue α) := -- list.traverse f (shunt q) >>= λ l, pure ⟨l,[]⟩ def has (f : α → bool) : queue α → bool | ⟨l,r⟩ := list.any l f || list.any r f protected def mem : α → queue α → Prop | a ⟨l,r⟩ := a ∈ l ∨ a ∈ r instance : has_mem α (queue α) := ⟨queue.mem⟩ instance [decidable_eq α] {a:α} {q:queue α}: decidable (a ∈ q) := begin cases q with l r, show decidable (a ∈ l ∨ a ∈ r), apply_instance end def enqueue_no_dup [decidable_eq α] : α → queue α → queue α | a q := if a ∈ q then q else enqueue a q end queue /-- Priority queue. Lower `p a` means it is more prioritised. -/ meta def pqueue {α : Type} (p : α → ℤ) := dict ℤ (queue α) namespace pqueue open queue variables {α : Type} {p : α → ℤ} meta instance : has_emptyc (pqueue p) := dict.has_emptyc meta def empty : pqueue p := has_emptyc.emptyc meta def enqueue : α → pqueue p → pqueue p | a := dict.modify (queue.enqueue a ∘ option.iget) $ p a meta def enqueue_no_dup [decidable_eq α] : α → pqueue p → pqueue p | a := dict.modify (queue.enqueue_no_dup a ∘ option.iget) $ p a meta def enqueue_many : list α → pqueue p → pqueue p | l q := list.foldl (function.swap enqueue) q l meta def enqueue_many_no_dup [decidable_eq α]: list α → pqueue p → pqueue p | items q := list.foldl (function.swap enqueue_no_dup) q items meta def dequeue : pqueue p → option (α × pqueue p) | pq := do q ← dict.min pq, (a,q) ← q.dequeue, -- should not be empty if is_empty q then pure (a, dict.erase (p a) pq) else pure (a, dict.insert (p a) q pq) meta def of_list : list α → pqueue p | l := l.foldl (λ acc a, enqueue a acc) ∅ meta def append : pqueue p → pqueue p → pqueue p := dict.merge_with $ λ k, (++) meta instance : has_append (pqueue p) := ⟨append⟩ meta def fold {β} (f : β → α → β) : β → pqueue p → β := dict.fold (λ b k, queue.foldl f b) meta def mfold {T} [monad T] {β} (f : β → α → T β) : β → pqueue p → T β := dict.mfold (λ b k, queue.mfoldl f b) meta def has (f : α → bool) : pqueue p → bool := dict.any $ λ _, queue.has f -- [todo] arbitrate `any` vs `has` naming meta def to_list : pqueue p → list α := list.join ∘ list.map prod.snd ∘ dict.to_list ∘ dict.map queue.to_list meta instance has_pp [has_to_tactic_format α] : has_to_tactic_format (pqueue p) := ⟨tactic.pp ∘ to_list⟩ meta instance has_to_format [has_to_format α] : has_to_format (pqueue p) := ⟨λ p, format!"{p.to_list}"⟩ meta instance : has_sizeof (pqueue p) := by apply_instance meta def size : pqueue p → ℕ := λ pq, pq.fold (λ acc pq, nat.succ acc) 0 end pqueue
06a4be589cbe6b8d32e1415c68467a5b65174318
df7bb3acd9623e489e95e85d0bc55590ab0bc393
/lean/love04_functional_programming_demo.lean
9281b6e6541877fe44aeb45032b72e60ba58031c
[]
no_license
MaschavanderMarel/logical_verification_2020
a41c210b9237c56cb35f6cd399e3ac2fe42e775d
7d562ef174cc6578ca6013f74db336480470b708
refs/heads/master
1,692,144,223,196
1,634,661,675,000
1,634,661,675,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
12,638
lean
import .lovelib /- # LoVe Demo 4: Functional Programming We take a closer look at the basics of typed functional programming: inductive types, proofs by induction, recursive functions, pattern matching, structures (records), and type classes. -/ set_option pp.beta true set_option pp.generalized_field_notation false namespace LoVe /- ## Inductive Types Recall the definition of type `nat` (= `ℕ`): -/ #print nat /- Mottos: * **No junk**: The type contains no values beyond those expressible using the constructors. * **No confusion**: Values built in a different ways are different. For `nat` (= `ℕ`): * "No junk" means that there are no special values, say, `–1` or `ε`, that cannot be expressed using a finite combination of `zero` and `succ`. * "No confusion" is what ensures that `zero` ≠ `succ x`. In addition, inductive types are always finite. `succ (succ (succ …))` is not a value. ## Structural Induction __Structural induction__ is a generalization of mathematical induction to inductive types. To prove a property `P[n]` for all natural numbers `n`, it suffices to prove the base case `P[0]` and the induction step `∀k, P[k] → P[k + 1]` For lists, the base case is `P[[]]` and the induction step is `∀y ys, P[ys] → P[y :: ys]` In general, there is one subgoal per constructor, and induction hypotheses are available for all constructor arguments of the type we are doing the induction on. -/ lemma nat.succ_neq_self (n : ℕ) : nat.succ n ≠ n := begin induction' n, { simp }, { simp [ih] } end /- The `case` tactic can be used to supply custom names, and potentially reorder the cases. -/ lemma nat.succ_neq_self₂ (n : ℕ) : nat.succ n ≠ n := begin induction' n, case succ : m IH { simp [IH] }, case zero { simp } end /- ## Structural Recursion __Structural recursion__ is a form of recursion that allows us to peel off one or more constructors from the value on which we recurse. Such functions are guaranteed to call themselves only finitely many times before the recursion stops. This is a prerequisite for establishing that the function terminates. -/ def fact : ℕ → ℕ | 0 := 1 | (n + 1) := (n + 1) * fact n def fact₂ : ℕ → ℕ | 0 := 1 | 1 := 1 | (n + 1) := (n + 1) * fact₂ n /- For structurally recursive functions, Lean can automatically prove termination. For more general recursive schemes, the termination check may fail. Sometimes it does so for a good reason, as in the following example: -/ -- fails def illegal : ℕ → ℕ | n := illegal n + 1 constant immoral : ℕ → ℕ axiom immoral_eq (n : ℕ) : immoral n = immoral n + 1 lemma proof_of_false : false := have immoral 0 = immoral 0 + 1 := immoral_eq 0, have immoral 0 - immoral 0 = immoral 0 + 1 - immoral 0 := by cc, have 0 = 1 := by simp [*] at *, show false, from by cc /- ## Pattern Matching Expressions `match` _term₁_, …, _termM_ `with` | _pattern₁₁_, …, _pattern₁M_ := _result₁_ ⋮ | _patternN₁_, …, _patternNM_ := _resultN_ `end` `match` allows nonrecursive pattern matching within terms. In contrast to pattern matching after `lemma` or `def`, the patterns are separated by commas, so parentheses are optional. -/ def bcount {α : Type} (p : α → bool) : list α → ℕ | [] := 0 | (x :: xs) := match p x with | tt := bcount xs + 1 | ff := bcount xs end def min (a b : ℕ) : ℕ := if a ≤ b then a else b /- ## Structures Lean provides a convenient syntax for defining records, or structures. These are essentially nonrecursive, single-constructor inductive types. -/ structure rgb := (red green blue : ℕ) #check rgb.mk #check rgb.red #check rgb.green #check rgb.blue namespace rgb_as_inductive inductive rgb : Type | mk : ℕ → ℕ → ℕ → rgb def rgb.red : rgb → ℕ | (rgb.mk r _ _) := r def rgb.green : rgb → ℕ | (rgb.mk _ g _) := g def rgb.blue : rgb → ℕ | (rgb.mk _ _ b) := b end rgb_as_inductive structure rgba extends rgb := (alpha : ℕ) #print rgba def pure_red : rgb := { red := 0xff, green := 0x00, blue := 0x00 } def semitransparent_red : rgba := { alpha := 0x7f, ..pure_red } #print pure_red #print semitransparent_red def shuffle (c : rgb) : rgb := { red := rgb.green c, green := rgb.blue c, blue := rgb.red c } /- `cases'` performs a case distinction on the specified term. This gives rise to as many subgoals as there are constructors in the definition of the term's type. The tactic behaves the same as `induction'` except that it does not produce induction hypotheses. -/ lemma shuffle_shuffle_shuffle (c : rgb) : shuffle (shuffle (shuffle c)) = c := begin cases' c, refl end lemma shuffle_shuffle_shuffle₂ (c : rgb) : shuffle (shuffle (shuffle c)) = c := match c with | rgb.mk r g b := eq.refl _ end /- ## Type Classes A __type class__ is a structure type combining abstract constants and their properties. A type can be declared an instance of a type class by providing concrete definitions for the constants and proving that the properties hold. Based on the type, Lean retrieves the relevant instance. -/ #print inhabited @[instance] def nat.inhabited : inhabited ℕ := { default := 0 } @[instance] def list.inhabited {α : Type} : inhabited (list α) := { default := [] } #eval inhabited.default ℕ -- result: 0 #eval inhabited.default (list ℤ) -- result: [] def head {α : Type} [inhabited α] : list α → α | [] := inhabited.default α | (x :: _) := x lemma head_head {α : Type} [inhabited α] (xs : list α) : head [head xs] = head xs := begin cases' xs, { refl }, { refl } end #eval head ([] : list ℕ) -- result: 0 #check list.head @[instance] def fun.inhabited {α β : Type} [inhabited β] : inhabited (α → β) := { default := λa : α, inhabited.default β } inductive empty : Type @[instance] def fun_empty.inhabited {β : Type} : inhabited (empty → β) := { default := λa : empty, match a with end } @[instance] def prod.inhabited {α β : Type} [inhabited α] [inhabited β] : inhabited (α × β) := { default := (inhabited.default α, inhabited.default β) } /- Here are other type classes without properties: -/ #check has_zero #check has_neg #check has_add #check has_one #check has_inv #check has_mul #check (1 : ℕ) #check (1 : ℤ) #check (1 : ℝ) /- We encountered these type classes in lecture 2: -/ #print is_commutative #print is_associative /- ## Lists `list` is an inductive polymorphic type constructed from `nil` and `cons`: -/ #print list /- `cases'` can also be used on a hypothesis of the form `l = r`. It matches `r` against `l` and replaces all occurrences of the variables occurring in `r` with the corresponding terms in `l` everywhere in the goal. -/ lemma injection_example {α : Type} (x y : α) (xs ys : list α) (h : list.cons x xs = list.cons y ys) : x = y ∧ xs = ys := begin cases' h, cc end /- If `r` fails to match `l`, no subgoals emerge; the proof is complete. -/ lemma distinctness_example {α : Type} (y : α) (ys : list α) (h : [] = y :: ys) : false := by cases' h def map {α β : Type} (f : α → β) : list α → list β | [] := [] | (x :: xs) := f x :: map xs def map₂ {α β : Type} : (α → β) → list α → list β | _ [] := [] | f (x :: xs) := f x :: map₂ f xs #check list.map lemma map_ident {α : Type} (xs : list α) : map (λx, x) xs = xs := begin induction' xs, case nil { refl }, case cons : y ys { simp [map, ih] } end lemma map_comp {α β γ : Type} (f : α → β) (g : β → γ) (xs : list α) : map g (map f xs) = map (λx, g (f x)) xs := begin induction' xs, case nil { refl }, case cons : y ys { simp [map, ih] } end lemma map_append {α β : Type} (f : α → β) (xs ys : list α) : map f (xs ++ ys) = map f xs ++ map f ys := begin induction' xs, case nil { refl }, case cons : y ys { simp [map, ih] } end def tail {α : Type} : list α → list α | [] := [] | (_ :: xs) := xs #check list.tail def head_opt {α : Type} : list α → option α | [] := option.none | (x :: _) := option.some x def head_le {α : Type} : ∀xs : list α, xs ≠ [] → α | [] hxs := by cc | (x :: _) _ := x #eval head_opt [3, 1, 4] #eval head_le [3, 1, 4] (by simp) -- fails #eval head_le ([] : list ℕ) sorry def zip {α β : Type} : list α → list β → list (α × β) | (x :: xs) (y :: ys) := (x, y) :: zip xs ys | [] _ := [] | (_ :: _) [] := [] #check list.zip def length {α : Type} : list α → ℕ | [] := 0 | (x :: xs) := length xs + 1 #check list.length /- `cases'` can also be used to perform a case distinction on a proposition, in conjunction with `classical.em`. Two cases emerge: one in which the proposition is true and one in which it is false. -/ #check classical.em lemma min_add_add (l m n : ℕ) : min (m + l) (n + l) = min m n + l := begin cases' classical.em (m ≤ n), case inl { simp [min, h] }, case inr { simp [min, h] } end lemma min_add_add₂ (l m n : ℕ) : min (m + l) (n + l) = min m n + l := match classical.em (m ≤ n) with | or.inl h := by simp [min, h] | or.inr h := by simp [min, h] end lemma min_add_add₃ (l m n : ℕ) : min (m + l) (n + l) = min m n + l := if h : m ≤ n then by simp [min, h] else by simp [min, h] lemma length_zip {α β : Type} (xs : list α) (ys : list β) : length (zip xs ys) = min (length xs) (length ys) := begin induction' xs, case nil { refl }, case cons : x xs' { cases' ys, case nil { refl }, case cons : y ys' { simp [zip, length, ih ys', min_add_add] } } end lemma map_zip {α α' β β' : Type} (f : α → α') (g : β → β') : ∀xs ys, map (λab : α × β, (f (prod.fst ab), g (prod.snd ab))) (zip xs ys) = zip (map f xs) (map g ys) | (x :: xs) (y :: ys) := by simp [zip, map, map_zip xs ys] | [] _ := by refl | (_ :: _) [] := by refl /- ## Binary Trees Inductive types with constructors taking several recursive arguments define tree-like objects. __Binary trees__ have nodes with at most two children. -/ inductive btree (α : Type) : Type | empty {} : btree | node : α → btree → btree → btree /- The type `aexp` of arithmetic expressions was also an example of a tree data structure. The nodes of a tree, whether inner nodes or leaf nodes, often carry labels or other annotations. Inductive trees contain no infinite branches, not even cycles. This is less expressive than pointer- or reference-based data structures (in imperative languages) but easier to reason about. Recursive definitions (and proofs by induction) work roughly as for lists, but we may need to recurse (or invoke the induction hypothesis) on several child nodes. -/ def mirror {α : Type} : btree α → btree α | btree.empty := btree.empty | (btree.node a l r) := btree.node a (mirror r) (mirror l) lemma mirror_mirror {α : Type} (t : btree α) : mirror (mirror t) = t := begin induction' t, case empty { refl }, case node : a l r ih_l ih_r { simp [mirror, ih_l, ih_r] } end lemma mirror_mirror₂ {α : Type} : ∀t : btree α, mirror (mirror t) = t | btree.empty := by refl | (btree.node a l r) := calc mirror (mirror (btree.node a l r)) = mirror (btree.node a (mirror r) (mirror l)) : by refl ... = btree.node a (mirror (mirror l)) (mirror (mirror r)) : by refl ... = btree.node a l (mirror (mirror r)) : by rw mirror_mirror₂ l ... = btree.node a l r : by rw mirror_mirror₂ r lemma mirror_eq_empty_iff {α : Type} : ∀t : btree α, mirror t = btree.empty ↔ t = btree.empty | btree.empty := by refl | (btree.node _ _ _) := by simp [mirror] /- ## Dependent Inductive Types (**optional**) -/ #check vector inductive vec (α : Type) : ℕ → Type | nil {} : vec 0 | cons (a : α) {n : ℕ} (v : vec n) : vec (n + 1) #check vec.nil #check vec.cons def list_of_vec {α : Type} : ∀{n : ℕ}, vec α n → list α | _ vec.nil := [] | _ (vec.cons a v) := a :: list_of_vec v def vec_of_list {α : Type} : ∀xs : list α, vec α (list.length xs) | [] := vec.nil | (x :: xs) := vec.cons x (vec_of_list xs) lemma length_list_of_vec {α : Type} : ∀{n : ℕ} (v : vec α n), list.length (list_of_vec v) = n | _ vec.nil := by refl | _ (vec.cons a v) := by simp [list_of_vec, length_list_of_vec v] end LoVe
657e5344f967b71257cf8f58fb7b4ad556697dbf
c777c32c8e484e195053731103c5e52af26a25d1
/src/set_theory/game/pgame.lean
fd8e873590ce1659ba1889f3ff8e0cda3e197893
[ "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
57,202
lean
/- Copyright (c) 2019 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Reid Barton, Mario Carneiro, Isabel Longbottom, Scott Morrison -/ import data.fin.basic import data.list.basic import logic.relation import order.game_add /-! # Combinatorial (pre-)games. The basic theory of combinatorial games, following Conway's book `On Numbers and Games`. We construct "pregames", define an ordering and arithmetic operations on them, then show that the operations descend to "games", defined via the equivalence relation `p ≈ q ↔ p ≤ q ∧ q ≤ p`. The surreal numbers will be built as a quotient of a subtype of pregames. A pregame (`pgame` below) is axiomatised via an inductive type, whose sole constructor takes two types (thought of as indexing the possible moves for the players Left and Right), and a pair of functions out of these types to `pgame` (thought of as describing the resulting game after making a move). Combinatorial games themselves, as a quotient of pregames, are constructed in `game.lean`. ## Conway induction By construction, the induction principle for pregames is exactly "Conway induction". That is, to prove some predicate `pgame → Prop` holds for all pregames, it suffices to prove that for every pregame `g`, if the predicate holds for every game resulting from making a move, then it also holds for `g`. While it is often convenient to work "by induction" on pregames, in some situations this becomes awkward, so we also define accessor functions `pgame.left_moves`, `pgame.right_moves`, `pgame.move_left` and `pgame.move_right`. There is a relation `pgame.subsequent p q`, saying that `p` can be reached by playing some non-empty sequence of moves starting from `q`, an instance `well_founded subsequent`, and a local tactic `pgame_wf_tac` which is helpful for discharging proof obligations in inductive proofs relying on this relation. ## Order properties Pregames have both a `≤` and a `<` relation, satisfying the usual properties of a `preorder`. The relation `0 < x` means that `x` can always be won by Left, while `0 ≤ x` means that `x` can be won by Left as the second player. It turns out to be quite convenient to define various relations on top of these. We define the "less or fuzzy" relation `x ⧏ y` as `¬ y ≤ x`, the equivalence relation `x ≈ y` as `x ≤ y ∧ y ≤ x`, and the fuzzy relation `x ‖ y` as `x ⧏ y ∧ y ⧏ x`. If `0 ⧏ x`, then `x` can be won by Left as the first player. If `x ≈ 0`, then `x` can be won by the second player. If `x ‖ 0`, then `x` can be won by the first player. Statements like `zero_le_lf`, `zero_lf_le`, etc. unfold these definitions. The theorems `le_def` and `lf_def` give a recursive characterisation of each relation in terms of themselves two moves later. The theorems `zero_le`, `zero_lf`, etc. also take into account that `0` has no moves. Later, games will be defined as the quotient by the `≈` relation; that is to say, the `antisymmetrization` of `pgame`. ## Algebraic structures We next turn to defining the operations necessary to make games into a commutative additive group. Addition is defined for $x = \{xL | xR\}$ and $y = \{yL | yR\}$ by $x + y = \{xL + y, x + yL | xR + y, x + yR\}$. Negation is defined by $\{xL | xR\} = \{-xR | -xL\}$. The order structures interact in the expected way with addition, so we have ``` theorem le_iff_sub_nonneg {x y : pgame} : x ≤ y ↔ 0 ≤ y - x := sorry theorem lt_iff_sub_pos {x y : pgame} : x < y ↔ 0 < y - x := sorry ``` We show that these operations respect the equivalence relation, and hence descend to games. At the level of games, these operations satisfy all the laws of a commutative group. To prove the necessary equivalence relations at the level of pregames, we introduce the notion of a `relabelling` of a game, and show, for example, that there is a relabelling between `x + (y + z)` and `(x + y) + z`. ## Future work * The theory of dominated and reversible positions, and unique normal form for short games. * Analysis of basic domineering positions. * Hex. * Temperature. * The development of surreal numbers, based on this development of combinatorial games, is still quite incomplete. ## References The material here is all drawn from * [Conway, *On numbers and games*][conway2001] An interested reader may like to formalise some of the material from * [Andreas Blass, *A game semantics for linear logic*][MR1167694] * [André Joyal, *Remarques sur la théorie des jeux à deux personnes*][joyal1997] -/ open function relation universes u /-! ### Pre-game moves -/ /-- The type of pre-games, before we have quotiented by equivalence (`pgame.setoid`). In ZFC, a combinatorial game is constructed from two sets of combinatorial games that have been constructed at an earlier stage. To do this in type theory, we say that a pre-game is built inductively from two families of pre-games indexed over any type in Type u. The resulting type `pgame.{u}` lives in `Type (u+1)`, reflecting that it is a proper class in ZFC. -/ inductive pgame : Type (u+1) | mk : ∀ α β : Type u, (α → pgame) → (β → pgame) → pgame namespace pgame /-- The indexing type for allowable moves by Left. -/ def left_moves : pgame → Type u | (mk l _ _ _) := l /-- The indexing type for allowable moves by Right. -/ def right_moves : pgame → Type u | (mk _ r _ _) := r /-- The new game after Left makes an allowed move. -/ def move_left : Π (g : pgame), left_moves g → pgame | (mk l _ L _) := L /-- The new game after Right makes an allowed move. -/ def move_right : Π (g : pgame), right_moves g → pgame | (mk _ r _ R) := R @[simp] lemma left_moves_mk {xl xr xL xR} : (⟨xl, xr, xL, xR⟩ : pgame).left_moves = xl := rfl @[simp] lemma move_left_mk {xl xr xL xR} : (⟨xl, xr, xL, xR⟩ : pgame).move_left = xL := rfl @[simp] lemma right_moves_mk {xl xr xL xR} : (⟨xl, xr, xL, xR⟩ : pgame).right_moves = xr := rfl @[simp] lemma move_right_mk {xl xr xL xR} : (⟨xl, xr, xL, xR⟩ : pgame).move_right = xR := rfl /-- Construct a pre-game from list of pre-games describing the available moves for Left and Right. -/ -- TODO define this at the level of games, as well, and perhaps also for finsets of games. def of_lists (L R : list pgame.{u}) : pgame.{u} := mk (ulift (fin L.length)) (ulift (fin R.length)) (λ i, L.nth_le i.down i.down.is_lt) (λ j, R.nth_le j.down j.down.prop) lemma left_moves_of_lists (L R : list pgame) : (of_lists L R).left_moves = ulift (fin L.length) := rfl lemma right_moves_of_lists (L R : list pgame) : (of_lists L R).right_moves = ulift (fin R.length) := rfl /-- Converts a number into a left move for `of_lists`. -/ def to_of_lists_left_moves {L R : list pgame} : fin L.length ≃ (of_lists L R).left_moves := ((equiv.cast (left_moves_of_lists L R).symm).trans equiv.ulift).symm /-- Converts a number into a right move for `of_lists`. -/ def to_of_lists_right_moves {L R : list pgame} : fin R.length ≃ (of_lists L R).right_moves := ((equiv.cast (right_moves_of_lists L R).symm).trans equiv.ulift).symm theorem of_lists_move_left {L R : list pgame} (i : fin L.length) : (of_lists L R).move_left (to_of_lists_left_moves i) = L.nth_le i i.is_lt := rfl @[simp] theorem of_lists_move_left' {L R : list pgame} (i : (of_lists L R).left_moves) : (of_lists L R).move_left i = L.nth_le (to_of_lists_left_moves.symm i) (to_of_lists_left_moves.symm i).is_lt := rfl theorem of_lists_move_right {L R : list pgame} (i : fin R.length) : (of_lists L R).move_right (to_of_lists_right_moves i) = R.nth_le i i.is_lt := rfl @[simp] theorem of_lists_move_right' {L R : list pgame} (i : (of_lists L R).right_moves) : (of_lists L R).move_right i = R.nth_le (to_of_lists_right_moves.symm i) (to_of_lists_right_moves.symm i).is_lt := rfl /-- A variant of `pgame.rec_on` expressed in terms of `pgame.move_left` and `pgame.move_right`. Both this and `pgame.rec_on` describe Conway induction on games. -/ @[elab_as_eliminator] def move_rec_on {C : pgame → Sort*} (x : pgame) (IH : ∀ (y : pgame), (∀ i, C (y.move_left i)) → (∀ j, C (y.move_right j)) → C y) : C x := x.rec_on $ λ yl yr yL yR, IH (mk yl yr yL yR) /-- `is_option x y` means that `x` is either a left or right option for `y`. -/ @[mk_iff] inductive is_option : pgame → pgame → Prop | move_left {x : pgame} (i : x.left_moves) : is_option (x.move_left i) x | move_right {x : pgame} (i : x.right_moves) : is_option (x.move_right i) x theorem is_option.mk_left {xl xr : Type u} (xL : xl → pgame) (xR : xr → pgame) (i : xl) : (xL i).is_option (mk xl xr xL xR) := @is_option.move_left (mk _ _ _ _) i theorem is_option.mk_right {xl xr : Type u} (xL : xl → pgame) (xR : xr → pgame) (i : xr) : (xR i).is_option (mk xl xr xL xR) := @is_option.move_right (mk _ _ _ _) i theorem wf_is_option : well_founded is_option := ⟨λ x, move_rec_on x $ λ x IHl IHr, acc.intro x $ λ y h, begin induction h with _ i _ j, { exact IHl i }, { exact IHr j } end⟩ /-- `subsequent x y` says that `x` can be obtained by playing some nonempty sequence of moves from `y`. It is the transitive closure of `is_option`. -/ def subsequent : pgame → pgame → Prop := trans_gen is_option instance : is_trans _ subsequent := trans_gen.is_trans @[trans] theorem subsequent.trans {x y z} : subsequent x y → subsequent y z → subsequent x z := trans_gen.trans theorem wf_subsequent : well_founded subsequent := wf_is_option.trans_gen instance : has_well_founded pgame := ⟨_, wf_subsequent⟩ lemma subsequent.move_left {x : pgame} (i : x.left_moves) : subsequent (x.move_left i) x := trans_gen.single (is_option.move_left i) lemma subsequent.move_right {x : pgame} (j : x.right_moves) : subsequent (x.move_right j) x := trans_gen.single (is_option.move_right j) lemma subsequent.mk_left {xl xr} (xL : xl → pgame) (xR : xr → pgame) (i : xl) : subsequent (xL i) (mk xl xr xL xR) := @subsequent.move_left (mk _ _ _ _) i lemma subsequent.mk_right {xl xr} (xL : xl → pgame) (xR : xr → pgame) (j : xr) : subsequent (xR j) (mk xl xr xL xR) := @subsequent.move_right (mk _ _ _ _) j /-- A local tactic for proving well-foundedness of recursive definitions involving pregames. -/ meta def pgame_wf_tac := `[solve_by_elim [psigma.lex.left, psigma.lex.right, subsequent.move_left, subsequent.move_right, subsequent.mk_left, subsequent.mk_right, subsequent.trans] { max_depth := 6 }] /-! ### Basic pre-games -/ /-- The pre-game `zero` is defined by `0 = { | }`. -/ instance : has_zero pgame := ⟨⟨pempty, pempty, pempty.elim, pempty.elim⟩⟩ @[simp] lemma zero_left_moves : left_moves 0 = pempty := rfl @[simp] lemma zero_right_moves : right_moves 0 = pempty := rfl instance is_empty_zero_left_moves : is_empty (left_moves 0) := pempty.is_empty instance is_empty_zero_right_moves : is_empty (right_moves 0) := pempty.is_empty instance : inhabited pgame := ⟨0⟩ /-- The pre-game `one` is defined by `1 = { 0 | }`. -/ instance : has_one pgame := ⟨⟨punit, pempty, λ _, 0, pempty.elim⟩⟩ @[simp] lemma one_left_moves : left_moves 1 = punit := rfl @[simp] lemma one_move_left (x) : move_left 1 x = 0 := rfl @[simp] lemma one_right_moves : right_moves 1 = pempty := rfl instance unique_one_left_moves : unique (left_moves 1) := punit.unique instance is_empty_one_right_moves : is_empty (right_moves 1) := pempty.is_empty /-! ### Pre-game order relations -/ /-- The less or equal relation on pre-games. If `0 ≤ x`, then Left can win `x` as the second player. -/ instance : has_le pgame := ⟨sym2.game_add.fix wf_is_option $ λ x y le, (∀ i, ¬ le y (x.move_left i) (sym2.game_add.snd_fst $ is_option.move_left i)) ∧ (∀ j, ¬ le (y.move_right j) x (sym2.game_add.fst_snd $ is_option.move_right j))⟩ /-- The less or fuzzy relation on pre-games. If `0 ⧏ x`, then Left can win `x` as the first player. -/ def lf (x y : pgame) : Prop := ¬ y ≤ x localized "infix (name := pgame.lf) ` ⧏ `:50 := pgame.lf" in pgame @[simp] protected theorem not_le {x y : pgame} : ¬ x ≤ y ↔ y ⧏ x := iff.rfl @[simp] theorem not_lf {x y : pgame} : ¬ x ⧏ y ↔ y ≤ x := not_not theorem _root_.has_le.le.not_gf {x y : pgame} : x ≤ y → ¬ y ⧏ x := not_lf.2 theorem lf.not_ge {x y : pgame} : x ⧏ y → ¬ y ≤ x := id /-- Definition of `x ≤ y` on pre-games, in terms of `⧏`. The ordering here is chosen so that `and.left` refer to moves by Left, and `and.right` refer to moves by Right. -/ theorem le_iff_forall_lf {x y : pgame} : x ≤ y ↔ (∀ i, x.move_left i ⧏ y) ∧ ∀ j, x ⧏ y.move_right j := by { unfold has_le.le, rw sym2.game_add.fix_eq, refl } /-- Definition of `x ≤ y` on pre-games built using the constructor. -/ @[simp] theorem mk_le_mk {xl xr xL xR yl yr yL yR} : mk xl xr xL xR ≤ mk yl yr yL yR ↔ (∀ i, xL i ⧏ mk yl yr yL yR) ∧ ∀ j, mk xl xr xL xR ⧏ yR j := le_iff_forall_lf theorem le_of_forall_lf {x y : pgame} (h₁ : ∀ i, x.move_left i ⧏ y) (h₂ : ∀ j, x ⧏ y.move_right j) : x ≤ y := le_iff_forall_lf.2 ⟨h₁, h₂⟩ /-- Definition of `x ⧏ y` on pre-games, in terms of `≤`. The ordering here is chosen so that `or.inl` refer to moves by Left, and `or.inr` refer to moves by Right. -/ theorem lf_iff_exists_le {x y : pgame} : x ⧏ y ↔ (∃ i, x ≤ y.move_left i) ∨ ∃ j, x.move_right j ≤ y := by { rw [lf, le_iff_forall_lf, not_and_distrib], simp } /-- Definition of `x ⧏ y` on pre-games built using the constructor. -/ @[simp] theorem mk_lf_mk {xl xr xL xR yl yr yL yR} : mk xl xr xL xR ⧏ mk yl yr yL yR ↔ (∃ i, mk xl xr xL xR ≤ yL i) ∨ ∃ j, xR j ≤ mk yl yr yL yR := lf_iff_exists_le theorem le_or_gf (x y : pgame) : x ≤ y ∨ y ⧏ x := by { rw ←pgame.not_le, apply em } theorem move_left_lf_of_le {x y : pgame} (h : x ≤ y) (i) : x.move_left i ⧏ y := (le_iff_forall_lf.1 h).1 i alias move_left_lf_of_le ← _root_.has_le.le.move_left_lf theorem lf_move_right_of_le {x y : pgame} (h : x ≤ y) (j) : x ⧏ y.move_right j := (le_iff_forall_lf.1 h).2 j alias lf_move_right_of_le ← _root_.has_le.le.lf_move_right theorem lf_of_move_right_le {x y : pgame} {j} (h : x.move_right j ≤ y) : x ⧏ y := lf_iff_exists_le.2 $ or.inr ⟨j, h⟩ theorem lf_of_le_move_left {x y : pgame} {i} (h : x ≤ y.move_left i) : x ⧏ y := lf_iff_exists_le.2 $ or.inl ⟨i, h⟩ theorem lf_of_le_mk {xl xr xL xR y} : mk xl xr xL xR ≤ y → ∀ i, xL i ⧏ y := move_left_lf_of_le theorem lf_of_mk_le {x yl yr yL yR} : x ≤ mk yl yr yL yR → ∀ j, x ⧏ yR j := lf_move_right_of_le theorem mk_lf_of_le {xl xr y j} (xL) {xR : xr → pgame} : xR j ≤ y → mk xl xr xL xR ⧏ y := @lf_of_move_right_le (mk _ _ _ _) y j theorem lf_mk_of_le {x yl yr} {yL : yl → pgame} (yR) {i} : x ≤ yL i → x ⧏ mk yl yr yL yR := @lf_of_le_move_left x (mk _ _ _ _) i /- We prove that `x ≤ y → y ≤ z ← x ≤ z` inductively, by also simultaneously proving its cyclic reorderings. This auxiliary lemma is used during said induction. -/ private theorem le_trans_aux {x y z : pgame} (h₁ : ∀ {i}, y ≤ z → z ≤ x.move_left i → y ≤ x.move_left i) (h₂ : ∀ {j}, z.move_right j ≤ x → x ≤ y → z.move_right j ≤ y) (hxy : x ≤ y) (hyz : y ≤ z) : x ≤ z := le_of_forall_lf (λ i, pgame.not_le.1 $ λ h, (h₁ hyz h).not_gf $ hxy.move_left_lf i) (λ j, pgame.not_le.1 $ λ h, (h₂ h hxy).not_gf $ hyz.lf_move_right j) instance : preorder pgame := { le_refl := λ x, begin induction x with _ _ _ _ IHl IHr, exact le_of_forall_lf (λ i, lf_of_le_move_left (IHl i)) (λ i, lf_of_move_right_le (IHr i)) end, le_trans := begin suffices : ∀ {x y z : pgame}, (x ≤ y → y ≤ z → x ≤ z) ∧ (y ≤ z → z ≤ x → y ≤ x) ∧ (z ≤ x → x ≤ y → z ≤ y), from λ x y z, this.1, intros x y z, induction x with xl xr xL xR IHxl IHxr generalizing y z, induction y with yl yr yL yR IHyl IHyr generalizing z, induction z with zl zr zL zR IHzl IHzr, exact ⟨le_trans_aux (λ i, (IHxl i).2.1) (λ j, (IHzr j).2.2), le_trans_aux (λ i, (IHyl i).2.2) (λ j, (IHxr j).1), le_trans_aux (λ i, (IHzl i).1) (λ j, (IHyr j).2.1)⟩ end, lt := λ x y, x ≤ y ∧ x ⧏ y, ..pgame.has_le, } theorem lt_iff_le_and_lf {x y : pgame} : x < y ↔ x ≤ y ∧ x ⧏ y := iff.rfl theorem lt_of_le_of_lf {x y : pgame} (h₁ : x ≤ y) (h₂ : x ⧏ y) : x < y := ⟨h₁, h₂⟩ theorem lf_of_lt {x y : pgame} (h : x < y) : x ⧏ y := h.2 alias lf_of_lt ← _root_.has_lt.lt.lf theorem lf_irrefl (x : pgame) : ¬ x ⧏ x := le_rfl.not_gf instance : is_irrefl _ (⧏) := ⟨lf_irrefl⟩ @[trans] theorem lf_of_le_of_lf {x y z : pgame} (h₁ : x ≤ y) (h₂ : y ⧏ z) : x ⧏ z := by { rw ←pgame.not_le at h₂ ⊢, exact λ h₃, h₂ (h₃.trans h₁) } @[trans] theorem lf_of_lf_of_le {x y z : pgame} (h₁ : x ⧏ y) (h₂ : y ≤ z) : x ⧏ z := by { rw ←pgame.not_le at h₁ ⊢, exact λ h₃, h₁ (h₂.trans h₃) } alias lf_of_le_of_lf ← _root_.has_le.le.trans_lf alias lf_of_lf_of_le ← lf.trans_le @[trans] theorem lf_of_lt_of_lf {x y z : pgame} (h₁ : x < y) (h₂ : y ⧏ z) : x ⧏ z := h₁.le.trans_lf h₂ @[trans] theorem lf_of_lf_of_lt {x y z : pgame} (h₁ : x ⧏ y) (h₂ : y < z) : x ⧏ z := h₁.trans_le h₂.le alias lf_of_lt_of_lf ← _root_.has_lt.lt.trans_lf alias lf_of_lf_of_lt ← lf.trans_lt theorem move_left_lf {x : pgame} : ∀ i, x.move_left i ⧏ x := le_rfl.move_left_lf theorem lf_move_right {x : pgame} : ∀ j, x ⧏ x.move_right j := le_rfl.lf_move_right theorem lf_mk {xl xr} (xL : xl → pgame) (xR : xr → pgame) (i) : xL i ⧏ mk xl xr xL xR := @move_left_lf (mk _ _ _ _) i theorem mk_lf {xl xr} (xL : xl → pgame) (xR : xr → pgame) (j) : mk xl xr xL xR ⧏ xR j := @lf_move_right (mk _ _ _ _) j /-- This special case of `pgame.le_of_forall_lf` is useful when dealing with surreals, where `<` is preferred over `⧏`. -/ theorem le_of_forall_lt {x y : pgame} (h₁ : ∀ i, x.move_left i < y) (h₂ : ∀ j, x < y.move_right j) : x ≤ y := le_of_forall_lf (λ i, (h₁ i).lf) (λ i, (h₂ i).lf) /-- The definition of `x ≤ y` on pre-games, in terms of `≤` two moves later. -/ theorem le_def {x y : pgame} : x ≤ y ↔ (∀ i, (∃ i', x.move_left i ≤ y.move_left i') ∨ ∃ j, (x.move_left i).move_right j ≤ y) ∧ ∀ j, (∃ i, x ≤ (y.move_right j).move_left i) ∨ ∃ j', x.move_right j' ≤ y.move_right j := by { rw le_iff_forall_lf, conv { to_lhs, simp only [lf_iff_exists_le] } } /-- The definition of `x ⧏ y` on pre-games, in terms of `⧏` two moves later. -/ theorem lf_def {x y : pgame} : x ⧏ y ↔ (∃ i, (∀ i', x.move_left i' ⧏ y.move_left i) ∧ ∀ j, x ⧏ (y.move_left i).move_right j) ∨ ∃ j, (∀ i, (x.move_right j).move_left i ⧏ y) ∧ ∀ j', x.move_right j ⧏ y.move_right j' := by { rw lf_iff_exists_le, conv { to_lhs, simp only [le_iff_forall_lf] } } /-- The definition of `0 ≤ x` on pre-games, in terms of `0 ⧏`. -/ theorem zero_le_lf {x : pgame} : 0 ≤ x ↔ ∀ j, 0 ⧏ x.move_right j := by { rw le_iff_forall_lf, simp } /-- The definition of `x ≤ 0` on pre-games, in terms of `⧏ 0`. -/ theorem le_zero_lf {x : pgame} : x ≤ 0 ↔ ∀ i, x.move_left i ⧏ 0 := by { rw le_iff_forall_lf, simp } /-- The definition of `0 ⧏ x` on pre-games, in terms of `0 ≤`. -/ theorem zero_lf_le {x : pgame} : 0 ⧏ x ↔ ∃ i, 0 ≤ x.move_left i := by { rw lf_iff_exists_le, simp } /-- The definition of `x ⧏ 0` on pre-games, in terms of `≤ 0`. -/ theorem lf_zero_le {x : pgame} : x ⧏ 0 ↔ ∃ j, x.move_right j ≤ 0 := by { rw lf_iff_exists_le, simp } /-- The definition of `0 ≤ x` on pre-games, in terms of `0 ≤` two moves later. -/ theorem zero_le {x : pgame} : 0 ≤ x ↔ ∀ j, ∃ i, 0 ≤ (x.move_right j).move_left i := by { rw le_def, simp } /-- The definition of `x ≤ 0` on pre-games, in terms of `≤ 0` two moves later. -/ theorem le_zero {x : pgame} : x ≤ 0 ↔ ∀ i, ∃ j, (x.move_left i).move_right j ≤ 0 := by { rw le_def, simp } /-- The definition of `0 ⧏ x` on pre-games, in terms of `0 ⧏` two moves later. -/ theorem zero_lf {x : pgame} : 0 ⧏ x ↔ ∃ i, ∀ j, 0 ⧏ (x.move_left i).move_right j := by { rw lf_def, simp } /-- The definition of `x ⧏ 0` on pre-games, in terms of `⧏ 0` two moves later. -/ theorem lf_zero {x : pgame} : x ⧏ 0 ↔ ∃ j, ∀ i, (x.move_right j).move_left i ⧏ 0 := by { rw lf_def, simp } @[simp] theorem zero_le_of_is_empty_right_moves (x : pgame) [is_empty x.right_moves] : 0 ≤ x := zero_le.2 is_empty_elim @[simp] theorem le_zero_of_is_empty_left_moves (x : pgame) [is_empty x.left_moves] : x ≤ 0 := le_zero.2 is_empty_elim /-- Given a game won by the right player when they play second, provide a response to any move by left. -/ noncomputable def right_response {x : pgame} (h : x ≤ 0) (i : x.left_moves) : (x.move_left i).right_moves := classical.some $ (le_zero.1 h) i /-- Show that the response for right provided by `right_response` preserves the right-player-wins condition. -/ lemma right_response_spec {x : pgame} (h : x ≤ 0) (i : x.left_moves) : (x.move_left i).move_right (right_response h i) ≤ 0 := classical.some_spec $ (le_zero.1 h) i /-- Given a game won by the left player when they play second, provide a response to any move by right. -/ noncomputable def left_response {x : pgame} (h : 0 ≤ x) (j : x.right_moves) : (x.move_right j).left_moves := classical.some $ (zero_le.1 h) j /-- Show that the response for left provided by `left_response` preserves the left-player-wins condition. -/ lemma left_response_spec {x : pgame} (h : 0 ≤ x) (j : x.right_moves) : 0 ≤ (x.move_right j).move_left (left_response h j) := classical.some_spec $ (zero_le.1 h) j /-- The equivalence relation on pre-games. Two pre-games `x`, `y` are equivalent if `x ≤ y` and `y ≤ x`. If `x ≈ 0`, then the second player can always win `x`. -/ def equiv (x y : pgame) : Prop := x ≤ y ∧ y ≤ x localized "infix (name := pgame.equiv) ` ≈ ` := pgame.equiv" in pgame instance : is_equiv _ (≈) := { refl := λ x, ⟨le_rfl, le_rfl⟩, trans := λ x y z ⟨xy, yx⟩ ⟨yz, zy⟩, ⟨xy.trans yz, zy.trans yx⟩, symm := λ x y, and.symm } theorem equiv.le {x y : pgame} (h : x ≈ y) : x ≤ y := h.1 theorem equiv.ge {x y : pgame} (h : x ≈ y) : y ≤ x := h.2 @[refl, simp] theorem equiv_rfl {x} : x ≈ x := refl x theorem equiv_refl (x) : x ≈ x := refl x @[symm] protected theorem equiv.symm {x y} : x ≈ y → y ≈ x := symm @[trans] protected theorem equiv.trans {x y z} : x ≈ y → y ≈ z → x ≈ z := trans protected theorem equiv_comm {x y} : x ≈ y ↔ y ≈ x := comm theorem equiv_of_eq {x y} (h : x = y) : x ≈ y := by subst h @[trans] theorem le_of_le_of_equiv {x y z} (h₁ : x ≤ y) (h₂ : y ≈ z) : x ≤ z := h₁.trans h₂.1 @[trans] theorem le_of_equiv_of_le {x y z} (h₁ : x ≈ y) : y ≤ z → x ≤ z := h₁.1.trans theorem lf.not_equiv {x y} (h : x ⧏ y) : ¬ x ≈ y := λ h', h.not_ge h'.2 theorem lf.not_equiv' {x y} (h : x ⧏ y) : ¬ y ≈ x := λ h', h.not_ge h'.1 theorem lf.not_gt {x y} (h : x ⧏ y) : ¬ y < x := λ h', h.not_ge h'.le theorem le_congr_imp {x₁ y₁ x₂ y₂} (hx : x₁ ≈ x₂) (hy : y₁ ≈ y₂) (h : x₁ ≤ y₁) : x₂ ≤ y₂ := hx.2.trans (h.trans hy.1) theorem le_congr {x₁ y₁ x₂ y₂} (hx : x₁ ≈ x₂) (hy : y₁ ≈ y₂) : x₁ ≤ y₁ ↔ x₂ ≤ y₂ := ⟨le_congr_imp hx hy, le_congr_imp hx.symm hy.symm⟩ theorem le_congr_left {x₁ x₂ y} (hx : x₁ ≈ x₂) : x₁ ≤ y ↔ x₂ ≤ y := le_congr hx equiv_rfl theorem le_congr_right {x y₁ y₂} (hy : y₁ ≈ y₂) : x ≤ y₁ ↔ x ≤ y₂ := le_congr equiv_rfl hy theorem lf_congr {x₁ y₁ x₂ y₂} (hx : x₁ ≈ x₂) (hy : y₁ ≈ y₂) : x₁ ⧏ y₁ ↔ x₂ ⧏ y₂ := pgame.not_le.symm.trans $ (not_congr (le_congr hy hx)).trans pgame.not_le theorem lf_congr_imp {x₁ y₁ x₂ y₂} (hx : x₁ ≈ x₂) (hy : y₁ ≈ y₂) : x₁ ⧏ y₁ → x₂ ⧏ y₂ := (lf_congr hx hy).1 theorem lf_congr_left {x₁ x₂ y} (hx : x₁ ≈ x₂) : x₁ ⧏ y ↔ x₂ ⧏ y := lf_congr hx equiv_rfl theorem lf_congr_right {x y₁ y₂} (hy : y₁ ≈ y₂) : x ⧏ y₁ ↔ x ⧏ y₂ := lf_congr equiv_rfl hy @[trans] theorem lf_of_lf_of_equiv {x y z} (h₁ : x ⧏ y) (h₂ : y ≈ z) : x ⧏ z := lf_congr_imp equiv_rfl h₂ h₁ @[trans] theorem lf_of_equiv_of_lf {x y z} (h₁ : x ≈ y) : y ⧏ z → x ⧏ z := lf_congr_imp h₁.symm equiv_rfl @[trans] theorem lt_of_lt_of_equiv {x y z} (h₁ : x < y) (h₂ : y ≈ z) : x < z := h₁.trans_le h₂.1 @[trans] theorem lt_of_equiv_of_lt {x y z} (h₁ : x ≈ y) : y < z → x < z := h₁.1.trans_lt theorem lt_congr_imp {x₁ y₁ x₂ y₂} (hx : x₁ ≈ x₂) (hy : y₁ ≈ y₂) (h : x₁ < y₁) : x₂ < y₂ := hx.2.trans_lt (h.trans_le hy.1) theorem lt_congr {x₁ y₁ x₂ y₂} (hx : x₁ ≈ x₂) (hy : y₁ ≈ y₂) : x₁ < y₁ ↔ x₂ < y₂ := ⟨lt_congr_imp hx hy, lt_congr_imp hx.symm hy.symm⟩ theorem lt_congr_left {x₁ x₂ y} (hx : x₁ ≈ x₂) : x₁ < y ↔ x₂ < y := lt_congr hx equiv_rfl theorem lt_congr_right {x y₁ y₂} (hy : y₁ ≈ y₂) : x < y₁ ↔ x < y₂ := lt_congr equiv_rfl hy theorem lt_or_equiv_of_le {x y : pgame} (h : x ≤ y) : x < y ∨ x ≈ y := and_or_distrib_left.mp ⟨h, (em $ y ≤ x).swap.imp_left pgame.not_le.1⟩ theorem lf_or_equiv_or_gf (x y : pgame) : x ⧏ y ∨ x ≈ y ∨ y ⧏ x := begin by_cases h : x ⧏ y, { exact or.inl h }, { right, cases (lt_or_equiv_of_le (pgame.not_lf.1 h)) with h' h', { exact or.inr h'.lf }, { exact or.inl h'.symm } } end theorem equiv_congr_left {y₁ y₂} : y₁ ≈ y₂ ↔ ∀ x₁, x₁ ≈ y₁ ↔ x₁ ≈ y₂ := ⟨λ h x₁, ⟨λ h', h'.trans h, λ h', h'.trans h.symm⟩, λ h, (h y₁).1 $ equiv_rfl⟩ theorem equiv_congr_right {x₁ x₂} : x₁ ≈ x₂ ↔ ∀ y₁, x₁ ≈ y₁ ↔ x₂ ≈ y₁ := ⟨λ h y₁, ⟨λ h', h.symm.trans h', λ h', h.trans h'⟩, λ h, (h x₂).2 $ equiv_rfl⟩ theorem equiv_of_mk_equiv {x y : pgame} (L : x.left_moves ≃ y.left_moves) (R : x.right_moves ≃ y.right_moves) (hl : ∀ i, x.move_left i ≈ y.move_left (L i)) (hr : ∀ j, x.move_right j ≈ y.move_right (R j)) : x ≈ y := begin fsplit; rw le_def, { exact ⟨λ i, or.inl ⟨_, (hl i).1⟩, λ j, or.inr ⟨_, by simpa using (hr (R.symm j)).1⟩⟩ }, { exact ⟨λ i, or.inl ⟨_, by simpa using (hl (L.symm i)).2⟩, λ j, or.inr ⟨_, (hr j).2⟩⟩ } end /-- The fuzzy, confused, or incomparable relation on pre-games. If `x ‖ 0`, then the first player can always win `x`. -/ def fuzzy (x y : pgame) : Prop := x ⧏ y ∧ y ⧏ x localized "infix (name := pgame.fuzzy) ` ‖ `:50 := pgame.fuzzy" in pgame @[symm] theorem fuzzy.swap {x y : pgame} : x ‖ y → y ‖ x := and.swap instance : is_symm _ (‖) := ⟨λ x y, fuzzy.swap⟩ theorem fuzzy.swap_iff {x y : pgame} : x ‖ y ↔ y ‖ x := ⟨fuzzy.swap, fuzzy.swap⟩ theorem fuzzy_irrefl (x : pgame) : ¬ x ‖ x := λ h, lf_irrefl x h.1 instance : is_irrefl _ (‖) := ⟨fuzzy_irrefl⟩ theorem lf_iff_lt_or_fuzzy {x y : pgame} : x ⧏ y ↔ x < y ∨ x ‖ y := by { simp only [lt_iff_le_and_lf, fuzzy, ←pgame.not_le], tauto! } theorem lf_of_fuzzy {x y : pgame} (h : x ‖ y) : x ⧏ y := lf_iff_lt_or_fuzzy.2 (or.inr h) alias lf_of_fuzzy ← fuzzy.lf theorem lt_or_fuzzy_of_lf {x y : pgame} : x ⧏ y → x < y ∨ x ‖ y := lf_iff_lt_or_fuzzy.1 theorem fuzzy.not_equiv {x y : pgame} (h : x ‖ y) : ¬ x ≈ y := λ h', h'.1.not_gf h.2 theorem fuzzy.not_equiv' {x y : pgame} (h : x ‖ y) : ¬ y ≈ x := λ h', h'.2.not_gf h.2 theorem not_fuzzy_of_le {x y : pgame} (h : x ≤ y) : ¬ x ‖ y := λ h', h'.2.not_ge h theorem not_fuzzy_of_ge {x y : pgame} (h : y ≤ x) : ¬ x ‖ y := λ h', h'.1.not_ge h theorem equiv.not_fuzzy {x y : pgame} (h : x ≈ y) : ¬ x ‖ y := not_fuzzy_of_le h.1 theorem equiv.not_fuzzy' {x y : pgame} (h : x ≈ y) : ¬ y ‖ x := not_fuzzy_of_le h.2 theorem fuzzy_congr {x₁ y₁ x₂ y₂ : pgame} (hx : x₁ ≈ x₂) (hy : y₁ ≈ y₂) : x₁ ‖ y₁ ↔ x₂ ‖ y₂ := show _ ∧ _ ↔ _ ∧ _, by rw [lf_congr hx hy, lf_congr hy hx] theorem fuzzy_congr_imp {x₁ y₁ x₂ y₂ : pgame} (hx : x₁ ≈ x₂) (hy : y₁ ≈ y₂) : x₁ ‖ y₁ → x₂ ‖ y₂ := (fuzzy_congr hx hy).1 theorem fuzzy_congr_left {x₁ x₂ y} (hx : x₁ ≈ x₂) : x₁ ‖ y ↔ x₂ ‖ y := fuzzy_congr hx equiv_rfl theorem fuzzy_congr_right {x y₁ y₂} (hy : y₁ ≈ y₂) : x ‖ y₁ ↔ x ‖ y₂ := fuzzy_congr equiv_rfl hy @[trans] theorem fuzzy_of_fuzzy_of_equiv {x y z} (h₁ : x ‖ y) (h₂ : y ≈ z) : x ‖ z := (fuzzy_congr_right h₂).1 h₁ @[trans] theorem fuzzy_of_equiv_of_fuzzy {x y z} (h₁ : x ≈ y) (h₂ : y ‖ z) : x ‖ z := (fuzzy_congr_left h₁).2 h₂ /-- Exactly one of the following is true (although we don't prove this here). -/ theorem lt_or_equiv_or_gt_or_fuzzy (x y : pgame) : x < y ∨ x ≈ y ∨ y < x ∨ x ‖ y := begin cases le_or_gf x y with h₁ h₁; cases le_or_gf y x with h₂ h₂, { right, left, exact ⟨h₁, h₂⟩ }, { left, exact ⟨h₁, h₂⟩ }, { right, right, left, exact ⟨h₂, h₁⟩ }, { right, right, right, exact ⟨h₂, h₁⟩ } end theorem lt_or_equiv_or_gf (x y : pgame) : x < y ∨ x ≈ y ∨ y ⧏ x := begin rw [lf_iff_lt_or_fuzzy, fuzzy.swap_iff], exact lt_or_equiv_or_gt_or_fuzzy x y end /-! ### Relabellings -/ /-- `relabelling x y` says that `x` and `y` are really the same game, just dressed up differently. Specifically, there is a bijection between the moves for Left in `x` and in `y`, and similarly for Right, and under these bijections we inductively have `relabelling`s for the consequent games. -/ inductive relabelling : pgame.{u} → pgame.{u} → Type (u+1) | mk : Π {x y : pgame} (L : x.left_moves ≃ y.left_moves) (R : x.right_moves ≃ y.right_moves), (∀ i, relabelling (x.move_left i) (y.move_left (L i))) → (∀ j, relabelling (x.move_right j) (y.move_right (R j))) → relabelling x y localized "infix (name := pgame.relabelling) ` ≡r `:50 := pgame.relabelling" in pgame namespace relabelling variables {x y : pgame.{u}} /-- A constructor for relabellings swapping the equivalences. -/ def mk' (L : y.left_moves ≃ x.left_moves) (R : y.right_moves ≃ x.right_moves) (hL : ∀ i, x.move_left (L i) ≡r y.move_left i) (hR : ∀ j, x.move_right (R j) ≡r y.move_right j) : x ≡r y := ⟨L.symm, R.symm, λ i, by simpa using hL (L.symm i), λ j, by simpa using hR (R.symm j)⟩ /-- The equivalence between left moves of `x` and `y` given by the relabelling. -/ def left_moves_equiv : Π (r : x ≡r y), x.left_moves ≃ y.left_moves | ⟨L, R, hL, hR⟩ := L @[simp] theorem mk_left_moves_equiv {x y L R hL hR} : (@relabelling.mk x y L R hL hR).left_moves_equiv = L := rfl @[simp] theorem mk'_left_moves_equiv {x y L R hL hR} : (@relabelling.mk' x y L R hL hR).left_moves_equiv = L.symm := rfl /-- The equivalence between right moves of `x` and `y` given by the relabelling. -/ def right_moves_equiv : Π (r : x ≡r y), x.right_moves ≃ y.right_moves | ⟨L, R, hL, hR⟩ := R @[simp] theorem mk_right_moves_equiv {x y L R hL hR} : (@relabelling.mk x y L R hL hR).right_moves_equiv = R := rfl @[simp] theorem mk'_right_moves_equiv {x y L R hL hR} : (@relabelling.mk' x y L R hL hR).right_moves_equiv = R.symm := rfl /-- A left move of `x` is a relabelling of a left move of `y`. -/ def move_left : ∀ (r : x ≡r y) (i : x.left_moves), x.move_left i ≡r y.move_left (r.left_moves_equiv i) | ⟨L, R, hL, hR⟩ := hL /-- A left move of `y` is a relabelling of a left move of `x`. -/ def move_left_symm : ∀ (r : x ≡r y) (i : y.left_moves), x.move_left (r.left_moves_equiv.symm i) ≡r y.move_left i | ⟨L, R, hL, hR⟩ i := by simpa using hL (L.symm i) /-- A right move of `x` is a relabelling of a right move of `y`. -/ def move_right : ∀ (r : x ≡r y) (i : x.right_moves), x.move_right i ≡r y.move_right (r.right_moves_equiv i) | ⟨L, R, hL, hR⟩ := hR /-- A right move of `y` is a relabelling of a right move of `x`. -/ def move_right_symm : ∀ (r : x ≡r y) (i : y.right_moves), x.move_right (r.right_moves_equiv.symm i) ≡r y.move_right i | ⟨L, R, hL, hR⟩ i := by simpa using hR (R.symm i) /-- The identity relabelling. -/ @[refl] def refl : Π (x : pgame), x ≡r x | x := ⟨equiv.refl _, equiv.refl _, λ i, refl _, λ j, refl _⟩ using_well_founded { dec_tac := pgame_wf_tac } instance (x : pgame) : inhabited (x ≡r x) := ⟨refl _⟩ /-- Flip a relabelling. -/ @[symm] def symm : Π {x y : pgame}, x ≡r y → y ≡r x | x y ⟨L, R, hL, hR⟩ := mk' L R (λ i, (hL i).symm) (λ j, (hR j).symm) theorem le : ∀ {x y : pgame} (r : x ≡r y), x ≤ y | x y r := le_def.2 ⟨λ i, or.inl ⟨_, (r.move_left i).le⟩, λ j, or.inr ⟨_, (r.move_right_symm j).le⟩⟩ using_well_founded { dec_tac := pgame_wf_tac } theorem ge {x y : pgame} (r : x ≡r y) : y ≤ x := r.symm.le /-- A relabelling lets us prove equivalence of games. -/ theorem equiv (r : x ≡r y) : x ≈ y := ⟨r.le, r.ge⟩ /-- Transitivity of relabelling. -/ @[trans] def trans : Π {x y z : pgame}, x ≡r y → y ≡r z → x ≡r z | x y z ⟨L₁, R₁, hL₁, hR₁⟩ ⟨L₂, R₂, hL₂, hR₂⟩ := ⟨L₁.trans L₂, R₁.trans R₂, λ i, (hL₁ i).trans (hL₂ _), λ j, (hR₁ j).trans (hR₂ _)⟩ /-- Any game without left or right moves is a relabelling of 0. -/ def is_empty (x : pgame) [is_empty x.left_moves] [is_empty x.right_moves] : x ≡r 0 := ⟨equiv.equiv_pempty _, equiv.equiv_of_is_empty _ _, is_empty_elim, is_empty_elim⟩ end relabelling theorem equiv.is_empty (x : pgame) [is_empty x.left_moves] [is_empty x.right_moves] : x ≈ 0 := (relabelling.is_empty x).equiv instance {x y : pgame} : has_coe (x ≡r y) (x ≈ y) := ⟨relabelling.equiv⟩ /-- Replace the types indexing the next moves for Left and Right by equivalent types. -/ def relabel {x : pgame} {xl' xr'} (el : xl' ≃ x.left_moves) (er : xr' ≃ x.right_moves) : pgame := ⟨xl', xr', x.move_left ∘ el, x.move_right ∘ er⟩ @[simp] lemma relabel_move_left' {x : pgame} {xl' xr'} (el : xl' ≃ x.left_moves) (er : xr' ≃ x.right_moves) (i : xl') : move_left (relabel el er) i = x.move_left (el i) := rfl @[simp] lemma relabel_move_left {x : pgame} {xl' xr'} (el : xl' ≃ x.left_moves) (er : xr' ≃ x.right_moves) (i : x.left_moves) : move_left (relabel el er) (el.symm i) = x.move_left i := by simp @[simp] lemma relabel_move_right' {x : pgame} {xl' xr'} (el : xl' ≃ x.left_moves) (er : xr' ≃ x.right_moves) (j : xr') : move_right (relabel el er) j = x.move_right (er j) := rfl @[simp] lemma relabel_move_right {x : pgame} {xl' xr'} (el : xl' ≃ x.left_moves) (er : xr' ≃ x.right_moves) (j : x.right_moves) : move_right (relabel el er) (er.symm j) = x.move_right j := by simp /-- The game obtained by relabelling the next moves is a relabelling of the original game. -/ def relabel_relabelling {x : pgame} {xl' xr'} (el : xl' ≃ x.left_moves) (er : xr' ≃ x.right_moves) : x ≡r relabel el er := relabelling.mk' el er (λ i, by simp) (λ j, by simp) /-! ### Negation -/ /-- The negation of `{L | R}` is `{-R | -L}`. -/ def neg : pgame → pgame | ⟨l, r, L, R⟩ := ⟨r, l, λ i, neg (R i), λ i, neg (L i)⟩ instance : has_neg pgame := ⟨neg⟩ @[simp] lemma neg_def {xl xr xL xR} : -(mk xl xr xL xR) = mk xr xl (λ j, -(xR j)) (λ i, -(xL i)) := rfl instance : has_involutive_neg pgame := { neg_neg := λ x, begin induction x with xl xr xL xR ihL ihR, simp_rw [neg_def, ihL, ihR], exact ⟨rfl, rfl, heq.rfl, heq.rfl⟩, end, ..pgame.has_neg } instance : neg_zero_class pgame := { neg_zero := begin dsimp [has_zero.zero, has_neg.neg, neg], congr; funext i; cases i end, ..pgame.has_zero, ..pgame.has_neg } @[simp] lemma neg_of_lists (L R : list pgame) : -of_lists L R = of_lists (R.map (λ x, -x)) (L.map (λ x, -x)) := begin simp only [of_lists, neg_def, list.length_map, list.nth_le_map', eq_self_iff_true, true_and], split, all_goals { apply hfunext, { simp }, { intros a a' ha, congr' 2, have : ∀ {m n} (h₁ : m = n) {b : ulift (fin m)} {c : ulift (fin n)} (h₂ : b == c), (b.down : ℕ) = ↑c.down, { rintros m n rfl b c rfl, refl }, exact this (list.length_map _ _).symm ha } } end theorem is_option_neg {x y : pgame} : is_option x (-y) ↔ is_option (-x) y := begin rw [is_option_iff, is_option_iff, or_comm], cases y, apply or_congr; { apply exists_congr, intro, rw neg_eq_iff_eq_neg, refl }, end @[simp] theorem is_option_neg_neg {x y : pgame} : is_option (-x) (-y) ↔ is_option x y := by rw [is_option_neg, neg_neg] theorem left_moves_neg : ∀ x : pgame, (-x).left_moves = x.right_moves | ⟨_, _, _, _⟩ := rfl theorem right_moves_neg : ∀ x : pgame, (-x).right_moves = x.left_moves | ⟨_, _, _, _⟩ := rfl /-- Turns a right move for `x` into a left move for `-x` and vice versa. Even though these types are the same (not definitionally so), this is the preferred way to convert between them. -/ def to_left_moves_neg {x : pgame} : x.right_moves ≃ (-x).left_moves := equiv.cast (left_moves_neg x).symm /-- Turns a left move for `x` into a right move for `-x` and vice versa. Even though these types are the same (not definitionally so), this is the preferred way to convert between them. -/ def to_right_moves_neg {x : pgame} : x.left_moves ≃ (-x).right_moves := equiv.cast (right_moves_neg x).symm lemma move_left_neg {x : pgame} (i) : (-x).move_left (to_left_moves_neg i) = -x.move_right i := by { cases x, refl } @[simp] lemma move_left_neg' {x : pgame} (i) : (-x).move_left i = -x.move_right (to_left_moves_neg.symm i) := by { cases x, refl } lemma move_right_neg {x : pgame} (i) : (-x).move_right (to_right_moves_neg i) = -(x.move_left i) := by { cases x, refl } @[simp] lemma move_right_neg' {x : pgame} (i) : (-x).move_right i = -x.move_left (to_right_moves_neg.symm i) := by { cases x, refl } lemma move_left_neg_symm {x : pgame} (i) : x.move_left (to_right_moves_neg.symm i) = -(-x).move_right i := by simp lemma move_left_neg_symm' {x : pgame} (i) : x.move_left i = -(-x).move_right (to_right_moves_neg i) := by simp lemma move_right_neg_symm {x : pgame} (i) : x.move_right (to_left_moves_neg.symm i) = -(-x).move_left i := by simp lemma move_right_neg_symm' {x : pgame} (i) : x.move_right i = -(-x).move_left (to_left_moves_neg i) := by simp /-- If `x` has the same moves as `y`, then `-x` has the sames moves as `-y`. -/ def relabelling.neg_congr : ∀ {x y : pgame}, x ≡r y → -x ≡r -y | ⟨xl, xr, xL, xR⟩ ⟨yl, yr, yL, yR⟩ ⟨L, R, hL, hR⟩ := ⟨R, L, λ j, (hR j).neg_congr, λ i, (hL i).neg_congr⟩ private theorem neg_le_lf_neg_iff : Π {x y : pgame.{u}}, (-y ≤ -x ↔ x ≤ y) ∧ (-y ⧏ -x ↔ x ⧏ y) | (mk xl xr xL xR) (mk yl yr yL yR) := begin simp_rw [neg_def, mk_le_mk, mk_lf_mk, ← neg_def], split, { rw and_comm, apply and_congr; exact forall_congr (λ _, neg_le_lf_neg_iff.2) }, { rw or_comm, apply or_congr; exact exists_congr (λ _, neg_le_lf_neg_iff.1) }, end using_well_founded { dec_tac := pgame_wf_tac } @[simp] theorem neg_le_neg_iff {x y : pgame} : -y ≤ -x ↔ x ≤ y := neg_le_lf_neg_iff.1 @[simp] theorem neg_lf_neg_iff {x y : pgame} : -y ⧏ -x ↔ x ⧏ y := neg_le_lf_neg_iff.2 @[simp] theorem neg_lt_neg_iff {x y : pgame} : -y < -x ↔ x < y := by rw [lt_iff_le_and_lf, lt_iff_le_and_lf, neg_le_neg_iff, neg_lf_neg_iff] @[simp] theorem neg_equiv_neg_iff {x y : pgame} : -x ≈ -y ↔ x ≈ y := by rw [equiv, equiv, neg_le_neg_iff, neg_le_neg_iff, and.comm] @[simp] theorem neg_fuzzy_neg_iff {x y : pgame} : -x ‖ -y ↔ x ‖ y := by rw [fuzzy, fuzzy, neg_lf_neg_iff, neg_lf_neg_iff, and.comm] theorem neg_le_iff {x y : pgame} : -y ≤ x ↔ -x ≤ y := by rw [←neg_neg x, neg_le_neg_iff, neg_neg] theorem neg_lf_iff {x y : pgame} : -y ⧏ x ↔ -x ⧏ y := by rw [←neg_neg x, neg_lf_neg_iff, neg_neg] theorem neg_lt_iff {x y : pgame} : -y < x ↔ -x < y := by rw [←neg_neg x, neg_lt_neg_iff, neg_neg] theorem neg_equiv_iff {x y : pgame} : -x ≈ y ↔ x ≈ -y := by rw [←neg_neg y, neg_equiv_neg_iff, neg_neg] theorem neg_fuzzy_iff {x y : pgame} : -x ‖ y ↔ x ‖ -y := by rw [←neg_neg y, neg_fuzzy_neg_iff, neg_neg] theorem le_neg_iff {x y : pgame} : y ≤ -x ↔ x ≤ -y := by rw [←neg_neg x, neg_le_neg_iff, neg_neg] theorem lf_neg_iff {x y : pgame} : y ⧏ -x ↔ x ⧏ -y := by rw [←neg_neg x, neg_lf_neg_iff, neg_neg] theorem lt_neg_iff {x y : pgame} : y < -x ↔ x < -y := by rw [←neg_neg x, neg_lt_neg_iff, neg_neg] @[simp] theorem neg_le_zero_iff {x : pgame} : -x ≤ 0 ↔ 0 ≤ x := by rw [neg_le_iff, neg_zero] @[simp] theorem zero_le_neg_iff {x : pgame} : 0 ≤ -x ↔ x ≤ 0 := by rw [le_neg_iff, neg_zero] @[simp] theorem neg_lf_zero_iff {x : pgame} : -x ⧏ 0 ↔ 0 ⧏ x := by rw [neg_lf_iff, neg_zero] @[simp] theorem zero_lf_neg_iff {x : pgame} : 0 ⧏ -x ↔ x ⧏ 0 := by rw [lf_neg_iff, neg_zero] @[simp] theorem neg_lt_zero_iff {x : pgame} : -x < 0 ↔ 0 < x := by rw [neg_lt_iff, neg_zero] @[simp] theorem zero_lt_neg_iff {x : pgame} : 0 < -x ↔ x < 0 := by rw [lt_neg_iff, neg_zero] @[simp] theorem neg_equiv_zero_iff {x : pgame} : -x ≈ 0 ↔ x ≈ 0 := by rw [neg_equiv_iff, neg_zero] @[simp] theorem neg_fuzzy_zero_iff {x : pgame} : -x ‖ 0 ↔ x ‖ 0 := by rw [neg_fuzzy_iff, neg_zero] @[simp] theorem zero_equiv_neg_iff {x : pgame} : 0 ≈ -x ↔ 0 ≈ x := by rw [←neg_equiv_iff, neg_zero] @[simp] theorem zero_fuzzy_neg_iff {x : pgame} : 0 ‖ -x ↔ 0 ‖ x := by rw [←neg_fuzzy_iff, neg_zero] /-! ### Addition and subtraction -/ /-- The sum of `x = {xL | xR}` and `y = {yL | yR}` is `{xL + y, x + yL | xR + y, x + yR}`. -/ instance : has_add pgame.{u} := ⟨λ x y, begin induction x with xl xr xL xR IHxl IHxr generalizing y, induction y with yl yr yL yR IHyl IHyr, have y := mk yl yr yL yR, refine ⟨xl ⊕ yl, xr ⊕ yr, sum.rec _ _, sum.rec _ _⟩, { exact λ i, IHxl i y }, { exact IHyl }, { exact λ i, IHxr i y }, { exact IHyr } end⟩ /-- The pre-game `((0+1)+⋯)+1`. -/ instance : has_nat_cast pgame := ⟨nat.unary_cast⟩ @[simp] protected theorem nat_succ (n : ℕ) : ((n + 1 : ℕ) : pgame) = n + 1 := rfl instance is_empty_left_moves_add (x y : pgame.{u}) [is_empty x.left_moves] [is_empty y.left_moves] : is_empty (x + y).left_moves := begin unfreezingI { cases x, cases y }, apply is_empty_sum.2 ⟨_, _⟩, assumption' end instance is_empty_right_moves_add (x y : pgame.{u}) [is_empty x.right_moves] [is_empty y.right_moves] : is_empty (x + y).right_moves := begin unfreezingI { cases x, cases y }, apply is_empty_sum.2 ⟨_, _⟩, assumption' end /-- `x + 0` has exactly the same moves as `x`. -/ def add_zero_relabelling : Π (x : pgame.{u}), x + 0 ≡r x | ⟨xl, xr, xL, xR⟩ := begin refine ⟨equiv.sum_empty xl pempty, equiv.sum_empty xr pempty, _, _⟩; rintro (⟨i⟩|⟨⟨⟩⟩); apply add_zero_relabelling end /-- `x + 0` is equivalent to `x`. -/ lemma add_zero_equiv (x : pgame.{u}) : x + 0 ≈ x := (add_zero_relabelling x).equiv /-- `0 + x` has exactly the same moves as `x`. -/ def zero_add_relabelling : Π (x : pgame.{u}), 0 + x ≡r x | ⟨xl, xr, xL, xR⟩ := begin refine ⟨equiv.empty_sum pempty xl, equiv.empty_sum pempty xr, _, _⟩; rintro (⟨⟨⟩⟩|⟨i⟩); apply zero_add_relabelling end /-- `0 + x` is equivalent to `x`. -/ lemma zero_add_equiv (x : pgame.{u}) : 0 + x ≈ x := (zero_add_relabelling x).equiv theorem left_moves_add : ∀ (x y : pgame.{u}), (x + y).left_moves = (x.left_moves ⊕ y.left_moves) | ⟨_, _, _, _⟩ ⟨_, _, _, _⟩ := rfl theorem right_moves_add : ∀ (x y : pgame.{u}), (x + y).right_moves = (x.right_moves ⊕ y.right_moves) | ⟨_, _, _, _⟩ ⟨_, _, _, _⟩ := rfl /-- Converts a left move for `x` or `y` into a left move for `x + y` and vice versa. Even though these types are the same (not definitionally so), this is the preferred way to convert between them. -/ def to_left_moves_add {x y : pgame} : x.left_moves ⊕ y.left_moves ≃ (x + y).left_moves := equiv.cast (left_moves_add x y).symm /-- Converts a right move for `x` or `y` into a right move for `x + y` and vice versa. Even though these types are the same (not definitionally so), this is the preferred way to convert between them. -/ def to_right_moves_add {x y : pgame} : x.right_moves ⊕ y.right_moves ≃ (x + y).right_moves := equiv.cast (right_moves_add x y).symm @[simp] lemma mk_add_move_left_inl {xl xr yl yr} {xL xR yL yR} {i} : (mk xl xr xL xR + mk yl yr yL yR).move_left (sum.inl i) = (mk xl xr xL xR).move_left i + (mk yl yr yL yR) := rfl @[simp] lemma add_move_left_inl {x : pgame} (y : pgame) (i) : (x + y).move_left (to_left_moves_add (sum.inl i)) = x.move_left i + y := by { cases x, cases y, refl } @[simp] lemma mk_add_move_right_inl {xl xr yl yr} {xL xR yL yR} {i} : (mk xl xr xL xR + mk yl yr yL yR).move_right (sum.inl i) = (mk xl xr xL xR).move_right i + (mk yl yr yL yR) := rfl @[simp] lemma add_move_right_inl {x : pgame} (y : pgame) (i) : (x + y).move_right (to_right_moves_add (sum.inl i)) = x.move_right i + y := by { cases x, cases y, refl } @[simp] lemma mk_add_move_left_inr {xl xr yl yr} {xL xR yL yR} {i} : (mk xl xr xL xR + mk yl yr yL yR).move_left (sum.inr i) = (mk xl xr xL xR) + (mk yl yr yL yR).move_left i := rfl @[simp] lemma add_move_left_inr (x : pgame) {y : pgame} (i) : (x + y).move_left (to_left_moves_add (sum.inr i)) = x + y.move_left i := by { cases x, cases y, refl } @[simp] lemma mk_add_move_right_inr {xl xr yl yr} {xL xR yL yR} {i} : (mk xl xr xL xR + mk yl yr yL yR).move_right (sum.inr i) = (mk xl xr xL xR) + (mk yl yr yL yR).move_right i := rfl @[simp] lemma add_move_right_inr (x : pgame) {y : pgame} (i) : (x + y).move_right (to_right_moves_add (sum.inr i)) = x + y.move_right i := by { cases x, cases y, refl } lemma left_moves_add_cases {x y : pgame} (k) {P : (x + y).left_moves → Prop} (hl : ∀ i, P $ to_left_moves_add (sum.inl i)) (hr : ∀ i, P $ to_left_moves_add (sum.inr i)) : P k := begin rw ←to_left_moves_add.apply_symm_apply k, cases to_left_moves_add.symm k with i i, { exact hl i }, { exact hr i } end lemma right_moves_add_cases {x y : pgame} (k) {P : (x + y).right_moves → Prop} (hl : ∀ j, P $ to_right_moves_add (sum.inl j)) (hr : ∀ j, P $ to_right_moves_add (sum.inr j)) : P k := begin rw ←to_right_moves_add.apply_symm_apply k, cases to_right_moves_add.symm k with i i, { exact hl i }, { exact hr i } end instance is_empty_nat_right_moves : ∀ n : ℕ, is_empty (right_moves n) | 0 := pempty.is_empty | (n + 1) := begin haveI := is_empty_nat_right_moves n, rw [pgame.nat_succ, right_moves_add], apply_instance end /-- If `w` has the same moves as `x` and `y` has the same moves as `z`, then `w + y` has the same moves as `x + z`. -/ def relabelling.add_congr : ∀ {w x y z : pgame.{u}}, w ≡r x → y ≡r z → w + y ≡r x + z | ⟨wl, wr, wL, wR⟩ ⟨xl, xr, xL, xR⟩ ⟨yl, yr, yL, yR⟩ ⟨zl, zr, zL, zR⟩ ⟨L₁, R₁, hL₁, hR₁⟩ ⟨L₂, R₂, hL₂, hR₂⟩ := begin let Hwx : ⟨wl, wr, wL, wR⟩ ≡r ⟨xl, xr, xL, xR⟩ := ⟨L₁, R₁, hL₁, hR₁⟩, let Hyz : ⟨yl, yr, yL, yR⟩ ≡r ⟨zl, zr, zL, zR⟩ := ⟨L₂, R₂, hL₂, hR₂⟩, refine ⟨equiv.sum_congr L₁ L₂, equiv.sum_congr R₁ R₂, _, _⟩; rintro (i|j), { exact (hL₁ i).add_congr Hyz }, { exact Hwx.add_congr (hL₂ j) }, { exact (hR₁ i).add_congr Hyz }, { exact Hwx.add_congr (hR₂ j) } end using_well_founded { dec_tac := pgame_wf_tac } instance : has_sub pgame := ⟨λ x y, x + -y⟩ @[simp] theorem sub_zero (x : pgame) : x - 0 = x + 0 := show x + -0 = x + 0, by rw neg_zero /-- If `w` has the same moves as `x` and `y` has the same moves as `z`, then `w - y` has the same moves as `x - z`. -/ def relabelling.sub_congr {w x y z : pgame} (h₁ : w ≡r x) (h₂ : y ≡r z) : w - y ≡r x - z := h₁.add_congr h₂.neg_congr /-- `-(x + y)` has exactly the same moves as `-x + -y`. -/ def neg_add_relabelling : Π (x y : pgame), -(x + y) ≡r -x + -y | ⟨xl, xr, xL, xR⟩ ⟨yl, yr, yL, yR⟩ := begin refine ⟨equiv.refl _, equiv.refl _, _, _⟩, all_goals { exact λ j, sum.cases_on j (λ j, neg_add_relabelling _ _) (λ j, neg_add_relabelling ⟨xl, xr, xL, xR⟩ _) } end using_well_founded { dec_tac := pgame_wf_tac } theorem neg_add_le {x y : pgame} : -(x + y) ≤ -x + -y := (neg_add_relabelling x y).le /-- `x + y` has exactly the same moves as `y + x`. -/ def add_comm_relabelling : Π (x y : pgame.{u}), x + y ≡r y + x | (mk xl xr xL xR) (mk yl yr yL yR) := begin refine ⟨equiv.sum_comm _ _, equiv.sum_comm _ _, _, _⟩; rintros (_|_); { dsimp [left_moves_add, right_moves_add], apply add_comm_relabelling } end using_well_founded { dec_tac := pgame_wf_tac } theorem add_comm_le {x y : pgame} : x + y ≤ y + x := (add_comm_relabelling x y).le theorem add_comm_equiv {x y : pgame} : x + y ≈ y + x := (add_comm_relabelling x y).equiv /-- `(x + y) + z` has exactly the same moves as `x + (y + z)`. -/ def add_assoc_relabelling : Π (x y z : pgame.{u}), x + y + z ≡r x + (y + z) | ⟨xl, xr, xL, xR⟩ ⟨yl, yr, yL, yR⟩ ⟨zl, zr, zL, zR⟩ := begin refine ⟨equiv.sum_assoc _ _ _, equiv.sum_assoc _ _ _, _, _⟩, all_goals { rintro (⟨i|i⟩|i) <|> rintro (j|⟨j|j⟩), { apply add_assoc_relabelling }, { apply add_assoc_relabelling ⟨xl, xr, xL, xR⟩ }, { apply add_assoc_relabelling ⟨xl, xr, xL, xR⟩ ⟨yl, yr, yL, yR⟩ } } end using_well_founded { dec_tac := pgame_wf_tac } theorem add_assoc_equiv {x y z : pgame} : (x + y) + z ≈ x + (y + z) := (add_assoc_relabelling x y z).equiv theorem add_left_neg_le_zero : ∀ (x : pgame), -x + x ≤ 0 | ⟨xl, xr, xL, xR⟩ := le_zero.2 $ λ i, begin cases i, { -- If Left played in -x, Right responds with the same move in x. refine ⟨@to_right_moves_add _ ⟨_, _, _, _⟩ (sum.inr i), _⟩, convert @add_left_neg_le_zero (xR i), apply add_move_right_inr }, { -- If Left in x, Right responds with the same move in -x. dsimp, refine ⟨@to_right_moves_add ⟨_, _, _, _⟩ _ (sum.inl i), _⟩, convert @add_left_neg_le_zero (xL i), apply add_move_right_inl } end theorem zero_le_add_left_neg (x : pgame) : 0 ≤ -x + x := begin rw [←neg_le_neg_iff, neg_zero], exact neg_add_le.trans (add_left_neg_le_zero _) end theorem add_left_neg_equiv (x : pgame) : -x + x ≈ 0 := ⟨add_left_neg_le_zero x, zero_le_add_left_neg x⟩ theorem add_right_neg_le_zero (x : pgame) : x + -x ≤ 0 := add_comm_le.trans (add_left_neg_le_zero x) theorem zero_le_add_right_neg (x : pgame) : 0 ≤ x + -x := (zero_le_add_left_neg x).trans add_comm_le theorem add_right_neg_equiv (x : pgame) : x + -x ≈ 0 := ⟨add_right_neg_le_zero x, zero_le_add_right_neg x⟩ theorem sub_self_equiv : ∀ x, x - x ≈ 0 := add_right_neg_equiv private lemma add_le_add_right' : ∀ {x y z : pgame} (h : x ≤ y), x + z ≤ y + z | (mk xl xr xL xR) (mk yl yr yL yR) (mk zl zr zL zR) := λ h, begin refine le_def.2 ⟨λ i, _, λ i, _⟩; cases i, { rw le_def at h, cases h, rcases h_left i with ⟨i', ih⟩ | ⟨j, jh⟩, { exact or.inl ⟨to_left_moves_add (sum.inl i'), add_le_add_right' ih⟩ }, { refine or.inr ⟨to_right_moves_add (sum.inl j), _⟩, convert add_le_add_right' jh, apply add_move_right_inl } }, { exact or.inl ⟨@to_left_moves_add _ ⟨_, _, _, _⟩ (sum.inr i), add_le_add_right' h⟩ }, { rw le_def at h, cases h, rcases h_right i with ⟨i, ih⟩ | ⟨j', jh⟩, { refine or.inl ⟨to_left_moves_add (sum.inl i), _⟩, convert add_le_add_right' ih, apply add_move_left_inl }, { exact or.inr ⟨to_right_moves_add (sum.inl j'), add_le_add_right' jh⟩ } }, { exact or.inr ⟨@to_right_moves_add _ ⟨_, _, _, _⟩ (sum.inr i), add_le_add_right' h⟩ } end using_well_founded { dec_tac := pgame_wf_tac } instance covariant_class_swap_add_le : covariant_class pgame pgame (swap (+)) (≤) := ⟨λ x y z, add_le_add_right'⟩ instance covariant_class_add_le : covariant_class pgame pgame (+) (≤) := ⟨λ x y z h, (add_comm_le.trans (add_le_add_right h x)).trans add_comm_le⟩ theorem add_lf_add_right {y z : pgame} (h : y ⧏ z) (x) : y + x ⧏ z + x := suffices z + x ≤ y + x → z ≤ y, by { rw ←pgame.not_le at ⊢ h, exact mt this h }, λ w, calc z ≤ z + 0 : (add_zero_relabelling _).symm.le ... ≤ z + (x + -x) : add_le_add_left (zero_le_add_right_neg x) _ ... ≤ z + x + -x : (add_assoc_relabelling _ _ _).symm.le ... ≤ y + x + -x : add_le_add_right w _ ... ≤ y + (x + -x) : (add_assoc_relabelling _ _ _).le ... ≤ y + 0 : add_le_add_left (add_right_neg_le_zero x) _ ... ≤ y : (add_zero_relabelling _).le theorem add_lf_add_left {y z : pgame} (h : y ⧏ z) (x) : x + y ⧏ x + z := by { rw lf_congr add_comm_equiv add_comm_equiv, apply add_lf_add_right h } instance covariant_class_swap_add_lt : covariant_class pgame pgame (swap (+)) (<) := ⟨λ x y z h, ⟨add_le_add_right h.1 x, add_lf_add_right h.2 x⟩⟩ instance covariant_class_add_lt : covariant_class pgame pgame (+) (<) := ⟨λ x y z h, ⟨add_le_add_left h.1 x, add_lf_add_left h.2 x⟩⟩ theorem add_lf_add_of_lf_of_le {w x y z : pgame} (hwx : w ⧏ x) (hyz : y ≤ z) : w + y ⧏ x + z := lf_of_lf_of_le (add_lf_add_right hwx y) (add_le_add_left hyz x) theorem add_lf_add_of_le_of_lf {w x y z : pgame} (hwx : w ≤ x) (hyz : y ⧏ z) : w + y ⧏ x + z := lf_of_le_of_lf (add_le_add_right hwx y) (add_lf_add_left hyz x) theorem add_congr {w x y z : pgame} (h₁ : w ≈ x) (h₂ : y ≈ z) : w + y ≈ x + z := ⟨(add_le_add_left h₂.1 w).trans (add_le_add_right h₁.1 z), (add_le_add_left h₂.2 x).trans (add_le_add_right h₁.2 y)⟩ theorem add_congr_left {x y z : pgame} (h : x ≈ y) : x + z ≈ y + z := add_congr h equiv_rfl theorem add_congr_right {x y z : pgame} : y ≈ z → x + y ≈ x + z := add_congr equiv_rfl theorem sub_congr {w x y z : pgame} (h₁ : w ≈ x) (h₂ : y ≈ z) : w - y ≈ x - z := add_congr h₁ (neg_equiv_neg_iff.2 h₂) theorem sub_congr_left {x y z : pgame} (h : x ≈ y) : x - z ≈ y - z := sub_congr h equiv_rfl theorem sub_congr_right {x y z : pgame} : y ≈ z → x - y ≈ x - z := sub_congr equiv_rfl theorem le_iff_sub_nonneg {x y : pgame} : x ≤ y ↔ 0 ≤ y - x := ⟨λ h, (zero_le_add_right_neg x).trans (add_le_add_right h _), λ h, calc x ≤ 0 + x : (zero_add_relabelling x).symm.le ... ≤ y - x + x : add_le_add_right h _ ... ≤ y + (-x + x) : (add_assoc_relabelling _ _ _).le ... ≤ y + 0 : add_le_add_left (add_left_neg_le_zero x) _ ... ≤ y : (add_zero_relabelling y).le⟩ theorem lf_iff_sub_zero_lf {x y : pgame} : x ⧏ y ↔ 0 ⧏ y - x := ⟨λ h, (zero_le_add_right_neg x).trans_lf (add_lf_add_right h _), λ h, calc x ≤ 0 + x : (zero_add_relabelling x).symm.le ... ⧏ y - x + x : add_lf_add_right h _ ... ≤ y + (-x + x) : (add_assoc_relabelling _ _ _).le ... ≤ y + 0 : add_le_add_left (add_left_neg_le_zero x) _ ... ≤ y : (add_zero_relabelling y).le⟩ theorem lt_iff_sub_pos {x y : pgame} : x < y ↔ 0 < y - x := ⟨λ h, lt_of_le_of_lt (zero_le_add_right_neg x) (add_lt_add_right h _), λ h, calc x ≤ 0 + x : (zero_add_relabelling x).symm.le ... < y - x + x : add_lt_add_right h _ ... ≤ y + (-x + x) : (add_assoc_relabelling _ _ _).le ... ≤ y + 0 : add_le_add_left (add_left_neg_le_zero x) _ ... ≤ y : (add_zero_relabelling y).le⟩ /-! ### Special pre-games -/ /-- The pre-game `star`, which is fuzzy with zero. -/ def star : pgame.{u} := ⟨punit, punit, λ _, 0, λ _, 0⟩ @[simp] theorem star_left_moves : star.left_moves = punit := rfl @[simp] theorem star_right_moves : star.right_moves = punit := rfl @[simp] theorem star_move_left (x) : star.move_left x = 0 := rfl @[simp] theorem star_move_right (x) : star.move_right x = 0 := rfl instance unique_star_left_moves : unique star.left_moves := punit.unique instance unique_star_right_moves : unique star.right_moves := punit.unique theorem star_fuzzy_zero : star ‖ 0 := ⟨by { rw lf_zero, use default, rintros ⟨⟩ }, by { rw zero_lf, use default, rintros ⟨⟩ }⟩ @[simp] theorem neg_star : -star = star := by simp [star] @[simp] protected theorem zero_lt_one : (0 : pgame) < 1 := lt_of_le_of_lf (zero_le_of_is_empty_right_moves 1) (zero_lf_le.2 ⟨default, le_rfl⟩) instance : zero_le_one_class pgame := ⟨pgame.zero_lt_one.le⟩ @[simp] theorem zero_lf_one : (0 : pgame) ⧏ 1 := pgame.zero_lt_one.lf end pgame
b781b38bc1d7c7235b611cbe17c4b87e640705c6
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/analysis/inner_product_space/rayleigh.lean
d9235f68c7081682a09e5f3b85a80734402353f4
[ "Apache-2.0" ]
permissive
AntoineChambert-Loir/mathlib
64aabb896129885f12296a799818061bc90da1ff
07be904260ab6e36a5769680b6012f03a4727134
refs/heads/master
1,693,187,631,771
1,636,719,886,000
1,636,719,886,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
12,319
lean
/- Copyright (c) 2021 Heather Macbeth. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Heather Macbeth, Frédéric Dupuis -/ import analysis.inner_product_space.calculus import analysis.inner_product_space.dual import analysis.calculus.lagrange_multipliers import linear_algebra.eigenspace /-! # The Rayleigh quotient The Rayleigh quotient of a self-adjoint operator `T` on an inner product space `E` is the function `λ x, ⟪T x, x⟫ / ∥x∥ ^ 2`. The main results of this file are `is_self_adjoint.has_eigenvector_of_is_max_on` and `is_self_adjoint.has_eigenvector_of_is_min_on`, which state that if `E` is complete, and if the Rayleigh quotient attains its global maximum/minimum over some sphere at the point `x₀`, then `x₀` is an eigenvector of `T`, and the `supr`/`infi` of `λ x, ⟪T x, x⟫ / ∥x∥ ^ 2` is the corresponding eigenvalue. The corollaries `is_self_adjoint.has_eigenvalue_supr_of_finite_dimensional` and `is_self_adjoint.has_eigenvalue_supr_of_finite_dimensional` state that if `E` is finite-dimensional and nontrivial, then `T` has some (nonzero) eigenvectors with eigenvalue the `supr`/`infi` of `λ x, ⟪T x, x⟫ / ∥x∥ ^ 2`. ## TODO A slightly more elaborate corollary is that if `E` is complete and `T` is a compact operator, then `T` has some (nonzero) eigenvector with eigenvalue either `⨆ x, ⟪T x, x⟫ / ∥x∥ ^ 2` or `⨅ x, ⟪T x, x⟫ / ∥x∥ ^ 2` (not necessarily both). -/ variables {𝕜 : Type*} [is_R_or_C 𝕜] variables {E : Type*} [inner_product_space 𝕜 E] local notation `⟪`x`, `y`⟫` := @inner 𝕜 _ _ x y open_locale nnreal open module.End metric namespace continuous_linear_map variables (T : E →L[𝕜] E) local notation `rayleigh_quotient` := λ x : E, T.re_apply_inner_self x / ∥(x:E)∥ ^ 2 lemma rayleigh_smul (x : E) {c : 𝕜} (hc : c ≠ 0) : rayleigh_quotient (c • x) = rayleigh_quotient x := begin by_cases hx : x = 0, { simp [hx] }, have : ∥c∥ ≠ 0 := by simp [hc], have : ∥x∥ ≠ 0 := by simp [hx], field_simp [norm_smul, T.re_apply_inner_self_smul], ring end lemma image_rayleigh_eq_image_rayleigh_sphere {r : ℝ} (hr : 0 < r) : rayleigh_quotient '' {0}ᶜ = rayleigh_quotient '' (sphere 0 r) := begin ext a, split, { rintros ⟨x, (hx : x ≠ 0), hxT⟩, have : ∥x∥ ≠ 0 := by simp [hx], let c : 𝕜 := ↑∥x∥⁻¹ * r, have : c ≠ 0 := by simp [c, hx, hr.ne'], refine ⟨c • x, _, _⟩, { field_simp [norm_smul, is_R_or_C.norm_eq_abs, abs_of_nonneg hr.le] }, { rw T.rayleigh_smul x this, exact hxT } }, { rintros ⟨x, hx, hxT⟩, exact ⟨x, nonzero_of_mem_sphere hr ⟨x, hx⟩, hxT⟩ }, end lemma supr_rayleigh_eq_supr_rayleigh_sphere {r : ℝ} (hr : 0 < r) : (⨆ x : {x : E // x ≠ 0}, rayleigh_quotient x) = ⨆ x : sphere (0:E) r, rayleigh_quotient x := show (⨆ x : ({0} : set E)ᶜ, rayleigh_quotient x) = _, by simp only [@csupr_set _ _ _ _ rayleigh_quotient, T.image_rayleigh_eq_image_rayleigh_sphere hr] lemma infi_rayleigh_eq_infi_rayleigh_sphere {r : ℝ} (hr : 0 < r) : (⨅ x : {x : E // x ≠ 0}, rayleigh_quotient x) = ⨅ x : sphere (0:E) r, rayleigh_quotient x := show (⨅ x : ({0} : set E)ᶜ, rayleigh_quotient x) = _, by simp only [@cinfi_set _ _ _ _ rayleigh_quotient, T.image_rayleigh_eq_image_rayleigh_sphere hr] end continuous_linear_map namespace is_self_adjoint section real variables {F : Type*} [inner_product_space ℝ F] lemma has_strict_fderiv_at_re_apply_inner_self {T : F →L[ℝ] F} (hT : is_self_adjoint (T : F →ₗ[ℝ] F)) (x₀ : F) : has_strict_fderiv_at T.re_apply_inner_self (bit0 (inner_right (T x₀))) x₀ := begin convert T.has_strict_fderiv_at.inner (has_strict_fderiv_at_id x₀), ext y, simp [bit0, hT.apply_clm x₀ y, real_inner_comm x₀] end variables [complete_space F] {T : F →L[ℝ] F} local notation `rayleigh_quotient` := λ x : F, T.re_apply_inner_self x / ∥(x:F)∥ ^ 2 lemma linearly_dependent_of_is_local_extr_on (hT : is_self_adjoint (T : F →ₗ[ℝ] F)) {x₀ : F} (hextr : is_local_extr_on T.re_apply_inner_self (sphere (0:F) ∥x₀∥) x₀) : ∃ a b : ℝ, (a, b) ≠ 0 ∧ a • x₀ + b • T x₀ = 0 := begin have H : is_local_extr_on T.re_apply_inner_self {x : F | ∥x∥ ^ 2 = ∥x₀∥ ^ 2} x₀, { convert hextr, ext x, simp [dist_eq_norm] }, -- find Lagrange multipliers for the function `T.re_apply_inner_self` and the -- hypersurface-defining function `λ x, ∥x∥ ^ 2` obtain ⟨a, b, h₁, h₂⟩ := is_local_extr_on.exists_multipliers_of_has_strict_fderiv_at_1d H (has_strict_fderiv_at_norm_sq x₀) (hT.has_strict_fderiv_at_re_apply_inner_self x₀), refine ⟨a, b, h₁, _⟩, apply (inner_product_space.to_dual_map ℝ F).injective, simp only [linear_isometry.map_add, linear_isometry.map_smul, linear_isometry.map_zero], change a • inner_right x₀ + b • inner_right (T x₀) = 0, apply smul_right_injective (F →L[ℝ] ℝ) (two_ne_zero : (2:ℝ) ≠ 0), simpa only [bit0, add_smul, smul_add, one_smul, add_zero] using h₂ end lemma eq_smul_self_of_is_local_extr_on_real (hT : is_self_adjoint (T : F →ₗ[ℝ] F)) {x₀ : F} (hextr : is_local_extr_on T.re_apply_inner_self (sphere (0:F) ∥x₀∥) x₀) : T x₀ = (rayleigh_quotient x₀) • x₀ := begin obtain ⟨a, b, h₁, h₂⟩ := hT.linearly_dependent_of_is_local_extr_on hextr, by_cases hx₀ : x₀ = 0, { simp [hx₀] }, by_cases hb : b = 0, { have : a ≠ 0 := by simpa [hb] using h₁, refine absurd _ hx₀, apply smul_right_injective F this, simpa [hb] using h₂ }, let c : ℝ := - b⁻¹ * a, have hc : T x₀ = c • x₀, { have : b * (b⁻¹ * a) = a := by field_simp [mul_comm], apply smul_right_injective F hb, simp [c, ← neg_eq_of_add_eq_zero h₂, ← mul_smul, this] }, convert hc, have : ∥x₀∥ ≠ 0 := by simp [hx₀], field_simp, simpa [inner_smul_left, real_inner_self_eq_norm_mul_norm, sq] using congr_arg (λ x, ⟪x, x₀⟫_ℝ) hc, end end real section complete_space variables [complete_space E] {T : E →L[𝕜] E} local notation `rayleigh_quotient` := λ x : E, T.re_apply_inner_self x / ∥(x:E)∥ ^ 2 lemma eq_smul_self_of_is_local_extr_on (hT : is_self_adjoint (T : E →ₗ[𝕜] E)) {x₀ : E} (hextr : is_local_extr_on T.re_apply_inner_self (sphere (0:E) ∥x₀∥) x₀) : T x₀ = (↑(rayleigh_quotient x₀) : 𝕜) • x₀ := begin letI := inner_product_space.is_R_or_C_to_real 𝕜 E, letI : is_scalar_tower ℝ 𝕜 E := restrict_scalars.is_scalar_tower _ _ _, let S : E →L[ℝ] E := @continuous_linear_map.restrict_scalars 𝕜 E E _ _ _ _ _ _ _ ℝ _ _ _ _ T, have hSA : is_self_adjoint (S : E →ₗ[ℝ] E) := λ x y, by { have := hT x y, simp only [continuous_linear_map.coe_coe] at this, simp only [real_inner_eq_re_inner, this, continuous_linear_map.coe_restrict_scalars, continuous_linear_map.coe_coe, linear_map.coe_restrict_scalars_eq_coe] }, exact eq_smul_self_of_is_local_extr_on_real hSA hextr, end /-- For a self-adjoint operator `T`, a local extremum of the Rayleigh quotient of `T` on a sphere centred at the origin is an eigenvector of `T`. -/ lemma has_eigenvector_of_is_local_extr_on (hT : is_self_adjoint (T : E →ₗ[𝕜] E)) {x₀ : E} (hx₀ : x₀ ≠ 0) (hextr : is_local_extr_on T.re_apply_inner_self (sphere (0:E) ∥x₀∥) x₀) : has_eigenvector (T : E →ₗ[𝕜] E) ↑(rayleigh_quotient x₀) x₀ := begin refine ⟨_, hx₀⟩, rw module.End.mem_eigenspace_iff, exact hT.eq_smul_self_of_is_local_extr_on hextr end /-- For a self-adjoint operator `T`, a maximum of the Rayleigh quotient of `T` on a sphere centred at the origin is an eigenvector of `T`, with eigenvalue the global supremum of the Rayleigh quotient. -/ lemma has_eigenvector_of_is_max_on (hT : is_self_adjoint (T : E →ₗ[𝕜] E)) {x₀ : E} (hx₀ : x₀ ≠ 0) (hextr : is_max_on T.re_apply_inner_self (sphere (0:E) ∥x₀∥) x₀) : has_eigenvector (T : E →ₗ[𝕜] E) ↑(⨆ x : {x : E // x ≠ 0}, rayleigh_quotient x) x₀ := begin convert hT.has_eigenvector_of_is_local_extr_on hx₀ (or.inr hextr.localize), have hx₀' : 0 < ∥x₀∥ := by simp [hx₀], have hx₀'' : x₀ ∈ sphere (0:E) (∥x₀∥) := by simp, rw T.supr_rayleigh_eq_supr_rayleigh_sphere hx₀', refine is_max_on.supr_eq hx₀'' _, intros x hx, dsimp, have : ∥x∥ = ∥x₀∥ := by simpa using hx, rw this, exact div_le_div_of_le (sq_nonneg ∥x₀∥) (hextr hx) end /-- For a self-adjoint operator `T`, a minimum of the Rayleigh quotient of `T` on a sphere centred at the origin is an eigenvector of `T`, with eigenvalue the global infimum of the Rayleigh quotient. -/ lemma has_eigenvector_of_is_min_on (hT : is_self_adjoint (T : E →ₗ[𝕜] E)) {x₀ : E} (hx₀ : x₀ ≠ 0) (hextr : is_min_on T.re_apply_inner_self (sphere (0:E) ∥x₀∥) x₀) : has_eigenvector (T : E →ₗ[𝕜] E) ↑(⨅ x : {x : E // x ≠ 0}, rayleigh_quotient x) x₀ := begin convert hT.has_eigenvector_of_is_local_extr_on hx₀ (or.inl hextr.localize), have hx₀' : 0 < ∥x₀∥ := by simp [hx₀], have hx₀'' : x₀ ∈ sphere (0:E) (∥x₀∥) := by simp, rw T.infi_rayleigh_eq_infi_rayleigh_sphere hx₀', refine is_min_on.infi_eq hx₀'' _, intros x hx, dsimp, have : ∥x∥ = ∥x₀∥ := by simpa using hx, rw this, exact div_le_div_of_le (sq_nonneg ∥x₀∥) (hextr hx) end end complete_space section finite_dimensional variables [finite_dimensional 𝕜 E] [nontrivial E] {T : E →ₗ[𝕜] E} /-- The supremum of the Rayleigh quotient of a self-adjoint operator `T` on a nontrivial finite-dimensional vector space is an eigenvalue for that operator. -/ lemma has_eigenvalue_supr_of_finite_dimensional (hT : is_self_adjoint T) : has_eigenvalue T ↑(⨆ x : {x : E // x ≠ 0}, is_R_or_C.re ⟪T x, x⟫ / ∥(x:E)∥ ^ 2) := begin let T' : E →L[𝕜] E := T.to_continuous_linear_map, have hT' : is_self_adjoint (T' : E →ₗ[𝕜] E) := hT, obtain ⟨x, hx⟩ : ∃ x : E, x ≠ 0 := exists_ne 0, have H₁ : is_compact (sphere (0:E) ∥x∥) := is_compact_sphere _ _, have H₂ : (sphere (0:E) ∥x∥).nonempty := ⟨x, by simp⟩, -- key point: in finite dimension, a continuous function on the sphere has a max obtain ⟨x₀, hx₀', hTx₀⟩ := H₁.exists_forall_ge H₂ T'.re_apply_inner_self_continuous.continuous_on, have hx₀ : ∥x₀∥ = ∥x∥ := by simpa using hx₀', have : is_max_on T'.re_apply_inner_self (sphere 0 ∥x₀∥) x₀, { simpa only [← hx₀] using hTx₀ }, have hx₀_ne : x₀ ≠ 0, { have : ∥x₀∥ ≠ 0 := by simp only [hx₀, norm_eq_zero, hx, ne.def, not_false_iff], simpa [← norm_eq_zero, ne.def] }, exact has_eigenvalue_of_has_eigenvector (hT'.has_eigenvector_of_is_max_on hx₀_ne this) end /-- The infimum of the Rayleigh quotient of a self-adjoint operator `T` on a nontrivial finite-dimensional vector space is an eigenvalue for that operator. -/ lemma has_eigenvalue_infi_of_finite_dimensional (hT : is_self_adjoint T) : has_eigenvalue T ↑(⨅ x : {x : E // x ≠ 0}, is_R_or_C.re ⟪T x, x⟫ / ∥(x:E)∥ ^ 2) := begin let T' : E →L[𝕜] E := T.to_continuous_linear_map, have hT' : is_self_adjoint (T' : E →ₗ[𝕜] E) := hT, obtain ⟨x, hx⟩ : ∃ x : E, x ≠ 0 := exists_ne 0, have H₁ : is_compact (sphere (0:E) ∥x∥) := is_compact_sphere _ _, have H₂ : (sphere (0:E) ∥x∥).nonempty := ⟨x, by simp⟩, -- key point: in finite dimension, a continuous function on the sphere has a min obtain ⟨x₀, hx₀', hTx₀⟩ := H₁.exists_forall_le H₂ T'.re_apply_inner_self_continuous.continuous_on, have hx₀ : ∥x₀∥ = ∥x∥ := by simpa using hx₀', have : is_min_on T'.re_apply_inner_self (sphere 0 ∥x₀∥) x₀, { simpa only [← hx₀] using hTx₀ }, have hx₀_ne : x₀ ≠ 0, { have : ∥x₀∥ ≠ 0 := by simp only [hx₀, norm_eq_zero, hx, ne.def, not_false_iff], simpa [← norm_eq_zero, ne.def] }, exact has_eigenvalue_of_has_eigenvector (hT'.has_eigenvector_of_is_min_on hx₀_ne this) end end finite_dimensional end is_self_adjoint
221585ed97ab6c167fb899aaa9f7654884baf83f
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/algebra/category/Group/colimits_auto.lean
c34f9772b875ba733868674718f535c6ab54b714
[]
no_license
AurelienSaue/Mathlib4_auto
f538cfd0980f65a6361eadea39e6fc639e9dae14
590df64109b08190abe22358fabc3eae000943f2
refs/heads/master
1,683,906,849,776
1,622,564,669,000
1,622,564,669,000
371,723,747
0
0
null
null
null
null
UTF-8
Lean
false
false
10,660
lean
/- Copyright (c) 2019 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.algebra.category.Group.preadditive import Mathlib.group_theory.quotient_group import Mathlib.category_theory.limits.limits import Mathlib.category_theory.limits.concrete_category import Mathlib.category_theory.limits.shapes.kernels import Mathlib.category_theory.limits.shapes.concrete_category import Mathlib.PostPort universes v l u_1 namespace Mathlib /-! # The category of additive commutative groups has all colimits. This file uses a "pre-automated" approach, just as for `Mon/colimits.lean`. It is a very uniform approach, that conceivably could be synthesised directly by a tactic that analyses the shape of `add_comm_group` and `monoid_hom`. TODO: In fact, in `AddCommGroup` there is a much nicer model of colimits as quotients of finitely supported functions, and we really should implement this as well (or instead). -/ -- [ROBOT VOICE]: -- You should pretend for now that this file was automatically generated. -- It follows the same template as colimits in Mon. namespace AddCommGroup.colimits /-! We build the colimit of a diagram in `AddCommGroup` by constructing the free group on the disjoint union of all the abelian groups in the diagram, then taking the quotient by the abelian group laws within each abelian group, and the identifications given by the morphisms in the diagram. -/ /-- An inductive type representing all group expressions (without relations) on a collection of types indexed by the objects of `J`. -/ -- There's always `of` inductive prequotient {J : Type v} [category_theory.small_category J] (F : J ⥤ AddCommGroup) where | of : (j : J) → ↥(category_theory.functor.obj F j) → prequotient F | zero : prequotient F | neg : prequotient F → prequotient F | add : prequotient F → prequotient F → prequotient F -- Then one generator for each operation protected instance prequotient.inhabited {J : Type v} [category_theory.small_category J] (F : J ⥤ AddCommGroup) : Inhabited (prequotient F) := { default := prequotient.zero } /-- The relation on `prequotient` saying when two expressions are equal because of the abelian group laws, or because one element is mapped to another by a morphism in the diagram. -/ -- Make it an equivalence relation: inductive relation {J : Type v} [category_theory.small_category J] (F : J ⥤ AddCommGroup) : prequotient F → prequotient F → Prop where | refl : ∀ (x : prequotient F), relation F x x | symm : ∀ (x y : prequotient F), relation F x y → relation F y x | trans : ∀ (x y z : prequotient F), relation F x y → relation F y z → relation F x z | map : ∀ (j j' : J) (f : j ⟶ j') (x : ↥(category_theory.functor.obj F j)), relation F (prequotient.of j' (coe_fn (category_theory.functor.map F f) x)) (prequotient.of j x) | zero : ∀ (j : J), relation F (prequotient.of j 0) prequotient.zero | neg : ∀ (j : J) (x : ↥(category_theory.functor.obj F j)), relation F (prequotient.of j (-x)) (prequotient.neg (prequotient.of j x)) | add : ∀ (j : J) (x y : ↥(category_theory.functor.obj F j)), relation F (prequotient.of j (x + y)) (prequotient.add (prequotient.of j x) (prequotient.of j y)) | neg_1 : ∀ (x x' : prequotient F), relation F x x' → relation F (prequotient.neg x) (prequotient.neg x') | add_1 : ∀ (x x' y : prequotient F), relation F x x' → relation F (prequotient.add x y) (prequotient.add x' y) | add_2 : ∀ (x y y' : prequotient F), relation F y y' → relation F (prequotient.add x y) (prequotient.add x y') | zero_add : ∀ (x : prequotient F), relation F (prequotient.add prequotient.zero x) x | add_zero : ∀ (x : prequotient F), relation F (prequotient.add x prequotient.zero) x | add_left_neg : ∀ (x : prequotient F), relation F (prequotient.add (prequotient.neg x) x) prequotient.zero | add_comm : ∀ (x y : prequotient F), relation F (prequotient.add x y) (prequotient.add y x) | add_assoc : ∀ (x y z : prequotient F), relation F (prequotient.add (prequotient.add x y) z) (prequotient.add x (prequotient.add y z)) -- There's always a `map` relation -- Then one relation per operation, describing the interaction with `of` -- Then one relation per argument of each operation -- And one relation per axiom /-- The setoid corresponding to group expressions modulo abelian group relations and identifications. -/ instance colimit_setoid {J : Type v} [category_theory.small_category J] (F : J ⥤ AddCommGroup) : setoid (prequotient F) := setoid.mk (relation F) sorry /-- The underlying type of the colimit of a diagram in `AddCommGroup`. -/ def colimit_type {J : Type v} [category_theory.small_category J] (F : J ⥤ AddCommGroup) := quotient (colimit_setoid F) protected instance colimit_type.add_comm_group {J : Type v} [category_theory.small_category J] (F : J ⥤ AddCommGroup) : add_comm_group (colimit_type F) := add_comm_group.mk (Quot.lift (fun (x : prequotient F) => Quot.lift (fun (y : prequotient F) => Quot.mk setoid.r (prequotient.add x y)) sorry) sorry) sorry (Quot.mk setoid.r prequotient.zero) sorry sorry (Quot.lift (fun (x : prequotient F) => Quot.mk setoid.r (prequotient.neg x)) sorry) (add_group.sub._default (Quot.lift (fun (x : prequotient F) => Quot.lift (fun (y : prequotient F) => Quot.mk setoid.r (prequotient.add x y)) sorry) sorry) sorry (Quot.mk setoid.r prequotient.zero) sorry sorry (Quot.lift (fun (x : prequotient F) => Quot.mk setoid.r (prequotient.neg x)) sorry)) sorry sorry @[simp] theorem quot_zero {J : Type v} [category_theory.small_category J] (F : J ⥤ AddCommGroup) : Quot.mk setoid.r prequotient.zero = 0 := rfl @[simp] theorem quot_neg {J : Type v} [category_theory.small_category J] (F : J ⥤ AddCommGroup) (x : prequotient F) : Quot.mk setoid.r (prequotient.neg x) = -Quot.mk setoid.r x := rfl @[simp] theorem quot_add {J : Type v} [category_theory.small_category J] (F : J ⥤ AddCommGroup) (x : prequotient F) (y : prequotient F) : Quot.mk setoid.r (prequotient.add x y) = Quot.mk setoid.r x + Quot.mk setoid.r y := rfl /-- The bundled abelian group giving the colimit of a diagram. -/ def colimit {J : Type v} [category_theory.small_category J] (F : J ⥤ AddCommGroup) : AddCommGroup := of (colimit_type F) /-- The function from a given abelian group in the diagram to the colimit abelian group. -/ def cocone_fun {J : Type v} [category_theory.small_category J] (F : J ⥤ AddCommGroup) (j : J) (x : ↥(category_theory.functor.obj F j)) : colimit_type F := Quot.mk setoid.r (prequotient.of j x) /-- The group homomorphism from a given abelian group in the diagram to the colimit abelian group. -/ def cocone_morphism {J : Type v} [category_theory.small_category J] (F : J ⥤ AddCommGroup) (j : J) : category_theory.functor.obj F j ⟶ colimit F := add_monoid_hom.mk (cocone_fun F j) sorry sorry @[simp] theorem cocone_naturality {J : Type v} [category_theory.small_category J] (F : J ⥤ AddCommGroup) {j : J} {j' : J} (f : j ⟶ j') : category_theory.functor.map F f ≫ cocone_morphism F j' = cocone_morphism F j := ext (category_theory.functor.obj F j) (colimit F) (category_theory.functor.map F f ≫ cocone_morphism F j') (cocone_morphism F j) fun (x : ↥(category_theory.functor.obj F j)) => quot.sound (relation.map j j' f x) @[simp] theorem cocone_naturality_components {J : Type v} [category_theory.small_category J] (F : J ⥤ AddCommGroup) (j : J) (j' : J) (f : j ⟶ j') (x : ↥(category_theory.functor.obj F j)) : coe_fn (cocone_morphism F j') (coe_fn (category_theory.functor.map F f) x) = coe_fn (cocone_morphism F j) x := sorry /-- The cocone over the proposed colimit abelian group. -/ def colimit_cocone {J : Type v} [category_theory.small_category J] (F : J ⥤ AddCommGroup) : category_theory.limits.cocone F := category_theory.limits.cocone.mk (colimit F) (category_theory.nat_trans.mk (cocone_morphism F)) /-- The function from the free abelian group on the diagram to the cone point of any other cocone. -/ @[simp] def desc_fun_lift {J : Type v} [category_theory.small_category J] (F : J ⥤ AddCommGroup) (s : category_theory.limits.cocone F) : prequotient F → ↥(category_theory.limits.cocone.X s) := sorry /-- The function from the colimit abelian group to the cone point of any other cocone. -/ def desc_fun {J : Type v} [category_theory.small_category J] (F : J ⥤ AddCommGroup) (s : category_theory.limits.cocone F) : colimit_type F → ↥(category_theory.limits.cocone.X s) := Quot.lift (desc_fun_lift F s) sorry /-- The group homomorphism from the colimit abelian group to the cone point of any other cocone. -/ def desc_morphism {J : Type v} [category_theory.small_category J] (F : J ⥤ AddCommGroup) (s : category_theory.limits.cocone F) : colimit F ⟶ category_theory.limits.cocone.X s := add_monoid_hom.mk (desc_fun F s) sorry sorry /-- Evidence that the proposed colimit is the colimit. -/ def colimit_cocone_is_colimit {J : Type v} [category_theory.small_category J] (F : J ⥤ AddCommGroup) : category_theory.limits.is_colimit (colimit_cocone F) := category_theory.limits.is_colimit.mk fun (s : category_theory.limits.cocone F) => desc_morphism F s protected instance has_colimits_AddCommGroup : category_theory.limits.has_colimits AddCommGroup := category_theory.limits.has_colimits.mk fun (J : Type u_1) (𝒥 : category_theory.small_category J) => category_theory.limits.has_colimits_of_shape.mk fun (F : J ⥤ AddCommGroup) => category_theory.limits.has_colimit.mk (category_theory.limits.colimit_cocone.mk (colimit_cocone F) (colimit_cocone_is_colimit F)) end AddCommGroup.colimits namespace AddCommGroup /-- The categorical cokernel of a morphism in `AddCommGroup` agrees with the usual group-theoretical quotient. -/ def cokernel_iso_quotient {G : AddCommGroup} {H : AddCommGroup} (f : G ⟶ H) : category_theory.limits.cokernel f ≅ of (quotient_add_group.quotient (add_monoid_hom.range f)) := category_theory.iso.mk (category_theory.limits.cokernel.desc f (quotient_add_group.mk' (add_monoid_hom.range f)) sorry) (add_monoid_hom.of ⇑(quotient_add_group.lift (add_monoid_hom.range f) (category_theory.limits.cokernel.π f) sorry)) end Mathlib
252294695456d95950ee64db675604e63c779733
a81826cfd4fd71c797ea79b8e827b03ccb332c17
/src/wonky_sq/addition_formulae.lean
b03649c53cd289d5af09c8e0694a7b8d6ba43c94
[ "Apache-2.0" ]
permissive
jamesa9283/Generalised-Trigonometric-Functions-for-Lean
0a0f4774363c3708be466526935c6d07f4b970f0
33775fb8286eacfc17397fe41af9d446cbdd78f3
refs/heads/master
1,669,337,232,958
1,597,061,947,000
1,597,061,947,000
276,104,804
0
0
null
1,593,540,795,000
1,593,523,262,000
Lean
UTF-8
Lean
false
false
4,716
lean
import tactic import data.real.basic data.int.basic init.data.int.basic import data.complex.exponential import analysis.special_functions.trigonometric -- local imports import wonky_sq.basic open real /- 033 Let us try to prove some stuff just about radius (x + y), just to make it easier tp rove 032 -/ @[simp] lemma radius_add (a b m : ℝ) : radius (a + b) m = 1 / (|sin a * cos b + cos a * sin b| ^ m + |cos a * cos b - sin a * sin b| ^ m) ^ (1 / m) := begin unfold radius, rw [sin_add, cos_add], ---- rw pow_abs (sin a * cos b + cos a * sin b) m, end /- 031 Let us do the cosₘ x addition formula -/ -- Thanks, I hate it. @[simp] lemma cosm_add ( x y m : ℝ) : cosm (x + y) m = (cos x * cos y - sin x * sin y) / (|cos x * cos y - sin x * sin y| ^ m + |sin x * cos y + cos x * sin y|^m)^ (1/m) := begin unfold cosm, rw [radius_add, cos_add], simp, rw div_eq_inv_mul, rw [mul_comm, add_comm], -- nah, this is yuck. I think this is the most cursed thing in lean. -- it's worse. -- What have I proved: That this definition is just awful. end -- that worked?!? No errors! /- 032 Now, for the sinₘ x one! -/ @[simp] lemma sinm_add (x y m : ℝ) : sinm (x + y) m = (sin x * cos y + cos x * sin y)/(|cos x * cos y - sin x * sin y|^m + |sin x * cos y + cos x * sin y|^m)^(1/m) := begin unfold sinm, rw [radius_add, sin_add], simp, rw div_eq_inv_mul, rw [mul_comm, add_comm], end /- 035 -/ @[simp] lemma sinm_2x (x m : ℝ) : sinm (2*x) m = (2 * sin x * cos x) / (|(cos x) ^2 - (sin x) ^2| ^ m + |2 * sin x * cos x|^m)^ (1/m) := begin rw [mul_comm, mul_two, sinm_add]; repeat {rw [mul_comm, ←mul_two, ←pow_two, ←pow_two]}, rw [mul_comm], rw mul_assoc, rw mul_comm (sin x) (cos x), end /- 036 -/ @[simp] lemma cosm_2x (x m : ℝ) : cosm (2*x) m = ((cos x) ^ 2 - (sin x) ^ 2) / (|(cos x) ^2 - (sin x) ^2| ^ m + |2 * sin x * cos x|^m)^ (1/m) := begin rw [mul_comm, mul_two, cosm_add]; repeat {rw [←pow_two]}, rw [mul_comm (sin x) (cos x), ←mul_two], rw [mul_comm (cos x) (sin x), mul_comm (sin x * cos x) 2, mul_assoc], end /- 036 -/ @[simp] lemma sinm_sub (x m y : ℝ) : sinm (x - y) m = (sin x * cos y - cos x * sin y)/(|cos x * cos y + sin x * sin y|^m + |sin x * cos y - cos x * sin y|^m)^(1/m) := begin rw sub_eq_add_neg, rw [sinm_add x (-y), cos_neg, sin_neg], repeat {rw ←neg_mul_eq_mul_neg}, rw [one_div_eq_inv, sub_neg_eq_add], ring, end /- 039 -/ @[simp] lemma cosm_sub (x m y : ℝ) : cosm (x - y) m = (cos x * cos y + sin x * sin y) / (|cos x * cos y + sin x * sin y| ^ m + |sin x * cos y - cos x * sin y|^m)^ (1/m) := begin rw sub_eq_add_neg, rw [cosm_add x (-y), cos_neg, sin_neg], repeat {rw ←neg_mul_eq_mul_neg}, rw [one_div_eq_inv, sub_neg_eq_add], ring, end /- 043 -/ @[simp] lemma cosm_sq_plus_sinm_sq (x m : ℝ) : cosm x m ^ 2 + sinm x m ^ 2 = radius x m ^ 2 := begin unfold sinm cosm, ring, rw [mul_comm (sin x ^2), ←mul_add (radius x m ^2) (cos x ^ 2) (sin x ^2), add_comm, sin_sq_add_cos_sq x, mul_one], end /- 045 -/ @[simp] lemma radius_nonneg (x m : ℝ) : 0 ≤ radius x m := begin unfold radius, ring, rw inv_nonneg, rw ←inv_eq_one_div, apply rpow_nonneg_of_nonneg, apply add_nonneg, repeat {apply rpow_nonneg_of_nonneg, apply abs_nonneg}, end @[simp] lemma abs_radius_eq_radius (x m : ℝ) (H: 0 ≤ radius x m): |radius x m| = radius x m := abs_of_nonneg H lemma cos_zero_im_sin_one (x : ℝ) (F : 0 ≤ sin x) : cos x = 0 → sin x = 1 := begin have H : sin x ^ 2 + cos x ^2 = 1, {rw sin_sq_add_cos_sq}, intros, { rw a at H, norm_num at H, apply_fun sqrt at H, rw sqrt_sqr at H, rw sqrt_one at H, rw H, exact F, }, end /- 044 -/ lemma cosm_powm_plus_sinm_powm (m n x : ℝ) (H : m ≠ 0) (F : 0 ≤ sin x) : |sinm x m|^m + |cosm x m|^m = 1 := begin unfold sinm cosm, repeat {rw [abs_mul, mul_rpow]}, repeat{apply abs_nonneg,}, --have H : radius_nonneg, rw abs_radius_eq_radius, rw ←add_mul, rw radius_powm m x m, rw ←div_eq_mul_one_div, rw div_self, { -- this looks like hell by_cases h : cos x = 0, { have fs : |sin x| = 1, { have f := sin_sq_add_cos_sq x, rw [h] at f, norm_num at f, apply_fun sqrt at f, rw [sqrt_sqr_eq_abs, sqrt_one] at f, exact f, }, { rw [h, fs, abs_zero, zero_rpow], norm_num, exact H, }, }, { have hcpos : 0 < | cos x | ^ m := rpow_pos_of_pos (abs_pos_of_ne_zero h) _, have hsnn : 0 ≤ | sin x | ^ m := rpow_nonneg_of_nonneg (abs_nonneg _) _, linarith, }, }, {exact H}, {apply radius_nonneg}, end
e1b9ad0d0957e9af6133b1c5676d02321902c160
9dd3f3912f7321eb58ee9aa8f21778ad6221f87c
/tests/lean/run/sub.lean
27c58e054da61be6c82da6334e5b4ec875020dcc
[ "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
63
lean
check { x : nat // x > 0 } check { x : nat → nat // true }
facd08b30b6c47ca0bb477b267e329ebdcc1f840
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/analysis/inner_product_space/projection.lean
3e772563a58544d3fac57fd81d7ecf71cfbafde9
[ "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
64,043
lean
/- Copyright (c) 2019 Zhouhang Zhou. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Zhouhang Zhou, Frédéric Dupuis, Heather Macbeth -/ import algebra.direct_sum.decomposition import analysis.convex.basic import analysis.inner_product_space.orthogonal import analysis.inner_product_space.symmetric import analysis.normed_space.is_R_or_C import data.is_R_or_C.lemmas /-! # The orthogonal projection > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. Given a nonempty complete subspace `K` of an inner product space `E`, this file constructs `orthogonal_projection K : E →L[𝕜] K`, the orthogonal projection of `E` onto `K`. This map satisfies: for any point `u` in `E`, the point `v = orthogonal_projection K u` in `K` minimizes the distance `‖u - v‖` to `u`. Also a linear isometry equivalence `reflection K : E ≃ₗᵢ[𝕜] E` is constructed, by choosing, for each `u : E`, the point `reflection K u` to satisfy `u + (reflection K u) = 2 • orthogonal_projection K u`. Basic API for `orthogonal_projection` and `reflection` is developed. Next, the orthogonal projection is used to prove a series of more subtle lemmas about the the orthogonal complement of complete subspaces of `E` (the orthogonal complement itself was defined in `analysis.inner_product_space.basic`); the lemma `submodule.sup_orthogonal_of_is_complete`, stating that for a complete subspace `K` of `E` we have `K ⊔ Kᗮ = ⊤`, is a typical example. ## References The orthogonal projection construction is adapted from * [Clément & Martin, *The Lax-Milgram Theorem. A detailed proof to be formalized in Coq*] * [Clément & Martin, *A Coq formal proof of the Lax–Milgram theorem*] The Coq code is available at the following address: <http://www.lri.fr/~sboldo/elfic/index.html> -/ noncomputable theory open is_R_or_C real filter linear_map (ker range) open_locale big_operators topology variables {𝕜 E F : Type*} [is_R_or_C 𝕜] variables [normed_add_comm_group E] [normed_add_comm_group F] variables [inner_product_space 𝕜 E] [inner_product_space ℝ F] local notation `⟪`x`, `y`⟫` := @inner 𝕜 _ _ x y local notation `absR` := has_abs.abs /-! ### Orthogonal projection in inner product spaces -/ /-- Existence of minimizers Let `u` be a point in a real inner product space, and let `K` be a nonempty complete convex subset. Then there exists a (unique) `v` in `K` that minimizes the distance `‖u - v‖` to `u`. -/ -- FIXME this monolithic proof causes a deterministic timeout with `-T50000` -- It should be broken in a sequence of more manageable pieces, -- perhaps with individual statements for the three steps below. theorem exists_norm_eq_infi_of_complete_convex {K : set F} (ne : K.nonempty) (h₁ : is_complete K) (h₂ : convex ℝ K) : ∀ u : F, ∃ v ∈ K, ‖u - v‖ = ⨅ w : K, ‖u - w‖ := assume u, begin let δ := ⨅ w : K, ‖u - w‖, letI : nonempty K := ne.to_subtype, have zero_le_δ : 0 ≤ δ := le_cinfi (λ _, norm_nonneg _), have δ_le : ∀ w : K, δ ≤ ‖u - w‖, from cinfi_le ⟨0, set.forall_range_iff.2 $ λ _, norm_nonneg _⟩, have δ_le' : ∀ w ∈ K, δ ≤ ‖u - w‖ := assume w hw, δ_le ⟨w, hw⟩, -- Step 1: since `δ` is the infimum, can find a sequence `w : ℕ → K` in `K` -- such that `‖u - w n‖ < δ + 1 / (n + 1)` (which implies `‖u - w n‖ --> δ`); -- maybe this should be a separate lemma have exists_seq : ∃ w : ℕ → K, ∀ n, ‖u - w n‖ < δ + 1 / (n + 1), { have hδ : ∀n:ℕ, δ < δ + 1 / (n + 1), from λ n, lt_add_of_le_of_pos le_rfl nat.one_div_pos_of_nat, have h := λ n, exists_lt_of_cinfi_lt (hδ n), let w : ℕ → K := λ n, classical.some (h n), exact ⟨w, λ n, classical.some_spec (h n)⟩ }, rcases exists_seq with ⟨w, hw⟩, have norm_tendsto : tendsto (λ n, ‖u - w n‖) at_top (nhds δ), { have h : tendsto (λ n:ℕ, δ) at_top (nhds δ) := tendsto_const_nhds, have h' : tendsto (λ n:ℕ, δ + 1 / (n + 1)) at_top (nhds δ), { convert h.add tendsto_one_div_add_at_top_nhds_0_nat, simp only [add_zero] }, exact tendsto_of_tendsto_of_tendsto_of_le_of_le h h' (λ x, δ_le _) (λ x, le_of_lt (hw _)) }, -- Step 2: Prove that the sequence `w : ℕ → K` is a Cauchy sequence have seq_is_cauchy : cauchy_seq (λ n, ((w n):F)), { rw cauchy_seq_iff_le_tendsto_0, -- splits into three goals let b := λ n:ℕ, (8 * δ * (1/(n+1)) + 4 * (1/(n+1)) * (1/(n+1))), use (λn, sqrt (b n)), split, -- first goal : `∀ (n : ℕ), 0 ≤ sqrt (b n)` assume n, exact sqrt_nonneg _, split, -- second goal : `∀ (n m N : ℕ), N ≤ n → N ≤ m → dist ↑(w n) ↑(w m) ≤ sqrt (b N)` assume p q N hp hq, let wp := ((w p):F), let wq := ((w q):F), let a := u - wq, let b := u - wp, let half := 1 / (2:ℝ), let div := 1 / ((N:ℝ) + 1), have : 4 * ‖u - half • (wq + wp)‖ * ‖u - half • (wq + wp)‖ + ‖wp - wq‖ * ‖wp - wq‖ = 2 * (‖a‖ * ‖a‖ + ‖b‖ * ‖b‖) := calc 4 * ‖u - half•(wq + wp)‖ * ‖u - half•(wq + wp)‖ + ‖wp - wq‖ * ‖wp - wq‖ = (2*‖u - half•(wq + wp)‖) * (2 * ‖u - half•(wq + wp)‖) + ‖wp-wq‖*‖wp-wq‖ : by ring ... = (absR ((2:ℝ)) * ‖u - half•(wq + wp)‖) * (absR ((2:ℝ)) * ‖u - half•(wq+wp)‖) + ‖wp-wq‖*‖wp-wq‖ : by { rw _root_.abs_of_nonneg, exact zero_le_two } ... = ‖(2:ℝ) • (u - half • (wq + wp))‖ * ‖(2:ℝ) • (u - half • (wq + wp))‖ + ‖wp-wq‖ * ‖wp-wq‖ : by simp [norm_smul] ... = ‖a + b‖ * ‖a + b‖ + ‖a - b‖ * ‖a - b‖ : begin rw [smul_sub, smul_smul, mul_one_div_cancel (_root_.two_ne_zero : (2 : ℝ) ≠ 0), ← one_add_one_eq_two, add_smul], simp only [one_smul], have eq₁ : wp - wq = a - b, from (sub_sub_sub_cancel_left _ _ _).symm, have eq₂ : u + u - (wq + wp) = a + b, show u + u - (wq + wp) = (u - wq) + (u - wp), abel, rw [eq₁, eq₂], end ... = 2 * (‖a‖ * ‖a‖ + ‖b‖ * ‖b‖) : parallelogram_law_with_norm ℝ _ _, have eq : δ ≤ ‖u - half • (wq + wp)‖, { rw smul_add, apply δ_le', apply h₂, repeat {exact subtype.mem _}, repeat {exact le_of_lt one_half_pos}, exact add_halves 1 }, have eq₁ : 4 * δ * δ ≤ 4 * ‖u - half • (wq + wp)‖ * ‖u - half • (wq + wp)‖, { simp_rw mul_assoc, exact mul_le_mul_of_nonneg_left (mul_self_le_mul_self zero_le_δ eq) zero_le_four }, have eq₂ : ‖a‖ * ‖a‖ ≤ (δ + div) * (δ + div) := mul_self_le_mul_self (norm_nonneg _) (le_trans (le_of_lt $ hw q) (add_le_add_left (nat.one_div_le_one_div hq) _)), have eq₂' : ‖b‖ * ‖b‖ ≤ (δ + div) * (δ + div) := mul_self_le_mul_self (norm_nonneg _) (le_trans (le_of_lt $ hw p) (add_le_add_left (nat.one_div_le_one_div hp) _)), rw dist_eq_norm, apply nonneg_le_nonneg_of_sq_le_sq, { exact sqrt_nonneg _ }, rw mul_self_sqrt, calc ‖wp - wq‖ * ‖wp - wq‖ = 2 * (‖a‖*‖a‖ + ‖b‖*‖b‖) - 4 * ‖u - half • (wq+wp)‖ * ‖u - half • (wq+wp)‖ : by { rw ← this, simp } ... ≤ 2 * (‖a‖ * ‖a‖ + ‖b‖ * ‖b‖) - 4 * δ * δ : sub_le_sub_left eq₁ _ ... ≤ 2 * ((δ + div) * (δ + div) + (δ + div) * (δ + div)) - 4 * δ * δ : sub_le_sub_right (mul_le_mul_of_nonneg_left (add_le_add eq₂ eq₂') (by norm_num)) _ ... = 8 * δ * div + 4 * div * div : by ring, exact add_nonneg (mul_nonneg (mul_nonneg (by norm_num) zero_le_δ) (le_of_lt nat.one_div_pos_of_nat)) (mul_nonneg (mul_nonneg (by norm_num) nat.one_div_pos_of_nat.le) nat.one_div_pos_of_nat.le), -- third goal : `tendsto (λ (n : ℕ), sqrt (b n)) at_top (𝓝 0)` apply tendsto.comp, { convert continuous_sqrt.continuous_at, exact sqrt_zero.symm }, have eq₁ : tendsto (λ (n : ℕ), 8 * δ * (1 / (n + 1))) at_top (nhds (0:ℝ)), { convert (@tendsto_const_nhds _ _ _ (8 * δ) _).mul tendsto_one_div_add_at_top_nhds_0_nat, simp only [mul_zero] }, have : tendsto (λ (n : ℕ), (4:ℝ) * (1 / (n + 1))) at_top (nhds (0:ℝ)), { convert (@tendsto_const_nhds _ _ _ (4:ℝ) _).mul tendsto_one_div_add_at_top_nhds_0_nat, simp only [mul_zero] }, have eq₂ : tendsto (λ (n : ℕ), (4:ℝ) * (1 / (n + 1)) * (1 / (n + 1))) at_top (nhds (0:ℝ)), { convert this.mul tendsto_one_div_add_at_top_nhds_0_nat, simp only [mul_zero] }, convert eq₁.add eq₂, simp only [add_zero] }, -- Step 3: By completeness of `K`, let `w : ℕ → K` converge to some `v : K`. -- Prove that it satisfies all requirements. rcases cauchy_seq_tendsto_of_is_complete h₁ (λ n, _) seq_is_cauchy with ⟨v, hv, w_tendsto⟩, use v, use hv, have h_cont : continuous (λ v, ‖u - v‖) := continuous.comp continuous_norm (continuous.sub continuous_const continuous_id), have : tendsto (λ n, ‖u - w n‖) at_top (nhds ‖u - v‖), convert (tendsto.comp h_cont.continuous_at w_tendsto), exact tendsto_nhds_unique this norm_tendsto, exact subtype.mem _ end /-- Characterization of minimizers for the projection on a convex set in a real inner product space. -/ theorem norm_eq_infi_iff_real_inner_le_zero {K : set F} (h : convex ℝ K) {u : F} {v : F} (hv : v ∈ K) : ‖u - v‖ = (⨅ w : K, ‖u - w‖) ↔ ∀ w ∈ K, ⟪u - v, w - v⟫_ℝ ≤ 0 := iff.intro begin assume eq w hw, let δ := ⨅ w : K, ‖u - w‖, let p := ⟪u - v, w - v⟫_ℝ, let q := ‖w - v‖^2, letI : nonempty K := ⟨⟨v, hv⟩⟩, have zero_le_δ : 0 ≤ δ, apply le_cinfi, intro, exact norm_nonneg _, have δ_le : ∀ w : K, δ ≤ ‖u - w‖, assume w, apply cinfi_le, use (0:ℝ), rintros _ ⟨_, rfl⟩, exact norm_nonneg _, have δ_le' : ∀ w ∈ K, δ ≤ ‖u - w‖ := assume w hw, δ_le ⟨w, hw⟩, have : ∀θ:ℝ, 0 < θ → θ ≤ 1 → 2 * p ≤ θ * q, assume θ hθ₁ hθ₂, have : ‖u - v‖^2 ≤ ‖u - v‖^2 - 2 * θ * ⟪u - v, w - v⟫_ℝ + θ*θ*‖w - v‖^2 := calc ‖u - v‖^2 ≤ ‖u - (θ•w + (1-θ)•v)‖^2 : begin simp only [sq], apply mul_self_le_mul_self (norm_nonneg _), rw [eq], apply δ_le', apply h hw hv, exacts [le_of_lt hθ₁, sub_nonneg.2 hθ₂, add_sub_cancel'_right _ _], end ... = ‖(u - v) - θ • (w - v)‖^2 : begin have : u - (θ•w + (1-θ)•v) = (u - v) - θ • (w - v), { rw [smul_sub, sub_smul, one_smul], simp only [sub_eq_add_neg, add_comm, add_left_comm, add_assoc, neg_add_rev] }, rw this end ... = ‖u - v‖^2 - 2 * θ * inner (u - v) (w - v) + θ*θ*‖w - v‖^2 : begin rw [@norm_sub_sq ℝ, inner_smul_right, norm_smul], simp only [sq], show ‖u-v‖*‖u-v‖-2*(θ*inner(u-v)(w-v))+absR (θ)*‖w-v‖*(absR (θ)*‖w-v‖)= ‖u-v‖*‖u-v‖-2*θ*inner(u-v)(w-v)+θ*θ*(‖w-v‖*‖w-v‖), rw abs_of_pos hθ₁, ring end, have eq₁ : ‖u-v‖^2-2*θ*inner(u-v)(w-v)+θ*θ*‖w-v‖^2=‖u-v‖^2+(θ*θ*‖w-v‖^2-2*θ*inner(u-v)(w-v)), by abel, rw [eq₁, le_add_iff_nonneg_right] at this, have eq₂ : θ*θ*‖w-v‖^2-2*θ*inner(u-v)(w-v)=θ*(θ*‖w-v‖^2-2*inner(u-v)(w-v)), ring, rw eq₂ at this, have := le_of_sub_nonneg (nonneg_of_mul_nonneg_right this hθ₁), exact this, by_cases hq : q = 0, { rw hq at this, have : p ≤ 0, have := this (1:ℝ) (by norm_num) (by norm_num), linarith, exact this }, { have q_pos : 0 < q, apply lt_of_le_of_ne, exact sq_nonneg _, intro h, exact hq h.symm, by_contradiction hp, rw not_le at hp, let θ := min (1:ℝ) (p / q), have eq₁ : θ*q ≤ p := calc θ*q ≤ (p/q) * q : mul_le_mul_of_nonneg_right (min_le_right _ _) (sq_nonneg _) ... = p : div_mul_cancel _ hq, have : 2 * p ≤ p := calc 2 * p ≤ θ*q : by { refine this θ (lt_min (by norm_num) (div_pos hp q_pos)) (by norm_num) } ... ≤ p : eq₁, linarith } end begin assume h, letI : nonempty K := ⟨⟨v, hv⟩⟩, apply le_antisymm, { apply le_cinfi, assume w, apply nonneg_le_nonneg_of_sq_le_sq (norm_nonneg _), have := h w w.2, calc ‖u - v‖ * ‖u - v‖ ≤ ‖u - v‖ * ‖u - v‖ - 2 * inner (u - v) ((w:F) - v) : by linarith ... ≤ ‖u - v‖^2 - 2 * inner (u - v) ((w:F) - v) + ‖(w:F) - v‖^2 : by { rw sq, refine le_add_of_nonneg_right _, exact sq_nonneg _ } ... = ‖(u - v) - (w - v)‖^2 : (@norm_sub_sq ℝ _ _ _ _ _ _).symm ... = ‖u - w‖ * ‖u - w‖ : by { have : (u - v) - (w - v) = u - w, abel, rw [this, sq] } }, { show (⨅ (w : K), ‖u - w‖) ≤ (λw:K, ‖u - w‖) ⟨v, hv⟩, apply cinfi_le, use 0, rintros y ⟨z, rfl⟩, exact norm_nonneg _ } end variables (K : submodule 𝕜 E) /-- Existence of projections on complete subspaces. Let `u` be a point in an inner product space, and let `K` be a nonempty complete subspace. Then there exists a (unique) `v` in `K` that minimizes the distance `‖u - v‖` to `u`. This point `v` is usually called the orthogonal projection of `u` onto `K`. -/ theorem exists_norm_eq_infi_of_complete_subspace (h : is_complete (↑K : set E)) : ∀ u : E, ∃ v ∈ K, ‖u - v‖ = ⨅ w : (K : set E), ‖u - w‖ := begin letI : inner_product_space ℝ E := inner_product_space.is_R_or_C_to_real 𝕜 E, letI : module ℝ E := restrict_scalars.module ℝ 𝕜 E, let K' : submodule ℝ E := submodule.restrict_scalars ℝ K, exact exists_norm_eq_infi_of_complete_convex ⟨0, K'.zero_mem⟩ h K'.convex end /-- Characterization of minimizers in the projection on a subspace, in the real case. Let `u` be a point in a real inner product space, and let `K` be a nonempty subspace. Then point `v` minimizes the distance `‖u - v‖` over points in `K` if and only if for all `w ∈ K`, `⟪u - v, w⟫ = 0` (i.e., `u - v` is orthogonal to the subspace `K`). This is superceded by `norm_eq_infi_iff_inner_eq_zero` that gives the same conclusion over any `is_R_or_C` field. -/ theorem norm_eq_infi_iff_real_inner_eq_zero (K : submodule ℝ F) {u : F} {v : F} (hv : v ∈ K) : ‖u - v‖ = (⨅ w : (↑K : set F), ‖u - w‖) ↔ ∀ w ∈ K, ⟪u - v, w⟫_ℝ = 0 := iff.intro begin assume h, have h : ∀ w ∈ K, ⟪u - v, w - v⟫_ℝ ≤ 0, { rwa [norm_eq_infi_iff_real_inner_le_zero] at h, exacts [K.convex, hv] }, assume w hw, have le : ⟪u - v, w⟫_ℝ ≤ 0, let w' := w + v, have : w' ∈ K := submodule.add_mem _ hw hv, have h₁ := h w' this, have h₂ : w' - v = w, simp only [add_neg_cancel_right, sub_eq_add_neg], rw h₂ at h₁, exact h₁, have ge : ⟪u - v, w⟫_ℝ ≥ 0, let w'' := -w + v, have : w'' ∈ K := submodule.add_mem _ (submodule.neg_mem _ hw) hv, have h₁ := h w'' this, have h₂ : w'' - v = -w, simp only [neg_inj, add_neg_cancel_right, sub_eq_add_neg], rw [h₂, inner_neg_right] at h₁, linarith, exact le_antisymm le ge end begin assume h, have : ∀ w ∈ K, ⟪u - v, w - v⟫_ℝ ≤ 0, assume w hw, let w' := w - v, have : w' ∈ K := submodule.sub_mem _ hw hv, have h₁ := h w' this, exact le_of_eq h₁, rwa norm_eq_infi_iff_real_inner_le_zero, exacts [submodule.convex _, hv] end /-- Characterization of minimizers in the projection on a subspace. Let `u` be a point in an inner product space, and let `K` be a nonempty subspace. Then point `v` minimizes the distance `‖u - v‖` over points in `K` if and only if for all `w ∈ K`, `⟪u - v, w⟫ = 0` (i.e., `u - v` is orthogonal to the subspace `K`) -/ theorem norm_eq_infi_iff_inner_eq_zero {u : E} {v : E} (hv : v ∈ K) : ‖u - v‖ = (⨅ w : K, ‖u - w‖) ↔ ∀ w ∈ K, ⟪u - v, w⟫ = 0 := begin letI : inner_product_space ℝ E := inner_product_space.is_R_or_C_to_real 𝕜 E, letI : module ℝ E := restrict_scalars.module ℝ 𝕜 E, let K' : submodule ℝ E := K.restrict_scalars ℝ, split, { assume H, have A : ∀ w ∈ K, re ⟪u - v, w⟫ = 0 := (norm_eq_infi_iff_real_inner_eq_zero K' hv).1 H, assume w hw, apply ext, { simp [A w hw] }, { symmetry, calc im (0 : 𝕜) = 0 : im.map_zero ... = re ⟪u - v, (-I) • w⟫ : (A _ (K.smul_mem (-I) hw)).symm ... = re ((-I) * ⟪u - v, w⟫) : by rw inner_smul_right ... = im ⟪u - v, w⟫ : by simp } }, { assume H, have : ∀ w ∈ K', ⟪u - v, w⟫_ℝ = 0, { assume w hw, rw [real_inner_eq_re_inner, H w hw], exact zero_re' }, exact (norm_eq_infi_iff_real_inner_eq_zero K' hv).2 this } end section orthogonal_projection variables [complete_space K] /-- The orthogonal projection onto a complete subspace, as an unbundled function. This definition is only intended for use in setting up the bundled version `orthogonal_projection` and should not be used once that is defined. -/ def orthogonal_projection_fn (v : E) := (exists_norm_eq_infi_of_complete_subspace K (complete_space_coe_iff_is_complete.mp ‹_›) v).some variables {K} /-- The unbundled orthogonal projection is in the given subspace. This lemma is only intended for use in setting up the bundled version and should not be used once that is defined. -/ lemma orthogonal_projection_fn_mem (v : E) : orthogonal_projection_fn K v ∈ K := (exists_norm_eq_infi_of_complete_subspace K (complete_space_coe_iff_is_complete.mp ‹_›) v).some_spec.some /-- The characterization of the unbundled orthogonal projection. This lemma is only intended for use in setting up the bundled version and should not be used once that is defined. -/ lemma orthogonal_projection_fn_inner_eq_zero (v : E) : ∀ w ∈ K, ⟪v - orthogonal_projection_fn K v, w⟫ = 0 := begin rw ←norm_eq_infi_iff_inner_eq_zero K (orthogonal_projection_fn_mem v), exact (exists_norm_eq_infi_of_complete_subspace K (complete_space_coe_iff_is_complete.mp ‹_›) v).some_spec.some_spec end /-- The unbundled orthogonal projection is the unique point in `K` with the orthogonality property. This lemma is only intended for use in setting up the bundled version and should not be used once that is defined. -/ lemma eq_orthogonal_projection_fn_of_mem_of_inner_eq_zero {u v : E} (hvm : v ∈ K) (hvo : ∀ w ∈ K, ⟪u - v, w⟫ = 0) : orthogonal_projection_fn K u = v := begin rw [←sub_eq_zero, ←@inner_self_eq_zero 𝕜], have hvs : orthogonal_projection_fn K u - v ∈ K := submodule.sub_mem K (orthogonal_projection_fn_mem u) hvm, have huo : ⟪u - orthogonal_projection_fn K u, orthogonal_projection_fn K u - v⟫ = 0 := orthogonal_projection_fn_inner_eq_zero u _ hvs, have huv : ⟪u - v, orthogonal_projection_fn K u - v⟫ = 0 := hvo _ hvs, have houv : ⟪(u - v) - (u - orthogonal_projection_fn K u), orthogonal_projection_fn K u - v⟫ = 0, { rw [inner_sub_left, huo, huv, sub_zero] }, rwa sub_sub_sub_cancel_left at houv end variables (K) lemma orthogonal_projection_fn_norm_sq (v : E) : ‖v‖ * ‖v‖ = ‖v - (orthogonal_projection_fn K v)‖ * ‖v - (orthogonal_projection_fn K v)‖ + ‖orthogonal_projection_fn K v‖ * ‖orthogonal_projection_fn K v‖ := begin set p := orthogonal_projection_fn K v, have h' : ⟪v - p, p⟫ = 0, { exact orthogonal_projection_fn_inner_eq_zero _ _ (orthogonal_projection_fn_mem v) }, convert norm_add_sq_eq_norm_sq_add_norm_sq_of_inner_eq_zero (v - p) p h' using 2; simp, end /-- The orthogonal projection onto a complete subspace. -/ def orthogonal_projection : E →L[𝕜] K := linear_map.mk_continuous { to_fun := λ v, ⟨orthogonal_projection_fn K v, orthogonal_projection_fn_mem v⟩, map_add' := λ x y, begin have hm : orthogonal_projection_fn K x + orthogonal_projection_fn K y ∈ K := submodule.add_mem K (orthogonal_projection_fn_mem x) (orthogonal_projection_fn_mem y), have ho : ∀ w ∈ K, ⟪x + y - (orthogonal_projection_fn K x + orthogonal_projection_fn K y), w⟫ = 0, { intros w hw, rw [add_sub_add_comm, inner_add_left, orthogonal_projection_fn_inner_eq_zero _ w hw, orthogonal_projection_fn_inner_eq_zero _ w hw, add_zero] }, ext, simp [eq_orthogonal_projection_fn_of_mem_of_inner_eq_zero hm ho] end, map_smul' := λ c x, begin have hm : c • orthogonal_projection_fn K x ∈ K := submodule.smul_mem K _ (orthogonal_projection_fn_mem x), have ho : ∀ w ∈ K, ⟪c • x - c • orthogonal_projection_fn K x, w⟫ = 0, { intros w hw, rw [←smul_sub, inner_smul_left, orthogonal_projection_fn_inner_eq_zero _ w hw, mul_zero] }, ext, simp [eq_orthogonal_projection_fn_of_mem_of_inner_eq_zero hm ho] end } 1 (λ x, begin simp only [one_mul, linear_map.coe_mk], refine le_of_pow_le_pow 2 (norm_nonneg _) (by norm_num) _, change ‖orthogonal_projection_fn K x‖ ^ 2 ≤ ‖x‖ ^ 2, nlinarith [orthogonal_projection_fn_norm_sq K x] end) variables {K} @[simp] lemma orthogonal_projection_fn_eq (v : E) : orthogonal_projection_fn K v = (orthogonal_projection K v : E) := rfl /-- The characterization of the orthogonal projection. -/ @[simp] lemma orthogonal_projection_inner_eq_zero (v : E) : ∀ w ∈ K, ⟪v - orthogonal_projection K v, w⟫ = 0 := orthogonal_projection_fn_inner_eq_zero v /-- The difference of `v` from its orthogonal projection onto `K` is in `Kᗮ`. -/ @[simp] lemma sub_orthogonal_projection_mem_orthogonal (v : E) : v - orthogonal_projection K v ∈ Kᗮ := begin intros w hw, rw inner_eq_zero_symm, exact orthogonal_projection_inner_eq_zero _ _ hw end /-- The orthogonal projection is the unique point in `K` with the orthogonality property. -/ lemma eq_orthogonal_projection_of_mem_of_inner_eq_zero {u v : E} (hvm : v ∈ K) (hvo : ∀ w ∈ K, ⟪u - v, w⟫ = 0) : (orthogonal_projection K u : E) = v := eq_orthogonal_projection_fn_of_mem_of_inner_eq_zero hvm hvo /-- The orthogonal projection of `y` on `U` minimizes the distance `‖y - x‖` for `x ∈ U`. -/ lemma orthogonal_projection_minimal {U : submodule 𝕜 E} [complete_space U] (y : E) : ‖y - orthogonal_projection U y‖ = ⨅ x : U, ‖y - x‖ := begin rw norm_eq_infi_iff_inner_eq_zero _ (submodule.coe_mem _), exact orthogonal_projection_inner_eq_zero _ end /-- The orthogonal projections onto equal subspaces are coerced back to the same point in `E`. -/ lemma eq_orthogonal_projection_of_eq_submodule {K' : submodule 𝕜 E} [complete_space K'] (h : K = K') (u : E) : (orthogonal_projection K u : E) = (orthogonal_projection K' u : E) := begin change orthogonal_projection_fn K u = orthogonal_projection_fn K' u, congr, exact h end /-- The orthogonal projection sends elements of `K` to themselves. -/ @[simp] lemma orthogonal_projection_mem_subspace_eq_self (v : K) : orthogonal_projection K v = v := by { ext, apply eq_orthogonal_projection_of_mem_of_inner_eq_zero; simp } /-- A point equals its orthogonal projection if and only if it lies in the subspace. -/ lemma orthogonal_projection_eq_self_iff {v : E} : (orthogonal_projection K v : E) = v ↔ v ∈ K := begin refine ⟨λ h, _, λ h, eq_orthogonal_projection_of_mem_of_inner_eq_zero h _⟩, { rw ← h, simp }, { simp } end lemma linear_isometry.map_orthogonal_projection {E E' : Type*} [normed_add_comm_group E] [normed_add_comm_group E'] [inner_product_space 𝕜 E] [inner_product_space 𝕜 E'] (f : E →ₗᵢ[𝕜] E') (p : submodule 𝕜 E) [complete_space p] (x : E) : f (orthogonal_projection p x) = orthogonal_projection (p.map f.to_linear_map) (f x) := begin refine (eq_orthogonal_projection_of_mem_of_inner_eq_zero _ $ λ y hy, _).symm, refine submodule.apply_coe_mem_map _ _, rcases hy with ⟨x', hx', rfl : f x' = y⟩, rw [← f.map_sub, f.inner_map_map, orthogonal_projection_inner_eq_zero x x' hx'] end lemma linear_isometry.map_orthogonal_projection' {E E' : Type*} [normed_add_comm_group E] [normed_add_comm_group E'] [inner_product_space 𝕜 E] [inner_product_space 𝕜 E'] (f : E →ₗᵢ[𝕜] E') (p : submodule 𝕜 E) [complete_space p] (x : E) : f (orthogonal_projection p x) = orthogonal_projection (p.map f) (f x) := begin refine (eq_orthogonal_projection_of_mem_of_inner_eq_zero _ $ λ y hy, _).symm, refine submodule.apply_coe_mem_map _ _, rcases hy with ⟨x', hx', rfl : f x' = y⟩, rw [← f.map_sub, f.inner_map_map, orthogonal_projection_inner_eq_zero x x' hx'] end /-- Orthogonal projection onto the `submodule.map` of a subspace. -/ lemma orthogonal_projection_map_apply {E E' : Type*} [normed_add_comm_group E] [normed_add_comm_group E'] [inner_product_space 𝕜 E] [inner_product_space 𝕜 E'] (f : E ≃ₗᵢ[𝕜] E') (p : submodule 𝕜 E) [complete_space p] (x : E') : (orthogonal_projection (p.map (f.to_linear_equiv : E →ₗ[𝕜] E')) x : E') = f (orthogonal_projection p (f.symm x)) := by simpa only [f.coe_to_linear_isometry, f.apply_symm_apply] using (f.to_linear_isometry.map_orthogonal_projection p (f.symm x)).symm /-- The orthogonal projection onto the trivial submodule is the zero map. -/ @[simp] lemma orthogonal_projection_bot : orthogonal_projection (⊥ : submodule 𝕜 E) = 0 := by ext variables (K) /-- The orthogonal projection has norm `≤ 1`. -/ lemma orthogonal_projection_norm_le : ‖orthogonal_projection K‖ ≤ 1 := linear_map.mk_continuous_norm_le _ (by norm_num) _ variables (𝕜) lemma smul_orthogonal_projection_singleton {v : E} (w : E) : (‖v‖ ^ 2 : 𝕜) • (orthogonal_projection (𝕜 ∙ v) w : E) = ⟪v, w⟫ • v := begin suffices : ↑(orthogonal_projection (𝕜 ∙ v) ((‖v‖ ^ 2 : 𝕜) • w)) = ⟪v, w⟫ • v, { simpa using this }, apply eq_orthogonal_projection_of_mem_of_inner_eq_zero, { rw submodule.mem_span_singleton, use ⟪v, w⟫ }, { intros x hx, obtain ⟨c, rfl⟩ := submodule.mem_span_singleton.mp hx, have hv : ↑‖v‖ ^ 2 = ⟪v, v⟫ := by { norm_cast, simp [@norm_sq_eq_inner 𝕜] }, simp [inner_sub_left, inner_smul_left, inner_smul_right, map_div₀, mul_comm, hv, inner_product_space.conj_symm, hv] } end /-- Formula for orthogonal projection onto a single vector. -/ lemma orthogonal_projection_singleton {v : E} (w : E) : (orthogonal_projection (𝕜 ∙ v) w : E) = (⟪v, w⟫ / ‖v‖ ^ 2) • v := begin by_cases hv : v = 0, { rw [hv, eq_orthogonal_projection_of_eq_submodule (submodule.span_zero_singleton 𝕜)], { simp }, { apply_instance } }, have hv' : ‖v‖ ≠ 0 := ne_of_gt (norm_pos_iff.mpr hv), have key : ((‖v‖ ^ 2 : 𝕜)⁻¹ * ‖v‖ ^ 2) • ↑(orthogonal_projection (𝕜 ∙ v) w) = ((‖v‖ ^ 2 : 𝕜)⁻¹ * ⟪v, w⟫) • v, { simp [mul_smul, smul_orthogonal_projection_singleton 𝕜 w] }, convert key; field_simp [hv'] end /-- Formula for orthogonal projection onto a single unit vector. -/ lemma orthogonal_projection_unit_singleton {v : E} (hv : ‖v‖ = 1) (w : E) : (orthogonal_projection (𝕜 ∙ v) w : E) = ⟪v, w⟫ • v := by { rw ← smul_orthogonal_projection_singleton 𝕜 w, simp [hv] } end orthogonal_projection section reflection variables {𝕜} (K) [complete_space K] /-- Auxiliary definition for `reflection`: the reflection as a linear equivalence. -/ def reflection_linear_equiv : E ≃ₗ[𝕜] E := linear_equiv.of_involutive (bit0 (K.subtype.comp (orthogonal_projection K).to_linear_map) - linear_map.id) (λ x, by simp [bit0]) /-- Reflection in a complete subspace of an inner product space. The word "reflection" is sometimes understood to mean specifically reflection in a codimension-one subspace, and sometimes more generally to cover operations such as reflection in a point. The definition here, of reflection in a subspace, is a more general sense of the word that includes both those common cases. -/ def reflection : E ≃ₗᵢ[𝕜] E := { norm_map' := begin intros x, let w : K := orthogonal_projection K x, let v := x - w, have : ⟪v, w⟫ = 0 := orthogonal_projection_inner_eq_zero x w w.2, convert norm_sub_eq_norm_add this using 2, { rw [linear_equiv.coe_mk, reflection_linear_equiv, linear_equiv.to_fun_eq_coe, linear_equiv.coe_of_involutive, linear_map.sub_apply, linear_map.id_apply, bit0, linear_map.add_apply, linear_map.comp_apply, submodule.subtype_apply, continuous_linear_map.to_linear_map_eq_coe, continuous_linear_map.coe_coe], dsimp [w, v], abel, }, { simp only [add_sub_cancel'_right, eq_self_iff_true], } end, ..reflection_linear_equiv K } variables {K} /-- The result of reflecting. -/ lemma reflection_apply (p : E) : reflection K p = bit0 ↑(orthogonal_projection K p) - p := rfl /-- Reflection is its own inverse. -/ @[simp] lemma reflection_symm : (reflection K).symm = reflection K := rfl /-- Reflection is its own inverse. -/ @[simp] lemma reflection_inv : (reflection K)⁻¹ = reflection K := rfl variables (K) /-- Reflecting twice in the same subspace. -/ @[simp] lemma reflection_reflection (p : E) : reflection K (reflection K p) = p := (reflection K).left_inv p /-- Reflection is involutive. -/ lemma reflection_involutive : function.involutive (reflection K) := reflection_reflection K /-- Reflection is involutive. -/ @[simp] lemma reflection_trans_reflection : (reflection K).trans (reflection K) = linear_isometry_equiv.refl 𝕜 E := linear_isometry_equiv.ext $ reflection_involutive K /-- Reflection is involutive. -/ @[simp] lemma reflection_mul_reflection : reflection K * reflection K = 1 := reflection_trans_reflection _ variables {K} /-- A point is its own reflection if and only if it is in the subspace. -/ lemma reflection_eq_self_iff (x : E) : reflection K x = x ↔ x ∈ K := begin rw [←orthogonal_projection_eq_self_iff, reflection_apply, sub_eq_iff_eq_add', ← two_smul 𝕜, ← two_smul' 𝕜], refine (smul_right_injective E _).eq_iff, exact two_ne_zero end lemma reflection_mem_subspace_eq_self {x : E} (hx : x ∈ K) : reflection K x = x := (reflection_eq_self_iff x).mpr hx /-- Reflection in the `submodule.map` of a subspace. -/ lemma reflection_map_apply {E E' : Type*} [normed_add_comm_group E] [normed_add_comm_group E'] [inner_product_space 𝕜 E] [inner_product_space 𝕜 E'] (f : E ≃ₗᵢ[𝕜] E') (K : submodule 𝕜 E) [complete_space K] (x : E') : reflection (K.map (f.to_linear_equiv : E →ₗ[𝕜] E')) x = f (reflection K (f.symm x)) := by simp [bit0, reflection_apply, orthogonal_projection_map_apply f K x] /-- Reflection in the `submodule.map` of a subspace. -/ lemma reflection_map {E E' : Type*} [normed_add_comm_group E] [normed_add_comm_group E'] [inner_product_space 𝕜 E] [inner_product_space 𝕜 E'] (f : E ≃ₗᵢ[𝕜] E') (K : submodule 𝕜 E) [complete_space K] : reflection (K.map (f.to_linear_equiv : E →ₗ[𝕜] E')) = f.symm.trans ((reflection K).trans f) := linear_isometry_equiv.ext $ reflection_map_apply f K /-- Reflection through the trivial subspace {0} is just negation. -/ @[simp] lemma reflection_bot : reflection (⊥ : submodule 𝕜 E) = linear_isometry_equiv.neg 𝕜 := by ext; simp [reflection_apply] end reflection section orthogonal /-- If `K₁` is complete and contained in `K₂`, `K₁` and `K₁ᗮ ⊓ K₂` span `K₂`. -/ lemma submodule.sup_orthogonal_inf_of_complete_space {K₁ K₂ : submodule 𝕜 E} (h : K₁ ≤ K₂) [complete_space K₁] : K₁ ⊔ (K₁ᗮ ⊓ K₂) = K₂ := begin ext x, rw submodule.mem_sup, let v : K₁ := orthogonal_projection K₁ x, have hvm : x - v ∈ K₁ᗮ := sub_orthogonal_projection_mem_orthogonal x, split, { rintro ⟨y, hy, z, hz, rfl⟩, exact K₂.add_mem (h hy) hz.2 }, { exact λ hx, ⟨v, v.prop, x - v, ⟨hvm, K₂.sub_mem hx (h v.prop)⟩, add_sub_cancel'_right _ _⟩ } end variables {K} /-- If `K` is complete, `K` and `Kᗮ` span the whole space. -/ lemma submodule.sup_orthogonal_of_complete_space [complete_space K] : K ⊔ Kᗮ = ⊤ := begin convert submodule.sup_orthogonal_inf_of_complete_space (le_top : K ≤ ⊤), simp end variables (K) /-- If `K` is complete, any `v` in `E` can be expressed as a sum of elements of `K` and `Kᗮ`. -/ lemma submodule.exists_sum_mem_mem_orthogonal [complete_space K] (v : E) : ∃ (y ∈ K) (z ∈ Kᗮ), v = y + z := begin have h_mem : v ∈ K ⊔ Kᗮ := by simp [submodule.sup_orthogonal_of_complete_space], obtain ⟨y, hy, z, hz, hyz⟩ := submodule.mem_sup.mp h_mem, exact ⟨y, hy, z, hz, hyz.symm⟩ end /-- If `K` is complete, then the orthogonal complement of its orthogonal complement is itself. -/ @[simp] lemma submodule.orthogonal_orthogonal [complete_space K] : Kᗮᗮ = K := begin ext v, split, { obtain ⟨y, hy, z, hz, rfl⟩ := K.exists_sum_mem_mem_orthogonal v, intros hv, have hz' : z = 0, { have hyz : ⟪z, y⟫ = 0 := by simp [hz y hy, inner_eq_zero_symm], simpa [inner_add_right, hyz] using hv z hz }, simp [hy, hz'] }, { intros hv w hw, rw inner_eq_zero_symm, exact hw v hv } end lemma submodule.orthogonal_orthogonal_eq_closure [complete_space E] : Kᗮᗮ = K.topological_closure := begin refine le_antisymm _ _, { convert submodule.orthogonal_orthogonal_monotone K.le_topological_closure, haveI : complete_space K.topological_closure := K.is_closed_topological_closure.complete_space_coe, rw K.topological_closure.orthogonal_orthogonal }, { exact K.topological_closure_minimal K.le_orthogonal_orthogonal Kᗮ.is_closed_orthogonal } end variables {K} /-- If `K` is complete, `K` and `Kᗮ` are complements of each other. -/ lemma submodule.is_compl_orthogonal_of_complete_space [complete_space K] : is_compl K Kᗮ := ⟨K.orthogonal_disjoint, codisjoint_iff.2 submodule.sup_orthogonal_of_complete_space⟩ @[simp] lemma submodule.orthogonal_eq_bot_iff [complete_space (K : set E)] : Kᗮ = ⊥ ↔ K = ⊤ := begin refine ⟨_, λ h, by rw [h, submodule.top_orthogonal_eq_bot] ⟩, intro h, have : K ⊔ Kᗮ = ⊤ := submodule.sup_orthogonal_of_complete_space, rwa [h, sup_comm, bot_sup_eq] at this, end /-- A point in `K` with the orthogonality property (here characterized in terms of `Kᗮ`) must be the orthogonal projection. -/ lemma eq_orthogonal_projection_of_mem_orthogonal [complete_space K] {u v : E} (hv : v ∈ K) (hvo : u - v ∈ Kᗮ) : (orthogonal_projection K u : E) = v := eq_orthogonal_projection_fn_of_mem_of_inner_eq_zero hv (λ w, inner_eq_zero_symm.mp ∘ (hvo w)) /-- A point in `K` with the orthogonality property (here characterized in terms of `Kᗮ`) must be the orthogonal projection. -/ lemma eq_orthogonal_projection_of_mem_orthogonal' [complete_space K] {u v z : E} (hv : v ∈ K) (hz : z ∈ Kᗮ) (hu : u = v + z) : (orthogonal_projection K u : E) = v := eq_orthogonal_projection_of_mem_orthogonal hv (by simpa [hu]) /-- The orthogonal projection onto `K` of an element of `Kᗮ` is zero. -/ lemma orthogonal_projection_mem_subspace_orthogonal_complement_eq_zero [complete_space K] {v : E} (hv : v ∈ Kᗮ) : orthogonal_projection K v = 0 := by { ext, convert eq_orthogonal_projection_of_mem_orthogonal _ _; simp [hv] } /-- The projection into `U` from an orthogonal submodule `V` is the zero map. -/ lemma submodule.is_ortho.orthogonal_projection_comp_subtypeL {U V : submodule 𝕜 E} [complete_space U] (h : U ⟂ V) : orthogonal_projection U ∘L V.subtypeL = 0 := continuous_linear_map.ext $ λ v, orthogonal_projection_mem_subspace_orthogonal_complement_eq_zero $ h.symm v.prop /-- The projection into `U` from `V` is the zero map if and only if `U` and `V` are orthogonal. -/ lemma orthogonal_projection_comp_subtypeL_eq_zero_iff {U V : submodule 𝕜 E} [complete_space U] : orthogonal_projection U ∘L V.subtypeL = 0 ↔ U ⟂ V := ⟨λ h u hu v hv, begin convert orthogonal_projection_inner_eq_zero v u hu using 2, have : orthogonal_projection U v = 0 := fun_like.congr_fun h ⟨_, hv⟩, rw [this, submodule.coe_zero, sub_zero] end, submodule.is_ortho.orthogonal_projection_comp_subtypeL⟩ lemma orthogonal_projection_eq_linear_proj [complete_space K] (x : E) : orthogonal_projection K x = K.linear_proj_of_is_compl _ submodule.is_compl_orthogonal_of_complete_space x := begin have : is_compl K Kᗮ := submodule.is_compl_orthogonal_of_complete_space, nth_rewrite 0 [← submodule.linear_proj_add_linear_proj_of_is_compl_eq_self this x], rw [map_add, orthogonal_projection_mem_subspace_eq_self, orthogonal_projection_mem_subspace_orthogonal_complement_eq_zero (submodule.coe_mem _), add_zero] end lemma orthogonal_projection_coe_linear_map_eq_linear_proj [complete_space K] : (orthogonal_projection K : E →ₗ[𝕜] K) = K.linear_proj_of_is_compl _ submodule.is_compl_orthogonal_of_complete_space := linear_map.ext $ orthogonal_projection_eq_linear_proj /-- The reflection in `K` of an element of `Kᗮ` is its negation. -/ lemma reflection_mem_subspace_orthogonal_complement_eq_neg [complete_space K] {v : E} (hv : v ∈ Kᗮ) : reflection K v = - v := by simp [reflection_apply, orthogonal_projection_mem_subspace_orthogonal_complement_eq_zero hv] /-- The orthogonal projection onto `Kᗮ` of an element of `K` is zero. -/ lemma orthogonal_projection_mem_subspace_orthogonal_precomplement_eq_zero [complete_space E] {v : E} (hv : v ∈ K) : orthogonal_projection Kᗮ v = 0 := orthogonal_projection_mem_subspace_orthogonal_complement_eq_zero (K.le_orthogonal_orthogonal hv) /-- If `U ≤ V`, then projecting on `V` and then on `U` is the same as projecting on `U`. -/ lemma orthogonal_projection_orthogonal_projection_of_le {U V : submodule 𝕜 E} [complete_space U] [complete_space V] (h : U ≤ V) (x : E) : orthogonal_projection U (orthogonal_projection V x) = orthogonal_projection U x := eq.symm $ by simpa only [sub_eq_zero, map_sub] using orthogonal_projection_mem_subspace_orthogonal_complement_eq_zero (submodule.orthogonal_le h (sub_orthogonal_projection_mem_orthogonal x)) /-- Given a monotone family `U` of complete submodules of `E` and a fixed `x : E`, the orthogonal projection of `x` on `U i` tends to the orthogonal projection of `x` on `(⨆ i, U i).topological_closure` along `at_top`. -/ lemma orthogonal_projection_tendsto_closure_supr [complete_space E] {ι : Type*} [semilattice_sup ι] (U : ι → submodule 𝕜 E) [∀ i, complete_space (U i)] (hU : monotone U) (x : E) : filter.tendsto (λ i, (orthogonal_projection (U i) x : E)) at_top (𝓝 (orthogonal_projection (⨆ i, U i).topological_closure x : E)) := begin casesI is_empty_or_nonempty ι, { rw filter_eq_bot_of_is_empty (at_top : filter ι), exact tendsto_bot }, let y := (orthogonal_projection (⨆ i, U i).topological_closure x : E), have proj_x : ∀ i, orthogonal_projection (U i) x = orthogonal_projection (U i) y := λ i, (orthogonal_projection_orthogonal_projection_of_le ((le_supr U i).trans (supr U).le_topological_closure) _).symm, suffices : ∀ ε > 0, ∃ I, ∀ i ≥ I, ‖(orthogonal_projection (U i) y : E) - y‖ < ε, { simpa only [proj_x, normed_add_comm_group.tendsto_at_top] using this }, intros ε hε, obtain ⟨a, ha, hay⟩ : ∃ a ∈ ⨆ i, U i, dist y a < ε, { have y_mem : y ∈ (⨆ i, U i).topological_closure := submodule.coe_mem _, rw [← set_like.mem_coe, submodule.topological_closure_coe, metric.mem_closure_iff] at y_mem, exact y_mem ε hε }, rw dist_eq_norm at hay, obtain ⟨I, hI⟩ : ∃ I, a ∈ U I, { rwa [submodule.mem_supr_of_directed _ (hU.directed_le)] at ha }, refine ⟨I, λ i (hi : I ≤ i), _⟩, rw [norm_sub_rev, orthogonal_projection_minimal], refine lt_of_le_of_lt _ hay, change _ ≤ ‖y - (⟨a, hU hi hI⟩ : U i)‖, exact cinfi_le ⟨0, set.forall_range_iff.mpr $ λ _, norm_nonneg _⟩ _, end /-- Given a monotone family `U` of complete submodules of `E` with dense span supremum, and a fixed `x : E`, the orthogonal projection of `x` on `U i` tends to `x` along `at_top`. -/ lemma orthogonal_projection_tendsto_self [complete_space E] {ι : Type*} [semilattice_sup ι] (U : ι → submodule 𝕜 E) [∀ t, complete_space (U t)] (hU : monotone U) (x : E) (hU' : ⊤ ≤ (⨆ t, U t).topological_closure) : filter.tendsto (λ t, (orthogonal_projection (U t) x : E)) at_top (𝓝 x) := begin rw ← eq_top_iff at hU', convert orthogonal_projection_tendsto_closure_supr U hU x, rw orthogonal_projection_eq_self_iff.mpr _, rw hU', trivial end /-- The orthogonal complement satisfies `Kᗮᗮᗮ = Kᗮ`. -/ lemma submodule.triorthogonal_eq_orthogonal [complete_space E] : Kᗮᗮᗮ = Kᗮ := begin rw Kᗮ.orthogonal_orthogonal_eq_closure, exact K.is_closed_orthogonal.submodule_topological_closure_eq, end /-- The closure of `K` is the full space iff `Kᗮ` is trivial. -/ lemma submodule.topological_closure_eq_top_iff [complete_space E] : K.topological_closure = ⊤ ↔ Kᗮ = ⊥ := begin rw ←submodule.orthogonal_orthogonal_eq_closure, split; intro h, { rw [←submodule.triorthogonal_eq_orthogonal, h, submodule.top_orthogonal_eq_bot] }, { rw [h, submodule.bot_orthogonal_eq_top] } end namespace dense open submodule variables {x y : E} [complete_space E] /-- If `S` is dense and `x - y ∈ Kᗮ`, then `x = y`. -/ lemma eq_of_sub_mem_orthogonal (hK : dense (K : set E)) (h : x - y ∈ Kᗮ) : x = y := begin rw [dense_iff_topological_closure_eq_top, topological_closure_eq_top_iff] at hK, rwa [hK, submodule.mem_bot, sub_eq_zero] at h, end lemma eq_zero_of_mem_orthogonal (hK : dense (K : set E)) (h : x ∈ Kᗮ) : x = 0 := hK.eq_of_sub_mem_orthogonal (by rwa [sub_zero]) lemma eq_of_inner_left (hK : dense (K : set E)) (h : ∀ v : K, ⟪x, v⟫ = ⟪y, v⟫) : x = y := hK.eq_of_sub_mem_orthogonal (submodule.sub_mem_orthogonal_of_inner_left h) lemma eq_zero_of_inner_left (hK : dense (K : set E)) (h : ∀ v : K, ⟪x, v⟫ = 0) : x = 0 := hK.eq_of_inner_left (λ v, by rw [inner_zero_left, h v]) lemma eq_of_inner_right (hK : dense (K : set E)) (h : ∀ v : K, ⟪(v : E), x⟫ = ⟪(v : E), y⟫) : x = y := hK.eq_of_sub_mem_orthogonal (submodule.sub_mem_orthogonal_of_inner_right h) lemma eq_zero_of_inner_right (hK : dense (K : set E)) (h : ∀ v : K, ⟪(v : E), x⟫ = 0) : x = 0 := hK.eq_of_inner_right (λ v, by rw [inner_zero_right, h v]) end dense /-- The reflection in `Kᗮ` of an element of `K` is its negation. -/ lemma reflection_mem_subspace_orthogonal_precomplement_eq_neg [complete_space E] {v : E} (hv : v ∈ K) : reflection Kᗮ v = -v := reflection_mem_subspace_orthogonal_complement_eq_neg (K.le_orthogonal_orthogonal hv) /-- The orthogonal projection onto `(𝕜 ∙ v)ᗮ` of `v` is zero. -/ lemma orthogonal_projection_orthogonal_complement_singleton_eq_zero [complete_space E] (v : E) : orthogonal_projection (𝕜 ∙ v)ᗮ v = 0 := orthogonal_projection_mem_subspace_orthogonal_precomplement_eq_zero (submodule.mem_span_singleton_self v) /-- The reflection in `(𝕜 ∙ v)ᗮ` of `v` is `-v`. -/ lemma reflection_orthogonal_complement_singleton_eq_neg [complete_space E] (v : E) : reflection (𝕜 ∙ v)ᗮ v = -v := reflection_mem_subspace_orthogonal_precomplement_eq_neg (submodule.mem_span_singleton_self v) lemma reflection_sub [complete_space F] {v w : F} (h : ‖v‖ = ‖w‖) : reflection (ℝ ∙ (v - w))ᗮ v = w := begin set R : F ≃ₗᵢ[ℝ] F := reflection (ℝ ∙ (v - w))ᗮ, suffices : R v + R v = w + w, { apply smul_right_injective F (by norm_num : (2:ℝ) ≠ 0), simpa [two_smul] using this }, have h₁ : R (v - w) = -(v - w) := reflection_orthogonal_complement_singleton_eq_neg (v - w), have h₂ : R (v + w) = v + w, { apply reflection_mem_subspace_eq_self, rw submodule.mem_orthogonal_singleton_iff_inner_left, rw real_inner_add_sub_eq_zero_iff, exact h }, convert congr_arg2 (+) h₂ h₁ using 1, { simp }, { abel } end variables (K) /-- In a complete space `E`, a vector splits as the sum of its orthogonal projections onto a complete submodule `K` and onto the orthogonal complement of `K`.-/ lemma eq_sum_orthogonal_projection_self_orthogonal_complement [complete_space E] [complete_space K] (w : E) : w = (orthogonal_projection K w : E) + (orthogonal_projection Kᗮ w : E) := begin obtain ⟨y, hy, z, hz, hwyz⟩ := K.exists_sum_mem_mem_orthogonal w, convert hwyz, { exact eq_orthogonal_projection_of_mem_orthogonal' hy hz hwyz }, { rw add_comm at hwyz, refine eq_orthogonal_projection_of_mem_orthogonal' hz _ hwyz, simp [hy] } end /-- The Pythagorean theorem, for an orthogonal projection.-/ lemma norm_sq_eq_add_norm_sq_projection (x : E) (S : submodule 𝕜 E) [complete_space E] [complete_space S] : ‖x‖^2 = ‖orthogonal_projection S x‖^2 + ‖orthogonal_projection Sᗮ x‖^2 := begin let p1 := orthogonal_projection S, let p2 := orthogonal_projection Sᗮ, have x_decomp : x = p1 x + p2 x := eq_sum_orthogonal_projection_self_orthogonal_complement S x, have x_orth : ⟪ (p1 x : E), p2 x ⟫ = 0 := submodule.inner_right_of_mem_orthogonal (set_like.coe_mem (p1 x)) (set_like.coe_mem (p2 x)), nth_rewrite 0 [x_decomp], simp only [sq, norm_add_sq_eq_norm_sq_add_norm_sq_of_inner_eq_zero ((p1 x) : E) (p2 x) x_orth, add_left_inj, mul_eq_mul_left_iff, norm_eq_zero, true_or, eq_self_iff_true, submodule.coe_norm, submodule.coe_eq_zero] end /-- In a complete space `E`, the projection maps onto a complete subspace `K` and its orthogonal complement sum to the identity. -/ lemma id_eq_sum_orthogonal_projection_self_orthogonal_complement [complete_space E] [complete_space K] : continuous_linear_map.id 𝕜 E = K.subtypeL.comp (orthogonal_projection K) + Kᗮ.subtypeL.comp (orthogonal_projection Kᗮ) := by { ext w, exact eq_sum_orthogonal_projection_self_orthogonal_complement K w } @[simp] lemma inner_orthogonal_projection_eq_of_mem_right [complete_space K] (u : K) (v : E) : ⟪orthogonal_projection K v, u⟫ = ⟪v, u⟫ := calc ⟪orthogonal_projection K v, u⟫ = ⟪(orthogonal_projection K v : E), u⟫ : K.coe_inner _ _ ... = ⟪(orthogonal_projection K v : E), u⟫ + ⟪v - orthogonal_projection K v, u⟫ : by rw [orthogonal_projection_inner_eq_zero _ _ (submodule.coe_mem _), add_zero] ... = ⟪v, u⟫ : by rw [← inner_add_left, add_sub_cancel'_right] @[simp] lemma inner_orthogonal_projection_eq_of_mem_left [complete_space K] (u : K) (v : E) : ⟪u, orthogonal_projection K v⟫ = ⟪(u : E), v⟫ := by rw [← inner_conj_symm, ← inner_conj_symm (u : E), inner_orthogonal_projection_eq_of_mem_right] /-- The orthogonal projection is self-adjoint. -/ lemma inner_orthogonal_projection_left_eq_right [complete_space K] (u v : E) : ⟪↑(orthogonal_projection K u), v⟫ = ⟪u, orthogonal_projection K v⟫ := by rw [← inner_orthogonal_projection_eq_of_mem_left, inner_orthogonal_projection_eq_of_mem_right] /-- The orthogonal projection is symmetric. -/ lemma orthogonal_projection_is_symmetric [complete_space K] : (K.subtypeL ∘L orthogonal_projection K : E →ₗ[𝕜] E).is_symmetric := inner_orthogonal_projection_left_eq_right K open finite_dimensional /-- Given a finite-dimensional subspace `K₂`, and a subspace `K₁` containined in it, the dimensions of `K₁` and the intersection of its orthogonal subspace with `K₂` add to that of `K₂`. -/ lemma submodule.finrank_add_inf_finrank_orthogonal {K₁ K₂ : submodule 𝕜 E} [finite_dimensional 𝕜 K₂] (h : K₁ ≤ K₂) : finrank 𝕜 K₁ + finrank 𝕜 (K₁ᗮ ⊓ K₂ : submodule 𝕜 E) = finrank 𝕜 K₂ := begin haveI := submodule.finite_dimensional_of_le h, haveI := proper_is_R_or_C 𝕜 K₁, have hd := submodule.finrank_sup_add_finrank_inf_eq K₁ (K₁ᗮ ⊓ K₂), rw [←inf_assoc, (submodule.orthogonal_disjoint K₁).eq_bot, bot_inf_eq, finrank_bot, submodule.sup_orthogonal_inf_of_complete_space h] at hd, rw add_zero at hd, exact hd.symm end /-- Given a finite-dimensional subspace `K₂`, and a subspace `K₁` containined in it, the dimensions of `K₁` and the intersection of its orthogonal subspace with `K₂` add to that of `K₂`. -/ lemma submodule.finrank_add_inf_finrank_orthogonal' {K₁ K₂ : submodule 𝕜 E} [finite_dimensional 𝕜 K₂] (h : K₁ ≤ K₂) {n : ℕ} (h_dim : finrank 𝕜 K₁ + n = finrank 𝕜 K₂) : finrank 𝕜 (K₁ᗮ ⊓ K₂ : submodule 𝕜 E) = n := by { rw ← add_right_inj (finrank 𝕜 K₁), simp [submodule.finrank_add_inf_finrank_orthogonal h, h_dim] } /-- Given a finite-dimensional space `E` and subspace `K`, the dimensions of `K` and `Kᗮ` add to that of `E`. -/ lemma submodule.finrank_add_finrank_orthogonal [finite_dimensional 𝕜 E] (K : submodule 𝕜 E) : finrank 𝕜 K + finrank 𝕜 Kᗮ = finrank 𝕜 E := begin convert submodule.finrank_add_inf_finrank_orthogonal (le_top : K ≤ ⊤) using 1, { rw inf_top_eq }, { simp } end /-- Given a finite-dimensional space `E` and subspace `K`, the dimensions of `K` and `Kᗮ` add to that of `E`. -/ lemma submodule.finrank_add_finrank_orthogonal' [finite_dimensional 𝕜 E] {K : submodule 𝕜 E} {n : ℕ} (h_dim : finrank 𝕜 K + n = finrank 𝕜 E) : finrank 𝕜 Kᗮ = n := by { rw ← add_right_inj (finrank 𝕜 K), simp [submodule.finrank_add_finrank_orthogonal, h_dim] } local attribute [instance] fact_finite_dimensional_of_finrank_eq_succ /-- In a finite-dimensional inner product space, the dimension of the orthogonal complement of the span of a nonzero vector is one less than the dimension of the space. -/ lemma finrank_orthogonal_span_singleton {n : ℕ} [_i : fact (finrank 𝕜 E = n + 1)] {v : E} (hv : v ≠ 0) : finrank 𝕜 (𝕜 ∙ v)ᗮ = n := submodule.finrank_add_finrank_orthogonal' $ by simp [finrank_span_singleton hv, _i.elim, add_comm] /-- An element `φ` of the orthogonal group of `F` can be factored as a product of reflections, and specifically at most as many reflections as the dimension of the complement of the fixed subspace of `φ`. -/ lemma linear_isometry_equiv.reflections_generate_dim_aux [finite_dimensional ℝ F] {n : ℕ} (φ : F ≃ₗᵢ[ℝ] F) (hn : finrank ℝ (ker (continuous_linear_map.id ℝ F - φ))ᗮ ≤ n) : ∃ l : list F, l.length ≤ n ∧ φ = (l.map (λ v, reflection (ℝ ∙ v)ᗮ)).prod := begin -- We prove this by strong induction on `n`, the dimension of the orthogonal complement of the -- fixed subspace of the endomorphism `φ` induction n with n IH generalizing φ, { -- Base case: `n = 0`, the fixed subspace is the whole space, so `φ = id` refine ⟨[], rfl.le, show φ = 1, from _⟩, have : ker (continuous_linear_map.id ℝ F - φ) = ⊤, { rwa [le_zero_iff, finrank_eq_zero, submodule.orthogonal_eq_bot_iff] at hn }, symmetry, ext x, have := linear_map.congr_fun (linear_map.ker_eq_top.mp this) x, simpa only [sub_eq_zero, continuous_linear_map.to_linear_map_eq_coe, continuous_linear_map.coe_sub, linear_map.sub_apply, linear_map.zero_apply] using this }, { -- Inductive step. Let `W` be the fixed subspace of `φ`. We suppose its complement to have -- dimension at most n + 1. let W := ker (continuous_linear_map.id ℝ F - φ), have hW : ∀ w ∈ W, φ w = w := λ w hw, (sub_eq_zero.mp hw).symm, by_cases hn' : finrank ℝ Wᗮ ≤ n, { obtain ⟨V, hV₁, hV₂⟩ := IH φ hn', exact ⟨V, hV₁.trans n.le_succ, hV₂⟩ }, -- Take a nonzero element `v` of the orthogonal complement of `W`. haveI : nontrivial Wᗮ := nontrivial_of_finrank_pos (by linarith [zero_le n] : 0 < finrank ℝ Wᗮ), obtain ⟨v, hv⟩ := exists_ne (0 : Wᗮ), have hφv : φ v ∈ Wᗮ, { intros w hw, rw [← hW w hw, linear_isometry_equiv.inner_map_map], exact v.prop w hw }, have hv' : (v:F) ∉ W, { intros h, exact hv ((submodule.mem_left_iff_eq_zero_of_disjoint W.orthogonal_disjoint).mp h) }, -- Let `ρ` be the reflection in `v - φ v`; this is designed to swap `v` and `φ v` let x : F := v - φ v, let ρ := reflection (ℝ ∙ x)ᗮ, -- Notation: Let `V` be the fixed subspace of `φ.trans ρ` let V := ker (continuous_linear_map.id ℝ F - (φ.trans ρ)), have hV : ∀ w, ρ (φ w) = w → w ∈ V, { intros w hw, change w - ρ (φ w) = 0, rw [sub_eq_zero, hw] }, -- Everything fixed by `φ` is fixed by `φ.trans ρ` have H₂V : W ≤ V, { intros w hw, apply hV, rw hW w hw, refine reflection_mem_subspace_eq_self _, rw submodule.mem_orthogonal_singleton_iff_inner_left, exact submodule.sub_mem _ v.prop hφv _ hw }, -- `v` is also fixed by `φ.trans ρ` have H₁V : (v : F) ∈ V, { apply hV, have : ρ v = φ v := reflection_sub (φ.norm_map v).symm, rw ←this, exact reflection_reflection _ _, }, -- By dimension-counting, the complement of the fixed subspace of `φ.trans ρ` has dimension at -- most `n` have : finrank ℝ Vᗮ ≤ n, { change finrank ℝ Wᗮ ≤ n + 1 at hn, have : finrank ℝ W + 1 ≤ finrank ℝ V := submodule.finrank_lt_finrank_of_lt (set_like.lt_iff_le_and_exists.2 ⟨H₂V, v, H₁V, hv'⟩), have : finrank ℝ V + finrank ℝ Vᗮ = finrank ℝ F := V.finrank_add_finrank_orthogonal, have : finrank ℝ W + finrank ℝ Wᗮ = finrank ℝ F := W.finrank_add_finrank_orthogonal, linarith }, -- So apply the inductive hypothesis to `φ.trans ρ` obtain ⟨l, hl, hφl⟩ := IH (ρ * φ) this, -- Prepend `ρ` to the factorization into reflections obtained for `φ.trans ρ`; this gives a -- factorization into reflections for `φ`. refine ⟨x :: l, nat.succ_le_succ hl, _⟩, rw [list.map_cons, list.prod_cons], have := congr_arg ((*) ρ) hφl, rwa [←mul_assoc, reflection_mul_reflection, one_mul] at this, } end /-- The orthogonal group of `F` is generated by reflections; specifically each element `φ` of the orthogonal group is a product of at most as many reflections as the dimension of `F`. Special case of the **Cartan–Dieudonné theorem**. -/ lemma linear_isometry_equiv.reflections_generate_dim [finite_dimensional ℝ F] (φ : F ≃ₗᵢ[ℝ] F) : ∃ l : list F, l.length ≤ finrank ℝ F ∧ φ = (l.map (λ v, reflection (ℝ ∙ v)ᗮ)).prod := let ⟨l, hl₁, hl₂⟩ := φ.reflections_generate_dim_aux le_rfl in ⟨l, hl₁.trans (submodule.finrank_le _), hl₂⟩ /-- The orthogonal group of `F` is generated by reflections. -/ lemma linear_isometry_equiv.reflections_generate [finite_dimensional ℝ F] : subgroup.closure (set.range (λ v : F, reflection (ℝ ∙ v)ᗮ)) = ⊤ := begin rw subgroup.eq_top_iff', intros φ, rcases φ.reflections_generate_dim with ⟨l, _, rfl⟩, apply (subgroup.closure _).list_prod_mem, intros x hx, rcases list.mem_map.mp hx with ⟨a, _, hax⟩, exact subgroup.subset_closure ⟨a, hax⟩, end end orthogonal section orthogonal_family variables {ι : Type*} /-- An orthogonal family of subspaces of `E` satisfies `direct_sum.is_internal` (that is, they provide an internal direct sum decomposition of `E`) if and only if their span has trivial orthogonal complement. -/ lemma orthogonal_family.is_internal_iff_of_is_complete [decidable_eq ι] {V : ι → submodule 𝕜 E} (hV : orthogonal_family 𝕜 (λ i, V i) (λ i, (V i).subtypeₗᵢ)) (hc : is_complete (↑(supr V) : set E)) : direct_sum.is_internal V ↔ (supr V)ᗮ = ⊥ := begin haveI : complete_space ↥(supr V) := hc.complete_space_coe, simp only [direct_sum.is_internal_submodule_iff_independent_and_supr_eq_top, hV.independent, true_and, submodule.orthogonal_eq_bot_iff] end /-- An orthogonal family of subspaces of `E` satisfies `direct_sum.is_internal` (that is, they provide an internal direct sum decomposition of `E`) if and only if their span has trivial orthogonal complement. -/ lemma orthogonal_family.is_internal_iff [decidable_eq ι] [finite_dimensional 𝕜 E] {V : ι → submodule 𝕜 E} (hV : orthogonal_family 𝕜 (λ i, V i) (λ i, (V i).subtypeₗᵢ)) : direct_sum.is_internal V ↔ (supr V)ᗮ = ⊥ := begin haveI h := finite_dimensional.proper_is_R_or_C 𝕜 ↥(supr V), exact hV.is_internal_iff_of_is_complete (complete_space_coe_iff_is_complete.mp infer_instance) end open_locale direct_sum /-- If `x` lies within an orthogonal family `v`, it can be expressed as a sum of projections. -/ lemma orthogonal_family.sum_projection_of_mem_supr [fintype ι] {V : ι → submodule 𝕜 E} [∀ i, complete_space ↥(V i)] (hV : orthogonal_family 𝕜 (λ i, V i) (λ i, (V i).subtypeₗᵢ)) (x : E) (hx : x ∈ supr V) : ∑ i, (orthogonal_projection (V i) x : E) = x := begin refine submodule.supr_induction _ hx (λ i x hx, _) _ (λ x y hx hy, _), { refine (finset.sum_eq_single_of_mem i (finset.mem_univ _) $ λ j _ hij, _).trans (orthogonal_projection_eq_self_iff.mpr hx), rw [orthogonal_projection_mem_subspace_orthogonal_complement_eq_zero, submodule.coe_zero], exact hV.is_ortho hij.symm hx }, { simp_rw [map_zero, submodule.coe_zero, finset.sum_const_zero] }, { simp_rw [map_add, submodule.coe_add, finset.sum_add_distrib], exact congr_arg2 (+) hx hy }, end /-- If a family of submodules is orthogonal, then the `orthogonal_projection` on a direct sum is just the coefficient of that direct sum. -/ lemma orthogonal_family.projection_direct_sum_coe_add_hom [decidable_eq ι] {V : ι → submodule 𝕜 E} (hV : orthogonal_family 𝕜 (λ i, V i) (λ i, (V i).subtypeₗᵢ)) (x : ⨁ i, V i) (i : ι) [complete_space ↥(V i)] : orthogonal_projection (V i) (direct_sum.coe_add_monoid_hom V x) = x i := begin induction x using direct_sum.induction_on with j x x y hx hy, { simp }, { simp_rw [direct_sum.coe_add_monoid_hom_of, direct_sum.of, dfinsupp.single_add_hom_apply], obtain rfl | hij := decidable.eq_or_ne i j, { rw [orthogonal_projection_mem_subspace_eq_self, dfinsupp.single_eq_same] }, { rw [orthogonal_projection_mem_subspace_orthogonal_complement_eq_zero, dfinsupp.single_eq_of_ne hij.symm], exact hV.is_ortho hij.symm x.prop } }, { simp_rw [map_add, dfinsupp.add_apply], exact congr_arg2 (+) hx hy }, end /-- If a family of submodules is orthogonal and they span the whole space, then the orthogonal projection provides a means to decompose the space into its submodules. The projection function is `decompose V x i = orthogonal_projection (V i) x`. See note [reducible non-instances]. -/ @[reducible] def orthogonal_family.decomposition [decidable_eq ι] [fintype ι] {V : ι → submodule 𝕜 E} [∀ i, complete_space ↥(V i)] (hV : orthogonal_family 𝕜 (λ i, V i) (λ i, (V i).subtypeₗᵢ)) (h : supr V = ⊤) : direct_sum.decomposition V := { decompose' := λ x, dfinsupp.equiv_fun_on_fintype.symm $ λ i, orthogonal_projection (V i) x, left_inv := λ x, begin dsimp only, letI := λ i, classical.dec_eq (V i), rw [direct_sum.coe_add_monoid_hom, direct_sum.to_add_monoid, dfinsupp.lift_add_hom_apply, dfinsupp.sum_add_hom_apply, dfinsupp.sum_eq_sum_fintype], { simp_rw [equiv.apply_symm_apply, add_submonoid_class.coe_subtype], exact hV.sum_projection_of_mem_supr _ ((h.ge : _) submodule.mem_top),}, { intro i, exact map_zero _ }, end, right_inv := λ x, begin dsimp only, simp_rw [hV.projection_direct_sum_coe_add_hom, dfinsupp.equiv_fun_on_fintype_symm_coe], end } end orthogonal_family section orthonormal_basis variables {𝕜 E} {v : set E} open finite_dimensional submodule set /-- An orthonormal set in an `inner_product_space` is maximal, if and only if the orthogonal complement of its span is empty. -/ lemma maximal_orthonormal_iff_orthogonal_complement_eq_bot (hv : orthonormal 𝕜 (coe : v → E)) : (∀ u ⊇ v, orthonormal 𝕜 (coe : u → E) → u = v) ↔ (span 𝕜 v)ᗮ = ⊥ := begin rw submodule.eq_bot_iff, split, { contrapose!, -- ** direction 1: nonempty orthogonal complement implies nonmaximal rintros ⟨x, hx', hx⟩, -- take a nonzero vector and normalize it let e := (‖x‖⁻¹ : 𝕜) • x, have he : ‖e‖ = 1 := by simp [e, norm_smul_inv_norm hx], have he' : e ∈ (span 𝕜 v)ᗮ := smul_mem' _ _ hx', have he'' : e ∉ v, { intros hev, have : e = 0, { have : e ∈ (span 𝕜 v) ⊓ (span 𝕜 v)ᗮ := ⟨subset_span hev, he'⟩, simpa [(span 𝕜 v).inf_orthogonal_eq_bot] using this }, have : e ≠ 0 := hv.ne_zero ⟨e, hev⟩, contradiction }, -- put this together with `v` to provide a candidate orthonormal basis for the whole space refine ⟨insert e v, v.subset_insert e, ⟨_, _⟩, (v.ne_insert_of_not_mem he'').symm⟩, { -- show that the elements of `insert e v` have unit length rintros ⟨a, ha'⟩, cases eq_or_mem_of_mem_insert ha' with ha ha, { simp [ha, he] }, { exact hv.1 ⟨a, ha⟩ } }, { -- show that the elements of `insert e v` are orthogonal have h_end : ∀ a ∈ v, ⟪a, e⟫ = 0, { intros a ha, exact he' a (submodule.subset_span ha) }, rintros ⟨a, ha'⟩, cases eq_or_mem_of_mem_insert ha' with ha ha, { rintros ⟨b, hb'⟩ hab', have hb : b ∈ v, { refine mem_of_mem_insert_of_ne hb' _, intros hbe', apply hab', simp [ha, hbe'] }, rw inner_eq_zero_symm, simpa [ha] using h_end b hb }, rintros ⟨b, hb'⟩ hab', cases eq_or_mem_of_mem_insert hb' with hb hb, { simpa [hb] using h_end a ha }, have : (⟨a, ha⟩ : v) ≠ ⟨b, hb⟩, { intros hab'', apply hab', simpa using hab'' }, exact hv.2 this } }, { -- ** direction 2: empty orthogonal complement implies maximal simp only [subset.antisymm_iff], rintros h u (huv : v ⊆ u) hu, refine ⟨_, huv⟩, intros x hxu, refine ((mt (h x)) (hu.ne_zero ⟨x, hxu⟩)).imp_symm _, intros hxv y hy, have hxv' : (⟨x, hxu⟩ : u) ∉ (coe ⁻¹' v : set u) := by simp [huv, hxv], obtain ⟨l, hl, rfl⟩ : ∃ l ∈ finsupp.supported 𝕜 𝕜 (coe ⁻¹' v : set u), (finsupp.total ↥u E 𝕜 coe) l = y, { rw ← finsupp.mem_span_image_iff_total, simp [huv, inter_eq_self_of_subset_left, hy] }, exact hu.inner_finsupp_eq_zero hxv' hl } end variables [finite_dimensional 𝕜 E] /-- An orthonormal set in a finite-dimensional `inner_product_space` is maximal, if and only if it is a basis. -/ lemma maximal_orthonormal_iff_basis_of_finite_dimensional (hv : orthonormal 𝕜 (coe : v → E)) : (∀ u ⊇ v, orthonormal 𝕜 (coe : u → E) → u = v) ↔ ∃ b : basis v 𝕜 E, ⇑b = coe := begin haveI := proper_is_R_or_C 𝕜 (span 𝕜 v), rw maximal_orthonormal_iff_orthogonal_complement_eq_bot hv, have hv_compl : is_complete (span 𝕜 v : set E) := (span 𝕜 v).complete_of_finite_dimensional, rw submodule.orthogonal_eq_bot_iff, have hv_coe : range (coe : v → E) = v := by simp, split, { refine λ h, ⟨basis.mk hv.linear_independent _, basis.coe_mk _ _⟩, convert h.ge }, { rintros ⟨h, coe_h⟩, rw [← h.span_eq, coe_h, hv_coe] } end end orthonormal_basis
871c80b196f694e91c09d4b95cfe526b761d324c
b561a44b48979a98df50ade0789a21c79ee31288
/src/Lean/Elab/Command.lean
a87e7a6c9014f04f87a394e39f2ca1df6112a139
[ "Apache-2.0" ]
permissive
3401ijk/lean4
97659c475ebd33a034fed515cb83a85f75ccfb06
a5b1b8de4f4b038ff752b9e607b721f15a9a4351
refs/heads/master
1,693,933,007,651
1,636,424,845,000
1,636,424,845,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
18,347
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.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 := let i := inferInstanceAs (Monad CommandElabM); { pure := i.pure, bind := i.bind } 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 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, traceState := s.traceState } let (ea, coreS) ← liftM x modify fun s => { s with env := coreS.env, ngen := coreS.ngen, traceState := coreS.traceState } 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 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 mkInfoTree (elaborator : Name) (stx : Syntax) (trees : Std.PersistentArray InfoTree) : CommandElabM InfoTree := do let ctx ← read let s ← get let scope := s.scopes.head! let tree := InfoTree.node (Info.ofCommandInfo { elaborator, stx }) trees return InfoTree.context { env := s.env, fileMap := ctx.fileMap, mctx := {}, currNamespace := scope.currNamespace, openDecls := scope.openDecls, options := scope.opts } tree private def elabCommandUsing (s : State) (stx : Syntax) : List (KeyedDeclsAttribute.AttributeEntry CommandElab) → CommandElabM Unit | [] => throwError "unexpected syntax{indentD stx}" | (elabFn::elabFns) => catchInternalId unsupportedSyntaxExceptionId (withInfoTreeContext (mkInfoTree := mkInfoTree elabFn.declName stx) <| elabFn.value stx) (fun _ => do set s; elabCommandUsing s stx elabFns) /- Elaborate `x` with `stx` on the macro stack -/ 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)" } 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 withLogging <| withRef stx <| withIncRecDepth <| withFreshMacroScope do 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 match (← liftMacroM <| expandMacroImpl? s.env stx) with | some (decl, stxNew) => withInfoTreeContext (mkInfoTree := mkInfoTree decl stx) do withMacroExpansion stx stxNew do elabCommand stxNew | _ => match commandElabAttribute.getEntries s.env k with | [] => throwError "elaboration function for '{k}' has not been implemented" | elabFns => elabCommandUsing s stx elabFns | _ => throwError "unexpected command" /-- `elabCommand` wrapper that should be used for the initial invocation, not for recursive calls after macro expansion etc. -/ def elabCommandTopLevel (stx : Syntax) : CommandElabM Unit := withRef stx do let initMsgs ← modifyGet fun st => (st.messages, { st with messages := {} }) let initInfoTrees ← getResetInfoTrees withLogging do runLinters stx -- We should *not* factor out `elabCommand`'s `withLogging` to here since it would make its error -- recovery more coarse. In particular, If `c` in `set_option ... in $c` fails, the remaining -- `end` command of the `in` macro would be skipped and the option would be leaked to the outside! elabCommand stx -- note the order: first process current messages & info trees, then add back old messages & trees, -- then convert new traces to messages 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⟩ for tree in (← getInfoTrees) do trace[Elab.info] (← tree.format) modify fun st => { st with messages := initMsgs ++ msgs infoState := { st.infoState with trees := initInfoTrees ++ st.infoState.trees } } addTraceAsMessages /-- 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 -- 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 : TermElabM _ := withSaveInfoContext x 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 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 termS.infoState.trees } 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 def getScopes : CommandElabM (List Scope) := do pure (← get).scopes def modifyScope (f : Scope → Scope) : CommandElabM Unit := modify fun s => { s with scopes := match s.scopes with | h::t => f h :: t | [] => unreachable! } def withScope (f : Scope → Scope) (x : CommandElabM α) : CommandElabM α := do match (← get).scopes with | [] => x | h :: t => try modify fun s => { s with scopes := f h :: t } x finally modify fun s => { s with scopes := h :: t } 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 } 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
6aae29bfb735ca1fcc18d38c36642fb9f95cf6dc
26ac254ecb57ffcb886ff709cf018390161a9225
/src/algebra/field.lean
f72ba4e3ef9e976e4cb3a54132f5072efe519a9e
[ "Apache-2.0" ]
permissive
eric-wieser/mathlib
42842584f584359bbe1fc8b88b3ff937c8acd72d
d0df6b81cd0920ad569158c06a3fd5abb9e63301
refs/heads/master
1,669,546,404,255
1,595,254,668,000
1,595,254,668,000
281,173,504
0
0
Apache-2.0
1,595,263,582,000
1,595,263,581,000
null
UTF-8
Lean
false
false
7,486
lean
/- Copyright (c) 2014 Robert Lewis. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Robert Lewis, Leonardo de Moura, Johannes Hölzl, Mario Carneiro -/ import algebra.ring import algebra.group_with_zero open set set_option default_priority 100 -- see Note [default priority] set_option old_structure_cmd true universe u variables {α : Type u} @[protect_proj, ancestor ring has_inv] class division_ring (α : Type u) extends ring α, has_inv α, nontrivial α := (mul_inv_cancel : ∀ {a : α}, a ≠ 0 → a * a⁻¹ = 1) (inv_mul_cancel : ∀ {a : α}, a ≠ 0 → a⁻¹ * a = 1) (inv_zero : (0 : α)⁻¹ = 0) section division_ring variables [division_ring α] {a b : α} instance division_ring_has_div : has_div α := ⟨λ a b, a * b⁻¹⟩ /-- Every division ring is a `group_with_zero`. -/ @[priority 100] -- see Note [lower instance priority] instance division_ring.to_group_with_zero : group_with_zero α := { .. ‹division_ring α›, .. (infer_instance : semiring α) } @[simp] lemma one_div_eq_inv (a : α) : 1 / a = a⁻¹ := one_mul a⁻¹ @[field_simps] lemma inv_eq_one_div (a : α) : a⁻¹ = 1 / a := by simp local attribute [simp] division_def mul_comm mul_assoc mul_left_comm mul_inv_cancel inv_mul_cancel @[field_simps] lemma mul_div_assoc' (a b c : α) : a * (b / c) = (a * b) / c := by simp [mul_div_assoc] lemma one_div_neg_one_eq_neg_one : (1:α) / (-1) = -1 := have (-1) * (-1) = (1:α), by rw [neg_mul_neg, one_mul], eq.symm (eq_one_div_of_mul_eq_one this) lemma one_div_neg_eq_neg_one_div (a : α) : 1 / (- a) = - (1 / a) := calc 1 / (- a) = 1 / ((-1) * a) : by rw neg_eq_neg_one_mul ... = (1 / a) * (1 / (- 1)) : by rw one_div_mul_one_div_rev ... = (1 / a) * (-1) : by rw one_div_neg_one_eq_neg_one ... = - (1 / a) : by rw [mul_neg_eq_neg_mul_symm, mul_one] lemma div_neg_eq_neg_div (a b : α) : b / (- a) = - (b / a) := calc b / (- a) = b * (1 / (- a)) : by rw [← inv_eq_one_div, division_def] ... = b * -(1 / a) : by rw one_div_neg_eq_neg_one_div ... = -(b * (1 / a)) : by rw neg_mul_eq_mul_neg ... = - (b * a⁻¹) : by rw inv_eq_one_div lemma neg_div (a b : α) : (-b) / a = - (b / a) := by rw [neg_eq_neg_one_mul, mul_div_assoc, ← neg_eq_neg_one_mul] @[field_simps] lemma neg_div' {α : Type*} [division_ring α] (a b : α) : - (b / a) = (-b) / a := by simp [neg_div] lemma neg_div_neg_eq (a b : α) : (-a) / (-b) = a / b := by rw [div_neg_eq_neg_div, neg_div, neg_neg] @[field_simps] lemma div_add_div_same (a b c : α) : a / c + b / c = (a + b) / c := eq.symm $ right_distrib a b (c⁻¹) lemma div_sub_div_same (a b c : α) : (a / c) - (b / c) = (a - b) / c := by rw [sub_eq_add_neg, ← neg_div, div_add_div_same, sub_eq_add_neg] lemma neg_inv : - a⁻¹ = (- a)⁻¹ := by rw [inv_eq_one_div, inv_eq_one_div, div_neg_eq_neg_div] lemma add_div (a b c : α) : (a + b) / c = a / c + b / c := (div_add_div_same _ _ _).symm lemma sub_div (a b c : α) : (a - b) / c = a / c - b / c := (div_sub_div_same _ _ _).symm lemma div_neg (a : α) : a / -b = -(a / b) := by rw [← div_neg_eq_neg_div] lemma inv_neg : (-a)⁻¹ = -(a⁻¹) := by rw neg_inv lemma one_div_mul_add_mul_one_div_eq_one_div_add_one_div (ha : a ≠ 0) (hb : b ≠ 0) : (1 / a) * (a + b) * (1 / b) = 1 / a + 1 / b := by rw [(left_distrib (1 / a)), (one_div_mul_cancel ha), right_distrib, one_mul, mul_assoc, (mul_one_div_cancel hb), mul_one, add_comm] lemma one_div_mul_sub_mul_one_div_eq_one_div_add_one_div (ha : a ≠ 0) (hb : b ≠ 0) : (1 / a) * (b - a) * (1 / b) = 1 / a - 1 / b := by rw [(mul_sub_left_distrib (1 / a)), (one_div_mul_cancel ha), mul_sub_right_distrib, one_mul, mul_assoc, (mul_one_div_cancel hb), mul_one] lemma add_div_eq_mul_add_div (a b : α) {c : α} (hc : c ≠ 0) : a + b / c = (a * c + b) / c := (eq_div_iff_mul_eq hc).2 $ by rw [right_distrib, (div_mul_cancel _ hc)] instance division_ring.to_domain : domain α := { ..‹division_ring α›, ..(by apply_instance : semiring α), ..(by apply_instance : no_zero_divisors α) } end division_ring @[protect_proj, ancestor division_ring comm_ring] class field (α : Type u) extends comm_ring α, has_inv α, nontrivial α := (mul_inv_cancel : ∀ {a : α}, a ≠ 0 → a * a⁻¹ = 1) (inv_zero : (0 : α)⁻¹ = 0) section field variable [field α] instance field.to_division_ring : division_ring α := { inv_mul_cancel := λ _ h, by rw [mul_comm, field.mul_inv_cancel h] ..show field α, by apply_instance } /-- Every field is a `comm_group_with_zero`. -/ instance field.to_comm_group_with_zero : comm_group_with_zero α := { .. (_ : group_with_zero α), .. ‹field α› } lemma one_div_add_one_div {a b : α} (ha : a ≠ 0) (hb : b ≠ 0) : 1 / a + 1 / b = (a + b) / (a * b) := by rw [add_comm, ← div_mul_left ha, ← div_mul_right _ hb, division_def, division_def, division_def, ← right_distrib, mul_comm a] local attribute [simp] mul_assoc mul_comm mul_left_comm lemma div_add_div (a : α) {b : α} (c : α) {d : α} (hb : b ≠ 0) (hd : d ≠ 0) : (a / b) + (c / d) = ((a * d) + (b * c)) / (b * d) := by rw [← mul_div_mul_right _ b hd, ← mul_div_mul_left c d hb, div_add_div_same] @[field_simps] lemma div_sub_div (a : α) {b : α} (c : α) {d : α} (hb : b ≠ 0) (hd : d ≠ 0) : (a / b) - (c / d) = ((a * d) - (b * c)) / (b * d) := begin simp [sub_eq_add_neg], rw [neg_eq_neg_one_mul, ← mul_div_assoc, div_add_div _ _ hb hd, ← mul_assoc, mul_comm b, mul_assoc, ← neg_eq_neg_one_mul] end lemma inv_add_inv {a b : α} (ha : a ≠ 0) (hb : b ≠ 0) : a⁻¹ + b⁻¹ = (a + b) / (a * b) := by rw [inv_eq_one_div, inv_eq_one_div, one_div_add_one_div ha hb] lemma inv_sub_inv {a b : α} (ha : a ≠ 0) (hb : b ≠ 0) : a⁻¹ - b⁻¹ = (b - a) / (a * b) := by rw [inv_eq_one_div, inv_eq_one_div, div_sub_div _ _ ha hb, one_mul, mul_one] @[field_simps] lemma add_div' (a b c : α) (hc : c ≠ 0) : b + a / c = (b * c + a) / c := by simpa using div_add_div b a one_ne_zero hc @[field_simps] lemma sub_div' (a b c : α) (hc : c ≠ 0) : b - a / c = (b * c - a) / c := by simpa using div_sub_div b a one_ne_zero hc @[field_simps] lemma div_add' (a b c : α) (hc : c ≠ 0) : a / c + b = (a + b * c) / c := by rwa [add_comm, add_div', add_comm] @[field_simps] lemma div_sub' (a b c : α) (hc : c ≠ 0) : a / c - b = (a - c * b) / c := by simpa using div_sub_div a b hc one_ne_zero @[priority 100] -- see Note [lower instance priority] instance field.to_integral_domain : integral_domain α := { ..‹field α›, ..division_ring.to_domain } end field namespace ring_hom section variables {R K : Type*} [semiring R] [field K] (f : R →+* K) @[simp] lemma map_units_inv (u : units R) : f ↑u⁻¹ = (f ↑u)⁻¹ := monoid_hom.map_units_inv f.to_monoid_hom u end section variables {β : Type*} [division_ring α] [division_ring β] (f : α →+* β) {x y : α} lemma map_ne_zero : f x ≠ 0 ↔ x ≠ 0 := (f : α →* β).map_ne_zero f.map_zero lemma map_eq_zero : f x = 0 ↔ x = 0 := (f : α →* β).map_eq_zero f.map_zero variables (x y) lemma map_inv : f x⁻¹ = (f x)⁻¹ := (f : α →* β).map_inv' f.map_zero x lemma map_div : f (x / y) = f x / f y := (f : α →* β).map_div f.map_zero x y protected lemma injective : function.injective f := f.injective_iff.2 $ λ x, f.map_eq_zero.1 end end ring_hom
a29d14f2ef71b8cc48daf11e363c3e79a395cfd2
367134ba5a65885e863bdc4507601606690974c1
/src/category_theory/Fintype.lean
d80f74c9ffbab0e12a76fc8029cf2c177ef1629e
[ "Apache-2.0" ]
permissive
kodyvajjha/mathlib
9bead00e90f68269a313f45f5561766cfd8d5cad
b98af5dd79e13a38d84438b850a2e8858ec21284
refs/heads/master
1,624,350,366,310
1,615,563,062,000
1,615,563,062,000
162,666,963
0
0
Apache-2.0
1,545,367,651,000
1,545,367,651,000
null
UTF-8
Lean
false
false
3,534
lean
/- Copyright (c) 2020 Adam Topaz. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Bhavik Mehta, Adam Topaz -/ import data.fintype.basic import data.fin import category_theory.concrete_category.bundled import category_theory.concrete_category import category_theory.full_subcategory import category_theory.skeletal /-! # The category of finite types. We define the category of finite types, denoted `Fintype` as (bundled) types with a `fintype` instance. We also define `Fintype.skeleton`, the standard skeleton of `Fintype` whose objects are `fin n` for `n : ℕ`. We prove that the obvious inclusion functor `Fintype.skeleton ⥤ Fintype` is an equivalence of categories in `Fintype.skeleton.equivalence`. We prove that `Fintype.skeleton` is a skeleton of `Fintype` in `Fintype.is_skeleton`. -/ open_locale classical open category_theory /-- The category of finite types. -/ @[derive has_coe_to_sort] def Fintype := bundled fintype namespace Fintype /-- Construct a bundled `Fintype` from the underlying type and typeclass. -/ def of (X : Type*) [fintype X] : Fintype := bundled.of X instance : inhabited Fintype := ⟨⟨pempty⟩⟩ instance {X : Fintype} : fintype X := X.2 instance : category Fintype := induced_category.category bundled.α /-- The fully faithful embedding of `Fintype` into the category of types. -/ @[derive [full, faithful], simps] def incl : Fintype ⥤ Type* := induced_functor _ instance : concrete_category Fintype := ⟨incl⟩ /-- The "standard" skeleton for `Fintype`. This is the full subcategory of `Fintype` spanned by objects of the form `fin n` for `n : ℕ`. We parameterize the objects of `Fintype.skeleton` directly as `ℕ`, as the type `fin m ≃ fin n` is nonempty if and only if `n = m`. -/ def skeleton := ℕ namespace skeleton /-- Given any natural number `n`, this creates the associated object of `Fintype.skeleton`. -/ def mk : ℕ → skeleton := id instance : inhabited skeleton := ⟨mk 0⟩ /-- Given any object of `Fintype.skeleton`, this returns the associated natural number. -/ def to_nat : skeleton → ℕ := id instance : category skeleton := { hom := λ X Y, fin X → fin Y, id := λ _, id, comp := λ _ _ _ f g, g ∘ f } lemma is_skeletal : skeletal skeleton := λ X Y ⟨h⟩, fin.equiv_iff_eq.mp $ nonempty.intro $ { to_fun := h.1, inv_fun := h.2, left_inv := λ _, by {change (h.hom ≫ h.inv) _ = _, simpa}, right_inv := λ _, by {change (h.inv ≫ h.hom) _ = _, simpa} } /-- The canonical fully faithful embedding of `Fintype.skeleton` into `Fintype`. -/ def incl : skeleton ⥤ Fintype := { obj := λ X, Fintype.of (fin X), map := λ _ _ f, f } instance : full incl := { preimage := λ _ _ f, f } instance : faithful incl := {} instance : ess_surj incl := { mem_ess_image := λ X, let F := trunc.out (fintype.equiv_fin X) in ⟨fintype.card X, ⟨⟨F.symm, F, F.self_comp_symm, F.symm_comp_self⟩⟩⟩ } noncomputable instance : is_equivalence incl := equivalence.equivalence_of_fully_faithfully_ess_surj _ /-- The equivalence between `Fintype.skeleton` and `Fintype`. -/ noncomputable def equivalence : skeleton ≌ Fintype := incl.as_equivalence @[simp] lemma incl_mk_nat_card (n : ℕ) : fintype.card (incl.obj (mk n)) = n := finset.card_fin n end skeleton /-- `Fintype.skeleton` is a skeleton of `Fintype`. -/ noncomputable def is_skeleton : is_skeleton_of Fintype skeleton skeleton.incl := { skel := skeleton.is_skeletal, eqv := by apply_instance } end Fintype
04840d646484d75d6e1e80a3ab2642837d64d555
367134ba5a65885e863bdc4507601606690974c1
/src/algebra/polynomial/group_ring_action.lean
581c6735a266add989dd28c656c13f7411b1b0ce
[ "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,513
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.polynomial.monic import algebra.group_ring_action import algebra.group_action_hom /-! # Group action on rings applied to polynomials This file contains instances and definitions relating `mul_semiring_action` to `polynomial`. -/ variables (M : Type*) [monoid M] namespace polynomial variables (R : Type*) [semiring R] noncomputable instance [mul_semiring_action M R] : mul_semiring_action M (polynomial R) := { smul := λ m, map $ mul_semiring_action.to_semiring_hom M R m, one_smul := λ p, by { ext n, erw coeff_map, exact one_smul M (p.coeff n) }, mul_smul := λ m n p, by { ext i, iterate 3 { rw coeff_map (mul_semiring_action.to_semiring_hom M R _) }, exact mul_smul m n (p.coeff i) }, smul_add := λ m p q, map_add (mul_semiring_action.to_semiring_hom M R m), smul_zero := λ m, map_zero (mul_semiring_action.to_semiring_hom M R m), smul_one := λ m, map_one (mul_semiring_action.to_semiring_hom M R m), smul_mul := λ m p q, map_mul (mul_semiring_action.to_semiring_hom M R m), } noncomputable instance [faithful_mul_semiring_action M R] : faithful_mul_semiring_action M (polynomial R) := { eq_of_smul_eq_smul' := λ m₁ m₂ h, eq_of_smul_eq_smul R $ λ s, C_inj.1 $ calc C (m₁ • s) = m₁ • C s : (map_C $ mul_semiring_action.to_semiring_hom M R m₁).symm ... = m₂ • C s : h (C s) ... = C (m₂ • s) : map_C _, .. polynomial.mul_semiring_action M R } variables {M R} variables [mul_semiring_action M R] @[simp] lemma coeff_smul' (m : M) (p : polynomial R) (n : ℕ) : (m • p).coeff n = m • p.coeff n := coeff_map _ _ @[simp] lemma smul_C (m : M) (r : R) : m • C r = C (m • r) := map_C _ @[simp] lemma smul_X (m : M) : (m • X : polynomial R) = X := map_X _ variables (S : Type*) [comm_semiring S] [mul_semiring_action M S] theorem smul_eval_smul (m : M) (f : polynomial S) (x : S) : (m • f).eval (m • x) = m • f.eval x := polynomial.induction_on f (λ r, by rw [smul_C, eval_C, eval_C]) (λ f g ihf ihg, by rw [smul_add, eval_add, ihf, ihg, eval_add, smul_add]) (λ n r ih, by rw [smul_mul', smul_pow, smul_C, smul_X, eval_mul, eval_C, eval_pow, eval_X, eval_mul, eval_C, eval_pow, eval_X, smul_mul', smul_pow]) variables (G : Type*) [group G] theorem eval_smul' [mul_semiring_action G S] (g : G) (f : polynomial S) (x : S) : f.eval (g • x) = g • (g⁻¹ • f).eval x := by rw [← smul_eval_smul, smul_inv_smul] theorem smul_eval [mul_semiring_action G S] (g : G) (f : polynomial S) (x : S) : (g • f).eval x = g • f.eval (g⁻¹ • x) := by rw [← smul_eval_smul, smul_inv_smul] end polynomial section comm_ring variables (G : Type*) [group G] [fintype G] variables (R : Type*) [comm_ring R] [mul_semiring_action G R] open mul_action open_locale classical /-- the product of `(X - g • x)` over distinct `g • x`. -/ noncomputable def prod_X_sub_smul (x : R) : polynomial R := (finset.univ : finset (quotient_group.quotient $ mul_action.stabilizer G x)).prod $ λ g, polynomial.X - polynomial.C (of_quotient_stabilizer G x g) theorem prod_X_sub_smul.monic (x : R) : (prod_X_sub_smul G R x).monic := polynomial.monic_prod_of_monic _ _ $ λ g _, polynomial.monic_X_sub_C _ theorem prod_X_sub_smul.eval (x : R) : (prod_X_sub_smul G R x).eval x = 0 := (finset.prod_hom _ (polynomial.eval x)).symm.trans $ finset.prod_eq_zero (finset.mem_univ $ quotient_group.mk 1) $ by rw [of_quotient_stabilizer_mk, one_smul, polynomial.eval_sub, polynomial.eval_X, polynomial.eval_C, sub_self] theorem prod_X_sub_smul.smul (x : R) (g : G) : g • prod_X_sub_smul G R x = prod_X_sub_smul G R x := (smul_prod _ _ _ _ _).trans $ finset.prod_bij (λ g' _, g • g') (λ _ _, finset.mem_univ _) (λ g' _, by rw [of_quotient_stabilizer_smul, smul_sub, polynomial.smul_X, polynomial.smul_C]) (λ _ _ _ _ H, (mul_action.bijective g).1 H) (λ g' _, ⟨g⁻¹ • g', finset.mem_univ _, by rw [smul_smul, mul_inv_self, one_smul]⟩) theorem prod_X_sub_smul.coeff (x : R) (g : G) (n : ℕ) : g • (prod_X_sub_smul G R x).coeff n = (prod_X_sub_smul G R x).coeff n := by rw [← polynomial.coeff_smul', prod_X_sub_smul.smul] end comm_ring namespace mul_semiring_action_hom variables {M} variables {P : Type*} [comm_semiring P] [mul_semiring_action M P] variables {Q : Type*} [comm_semiring Q] [mul_semiring_action M Q] open polynomial /-- An equivariant map induces an equivariant map on polynomials. -/ protected noncomputable def polynomial (g : P →+*[M] Q) : polynomial P →+*[M] polynomial Q := { to_fun := map g, map_smul' := λ m p, polynomial.induction_on p (λ b, by rw [smul_C, map_C, coe_fn_coe, g.map_smul, map_C, coe_fn_coe, smul_C]) (λ p q ihp ihq, by rw [smul_add, polynomial.map_add, ihp, ihq, polynomial.map_add, smul_add]) (λ n b ih, by rw [smul_mul', smul_C, smul_pow, smul_X, polynomial.map_mul, map_C, polynomial.map_pow, map_X, coe_fn_coe, g.map_smul, polynomial.map_mul, map_C, polynomial.map_pow, map_X, smul_mul', smul_C, smul_pow, smul_X, coe_fn_coe]), map_zero' := polynomial.map_zero g, map_add' := λ p q, polynomial.map_add g, map_one' := polynomial.map_one g, map_mul' := λ p q, polynomial.map_mul g } @[simp] theorem coe_polynomial (g : P →+*[M] Q) : (g.polynomial : polynomial P → polynomial Q) = map g := rfl end mul_semiring_action_hom
0e147518a02e1c8b723c90554f263a849aa64c05
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/field_theory/finite/polynomial.lean
31bc5929653de541d9f266ffa5cafe52b82f3093
[ "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
8,069
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 linear_algebra.finite_dimensional import linear_algebra.basic import ring_theory.mv_polynomial.basic import data.mv_polynomial.expand import field_theory.finite.basic /-! ## Polynomials over finite fields -/ namespace mv_polynomial variables {σ : Type*} /-- A polynomial over the integers is divisible by `n : ℕ` if and only if it is zero over `zmod n`. -/ lemma C_dvd_iff_zmod (n : ℕ) (φ : mv_polynomial σ ℤ) : C (n:ℤ) ∣ φ ↔ map (int.cast_ring_hom (zmod n)) φ = 0 := C_dvd_iff_map_hom_eq_zero _ _ (char_p.int_cast_eq_zero_iff (zmod n) n) _ section frobenius variables {p : ℕ} [fact p.prime] lemma frobenius_zmod (f : mv_polynomial σ (zmod p)) : frobenius _ p f = expand p f := begin apply induction_on f, { intro a, rw [expand_C, frobenius_def, ← C_pow, zmod.pow_card], }, { simp only [alg_hom.map_add, ring_hom.map_add], intros _ _ hf hg, rw [hf, hg] }, { simp only [expand_X, ring_hom.map_mul, alg_hom.map_mul], intros _ _ hf, rw [hf, frobenius_def], }, end lemma expand_zmod (f : mv_polynomial σ (zmod p)) : expand p f = f ^ p := (frobenius_zmod _).symm end frobenius end mv_polynomial namespace mv_polynomial noncomputable theory open_locale big_operators classical open set linear_map submodule variables {K : Type*} {σ : Type*} section indicator variables [fintype K] [fintype σ] /-- Over a field, this is the indicator function as an `mv_polynomial`. -/ def indicator [comm_ring K] (a : σ → K) : mv_polynomial σ K := ∏ n, (1 - (X n - C (a n)) ^ (fintype.card K - 1)) section comm_ring variables [comm_ring K] lemma eval_indicator_apply_eq_one (a : σ → K) : eval a (indicator a) = 1 := begin nontriviality, have : 0 < fintype.card K - 1 := tsub_pos_of_lt fintype.one_lt_card, simp only [indicator, map_prod, map_sub, map_one, map_pow, eval_X, eval_C, sub_self, zero_pow this, sub_zero, finset.prod_const_one] end lemma degrees_indicator (c : σ → K) : degrees (indicator c) ≤ ∑ s : σ, (fintype.card K - 1) • {s} := begin rw [indicator], refine le_trans (degrees_prod _ _) (finset.sum_le_sum $ assume s hs, _), refine le_trans (degrees_sub _ _) _, rw [degrees_one, ← bot_eq_zero, bot_sup_eq], refine le_trans (degrees_pow _ _) (nsmul_le_nsmul_of_le_right _ _), refine le_trans (degrees_sub _ _) _, rw [degrees_C, ← bot_eq_zero, sup_bot_eq], exact degrees_X' _ end lemma indicator_mem_restrict_degree (c : σ → K) : indicator c ∈ restrict_degree σ K (fintype.card K - 1) := begin rw [mem_restrict_degree_iff_sup, indicator], assume n, refine le_trans (multiset.count_le_of_le _ $ degrees_indicator _) (le_of_eq _), simp_rw [ ← multiset.coe_count_add_monoid_hom, (multiset.count_add_monoid_hom n).map_sum, add_monoid_hom.map_nsmul, multiset.coe_count_add_monoid_hom, nsmul_eq_mul, nat.cast_id], transitivity, refine finset.sum_eq_single n _ _, { assume b hb ne, rw [multiset.count_singleton, if_neg ne.symm, mul_zero] }, { assume h, exact (h $ finset.mem_univ _).elim }, { rw [multiset.count_singleton_self, mul_one] } end end comm_ring variables [field K] lemma eval_indicator_apply_eq_zero (a b : σ → K) (h : a ≠ b) : eval a (indicator b) = 0 := begin obtain ⟨i, hi⟩ : ∃ i, a i ≠ b i := by rwa [(≠), function.funext_iff, not_forall] at h, simp only [indicator, map_prod, map_sub, map_one, map_pow, eval_X, eval_C, sub_self, finset.prod_eq_zero_iff], refine ⟨i, finset.mem_univ _, _⟩, rw [finite_field.pow_card_sub_one_eq_one, sub_self], rwa [(≠), sub_eq_zero], end end indicator section variables (K σ) /-- `mv_polynomial.eval` as a `K`-linear map. -/ @[simps] def evalₗ [comm_semiring K] : mv_polynomial σ K →ₗ[K] (σ → K) → K := { to_fun := λ p e, eval e p, map_add' := λ p q, by { ext x, rw ring_hom.map_add, refl, }, map_smul' := λ a p, by { ext e, rw [smul_eq_C_mul, ring_hom.map_mul, eval_C], refl } } end variables [field K] [fintype K] [finite σ] lemma map_restrict_dom_evalₗ : (restrict_degree σ K (fintype.card K - 1)).map (evalₗ K σ) = ⊤ := begin casesI nonempty_fintype σ, refine top_unique (set_like.le_def.2 $ assume e _, mem_map.2 _), refine ⟨∑ n : σ → K, e n • indicator n, _, _⟩, { exact sum_mem (assume c _, smul_mem _ _ (indicator_mem_restrict_degree _)) }, { ext n, simp only [linear_map.map_sum, @finset.sum_apply (σ → K) (λ_, K) _ _ _ _ _, pi.smul_apply, linear_map.map_smul], simp only [evalₗ_apply], transitivity, refine finset.sum_eq_single n (λ b _ h, _) _, { rw [eval_indicator_apply_eq_zero _ _ h.symm, smul_zero] }, { exact λ h, (h $ finset.mem_univ n).elim }, { rw [eval_indicator_apply_eq_one, smul_eq_mul, mul_one] } } end end mv_polynomial namespace mv_polynomial open_locale classical cardinal open linear_map submodule universe u variables (σ : Type u) (K : Type u) [fintype K] /-- The submodule of multivariate polynomials whose degree of each variable is strictly less than the cardinality of K. -/ @[derive [add_comm_group, module K, inhabited]] def R [comm_ring K] : Type u := restrict_degree σ K (fintype.card K - 1) /-- Evaluation in the `mv_polynomial.R` subtype. -/ def evalᵢ [comm_ring K] : R σ K →ₗ[K] (σ → K) → K := ((evalₗ K σ).comp (restrict_degree σ K (fintype.card K - 1)).subtype) section comm_ring variables [comm_ring K] noncomputable instance decidable_restrict_degree (m : ℕ) : decidable_pred (∈ {n : σ →₀ ℕ | ∀i, n i ≤ m }) := by simp only [set.mem_set_of_eq]; apply_instance end comm_ring variables [field K] lemma dim_R [fintype σ] : module.rank K (R σ K) = fintype.card (σ → K) := calc module.rank K (R σ K) = module.rank K (↥{s : σ →₀ ℕ | ∀ (n : σ), s n ≤ fintype.card K - 1} →₀ K) : linear_equiv.dim_eq (finsupp.supported_equiv_finsupp {s : σ →₀ ℕ | ∀n:σ, s n ≤ fintype.card K - 1 }) ... = #{s : σ →₀ ℕ | ∀ (n : σ), s n ≤ fintype.card K - 1} : by rw [finsupp.dim_eq, dim_self, mul_one] ... = #{s : σ → ℕ | ∀ (n : σ), s n < fintype.card K } : begin refine quotient.sound ⟨equiv.subtype_equiv finsupp.equiv_fun_on_finite $ assume f, _⟩, refine forall_congr (assume n, le_tsub_iff_right _), exact fintype.card_pos_iff.2 ⟨0⟩ end ... = #(σ → {n // n < fintype.card K}) : (@equiv.subtype_pi_equiv_pi σ (λ_, ℕ) (λs n, n < fintype.card K)).cardinal_eq ... = #(σ → fin (fintype.card K)) : (equiv.arrow_congr (equiv.refl σ) fin.equiv_subtype.symm).cardinal_eq ... = #(σ → K) : (equiv.arrow_congr (equiv.refl σ) (fintype.equiv_fin K).symm).cardinal_eq ... = fintype.card (σ → K) : cardinal.mk_fintype _ instance [finite σ] : finite_dimensional K (R σ K) := by { casesI nonempty_fintype σ, exact is_noetherian.iff_fg.1 (is_noetherian.iff_dim_lt_aleph_0.mpr $ by simpa only [dim_R] using cardinal.nat_lt_aleph_0 (fintype.card (σ → K))) } lemma finrank_R [fintype σ] : finite_dimensional.finrank K (R σ K) = fintype.card (σ → K) := finite_dimensional.finrank_eq_of_dim_eq (dim_R σ K) lemma range_evalᵢ [finite σ] : (evalᵢ σ K).range = ⊤ := begin rw [evalᵢ, linear_map.range_comp, range_subtype], exact map_restrict_dom_evalₗ end lemma ker_evalₗ [finite σ] : (evalᵢ σ K).ker = ⊥ := begin casesI nonempty_fintype σ, refine (ker_eq_bot_iff_range_eq_top_of_finrank_eq_finrank _).mpr (range_evalᵢ _ _), rw [finite_dimensional.finrank_fintype_fun_eq_card, finrank_R] end lemma eq_zero_of_eval_eq_zero [finite σ] (p : mv_polynomial σ K) (h : ∀v:σ → K, eval v p = 0) (hp : p ∈ restrict_degree σ K (fintype.card K - 1)) : p = 0 := let p' : R σ K := ⟨p, hp⟩ in have p' ∈ (evalᵢ σ K).ker := funext h, show p'.1 = (0 : R σ K).1, from congr_arg _ $ by rwa [ker_evalₗ, mem_bot] at this end mv_polynomial
1243193a9d9ec2883fb7b76345426fdd9147acf7
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/matchOfNatIssue.lean
0ffdce3d4fcbc8d76ac3d0982c9aa21e5199b695
[ "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
472
lean
example (x : Int) (h : x = 2) : Int.div 2 1 = x := by simp [Int.div] trace_state simp [h] example (n : Nat) : Int.div (Int.ofNat n) (Int.ofNat 0) = Int.ofNat (n / 0) := by simp [Int.div] example (n : Nat) : Int.div (Int.ofNat n) 0 = Int.ofNat (n / 0) := by simp [Int.div] example (n : Nat) : Int.mul (Int.ofNat n) (Int.ofNat 0) = Int.ofNat (n * 0) := by simp [Int.mul] example (n : Nat) : Int.mul (Int.ofNat n) 0 = Int.ofNat (n * 0) := by simp [Int.mul]
41566df328d089ccd25b4a2c07ce59cee9033167
ac89c256db07448984849346288e0eeffe8b20d0
/src/Lean/Message.lean
4698888d79f8cafd73eb62e4cd634e13aa15695a
[ "Apache-2.0" ]
permissive
chepinzhang/lean4
002cc667f35417a418f0ebc9cb4a44559bb0ccac
24fe2875c68549b5481f07c57eab4ad4a0ae5305
refs/heads/master
1,688,942,838,326
1,628,801,942,000
1,628,801,995,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
14,427
lean
/- Copyright (c) 2018 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Sebastian Ullrich, Leonardo de Moura Message Type used by the Lean frontend -/ import Lean.Data.Position import Lean.Data.OpenDecl import Lean.Syntax import Lean.MetavarContext import Lean.Environment import Lean.Util.PPExt namespace Lean def mkErrorStringWithPos (fileName : String) (pos : Position) (msg : String) (endPos : Option Position := none) : String := let endPos := match endPos with | some endPos => s!"-{endPos.line}:{endPos.column}" | none => "" s!"{fileName}:{pos.line}:{pos.column}{endPos}: {msg}" inductive MessageSeverity where | information | warning | error deriving Inhabited, BEq structure MessageDataContext where env : Environment mctx : MetavarContext lctx : LocalContext opts : Options structure NamingContext where currNamespace : Name openDecls : List OpenDecl /- Structure message data. We use it for reporting errors, trace messages, etc. -/ inductive MessageData where | ofFormat : Format → MessageData | ofSyntax : Syntax → MessageData | ofExpr : Expr → MessageData | ofLevel : Level → MessageData | ofName : Name → MessageData | ofGoal : MVarId → MessageData /- `withContext ctx d` specifies the pretty printing context `(env, mctx, lctx, opts)` for the nested expressions in `d`. -/ | withContext : MessageDataContext → MessageData → MessageData | withNamingContext : NamingContext → MessageData → MessageData /- Lifted `Format.nest` -/ | nest : Nat → MessageData → MessageData /- Lifted `Format.group` -/ | group : MessageData → MessageData /- Lifted `Format.compose` -/ | compose : MessageData → MessageData → MessageData /- Tagged sections. `Name` should be viewed as a "kind", and is used by `MessageData` inspector functions. Example: an inspector that tries to find "definitional equality failures" may look for the tag "DefEqFailure". -/ | tagged : Name → MessageData → MessageData | node : Array MessageData → MessageData deriving Inhabited namespace MessageData /- Instantiate metavariables occurring in nexted `ofExpr` constructors. It uses the surrounding `MetavarContext` at `withContext` constructors. -/ partial def instantiateMVars (msg : MessageData) : MessageData := visit msg {} where visit (msg : MessageData) (mctx : MetavarContext) : MessageData := match msg with | ofExpr e => ofExpr <| mctx.instantiateMVars e |>.1 | withContext ctx msg => withContext ctx <| visit msg ctx.mctx | withNamingContext ctx msg => withNamingContext ctx <| visit msg mctx | nest n msg => nest n <| visit msg mctx | group msg => group <| visit msg mctx | compose msg₁ msg₂ => compose (visit msg₁ mctx) <| visit msg₂ mctx | tagged n msg => tagged n <| visit msg mctx | node msgs => node <| msgs.map (visit . mctx) | _ => msg variable (tag : Name) in partial def hasTag : MessageData → Bool | withContext _ msg => hasTag msg | withNamingContext _ msg => hasTag msg | nest _ msg => hasTag msg | group msg => hasTag msg | compose msg₁ msg₂ => hasTag msg₁ || hasTag msg₂ | tagged n msg => tag == n || hasTag msg | node msgs => msgs.any hasTag | _ => false def nil : MessageData := ofFormat Format.nil def isNil : MessageData → Bool | ofFormat Format.nil => true | _ => false def isNest : MessageData → Bool | nest _ _ => true | _ => false def mkPPContext (nCtx : NamingContext) (ctx : MessageDataContext) : PPContext := { env := ctx.env, mctx := ctx.mctx, lctx := ctx.lctx, opts := ctx.opts, currNamespace := nCtx.currNamespace, openDecls := nCtx.openDecls } partial def formatAux : NamingContext → Option MessageDataContext → MessageData → IO Format | _, _, ofFormat fmt => pure fmt | _, _, ofLevel u => pure $ format u | _, _, ofName n => pure $ format n | nCtx, some ctx, ofSyntax s => ppTerm (mkPPContext nCtx ctx) s -- HACK: might not be a term | _, none, ofSyntax s => pure $ s.formatStx | _, none, ofExpr e => pure $ format (toString e) | nCtx, some ctx, ofExpr e => ppExpr (mkPPContext nCtx ctx) e | _, none, ofGoal mvarId => pure $ "goal " ++ format (mkMVar mvarId) | nCtx, some ctx, ofGoal mvarId => ppGoal (mkPPContext nCtx ctx) mvarId | nCtx, _, withContext ctx d => formatAux nCtx ctx d | _, ctx, withNamingContext nCtx d => formatAux nCtx ctx d | nCtx, ctx, tagged _ d => formatAux nCtx ctx d | nCtx, ctx, nest n d => Format.nest n <$> formatAux nCtx ctx d | nCtx, ctx, compose d₁ d₂ => do let d₁ ← formatAux nCtx ctx d₁; let d₂ ← formatAux nCtx ctx d₂; pure $ d₁ ++ d₂ | nCtx, ctx, group d => Format.group <$> formatAux nCtx ctx d | nCtx, ctx, node ds => Format.nest 2 <$> ds.foldlM (fun r d => do let d ← formatAux nCtx ctx d; pure $ r ++ Format.line ++ d) Format.nil protected def format (msgData : MessageData) : IO Format := formatAux { currNamespace := Name.anonymous, openDecls := [] } none msgData protected def toString (msgData : MessageData) : IO String := do let fmt ← msgData.format pure $ toString fmt instance : Append MessageData := ⟨compose⟩ instance : Coe String MessageData := ⟨ofFormat ∘ format⟩ instance : Coe Format MessageData := ⟨ofFormat⟩ instance : Coe Level MessageData := ⟨ofLevel⟩ instance : Coe Expr MessageData := ⟨ofExpr⟩ instance : Coe Name MessageData := ⟨ofName⟩ instance : Coe Syntax MessageData := ⟨ofSyntax⟩ instance : Coe (Option Expr) MessageData := ⟨fun o => match o with | none => "none" | some e => ofExpr e⟩ partial def arrayExpr.toMessageData (es : Array Expr) (i : Nat) (acc : MessageData) : MessageData := if h : i < es.size then let e := es.get ⟨i, h⟩; let acc := if i == 0 then acc ++ ofExpr e else acc ++ ", " ++ ofExpr e; toMessageData es (i+1) acc else acc ++ "]" instance : Coe (Array Expr) MessageData := ⟨fun es => arrayExpr.toMessageData es 0 "#["⟩ def bracket (l : String) (f : MessageData) (r : String) : MessageData := group (nest l.length $ l ++ f ++ r) def paren (f : MessageData) : MessageData := bracket "(" f ")" def sbracket (f : MessageData) : MessageData := bracket "[" f "]" def joinSep : List MessageData → MessageData → MessageData | [], sep => Format.nil | [a], sep => a | a::as, sep => a ++ sep ++ joinSep as sep def ofList: List MessageData → MessageData | [] => "[]" | xs => sbracket $ joinSep xs (ofFormat "," ++ Format.line) def ofArray (msgs : Array MessageData) : MessageData := ofList msgs.toList instance : Coe (List MessageData) MessageData := ⟨ofList⟩ instance : Coe (List Expr) MessageData := ⟨fun es => ofList $ es.map ofExpr⟩ end MessageData structure Message where fileName : String pos : Position endPos : Option Position := none severity : MessageSeverity := MessageSeverity.error caption : String := "" data : MessageData deriving Inhabited namespace Message protected def toString (msg : Message) (includeEndPos := false) : IO String := do let mut str ← msg.data.toString let endPos := if includeEndPos then msg.endPos else none unless msg.caption == "" do str := msg.caption ++ ":\n" ++ str match msg.severity with | MessageSeverity.information => pure () | MessageSeverity.warning => str := mkErrorStringWithPos msg.fileName msg.pos (endPos := endPos) "warning: " ++ str | MessageSeverity.error => str := mkErrorStringWithPos msg.fileName msg.pos (endPos := endPos) "error: " ++ str if str.isEmpty || str.back != '\n' then str := str ++ "\n" return str end Message structure MessageLog where msgs : Std.PersistentArray Message := {} deriving Inhabited namespace MessageLog def empty : MessageLog := ⟨{}⟩ def isEmpty (log : MessageLog) : Bool := log.msgs.isEmpty def add (msg : Message) (log : MessageLog) : MessageLog := ⟨log.msgs.push msg⟩ protected def append (l₁ l₂ : MessageLog) : MessageLog := ⟨l₁.msgs ++ l₂.msgs⟩ instance : Append MessageLog := ⟨MessageLog.append⟩ def hasErrors (log : MessageLog) : Bool := log.msgs.any fun m => match m.severity with | MessageSeverity.error => true | _ => false def errorsToWarnings (log : MessageLog) : MessageLog := { msgs := log.msgs.map (fun m => match m.severity with | MessageSeverity.error => { m with severity := MessageSeverity.warning } | _ => m) } def getInfoMessages (log : MessageLog) : MessageLog := { msgs := log.msgs.filter fun m => match m.severity with | MessageSeverity.information => true | _ => false } def forM {m : Type → Type} [Monad m] (log : MessageLog) (f : Message → m Unit) : m Unit := log.msgs.forM f def toList (log : MessageLog) : List Message := (log.msgs.foldl (fun acc msg => msg :: acc) []).reverse end MessageLog def MessageData.nestD (msg : MessageData) : MessageData := MessageData.nest 2 msg def indentD (msg : MessageData) : MessageData := MessageData.nestD (Format.line ++ msg) def indentExpr (e : Expr) : MessageData := indentD e class AddMessageContext (m : Type → Type) where addMessageContext : MessageData → m MessageData export AddMessageContext (addMessageContext) instance (m n) [MonadLift m n] [AddMessageContext m] : AddMessageContext n where addMessageContext := fun msg => liftM (addMessageContext msg : m _) def addMessageContextPartial {m} [Monad m] [MonadEnv m] [MonadOptions m] (msgData : MessageData) : m MessageData := do let env ← getEnv let opts ← getOptions pure $ MessageData.withContext { env := env, mctx := {}, lctx := {}, opts := opts } msgData def addMessageContextFull {m} [Monad m] [MonadEnv m] [MonadMCtx m] [MonadLCtx m] [MonadOptions m] (msgData : MessageData) : m MessageData := do let env ← getEnv let mctx ← getMCtx let lctx ← getLCtx let opts ← getOptions pure $ MessageData.withContext { env := env, mctx := mctx, lctx := lctx, opts := opts } msgData class ToMessageData (α : Type) where toMessageData : α → MessageData export ToMessageData (toMessageData) def stringToMessageData (str : String) : MessageData := let lines := str.split (· == '\n') let lines := lines.map (MessageData.ofFormat ∘ format) MessageData.joinSep lines (MessageData.ofFormat Format.line) instance {α} [ToFormat α] : ToMessageData α := ⟨MessageData.ofFormat ∘ format⟩ instance : ToMessageData Expr := ⟨MessageData.ofExpr⟩ instance : ToMessageData Level := ⟨MessageData.ofLevel⟩ instance : ToMessageData Name := ⟨MessageData.ofName⟩ instance : ToMessageData String := ⟨stringToMessageData⟩ instance : ToMessageData Syntax := ⟨MessageData.ofSyntax⟩ instance : ToMessageData Format := ⟨MessageData.ofFormat⟩ instance : ToMessageData MessageData := ⟨id⟩ instance {α} [ToMessageData α] : ToMessageData (List α) := ⟨fun as => MessageData.ofList $ as.map toMessageData⟩ instance {α} [ToMessageData α] : ToMessageData (Array α) := ⟨fun as => toMessageData as.toList⟩ instance {α} [ToMessageData α] : ToMessageData (Option α) := ⟨fun | none => "none" | some e => "some (" ++ toMessageData e ++ ")"⟩ instance : ToMessageData (Option Expr) := ⟨fun | none => "<not-available>" | some e => toMessageData e⟩ syntax:max "m!" interpolatedStr(term) : term macro_rules | `(m! $interpStr) => do interpStr.expandInterpolatedStr (← `(MessageData)) (← `(toMessageData)) namespace KernelException private def mkCtx (env : Environment) (lctx : LocalContext) (opts : Options) (msg : MessageData) : MessageData := MessageData.withContext { env := env, mctx := {}, lctx := lctx, opts := opts } msg def toMessageData (e : KernelException) (opts : Options) : MessageData := match e with | unknownConstant env constName => mkCtx env {} opts m!"(kernel) unknown constant '{constName}'" | alreadyDeclared env constName => mkCtx env {} opts m!"(kernel) constant has already been declared '{constName}'" | declTypeMismatch env decl givenType => let process (n : Name) (expectedType : Expr) : MessageData := m!"(kernel) declaration type mismatch, '{n}' has type{indentExpr givenType}\nbut it is expected to have type{indentExpr expectedType}"; match decl with | Declaration.defnDecl { name := n, type := type, .. } => process n type | Declaration.thmDecl { name := n, type := type, .. } => process n type | _ => "(kernel) declaration type mismatch" -- TODO fix type checker, type mismatch for mutual decls does not have enough information | declHasMVars env constName _ => mkCtx env {} opts m!"(kernel) declaration has metavariables '{constName}'" | declHasFVars env constName _ => mkCtx env {} opts m!"(kernel) declaration has free variables '{constName}'" | funExpected env lctx e => mkCtx env lctx opts m!"(kernel) function expected{indentExpr e}" | typeExpected env lctx e => mkCtx env lctx opts m!"(kernel) type expected{indentExpr e}" | letTypeMismatch env lctx n _ _ => mkCtx env lctx opts m!"(kernel) let-declaration type mismatch '{n}'" | exprTypeMismatch env lctx e _ => mkCtx env lctx opts m!"(kernel) type mismatch at{indentExpr e}" | appTypeMismatch env lctx e fnType argType => mkCtx env lctx opts m!"application type mismatch{indentExpr e}\nargument has type{indentExpr argType}\nbut function has type{indentExpr fnType}" | invalidProj env lctx e => mkCtx env lctx opts m!"(kernel) invalid projection{indentExpr e}" | other msg => m!"(kernel) {msg}" end KernelException end Lean
fb5237f291ff79b08d46d5c98270b0cb2dbd5997
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/ring_theory/coprime/lemmas.lean
bb1fe54029b62fcbba0765155705f54ce65e4523
[ "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
4,365
lean
/- Copyright (c) 2020 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau, Ken Lee, Chris Hughes -/ import algebra.big_operators.basic import data.fintype.basic import data.int.gcd import ring_theory.coprime.basic /-! # Additional lemmas about elements of a ring satisfying `is_coprime` These lemmas are in a separate file to the definition of `is_coprime` as they require more imports. Notably, this includes lemmas about `finset.prod` as this requires importing big_operators, and lemmas about `has_pow` since these are easiest to prove via `finset.prod`. -/ universes u v variables {R : Type u} {I : Type v} [comm_semiring R] {x y z : R} {s : I → R} {t : finset I} open_locale big_operators classical theorem nat.is_coprime_iff_coprime {m n : ℕ} : is_coprime (m : ℤ) n ↔ nat.coprime m n := ⟨λ ⟨a, b, H⟩, nat.eq_one_of_dvd_one $ int.coe_nat_dvd.1 $ by { rw [int.coe_nat_one, ← H], exact dvd_add (dvd_mul_of_dvd_right (int.coe_nat_dvd.2 $ nat.gcd_dvd_left m n) _) (dvd_mul_of_dvd_right (int.coe_nat_dvd.2 $ nat.gcd_dvd_right m n) _) }, λ H, ⟨nat.gcd_a m n, nat.gcd_b m n, by rw [mul_comm _ (m : ℤ), mul_comm _ (n : ℤ), ← nat.gcd_eq_gcd_ab, show _ = _, from H, int.coe_nat_one]⟩⟩ theorem is_coprime.prod_left : (∀ i ∈ t, is_coprime (s i) x) → is_coprime (∏ i in t, s i) x := finset.induction_on t (λ _, is_coprime_one_left) $ λ b t hbt ih H, by { rw finset.prod_insert hbt, rw finset.forall_mem_insert at H, exact H.1.mul_left (ih H.2) } theorem is_coprime.prod_right : (∀ i ∈ t, is_coprime x (s i)) → is_coprime x (∏ i in t, s i) := by simpa only [is_coprime_comm] using is_coprime.prod_left theorem is_coprime.prod_left_iff : is_coprime (∏ i in t, s i) x ↔ ∀ i ∈ t, is_coprime (s i) x := finset.induction_on t (iff_of_true is_coprime_one_left $ λ _, false.elim) $ λ b t hbt ih, by rw [finset.prod_insert hbt, is_coprime.mul_left_iff, ih, finset.forall_mem_insert] theorem is_coprime.prod_right_iff : is_coprime x (∏ i in t, s i) ↔ ∀ i ∈ t, is_coprime x (s i) := by simpa only [is_coprime_comm] using is_coprime.prod_left_iff theorem is_coprime.of_prod_left (H1 : is_coprime (∏ i in t, s i) x) (i : I) (hit : i ∈ t) : is_coprime (s i) x := is_coprime.prod_left_iff.1 H1 i hit theorem is_coprime.of_prod_right (H1 : is_coprime x (∏ i in t, s i)) (i : I) (hit : i ∈ t) : is_coprime x (s i) := is_coprime.prod_right_iff.1 H1 i hit theorem finset.prod_dvd_of_coprime : ∀ (Hs : (t : set I).pairwise (is_coprime on s)) (Hs1 : ∀ i ∈ t, s i ∣ z), ∏ x in t, s x ∣ z := finset.induction_on t (λ _ _, one_dvd z) begin intros a r har ih Hs Hs1, rw finset.prod_insert har, have aux1 : a ∈ (↑(insert a r) : set I) := finset.mem_insert_self a r, refine (is_coprime.prod_right $ λ i hir, Hs aux1 (finset.mem_insert_of_mem hir) $ by { rintro rfl, exact har hir }).mul_dvd (Hs1 a aux1) (ih (Hs.mono _) $ λ i hi, Hs1 i $ finset.mem_insert_of_mem hi), simp only [finset.coe_insert, set.subset_insert], end theorem fintype.prod_dvd_of_coprime [fintype I] (Hs : pairwise (is_coprime on s)) (Hs1 : ∀ i, s i ∣ z) : ∏ x, s x ∣ z := finset.prod_dvd_of_coprime (Hs.set_pairwise _) (λ i _, Hs1 i) variables {m n : ℕ} theorem is_coprime.pow_left (H : is_coprime x y) : is_coprime (x ^ m) y := by { rw [← finset.card_range m, ← finset.prod_const], exact is_coprime.prod_left (λ _ _, H) } theorem is_coprime.pow_right (H : is_coprime x y) : is_coprime x (y ^ n) := by { rw [← finset.card_range n, ← finset.prod_const], exact is_coprime.prod_right (λ _ _, H) } theorem is_coprime.pow (H : is_coprime x y) : is_coprime (x ^ m) (y ^ n) := H.pow_left.pow_right theorem is_coprime.pow_left_iff (hm : 0 < m) : is_coprime (x ^ m) y ↔ is_coprime x y := begin refine ⟨λ h, _, is_coprime.pow_left⟩, rw [← finset.card_range m, ← finset.prod_const] at h, exact h.of_prod_left 0 (finset.mem_range.mpr hm), end theorem is_coprime.pow_right_iff (hm : 0 < m) : is_coprime x (y ^ m) ↔ is_coprime x y := is_coprime_comm.trans $ (is_coprime.pow_left_iff hm).trans $ is_coprime_comm theorem is_coprime.pow_iff (hm : 0 < m) (hn : 0 < n) : is_coprime (x ^ m) (y ^ n) ↔ is_coprime x y := (is_coprime.pow_left_iff hm).trans $ is_coprime.pow_right_iff hn
6c7add37dd35afa3d4303c3aa151dca8761169da
a047a4718edfa935d17231e9e6ecec8c7b701e05
/src/ring_theory/ideals.lean
cbf5df2ad67fffd49b471859f4048892a764b148
[ "Apache-2.0" ]
permissive
utensil-contrib/mathlib
bae0c9fafe5e2bdb516efc89d6f8c1502ecc9767
b91909e77e219098a2f8cc031f89d595fe274bd2
refs/heads/master
1,668,048,976,965
1,592,442,701,000
1,592,442,701,000
273,197,855
0
0
null
1,592,472,812,000
1,592,472,811,000
null
UTF-8
Lean
false
false
18,695
lean
/- Copyright (c) 2018 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau, Chris Hughes, Mario Carneiro -/ import algebra.associated import linear_algebra.basic import order.zorn universes u v variables {α : Type u} {β : Type v} {a b : α} open set function open_locale classical big_operators namespace ideal variables [comm_ring α] (I : ideal α) @[ext] lemma ext {I J : ideal α} (h : ∀ x, x ∈ I ↔ x ∈ J) : I = J := submodule.ext h theorem eq_top_of_unit_mem (x y : α) (hx : x ∈ I) (h : y * x = 1) : I = ⊤ := eq_top_iff.2 $ λ z _, calc z = z * (y * x) : by simp [h] ... = (z * y) * x : eq.symm $ mul_assoc z y x ... ∈ I : I.mul_mem_left hx theorem eq_top_of_is_unit_mem {x} (hx : x ∈ I) (h : is_unit x) : I = ⊤ := let ⟨y, hy⟩ := is_unit_iff_exists_inv'.1 h in eq_top_of_unit_mem I x y hx hy theorem eq_top_iff_one : I = ⊤ ↔ (1:α) ∈ I := ⟨by rintro rfl; trivial, λ h, eq_top_of_unit_mem _ _ 1 h (by simp)⟩ theorem ne_top_iff_one : I ≠ ⊤ ↔ (1:α) ∉ I := not_congr I.eq_top_iff_one def span (s : set α) : ideal α := submodule.span α s lemma subset_span {s : set α} : s ⊆ span s := submodule.subset_span lemma span_le {s : set α} {I} : span s ≤ I ↔ s ⊆ I := submodule.span_le lemma span_mono {s t : set α} : s ⊆ t → span s ≤ span t := submodule.span_mono @[simp] lemma span_eq : span (I : set α) = I := submodule.span_eq _ @[simp] lemma span_singleton_one : span ({1} : set α) = ⊤ := (eq_top_iff_one _).2 $ subset_span $ mem_singleton _ lemma mem_span_insert {s : set α} {x y} : x ∈ span (insert y s) ↔ ∃ a (z ∈ span s), x = a * y + z := submodule.mem_span_insert lemma mem_span_insert' {s : set α} {x y} : x ∈ span (insert y s) ↔ ∃a, x + a * y ∈ span s := submodule.mem_span_insert' lemma mem_span_singleton' {x y : α} : x ∈ span ({y} : set α) ↔ ∃ a, a * y = x := submodule.mem_span_singleton lemma mem_span_singleton {x y : α} : x ∈ span ({y} : set α) ↔ y ∣ x := mem_span_singleton'.trans $ exists_congr $ λ _, by rw [eq_comm, mul_comm] lemma span_singleton_le_span_singleton {x y : α} : span ({x} : set α) ≤ span ({y} : set α) ↔ y ∣ x := span_le.trans $ singleton_subset_iff.trans mem_span_singleton lemma span_eq_bot {s : set α} : span s = ⊥ ↔ ∀ x ∈ s, (x:α) = 0 := submodule.span_eq_bot lemma span_singleton_eq_bot {x} : span ({x} : set α) = ⊥ ↔ x = 0 := submodule.span_singleton_eq_bot lemma span_singleton_eq_top {x} : span ({x} : set α) = ⊤ ↔ is_unit x := by rw [is_unit_iff_dvd_one, ← span_singleton_le_span_singleton, span_singleton_one, eq_top_iff] @[class] def is_prime (I : ideal α) : Prop := I ≠ ⊤ ∧ ∀ {x y : α}, x * y ∈ I → x ∈ I ∨ y ∈ I theorem is_prime.mem_or_mem {I : ideal α} (hI : I.is_prime) : ∀ {x y : α}, x * y ∈ I → x ∈ I ∨ y ∈ I := hI.2 theorem is_prime.mem_or_mem_of_mul_eq_zero {I : ideal α} (hI : I.is_prime) {x y : α} (h : x * y = 0) : x ∈ I ∨ y ∈ I := hI.2 (h.symm ▸ I.zero_mem) theorem is_prime.mem_of_pow_mem {I : ideal α} (hI : I.is_prime) {r : α} (n : ℕ) (H : r^n ∈ I) : r ∈ I := begin induction n with n ih, { exact (mt (eq_top_iff_one _).2 hI.1).elim H }, exact or.cases_on (hI.mem_or_mem H) id ih end theorem zero_ne_one_of_proper {I : ideal α} (h : I ≠ ⊤) : (0:α) ≠ 1 := λ hz, I.ne_top_iff_one.1 h $ hz ▸ I.zero_mem theorem span_singleton_prime {p : α} (hp : p ≠ 0) : is_prime (span ({p} : set α)) ↔ prime p := by simp [is_prime, prime, span_singleton_eq_top, hp, mem_span_singleton] @[class] def is_maximal (I : ideal α) : Prop := I ≠ ⊤ ∧ ∀ J, I < J → J = ⊤ theorem is_maximal_iff {I : ideal α} : I.is_maximal ↔ (1:α) ∉ I ∧ ∀ (J : ideal α) x, I ≤ J → x ∉ I → x ∈ J → (1:α) ∈ J := and_congr I.ne_top_iff_one $ forall_congr $ λ J, by rw [lt_iff_le_not_le]; exact ⟨λ H x h hx₁ hx₂, J.eq_top_iff_one.1 $ H ⟨h, not_subset.2 ⟨_, hx₂, hx₁⟩⟩, λ H ⟨h₁, h₂⟩, let ⟨x, xJ, xI⟩ := not_subset.1 h₂ in J.eq_top_iff_one.2 $ H x h₁ xI xJ⟩ theorem is_maximal.eq_of_le {I J : ideal α} (hI : I.is_maximal) (hJ : J ≠ ⊤) (IJ : I ≤ J) : I = J := eq_iff_le_not_lt.2 ⟨IJ, λ h, hJ (hI.2 _ h)⟩ theorem is_maximal.exists_inv {I : ideal α} (hI : I.is_maximal) {x} (hx : x ∉ I) : ∃ y, y * x - 1 ∈ I := begin cases is_maximal_iff.1 hI with H₁ H₂, rcases mem_span_insert'.1 (H₂ (span (insert x I)) x (set.subset.trans (subset_insert _ _) subset_span) hx (subset_span (mem_insert _ _))) with ⟨y, hy⟩, rw [span_eq, ← neg_mem_iff, add_comm, neg_add', neg_mul_eq_neg_mul] at hy, exact ⟨-y, hy⟩ end theorem is_maximal.is_prime {I : ideal α} (H : I.is_maximal) : I.is_prime := ⟨H.1, λ x y hxy, or_iff_not_imp_left.2 $ λ hx, begin cases H.exists_inv hx with z hz, have := I.mul_mem_left hz, rw [mul_sub, mul_one, mul_comm, mul_assoc] at this, exact I.neg_mem_iff.1 ((I.add_mem_iff_right $ I.mul_mem_left hxy).1 this) end⟩ @[priority 100] -- see Note [lower instance priority] instance is_maximal.is_prime' (I : ideal α) : ∀ [H : I.is_maximal], I.is_prime := is_maximal.is_prime theorem exists_le_maximal (I : ideal α) (hI : I ≠ ⊤) : ∃ M : ideal α, M.is_maximal ∧ I ≤ M := begin rcases zorn.zorn_partial_order₀ { J : ideal α | J ≠ ⊤ } _ I hI with ⟨M, M0, IM, h⟩, { refine ⟨M, ⟨M0, λ J hJ, by_contradiction $ λ J0, _⟩, IM⟩, cases h J J0 (le_of_lt hJ), exact lt_irrefl _ hJ }, { intros S SC cC I IS, refine ⟨Sup S, λ H, _, λ _, le_Sup⟩, obtain ⟨J, JS, J0⟩ : ∃ J ∈ S, (1 : α) ∈ J, from (submodule.mem_Sup_of_directed ⟨I, IS⟩ cC.directed_on).1 ((eq_top_iff_one _).1 H), exact SC JS ((eq_top_iff_one _).2 J0) } end theorem mem_span_pair {x y z : α} : z ∈ span ({x, y} : set α) ↔ ∃ a b, a * x + b * y = z := by simp [mem_span_insert, mem_span_singleton', @eq_comm _ _ z] lemma span_singleton_lt_span_singleton [integral_domain β] {x y : β} : span ({x} : set β) < span ({y} : set β) ↔ y ≠ 0 ∧ ∃ d : β, ¬ is_unit d ∧ x = y * d := by rw [lt_iff_le_not_le, span_singleton_le_span_singleton, span_singleton_le_span_singleton, dvd_and_not_dvd_iff] def quotient (I : ideal α) := I.quotient namespace quotient variables {I} {x y : α} def mk (I : ideal α) (a : α) : I.quotient := submodule.quotient.mk a protected theorem eq : mk I x = mk I y ↔ x - y ∈ I := submodule.quotient.eq I instance (I : ideal α) : has_one I.quotient := ⟨mk I 1⟩ @[simp] lemma mk_one (I : ideal α) : mk I 1 = 1 := rfl instance (I : ideal α) : has_mul I.quotient := ⟨λ a b, quotient.lift_on₂' a b (λ a b, mk I (a * b)) $ λ a₁ a₂ b₁ b₂ h₁ h₂, quot.sound $ begin refine calc a₁ * a₂ - b₁ * b₂ = a₂ * (a₁ - b₁) + (a₂ - b₂) * b₁ : _ ... ∈ I : I.add_mem (I.mul_mem_left h₁) (I.mul_mem_right h₂), rw [mul_sub, sub_mul, sub_add_sub_cancel, mul_comm, mul_comm b₁] end⟩ @[simp] theorem mk_mul : mk I (x * y) = mk I x * mk I y := rfl instance (I : ideal α) : comm_ring I.quotient := { mul := (*), one := 1, mul_assoc := λ a b c, quotient.induction_on₃' a b c $ λ a b c, congr_arg (mk _) (mul_assoc a b c), mul_comm := λ a b, quotient.induction_on₂' a b $ λ a b, congr_arg (mk _) (mul_comm a b), one_mul := λ a, quotient.induction_on' a $ λ a, congr_arg (mk _) (one_mul a), mul_one := λ a, quotient.induction_on' a $ λ a, congr_arg (mk _) (mul_one a), left_distrib := λ a b c, quotient.induction_on₃' a b c $ λ a b c, congr_arg (mk _) (left_distrib a b c), right_distrib := λ a b c, quotient.induction_on₃' a b c $ λ a b c, congr_arg (mk _) (right_distrib a b c), ..submodule.quotient.add_comm_group I } /-- `ideal.quotient.mk` as a `ring_hom` -/ def mk_hom (I : ideal α) : α →+* I.quotient := ⟨mk I, rfl, λ _ _, rfl, rfl, λ _ _, rfl⟩ lemma mk_eq_mk_hom (I : ideal α) (x : α) : ideal.quotient.mk I x = ideal.quotient.mk_hom I x := rfl def map_mk (I J : ideal α) : ideal I.quotient := { carrier := mk I '' J, zero_mem' := ⟨0, J.zero_mem, rfl⟩, add_mem' := by rintro _ _ ⟨x, hx, rfl⟩ ⟨y, hy, rfl⟩; exact ⟨x + y, J.add_mem hx hy, rfl⟩, smul_mem' := by rintro ⟨c⟩ _ ⟨x, hx, rfl⟩; exact ⟨c * x, J.mul_mem_left hx, rfl⟩ } @[simp] lemma mk_zero (I : ideal α) : mk I 0 = 0 := rfl @[simp] lemma mk_add (I : ideal α) (a b : α) : mk I (a + b) = mk I a + mk I b := rfl @[simp] lemma mk_neg (I : ideal α) (a : α) : mk I (-a : α) = -mk I a := rfl @[simp] lemma mk_sub (I : ideal α) (a b : α) : mk I (a - b : α) = mk I a - mk I b := rfl @[simp] lemma mk_pow (I : ideal α) (a : α) (n : ℕ) : mk I (a ^ n : α) = mk I a ^ n := (mk_hom I).map_pow a n lemma mk_prod {ι} (I : ideal α) (s : finset ι) (f : ι → α) : mk I (∏ i in s, f i) = ∏ i in s, mk I (f i) := (mk_hom I).map_prod f s lemma mk_sum {ι} (I : ideal α) (s : finset ι) (f : ι → α) : mk I (∑ i in s, f i) = ∑ i in s, mk I (f i) := (mk_hom I).map_sum f s lemma eq_zero_iff_mem {I : ideal α} : mk I a = 0 ↔ a ∈ I := by conv {to_rhs, rw ← sub_zero a }; exact quotient.eq' theorem zero_eq_one_iff {I : ideal α} : (0 : I.quotient) = 1 ↔ I = ⊤ := eq_comm.trans $ eq_zero_iff_mem.trans (eq_top_iff_one _).symm theorem zero_ne_one_iff {I : ideal α} : (0 : I.quotient) ≠ 1 ↔ I ≠ ⊤ := not_congr zero_eq_one_iff protected theorem nonzero {I : ideal α} (hI : I ≠ ⊤) : nonzero I.quotient := { zero_ne_one := zero_ne_one_iff.2 hI } instance (I : ideal α) [hI : I.is_prime] : integral_domain I.quotient := { eq_zero_or_eq_zero_of_mul_eq_zero := λ a b, quotient.induction_on₂' a b $ λ a b hab, (hI.mem_or_mem (eq_zero_iff_mem.1 hab)).elim (or.inl ∘ eq_zero_iff_mem.2) (or.inr ∘ eq_zero_iff_mem.2), ..quotient.nonzero hI.1, ..quotient.comm_ring I } lemma exists_inv {I : ideal α} [hI : I.is_maximal] : ∀ {a : I.quotient}, a ≠ 0 → ∃ b : I.quotient, a * b = 1 := begin rintro ⟨a⟩ h, cases hI.exists_inv (mt eq_zero_iff_mem.2 h) with b hb, rw [mul_comm] at hb, exact ⟨mk _ b, quot.sound hb⟩ end /-- quotient by maximal ideal is a field. def rather than instance, since users will have computable inverses in some applications -/ protected noncomputable def field (I : ideal α) [hI : I.is_maximal] : field I.quotient := { inv := λ a, if ha : a = 0 then 0 else classical.some (exists_inv ha), mul_inv_cancel := λ a (ha : a ≠ 0), show a * dite _ _ _ = _, by rw dif_neg ha; exact classical.some_spec (exists_inv ha), inv_zero := dif_pos rfl, ..quotient.integral_domain I } variable [comm_ring β] /-- Given a ring homomorphism `f : α →+* β` sending all elements of an ideal to zero, lift it to the quotient by this ideal. -/ def lift (S : ideal α) (f : α →+* β) (H : ∀ (a : α), a ∈ S → f a = 0) : quotient S →+* β := { to_fun := λ x, quotient.lift_on' x f $ λ (a b) (h : _ ∈ _), eq_of_sub_eq_zero $ by rw [← f.map_sub, H _ h], map_one' := f.map_one, map_zero' := f.map_zero, map_add' := λ a₁ a₂, quotient.induction_on₂' a₁ a₂ f.map_add, map_mul' := λ a₁ a₂, quotient.induction_on₂' a₁ a₂ f.map_mul } @[simp] lemma lift_mk (S : ideal α) (f : α →+* β) (H : ∀ (a : α), a ∈ S → f a = 0) : lift S f H (mk S a) = f a := rfl end quotient section lattice variables {R : Type u} [comm_ring R] theorem mem_Inf {s : set (ideal R)} {x : R} : x ∈ Inf s ↔ ∀ ⦃I⦄, I ∈ s → x ∈ I := ⟨λ hx I his, hx I ⟨I, infi_pos his⟩, λ H I ⟨J, hij⟩, hij ▸ λ S ⟨hj, hS⟩, hS ▸ H hj⟩ end lattice /-- All ideals in a field are trivial. -/ lemma eq_bot_or_top {K : Type u} [field K] (I : ideal K) : I = ⊥ ∨ I = ⊤ := begin rw classical.or_iff_not_imp_right, change _ ≠ _ → _, rw ideal.ne_top_iff_one, intro h1, rw eq_bot_iff, intros r hr, by_cases H : r = 0, {simpa}, simpa [H, h1] using submodule.smul_mem I r⁻¹ hr, end lemma eq_bot_of_prime {K : Type u} [field K] (I : ideal K) [h : I.is_prime] : I = ⊥ := classical.or_iff_not_imp_right.mp I.eq_bot_or_top h.1 end ideal /-- The set of non-invertible elements of a monoid. -/ def nonunits (α : Type u) [monoid α] : set α := { a | ¬is_unit a } @[simp] theorem mem_nonunits_iff [comm_monoid α] : a ∈ nonunits α ↔ ¬ is_unit a := iff.rfl theorem mul_mem_nonunits_right [comm_monoid α] : b ∈ nonunits α → a * b ∈ nonunits α := mt is_unit_of_mul_is_unit_right theorem mul_mem_nonunits_left [comm_monoid α] : a ∈ nonunits α → a * b ∈ nonunits α := mt is_unit_of_mul_is_unit_left theorem zero_mem_nonunits [semiring α] : 0 ∈ nonunits α ↔ (0:α) ≠ 1 := not_congr is_unit_zero_iff @[simp] theorem one_not_mem_nonunits [monoid α] : (1:α) ∉ nonunits α := not_not_intro is_unit_one theorem coe_subset_nonunits [comm_ring α] {I : ideal α} (h : I ≠ ⊤) : (I : set α) ⊆ nonunits α := λ x hx hu, h $ I.eq_top_of_is_unit_mem hx hu lemma exists_max_ideal_of_mem_nonunits [comm_ring α] (h : a ∈ nonunits α) : ∃ I : ideal α, I.is_maximal ∧ a ∈ I := begin have : ideal.span ({a} : set α) ≠ ⊤, { intro H, rw ideal.span_singleton_eq_top at H, contradiction }, rcases ideal.exists_le_maximal _ this with ⟨I, Imax, H⟩, use [I, Imax], apply H, apply ideal.subset_span, exact set.mem_singleton a end section prio set_option default_priority 100 -- see Note [default priority] class local_ring (α : Type u) extends comm_ring α, nonzero α := (is_local : ∀ (a : α), (is_unit a) ∨ (is_unit (1 - a))) end prio namespace local_ring variable [local_ring α] lemma is_unit_or_is_unit_one_sub_self (a : α) : (is_unit a) ∨ (is_unit (1 - a)) := is_local a lemma is_unit_of_mem_nonunits_one_sub_self (a : α) (h : (1 - a) ∈ nonunits α) : is_unit a := or_iff_not_imp_right.1 (is_local a) h lemma is_unit_one_sub_self_of_mem_nonunits (a : α) (h : a ∈ nonunits α) : is_unit (1 - a) := or_iff_not_imp_left.1 (is_local a) h lemma nonunits_add {x y} (hx : x ∈ nonunits α) (hy : y ∈ nonunits α) : x + y ∈ nonunits α := begin rintros ⟨u, hu⟩, apply hy, suffices : is_unit ((↑u⁻¹ : α) * y), { rcases this with ⟨s, hs⟩, use u * s, convert congr_arg (λ z, (u : α) * z) hs, rw ← mul_assoc, simp }, rw show (↑u⁻¹ * y) = (1 - ↑u⁻¹ * x), { rw eq_sub_iff_add_eq, replace hu := congr_arg (λ z, (↑u⁻¹ : α) * z) hu.symm, simpa [mul_add, add_comm] using hu }, apply is_unit_one_sub_self_of_mem_nonunits, exact mul_mem_nonunits_right hx end variable (α) /-- The ideal of elements that are not units. -/ def nonunits_ideal : ideal α := { carrier := nonunits α, zero_mem' := zero_mem_nonunits.2 $ zero_ne_one, add_mem' := λ x y hx hy, nonunits_add hx hy, smul_mem' := λ a x, mul_mem_nonunits_right } instance nonunits_ideal.is_maximal : (nonunits_ideal α).is_maximal := begin rw ideal.is_maximal_iff, split, { intro h, apply h, exact is_unit_one }, { intros I x hI hx H, erw not_not at hx, rcases hx with ⟨u,rfl⟩, simpa using I.smul_mem ↑u⁻¹ H } end lemma max_ideal_unique : ∃! I : ideal α, I.is_maximal := ⟨nonunits_ideal α, nonunits_ideal.is_maximal α, λ I hI, hI.eq_of_le (nonunits_ideal.is_maximal α).1 $ λ x hx, hI.1 ∘ I.eq_top_of_is_unit_mem hx⟩ variable {α} @[simp] lemma mem_nonunits_ideal (x) : x ∈ nonunits_ideal α ↔ x ∈ nonunits α := iff.rfl end local_ring def is_local_ring (α : Type u) [comm_ring α] : Prop := ((0:α) ≠ 1) ∧ ∀ (a : α), (is_unit a) ∨ (is_unit (1 - a)) def local_of_is_local_ring [comm_ring α] (h : is_local_ring α) : local_ring α := { zero_ne_one := h.1, is_local := h.2, .. ‹comm_ring α› } def local_of_unit_or_unit_one_sub [comm_ring α] (hnze : (0:α) ≠ 1) (h : ∀ x : α, is_unit x ∨ is_unit (1 - x)) : local_ring α := local_of_is_local_ring ⟨hnze, h⟩ def local_of_nonunits_ideal [comm_ring α] (hnze : (0:α) ≠ 1) (h : ∀ x y ∈ nonunits α, x + y ∈ nonunits α) : local_ring α := local_of_is_local_ring ⟨hnze, λ x, or_iff_not_imp_left.mpr $ λ hx, begin by_contra H, apply h _ _ hx H, simp [-sub_eq_add_neg, add_sub_cancel'_right] end⟩ def local_of_unique_max_ideal [comm_ring α] (h : ∃! I : ideal α, I.is_maximal) : local_ring α := local_of_nonunits_ideal (let ⟨I, Imax, _⟩ := h in (λ (H : 0 = 1), Imax.1 $ I.eq_top_iff_one.2 $ H ▸ I.zero_mem)) $ λ x y hx hy H, let ⟨I, Imax, Iuniq⟩ := h in let ⟨Ix, Ixmax, Hx⟩ := exists_max_ideal_of_mem_nonunits hx in let ⟨Iy, Iymax, Hy⟩ := exists_max_ideal_of_mem_nonunits hy in have xmemI : x ∈ I, from ((Iuniq Ix Ixmax) ▸ Hx), have ymemI : y ∈ I, from ((Iuniq Iy Iymax) ▸ Hy), Imax.1 $ I.eq_top_of_is_unit_mem (I.add_mem xmemI ymemI) H section prio set_option default_priority 100 -- see Note [default priority] class is_local_ring_hom [semiring α] [semiring β] (f : α →+* β) : Prop := (map_nonunit : ∀ a, is_unit (f a) → is_unit a) end prio @[simp] lemma is_unit_of_map_unit [semiring α] [semiring β] (f : α →+* β) [is_local_ring_hom f] (a) (h : is_unit (f a)) : is_unit a := is_local_ring_hom.map_nonunit a h section open local_ring variables [local_ring α] [local_ring β] variables (f : α →+* β) [is_local_ring_hom f] lemma map_nonunit (a) (h : a ∈ nonunits_ideal α) : f a ∈ nonunits_ideal β := λ H, h $ is_unit_of_map_unit f a H end namespace local_ring variables [local_ring α] [local_ring β] variable (α) def residue_field := (nonunits_ideal α).quotient noncomputable instance residue_field.field : field (residue_field α) := ideal.quotient.field (nonunits_ideal α) /-- The quotient map from a local ring to it's residue field. -/ def residue : α →+* (residue_field α) := ideal.quotient.mk_hom _ namespace residue_field variables {α β} noncomputable def map (f : α →+* β) [is_local_ring_hom f] : residue_field α →+* residue_field β := ideal.quotient.lift (nonunits_ideal α) ((ideal.quotient.mk_hom _).comp f) $ λ a ha, begin erw ideal.quotient.eq_zero_iff_mem, exact map_nonunit f a ha end end residue_field end local_ring namespace field variables [field α] @[priority 100] -- see Note [lower instance priority] instance : local_ring α := { is_local := λ a, if h : a = 0 then or.inr (by rw [h, sub_zero]; exact is_unit_one) else or.inl $ is_unit_of_mul_eq_one a a⁻¹ $ div_self h } end field
7e34c75c16b0360a921e731bbd604146071971cd
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/topology/instances/ereal.lean
6daf58003709974a8adab9d7ae46ba4b28648e67
[ "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,365
lean
/- Copyright (c) 2021 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 data.rat.encodable import data.real.ereal import topology.algebra.order.monotone_continuity import topology.instances.ennreal /-! # Topological structure on `ereal` > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. We endow `ereal` with the order topology, and prove basic properties of this topology. ## Main results * `coe : ℝ → ereal` is an open embedding * `coe : ℝ≥0∞ → ereal` is an embedding * The addition on `ereal` is continuous except at `(⊥, ⊤)` and at `(⊤, ⊥)`. * Negation is a homeomorphism on `ereal`. ## Implementation Most proofs are adapted from the corresponding proofs on `ℝ≥0∞`. -/ noncomputable theory open classical set filter metric topological_space open_locale classical topology ennreal nnreal big_operators filter variables {α : Type*} [topological_space α] namespace ereal instance : topological_space ereal := preorder.topology ereal instance : order_topology ereal := ⟨rfl⟩ instance : t2_space ereal := by apply_instance instance : second_countable_topology ereal := ⟨begin refine ⟨⋃ (q : ℚ), {{a : ereal | a < (q : ℝ)}, {a : ereal | ((q : ℝ) : ereal) < a}}, countable_Union (λ a, (countable_singleton _).insert _), _⟩, refine le_antisymm (le_generate_from $ by simp [or_imp_distrib, is_open_lt', is_open_gt'] {contextual := tt}) _, apply le_generate_from (λ s h, _), rcases h with ⟨a, hs | hs⟩; [ rw show s = ⋃q∈{q:ℚ | a < (q : ℝ)}, {b | ((q : ℝ) : ereal) < b}, by { ext x, simpa only [hs, exists_prop, mem_Union] using lt_iff_exists_rat_btwn }, rw show s = ⋃q∈{q:ℚ | ((q : ℝ) : ereal) < a}, {b | b < ((q : ℝ) : ereal)}, by { ext x, simpa only [hs, and_comm, exists_prop, mem_Union] using lt_iff_exists_rat_btwn }]; { apply is_open_Union, intro q, apply is_open_Union, intro hq, apply generate_open.basic, exact mem_Union.2 ⟨q, by simp⟩ }, end⟩ /-! ### Real coercion -/ lemma embedding_coe : embedding (coe : ℝ → ereal) := ⟨⟨begin refine le_antisymm _ _, { rw [@order_topology.topology_eq_generate_intervals ereal _, ← coinduced_le_iff_le_induced], refine le_generate_from (assume s ha, _), rcases ha with ⟨a, rfl | rfl⟩, show is_open {b : ℝ | a < ↑b}, { induction a using ereal.rec, { simp only [is_open_univ, bot_lt_coe, set_of_true] }, { simp only [ereal.coe_lt_coe_iff], exact is_open_Ioi }, { simp only [set_of_false, is_open_empty, not_top_lt] } }, show is_open {b : ℝ | ↑b < a}, { induction a using ereal.rec, { simp only [not_lt_bot, set_of_false, is_open_empty] }, { simp only [ereal.coe_lt_coe_iff], exact is_open_Iio }, { simp only [is_open_univ, coe_lt_top, set_of_true] } } }, { rw [@order_topology.topology_eq_generate_intervals ℝ _], 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, by simp only [imp_self, ereal.coe_eq_coe_iff]⟩ lemma open_embedding_coe : open_embedding (coe : ℝ → ereal) := ⟨embedding_coe, begin convert @is_open_Ioo ereal _ _ _ ⊥ ⊤, ext x, induction x using ereal.rec, { simp only [left_mem_Ioo, mem_range, coe_ne_bot, exists_false, not_false_iff] }, { simp only [mem_range_self, mem_Ioo, bot_lt_coe, coe_lt_top, and_self] }, { simp only [mem_range, right_mem_Ioo, exists_false, coe_ne_top] } end⟩ @[norm_cast] lemma tendsto_coe {α : Type*} {f : filter α} {m : α → ℝ} {a : ℝ} : tendsto (λ a, (m a : ereal)) f (𝓝 ↑a) ↔ tendsto m f (𝓝 a) := embedding_coe.tendsto_nhds_iff.symm lemma _root_.continuous_coe_real_ereal : continuous (coe : ℝ → ereal) := embedding_coe.continuous lemma continuous_coe_iff {f : α → ℝ} : continuous (λa, (f a : ereal)) ↔ continuous f := embedding_coe.continuous_iff.symm lemma nhds_coe {r : ℝ} : 𝓝 (r : ereal) = (𝓝 r).map coe := (open_embedding_coe.map_nhds_eq r).symm lemma nhds_coe_coe {r p : ℝ} : 𝓝 ((r : ereal), (p : ereal)) = (𝓝 (r, p)).map (λp:ℝ × ℝ, (p.1, p.2)) := ((open_embedding_coe.prod open_embedding_coe).map_nhds_eq (r, p)).symm lemma tendsto_to_real {a : ereal} (ha : a ≠ ⊤) (h'a : a ≠ ⊥) : tendsto ereal.to_real (𝓝 a) (𝓝 a.to_real) := begin lift a to ℝ using and.intro ha h'a, rw [nhds_coe, tendsto_map'_iff], exact tendsto_id end lemma continuous_on_to_real : continuous_on ereal.to_real ({⊥, ⊤}ᶜ : set ereal) := λ a ha, continuous_at.continuous_within_at (tendsto_to_real (by { simp [not_or_distrib] at ha, exact ha.2 }) (by { simp [not_or_distrib] at ha, exact ha.1 })) /-- The set of finite `ereal` numbers is homeomorphic to `ℝ`. -/ def ne_bot_top_homeomorph_real : ({⊥, ⊤}ᶜ : set ereal) ≃ₜ ℝ := { continuous_to_fun := continuous_on_iff_continuous_restrict.1 continuous_on_to_real, continuous_inv_fun := continuous_coe_real_ereal.subtype_mk _, .. ne_top_bot_equiv_real } /-! ### ennreal coercion -/ lemma embedding_coe_ennreal : embedding (coe : ℝ≥0∞ → ereal) := ⟨⟨begin refine le_antisymm _ _, { rw [@order_topology.topology_eq_generate_intervals ereal _, ← 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}, { induction a using ereal.rec with x, { simp only [is_open_univ, bot_lt_coe_ennreal, set_of_true] }, { rcases le_or_lt 0 x with h|h, { have : (x : ereal) = ((id ⟨x, h⟩ : ℝ≥0) : ℝ≥0∞) := rfl, rw this, simp only [id.def, coe_ennreal_lt_coe_ennreal_iff], exact is_open_Ioi, }, { have : ∀ (y : ℝ≥0∞), (x : ereal) < y := λ y, (ereal.coe_lt_coe_iff.2 h).trans_le (coe_ennreal_nonneg _), simp only [this, is_open_univ, set_of_true] } }, { simp only [set_of_false, is_open_empty, not_top_lt] } }, show is_open {b : ℝ≥0∞ | ↑b < a}, { induction a using ereal.rec with x, { simp only [not_lt_bot, set_of_false, is_open_empty] }, { rcases le_or_lt 0 x with h|h, { have : (x : ereal) = ((id ⟨x, h⟩ : ℝ≥0) : ℝ≥0∞) := rfl, rw this, simp only [id.def, coe_ennreal_lt_coe_ennreal_iff], exact is_open_Iio, }, { convert is_open_empty, apply eq_empty_iff_forall_not_mem.2 (λ y hy, lt_irrefl (x : ereal) _), exact ((ereal.coe_lt_coe_iff.2 h).trans_le (coe_ennreal_nonneg y)).trans hy } }, { simp only [← coe_ennreal_top, coe_ennreal_lt_coe_ennreal_iff], exact is_open_Iio } } }, { 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, by simp only [imp_self, coe_ennreal_eq_coe_ennreal_iff]⟩ @[norm_cast] lemma tendsto_coe_ennreal {α : Type*} {f : filter α} {m : α → ℝ≥0∞} {a : ℝ≥0∞} : tendsto (λ a, (m a : ereal)) f (𝓝 ↑a) ↔ tendsto m f (𝓝 a) := embedding_coe_ennreal.tendsto_nhds_iff.symm lemma _root_.continuous_coe_ennreal_ereal : continuous (coe : ℝ≥0∞ → ereal) := embedding_coe_ennreal.continuous lemma continuous_coe_ennreal_iff {f : α → ℝ≥0∞} : continuous (λa, (f a : ereal)) ↔ continuous f := embedding_coe_ennreal.continuous_iff.symm /-! ### Neighborhoods of infinity -/ lemma nhds_top : 𝓝 (⊤ : ereal) = ⨅ a ≠ ⊤, 𝓟 (Ioi a) := nhds_top_order.trans $ by simp [lt_top_iff_ne_top, Ioi] lemma nhds_top' : 𝓝 (⊤ : ereal) = ⨅ a : ℝ, 𝓟 (Ioi a) := begin rw [nhds_top], apply le_antisymm, { exact infi_mono' (λ x, ⟨x, by simp⟩) }, { refine le_infi (λ r, le_infi (λ hr, _)), induction r using ereal.rec, { exact (infi_le _ 0).trans (by simp) }, { exact infi_le _ _ }, { simpa using hr, } } end lemma mem_nhds_top_iff {s : set ereal} : s ∈ 𝓝 (⊤ : ereal) ↔ ∃ (y : ℝ), Ioi (y : ereal) ⊆ s := begin rw [nhds_top', mem_infi_of_directed], { refl }, exact λ x y, ⟨max x y, by simp [le_refl], by simp [le_refl]⟩, end lemma tendsto_nhds_top_iff_real {α : Type*} {m : α → ereal} {f : filter α} : tendsto m f (𝓝 ⊤) ↔ ∀ x : ℝ, ∀ᶠ a in f, ↑x < m a := by simp only [nhds_top', mem_Ioi, tendsto_infi, tendsto_principal] lemma nhds_bot : 𝓝 (⊥ : ereal) = ⨅ a ≠ ⊥, 𝓟 (Iio a) := nhds_bot_order.trans $ by simp [bot_lt_iff_ne_bot] lemma nhds_bot' : 𝓝 (⊥ : ereal) = ⨅ a : ℝ, 𝓟 (Iio a) := begin rw [nhds_bot], apply le_antisymm, { exact infi_mono' (λ x, ⟨x, by simp⟩) }, { refine le_infi (λ r, le_infi (λ hr, _)), induction r using ereal.rec, { simpa using hr }, { exact infi_le _ _ }, { exact (infi_le _ 0).trans (by simp) } } end lemma mem_nhds_bot_iff {s : set ereal} : s ∈ 𝓝 (⊥ : ereal) ↔ ∃ (y : ℝ), Iio (y : ereal) ⊆ s := begin rw [nhds_bot', mem_infi_of_directed], { refl }, exact λ x y, ⟨min x y, by simp [le_refl], by simp [le_refl]⟩, end lemma tendsto_nhds_bot_iff_real {α : Type*} {m : α → ereal} {f : filter α} : tendsto m f (𝓝 ⊥) ↔ ∀ x : ℝ, ∀ᶠ a in f, m a < x := by simp only [nhds_bot', mem_Iio, tendsto_infi, tendsto_principal] /-! ### Continuity of addition -/ lemma continuous_at_add_coe_coe (a b :ℝ) : continuous_at (λ (p : ereal × ereal), p.1 + p.2) (a, b) := by simp only [continuous_at, nhds_coe_coe, ← coe_add, tendsto_map'_iff, (∘), tendsto_coe, tendsto_add] lemma continuous_at_add_top_coe (a : ℝ) : continuous_at (λ (p : ereal × ereal), p.1 + p.2) (⊤, a) := begin simp only [continuous_at, tendsto_nhds_top_iff_real, top_add_coe, nhds_prod_eq], assume r, rw eventually_prod_iff, refine ⟨λ z, ((r - (a - 1): ℝ) : ereal) < z, Ioi_mem_nhds (coe_lt_top _), λ z, ((a - 1 : ℝ) : ereal) < z, Ioi_mem_nhds (by simp [-ereal.coe_sub]), λ x hx y hy, _⟩, dsimp, convert add_lt_add hx hy, simp, end lemma continuous_at_add_coe_top (a : ℝ) : continuous_at (λ (p : ereal × ereal), p.1 + p.2) (a, ⊤) := begin change continuous_at ((λ (p : ereal × ereal), p.2 + p.1) ∘ prod.swap) (a, ⊤), apply continuous_at.comp _ continuous_swap.continuous_at, simp_rw add_comm, exact continuous_at_add_top_coe a end lemma continuous_at_add_top_top : continuous_at (λ (p : ereal × ereal), p.1 + p.2) (⊤, ⊤) := begin simp only [continuous_at, tendsto_nhds_top_iff_real, top_add_top, nhds_prod_eq], assume r, rw eventually_prod_iff, refine ⟨λ z, (r : ereal) < z, Ioi_mem_nhds (coe_lt_top _), λ z, ((0 : ℝ) : ereal) < z, Ioi_mem_nhds (by simp [zero_lt_one]), λ x hx y hy, _⟩, dsimp, convert add_lt_add hx hy, simp, end lemma continuous_at_add_bot_coe (a : ℝ) : continuous_at (λ (p : ereal × ereal), p.1 + p.2) (⊥, a) := begin simp only [continuous_at, tendsto_nhds_bot_iff_real, nhds_prod_eq, bot_add], assume r, rw eventually_prod_iff, refine ⟨λ z, z < ((r - (a + 1): ℝ) : ereal), Iio_mem_nhds (bot_lt_coe _), λ z, z < ((a + 1 : ℝ) : ereal), Iio_mem_nhds (by simp [-coe_add, zero_lt_one]), λ x hx y hy, _⟩, convert add_lt_add hx hy, rw sub_add_cancel, end lemma continuous_at_add_coe_bot (a : ℝ) : continuous_at (λ (p : ereal × ereal), p.1 + p.2) (a, ⊥) := begin change continuous_at ((λ (p : ereal × ereal), p.2 + p.1) ∘ prod.swap) (a, ⊥), apply continuous_at.comp _ continuous_swap.continuous_at, simp_rw add_comm, exact continuous_at_add_bot_coe a end lemma continuous_at_add_bot_bot : continuous_at (λ (p : ereal × ereal), p.1 + p.2) (⊥, ⊥) := begin simp only [continuous_at, tendsto_nhds_bot_iff_real, nhds_prod_eq, bot_add], assume r, rw eventually_prod_iff, refine ⟨λ z, z < r, Iio_mem_nhds (bot_lt_coe _), λ z, z < 0, Iio_mem_nhds (bot_lt_coe _), λ x hx y hy, _⟩, dsimp, convert add_lt_add hx hy, simp end /-- The addition on `ereal` is continuous except where it doesn't make sense (i.e., at `(⊥, ⊤)` and at `(⊤, ⊥)`). -/ lemma continuous_at_add {p : ereal × ereal} (h : p.1 ≠ ⊤ ∨ p.2 ≠ ⊥) (h' : p.1 ≠ ⊥ ∨ p.2 ≠ ⊤) : continuous_at (λ (p : ereal × ereal), p.1 + p.2) p := begin rcases p with ⟨x, y⟩, induction x using ereal.rec; induction y using ereal.rec, { exact continuous_at_add_bot_bot }, { exact continuous_at_add_bot_coe _ }, { simpa using h' }, { exact continuous_at_add_coe_bot _ }, { exact continuous_at_add_coe_coe _ _ }, { exact continuous_at_add_coe_top _ }, { simpa using h }, { exact continuous_at_add_top_coe _ }, { exact continuous_at_add_top_top }, end /-! ### Negation-/ /-- Negation on `ereal` as a homeomorphism -/ def neg_homeo : ereal ≃ₜ ereal := neg_order_iso.to_homeomorph lemma continuous_neg : continuous (λ (x : ereal), -x) := neg_homeo.continuous end ereal
43402aef6f98db6bd700de22a1c730d280763e03
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/analysis/normed/group/add_circle.lean
192c1f5c0a21392c1b7b9091de7b80f7dac32675
[ "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
11,225
lean
/- Copyright (c) 2022 Oliver Nash. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Oliver Nash -/ import analysis.normed.group.quotient import topology.instances.add_circle /-! # The additive circle as a normed group We define the normed group structure on `add_circle p`, for `p : ℝ`. For example if `p = 1` then: `‖(x : add_circle 1)‖ = |x - round x|` for any `x : ℝ` (see `unit_add_circle.norm_eq`). ## Main definitions: * `add_circle.norm_eq`: a characterisation of the norm on `add_circle p` ## TODO * The fact `inner_product_geometry.angle (real.cos θ) (real.sin θ) = ‖(θ : real.angle)‖` -/ noncomputable theory open set int (hiding mem_zmultiples_iff) add_subgroup namespace add_circle variables (p : ℝ) instance : normed_add_comm_group (add_circle p) := add_subgroup.normed_add_comm_group_quotient _ @[simp] lemma norm_coe_mul (x : ℝ) (t : ℝ) : ‖(↑(t * x) : add_circle (t * p))‖ = |t| * ‖(x : add_circle p)‖ := begin have aux : ∀ {a b c : ℝ}, a ∈ zmultiples b → c * a ∈ zmultiples (c * b) := λ a b c h, by { simp only [mem_zmultiples_iff] at ⊢ h, obtain ⟨n, rfl⟩ := h, exact ⟨n, (mul_smul_comm n c b).symm⟩, }, rcases eq_or_ne t 0 with rfl | ht, { simp, }, have ht' : |t| ≠ 0 := (not_congr abs_eq_zero).mpr ht, simp only [quotient_norm_eq, real.norm_eq_abs], conv_rhs { rw [← smul_eq_mul, ← real.Inf_smul_of_nonneg (abs_nonneg t)], }, simp only [quotient_add_group.mk'_apply, quotient_add_group.eq_iff_sub_mem], congr' 1, ext z, rw mem_smul_set_iff_inv_smul_mem₀ ht', show (∃ y, y - t * x ∈ zmultiples (t * p) ∧ |y| = z) ↔ ∃w, w - x ∈ zmultiples p ∧ |w| = |t|⁻¹ * z, split, { rintros ⟨y, hy, rfl⟩, refine ⟨t⁻¹ * y, _, by rw [abs_mul, abs_inv]⟩, rw [← inv_mul_cancel_left₀ ht x, ← inv_mul_cancel_left₀ ht p, ← mul_sub], exact aux hy, }, { rintros ⟨w, hw, hw'⟩, refine ⟨t * w, _, by rw [← (eq_inv_mul_iff_mul_eq₀ ht').mp hw', abs_mul]⟩, rw ← mul_sub, exact aux hw, }, end lemma norm_neg_period (x : ℝ) : ‖(x : add_circle (-p))‖ = ‖(x : add_circle p)‖ := begin suffices : ‖(↑(-1 * x) : add_circle (-1 * p))‖ = ‖(x : add_circle p)‖, { rw [← this, neg_one_mul], simp, }, simp only [norm_coe_mul, abs_neg, abs_one, one_mul], end @[simp] lemma norm_eq_of_zero {x : ℝ} : ‖(x : add_circle (0 : ℝ))‖ = |x| := begin suffices : {y : ℝ | (y : add_circle (0 : ℝ)) = (x : add_circle (0 : ℝ)) } = { x }, { rw [quotient_norm_eq, this, image_singleton, real.norm_eq_abs, cInf_singleton], }, ext y, simp [quotient_add_group.eq_iff_sub_mem, mem_zmultiples_iff, sub_eq_zero], end lemma norm_eq {x : ℝ} : ‖(x : add_circle p)‖ = |x - round (p⁻¹ * x) * p| := begin suffices : ∀ (x : ℝ), ‖(x : add_circle (1 : ℝ))‖ = |x - round x|, { rcases eq_or_ne p 0 with rfl | hp, { simp, }, intros, have hx := norm_coe_mul p x p⁻¹, rw [abs_inv, eq_inv_mul_iff_mul_eq₀ ((not_congr abs_eq_zero).mpr hp)] at hx, rw [← hx, inv_mul_cancel hp, this, ← abs_mul, mul_sub, mul_inv_cancel_left₀ hp, mul_comm p], }, clear x p, intros, rw [quotient_norm_eq, abs_sub_round_eq_min], have h₁ : bdd_below (abs '' {m : ℝ | (m : add_circle (1 : ℝ)) = x}) := ⟨0, by simp [mem_lower_bounds]⟩, have h₂ : (abs '' {m : ℝ | (m : add_circle (1 : ℝ)) = x}).nonempty := ⟨|x|, ⟨x, rfl, rfl⟩⟩, apply le_antisymm, { simp only [le_min_iff, real.norm_eq_abs, cInf_le_iff h₁ h₂], intros b h, refine ⟨mem_lower_bounds.1 h _ ⟨fract x, _, abs_fract⟩, mem_lower_bounds.1 h _ ⟨fract x - 1, _, by rw [abs_sub_comm, abs_one_sub_fract]⟩⟩, { simp only [mem_set_of_eq, fract, sub_eq_self, quotient_add_group.coe_sub, quotient_add_group.eq_zero_iff, int_cast_mem_zmultiples_one], }, { simp only [mem_set_of_eq, fract, sub_eq_self, quotient_add_group.coe_sub, quotient_add_group.eq_zero_iff, int_cast_mem_zmultiples_one, sub_sub, (by norm_cast : (⌊x⌋ : ℝ) + 1 = (↑(⌊x⌋ + 1) : ℝ))], }, }, { simp only [quotient_add_group.mk'_apply, real.norm_eq_abs, le_cInf_iff h₁ h₂], rintros b' ⟨b, hb, rfl⟩, simp only [mem_set_of_eq, quotient_add_group.eq_iff_sub_mem, mem_zmultiples_iff, smul_one_eq_coe] at hb, obtain ⟨z, hz⟩ := hb, rw [(by { rw hz, abel, } : x = b - z), fract_sub_int, ← abs_sub_round_eq_min], convert round_le b 0, simp, }, end lemma norm_eq' (hp : 0 < p) {x : ℝ} : ‖(x : add_circle p)‖ = p * |(p⁻¹ * x) - round (p⁻¹ * x)| := begin conv_rhs { congr, rw ← abs_eq_self.mpr hp.le, }, rw [← abs_mul, mul_sub, mul_inv_cancel_left₀ hp.ne.symm, norm_eq, mul_comm p], end lemma norm_le_half_period {x : add_circle p} (hp : p ≠ 0) : ‖x‖ ≤ |p|/2 := begin obtain ⟨x⟩ := x, change ‖(x : add_circle p)‖ ≤ |p|/2, rw [norm_eq, ← mul_le_mul_left (abs_pos.mpr (inv_ne_zero hp)), ← abs_mul, mul_sub, mul_left_comm, ← mul_div_assoc, ← abs_mul, inv_mul_cancel hp, mul_one, abs_one], exact abs_sub_round (p⁻¹ * x), end @[simp] lemma norm_half_period_eq : ‖(↑(p/2) : add_circle p)‖ = |p|/2 := begin rcases eq_or_ne p 0 with rfl | hp, { simp, }, rw [norm_eq, ← mul_div_assoc, inv_mul_cancel hp, one_div, round_two_inv, algebra_map.coe_one, one_mul, (by linarith : p / 2 - p = -(p / 2)), abs_neg, abs_div, abs_two], end lemma norm_coe_eq_abs_iff {x : ℝ} (hp : p ≠ 0) : ‖(x : add_circle p)‖ = |x| ↔ |x| ≤ |p|/2 := begin refine ⟨λ hx, hx ▸ norm_le_half_period p hp, λ hx, _⟩, suffices : ∀ (p : ℝ), 0 < p → |x| ≤ p/2 → ‖(x : add_circle p)‖ = |x|, { rcases lt_trichotomy 0 p with hp | rfl | hp, { rw abs_eq_self.mpr hp.le at hx, exact this p hp hx, }, { contradiction, }, { rw ← norm_neg_period, rw abs_eq_neg_self.mpr hp.le at hx, exact this (-p) (neg_pos.mpr hp) hx, }, }, clear hx, intros p hp hx, rcases eq_or_ne x (p/2) with rfl | hx', { simp [abs_div, abs_two], }, suffices : round (p⁻¹ * x) = 0, { simp [norm_eq, this], }, rw round_eq_zero_iff, obtain ⟨hx₁, hx₂⟩ := abs_le.mp hx, replace hx₂ := ne.lt_of_le hx' hx₂, split, { rwa [← mul_le_mul_left hp, ← mul_assoc, mul_inv_cancel hp.ne.symm, one_mul, mul_neg, ← mul_div_assoc, mul_one], }, { rwa [← mul_lt_mul_left hp, ← mul_assoc, mul_inv_cancel hp.ne.symm, one_mul, ← mul_div_assoc, mul_one], }, end open metric lemma closed_ball_eq_univ_of_half_period_le (hp : p ≠ 0) (x : add_circle p) {ε : ℝ} (hε : |p|/2 ≤ ε) : closed_ball x ε = univ := eq_univ_iff_forall.mpr $ λ x, by simpa only [mem_closed_ball, dist_eq_norm] using (norm_le_half_period p hp).trans hε @[simp] lemma coe_real_preimage_closed_ball_period_zero (x ε : ℝ) : coe⁻¹' closed_ball (x : add_circle (0 : ℝ)) ε = closed_ball x ε := by { ext y; simp [dist_eq_norm, ← quotient_add_group.coe_sub], } lemma coe_real_preimage_closed_ball_eq_Union (x ε : ℝ) : coe⁻¹' closed_ball (x : add_circle p) ε = ⋃ (z : ℤ), closed_ball (x + z • p) ε := begin rcases eq_or_ne p 0 with rfl | hp, { simp [Union_const], }, ext y, simp only [dist_eq_norm, mem_preimage, mem_closed_ball, zsmul_eq_mul, mem_Union, real.norm_eq_abs, ← quotient_add_group.coe_sub, norm_eq, ← sub_sub], refine ⟨λ h, ⟨round (p⁻¹ * (y - x)), h⟩, _⟩, rintros ⟨n, hn⟩, rw [← mul_le_mul_left (abs_pos.mpr $ inv_ne_zero hp), ← abs_mul, mul_sub, mul_comm _ p, inv_mul_cancel_left₀ hp] at hn ⊢, exact (round_le (p⁻¹ * (y - x)) n).trans hn, end lemma coe_real_preimage_closed_ball_inter_eq {x ε : ℝ} (s : set ℝ) (hs : s ⊆ closed_ball x (|p|/2)) : coe⁻¹' closed_ball (x : add_circle p) ε ∩ s = if ε < |p|/2 then (closed_ball x ε) ∩ s else s := begin cases le_or_lt (|p|/2) ε with hε hε, { rcases eq_or_ne p 0 with rfl | hp, { simp only [abs_zero, zero_div] at hε, simp only [not_lt.mpr hε, coe_real_preimage_closed_ball_period_zero, abs_zero, zero_div, if_false, inter_eq_right_iff_subset], exact hs.trans (closed_ball_subset_closed_ball $ by simp [hε]), }, simp [closed_ball_eq_univ_of_half_period_le p hp ↑x hε, not_lt.mpr hε], }, { suffices : ∀ (z : ℤ), closed_ball (x + z • p) ε ∩ s = if z = 0 then closed_ball x ε ∩ s else ∅, { simp [-zsmul_eq_mul, ← quotient_add_group.coe_zero, coe_real_preimage_closed_ball_eq_Union, Union_inter, Union_ite, this, hε], }, intros z, simp only [real.closed_ball_eq_Icc, zero_sub, zero_add] at ⊢ hs, rcases eq_or_ne z 0 with rfl | hz, { simp, }, simp only [hz, zsmul_eq_mul, if_false, eq_empty_iff_forall_not_mem], rintros y ⟨⟨hy₁, hy₂⟩, hy₀⟩, obtain ⟨hy₃, hy₄⟩ := hs hy₀, rcases lt_trichotomy 0 p with hp | rfl | hp, { cases int.cast_le_neg_one_or_one_le_cast_of_ne_zero ℝ hz with hz' hz', { have : ↑z * p ≤ - p, nlinarith, linarith [abs_eq_self.mpr hp.le] }, { have : p ≤ ↑z * p, nlinarith, linarith [abs_eq_self.mpr hp.le] } }, { simp only [mul_zero, add_zero, abs_zero, zero_div] at hy₁ hy₂ hε, linarith }, { cases int.cast_le_neg_one_or_one_le_cast_of_ne_zero ℝ hz with hz' hz', { have : - p ≤ ↑z * p, nlinarith, linarith [abs_eq_neg_self.mpr hp.le] }, { have : ↑z * p ≤ p, nlinarith, linarith [abs_eq_neg_self.mpr hp.le] } } }, end section finite_order_points variables {p} [hp : fact (0 < p)] include hp lemma norm_div_nat_cast {m n : ℕ} : ‖(↑((↑m / ↑n) * p) : add_circle p)‖ = p * (↑(min (m % n) (n - m % n)) / n) := begin have : p⁻¹ * (↑m / ↑n * p) = ↑m / ↑n, { rw [mul_comm _ p, inv_mul_cancel_left₀ hp.out.ne.symm], }, rw [norm_eq' p hp.out, this, abs_sub_round_div_nat_cast_eq], end lemma exists_norm_eq_of_fin_add_order {u : add_circle p} (hu : is_of_fin_add_order u) : ∃ (k : ℕ), ‖u‖ = p * (k / add_order_of u) := begin let n := add_order_of u, change ∃ (k : ℕ), ‖u‖ = p * (k / n), obtain ⟨m, -, -, hm⟩ := exists_gcd_eq_one_of_is_of_fin_add_order hu, refine ⟨min (m % n) (n - m % n), _⟩, rw [← hm, norm_div_nat_cast], end lemma le_add_order_smul_norm_of_is_of_fin_add_order {u : add_circle p} (hu : is_of_fin_add_order u) (hu' : u ≠ 0) : p ≤ add_order_of u • ‖u‖ := begin obtain ⟨n, hn⟩ := exists_norm_eq_of_fin_add_order hu, replace hu : (add_order_of u : ℝ) ≠ 0, { norm_cast, exact (add_order_of_pos_iff.mpr hu).ne.symm }, conv_lhs { rw ← mul_one p, }, rw [hn, nsmul_eq_mul, ← mul_assoc, mul_comm _ p, mul_assoc, mul_div_cancel' _ hu, mul_le_mul_left hp.out, nat.one_le_cast, nat.one_le_iff_ne_zero], contrapose! hu', simpa only [hu', algebra_map.coe_zero, zero_div, mul_zero, norm_eq_zero] using hn, end end finite_order_points end add_circle namespace unit_add_circle lemma norm_eq {x : ℝ} : ‖(x : unit_add_circle)‖ = |x - round x| := by simp [add_circle.norm_eq] end unit_add_circle
7187faa40856dc76a0234a43f51babe5fe075e50
957a80ea22c5abb4f4670b250d55534d9db99108
/library/init/core.lean
30347dd282ac8ebfb4a873956d1781fc49394260
[ "Apache-2.0" ]
permissive
GaloisInc/lean
aa1e64d604051e602fcf4610061314b9a37ab8cd
f1ec117a24459b59c6ff9e56a1d09d9e9e60a6c0
refs/heads/master
1,592,202,909,807
1,504,624,387,000
1,504,624,387,000
75,319,626
2
1
Apache-2.0
1,539,290,164,000
1,480,616,104,000
C++
UTF-8
Lean
false
false
16,730
lean
/- Copyright (c) 2014 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura notation, basic datatypes and type classes -/ prelude notation `Prop` := Sort 0 notation f ` $ `:1 a:0 := f a /- Logical operations and relations -/ reserve prefix `¬`:40 reserve prefix `~`:40 reserve infixr ` ∧ `:35 reserve infixr ` /\ `:35 reserve infixr ` \/ `:30 reserve infixr ` ∨ `:30 reserve infix ` <-> `:20 reserve infix ` ↔ `:20 reserve infix ` = `:50 reserve infix ` == `:50 reserve infix ` ≠ `:50 reserve infix ` ≈ `:50 reserve infix ` ~ `:50 reserve infix ` ≡ `:50 reserve infixl ` ⬝ `:75 reserve infixr ` ▸ `:75 reserve infixr ` ▹ `:75 /- types and type constructors -/ reserve infixr ` ⊕ `:30 reserve infixr ` × `:35 /- arithmetic operations -/ reserve infixl ` + `:65 reserve infixl ` - `:65 reserve infixl ` * `:70 reserve infixl ` / `:70 reserve infixl ` % `:70 reserve prefix `-`:100 reserve infix ` ^ `:80 reserve infixr ` ∘ `:90 -- input with \comp reserve infix ` <= `:50 reserve infix ` ≤ `:50 reserve infix ` < `:50 reserve infix ` >= `:50 reserve infix ` ≥ `:50 reserve infix ` > `:50 /- boolean operations -/ reserve infixl ` && `:70 reserve infixl ` || `:65 /- set operations -/ reserve infix ` ∈ `:50 reserve infix ` ∉ `:50 reserve infixl ` ∩ `:70 reserve infixl ` ∪ `:65 reserve infix ` ⊆ `:50 reserve infix ` ⊇ `:50 reserve infix ` ⊂ `:50 reserve infix ` ⊃ `:50 reserve infix ` \ `:70 /- other symbols -/ reserve infix ` ∣ `:50 reserve infixl ` ++ `:65 reserve infixr ` :: `:67 reserve infixl `; `:1 universes u v w /-- Gadget for optional parameter support. -/ @[reducible] def opt_param (α : Sort u) (default : α) : Sort u := α /-- Gadget for marking output parameters in type classes. -/ @[reducible] def inout_param (α : Sort u) : Sort u := α notation `inout`:1024 a:0 := inout_param a inductive punit : Sort u | star : punit inductive unit : Type | star : unit /-- Gadget for defining thunks, thunk parameters have special treatment. Example: given def f (s : string) (t : thunk nat) : nat an application f "hello" 10 is converted into f "hello" (λ _, 10) -/ @[reducible] def thunk (α : Type u) : Type u := unit → α inductive true : Prop | intro : true inductive false : Prop inductive empty : Type def not (a : Prop) := a → false prefix `¬` := not inductive eq {α : Sort u} (a : α) : α → Prop | refl : eq a /- 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_quotient inductive heq {α : Sort u} (a : α) : Π {β : Sort u}, β → Prop | refl : heq a structure prod (α : Type u) (β : Type v) := (fst : α) (snd : β) /-- Similar to `prod`, but α and β can be propositions. We use this type internally to automatically generate the brec_on recursor. -/ structure pprod (α : Sort u) (β : Sort v) := (fst : α) (snd : β) inductive and (a b : Prop) : Prop | intro : a → b → and def and.elim_left {a b : Prop} (h : and a b) : a := and.rec (λ ha hb, ha) h def and.left := @and.elim_left def and.elim_right {a b : Prop} (h : and a b) : b := and.rec (λ ha hb, hb) h def and.right := @and.elim_right /- eq basic support -/ infix = := eq attribute [refl] eq.refl @[pattern] def rfl {α : Sort u} {a : α} : a = a := eq.refl a @[elab_as_eliminator, subst] lemma eq.subst {α : Sort u} {P : α → Prop} {a b : α} (h₁ : a = b) (h₂ : P a) : P b := eq.rec h₂ h₁ notation h1 ▸ h2 := eq.subst h1 h2 @[trans] lemma eq.trans {α : Sort u} {a b c : α} (h₁ : a = b) (h₂ : b = c) : a = c := h₂ ▸ h₁ @[symm] lemma eq.symm {α : Sort u} {a b : α} (h : a = b) : b = a := h ▸ rfl infix == := heq @[pattern] def heq.rfl {α : Sort u} {a : α} : a == a := heq.refl a lemma eq_of_heq {α : Sort u} {a a' : α} (h : a == a') : a = a' := have ∀ (α' : Sort u) (a' : α') (h₁ : @heq α a α' a') (h₂ : α = α'), (eq.rec_on h₂ a : α') = a', from λ (α' : Sort u) (a' : α') (h₁ : @heq α a α' a'), heq.rec_on h₁ (λ h₂ : α = α, rfl), show (eq.rec_on (eq.refl α) a : α) = a', from this α a' h (eq.refl α) /- The following four lemmas could not be automatically generated when the structures were declared, so we prove them manually here. -/ lemma prod.mk.inj {α : Type u} {β : Type v} {x₁ : α} {y₁ : β} {x₂ : α} {y₂ : β} : (x₁, y₁) = (x₂, y₂) → and (x₁ = x₂) (y₁ = y₂) := λ h, prod.no_confusion h (λ h₁ h₂, ⟨h₁, h₂⟩) lemma prod.mk.inj_arrow {α : Type u} {β : Type v} {x₁ : α} {y₁ : β} {x₂ : α} {y₂ : β} : (x₁, y₁) = (x₂, y₂) → Π ⦃P : Sort w⦄, (x₁ = x₂ → y₁ = y₂ → P) → P := λ h₁ _ h₂, prod.no_confusion h₁ h₂ lemma pprod.mk.inj {α : Sort u} {β : Sort v} {x₁ : α} {y₁ : β} {x₂ : α} {y₂ : β} : pprod.mk x₁ y₁ = pprod.mk x₂ y₂ → and (x₁ = x₂) (y₁ = y₂) := λ h, pprod.no_confusion h (λ h₁ h₂, ⟨h₁, h₂⟩) lemma pprod.mk.inj_arrow {α : Type u} {β : Type v} {x₁ : α} {y₁ : β} {x₂ : α} {y₂ : β} : (x₁, y₁) = (x₂, y₂) → Π ⦃P : Sort w⦄, (x₁ = x₂ → y₁ = y₂ → P) → P := λ h₁ _ h₂, prod.no_confusion h₁ h₂ inductive sum (α : Type u) (β : Type v) | inl {} : α → sum | inr {} : β → sum inductive psum (α : Sort u) (β : Sort v) | inl {} : α → psum | inr {} : β → psum inductive or (a b : Prop) : Prop | inl {} : a → or | inr {} : b → or def or.intro_left {a : Prop} (b : Prop) (ha : a) : or a b := or.inl ha def or.intro_right (a : Prop) {b : Prop} (hb : b) : or a b := or.inr hb structure sigma {α : Type u} (β : α → Type v) := mk :: (fst : α) (snd : β fst) structure psigma {α : Sort u} (β : α → Sort v) := mk :: (fst : α) (snd : β fst) inductive bool : Type | ff : bool | tt : bool /- Remark: subtype must take a Sort instead of Type because of the axiom strong_indefinite_description. -/ structure subtype {α : Sort u} (p : α → Prop) := (val : α) (property : p val) attribute [pp_using_anonymous_constructor] sigma psigma subtype pprod class inductive decidable (p : Prop) | is_false : ¬p → decidable | is_true : p → decidable @[reducible] def decidable_pred {α : Sort u} (r : α → Prop) := Π (a : α), decidable (r a) @[reducible] def decidable_rel {α : Sort u} (r : α → α → Prop) := Π (a b : α), decidable (r a b) @[reducible] def decidable_eq (α : Sort u) := decidable_rel (@eq α) inductive option (α : Type u) | none {} : option | some : α → option export option (none some) export bool (ff tt) inductive list (T : Type u) | nil {} : list | cons : T → list → list notation h :: t := list.cons h t notation `[` l:(foldr `, ` (h t, list.cons h t) list.nil `]`) := l inductive nat | zero : nat | succ : nat → nat structure unification_constraint := {α : Type u} (lhs : α) (rhs : α) infix ` ≟ `:50 := unification_constraint.mk infix ` =?= `:50 := unification_constraint.mk structure unification_hint := (pattern : unification_constraint) (constraints : list unification_constraint) /- Declare builtin and reserved notation -/ class has_zero (α : Type u) := (zero : α) class has_one (α : Type u) := (one : α) class has_add (α : Type u) := (add : α → α → α) class has_mul (α : Type u) := (mul : α → α → α) class has_inv (α : Type u) := (inv : α → α) class has_neg (α : Type u) := (neg : α → α) class has_sub (α : Type u) := (sub : α → α → α) class has_div (α : Type u) := (div : α → α → α) class has_dvd (α : Type u) := (dvd : α → α → Prop) class has_mod (α : Type u) := (mod : α → α → α) class has_le (α : Type u) := (le : α → α → Prop) class has_lt (α : Type u) := (lt : α → α → Prop) class has_append (α : Type u) := (append : α → α → α) class has_andthen (α : Type u) (β : Type v) (σ : inout Type w) := (andthen : α → β → σ) class has_union (α : Type u) := (union : α → α → α) class has_inter (α : Type u) := (inter : α → α → α) class has_sdiff (α : Type u) := (sdiff : α → α → α) class has_subset (α : Type u) := (subset : α → α → Prop) class has_ssubset (α : Type u) := (ssubset : α → α → Prop) /- Type classes has_emptyc and has_insert are used to implement polymorphic notation for collections. Example: {a, b, c}. -/ class has_emptyc (α : Type u) := (emptyc : α) class has_insert (α : inout Type u) (γ : Type v) := (insert : α → γ → γ) /- Type class used to implement the notation { a ∈ c | p a } -/ class has_sep (α : inout Type u) (γ : Type v) := (sep : (α → Prop) → γ → γ) /- Type class for set-like membership -/ class has_mem (α : inout Type u) (γ : Type v) := (mem : α → γ → Prop) def andthen {α : Type u} {β : Type v} {σ : Type w} [has_andthen α β σ] : α → β → σ := has_andthen.andthen σ infix ∈ := has_mem.mem notation a ∉ s := ¬ has_mem.mem a s infix + := has_add.add infix * := has_mul.mul infix - := has_sub.sub infix / := has_div.div infix ∣ := has_dvd.dvd infix % := has_mod.mod prefix - := has_neg.neg infix <= := has_le.le infix ≤ := has_le.le infix < := has_lt.lt infix ++ := has_append.append infix ; := andthen notation `∅` := has_emptyc.emptyc _ infix ∪ := has_union.union infix ∩ := has_inter.inter infix ⊆ := has_subset.subset infix ⊂ := has_ssubset.ssubset infix \ := has_sdiff.sdiff export has_append (append) @[reducible] def ge {α : Type u} [has_le α] (a b : α) : Prop := has_le.le b a @[reducible] def gt {α : Type u} [has_lt α] (a b : α) : Prop := has_lt.lt b a infix >= := ge infix ≥ := ge infix > := gt @[reducible] def superset {α : Type u} [has_subset α] (a b : α) : Prop := has_subset.subset b a @[reducible] def ssuperset {α : Type u} [has_ssubset α] (a b : α) : Prop := has_ssubset.ssubset b a infix ⊇ := superset infix ⊃ := ssuperset def bit0 {α : Type u} [s : has_add α] (a : α) : α := a + a def bit1 {α : Type u} [s₁ : has_one α] [s₂ : has_add α] (a : α) : α := (bit0 a) + 1 attribute [pattern] has_zero.zero has_one.one bit0 bit1 has_add.add has_neg.neg def insert {α : Type u} {γ : Type v} [has_insert α γ] : α → γ → γ := has_insert.insert /- The empty collection -/ def singleton {α : Type u} {γ : Type v} [has_emptyc γ] [has_insert α γ] (a : α) : γ := has_insert.insert a ∅ /- nat basic instances -/ namespace nat protected def add : nat → nat → nat | a zero := a | a (succ b) := succ (add a b) /- We mark the following definitions as pattern to make sure they can be used in recursive equations, and reduced by the equation compiler. -/ attribute [pattern] nat.add nat.add._main end nat instance : has_zero nat := ⟨nat.zero⟩ instance : has_one nat := ⟨nat.succ (nat.zero)⟩ instance : has_add nat := ⟨nat.add⟩ def std.priority.default : nat := 1000 def std.priority.max : nat := 0xFFFFFFFF namespace nat protected def prio := std.priority.default + 100 end nat /- Global declarations of right binding strength If a module reassigns these, it will be incompatible with other modules that adhere to these conventions. When hovering over a symbol, use "C-c C-k" to see how to input it. -/ def std.prec.max : nat := 1024 -- the strength of application, identifiers, (, [, etc. def std.prec.arrow : nat := 25 /- The next def is "max + 10". It can be used e.g. for postfix operations that should be stronger than application. -/ def std.prec.max_plus : nat := std.prec.max + 10 reserve postfix `⁻¹`:std.prec.max_plus -- input with \sy or \-1 or \inv postfix ⁻¹ := has_inv.inv notation α × β := prod α β -- notation for n-ary tuples /- sizeof -/ class has_sizeof (α : Sort u) := (sizeof : α → nat) def sizeof {α : Sort u} [s : has_sizeof α] : α → nat := has_sizeof.sizeof /- Declare sizeof instances and lemmas for types declared before has_sizeof. From now on, the inductive compiler will automatically generate sizeof instances and lemmas. -/ /- Every type `α` has a default has_sizeof instance that just returns 0 for every element of `α` -/ protected def default.sizeof (α : Sort u) : α → nat | a := 0 instance default_has_sizeof (α : Sort u) : has_sizeof α := ⟨default.sizeof α⟩ protected def nat.sizeof : nat → nat | n := n instance : has_sizeof nat := ⟨nat.sizeof⟩ protected def prod.sizeof {α : Type u} {β : Type v} [has_sizeof α] [has_sizeof β] : (prod α β) → nat | ⟨a, b⟩ := 1 + sizeof a + sizeof b instance (α : Type u) (β : Type v) [has_sizeof α] [has_sizeof β] : has_sizeof (prod α β) := ⟨prod.sizeof⟩ protected def sum.sizeof {α : Type u} {β : Type v} [has_sizeof α] [has_sizeof β] : (sum α β) → nat | (sum.inl a) := 1 + sizeof a | (sum.inr b) := 1 + sizeof b instance (α : Type u) (β : Type v) [has_sizeof α] [has_sizeof β] : has_sizeof (sum α β) := ⟨sum.sizeof⟩ protected def psum.sizeof {α : Type u} {β : Type v} [has_sizeof α] [has_sizeof β] : (psum α β) → nat | (psum.inl a) := 1 + sizeof a | (psum.inr b) := 1 + sizeof b instance (α : Type u) (β : Type v) [has_sizeof α] [has_sizeof β] : has_sizeof (psum α β) := ⟨psum.sizeof⟩ protected def sigma.sizeof {α : Type u} {β : α → Type v} [has_sizeof α] [∀ a, has_sizeof (β a)] : sigma β → nat | ⟨a, b⟩ := 1 + sizeof a + sizeof b instance (α : Type u) (β : α → Type v) [has_sizeof α] [∀ a, has_sizeof (β a)] : has_sizeof (sigma β) := ⟨sigma.sizeof⟩ protected def psigma.sizeof {α : Type u} {β : α → Type v} [has_sizeof α] [∀ a, has_sizeof (β a)] : psigma β → nat | ⟨a, b⟩ := 1 + sizeof a + sizeof b instance (α : Type u) (β : α → Type v) [has_sizeof α] [∀ a, has_sizeof (β a)] : has_sizeof (psigma β) := ⟨psigma.sizeof⟩ protected def unit.sizeof : unit → nat | u := 1 instance : has_sizeof unit := ⟨unit.sizeof⟩ protected def punit.sizeof : punit → nat | u := 1 instance : has_sizeof punit := ⟨punit.sizeof⟩ protected def bool.sizeof : bool → nat | b := 1 instance : has_sizeof bool := ⟨bool.sizeof⟩ protected def option.sizeof {α : Type u} [has_sizeof α] : option α → nat | none := 1 | (some a) := 1 + sizeof a instance (α : Type u) [has_sizeof α] : has_sizeof (option α) := ⟨option.sizeof⟩ protected def list.sizeof {α : Type u} [has_sizeof α] : list α → nat | list.nil := 1 | (list.cons a l) := 1 + sizeof a + list.sizeof l instance (α : Type u) [has_sizeof α] : has_sizeof (list α) := ⟨list.sizeof⟩ protected def subtype.sizeof {α : Type u} [has_sizeof α] {p : α → Prop} : subtype p → nat | ⟨a, _⟩ := sizeof a instance {α : Type u} [has_sizeof α] (p : α → Prop) : has_sizeof (subtype p) := ⟨subtype.sizeof⟩ lemma nat_add_zero (n : nat) : n + 0 = n := rfl /- Combinator calculus -/ namespace combinator universes u₁ u₂ u₃ def I {α : Type u₁} (a : α) := a def K {α : Type u₁} {β : Type u₂} (a : α) (b : β) := a def S {α : Type u₁} {β : Type u₂} {γ : Type u₃} (x : α → β → γ) (y : α → β) (z : α) := x z (y z) end combinator /-- Auxiliary datatype for #[ ... ] notation. #[1, 2, 3, 4] is notation for bin_tree.node (bin_tree.node (bin_tree.leaf 1) (bin_tree.leaf 2)) (bin_tree.node (bin_tree.leaf 3) (bin_tree.leaf 4)) We use this notation to input long sequences without exhausting the system stack space. Later, we define a coercion from `bin_tree` into `list`. -/ inductive bin_tree (α : Type u) | empty {} : bin_tree | leaf (val : α) : bin_tree | node (left right : bin_tree) : bin_tree attribute [elab_simple] bin_tree.node bin_tree.leaf /- Basic unification hints -/ @[unify] def add_succ_defeq_succ_add_hint (x y z : nat) : unification_hint := { pattern := x + nat.succ y ≟ nat.succ z, constraints := [z ≟ x + y] }
6851e17acad0591ff4550b1d21f224804347e13a
8d65764a9e5f0923a67fc435eb1a5a1d02fd80e3
/src/linear_algebra/matrix/to_lin.lean
ad5cf3f7ae211d984e5fa70d1985296d6e16deba
[ "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
27,505
lean
/- Copyright (c) 2019 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Patrick Massot, Casper Putz, Anne Baanen -/ import data.matrix.block import linear_algebra.matrix.finite_dimensional import linear_algebra.std_basis import ring_theory.algebra_tower /-! # Linear maps and matrices This file defines the maps to send matrices to a linear map, and to send linear maps between modules with a finite bases to matrices. This defines a linear equivalence between linear maps between finite-dimensional vector spaces and matrices indexed by the respective bases. ## Main definitions In the list below, and in all this file, `R` is a commutative ring (semiring is sometimes enough), `M` and its variations are `R`-modules, `ι`, `κ`, `n` and `m` are finite types used for indexing. * `linear_map.to_matrix`: given bases `v₁ : ι → M₁` and `v₂ : κ → M₂`, the `R`-linear equivalence from `M₁ →ₗ[R] M₂` to `matrix κ ι R` * `matrix.to_lin`: the inverse of `linear_map.to_matrix` * `linear_map.to_matrix'`: the `R`-linear equivalence from `(n → R) →ₗ[R] (m → R)` to `matrix n m R` (with the standard basis on `n → R` and `m → R`) * `matrix.to_lin'`: the inverse of `linear_map.to_matrix'` * `alg_equiv_matrix`: given a basis indexed by `n`, the `R`-algebra equivalence between `R`-endomorphisms of `M` and `matrix n n R` ## Tags linear_map, matrix, linear_equiv, diagonal, det, trace -/ noncomputable theory open linear_map matrix set submodule open_locale big_operators open_locale matrix universes u v w section to_matrix' variables {R : Type*} [comm_ring R] variables {l m n : Type*} [fintype l] [fintype m] [fintype n] instance [decidable_eq m] [decidable_eq n] (R) [fintype R] : fintype (matrix m n R) := by unfold matrix; apply_instance /-- `matrix.mul_vec M` is a linear map. -/ def matrix.mul_vec_lin (M : matrix m n R) : (n → R) →ₗ[R] (m → R) := { to_fun := M.mul_vec, map_add' := λ v w, funext (λ i, dot_product_add _ _ _), map_smul' := λ c v, funext (λ i, dot_product_smul _ _ _) } @[simp] lemma matrix.mul_vec_lin_apply (M : matrix m n R) (v : n → R) : matrix.mul_vec_lin M v = M.mul_vec v := rfl variables [decidable_eq n] @[simp] lemma matrix.mul_vec_std_basis (M : matrix m n R) (i j) : M.mul_vec (std_basis R (λ _, R) j 1) i = M i j := begin have : (∑ j', M i j' * if j = j' then 1 else 0) = M i j, { simp_rw [mul_boole, finset.sum_ite_eq, finset.mem_univ, if_true] }, convert this, ext, split_ifs with h; simp only [std_basis_apply], { rw [h, function.update_same] }, { rw [function.update_noteq (ne.symm h), pi.zero_apply] } end /-- Linear maps `(n → R) →ₗ[R] (m → R)` are linearly equivalent to `matrix m n R`. -/ def linear_map.to_matrix' : ((n → R) →ₗ[R] (m → R)) ≃ₗ[R] matrix m n R := { to_fun := λ f i j, f (std_basis R (λ _, R) j 1) i, inv_fun := matrix.mul_vec_lin, right_inv := λ M, by { ext i j, simp only [matrix.mul_vec_std_basis, matrix.mul_vec_lin_apply] }, left_inv := λ f, begin apply (pi.basis_fun R n).ext, intro j, ext i, simp only [pi.basis_fun_apply, matrix.mul_vec_std_basis, matrix.mul_vec_lin_apply] end, map_add' := λ f g, by { ext i j, simp only [pi.add_apply, linear_map.add_apply] }, map_smul' := λ c f, by { ext i j, simp only [pi.smul_apply, linear_map.smul_apply] } } /-- A `matrix m n R` is linearly equivalent to a linear map `(n → R) →ₗ[R] (m → R)`. -/ def matrix.to_lin' : matrix m n R ≃ₗ[R] ((n → R) →ₗ[R] (m → R)) := linear_map.to_matrix'.symm @[simp] lemma linear_map.to_matrix'_symm : (linear_map.to_matrix'.symm : matrix m n R ≃ₗ[R] _) = matrix.to_lin' := rfl @[simp] lemma matrix.to_lin'_symm : (matrix.to_lin'.symm : ((n → R) →ₗ[R] (m → R)) ≃ₗ[R] _) = linear_map.to_matrix' := rfl @[simp] lemma linear_map.to_matrix'_to_lin' (M : matrix m n R) : linear_map.to_matrix' (matrix.to_lin' M) = M := linear_map.to_matrix'.apply_symm_apply M @[simp] lemma matrix.to_lin'_to_matrix' (f : (n → R) →ₗ[R] (m → R)) : matrix.to_lin' (linear_map.to_matrix' f) = f := matrix.to_lin'.apply_symm_apply f @[simp] lemma linear_map.to_matrix'_apply (f : (n → R) →ₗ[R] (m → R)) (i j) : linear_map.to_matrix' f i j = f (λ j', if j' = j then 1 else 0) i := begin simp only [linear_map.to_matrix', linear_equiv.coe_mk], congr, ext j', split_ifs with h, { rw [h, std_basis_same] }, apply std_basis_ne _ _ _ _ h end @[simp] lemma matrix.to_lin'_apply (M : matrix m n R) (v : n → R) : matrix.to_lin' M v = M.mul_vec v := rfl @[simp] lemma matrix.to_lin'_one : matrix.to_lin' (1 : matrix n n R) = id := by { ext, simp [linear_map.one_apply, std_basis_apply] } @[simp] lemma linear_map.to_matrix'_id : (linear_map.to_matrix' (linear_map.id : (n → R) →ₗ[R] (n → R))) = 1 := by { ext, rw [matrix.one_apply, linear_map.to_matrix'_apply, id_apply] } @[simp] lemma matrix.to_lin'_mul [decidable_eq m] (M : matrix l m R) (N : matrix m n R) : matrix.to_lin' (M ⬝ N) = (matrix.to_lin' M).comp (matrix.to_lin' N) := by { ext, simp } /-- Shortcut lemma for `matrix.to_lin'_mul` and `linear_map.comp_apply` -/ lemma matrix.to_lin'_mul_apply [decidable_eq m] (M : matrix l m R) (N : matrix m n R) (x) : matrix.to_lin' (M ⬝ N) x = (matrix.to_lin' M (matrix.to_lin' N x)) := by rw [matrix.to_lin'_mul, linear_map.comp_apply] lemma linear_map.to_matrix'_comp [decidable_eq l] (f : (n → R) →ₗ[R] (m → R)) (g : (l → R) →ₗ[R] (n → R)) : (f.comp g).to_matrix' = f.to_matrix' ⬝ g.to_matrix' := suffices (f.comp g) = (f.to_matrix' ⬝ g.to_matrix').to_lin', by rw [this, linear_map.to_matrix'_to_lin'], by rw [matrix.to_lin'_mul, matrix.to_lin'_to_matrix', matrix.to_lin'_to_matrix'] lemma linear_map.to_matrix'_mul [decidable_eq m] (f g : (m → R) →ₗ[R] (m → R)) : (f * g).to_matrix' = f.to_matrix' ⬝ g.to_matrix' := linear_map.to_matrix'_comp f g /-- If `M` and `M'` are each other's inverse matrices, they provide an equivalence between `m → A` and `n → A` corresponding to `M.mul_vec` and `M'.mul_vec`. -/ @[simps] def matrix.to_lin'_of_inv [decidable_eq m] {M : matrix m n R} {M' : matrix n m R} (hMM' : M ⬝ M' = 1) (hM'M : M' ⬝ M = 1) : (m → R) ≃ₗ[R] (n → R) := { to_fun := matrix.to_lin' M', inv_fun := M.to_lin', left_inv := λ x, by rw [← matrix.to_lin'_mul_apply, hMM', matrix.to_lin'_one, id_apply], right_inv := λ x, by rw [← matrix.to_lin'_mul_apply, hM'M, matrix.to_lin'_one, id_apply], .. matrix.to_lin' M' } /-- Linear maps `(n → R) →ₗ[R] (n → R)` are algebra equivalent to `matrix n n R`. -/ def linear_map.to_matrix_alg_equiv' : ((n → R) →ₗ[R] (n → R)) ≃ₐ[R] matrix n n R := alg_equiv.of_linear_equiv linear_map.to_matrix' linear_map.to_matrix'_mul (by simp [module.algebra_map_End_eq_smul_id]) /-- A `matrix n n R` is algebra equivalent to a linear map `(n → R) →ₗ[R] (n → R)`. -/ def matrix.to_lin_alg_equiv' : matrix n n R ≃ₐ[R] ((n → R) →ₗ[R] (n → R)) := linear_map.to_matrix_alg_equiv'.symm @[simp] lemma linear_map.to_matrix_alg_equiv'_symm : (linear_map.to_matrix_alg_equiv'.symm : matrix n n R ≃ₐ[R] _) = matrix.to_lin_alg_equiv' := rfl @[simp] lemma matrix.to_lin_alg_equiv'_symm : (matrix.to_lin_alg_equiv'.symm : ((n → R) →ₗ[R] (n → R)) ≃ₐ[R] _) = linear_map.to_matrix_alg_equiv' := rfl @[simp] lemma linear_map.to_matrix_alg_equiv'_to_lin_alg_equiv' (M : matrix n n R) : linear_map.to_matrix_alg_equiv' (matrix.to_lin_alg_equiv' M) = M := linear_map.to_matrix_alg_equiv'.apply_symm_apply M @[simp] lemma matrix.to_lin_alg_equiv'_to_matrix_alg_equiv' (f : (n → R) →ₗ[R] (n → R)) : matrix.to_lin_alg_equiv' (linear_map.to_matrix_alg_equiv' f) = f := matrix.to_lin_alg_equiv'.apply_symm_apply f @[simp] lemma linear_map.to_matrix_alg_equiv'_apply (f : (n → R) →ₗ[R] (n → R)) (i j) : linear_map.to_matrix_alg_equiv' f i j = f (λ j', if j' = j then 1 else 0) i := by simp [linear_map.to_matrix_alg_equiv'] @[simp] lemma matrix.to_lin_alg_equiv'_apply (M : matrix n n R) (v : n → R) : matrix.to_lin_alg_equiv' M v = M.mul_vec v := rfl @[simp] lemma matrix.to_lin_alg_equiv'_one : matrix.to_lin_alg_equiv' (1 : matrix n n R) = id := by { ext, simp [matrix.one_apply, std_basis_apply] } @[simp] lemma linear_map.to_matrix_alg_equiv'_id : (linear_map.to_matrix_alg_equiv' (linear_map.id : (n → R) →ₗ[R] (n → R))) = 1 := by { ext, rw [matrix.one_apply, linear_map.to_matrix_alg_equiv'_apply, id_apply] } @[simp] lemma matrix.to_lin_alg_equiv'_mul (M N : matrix n n R) : matrix.to_lin_alg_equiv' (M ⬝ N) = (matrix.to_lin_alg_equiv' M).comp (matrix.to_lin_alg_equiv' N) := by { ext, simp } lemma linear_map.to_matrix_alg_equiv'_comp (f g : (n → R) →ₗ[R] (n → R)) : (f.comp g).to_matrix_alg_equiv' = f.to_matrix_alg_equiv' ⬝ g.to_matrix_alg_equiv' := suffices (f.comp g) = (f.to_matrix_alg_equiv' ⬝ g.to_matrix_alg_equiv').to_lin_alg_equiv', by rw [this, linear_map.to_matrix_alg_equiv'_to_lin_alg_equiv'], by rw [matrix.to_lin_alg_equiv'_mul, matrix.to_lin_alg_equiv'_to_matrix_alg_equiv', matrix.to_lin_alg_equiv'_to_matrix_alg_equiv'] lemma linear_map.to_matrix_alg_equiv'_mul (f g : (n → R) →ₗ[R] (n → R)) : (f * g).to_matrix_alg_equiv' = f.to_matrix_alg_equiv' ⬝ g.to_matrix_alg_equiv' := linear_map.to_matrix_alg_equiv'_comp f g lemma matrix.rank_vec_mul_vec {K m n : Type u} [field K] [fintype m] [fintype n] [decidable_eq n] (w : m → K) (v : n → K) : rank (vec_mul_vec w v).to_lin' ≤ 1 := begin rw [vec_mul_vec_eq, matrix.to_lin'_mul], refine le_trans (rank_comp_le1 _ _) _, refine le_trans (rank_le_domain _) _, rw [dim_fun', ← cardinal.lift_eq_nat_iff.mpr (cardinal.fintype_card unit), cardinal.mk_unit], exact le_of_eq (cardinal.lift_one) end end to_matrix' section to_matrix variables {R : Type*} [comm_ring R] variables {l m n : Type*} [fintype l] [fintype m] [fintype n] [decidable_eq n] variables {M₁ M₂ : Type*} [add_comm_group M₁] [add_comm_group M₂] [module R M₁] [module R M₂] variables (v₁ : basis n R M₁) (v₂ : basis m R M₂) /-- Given bases of two modules `M₁` and `M₂` over a commutative ring `R`, we get a linear equivalence between linear maps `M₁ →ₗ M₂` and matrices over `R` indexed by the bases. -/ def linear_map.to_matrix : (M₁ →ₗ[R] M₂) ≃ₗ[R] matrix m n R := linear_equiv.trans (linear_equiv.arrow_congr v₁.equiv_fun v₂.equiv_fun) linear_map.to_matrix' /-- Given bases of two modules `M₁` and `M₂` over a commutative ring `R`, we get a linear equivalence between matrices over `R` indexed by the bases and linear maps `M₁ →ₗ M₂`. -/ def matrix.to_lin : matrix m n R ≃ₗ[R] (M₁ →ₗ[R] M₂) := (linear_map.to_matrix v₁ v₂).symm @[simp] lemma linear_map.to_matrix_symm : (linear_map.to_matrix v₁ v₂).symm = matrix.to_lin v₁ v₂ := rfl @[simp] lemma matrix.to_lin_symm : (matrix.to_lin v₁ v₂).symm = linear_map.to_matrix v₁ v₂ := rfl @[simp] lemma matrix.to_lin_to_matrix (f : M₁ →ₗ[R] M₂) : matrix.to_lin v₁ v₂ (linear_map.to_matrix v₁ v₂ f) = f := by rw [← matrix.to_lin_symm, linear_equiv.apply_symm_apply] @[simp] lemma linear_map.to_matrix_to_lin (M : matrix m n R) : linear_map.to_matrix v₁ v₂ (matrix.to_lin v₁ v₂ M) = M := by rw [← matrix.to_lin_symm, linear_equiv.symm_apply_apply] lemma linear_map.to_matrix_apply (f : M₁ →ₗ[R] M₂) (i : m) (j : n) : linear_map.to_matrix v₁ v₂ f i j = v₂.repr (f (v₁ j)) i := begin rw [linear_map.to_matrix, linear_equiv.trans_apply, linear_map.to_matrix'_apply, linear_equiv.arrow_congr_apply, basis.equiv_fun_symm_apply, finset.sum_eq_single j, if_pos rfl, one_smul, basis.equiv_fun_apply], { intros j' _ hj', rw [if_neg hj', zero_smul] }, { intro hj, have := finset.mem_univ j, contradiction } end lemma linear_map.to_matrix_transpose_apply (f : M₁ →ₗ[R] M₂) (j : n) : (linear_map.to_matrix v₁ v₂ f)ᵀ j = v₂.repr (f (v₁ j)) := funext $ λ i, f.to_matrix_apply _ _ i j lemma linear_map.to_matrix_apply' (f : M₁ →ₗ[R] M₂) (i : m) (j : n) : linear_map.to_matrix v₁ v₂ f i j = v₂.repr (f (v₁ j)) i := linear_map.to_matrix_apply v₁ v₂ f i j lemma linear_map.to_matrix_transpose_apply' (f : M₁ →ₗ[R] M₂) (j : n) : (linear_map.to_matrix v₁ v₂ f)ᵀ j = v₂.repr (f (v₁ j)) := linear_map.to_matrix_transpose_apply v₁ v₂ f j lemma matrix.to_lin_apply (M : matrix m n R) (v : M₁) : matrix.to_lin v₁ v₂ M v = ∑ j, M.mul_vec (v₁.repr v) j • v₂ j := show v₂.equiv_fun.symm (matrix.to_lin' M (v₁.repr v)) = _, by rw [matrix.to_lin'_apply, v₂.equiv_fun_symm_apply] @[simp] lemma matrix.to_lin_self (M : matrix m n R) (i : n) : matrix.to_lin v₁ v₂ M (v₁ i) = ∑ j, M j i • v₂ j := begin rw [matrix.to_lin_apply, finset.sum_congr rfl (λ j hj, _)], rw [basis.repr_self, matrix.mul_vec, dot_product, finset.sum_eq_single i, finsupp.single_eq_same, mul_one], { intros i' _ i'_ne, rw [finsupp.single_eq_of_ne i'_ne.symm, mul_zero] }, { intros, have := finset.mem_univ i, contradiction }, end /-- This will be a special case of `linear_map.to_matrix_id_eq_basis_to_matrix`. -/ lemma linear_map.to_matrix_id : linear_map.to_matrix v₁ v₁ id = 1 := begin ext i j, simp [linear_map.to_matrix_apply, matrix.one_apply, finsupp.single, eq_comm] end lemma linear_map.to_matrix_one : linear_map.to_matrix v₁ v₁ 1 = 1 := linear_map.to_matrix_id v₁ @[simp] lemma matrix.to_lin_one : matrix.to_lin v₁ v₁ 1 = id := by rw [← linear_map.to_matrix_id v₁, matrix.to_lin_to_matrix] theorem linear_map.to_matrix_reindex_range [decidable_eq M₁] [decidable_eq M₂] (f : M₁ →ₗ[R] M₂) (k : m) (i : n) : linear_map.to_matrix v₁.reindex_range v₂.reindex_range f ⟨v₂ k, mem_range_self k⟩ ⟨v₁ i, mem_range_self i⟩ = linear_map.to_matrix v₁ v₂ f k i := by simp_rw [linear_map.to_matrix_apply, basis.reindex_range_self, basis.reindex_range_repr] variables {M₃ : Type*} [add_comm_group M₃] [module R M₃] (v₃ : basis l R M₃) lemma linear_map.to_matrix_comp [decidable_eq m] (f : M₂ →ₗ[R] M₃) (g : M₁ →ₗ[R] M₂) : linear_map.to_matrix v₁ v₃ (f.comp g) = linear_map.to_matrix v₂ v₃ f ⬝ linear_map.to_matrix v₁ v₂ g := by simp_rw [linear_map.to_matrix, linear_equiv.trans_apply, linear_equiv.arrow_congr_comp _ v₂.equiv_fun, linear_map.to_matrix'_comp] lemma linear_map.to_matrix_mul (f g : M₁ →ₗ[R] M₁) : linear_map.to_matrix v₁ v₁ (f * g) = linear_map.to_matrix v₁ v₁ f ⬝ linear_map.to_matrix v₁ v₁ g := by { rw [show (@has_mul.mul (M₁ →ₗ[R] M₁) _) = linear_map.comp, from rfl, linear_map.to_matrix_comp v₁ v₁ v₁ f g] } lemma linear_map.to_matrix_mul_vec_repr (f : M₁ →ₗ[R] M₂) (x : M₁) : (linear_map.to_matrix v₁ v₂ f).mul_vec (v₁.repr x) = v₂.repr (f x) := by { ext i, rw [← matrix.to_lin'_apply, linear_map.to_matrix, linear_equiv.trans_apply, matrix.to_lin'_to_matrix', linear_equiv.arrow_congr_apply, v₂.equiv_fun_apply], congr, exact v₁.equiv_fun.symm_apply_apply x } lemma matrix.to_lin_mul [decidable_eq m] (A : matrix l m R) (B : matrix m n R) : matrix.to_lin v₁ v₃ (A ⬝ B) = (matrix.to_lin v₂ v₃ A).comp (matrix.to_lin v₁ v₂ B) := begin apply (linear_map.to_matrix v₁ v₃).injective, haveI : decidable_eq l := λ _ _, classical.prop_decidable _, rw linear_map.to_matrix_comp v₁ v₂ v₃, repeat { rw linear_map.to_matrix_to_lin }, end /-- Shortcut lemma for `matrix.to_lin_mul` and `linear_map.comp_apply`. -/ lemma matrix.to_lin_mul_apply [decidable_eq m] (A : matrix l m R) (B : matrix m n R) (x) : matrix.to_lin v₁ v₃ (A ⬝ B) x = (matrix.to_lin v₂ v₃ A) (matrix.to_lin v₁ v₂ B x) := by rw [matrix.to_lin_mul v₁ v₂, linear_map.comp_apply] /-- If `M` and `M` are each other's inverse matrices, `matrix.to_lin M` and `matrix.to_lin M'` form a linear equivalence. -/ @[simps] def matrix.to_lin_of_inv [decidable_eq m] {M : matrix m n R} {M' : matrix n m R} (hMM' : M ⬝ M' = 1) (hM'M : M' ⬝ M = 1) : M₁ ≃ₗ[R] M₂ := { to_fun := matrix.to_lin v₁ v₂ M, inv_fun := matrix.to_lin v₂ v₁ M', left_inv := λ x, by rw [← matrix.to_lin_mul_apply, hM'M, matrix.to_lin_one, id_apply], right_inv := λ x, by rw [← matrix.to_lin_mul_apply, hMM', matrix.to_lin_one, id_apply], .. matrix.to_lin v₁ v₂ M } /-- Given a basis of a module `M₁` over a commutative ring `R`, we get an algebra equivalence between linear maps `M₁ →ₗ M₁` and square matrices over `R` indexed by the basis. -/ def linear_map.to_matrix_alg_equiv : (M₁ →ₗ[R] M₁) ≃ₐ[R] matrix n n R := alg_equiv.of_linear_equiv (linear_map.to_matrix v₁ v₁) (linear_map.to_matrix_mul v₁) (by simp [module.algebra_map_End_eq_smul_id, linear_map.to_matrix_id]) /-- Given a basis of a module `M₁` over a commutative ring `R`, we get an algebra equivalence between square matrices over `R` indexed by the basis and linear maps `M₁ →ₗ M₁`. -/ def matrix.to_lin_alg_equiv : matrix n n R ≃ₐ[R] (M₁ →ₗ[R] M₁) := (linear_map.to_matrix_alg_equiv v₁).symm @[simp] lemma linear_map.to_matrix_alg_equiv_symm : (linear_map.to_matrix_alg_equiv v₁).symm = matrix.to_lin_alg_equiv v₁ := rfl @[simp] lemma matrix.to_lin_alg_equiv_symm : (matrix.to_lin_alg_equiv v₁).symm = linear_map.to_matrix_alg_equiv v₁ := rfl @[simp] lemma matrix.to_lin_alg_equiv_to_matrix_alg_equiv (f : M₁ →ₗ[R] M₁) : matrix.to_lin_alg_equiv v₁ (linear_map.to_matrix_alg_equiv v₁ f) = f := by rw [← matrix.to_lin_alg_equiv_symm, alg_equiv.apply_symm_apply] @[simp] lemma linear_map.to_matrix_alg_equiv_to_lin_alg_equiv (M : matrix n n R) : linear_map.to_matrix_alg_equiv v₁ (matrix.to_lin_alg_equiv v₁ M) = M := by rw [← matrix.to_lin_alg_equiv_symm, alg_equiv.symm_apply_apply] lemma linear_map.to_matrix_alg_equiv_apply (f : M₁ →ₗ[R] M₁) (i j : n) : linear_map.to_matrix_alg_equiv v₁ f i j = v₁.repr (f (v₁ j)) i := by simp [linear_map.to_matrix_alg_equiv, linear_map.to_matrix_apply] lemma linear_map.to_matrix_alg_equiv_transpose_apply (f : M₁ →ₗ[R] M₁) (j : n) : (linear_map.to_matrix_alg_equiv v₁ f)ᵀ j = v₁.repr (f (v₁ j)) := funext $ λ i, f.to_matrix_apply _ _ i j lemma linear_map.to_matrix_alg_equiv_apply' (f : M₁ →ₗ[R] M₁) (i j : n) : linear_map.to_matrix_alg_equiv v₁ f i j = v₁.repr (f (v₁ j)) i := linear_map.to_matrix_alg_equiv_apply v₁ f i j lemma linear_map.to_matrix_alg_equiv_transpose_apply' (f : M₁ →ₗ[R] M₁) (j : n) : (linear_map.to_matrix_alg_equiv v₁ f)ᵀ j = v₁.repr (f (v₁ j)) := linear_map.to_matrix_alg_equiv_transpose_apply v₁ f j lemma matrix.to_lin_alg_equiv_apply (M : matrix n n R) (v : M₁) : matrix.to_lin_alg_equiv v₁ M v = ∑ j, M.mul_vec (v₁.repr v) j • v₁ j := show v₁.equiv_fun.symm (matrix.to_lin_alg_equiv' M (v₁.repr v)) = _, by rw [matrix.to_lin_alg_equiv'_apply, v₁.equiv_fun_symm_apply] @[simp] lemma matrix.to_lin_alg_equiv_self (M : matrix n n R) (i : n) : matrix.to_lin_alg_equiv v₁ M (v₁ i) = ∑ j, M j i • v₁ j := matrix.to_lin_self _ _ _ _ lemma linear_map.to_matrix_alg_equiv_id : linear_map.to_matrix_alg_equiv v₁ id = 1 := by simp_rw [linear_map.to_matrix_alg_equiv, alg_equiv.of_linear_equiv_apply, linear_map.to_matrix_id] @[simp] lemma matrix.to_lin_alg_equiv_one : matrix.to_lin_alg_equiv v₁ 1 = id := by rw [← linear_map.to_matrix_alg_equiv_id v₁, matrix.to_lin_alg_equiv_to_matrix_alg_equiv] theorem linear_map.to_matrix_alg_equiv_reindex_range [decidable_eq M₁] (f : M₁ →ₗ[R] M₁) (k i : n) : linear_map.to_matrix_alg_equiv v₁.reindex_range f ⟨v₁ k, mem_range_self k⟩ ⟨v₁ i, mem_range_self i⟩ = linear_map.to_matrix_alg_equiv v₁ f k i := by simp_rw [linear_map.to_matrix_alg_equiv_apply, basis.reindex_range_self, basis.reindex_range_repr] lemma linear_map.to_matrix_alg_equiv_comp (f g : M₁ →ₗ[R] M₁) : linear_map.to_matrix_alg_equiv v₁ (f.comp g) = linear_map.to_matrix_alg_equiv v₁ f ⬝ linear_map.to_matrix_alg_equiv v₁ g := by simp [linear_map.to_matrix_alg_equiv, linear_map.to_matrix_comp v₁ v₁ v₁ f g] lemma linear_map.to_matrix_alg_equiv_mul (f g : M₁ →ₗ[R] M₁) : linear_map.to_matrix_alg_equiv v₁ (f * g) = linear_map.to_matrix_alg_equiv v₁ f ⬝ linear_map.to_matrix_alg_equiv v₁ g := by { rw [show (@has_mul.mul (M₁ →ₗ[R] M₁) _) = linear_map.comp, from rfl, linear_map.to_matrix_alg_equiv_comp v₁ f g] } lemma matrix.to_lin_alg_equiv_mul (A B : matrix n n R) : matrix.to_lin_alg_equiv v₁ (A ⬝ B) = (matrix.to_lin_alg_equiv v₁ A).comp (matrix.to_lin_alg_equiv v₁ B) := by convert matrix.to_lin_mul v₁ v₁ v₁ A B end to_matrix namespace algebra section lmul variables {R S T : Type*} [comm_ring R] [comm_ring S] [comm_ring T] variables [algebra R S] [algebra S T] [algebra R T] [is_scalar_tower R S T] variables {m n : Type*} [fintype m] [decidable_eq m] [fintype n] [decidable_eq n] variables (b : basis m R S) (c : basis n S T) open algebra lemma to_matrix_lmul' (x : S) (i j) : linear_map.to_matrix b b (lmul R S x) i j = b.repr (x * b j) i := by rw [linear_map.to_matrix_apply', lmul_apply] @[simp] lemma to_matrix_lsmul (x : R) (i j) : linear_map.to_matrix b b (algebra.lsmul R S x) i j = if i = j then x else 0 := by { rw [linear_map.to_matrix_apply', algebra.lsmul_coe, linear_equiv.map_smul, finsupp.smul_apply, b.repr_self_apply, smul_eq_mul, mul_boole], congr' 1; simp only [eq_comm] } /-- `left_mul_matrix b x` is the matrix corresponding to the linear map `λ y, x * y`. `left_mul_matrix_eq_repr_mul` gives a formula for the entries of `left_mul_matrix`. This definition is useful for doing (more) explicit computations with `algebra.lmul`, such as the trace form or norm map for algebras. -/ noncomputable def left_mul_matrix : S →ₐ[R] matrix m m R := { to_fun := λ x, linear_map.to_matrix b b (algebra.lmul R S x), map_zero' := by rw [alg_hom.map_zero, linear_equiv.map_zero], map_one' := by rw [alg_hom.map_one, linear_map.to_matrix_one], map_add' := λ x y, by rw [alg_hom.map_add, linear_equiv.map_add], map_mul' := λ x y, by rw [alg_hom.map_mul, linear_map.to_matrix_mul, matrix.mul_eq_mul], commutes' := λ r, by { ext, rw [lmul_algebra_map, to_matrix_lsmul, algebra_map_matrix_apply, id.map_eq_self] } } lemma left_mul_matrix_apply (x : S) : left_mul_matrix b x = linear_map.to_matrix b b (lmul R S x) := rfl lemma left_mul_matrix_eq_repr_mul (x : S) (i j) : left_mul_matrix b x i j = b.repr (x * b j) i := -- This is defeq to just `to_matrix_lmul' b x i j`, -- but the unfolding goes a lot faster with this explicit `rw`. by rw [left_mul_matrix_apply, to_matrix_lmul' b x i j] lemma left_mul_matrix_mul_vec_repr (x y : S) : (left_mul_matrix b x).mul_vec (b.repr y) = b.repr (x * y) := linear_map.to_matrix_mul_vec_repr b b (algebra.lmul R S x) y @[simp] lemma to_matrix_lmul_eq (x : S) : linear_map.to_matrix b b (lmul R S x) = left_mul_matrix b x := rfl lemma left_mul_matrix_injective : function.injective (left_mul_matrix b) := λ x x' h, calc x = algebra.lmul R S x 1 : (mul_one x).symm ... = algebra.lmul R S x' 1 : by rw (linear_map.to_matrix b b).injective h ... = x' : mul_one x' lemma smul_left_mul_matrix (x) (ik jk) : left_mul_matrix (b.smul c) x ik jk = left_mul_matrix b (left_mul_matrix c x ik.2 jk.2) ik.1 jk.1 := by simp only [left_mul_matrix_apply, linear_map.to_matrix_apply, mul_comm, basis.smul_apply, basis.smul_repr, finsupp.smul_apply, algebra.lmul_apply, id.smul_eq_mul, linear_equiv.map_smul, mul_smul_comm] lemma smul_left_mul_matrix_algebra_map (x : S) : left_mul_matrix (b.smul c) (algebra_map _ _ x) = block_diagonal (λ k, left_mul_matrix b x) := begin ext ⟨i, k⟩ ⟨j, k'⟩, rw [smul_left_mul_matrix, alg_hom.commutes, block_diagonal_apply, algebra_map_matrix_apply], split_ifs with h; simp [h], end lemma smul_left_mul_matrix_algebra_map_eq (x : S) (i j k) : left_mul_matrix (b.smul c) (algebra_map _ _ x) (i, k) (j, k) = left_mul_matrix b x i j := by rw [smul_left_mul_matrix_algebra_map, block_diagonal_apply_eq] lemma smul_left_mul_matrix_algebra_map_ne (x : S) (i j) {k k'} (h : k ≠ k') : left_mul_matrix (b.smul c) (algebra_map _ _ x) (i, k) (j, k') = 0 := by rw [smul_left_mul_matrix_algebra_map, block_diagonal_apply_ne _ _ _ h] end lmul end algebra namespace linear_map section finite_dimensional open_locale classical variables {K : Type*} [field K] variables {V : Type*} [add_comm_group V] [module K V] [finite_dimensional K V] variables {W : Type*} [add_comm_group W] [module K W] [finite_dimensional K W] instance : finite_dimensional K (V →ₗ[K] W) := linear_equiv.finite_dimensional (linear_map.to_matrix (basis.of_vector_space K V) (basis.of_vector_space K W)).symm /-- The dimension of the space of linear transformations is the product of the dimensions of the domain and codomain. -/ @[simp] lemma finrank_linear_map : finite_dimensional.finrank K (V →ₗ[K] W) = (finite_dimensional.finrank K V) * (finite_dimensional.finrank K W) := begin let hbV := basis.of_vector_space K V, let hbW := basis.of_vector_space K W, rw [linear_equiv.finrank_eq (linear_map.to_matrix hbV hbW), matrix.finrank_matrix, finite_dimensional.finrank_eq_card_basis hbV, finite_dimensional.finrank_eq_card_basis hbW, mul_comm], end end finite_dimensional end linear_map section variables {R : Type v} [comm_ring R] {n : Type*} [fintype n] [decidable_eq n] variables {M M₁ M₂ : Type*} [add_comm_group M] [module R M] variables [add_comm_group M₁] [module R M₁] [add_comm_group M₂] [module R M₂] /-- The natural equivalence between linear endomorphisms of finite free modules and square matrices is compatible with the algebra structures. -/ def alg_equiv_matrix' : module.End R (n → R) ≃ₐ[R] matrix n n R := { map_mul' := linear_map.to_matrix'_comp, map_add' := linear_map.to_matrix'.map_add, commutes' := λ r, by { change (r • (linear_map.id : module.End R _)).to_matrix' = r • 1, rw ←linear_map.to_matrix'_id, refl, }, ..linear_map.to_matrix' } /-- A linear equivalence of two modules induces an equivalence of algebras of their endomorphisms. -/ def linear_equiv.alg_conj (e : M₁ ≃ₗ[R] M₂) : module.End R M₁ ≃ₐ[R] module.End R M₂ := { map_mul' := λ f g, by apply e.arrow_congr_comp, map_add' := e.conj.map_add, commutes' := λ r, by { change e.conj (r • linear_map.id) = r • linear_map.id, rw [linear_equiv.map_smul, linear_equiv.conj_id], }, ..e.conj } /-- A basis of a module induces an equivalence of algebras from the endomorphisms of the module to square matrices. -/ def alg_equiv_matrix (h : basis n R M) : module.End R M ≃ₐ[R] matrix n n R := h.equiv_fun.alg_conj.trans alg_equiv_matrix' end
afcfbff63920b85949bc49edcb7539c9b16ee719
5d166a16ae129621cb54ca9dde86c275d7d2b483
/library/init/native/format.lean
b4a13ce0d454fbd37f078e1006c9b49020e83eae
[ "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
6,166
lean
/- Copyright (c) 2016 Jared Roesch. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jared Roesch -/ prelude import init.meta.name import init.meta.format import init.function import init.native.ir def intersperse {A : Type} (elem : A) : list A → list A | [] := [] | (x :: []) := [x] | (x :: xs) := x :: elem :: intersperse xs meta def format_concat : list format → format | [] := format.nil | (f :: fs) := f ++ format_concat fs meta def comma_sep (items : list format) : format := format_concat (intersperse (format.of_string "," ++ format.space) items) namespace format_cpp meta def mangle_name (n : name) : format := to_fmt $ name.to_string_with_sep "_" n private meta def mk_constructor_args : list name → list format | [] := [] | (n :: ns) := mangle_name n :: mk_constructor_args ns private meta def mk_constructor (arity : nat) (fs : list name) : format := "lean::mk_vm_constructor(" ++ to_fmt arity ++ "," ++ (format.bracket "{" "}" (comma_sep $ mk_constructor_args fs)) ++ ")" private meta def mk_call (symbol : name) (args : list name) : format := mangle_name symbol ++ (format.bracket "(" ")" (comma_sep $ list.map mangle_name args)) meta def literal : ir.literal → format | (ir.literal.nat n) := to_fmt "lean::mk_vm_nat(" ++ to_fmt n ++ ")" meta def format_local (n : name) : format := to_fmt (name.to_string_with_sep "_" n) meta def string_lit (s : string) : format := format.bracket "\"" "\"" (to_fmt s) meta def block (body : format) : format := format.bracket "{" "}" (format.nest 4 (format.line ++ body) ++ format.line) meta def expr' (action : ir.stmt → format) : ir.expr → format | (ir.expr.call f xs) := mk_call f xs | (ir.expr.mk_object n fs) := if n = 0 -- Over time I should remove these special case functions, -- and just use the def language of the IR. then to_fmt "lean::mk_vm_simple(0)" else mk_constructor n fs | (ir.expr.global n) := mk_call n [] | (ir.expr.locl n) := mangle_name n | (ir.expr.lit l) := literal l | (ir.expr.block s) := block (action s) -- project really should only work for like fields/primtive arrays, this is a temporary hack | (ir.expr.project obj n) := "cfield(" ++ (mangle_name obj) ++ ", " ++ (to_fmt n) ++ ")" | (ir.expr.panic err_msg) := to_fmt "throw std::runtime_error(" ++ string_lit err_msg ++ ");" | (ir.expr.mk_native_closure n args) := "lean::mk_native_closure(*g_env, lean::name({\"" ++ name.to_string_with_sep "\", \"" n ++ "\"})" ++ "," ++ format.bracket "{" "}" (comma_sep (list.map format_local args)) ++ ")" | (ir.expr.invoke n args) := "lean::invoke(" ++ name.to_string_with_sep "_" n ++ ", " ++ (comma_sep (list.map format_local args)) ++ ")" | (ir.expr.uninitialized) := ";" | (ir.expr.assign n val) := mangle_name n ++ " = " ++ expr' val | (ir.expr.constructor _ _) := "NYI" | (ir.expr.address_of e) := "& " ++ mangle_name e ++ ";" | (ir.expr.equals e1 e2) := expr' e1 ++ " == " ++ expr' e2 | (ir.expr.raw_int n) := to_string n | (ir.expr.sub e1 e2) := expr' e1 ++ " - " ++ expr' e2 meta def default_case (body : format) : format := to_fmt "default:" ++ block body meta def case (action : ir.stmt → format) : (nat × ir.stmt) → format | (n, s) := "case " ++ to_fmt n ++ ":" ++ block (action s ++ format.line ++ "break;" ++ format.line) meta def cases (action : ir.stmt → format) : list (nat × ir.stmt) → format | [] := format.nil | (c :: cs) := case action c ++ cases cs meta def ty : ir.ty → format | ir.ty.object := format.of_string "lean::vm_obj " | (ir.ty.ref T) := ty T ++ format.of_string " const & " | (ir.ty.mut_ref T) := ty T ++ format.of_string " &" | (ir.ty.tag _ _) := format.of_string "an_error" | (ir.ty.int) := "int " | (ir.ty.object_buffer) := "lean::buffer<lean::vm_obj> " | (ir.ty.name n) := to_fmt n ++ format.space meta def parens (inner : format) : format := format.bracket "(" ")" inner meta def stmt : ir.stmt → format | (ir.stmt.e e) := expr' stmt e ++ ";" | (ir.stmt.return e) := format.of_string "return" ++ format.space ++ expr' stmt e ++ format.of_string ";" | (ir.stmt.letb n t ir.expr.uninitialized nop) := ty t ++ (mangle_name n) ++ to_fmt ";" ++ format.line -- type checking should establish that these two types are equal | (ir.stmt.letb n t (ir.expr.constructor ty_name args) nop) := -- temporary hack, need to think about how to model this better if ty_name = "lean::name" then let ctor_args := comma_sep (list.map (string_lit ∘ to_string) args) in ty t ++ (mangle_name n) ++ " = lean::name({" ++ ctor_args ++ "})" ++ to_fmt ";" ++ format.line else let ctor_args := parens $ comma_sep (list.map mangle_name args) in ty t ++ (mangle_name n) ++ ctor_args ++ to_fmt ";" ++ format.line | (ir.stmt.letb n t v body) := ty t ++ (mangle_name n) ++ (to_fmt " = ") ++ (expr' stmt v) ++ to_fmt ";" ++ format.line ++ stmt body | (ir.stmt.switch scrut cs default) := (to_fmt "switch (") ++ (mangle_name scrut) ++ (to_fmt ")") ++ (block (format.line ++ cases stmt cs ++ default_case (stmt default))) | ir.stmt.nop := format.of_string ";" | (ir.stmt.ite cond tbranch fbranch) := "if (" ++ mangle_name cond ++ ") {" ++ format.line ++ stmt tbranch ++ format.line ++ "} else {" ++ format.line ++ stmt fbranch ++ format.line ++ "}" ++ format.line | (ir.stmt.seq cs) := format_concat (list.map (fun c, stmt c ++ format.line) cs) meta def expr := expr' stmt meta def format_param (param : name × ir.ty) := ty (prod.snd param) ++ format.space ++ to_fmt (name.to_string_with_sep "_" (mk_str_name "_$local$_" (name.to_string_with_sep "_" (prod.fst param)))) meta def format_argument_list (tys : list (name × ir.ty)) : format := format.bracket "(" ")" (comma_sep (list.map format_param tys)) -- meta_def format_prototypes () meta def defn (d : ir.defn) : format := match d with | ir.defn.mk n arg_tys ret_ty body := let body := stmt body in (ty ret_ty) ++ format.space ++ (mangle_name n) ++ (format_argument_list arg_tys) ++ format.space ++ (format.bracket "{" "}" $ format.nest 4 (format.line ++ body) ++ format.line) end end format_cpp
f8a4ca65b6a00a5bd98be657ef310834fd86c1d2
a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91
/hott/types/lift.hlean
86f90da02b47247e28fffe0d421ef3b459b18f75
[ "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
5,109
hlean
/- Copyright (c) 2015 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Floris van Doorn Theorems about lift -/ import ..function open eq equiv is_equiv is_trunc pointed namespace lift universe variables u v variables {A : Type.{u}} (z z' : lift.{u v} A) protected definition eta : up (down z) = z := by induction z; reflexivity protected definition code [unfold 2 3] : lift A → lift A → Type | code (up a) (up a') := a = a' protected definition decode [unfold 2 3] : Π(z z' : lift A), lift.code z z' → z = z' | decode (up a) (up a') := λc, ap up c variables {z z'} protected definition encode [unfold 3 4 5] (p : z = z') : lift.code z z' := by induction p; induction z; esimp variables (z z') definition lift_eq_equiv : (z = z') ≃ lift.code z z' := equiv.MK lift.encode !lift.decode abstract begin intro c, induction z with a, induction z' with a', esimp at *, induction c, reflexivity end end abstract begin intro p, induction p, induction z, reflexivity end end section variables {a a' : A} definition eq_of_up_eq_up [unfold 4] (p : up a = up a') : a = a' := lift.encode p definition lift_transport {P : A → Type} (p : a = a') (z : lift (P a)) : p ▸ z = up (p ▸ down z) := by induction p; induction z; reflexivity end variables {A' : Type} (f : A → A') (g : lift A → lift A') definition lift_functor [unfold 4] : lift A → lift A' | lift_functor (up a) := up (f a) definition is_equiv_lift_functor [constructor] [Hf : is_equiv f] : is_equiv (lift_functor f) := adjointify (lift_functor f) (lift_functor f⁻¹) abstract begin intro z', induction z' with a', esimp, exact ap up !right_inv end end abstract begin intro z, induction z with a, esimp, exact ap up !left_inv end end definition lift_equiv_lift_of_is_equiv [constructor] [Hf : is_equiv f] : lift A ≃ lift A' := equiv.mk _ (is_equiv_lift_functor f) definition lift_equiv_lift [constructor] (f : A ≃ A') : lift A ≃ lift A' := equiv.mk _ (is_equiv_lift_functor f) definition lift_equiv_lift_refl (A : Type) : lift_equiv_lift (erfl : A ≃ A) = erfl := by apply equiv_eq'; intro z; induction z with a; reflexivity definition lift_inv_functor [unfold_full] (a : A) : A' := down (g (up a)) definition is_equiv_lift_inv_functor [constructor] [Hf : is_equiv g] : is_equiv (lift_inv_functor g) := adjointify (lift_inv_functor g) (lift_inv_functor g⁻¹) abstract begin intro z', rewrite [▸*,lift.eta,right_inv g], end end abstract begin intro z', rewrite [▸*,lift.eta,left_inv g], end end definition equiv_of_lift_equiv_lift [constructor] (g : lift A ≃ lift A') : A ≃ A' := equiv.mk _ (is_equiv_lift_inv_functor g) definition lift_functor_left_inv : lift_inv_functor (lift_functor f) = f := eq_of_homotopy (λa, idp) definition lift_functor_right_inv : lift_functor (lift_inv_functor g) = g := begin apply eq_of_homotopy, intro z, induction z with a, esimp, apply lift.eta end variables (A A') definition is_equiv_lift_functor_fn [constructor] : is_equiv (lift_functor : (A → A') → (lift A → lift A')) := adjointify lift_functor lift_inv_functor lift_functor_right_inv lift_functor_left_inv definition lift_imp_lift_equiv [constructor] : (lift A → lift A') ≃ (A → A') := (equiv.mk _ (is_equiv_lift_functor_fn A A'))⁻¹ᵉ -- can we deduce this from lift_imp_lift_equiv? definition lift_equiv_lift_equiv [constructor] : (lift A ≃ lift A') ≃ (A ≃ A') := equiv.MK equiv_of_lift_equiv_lift lift_equiv_lift abstract begin intro f, apply equiv_eq, reflexivity end end abstract begin intro g, apply equiv_eq, esimp, apply eq_of_homotopy, intro z, induction z with a, esimp, apply lift.eta end end definition lift_eq_lift_equiv.{u1 u2} (A A' : Type.{u1}) : (lift.{u1 u2} A = lift.{u1 u2} A') ≃ (A = A') := !eq_equiv_equiv ⬝e !lift_equiv_lift_equiv ⬝e !eq_equiv_equiv⁻¹ᵉ definition is_embedding_lift [instance] : is_embedding lift := begin intro A A', fapply is_equiv.homotopy_closed, exact to_inv !lift_eq_lift_equiv, exact _, { intro p, induction p, esimp [lift_eq_lift_equiv,equiv.trans,equiv.symm,eq_equiv_equiv], rewrite [equiv_of_eq_refl,lift_equiv_lift_refl], apply ua_refl} end definition plift [constructor] (A : pType.{u}) : pType.{max u v} := pType.mk (lift A) (up pt) definition plift_functor [constructor] {A B : Type*} (f : A →* B) : plift A →* plift B := pmap.mk (lift_functor f) (ap up (respect_pt f)) -- is_trunc_lift is defined in init.trunc end lift
359ec2a5f95bfeff761b08af2f04f4e7add15220
cc62cd292c1acc80a10b1c645915b70d2cdee661
/src/category_theory/yoneda_terse.lean
cb81df53da057e2b02456085878f0d782ae5b87b
[]
no_license
RitaAhmadi/lean-category-theory
4afb881c4b387ee2c8ce706c454fbf9db8897a29
a27b4ae5eac978e9188d2e867c3d11d9a5b87a9e
refs/heads/master
1,651,786,183,402
1,565,604,314,000
1,565,604,314,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,308
lean
import category_theory.follow_your_nose universes u₁ v₁ open category_theory open opposite namespace terse variables (C : Type u₁) [𝒞 : category.{v₁+1} C] include 𝒞 def yoneda : C ⥤ ((Cᵒᵖ) ⥤ Type v₁) := ƛ X, ƛ Y, (unop Y) ⟶ X. def yoneda_evaluation : ((Cᵒᵖ) × ((Cᵒᵖ) ⥤ (Type v₁))) ⥤ (Type (max u₁ v₁)) := (evaluation_uncurried (Cᵒᵖ) (Type v₁)) ⋙ ulift_functor.{u₁} @[simp] lemma yoneda_evaluation_map_down (P Q : (Cᵒᵖ) × (Cᵒᵖ ⥤ Type v₁)) (α : P ⟶ Q) (x : (yoneda_evaluation C).obj P) : ((yoneda_evaluation C).map α x).down = (α.2).app (Q.1) ((P.2).map (α.1) (x.down)) := rfl def yoneda_pairing : ((Cᵒᵖ) × ((Cᵒᵖ) ⥤ (Type v₁))) ⥤ (Type (max u₁ v₁)) := (functor.prod ((yoneda C).op) (functor.id ((Cᵒᵖ) ⥤ (Type v₁)))) ⋙ (functor.hom ((Cᵒᵖ) ⥤ (Type v₁))) @[simp] lemma yoneda_pairing_map (P Q : (Cᵒᵖ) × (Cᵒᵖ ⥤ Type v₁)) (α : P ⟶ Q) (β : (yoneda_pairing C).obj P) : (yoneda_pairing C).map α β = (yoneda C).map (α.1.unop) ≫ β ≫ α.2 := rfl def yoneda_lemma : (yoneda_pairing C) ≅ (yoneda_evaluation C) := { hom := { app := λ F x, ulift.up ((x.app F.1) (𝟙 (unop F.1))) }, inv := { app := λ F x, { app := λ X a, (F.2.map a.op) x.down } } }. end terse
37e4c03e1313ce7ec893231e9375281ad3d49a27
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/category_theory/connected_components.lean
718dd4d8f9508f300c386952c99718f29615cd32
[ "Apache-2.0" ]
permissive
alreadydone/mathlib
dc0be621c6c8208c581f5170a8216c5ba6721927
c982179ec21091d3e102d8a5d9f5fe06c8fafb73
refs/heads/master
1,685,523,275,196
1,670,184,141,000
1,670,184,141,000
287,574,545
0
0
Apache-2.0
1,670,290,714,000
1,597,421,623,000
Lean
UTF-8
Lean
false
false
5,792
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 data.list.chain import category_theory.is_connected import category_theory.sigma.basic import category_theory.full_subcategory /-! # Connected components of a category Defines a type `connected_components J` indexing the connected components of a category, and the full subcategories giving each connected component: `component j : Type u₁`. We show that each `component j` is in fact connected. We show every category can be expressed as a disjoint union of its connected components, in particular `decomposed J` is the category (definitionally) given by the sigma-type of the connected components of `J`, and it is shown that this is equivalent to `J`. -/ universes v₁ v₂ v₃ u₁ u₂ noncomputable theory open category_theory.category namespace category_theory attribute [instance, priority 100] is_connected.is_nonempty variables {J : Type u₁} [category.{v₁} J] variables {C : Type u₂} [category.{u₁} C] /-- This type indexes the connected components of the category `J`. -/ def connected_components (J : Type u₁) [category.{v₁} J] : Type u₁ := quotient (zigzag.setoid J) instance [inhabited J] : inhabited (connected_components J) := ⟨quotient.mk' default⟩ /-- Given an index for a connected component, produce the actual component as a full subcategory. -/ @[derive category] def component (j : connected_components J) : Type u₁ := full_subcategory (λ k, quotient.mk' k = j) /-- The inclusion functor from a connected component to the whole category. -/ @[derive [full, faithful], simps {rhs_md := semireducible}] def component.ι (j) : component j ⥤ J := full_subcategory_inclusion _ /-- Each connected component of the category is nonempty. -/ instance (j : connected_components J) : nonempty (component j) := begin apply quotient.induction_on' j, intro k, refine ⟨⟨k, rfl⟩⟩, end instance (j : connected_components J) : inhabited (component j) := classical.inhabited_of_nonempty' /-- Each connected component of the category is connected. -/ instance (j : connected_components J) : is_connected (component j) := begin -- Show it's connected by constructing a zigzag (in `component j`) between any two objects apply is_connected_of_zigzag, rintro ⟨j₁, hj₁⟩ ⟨j₂, rfl⟩, -- We know that the underlying objects j₁ j₂ have some zigzag between them in `J` have h₁₂ : zigzag j₁ j₂ := quotient.exact' hj₁, -- Get an explicit zigzag as a list rcases list.exists_chain_of_relation_refl_trans_gen h₁₂ with ⟨l, hl₁, hl₂⟩, -- Everything which has a zigzag to j₂ can be lifted to the same component as `j₂`. let f : Π x, zigzag x j₂ → component (quotient.mk' j₂) := λ x h, ⟨x, quotient.sound' h⟩, -- Everything in our chosen zigzag from `j₁` to `j₂` has a zigzag to `j₂`. have hf : ∀ (a : J), a ∈ l → zigzag a j₂, { intros i hi, apply list.chain.induction (λ t, zigzag t j₂) _ hl₁ hl₂ _ _ _ (or.inr hi), { intros j k, apply relation.refl_trans_gen.head }, { apply relation.refl_trans_gen.refl } }, -- Now lift the zigzag from `j₁` to `j₂` in `J` to the same thing in `component j`. refine ⟨l.pmap f hf, _, _⟩, { refine @@list.chain_pmap_of_chain _ _ _ f (λ x y _ _ h, _) hl₁ h₁₂ _, exact zag_of_zag_obj (component.ι _) h }, { erw list.last_pmap _ f (j₁ :: l) (by simpa [h₁₂] using hf) (list.cons_ne_nil _ _), exact full_subcategory.ext _ _ hl₂ }, end /-- The disjoint union of `J`s connected components, written explicitly as a sigma-type with the category structure. This category is equivalent to `J`. -/ abbreviation decomposed (J : Type u₁) [category.{v₁} J] := Σ (j : connected_components J), component j /-- The inclusion of each component into the decomposed category. This is just `sigma.incl` but having this abbreviation helps guide typeclass search to get the right category instance on `decomposed J`. -/ -- This name may cause clashes further down the road, and so might need to be changed. abbreviation inclusion (j : connected_components J) : component j ⥤ decomposed J := sigma.incl _ /-- The forward direction of the equivalence between the decomposed category and the original. -/ @[simps {rhs_md := semireducible}] def decomposed_to (J : Type u₁) [category.{v₁} J] : decomposed J ⥤ J := sigma.desc component.ι @[simp] lemma inclusion_comp_decomposed_to (j : connected_components J) : inclusion j ⋙ decomposed_to J = component.ι j := rfl instance : full (decomposed_to J) := { preimage := begin rintro ⟨j', X, hX⟩ ⟨k', Y, hY⟩ f, dsimp at f, have : j' = k', rw [← hX, ← hY, quotient.eq'], exact relation.refl_trans_gen.single (or.inl ⟨f⟩), subst this, refine sigma.sigma_hom.mk f, end, witness' := begin rintro ⟨j', X, hX⟩ ⟨_, Y, rfl⟩ f, have : quotient.mk' Y = j', { rw [← hX, quotient.eq'], exact relation.refl_trans_gen.single (or.inr ⟨f⟩) }, subst this, refl, end } instance : faithful (decomposed_to J) := { map_injective' := begin rintro ⟨_, j, rfl⟩ ⟨_, k, hY⟩ ⟨f⟩ ⟨g⟩ e, change f = g at e, subst e, end } instance : ess_surj (decomposed_to J) := { mem_ess_image := λ j, ⟨⟨_, j, rfl⟩, ⟨iso.refl _⟩⟩ } instance : is_equivalence (decomposed_to J) := equivalence.of_fully_faithfully_ess_surj _ /-- This gives that any category is equivalent to a disjoint union of connected categories. -/ @[simps functor {rhs_md := semireducible}] def decomposed_equiv : decomposed J ≌ J := (decomposed_to J).as_equivalence end category_theory
6fb1e911eaf5502dd4c44a3ef730635323d1746d
618003631150032a5676f229d13a079ac875ff77
/src/measure_theory/measure_space.lean
cac52517fa008de3f2cd85c2ca6024a92f39375f
[ "Apache-2.0" ]
permissive
awainverse/mathlib
939b68c8486df66cfda64d327ad3d9165248c777
ea76bd8f3ca0a8bf0a166a06a475b10663dec44a
refs/heads/master
1,659,592,962,036
1,590,987,592,000
1,590,987,592,000
268,436,019
1
0
Apache-2.0
1,590,990,500,000
1,590,990,500,000
null
UTF-8
Lean
false
false
37,944
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 /-! # Measure spaces Measures are restricted to a measurable space (associated by the type class `measurable_space`). This allows us to prove equalities between measures by restricting to a generating set of the measurable space. On the other hand, the `μ.measure s` projection (i.e. the measure of `s` on the measure space `μ`) is the _outer_ measure generated by `μ`. This gives us a unrestricted monotonicity rule and it is somehow well-behaved on non-measurable sets. This allows us for the `lebesgue` measure space to have the `borel` measurable space, but still be a complete measure. -/ noncomputable theory open classical set filter finset function open_locale classical topological_space universes u v w x namespace measure_theory section of_measurable parameters {α : Type*} [measurable_space α] parameters (m : Π (s : set α), is_measurable s → ennreal) parameters (m0 : m ∅ is_measurable.empty = 0) include m0 /-- Measure projection which is ∞ for non-measurable sets. `measure'` is mainly used to derive the outer measure, for the main `measure` projection. -/ def measure' (s : set α) : ennreal := ⨅ h : is_measurable s, m s h lemma measure'_eq {s} (h : is_measurable s) : measure' s = m s h := by simp [measure', h] lemma measure'_empty : measure' ∅ = 0 := (measure'_eq is_measurable.empty).trans m0 lemma measure'_Union_nat {f : ℕ → set α} (hm : ∀i, is_measurable (f i)) (mU : m (⋃i, f i) (is_measurable.Union hm) = (∑'i, m (f i) (hm i))) : measure' (⋃i, f i) = (∑'i, measure' (f i)) := (measure'_eq _).trans $ mU.trans $ by congr; funext i; rw measure'_eq /-- outer measure of a measure -/ def outer_measure' : outer_measure α := outer_measure.of_function measure' measure'_empty lemma measure'_Union_le_tsum_nat' (mU : ∀ {f : ℕ → set α} (hm : ∀i, is_measurable (f i)), m (⋃i, f i) (is_measurable.Union hm) ≤ (∑'i, m (f i) (hm i))) (s : ℕ → set α) : measure' (⋃i, s i) ≤ (∑'i, measure' (s i)) := begin by_cases h : ∀i, is_measurable (s i), { rw [measure'_eq _ _ (is_measurable.Union h), congr_arg tsum _], {apply mU h}, funext i, apply measure'_eq _ _ (h i) }, { cases not_forall.1 h with i hi, exact le_trans (le_infi $ λ h, hi.elim h) (ennreal.le_tsum i) } end parameter (mU : ∀ {f : ℕ → set α} (hm : ∀i, is_measurable (f i)), pairwise (disjoint on f) → m (⋃i, f i) (is_measurable.Union hm) = (∑'i, m (f i) (hm i))) include mU lemma measure'_Union {β} [encodable β] {f : β → set α} (hd : pairwise (disjoint on f)) (hm : ∀i, is_measurable (f i)) : measure' (⋃i, f i) = (∑'i, measure' (f i)) := begin rw [encodable.Union_decode2, outer_measure.Union_aux], { exact measure'_Union_nat _ _ (λ n, encodable.Union_decode2_cases is_measurable.empty hm) (mU _ (measurable_space.Union_decode2_disjoint_on hd)) }, { apply measure'_empty }, end lemma measure'_union {s₁ s₂ : set α} (hd : disjoint s₁ s₂) (h₁ : is_measurable s₁) (h₂ : is_measurable s₂) : measure' (s₁ ∪ s₂) = measure' s₁ + measure' s₂ := begin rw [union_eq_Union, measure'_Union _ _ @mU (pairwise_disjoint_on_bool.2 hd) (bool.forall_bool.2 ⟨h₂, h₁⟩), tsum_fintype], change _+_ = _, simp end lemma measure'_mono {s₁ s₂ : set α} (h₁ : is_measurable s₁) (hs : s₁ ⊆ s₂) : measure' s₁ ≤ measure' s₂ := le_infi $ λ h₂, begin have := measure'_union _ _ @mU disjoint_diff h₁ (h₂.diff h₁), rw union_diff_cancel hs at this, rw ← measure'_eq m m0 _, exact le_iff_exists_add.2 ⟨_, this⟩ end lemma measure'_Union_le_tsum_nat : ∀ (s : ℕ → set α), measure' (⋃i, s i) ≤ (∑'i, measure' (s i)) := measure'_Union_le_tsum_nat' $ λ f h, begin simp [Union_disjointed.symm] {single_pass := tt}, rw [mU (is_measurable.disjointed h) disjoint_disjointed], refine ennreal.tsum_le_tsum (λ i, _), rw [← measure'_eq m m0, ← measure'_eq m m0], exact measure'_mono _ _ @mU (is_measurable.disjointed h _) (inter_subset_left _ _) end lemma outer_measure'_eq {s : set α} (hs : is_measurable s) : outer_measure' s = m s hs := by rw ← measure'_eq m m0 hs; exact (le_antisymm (outer_measure.of_function_le _ _ _) $ le_infi $ λ f, le_infi $ λ hf, le_trans (measure'_mono _ _ @mU hs hf) $ measure'_Union_le_tsum_nat _ _ @mU _) lemma outer_measure'_eq_measure' {s : set α} (hs : is_measurable s) : outer_measure' s = measure' s := by rw [measure'_eq m m0 hs, outer_measure'_eq m m0 @mU hs] end of_measurable namespace outer_measure variables {α : Type*} [measurable_space α] (m : outer_measure α) def trim : outer_measure α := outer_measure' (λ s _, m s) m.empty theorem trim_ge : m ≤ m.trim := λ s, le_infi $ λ f, le_infi $ λ hs, le_trans (m.mono hs) $ le_trans (m.Union_nat f) $ ennreal.tsum_le_tsum $ λ i, le_infi $ λ hf, le_refl _ theorem trim_eq {s : set α} (hs : is_measurable s) : m.trim s = m s := le_antisymm (le_trans (of_function_le _ _ _) (infi_le _ hs)) (trim_ge _ _) theorem trim_congr {m₁ m₂ : outer_measure α} (H : ∀ {s : set α}, is_measurable s → m₁ s = m₂ s) : m₁.trim = m₂.trim := by unfold trim; congr; funext s hs; exact H hs theorem trim_le_trim {m₁ m₂ : outer_measure α} (H : m₁ ≤ m₂) : m₁.trim ≤ m₂.trim := λ s, infi_le_infi $ λ f, infi_le_infi $ λ hs, ennreal.tsum_le_tsum $ λ b, infi_le_infi $ λ hf, H _ theorem le_trim_iff {m₁ m₂ : outer_measure α} : m₁ ≤ m₂.trim ↔ ∀ s, is_measurable s → m₁ s ≤ m₂ s := le_of_function.trans $ forall_congr $ λ s, le_infi_iff theorem trim_eq_infi (s : set α) : m.trim s = ⨅ t (st : s ⊆ t) (ht : is_measurable t), m t := begin refine le_antisymm (le_infi $ λ t, le_infi $ λ st, le_infi $ λ ht, _) (le_infi $ λ f, le_infi $ λ hf, _), { rw ← trim_eq m ht, exact (trim m).mono st }, { by_cases h : ∀i, is_measurable (f i), { refine infi_le_of_le _ (infi_le_of_le hf $ infi_le_of_le (is_measurable.Union h) _), rw congr_arg tsum _, {exact m.Union_nat _}, funext i, exact measure'_eq _ _ (h i) }, { cases not_forall.1 h with i hi, exact le_trans (le_infi $ λ h, hi.elim h) (ennreal.le_tsum i) } } end theorem trim_eq_infi' (s : set α) : m.trim s = ⨅ t : {t // s ⊆ t ∧ is_measurable t}, m t.1 := by simp [infi_subtype, infi_and, trim_eq_infi] theorem trim_trim (m : outer_measure α) : m.trim.trim = m.trim := le_antisymm (le_trim_iff.2 $ λ s hs, by simp [trim_eq _ hs, le_refl]) (trim_ge _) theorem trim_zero : (0 : outer_measure α).trim = 0 := ext $ λ s, le_antisymm (le_trans ((trim 0).mono (subset_univ s)) $ le_of_eq $ trim_eq _ is_measurable.univ) (zero_le _) theorem trim_add (m₁ m₂ : outer_measure α) : (m₁ + m₂).trim = m₁.trim + m₂.trim := ext $ λ s, begin simp [trim_eq_infi'], rw ennreal.infi_add_infi, rintro ⟨t₁, st₁, ht₁⟩ ⟨t₂, st₂, ht₂⟩, exact ⟨⟨_, subset_inter_iff.2 ⟨st₁, st₂⟩, ht₁.inter ht₂⟩, add_le_add' (m₁.mono' (inter_subset_left _ _)) (m₂.mono' (inter_subset_right _ _))⟩, end theorem trim_sum_ge {ι} (m : ι → outer_measure α) : sum (λ i, (m i).trim) ≤ (sum m).trim := λ s, by simp [trim_eq_infi]; exact λ t st ht, ennreal.tsum_le_tsum (λ i, infi_le_of_le t $ infi_le_of_le st $ infi_le _ ht) end outer_measure structure measure (α : Type*) [measurable_space α] extends outer_measure α := (m_Union {f : ℕ → set α} : (∀i, is_measurable (f i)) → pairwise (disjoint on f) → measure_of (⋃i, f i) = (∑'i, measure_of (f i))) (trimmed : to_outer_measure.trim = to_outer_measure) /-- Measure projections for a measure space. For measurable sets this returns the measure assigned by the `measure_of` field in `measure`. But we can extend this to _all_ sets, but using the outer measure. This gives us monotonicity and subadditivity for all sets. -/ instance measure.has_coe_to_fun {α} [measurable_space α] : has_coe_to_fun (measure α) := ⟨λ _, set α → ennreal, λ m, m.to_outer_measure⟩ namespace measure def of_measurable {α} [measurable_space α] (m : Π (s : set α), is_measurable s → ennreal) (m0 : m ∅ is_measurable.empty = 0) (mU : ∀ {f : ℕ → set α} (h : ∀i, is_measurable (f i)), pairwise (disjoint on f) → m (⋃i, f i) (is_measurable.Union h) = (∑'i, m (f i) (h i))) : measure α := { m_Union := λ f hf hd, show outer_measure' m m0 (Union f) = ∑' i, outer_measure' m m0 (f i), begin rw [outer_measure'_eq m m0 @mU, mU hf hd], congr, funext n, rw outer_measure'_eq m m0 @mU end, trimmed := show (outer_measure' m m0).trim = outer_measure' m m0, begin unfold outer_measure.trim, congr, funext s hs, exact outer_measure'_eq m m0 @mU hs end, ..outer_measure' m m0 } lemma of_measurable_apply {α} [measurable_space α] {m : Π (s : set α), is_measurable s → ennreal} {m0 : m ∅ is_measurable.empty = 0} {mU : ∀ {f : ℕ → set α} (h : ∀i, is_measurable (f i)), pairwise (disjoint on f) → m (⋃i, f i) (is_measurable.Union h) = (∑'i, m (f i) (h i))} (s : set α) (hs : is_measurable s) : of_measurable m m0 @mU s = m s hs := outer_measure'_eq m m0 @mU hs @[ext] lemma ext {α} [measurable_space α] : ∀ {μ₁ μ₂ : measure α}, (∀s, is_measurable s → μ₁ s = μ₂ s) → μ₁ = μ₂ | ⟨m₁, u₁, h₁⟩ ⟨m₂, u₂, h₂⟩ h := by congr; rw [← h₁, ← h₂]; exact outer_measure.trim_congr h end measure section variables {α : Type*} {β : Type*} [measurable_space α] {μ μ₁ μ₂ : measure α} {s s₁ s₂ : set α} @[simp] lemma to_outer_measure_apply (s) : μ.to_outer_measure s = μ s := rfl lemma measure_eq_trim (s) : μ s = μ.to_outer_measure.trim s := by rw μ.trimmed; refl lemma measure_eq_infi (s) : μ s = ⨅ t (st : s ⊆ t) (ht : is_measurable t), μ t := by rw [measure_eq_trim, outer_measure.trim_eq_infi]; refl lemma measure_eq_outer_measure' : μ s = outer_measure' (λ s _, μ s) μ.empty s := measure_eq_trim _ lemma to_outer_measure_eq_outer_measure' : μ.to_outer_measure = outer_measure' (λ s _, μ s) μ.empty := μ.trimmed.symm lemma measure_eq_measure' (hs : is_measurable s) : μ s = measure' (λ s _, μ s) μ.empty s := by rw [measure_eq_outer_measure', outer_measure'_eq_measure' (λ s _, μ s) _ μ.m_Union hs] @[simp] lemma measure_empty : μ ∅ = 0 := μ.empty lemma measure_mono (h : s₁ ⊆ s₂) : μ s₁ ≤ μ s₂ := μ.mono h lemma measure_mono_null (h : s₁ ⊆ s₂) (h₂ : μ s₂ = 0) : μ s₁ = 0 := by rw [← le_zero_iff_eq, ← h₂]; exact measure_mono h lemma exists_is_measurable_superset_of_measure_eq_zero {s : set α} (h : μ s = 0) : ∃t, s ⊆ t ∧ is_measurable t ∧ μ t = 0 := begin rw [measure_eq_infi] at h, have h := (infi_eq_bot _).1 h, choose t ht using show ∀n:ℕ, ∃t, s ⊆ t ∧ is_measurable t ∧ μ t < n⁻¹, { assume n, have : (0 : ennreal) < n⁻¹ := (zero_lt_iff_ne_zero.2 $ ennreal.inv_ne_zero.2 $ ennreal.nat_ne_top _), rcases h _ this with ⟨t, ht⟩, use [t], simpa [(>), infi_lt_iff, -add_comm] using ht }, refine ⟨⋂n, t n, subset_Inter (λn, (ht n).1), is_measurable.Inter (λn, (ht n).2.1), _⟩, refine eq_of_le_of_forall_le_of_dense bot_le (assume r hr, _), rcases ennreal.exists_inv_nat_lt (ne_of_gt hr) with ⟨n, hn⟩, calc μ (⋂n, t n) ≤ μ (t n) : measure_mono (Inter_subset _ _) ... ≤ n⁻¹ : le_of_lt (ht n).2.2 ... ≤ r : le_of_lt hn end theorem measure_Union_le {β} [encodable β] (s : β → set α) : μ (⋃i, s i) ≤ (∑'i, μ (s i)) := μ.to_outer_measure.Union _ lemma measure_Union_null {β} [encodable β] {s : β → set α} : (∀ i, μ (s i) = 0) → μ (⋃i, s i) = 0 := μ.to_outer_measure.Union_null theorem measure_union_le (s₁ s₂ : set α) : μ (s₁ ∪ s₂) ≤ μ s₁ + μ s₂ := μ.to_outer_measure.union _ _ lemma measure_union_null {s₁ s₂ : set α} : μ s₁ = 0 → μ s₂ = 0 → μ (s₁ ∪ s₂) = 0 := μ.to_outer_measure.union_null lemma measure_Union {β} [encodable β] {f : β → set α} (hn : pairwise (disjoint on f)) (h : ∀i, is_measurable (f i)) : μ (⋃i, f i) = (∑'i, μ (f i)) := by rw [measure_eq_measure' (is_measurable.Union h), measure'_Union (λ s _, μ s) _ μ.m_Union hn h]; simp [measure_eq_measure', h] lemma measure_union (hd : disjoint s₁ s₂) (h₁ : is_measurable s₁) (h₂ : is_measurable s₂) : μ (s₁ ∪ s₂) = μ s₁ + μ s₂ := by rw [measure_eq_measure' (h₁.union h₂), measure'_union (λ s _, μ s) _ μ.m_Union hd h₁ h₂]; simp [measure_eq_measure', h₁, h₂] lemma measure_bUnion {s : set β} {f : β → set α} (hs : countable s) (hd : pairwise_on s (disjoint on f)) (h : ∀b∈s, is_measurable (f b)) : μ (⋃b∈s, f b) = ∑'p:s, μ (f p.1) := begin haveI := hs.to_encodable, rw [← measure_Union, bUnion_eq_Union], { rintro ⟨i, hi⟩ ⟨j, hj⟩ ij x ⟨h₁, h₂⟩, exact hd i hi j hj (mt subtype.eq' ij:_) ⟨h₁, h₂⟩ }, { simpa } end lemma measure_sUnion {S : set (set α)} (hs : countable S) (hd : pairwise_on S disjoint) (h : ∀s∈S, is_measurable s) : μ (⋃₀ S) = ∑'s:S, μ s.1 := by rw [sUnion_eq_bUnion, measure_bUnion hs hd h] lemma measure_diff {s₁ s₂ : set α} (h : s₂ ⊆ s₁) (h₁ : is_measurable s₁) (h₂ : is_measurable s₂) (h_fin : μ s₂ < ⊤) : μ (s₁ \ s₂) = μ s₁ - μ s₂ := begin refine (ennreal.add_sub_self' h_fin).symm.trans _, rw [← measure_union disjoint_diff h₂ (h₁.diff h₂), union_diff_cancel h] end lemma measure_Union_eq_supr_nat {s : ℕ → set α} (h : ∀i, is_measurable (s i)) (hs : monotone s) : μ (⋃i, s i) = (⨆i, μ (s i)) := begin refine le_antisymm _ (supr_le $ λ i, measure_mono $ subset_Union _ _), rw [← Union_disjointed, measure_Union disjoint_disjointed (is_measurable.disjointed h), ennreal.tsum_eq_supr_nat], refine supr_le (λ n, _), cases n, {apply zero_le _}, suffices : (finset.range n.succ).sum (λ i, μ (disjointed s i)) = μ (s n), { rw this, exact le_supr _ n }, rw [← Union_disjointed_of_mono hs, measure_Union, tsum_eq_sum], { apply sum_congr rfl, intros i hi, simp [finset.mem_range.1 hi] }, { intros i hi, simp [mt finset.mem_range.2 hi] }, { rintro i j ij x ⟨⟨_, ⟨_, rfl⟩, h₁⟩, ⟨_, ⟨_, rfl⟩, h₂⟩⟩, exact disjoint_disjointed i j ij ⟨h₁, h₂⟩ }, { intro i, by_cases h' : i < n.succ; simp [h', is_measurable.empty], apply is_measurable.disjointed h } end lemma measure_Inter_eq_infi_nat {s : ℕ → set α} (h : ∀i, is_measurable (s i)) (hs : ∀i j, i ≤ j → s j ⊆ s i) (hfin : ∃i, μ (s i) < ⊤) : μ (⋂i, s i) = (⨅i, μ (s i)) := begin rcases hfin with ⟨k, hk⟩, rw [← ennreal.sub_sub_cancel (by exact hk) (infi_le _ k), ennreal.sub_infi, ← ennreal.sub_sub_cancel (by exact hk) (measure_mono (Inter_subset _ k)), ← measure_diff (Inter_subset _ k) (h k) (is_measurable.Inter h) (lt_of_le_of_lt (measure_mono (Inter_subset _ k)) hk), diff_Inter, measure_Union_eq_supr_nat], { congr, funext i, cases le_total k i with ik ik, { exact measure_diff (hs _ _ ik) (h k) (h i) (lt_of_le_of_lt (measure_mono (hs _ _ ik)) hk) }, { rw [diff_eq_empty.2 (hs _ _ ik), measure_empty, ennreal.sub_eq_zero_of_le (measure_mono (hs _ _ ik))] } }, { exact λ i, (h k).diff (h i) }, { exact λ i j ij, diff_subset_diff_right (hs _ _ ij) } end lemma measure_eq_inter_diff {μ : measure α} {s t : set α} (hs : is_measurable s) (ht : is_measurable t) : μ s = μ (s ∩ t) + μ (s \ t) := have hd : disjoint (s ∩ t) (s \ t) := assume a ⟨⟨_, hs⟩, _, hns⟩, hns hs , by rw [← measure_union hd (hs.inter ht) (hs.diff ht), inter_union_diff s t] lemma tendsto_measure_Union {μ : measure α} {s : ℕ → set α} (hs : ∀n, is_measurable (s n)) (hm : monotone s) : tendsto (μ ∘ s) at_top (𝓝 (μ (⋃n, s n))) := begin rw measure_Union_eq_supr_nat hs hm, exact tendsto_at_top_supr_nat (μ ∘ s) (assume n m hnm, measure_mono $ hm $ hnm) end lemma tendsto_measure_Inter {μ : measure α} {s : ℕ → set α} (hs : ∀n, is_measurable (s n)) (hm : ∀n m, n ≤ m → s m ⊆ s n) (hf : ∃i, μ (s i) < ⊤) : tendsto (μ ∘ s) at_top (𝓝 (μ (⋂n, s n))) := begin rw measure_Inter_eq_infi_nat hs hm hf, exact tendsto_at_top_infi_nat (μ ∘ s) (assume n m hnm, measure_mono $ hm _ _ $ hnm), end end def outer_measure.to_measure {α} (m : outer_measure α) [ms : measurable_space α] (h : ms ≤ m.caratheodory) : measure α := measure.of_measurable (λ s _, m s) m.empty (λ f hf hd, m.Union_eq_of_caratheodory (λ i, h _ (hf i)) hd) lemma le_to_outer_measure_caratheodory {α} [ms : measurable_space α] (μ : measure α) : ms ≤ μ.to_outer_measure.caratheodory := begin assume s hs, rw to_outer_measure_eq_outer_measure', refine outer_measure.caratheodory_is_measurable (λ t, le_infi $ λ ht, _), rw [← measure_eq_measure' (ht.inter hs), ← measure_eq_measure' (ht.diff hs), ← measure_union _ (ht.inter hs) (ht.diff hs), inter_union_diff], exact le_refl _, exact λ x ⟨⟨_, h₁⟩, _, h₂⟩, h₂ h₁ end lemma to_measure_to_outer_measure {α} (m : outer_measure α) [ms : measurable_space α] (h : ms ≤ m.caratheodory) : (m.to_measure h).to_outer_measure = m.trim := rfl @[simp] lemma to_measure_apply {α} (m : outer_measure α) [ms : measurable_space α] (h : ms ≤ m.caratheodory) {s : set α} (hs : is_measurable s) : m.to_measure h s = m s := m.trim_eq hs lemma to_outer_measure_to_measure {α : Type*} [ms : measurable_space α] {μ : measure α} : μ.to_outer_measure.to_measure (le_to_outer_measure_caratheodory _) = μ := measure.ext $ λ s, μ.to_outer_measure.trim_eq namespace measure variables {α : Type*} {β : Type*} {γ : Type*} [measurable_space α] [measurable_space β] [measurable_space γ] instance : has_zero (measure α) := ⟨{ to_outer_measure := 0, m_Union := λ f hf hd, tsum_zero.symm, trimmed := outer_measure.trim_zero }⟩ @[simp] theorem zero_to_outer_measure : (0 : measure α).to_outer_measure = 0 := rfl @[simp] theorem zero_apply (s : set α) : (0 : measure α) s = 0 := rfl 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] theorem add_apply (μ₁ μ₂ : measure α) (s : set α) : (μ₁ + μ₂) s = μ₁ s + μ₂ s := rfl instance add_comm_monoid : add_comm_monoid (measure α) := { zero := 0, add := (+), add_assoc := assume a b c, ext $ assume s hs, add_assoc _ _ _, add_comm := assume a b, ext $ assume s hs, add_comm _ _, zero_add := assume a, ext $ by simp, add_zero := assume a, ext $ assume s hs, add_zero _ } instance : partial_order (measure α) := { le := λm₁ m₂, ∀ s, is_measurable s → m₁ s ≤ m₂ s, le_refl := assume m s hs, le_refl _, le_trans := assume m₁ m₂ m₃ h₁ h₂ s hs, le_trans (h₁ s hs) (h₂ s hs), le_antisymm := assume m₁ m₂ h₁ h₂, ext $ assume s hs, le_antisymm (h₁ s hs) (h₂ s hs) } theorem le_iff {μ₁ μ₂ : measure α} : μ₁ ≤ μ₂ ↔ ∀ s, is_measurable s → μ₁ s ≤ μ₂ s := iff.rfl theorem to_outer_measure_le {μ₁ μ₂ : measure α} : μ₁.to_outer_measure ≤ μ₂.to_outer_measure ↔ μ₁ ≤ μ₂ := by rw [← μ₂.trimmed, outer_measure.le_trim_iff]; refl theorem le_iff' {μ₁ μ₂ : measure α} : μ₁ ≤ μ₂ ↔ ∀ s, μ₁ s ≤ μ₂ s := to_outer_measure_le.symm section variables {m : set (measure α)} {μ : measure α} lemma Inf_caratheodory (s : set α) (hs : is_measurable s) : (Inf (measure.to_outer_measure '' m)).caratheodory.is_measurable s := begin rw [outer_measure.Inf_eq_of_function_Inf_gen], refine outer_measure.caratheodory_is_measurable (assume t, _), cases t.eq_empty_or_nonempty with ht ht, by simp [ht], simp only [outer_measure.Inf_gen_nonempty1 _ _ ht, le_infi_iff, ball_image_iff, to_outer_measure_apply, measure_eq_infi t], assume μ hμ u htu hu, have hm : ∀{s t}, s ⊆ t → outer_measure.Inf_gen (to_outer_measure '' m) s ≤ μ t, { assume s t hst, rw [outer_measure.Inf_gen_nonempty2 _ _ (mem_image_of_mem _ hμ)], refine infi_le_of_le (μ.to_outer_measure) (infi_le_of_le (mem_image_of_mem _ hμ) _), rw [to_outer_measure_apply], refine measure_mono hst }, rw [measure_eq_inter_diff hu hs], refine add_le_add' (hm $ inter_subset_inter_left _ htu) (hm $ diff_subset_diff_left htu) end instance : has_Inf (measure α) := ⟨λm, (Inf (to_outer_measure '' m)).to_measure $ Inf_caratheodory⟩ lemma Inf_apply {m : set (measure α)} {s : set α} (hs : is_measurable s) : Inf m s = Inf (to_outer_measure '' m) s := to_measure_apply _ _ hs private lemma Inf_le (h : μ ∈ m) : Inf m ≤ μ := have Inf (to_outer_measure '' m) ≤ μ.to_outer_measure := Inf_le (mem_image_of_mem _ h), assume s hs, by rw [Inf_apply hs, ← to_outer_measure_apply]; exact this s private lemma le_Inf (h : ∀μ' ∈ m, μ ≤ μ') : μ ≤ Inf m := have μ.to_outer_measure ≤ Inf (to_outer_measure '' m) := le_Inf $ ball_image_of_ball $ assume μ hμ, to_outer_measure_le.2 $ h _ hμ, assume s hs, by rw [Inf_apply hs, ← to_outer_measure_apply]; exact this s instance : has_Sup (measure α) := ⟨λs, Inf {μ' | ∀μ∈s, μ ≤ μ' }⟩ private lemma le_Sup (h : μ ∈ m) : μ ≤ Sup m := le_Inf $ assume μ' h', h' _ h private lemma Sup_le (h : ∀μ' ∈ m, μ' ≤ μ) : Sup m ≤ μ := Inf_le h instance : order_bot (measure α) := { bot := 0, bot_le := assume a s hs, by exact bot_le, .. measure.partial_order } instance : order_top (measure α) := { 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], .. measure.partial_order } instance : complete_lattice (measure α) := { Inf := Inf, Sup := Sup, inf := λa b, Inf {a, b}, sup := λa b, Sup {a, b}, le_Sup := assume s μ h, le_Sup h, Sup_le := assume s μ h, Sup_le h, Inf_le := assume s μ h, Inf_le h, le_Inf := assume s μ h, le_Inf h, le_sup_left := assume a b, le_Sup $ by simp, le_sup_right := assume a b, le_Sup $ by simp, sup_le := assume a b c hac hbc, Sup_le $ by simp [*, or_imp_distrib] {contextual := tt}, inf_le_left := assume a b, Inf_le $ by simp, inf_le_right := assume a b, Inf_le $ by simp, le_inf := assume a b c hac hbc, le_Inf $ by simp [*, or_imp_distrib] {contextual := tt}, .. measure.partial_order, .. measure.order_top, .. measure.order_bot } end def map (f : α → β) (μ : measure α) : measure β := if hf : measurable f then (μ.to_outer_measure.map f).to_measure $ λ s hs t, le_to_outer_measure_caratheodory μ _ (hf _ hs) (f ⁻¹' t) else 0 variables {μ ν : measure α} @[simp] theorem map_apply {f : α → β} (hf : measurable f) {s : set β} (hs : is_measurable s) : (map f μ : measure β) s = μ (f ⁻¹' s) := by rw [map, dif_pos hf, to_measure_apply _ _ hs]; refl @[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.preimage hs, hg.comp hf]; rw ← preimage_comp /-- The dirac measure. -/ def dirac (a : α) : measure α := (outer_measure.dirac a).to_measure (by simp) @[simp] lemma dirac_apply (a : α) {s : set α} (hs : is_measurable s) : (dirac a : measure α) s = ⨆ h : a ∈ s, 1 := to_measure_apply _ _ hs /-- Sum of an indexed family of measures. -/ def sum {ι : Type*} (f : ι → measure α) : measure α := (outer_measure.sum (λ i, (f i).to_outer_measure)).to_measure $ le_trans (by exact le_infi (λ i, le_to_outer_measure_caratheodory _)) (outer_measure.le_sum_caratheodory _) /-- Counting measure on any measurable space. -/ def count : measure α := sum dirac @[class] def is_complete {α} {_:measurable_space α} (μ : measure α) : Prop := ∀ s, μ s = 0 → is_measurable s /-- The "almost everywhere" filter of co-null sets. -/ def a_e (μ : measure α) : filter α := { sets := {s | μ (-s) = 0}, univ_sets := by simp [measure_empty], inter_sets := λ s t hs ht, by simp [compl_inter]; exact measure_union_null hs ht, sets_of_superset := λ s t hs hst, measure_mono_null (set.compl_subset_compl.2 hst) hs } lemma mem_a_e_iff (s : set α) : s ∈ μ.a_e.sets ↔ μ (- s) = 0 := iff.rfl end measure end measure_theory section is_complete open measure_theory variables {α : Type*} [measurable_space α] (μ : measure α) def is_null_measurable (s : set α) : Prop := ∃ t z, s = t ∪ z ∧ is_measurable t ∧ μ z = 0 theorem is_null_measurable_iff {μ : measure α} {s : set α} : is_null_measurable μ s ↔ ∃ t, t ⊆ s ∧ is_measurable t ∧ μ (s \ t) = 0 := begin split, { rintro ⟨t, z, rfl, ht, hz⟩, refine ⟨t, set.subset_union_left _ _, ht, measure_mono_null _ hz⟩, simp [union_diff_left, diff_subset] }, { rintro ⟨t, st, ht, hz⟩, exact ⟨t, _, (union_diff_cancel st).symm, ht, hz⟩ } end theorem is_null_measurable_measure_eq {μ : measure α} {s t : set α} (st : t ⊆ s) (hz : μ (s \ t) = 0) : μ s = μ t := begin refine le_antisymm _ (measure_mono st), have := measure_union_le t (s \ t), rw [union_diff_cancel st, hz] at this, simpa end theorem is_measurable.is_null_measurable {s : set α} (hs : is_measurable s) : is_null_measurable μ s := ⟨s, ∅, by simp, hs, μ.empty⟩ theorem is_null_measurable_of_complete [c : μ.is_complete] {s : set α} : is_null_measurable μ s ↔ is_measurable s := ⟨by rintro ⟨t, z, rfl, ht, hz⟩; exact is_measurable.union ht (c _ hz), λ h, h.is_null_measurable _⟩ variables {μ} theorem is_null_measurable.union_null {s z : set α} (hs : is_null_measurable μ s) (hz : μ z = 0) : is_null_measurable μ (s ∪ z) := begin rcases hs with ⟨t, z', rfl, ht, hz'⟩, exact ⟨t, z' ∪ z, set.union_assoc _ _ _, ht, le_zero_iff_eq.1 (le_trans (measure_union_le _ _) $ by simp [hz, hz'])⟩ end theorem null_is_null_measurable {z : set α} (hz : μ z = 0) : is_null_measurable μ z := by simpa using (is_measurable.empty.is_null_measurable _).union_null hz theorem is_null_measurable.Union_nat {s : ℕ → set α} (hs : ∀ i, is_null_measurable μ (s i)) : is_null_measurable μ (Union s) := begin choose t ht using assume i, is_null_measurable_iff.1 (hs i), simp [forall_and_distrib] at ht, rcases ht with ⟨st, ht, hz⟩, refine is_null_measurable_iff.2 ⟨Union t, Union_subset_Union st, is_measurable.Union ht, measure_mono_null _ (measure_Union_null hz)⟩, rw [diff_subset_iff, ← Union_union_distrib], exact Union_subset_Union (λ i, by rw ← diff_subset_iff) end theorem is_measurable.diff_null {s z : set α} (hs : is_measurable s) (hz : μ z = 0) : is_null_measurable μ (s \ z) := begin rw measure_eq_infi at hz, choose f hf using show ∀ q : {q:ℚ//q>0}, ∃ t:set α, z ⊆ t ∧ is_measurable t ∧ μ t < (nnreal.of_real q.1 : ennreal), { rintro ⟨ε, ε0⟩, have : 0 < (nnreal.of_real ε : ennreal), { simpa using ε0 }, rw ← hz at this, simpa [infi_lt_iff] }, refine is_null_measurable_iff.2 ⟨s \ Inter f, diff_subset_diff_right (subset_Inter (λ i, (hf i).1)), hs.diff (is_measurable.Inter (λ i, (hf i).2.1)), measure_mono_null _ (le_zero_iff_eq.1 $ le_of_not_lt $ λ h, _)⟩, { exact Inter f }, { rw [diff_subset_iff, diff_union_self], exact subset.trans (diff_subset _ _) (subset_union_left _ _) }, rcases ennreal.lt_iff_exists_rat_btwn.1 h with ⟨ε, ε0', ε0, h⟩, simp at ε0, apply not_le_of_lt (lt_trans (hf ⟨ε, ε0⟩).2.2 h), exact measure_mono (Inter_subset _ _) end theorem is_null_measurable.diff_null {s z : set α} (hs : is_null_measurable μ s) (hz : μ z = 0) : is_null_measurable μ (s \ z) := begin rcases hs with ⟨t, z', rfl, ht, hz'⟩, rw [set.union_diff_distrib], exact (ht.diff_null hz).union_null (measure_mono_null (diff_subset _ _) hz') end theorem is_null_measurable.compl {s : set α} (hs : is_null_measurable μ s) : is_null_measurable μ (-s) := begin rcases hs with ⟨t, z, rfl, ht, hz⟩, rw compl_union, exact ht.compl.diff_null hz end def null_measurable {α : Type u} [measurable_space α] (μ : measure α) : measurable_space α := { is_measurable := is_null_measurable μ, is_measurable_empty := is_measurable.empty.is_null_measurable _, is_measurable_compl := λ s hs, hs.compl, is_measurable_Union := λ f, is_null_measurable.Union_nat } def completion {α : Type u} [measurable_space α] (μ : measure α) : @measure_theory.measure α (null_measurable μ) := { to_outer_measure := μ.to_outer_measure, m_Union := λ s hs hd, show μ (Union s) = ∑' i, μ (s i), begin choose t ht using assume i, is_null_measurable_iff.1 (hs i), simp [forall_and_distrib] at ht, rcases ht with ⟨st, ht, hz⟩, rw is_null_measurable_measure_eq (Union_subset_Union st), { rw measure_Union _ ht, { congr, funext i, exact (is_null_measurable_measure_eq (st i) (hz i)).symm }, { rintro i j ij x ⟨h₁, h₂⟩, exact hd i j ij ⟨st i h₁, st j h₂⟩ } }, { refine measure_mono_null _ (measure_Union_null hz), rw [diff_subset_iff, ← Union_union_distrib], exact Union_subset_Union (λ i, by rw ← diff_subset_iff) } end, trimmed := begin letI := null_measurable μ, refine le_antisymm (λ s, _) (outer_measure.trim_ge _), rw outer_measure.trim_eq_infi, dsimp, clear _inst, rw measure_eq_infi s, exact infi_le_infi (λ t, infi_le_infi $ λ st, infi_le_infi2 $ λ ht, ⟨ht.is_null_measurable _, le_refl _⟩) end } instance completion.is_complete {α : Type u} [measurable_space α] (μ : measure α) : (completion μ).is_complete := λ z hz, null_is_null_measurable hz end is_complete namespace measure_theory section prio set_option default_priority 100 -- see Note [default priority] /-- A measure space is a measurable space equipped with a measure, referred to as `volume`. -/ class measure_space (α : Type*) extends measurable_space α := (μ : measure α) end prio section measure_space variables {α : Type*} [measure_space α] {s₁ s₂ : set α} open measure_space /-- `volume s` is the measure of `s : set α` with respect to the canonical measure on `α`. -/ def volume : set α → ennreal := @μ α _ @[simp] lemma volume_empty : volume (∅ : set α) = 0 := μ.empty lemma volume_mono : s₁ ⊆ s₂ → volume s₁ ≤ volume s₂ := measure_mono lemma volume_mono_null : s₁ ⊆ s₂ → volume s₂ = 0 → volume s₁ = 0 := measure_mono_null theorem volume_Union_le {β} [encodable β] : ∀ (s : β → set α), volume (⋃i, s i) ≤ (∑'i, volume (s i)) := measure_Union_le lemma volume_Union_null {β} [encodable β] {s : β → set α} : (∀ i, volume (s i) = 0) → volume (⋃i, s i) = 0 := measure_Union_null theorem volume_union_le : ∀ (s₁ s₂ : set α), volume (s₁ ∪ s₂) ≤ volume s₁ + volume s₂ := measure_union_le lemma volume_union_null : volume s₁ = 0 → volume s₂ = 0 → volume (s₁ ∪ s₂) = 0 := measure_union_null lemma volume_Union {β} [encodable β] {f : β → set α} : pairwise (disjoint on f) → (∀i, is_measurable (f i)) → volume (⋃i, f i) = (∑'i, volume (f i)) := measure_Union lemma volume_union : disjoint s₁ s₂ → is_measurable s₁ → is_measurable s₂ → volume (s₁ ∪ s₂) = volume s₁ + volume s₂ := measure_union lemma volume_bUnion {β} {s : set β} {f : β → set α} : countable s → pairwise_on s (disjoint on f) → (∀b∈s, is_measurable (f b)) → volume (⋃b∈s, f b) = ∑'p:s, volume (f p.1) := measure_bUnion lemma volume_sUnion {S : set (set α)} : countable S → pairwise_on S disjoint → (∀s∈S, is_measurable s) → volume (⋃₀ S) = ∑'s:S, volume s.1 := measure_sUnion lemma volume_bUnion_finset {β} {s : finset β} {f : β → set α} (hd : pairwise_on ↑s (disjoint on f)) (hm : ∀b∈s, is_measurable (f b)) : volume (⋃b∈s, f b) = s.sum (λp, volume (f p)) := show volume (⋃b∈(↑s : set β), f b) = s.sum (λp, volume (f p)), begin rw [volume_bUnion s.countable_to_set hd hm, tsum_eq_sum], { show s.attach.sum (λb:(↑s : set β), volume (f b)) = s.sum (λb, volume (f b)), exact @finset.sum_attach _ _ s _ (λb, volume (f b)) }, simp end lemma volume_diff : s₂ ⊆ s₁ → is_measurable s₁ → is_measurable s₂ → volume s₂ < ⊤ → volume (s₁ \ s₂) = volume s₁ - volume s₂ := measure_diff variable {ι : Type*} lemma sum_volume_le_volume_univ {s : finset ι} {t : ι → set α} (h : ∀ i ∈ s, is_measurable (t i)) (H : pairwise_on ↑s (disjoint on t)) : s.sum (λ i, volume (t i)) ≤ volume (univ : set α) := volume_bUnion_finset H h ▸ volume_mono (subset_univ _) lemma tsum_volume_le_volume_univ {s : ι → set α} (hs : ∀ i, is_measurable (s i)) (H : pairwise (disjoint on s)) : (∑' i, volume (s i)) ≤ volume (univ : set α) := begin rw [ennreal.tsum_eq_supr_sum], exact supr_le (λ s, sum_volume_le_volume_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_volume_univ_lt_tsum_volume {s : ι → set α} (hs : ∀ i, is_measurable (s i)) (H : volume (univ : set α) < ∑' i, volume (s i)) : ∃ i j (h : i ≠ j), (s i ∩ s j).nonempty := begin contrapose! H, apply tsum_volume_le_volume_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 `s.sum (λ i, μ (t i)) > μ univ`, then one of the intersections `t i ∩ t j` is not empty. -/ lemma exists_nonempty_inter_of_volume_univ_lt_sum_volume {s : finset ι} {t : ι → set α} (h : ∀ i ∈ s, is_measurable (t i)) (H : volume (univ : set α) < s.sum (λ i, volume (t i))) : ∃ (i ∈ s) (j ∈ s) (h : i ≠ j), (t i ∩ t j).nonempty := begin contrapose! H, apply sum_volume_le_volume_univ h, exact λ i hi j hj hij x hx, H i hi j hj hij ⟨x, hx⟩ end /-- `∀ₘ a:α, p a` states that the property `p` is almost everywhere true in the measure space associated with `α`. This means that the measure of the complementary of `p` is `0`. In a probability measure, the measure of `p` is `1`, when `p` is measurable. -/ def all_ae (p : α → Prop) : Prop := ∀ᶠ a in μ.a_e, p a notation `∀ₘ` binders `, ` r:(scoped P, all_ae P) := r lemma all_ae_congr {p q : α → Prop} (h : ∀ₘ a, p a ↔ q a) : (∀ₘ a, p a) ↔ (∀ₘ a, q a) := iff.intro (assume h', by filter_upwards [h, h'] assume a hpq hp, hpq.1 hp) (assume h', by filter_upwards [h, h'] assume a hpq hq, hpq.2 hq) lemma all_ae_iff {p : α → Prop} : (∀ₘ a, p a) ↔ volume { a | ¬ p a } = 0 := iff.rfl lemma volume_zero_iff_all_ae_nmem {s : set α} : volume s = 0 ↔ ∀ₘ a, a ∉ s := by simp only [all_ae_iff, not_not, set_of_mem_eq] lemma all_ae_of_all {p : α → Prop} : (∀a, p a) → ∀ₘ a, p a := univ_mem_sets' lemma all_ae_all_iff {ι : Type*} [encodable ι] {p : α → ι → Prop} : (∀ₘ a, ∀i, p a i) ↔ (∀i, ∀ₘ a, p a i) := begin refine iff.intro (assume h i, _) (assume h, _), { filter_upwards [h] assume a ha, ha i }, { have h := measure_Union_null h, rw [← compl_Inter] at h, filter_upwards [h] assume a, mem_Inter.1 } end @[simp] lemma all_ae_and_iff {p q : α → Prop} : (∀ₘ a, p a ∧ q a) ↔ (∀ₘ a, p a) ∧ ∀ₘ a, q a := eventually_and @[simp] lemma all_ae_imp_distrib_left {p : Prop} {q : α → Prop} : (∀ₘ a, p → q a) ↔ (p → ∀ₘ a, q a) := eventually_imp_distrib_left @[simp] lemma all_ae_or_distrib_left {p : Prop} {q : α → Prop} : (∀ₘ a, p ∨ q a) ↔ (p ∨ ∀ₘ a, q a) := eventually_or_distrib_left @[simp] lemma all_ae_or_distrib_right {p : α → Prop} {q : Prop} : (∀ₘ a, p a ∨ q) ↔ ((∀ₘ a, p a) ∨ q) := eventually_or_distrib_right variables {β : Type*} lemma all_ae_eq_refl (f : α → β) : ∀ₘ a, f a = f a := by { filter_upwards [], assume a, apply eq.refl } lemma all_ae_eq_symm {f g : α → β} : (∀ₘ a, f a = g a) → (∀ₘ a, g a = f a) := by { assume h, filter_upwards [h], assume a, apply eq.symm } lemma all_ae_eq_trans {f g h: α → β} (h₁ : ∀ₘ a, f a = g a) (h₂ : ∀ₘ a, g a = h a) : ∀ₘ a, f a = h a := by { filter_upwards [h₁, h₂], intro a, exact eq.trans } end measure_space end measure_theory
3bd51ecff3f05f089ebbd67fee4870711a0e297d
2eab05920d6eeb06665e1a6df77b3157354316ad
/src/order/filter/pointwise.lean
bf20b6c465b9b4f01be91f69afdbf306656f2bf0
[ "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
6,694
lean
/- Copyright (c) 2019 Zhouhang Zhou. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Zhouhang Zhou -/ import algebra.pointwise import order.filter.basic /-! # Pointwise operations on filters. The pointwise operations on filters have nice properties, such as • `map m (f₁ * f₂) = map m f₁ * map m f₂` • `𝓝 x * 𝓝 y = 𝓝 (x * y)` -/ open classical set universes u v w variables {α : Type u} {β : Type v} {γ : Type w} open_locale classical pointwise namespace filter open set @[to_additive] instance [has_one α] : has_one (filter α) := ⟨principal 1⟩ @[simp, to_additive] lemma mem_one [has_one α] (s : set α) : s ∈ (1 : filter α) ↔ (1:α) ∈ s := calc s ∈ (1:filter α) ↔ 1 ⊆ s : iff.rfl ... ↔ (1 : α) ∈ s : by simp @[to_additive] instance [monoid α] : has_mul (filter α) := ⟨λf g, { sets := { s | ∃t₁ t₂, t₁ ∈ f ∧ t₂ ∈ g ∧ t₁ * t₂ ⊆ s }, univ_sets := begin have h₁ : (∃x, x ∈ f) := ⟨univ, univ_sets f⟩, have h₂ : (∃x, x ∈ g) := ⟨univ, univ_sets g⟩, simpa using and.intro h₁ h₂ end, sets_of_superset := λx y hx hxy, begin rcases hx with ⟨t₁, ht₁, t₂, ht₂, t₁t₂⟩, exact ⟨t₁, ht₁, t₂, ht₂, subset.trans t₁t₂ hxy⟩ end, inter_sets := λx y, begin simp only [exists_prop, mem_set_of_eq, subset_inter_iff], rintros ⟨s₁, s₂, hs₁, hs₂, s₁s₂⟩ ⟨t₁, t₂, ht₁, ht₂, t₁t₂⟩, exact ⟨s₁ ∩ t₁, s₂ ∩ t₂, inter_sets f hs₁ ht₁, inter_sets g hs₂ ht₂, subset.trans (mul_subset_mul (inter_subset_left _ _) (inter_subset_left _ _)) s₁s₂, subset.trans (mul_subset_mul (inter_subset_right _ _) (inter_subset_right _ _)) t₁t₂⟩, end }⟩ @[to_additive] lemma mem_mul [monoid α] {f g : filter α} {s : set α} : s ∈ f * g ↔ ∃t₁ t₂, t₁ ∈ f ∧ t₂ ∈ g ∧ t₁ * t₂ ⊆ s := iff.rfl @[to_additive] lemma mul_mem_mul [monoid α] {f g : filter α} {s t : set α} (hs : s ∈ f) (ht : t ∈ g) : s * t ∈ f * g := ⟨_, _, hs, ht, subset.refl _⟩ @[to_additive] protected lemma mul_le_mul [monoid α] {f₁ f₂ g₁ g₂ : filter α} (hf : f₁ ≤ f₂) (hg : g₁ ≤ g₂) : f₁ * g₁ ≤ f₂ * g₂ := assume _ ⟨s, t, hs, ht, hst⟩, ⟨s, t, hf hs, hg ht, hst⟩ @[to_additive] lemma ne_bot.mul [monoid α] {f g : filter α} : ne_bot f → ne_bot g → ne_bot (f * g) := begin simp only [forall_mem_nonempty_iff_ne_bot.symm], rintros hf hg s ⟨a, b, ha, hb, ab⟩, exact ((hf a ha).mul (hg b hb)).mono ab end @[to_additive] protected lemma mul_assoc [monoid α] (f g h : filter α) : f * g * h = f * (g * h) := begin ext s, split, { rintros ⟨a, b, ⟨a₁, a₂, ha₁, ha₂, a₁a₂⟩, hb, ab⟩, refine ⟨a₁, a₂ * b, ha₁, mul_mem_mul ha₂ hb, _⟩, rw [← mul_assoc], exact calc a₁ * a₂ * b ⊆ a * b : mul_subset_mul a₁a₂ (subset.refl _) ... ⊆ s : ab }, { rintros ⟨a, b, ha, ⟨b₁, b₂, hb₁, hb₂, b₁b₂⟩, ab⟩, refine ⟨a * b₁, b₂, mul_mem_mul ha hb₁, hb₂, _⟩, rw [mul_assoc], exact calc a * (b₁ * b₂) ⊆ a * b : mul_subset_mul (subset.refl _) b₁b₂ ... ⊆ s : ab } end @[to_additive] protected lemma one_mul [monoid α] (f : filter α) : 1 * f = f := begin ext s, split, { rintros ⟨t₁, t₂, ht₁, ht₂, t₁t₂⟩, refine mem_of_superset (mem_of_superset ht₂ _) t₁t₂, assume x hx, exact ⟨1, x, by rwa [← mem_one], hx, one_mul _⟩ }, { assume hs, refine ⟨(1:set α), s, mem_principal_self _, hs, by simp only [one_mul]⟩ } end @[to_additive] protected lemma mul_one [monoid α] (f : filter α) : f * 1 = f := begin ext s, split, { rintros ⟨t₁, t₂, ht₁, ht₂, t₁t₂⟩, refine mem_of_superset (mem_of_superset ht₁ _) t₁t₂, assume x hx, exact ⟨x, 1, hx, by rwa [← mem_one], mul_one _⟩ }, { assume hs, refine ⟨s, (1:set α), hs, mem_principal_self _, by simp only [mul_one]⟩ } end @[to_additive filter.add_monoid] instance [monoid α] : monoid (filter α) := { mul_assoc := filter.mul_assoc, one_mul := filter.one_mul, mul_one := filter.mul_one, .. filter.has_mul, .. filter.has_one } section map variables [monoid α] [monoid β] {f : filter α} (m : mul_hom α β) (φ : α →* β) @[to_additive] protected lemma map_mul {f₁ f₂ : filter α} : map m (f₁ * f₂) = map m f₁ * map m f₂ := begin ext s, simp only [mem_mul], split, { rintro ⟨t₁, t₂, ht₁, ht₂, t₁t₂⟩, have : m '' (t₁ * t₂) ⊆ s := subset.trans (image_subset m t₁t₂) (image_preimage_subset _ _), refine ⟨m '' t₁, m '' t₂, image_mem_map ht₁, image_mem_map ht₂, _⟩, rwa ← image_mul m }, { rintro ⟨t₁, t₂, ht₁, ht₂, t₁t₂⟩, refine ⟨m ⁻¹' t₁, m ⁻¹' t₂, ht₁, ht₂, image_subset_iff.1 _⟩, rw image_mul m, exact subset.trans (mul_subset_mul (image_preimage_subset _ _) (image_preimage_subset _ _)) t₁t₂ }, end @[to_additive] protected lemma map_one : map φ (1:filter α) = 1 := le_antisymm (le_principal_iff.2 $ mem_map_iff_exists_image.2 ⟨(1:set α), by simp, by { assume x, simp [φ.map_one] }⟩) (le_map $ assume s hs, begin simp only [mem_one], exact ⟨(1:α), (mem_one s).1 hs, φ.map_one⟩ end) /-- If `φ : α →* β` then `map_monoid_hom φ` is the monoid homomorphism `filter α →* filter β` induced by `map φ`. -/ @[to_additive "If `φ : α →+ β` then `map_add_monoid_hom φ` is the monoid homomorphism `filter α →+ filter β` induced by `map φ`."] def map_monoid_hom : filter α →* filter β := { to_fun := map φ, map_one' := filter.map_one φ, map_mul' := λ _ _, filter.map_mul φ.to_mul_hom } -- The other direction does not hold in general. @[to_additive] lemma comap_mul_comap_le {f₁ f₂ : filter β} : comap m f₁ * comap m f₂ ≤ comap m (f₁ * f₂) := begin rintros s ⟨t, ⟨t₁, t₂, ht₁, ht₂, t₁t₂⟩, mt⟩, refine ⟨m ⁻¹' t₁, m ⁻¹' t₂, ⟨t₁, ht₁, subset.refl _⟩, ⟨t₂, ht₂, subset.refl _⟩, _⟩, have := subset.trans (preimage_mono t₁t₂) mt, exact subset.trans (preimage_mul_preimage_subset _) this end @[to_additive] lemma tendsto.mul_mul {f₁ g₁ : filter α} {f₂ g₂ : filter β} : tendsto m f₁ f₂ → tendsto m g₁ g₂ → tendsto m (f₁ * g₁) (f₂ * g₂) := assume hf hg, by { rw [tendsto, filter.map_mul m], exact filter.mul_le_mul hf hg } end map end filter
5cce03b774ac221f9cd297bb3e56cda9240c0565
bb31430994044506fa42fd667e2d556327e18dfe
/src/topology/algebra/order/filter.lean
5ec5f68ec72c4aee299509521b0783e46d4b47d2
[ "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
1,279
lean
/- Copyright (c) 2022 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudryashov -/ import topology.order.basic import topology.filter /-! # Topology on filters of a space with order topology In this file we prove that `𝓝 (f x)` tends to `𝓝 filter.at_top` provided that `f` tends to `filter.at_top`, and similarly for `filter.at_bot`. -/ open_locale topological_space namespace filter variables {α X : Type*} [topological_space X] [partial_order X] [order_topology X] protected lemma tendsto_nhds_at_top [no_max_order X] : tendsto 𝓝 (at_top : filter X) (𝓝 at_top) := filter.tendsto_nhds_at_top_iff.2 $ λ x, (eventually_gt_at_top x).mono $ λ y, le_mem_nhds protected lemma tendsto_nhds_at_bot [no_min_order X] : tendsto 𝓝 (at_bot : filter X) (𝓝 at_bot) := @filter.tendsto_nhds_at_top Xᵒᵈ _ _ _ _ lemma tendsto.nhds_at_top [no_max_order X] {f : α → X} {l : filter α} (h : tendsto f l at_top) : tendsto (𝓝 ∘ f) l (𝓝 at_top) := filter.tendsto_nhds_at_top.comp h lemma tendsto.nhds_at_bot [no_min_order X] {f : α → X} {l : filter α} (h : tendsto f l at_bot) : tendsto (𝓝 ∘ f) l (𝓝 at_bot) := @tendsto.nhds_at_top α Xᵒᵈ _ _ _ _ _ _ h end filter
c64575a8c6fd6083794dade3bb8ab1c8e05bc11d
367134ba5a65885e863bdc4507601606690974c1
/src/data/int/sqrt.lean
6f3b9a10316219313d592fd1b7118bc4948d0dd2
[ "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
891
lean
/- Copyright (c) 2018 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau -/ import data.nat.sqrt namespace int /-- `sqrt n` is the square root of an integer `n`. If `n` is not a perfect square, and is positive, it returns the largest `k:ℤ` such that `k*k ≤ n`. If it is negative, it returns 0. For example, `sqrt 2 = 1` and `sqrt 1 = 1` and `sqrt (-1) = 0` -/ @[pp_nodot] def sqrt (n : ℤ) : ℤ := nat.sqrt $ int.to_nat n theorem sqrt_eq (n : ℤ) : sqrt (n*n) = n.nat_abs := by rw [sqrt, ← nat_abs_mul_self, to_nat_coe_nat, nat.sqrt_eq] theorem exists_mul_self (x : ℤ) : (∃ n, n * n = x) ↔ sqrt x * sqrt x = x := ⟨λ ⟨n, hn⟩, by rw [← hn, sqrt_eq, ← int.coe_nat_mul, nat_abs_mul_self], λ h, ⟨sqrt x, h⟩⟩ theorem sqrt_nonneg (n : ℤ) : 0 ≤ sqrt n := coe_nat_nonneg _ end int
0a5265a763966523d5a6b682327d5330504e4640
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/category_theory/limits/shapes/regular_mono.lean
b0329f2ef4fdfb94c17037167fe34912046541ba
[ "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
8,870
lean
/- Copyright (c) 2020 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.limits.shapes.pullbacks import category_theory.limits.shapes.strong_epi import category_theory.limits.shapes.equalizers /-! # Definitions and basic properties of regular monomorphisms and epimorphisms. A regular monomorphism is a morphism that is the equalizer of some parallel pair. We give the constructions * `split_mono → regular_mono` and * `regular_mono → mono` as well as the dual constructions for regular epimorphisms. Additionally, we give the construction * `regular_epi ⟶ strong_epi`. -/ noncomputable theory namespace category_theory open category_theory.limits universes v₁ u₁ u₂ variables {C : Type u₁} [category.{v₁} C] variables {X Y : C} /-- A regular monomorphism is a morphism which is the equalizer of some parallel pair. -/ class regular_mono (f : X ⟶ Y) := (Z : C) (left right : Y ⟶ Z) (w : f ≫ left = f ≫ right) (is_limit : is_limit (fork.of_ι f w)) attribute [reassoc] regular_mono.w /-- Every regular monomorphism is a monomorphism. -/ @[priority 100] instance regular_mono.mono (f : X ⟶ Y) [regular_mono f] : mono f := mono_of_is_limit_parallel_pair regular_mono.is_limit instance equalizer_regular (g h : X ⟶ Y) [has_limit (parallel_pair g h)] : regular_mono (equalizer.ι g h) := { Z := Y, left := g, right := h, w := equalizer.condition g h, is_limit := fork.is_limit.mk _ (λ s, limit.lift _ s) (by simp) (λ s m w, by { ext1, simp [←w] }) } /-- Every split monomorphism is a regular monomorphism. -/ @[priority 100] instance regular_mono.of_split_mono (f : X ⟶ Y) [split_mono f] : regular_mono f := { Z := Y, left := 𝟙 Y, right := retraction f ≫ f, w := by tidy, is_limit := split_mono_equalizes f } /-- If `f` is a regular mono, then any map `k : W ⟶ Y` equalizing `regular_mono.left` and `regular_mono.right` induces a morphism `l : W ⟶ X` such that `l ≫ f = k`. -/ def regular_mono.lift' {W : C} (f : X ⟶ Y) [regular_mono f] (k : W ⟶ Y) (h : k ≫ (regular_mono.left : Y ⟶ @regular_mono.Z _ _ _ _ f _) = k ≫ regular_mono.right) : {l : W ⟶ X // l ≫ f = k} := fork.is_limit.lift' regular_mono.is_limit _ h /-- The second leg of a pullback cone is a regular monomorphism if the right component is too. See also `pullback.snd_of_mono` for the basic monomorphism version, and `regular_of_is_pullback_fst_of_regular` for the flipped version. -/ def regular_of_is_pullback_snd_of_regular {P Q R S : C} {f : P ⟶ Q} {g : P ⟶ R} {h : Q ⟶ S} {k : R ⟶ S} [hr : regular_mono h] (comm : f ≫ h = g ≫ k) (t : is_limit (pullback_cone.mk _ _ comm)) : regular_mono g := { Z := hr.Z, left := k ≫ hr.left, right := k ≫ hr.right, w := by rw [← reassoc_of comm, ← reassoc_of comm, hr.w], is_limit := begin apply fork.is_limit.mk' _ _, intro s, have l₁ : (fork.ι s ≫ k) ≫ regular_mono.left = (fork.ι s ≫ k) ≫ regular_mono.right, rw [category.assoc, s.condition, category.assoc], obtain ⟨l, hl⟩ := fork.is_limit.lift' hr.is_limit _ l₁, obtain ⟨p, hp₁, hp₂⟩ := pullback_cone.is_limit.lift' t _ _ hl, refine ⟨p, hp₂, _⟩, intros m w, have z : m ≫ g = p ≫ g := w.trans hp₂.symm, apply t.hom_ext, apply (pullback_cone.mk f g comm).equalizer_ext, { erw [← cancel_mono h, category.assoc, category.assoc, comm, reassoc_of z] }, { exact z }, end } /-- The first leg of a pullback cone is a regular monomorphism if the left component is too. See also `pullback.fst_of_mono` for the basic monomorphism version, and `regular_of_is_pullback_snd_of_regular` for the flipped version. -/ def regular_of_is_pullback_fst_of_regular {P Q R S : C} {f : P ⟶ Q} {g : P ⟶ R} {h : Q ⟶ S} {k : R ⟶ S} [hr : regular_mono k] (comm : f ≫ h = g ≫ k) (t : is_limit (pullback_cone.mk _ _ comm)) : regular_mono f := regular_of_is_pullback_snd_of_regular comm.symm (pullback_cone.flip_is_limit t) @[priority 100] instance strong_mono_of_regular_mono (f : X ⟶ Y) [regular_mono f] : strong_mono f := { mono := by apply_instance, has_lift := begin introsI, have : v ≫ (regular_mono.left : Y ⟶ regular_mono.Z f) = v ≫ regular_mono.right, { apply (cancel_epi z).1, simp only [regular_mono.w, ← reassoc_of h] }, obtain ⟨t, ht⟩ := regular_mono.lift' _ _ this, refine arrow.has_lift.mk ⟨t, (cancel_mono f).1 _, ht⟩, simp only [arrow.mk_hom, arrow.hom_mk'_left, category.assoc, ht, h] end } /-- A regular monomorphism is an isomorphism if it is an epimorphism. -/ lemma is_iso_of_regular_mono_of_epi (f : X ⟶ Y) [regular_mono f] [e : epi f] : is_iso f := is_iso_of_epi_of_strong_mono _ /-- A regular epimorphism is a morphism which is the coequalizer of some parallel pair. -/ class regular_epi (f : X ⟶ Y) := (W : C) (left right : W ⟶ X) (w : left ≫ f = right ≫ f) (is_colimit : is_colimit (cofork.of_π f w)) attribute [reassoc] regular_epi.w /-- Every regular epimorphism is an epimorphism. -/ @[priority 100] instance regular_epi.epi (f : X ⟶ Y) [regular_epi f] : epi f := epi_of_is_colimit_parallel_pair regular_epi.is_colimit instance coequalizer_regular (g h : X ⟶ Y) [has_colimit (parallel_pair g h)] : regular_epi (coequalizer.π g h) := { W := X, left := g, right := h, w := coequalizer.condition g h, is_colimit := cofork.is_colimit.mk _ (λ s, colimit.desc _ s) (by simp) (λ s m w, by { ext1, simp [←w] }) } /-- Every split epimorphism is a regular epimorphism. -/ @[priority 100] instance regular_epi.of_split_epi (f : X ⟶ Y) [split_epi f] : regular_epi f := { W := X, left := 𝟙 X, right := f ≫ section_ f, w := by tidy, is_colimit := split_epi_coequalizes f } /-- If `f` is a regular epi, then every morphism `k : X ⟶ W` coequalizing `regular_epi.left` and `regular_epi.right` induces `l : Y ⟶ W` such that `f ≫ l = k`. -/ def regular_epi.desc' {W : C} (f : X ⟶ Y) [regular_epi f] (k : X ⟶ W) (h : (regular_epi.left : regular_epi.W f ⟶ X) ≫ k = regular_epi.right ≫ k) : {l : Y ⟶ W // f ≫ l = k} := cofork.is_colimit.desc' (regular_epi.is_colimit) _ h /-- The second leg of a pushout cocone is a regular epimorphism if the right component is too. See also `pushout.snd_of_epi` for the basic epimorphism version, and `regular_of_is_pushout_fst_of_regular` for the flipped version. -/ def regular_of_is_pushout_snd_of_regular {P Q R S : C} {f : P ⟶ Q} {g : P ⟶ R} {h : Q ⟶ S} {k : R ⟶ S} [gr : regular_epi g] (comm : f ≫ h = g ≫ k) (t : is_colimit (pushout_cocone.mk _ _ comm)) : regular_epi h := { W := gr.W, left := gr.left ≫ f, right := gr.right ≫ f, w := by rw [category.assoc, category.assoc, comm, reassoc_of gr.w], is_colimit := begin apply cofork.is_colimit.mk' _ _, intro s, have l₁ : gr.left ≫ f ≫ s.π = gr.right ≫ f ≫ s.π, rw [← category.assoc, ← category.assoc, s.condition], obtain ⟨l, hl⟩ := cofork.is_colimit.desc' gr.is_colimit (f ≫ cofork.π s) l₁, obtain ⟨p, hp₁, hp₂⟩ := pushout_cocone.is_colimit.desc' t _ _ hl.symm, refine ⟨p, hp₁, _⟩, intros m w, have z := w.trans hp₁.symm, apply t.hom_ext, apply (pushout_cocone.mk _ _ comm).coequalizer_ext, { exact z }, { erw [← cancel_epi g, ← reassoc_of comm, ← reassoc_of comm, z], refl }, end } /-- The first leg of a pushout cocone is a regular epimorphism if the left component is too. See also `pushout.fst_of_epi` for the basic epimorphism version, and `regular_of_is_pushout_snd_of_regular` for the flipped version. -/ def regular_of_is_pushout_fst_of_regular {P Q R S : C} {f : P ⟶ Q} {g : P ⟶ R} {h : Q ⟶ S} {k : R ⟶ S} [fr : regular_epi f] (comm : f ≫ h = g ≫ k) (t : is_colimit (pushout_cocone.mk _ _ comm)) : regular_epi k := regular_of_is_pushout_snd_of_regular comm.symm (pushout_cocone.flip_is_colimit t) @[priority 100] instance strong_epi_of_regular_epi (f : X ⟶ Y) [regular_epi f] : strong_epi f := { epi := by apply_instance, has_lift := begin introsI, have : (regular_epi.left : regular_epi.W f ⟶ X) ≫ u = regular_epi.right ≫ u, { apply (cancel_mono z).1, simp only [category.assoc, h, regular_epi.w_assoc] }, obtain ⟨t, ht⟩ := regular_epi.desc' f u this, exact arrow.has_lift.mk ⟨t, ht, (cancel_epi f).1 (by simp only [←category.assoc, ht, ←h, arrow.mk_hom, arrow.hom_mk'_right])⟩, end } /-- A regular epimorphism is an isomorphism if it is a monomorphism. -/ lemma is_iso_of_regular_epi_of_mono (f : X ⟶ Y) [regular_epi f] [m : mono f] : is_iso f := is_iso_of_mono_of_strong_epi _ end category_theory
99e3e8407ae6a5df05bb27a5b4a95c2feea3d5da
59a4b050600ed7b3d5826a8478db0a9bdc190252
/src/category_theory/equivalence/characterisation.lean
fd9dfc339e4f2574b2c86689d8fc0f42da7cb75a
[]
no_license
rwbarton/lean-category-theory
f720268d800b62a25d69842ca7b5d27822f00652
00df814d463406b7a13a56f5dcda67758ba1b419
refs/heads/master
1,585,366,296,767
1,536,151,349,000
1,536,151,349,000
147,652,096
0
0
null
1,536,226,960,000
1,536,226,960,000
null
UTF-8
Lean
false
false
2,705
lean
-- Copyright (c) 2017 Scott Morrison. All rights reserved. -- Released under Apache 2.0 license as described in the file LICENSE. -- Authors: Tim Baumann, Stephen Morgan, Scott Morrison import category_theory.equivalence import category_theory.natural_isomorphism open category_theory namespace category_theory.equivalence universes u₁ u₂ variables {C : Type (u₁+1)} [large_category C] {D : Type (u₂+1)} [large_category D] def Equivalences_are_EssentiallySurjective (e : Equivalence C D) : ess_surj (e.functor) := ⟨ λ Y : D, e.inverse Y, λ Y : D, (e.isomorphism_2 Y) ⟩ lemma Equivalences_are_Faithful (e : Equivalence C D) : faithful (e.functor) := { injectivity' := λ X Y f g w, begin have p := congr_arg (@category_theory.functor.map _ _ _ _ e.inverse _ _) w, simp at p, exact p end }. def Equivalences_are_Full (e : Equivalence C D) : full (e.functor) := { preimage := λ X Y f, (e.isomorphism_1 X).inv ≫ (e.inverse.map f) ≫ (e.isomorphism_1 Y).hom, witness' := λ X Y f, begin apply (Equivalences_are_Faithful e.symm).injectivity', obviously, end } section private meta def faithfulness := `[apply faithful.injectivity'] local attribute [tidy] faithfulness -- FIXME improve API for ess_surj def Fully_Faithful_EssentiallySurjective_Functor_inverse (F : C ⥤ D) [full F] [faithful : faithful F] [es : ess_surj F] : D ⥤ C := { obj := λ X, (ess_surj.pre.{u₁+1 u₁} F X), map' := λ X Y f, preimage F ((ess_surj.iso.{u₁+1 u₁} F X).hom ≫ f ≫ (ess_surj.iso.{u₁+1 u₁} F Y).inv) } -- FIXME pure boilerplate... @[simp] lemma Fully_Faithful_EssentiallySurjective_Functor_inverse_map (F : C ⥤ D) [full F] [faithful : faithful F] [es : ess_surj F] {X Y : D} (f : X ⟶ Y) : (Fully_Faithful_EssentiallySurjective_Functor_inverse F).map f = preimage F ((ess_surj.iso.{u₁+1 u₁} F X).hom ≫ f ≫ (ess_surj.iso.{u₁+1 u₁} F Y).inv) := rfl def Fully_Faithful_EssentiallySurjective_Functor_is_Equivalence (F : C ⥤ D) [full F] [faithful : faithful F] [es : ess_surj F] : is_Equivalence F := { inverse := Fully_Faithful_EssentiallySurjective_Functor_inverse F, isomorphism_1' := nat_iso.from_components (λ X, preimage_iso (ess_surj.iso F (F X))) (by obviously), isomorphism_2' := nat_iso.from_components (λ Y, (ess_surj.iso F Y)) (by obviously) } end -- TODO instance (F : C ⥤ D) [is_Equivalence F] : full F := sorry instance (F : C ⥤ D) [is_Equivalence F] : faithful F := sorry end category_theory.equivalence
62c3a0fca9b6dda377e394418bac26d51da52162
df561f413cfe0a88b1056655515399c546ff32a5
/3-multiplication-world/l6.lean
ba0be9fa5a9e1215ab7f23d1adbc97a24e17703a
[]
no_license
nicholaspun/natural-number-game-solutions
31d5158415c6f582694680044c5c6469032c2a06
1e2aed86d2e76a3f4a275c6d99e795ad30cf6df0
refs/heads/main
1,675,123,625,012
1,607,633,548,000
1,607,633,548,000
318,933,860
3
1
null
null
null
null
UTF-8
Lean
false
false
214
lean
lemma succ_mul (a b : mynat) : succ a * b = a * b + b := begin induction b with k Pk, repeat { rw mul_zero }, rw add_zero, refl, repeat { rw mul_succ }, rw Pk, repeat { rw add_succ }, rw add_right_comm, refl, end
5c0c94ad8aff6c7456e1220a50889ef679b8d594
d1a52c3f208fa42c41df8278c3d280f075eb020c
/tests/lean/run/printDecls.lean
6685048aa67ba87848e9aa1f7a0160fad0f435d0
[ "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
840
lean
import Lean open Lean open Lean.Meta -- Return true if `declName` should be ignored def shouldIgnore (declName : Name) : Bool := declName.isInternal || match declName with | Name.str _ s _ => "match_".isPrefixOf s || "proof_".isPrefixOf s || "eq_".isPrefixOf s | _ => true -- Print declarations that have the given prefix. def printDecls (pre : Name) : MetaM Unit := do let cs := (← getEnv).constants cs.forM fun declName info => do if pre.isPrefixOf declName && !shouldIgnore declName then if let some docString ← findDocString? (← getEnv) declName then IO.println s!"/-- {docString} -/\n{declName} : {← ppExpr info.type}" else IO.println s!"{declName} : {← ppExpr info.type}" #eval printDecls `Array #eval printDecls `List #eval printDecls `Bool #eval printDecls `Lean.Elab
65579de14488ed7f7ac3e0028b6b972f50239828
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/data/matrix/char_p.lean
470feac66e832f758e44946bd884c4bf91fd1d73
[]
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
562
lean
/- Copyright (c) 2020 Aaron Anderson. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Aaron Anderson -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.data.matrix.basic import Mathlib.algebra.char_p.basic import Mathlib.PostPort universes u_1 u_2 namespace Mathlib /-! # Matrices in prime characteristic -/ protected instance matrix.char_p {n : Type u_1} [fintype n] {R : Type u_2} [ring R] [DecidableEq n] [Nonempty n] (p : ℕ) [char_p R p] : char_p (matrix n n R) p := sorry
fd25becf6233cb73e5aaaaae041dbce947677ccb
b7f22e51856f4989b970961f794f1c435f9b8f78
/hott/init/equiv.hlean
e3ac361c2b0b05cbf8f7dc0cbe84a99d5d87c6b2
[ "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
18,013
hlean
/- Copyright (c) 2014 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Jeremy Avigad, Jakob von Raumer, Floris van Doorn Ported from Coq HoTT -/ prelude import .path .function open eq function lift /- Equivalences -/ -- This is our definition of equivalence. In the HoTT-book it's called -- ihae (half-adjoint equivalence). structure is_equiv [class] {A B : Type} (f : A → B) := mk' :: (inv : B → A) (right_inv : Πb, f (inv b) = b) (left_inv : Πa, inv (f a) = a) (adj : Πx, right_inv (f x) = ap f (left_inv x)) attribute is_equiv.inv [reducible] -- A more bundled version of equivalence structure equiv (A B : Type) := (to_fun : A → B) (to_is_equiv : is_equiv to_fun) namespace is_equiv /- Some instances and closure properties of equivalences -/ postfix ⁻¹ := inv /- a second notation for the inverse, which is not overloaded -/ postfix [parsing_only] `⁻¹ᶠ`:std.prec.max_plus := inv section variables {A B C : Type} (g : B → C) (f : A → B) {f' : A → B} -- The variant of mk' where f is explicit. protected abbreviation mk [constructor] := @is_equiv.mk' A B f -- The identity function is an equivalence. definition is_equiv_id [instance] [constructor] (A : Type) : (is_equiv (id : A → A)) := is_equiv.mk id id (λa, idp) (λa, idp) (λa, idp) -- The composition of two equivalences is, again, an equivalence. definition is_equiv_compose [constructor] [Hf : is_equiv f] [Hg : is_equiv g] : is_equiv (g ∘ f) := is_equiv.mk (g ∘ f) (f⁻¹ ∘ g⁻¹) abstract (λc, ap g (right_inv f (g⁻¹ c)) ⬝ right_inv g c) end abstract (λa, ap (inv f) (left_inv g (f a)) ⬝ left_inv f a) end abstract (λa, (whisker_left _ (adj g (f a))) ⬝ (ap_con g _ _)⁻¹ ⬝ ap02 g ((ap_con_eq_con (right_inv f) (left_inv g (f a)))⁻¹ ⬝ (ap_compose f (inv f) _ ◾ adj f a) ⬝ (ap_con f _ _)⁻¹ ) ⬝ (ap_compose g f _)⁻¹) end -- Any function equal to an equivalence is an equivlance as well. variable {f} definition is_equiv_eq_closed [Hf : is_equiv f] (Heq : f = f') : is_equiv f' := eq.rec_on Heq Hf end section parameters {A B : Type} (f : A → B) (g : B → A) (ret : Πb, f (g b) = b) (sec : Πa, g (f a) = a) definition adjointify_left_inv' [unfold_full] (a : A) : g (f a) = a := ap g (ap f (inverse (sec a))) ⬝ ap g (ret (f a)) ⬝ sec a theorem adjointify_adj' (a : A) : ret (f a) = ap f (adjointify_left_inv' a) := let fgretrfa := ap f (ap g (ret (f a))) in let fgfinvsect := ap f (ap g (ap f (sec a)⁻¹)) in let fgfa := f (g (f a)) in let retrfa := ret (f a) in have eq1 : ap f (sec a) = _, from calc ap f (sec a) = idp ⬝ ap f (sec a) : by rewrite idp_con ... = (ret (f a) ⬝ (ret (f a))⁻¹) ⬝ ap f (sec a) : by rewrite con.right_inv ... = ((ret fgfa)⁻¹ ⬝ ap (f ∘ g) (ret (f a))) ⬝ ap f (sec a) : by rewrite con_ap_eq_con ... = ((ret fgfa)⁻¹ ⬝ fgretrfa) ⬝ ap f (sec a) : by rewrite ap_compose ... = (ret fgfa)⁻¹ ⬝ (fgretrfa ⬝ ap f (sec a)) : by rewrite con.assoc, have eq2 : ap f (sec a) ⬝ idp = (ret fgfa)⁻¹ ⬝ (fgretrfa ⬝ ap f (sec a)), from !con_idp ⬝ eq1, have eq3 : idp = _, from calc idp = (ap f (sec a))⁻¹ ⬝ ((ret fgfa)⁻¹ ⬝ (fgretrfa ⬝ ap f (sec a))) : eq_inv_con_of_con_eq eq2 ... = ((ap f (sec a))⁻¹ ⬝ (ret fgfa)⁻¹) ⬝ (fgretrfa ⬝ ap f (sec a)) : by rewrite con.assoc' ... = (ap f (sec a)⁻¹ ⬝ (ret fgfa)⁻¹) ⬝ (fgretrfa ⬝ ap f (sec a)) : by rewrite ap_inv ... = ((ap f (sec a)⁻¹ ⬝ (ret fgfa)⁻¹) ⬝ fgretrfa) ⬝ ap f (sec a) : by rewrite con.assoc' ... = ((retrfa⁻¹ ⬝ ap (f ∘ g) (ap f (sec a)⁻¹)) ⬝ fgretrfa) ⬝ ap f (sec a) : by rewrite con_ap_eq_con ... = ((retrfa⁻¹ ⬝ fgfinvsect) ⬝ fgretrfa) ⬝ ap f (sec a) : by rewrite ap_compose ... = (retrfa⁻¹ ⬝ (fgfinvsect ⬝ fgretrfa)) ⬝ ap f (sec a) : by rewrite con.assoc' ... = retrfa⁻¹ ⬝ ap f (ap g (ap f (sec a)⁻¹) ⬝ ap g (ret (f a))) ⬝ ap f (sec a) : by rewrite ap_con ... = retrfa⁻¹ ⬝ (ap f (ap g (ap f (sec a)⁻¹) ⬝ ap g (ret (f a))) ⬝ ap f (sec a)) : by rewrite con.assoc' ... = retrfa⁻¹ ⬝ ap f ((ap g (ap f (sec a)⁻¹) ⬝ ap g (ret (f a))) ⬝ sec a) : by rewrite -ap_con, show ret (f a) = ap f ((ap g (ap f (sec a)⁻¹) ⬝ ap g (ret (f a))) ⬝ sec a), from eq_of_idp_eq_inv_con eq3 definition adjointify [constructor] : is_equiv f := is_equiv.mk f g ret adjointify_left_inv' adjointify_adj' end -- Any function pointwise equal to an equivalence is an equivalence as well. definition homotopy_closed [constructor] {A B : Type} (f : A → B) {f' : A → B} [Hf : is_equiv f] (Hty : f ~ f') : is_equiv f' := adjointify f' (inv f) (λ b, (Hty (inv f b))⁻¹ ⬝ right_inv f b) (λ a, (ap (inv f) (Hty a))⁻¹ ⬝ left_inv f a) definition inv_homotopy_closed [constructor] {A B : Type} {f : A → B} {f' : B → A} [Hf : is_equiv f] (Hty : f⁻¹ ~ f') : is_equiv f := adjointify f f' (λ b, ap f !Hty⁻¹ ⬝ right_inv f b) (λ a, !Hty⁻¹ ⬝ left_inv f a) definition is_equiv_up [instance] [constructor] (A : Type) : is_equiv (up : A → lift A) := adjointify up down (λa, by induction a;reflexivity) (λa, idp) section variables {A B C : Type} (f : A → B) {f' : A → B} [Hf : is_equiv f] (g : B → C) include Hf --The inverse of an equivalence is, again, an equivalence. definition is_equiv_inv [instance] [constructor] : is_equiv f⁻¹ := adjointify f⁻¹ f (left_inv f) (right_inv f) -- The 2-out-of-3 properties definition cancel_right (g : B → C) [Hgf : is_equiv (g ∘ f)] : (is_equiv g) := have Hfinv : is_equiv f⁻¹, from is_equiv_inv f, @homotopy_closed _ _ _ _ (is_equiv_compose (g ∘ f) f⁻¹) (λb, ap g (@right_inv _ _ f _ b)) definition cancel_left (g : C → A) [Hgf : is_equiv (f ∘ g)] : (is_equiv g) := have Hfinv : is_equiv f⁻¹, from is_equiv_inv f, @homotopy_closed _ _ _ _ (is_equiv_compose f⁻¹ (f ∘ g)) (λa, left_inv f (g a)) definition eq_of_fn_eq_fn' {x y : A} (q : f x = f y) : x = y := (left_inv f x)⁻¹ ⬝ ap f⁻¹ q ⬝ left_inv f y definition ap_eq_of_fn_eq_fn' {x y : A} (q : f x = f y) : ap f (eq_of_fn_eq_fn' f q) = q := !ap_con ⬝ whisker_right !ap_con _ ⬝ ((!ap_inv ⬝ inverse2 (adj f _)⁻¹) ◾ (inverse (ap_compose f f⁻¹ _)) ◾ (adj f _)⁻¹) ⬝ con_ap_con_eq_con_con (right_inv f) _ _ ⬝ whisker_right !con.left_inv _ ⬝ !idp_con definition eq_of_fn_eq_fn'_ap {x y : A} (q : x = y) : eq_of_fn_eq_fn' f (ap f q) = q := by induction q; apply con.left_inv definition is_equiv_ap [instance] [constructor] (x y : A) : is_equiv (ap f : x = y → f x = f y) := adjointify (ap f) (eq_of_fn_eq_fn' f) (ap_eq_of_fn_eq_fn' f) (eq_of_fn_eq_fn'_ap f) -- The function equiv_rect says that given an equivalence f : A → B, -- and a hypothesis from B, one may always assume that the hypothesis -- is in the image of e. -- In fibrational terms, if we have a fibration over B which has a section -- once pulled back along an equivalence f : A → B, then it has a section -- over all of B. definition is_equiv_rect (P : B → Type) (g : Πa, P (f a)) (b : B) : P b := right_inv f b ▸ g (f⁻¹ b) definition is_equiv_rect' (P : A → B → Type) (g : Πb, P (f⁻¹ b) b) (a : A) : P a (f a) := left_inv f a ▸ g (f a) definition is_equiv_rect_comp (P : B → Type) (df : Π (x : A), P (f x)) (x : A) : is_equiv_rect f P df (f x) = df x := calc is_equiv_rect f P df (f x) = right_inv f (f x) ▸ df (f⁻¹ (f x)) : by esimp ... = ap f (left_inv f x) ▸ df (f⁻¹ (f x)) : by rewrite -adj ... = left_inv f x ▸ df (f⁻¹ (f x)) : by rewrite -tr_compose ... = df x : by rewrite (apdt df (left_inv f x)) theorem adj_inv (b : B) : left_inv f (f⁻¹ b) = ap f⁻¹ (right_inv f b) := is_equiv_rect f _ (λa, eq.cancel_right (left_inv f (id a)) (whisker_left _ !ap_id⁻¹ ⬝ (ap_con_eq_con_ap (left_inv f) (left_inv f a))⁻¹) ⬝ !ap_compose ⬝ ap02 f⁻¹ (adj f a)⁻¹) b end section variables {A B C : Type} {f : A → B} [Hf : is_equiv f] include Hf section rewrite_rules variables {a : A} {b : B} definition eq_of_eq_inv (p : a = f⁻¹ b) : f a = b := ap f p ⬝ right_inv f b definition eq_of_inv_eq (p : f⁻¹ b = a) : b = f a := (eq_of_eq_inv p⁻¹)⁻¹ definition inv_eq_of_eq (p : b = f a) : f⁻¹ b = a := ap f⁻¹ p ⬝ left_inv f a definition eq_inv_of_eq (p : f a = b) : a = f⁻¹ b := (inv_eq_of_eq p⁻¹)⁻¹ end rewrite_rules variable (f) section pre_compose variables (α : A → C) (β : B → C) definition homotopy_of_homotopy_inv_pre (p : β ~ α ∘ f⁻¹) : β ∘ f ~ α := λ a, p (f a) ⬝ ap α (left_inv f a) definition homotopy_of_inv_homotopy_pre (p : α ∘ f⁻¹ ~ β) : α ~ β ∘ f := λ a, (ap α (left_inv f a))⁻¹ ⬝ p (f a) definition inv_homotopy_of_homotopy_pre (p : α ~ β ∘ f) : α ∘ f⁻¹ ~ β := λ b, p (f⁻¹ b) ⬝ ap β (right_inv f b) definition homotopy_inv_of_homotopy_pre (p : β ∘ f ~ α) : β ~ α ∘ f⁻¹ := λ b, (ap β (right_inv f b))⁻¹ ⬝ p (f⁻¹ b) end pre_compose section post_compose variables (α : C → A) (β : C → B) definition homotopy_of_homotopy_inv_post (p : α ~ f⁻¹ ∘ β) : f ∘ α ~ β := λ c, ap f (p c) ⬝ (right_inv f (β c)) definition homotopy_of_inv_homotopy_post (p : f⁻¹ ∘ β ~ α) : β ~ f ∘ α := λ c, (right_inv f (β c))⁻¹ ⬝ ap f (p c) definition inv_homotopy_of_homotopy_post (p : β ~ f ∘ α) : f⁻¹ ∘ β ~ α := λ c, ap f⁻¹ (p c) ⬝ (left_inv f (α c)) definition homotopy_inv_of_homotopy_post (p : f ∘ α ~ β) : α ~ f⁻¹ ∘ β := λ c, (left_inv f (α c))⁻¹ ⬝ ap f⁻¹ (p c) end post_compose end --Transporting is an equivalence definition is_equiv_tr [constructor] {A : Type} (P : A → Type) {x y : A} (p : x = y) : (is_equiv (transport P p)) := is_equiv.mk _ (transport P p⁻¹) (tr_inv_tr p) (inv_tr_tr p) (tr_inv_tr_lemma p) -- a version where the transport is a cast. Note: A and B live in the same universe here. definition is_equiv_cast [constructor] {A B : Type} (H : A = B) : is_equiv (cast H) := is_equiv_tr (λX, X) H section variables {A : Type} {B C : A → Type} (f : Π{a}, B a → C a) [H : Πa, is_equiv (@f a)] {g : A → A} {g' : A → A} (h : Π{a}, B (g' a) → B (g a)) (h' : Π{a}, C (g' a) → C (g a)) include H definition inv_commute' (p : Π⦃a : A⦄ (b : B (g' a)), f (h b) = h' (f b)) {a : A} (c : C (g' a)) : f⁻¹ (h' c) = h (f⁻¹ c) := eq_of_fn_eq_fn' f (right_inv f (h' c) ⬝ ap h' (right_inv f c)⁻¹ ⬝ (p (f⁻¹ c))⁻¹) definition fun_commute_of_inv_commute' (p : Π⦃a : A⦄ (c : C (g' a)), f⁻¹ (h' c) = h (f⁻¹ c)) {a : A} (b : B (g' a)) : f (h b) = h' (f b) := eq_of_fn_eq_fn' f⁻¹ (left_inv f (h b) ⬝ ap h (left_inv f b)⁻¹ ⬝ (p (f b))⁻¹) definition ap_inv_commute' (p : Π⦃a : A⦄ (b : B (g' a)), f (h b) = h' (f b)) {a : A} (c : C (g' a)) : ap f (inv_commute' @f @h @h' p c) = right_inv f (h' c) ⬝ ap h' (right_inv f c)⁻¹ ⬝ (p (f⁻¹ c))⁻¹ := !ap_eq_of_fn_eq_fn' -- inv_commute'_fn is in types.equiv end -- This is inv_commute' for A ≡ unit definition inv_commute1' {B C : Type} (f : B → C) [is_equiv f] (h : B → B) (h' : C → C) (p : Π(b : B), f (h b) = h' (f b)) (c : C) : f⁻¹ (h' c) = h (f⁻¹ c) := eq_of_fn_eq_fn' f (right_inv f (h' c) ⬝ ap h' (right_inv f c)⁻¹ ⬝ (p (f⁻¹ c))⁻¹) end is_equiv open is_equiv namespace eq local attribute is_equiv_tr [instance] definition tr_inv_fn {A : Type} {B : A → Type} {a a' : A} (p : a = a') : transport B p⁻¹ = (transport B p)⁻¹ := idp definition tr_inv {A : Type} {B : A → Type} {a a' : A} (p : a = a') (b : B a') : p⁻¹ ▸ b = (transport B p)⁻¹ b := idp definition cast_inv_fn {A B : Type} (p : A = B) : cast p⁻¹ = (cast p)⁻¹ := idp definition cast_inv {A B : Type} (p : A = B) (b : B) : cast p⁻¹ b = (cast p)⁻¹ b := idp end eq infix ` ≃ `:25 := equiv attribute equiv.to_is_equiv [instance] namespace equiv attribute to_fun [coercion] section variables {A B C : Type} protected definition MK [reducible] [constructor] (f : A → B) (g : B → A) (right_inv : Πb, f (g b) = b) (left_inv : Πa, g (f a) = a) : A ≃ B := equiv.mk f (adjointify f g right_inv left_inv) definition to_inv [reducible] [unfold 3] (f : A ≃ B) : B → A := f⁻¹ definition to_right_inv [reducible] [unfold 3] (f : A ≃ B) (b : B) : f (f⁻¹ b) = b := right_inv f b definition to_left_inv [reducible] [unfold 3] (f : A ≃ B) (a : A) : f⁻¹ (f a) = a := left_inv f a protected definition rfl [refl] [constructor] : A ≃ A := equiv.mk id !is_equiv_id protected definition refl [constructor] [reducible] (A : Type) : A ≃ A := @equiv.rfl A protected definition symm [symm] [constructor] (f : A ≃ B) : B ≃ A := equiv.mk f⁻¹ !is_equiv_inv protected definition trans [trans] [constructor] (f : A ≃ B) (g : B ≃ C) : A ≃ C := equiv.mk (g ∘ f) !is_equiv_compose infixl ` ⬝e `:75 := equiv.trans postfix `⁻¹ᵉ`:(max + 1) := equiv.symm -- notation for inverse which is not overloaded abbreviation erfl [constructor] := @equiv.rfl definition to_inv_trans [reducible] [unfold_full] (f : A ≃ B) (g : B ≃ C) : to_inv (f ⬝e g) = to_fun (g⁻¹ᵉ ⬝e f⁻¹ᵉ) := idp definition equiv_change_fun [constructor] (f : A ≃ B) {f' : A → B} (Heq : f ~ f') : A ≃ B := equiv.mk f' (is_equiv.homotopy_closed f Heq) definition equiv_change_inv [constructor] (f : A ≃ B) {f' : B → A} (Heq : f⁻¹ ~ f') : A ≃ B := equiv.mk f (inv_homotopy_closed Heq) --rename: eq_equiv_fn_eq_of_is_equiv definition eq_equiv_fn_eq [constructor] (f : A → B) [H : is_equiv f] (a b : A) : (a = b) ≃ (f a = f b) := equiv.mk (ap f) !is_equiv_ap --rename: eq_equiv_fn_eq definition eq_equiv_fn_eq_of_equiv [constructor] (f : A ≃ B) (a b : A) : (a = b) ≃ (f a = f b) := equiv.mk (ap f) !is_equiv_ap definition equiv_ap [constructor] (P : A → Type) {a b : A} (p : a = b) : P a ≃ P b := equiv.mk (transport P p) !is_equiv_tr definition equiv_of_eq [constructor] {A B : Type} (p : A = B) : A ≃ B := equiv.mk (cast p) !is_equiv_tr definition equiv_of_eq_refl [reducible] [unfold_full] (A : Type) : equiv_of_eq (refl A) = equiv.refl A := idp definition eq_of_fn_eq_fn (f : A ≃ B) {x y : A} (q : f x = f y) : x = y := (left_inv f x)⁻¹ ⬝ ap f⁻¹ q ⬝ left_inv f y definition eq_of_fn_eq_fn_inv (f : A ≃ B) {x y : B} (q : f⁻¹ x = f⁻¹ y) : x = y := (right_inv f x)⁻¹ ⬝ ap f q ⬝ right_inv f y --we need this theorem for the funext_of_ua proof theorem inv_eq {A B : Type} (eqf eqg : A ≃ B) (p : eqf = eqg) : (to_fun eqf)⁻¹ = (to_fun eqg)⁻¹ := eq.rec_on p idp definition equiv_of_equiv_of_eq [trans] {A B C : Type} (p : A = B) (q : B ≃ C) : A ≃ C := equiv_of_eq p ⬝e q definition equiv_of_eq_of_equiv [trans] {A B C : Type} (p : A ≃ B) (q : B = C) : A ≃ C := p ⬝e equiv_of_eq q definition equiv_lift [constructor] (A : Type) : A ≃ lift A := equiv.mk up _ definition equiv_rect (f : A ≃ B) (P : B → Type) (g : Πa, P (f a)) (b : B) : P b := right_inv f b ▸ g (f⁻¹ b) definition equiv_rect' (f : A ≃ B) (P : A → B → Type) (g : Πb, P (f⁻¹ b) b) (a : A) : P a (f a) := left_inv f a ▸ g (f a) definition equiv_rect_comp (f : A ≃ B) (P : B → Type) (df : Π (x : A), P (f x)) (x : A) : equiv_rect f P df (f x) = df x := calc equiv_rect f P df (f x) = right_inv f (f x) ▸ df (f⁻¹ (f x)) : by esimp ... = ap f (left_inv f x) ▸ df (f⁻¹ (f x)) : by rewrite -adj ... = left_inv f x ▸ df (f⁻¹ (f x)) : by rewrite -tr_compose ... = df x : by rewrite (apdt df (left_inv f x)) end section variables {A : Type} {B C : A → Type} (f : Π{a}, B a ≃ C a) {g : A → A} {g' : A → A} (h : Π{a}, B (g' a) → B (g a)) (h' : Π{a}, C (g' a) → C (g a)) definition inv_commute (p : Π⦃a : A⦄ (b : B (g' a)), f (h b) = h' (f b)) {a : A} (c : C (g' a)) : f⁻¹ (h' c) = h (f⁻¹ c) := inv_commute' @f @h @h' p c definition fun_commute_of_inv_commute (p : Π⦃a : A⦄ (c : C (g' a)), f⁻¹ (h' c) = h (f⁻¹ c)) {a : A} (b : B (g' a)) : f (h b) = h' (f b) := fun_commute_of_inv_commute' @f @h @h' p b definition inv_commute1 {B C : Type} (f : B ≃ C) (h : B → B) (h' : C → C) (p : Π(b : B), f (h b) = h' (f b)) (c : C) : f⁻¹ (h' c) = h (f⁻¹ c) := inv_commute1' (to_fun f) h h' p c end infixl ` ⬝pe `:75 := equiv_of_equiv_of_eq infixl ` ⬝ep `:75 := equiv_of_eq_of_equiv end equiv open equiv namespace is_equiv definition is_equiv_of_equiv_of_homotopy [constructor] {A B : Type} (f : A ≃ B) {f' : A → B} (Hty : f ~ f') : is_equiv f' := homotopy_closed f Hty end is_equiv export [unfold] equiv export [unfold] is_equiv
e27037ec5adc56114593ec9493d1b850cc95f9eb
32025d5c2d6e33ad3b6dd8a3c91e1e838066a7f7
/tests/lean/protected.lean
20692cca8d51e3cf263f25f822f6c1c5a0a4e3cc
[ "Apache-2.0" ]
permissive
walterhu1015/lean4
b2c71b688975177402758924eaa513475ed6ce72
2214d81e84646a905d0b20b032c89caf89c737ad
refs/heads/master
1,671,342,096,906
1,599,695,985,000
1,599,695,985,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
276
lean
new_frontend namespace Foo protected def x := 10 end Foo open Foo #check x -- error unknown identifier `x` #check Foo.x namespace Bla.Foo protected def y := 20 def z := 30 end Bla.Foo open Bla #check Foo.y open Bla.Foo #check y -- error unknown identifier `y` #check z
58cd638d2983d21315e8bf853c9ce1012b37287e
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/probability/martingale/basic.lean
e4cb7613f4d6f76eac993acdff56f0d06b5bbf76
[ "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
24,994
lean
/- Copyright (c) 2021 Rémy Degenne. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Rémy Degenne, Kexing Ying -/ import probability.notation import probability.process.stopping /-! # Martingales > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. A family of functions `f : ι → Ω → E` is a martingale with respect to a filtration `ℱ` if every `f i` is integrable, `f` is adapted with respect to `ℱ` and for all `i ≤ j`, `μ[f j | ℱ i] =ᵐ[μ] f i`. On the other hand, `f : ι → Ω → E` is said to be a supermartingale with respect to the filtration `ℱ` if `f i` is integrable, `f` is adapted with resepct to `ℱ` and for all `i ≤ j`, `μ[f j | ℱ i] ≤ᵐ[μ] f i`. Finally, `f : ι → Ω → E` is said to be a submartingale with respect to the filtration `ℱ` if `f i` is integrable, `f` is adapted with resepct to `ℱ` and for all `i ≤ j`, `f i ≤ᵐ[μ] μ[f j | ℱ i]`. The definitions of filtration and adapted can be found in `probability.stopping`. ### Definitions * `measure_theory.martingale f ℱ μ`: `f` is a martingale with respect to filtration `ℱ` and measure `μ`. * `measure_theory.supermartingale f ℱ μ`: `f` is a supermartingale with respect to filtration `ℱ` and measure `μ`. * `measure_theory.submartingale f ℱ μ`: `f` is a submartingale with respect to filtration `ℱ` and measure `μ`. ### Results * `measure_theory.martingale_condexp f ℱ μ`: the sequence `λ i, μ[f | ℱ i, ℱ.le i])` is a martingale with respect to `ℱ` and `μ`. -/ open topological_space filter open_locale nnreal ennreal measure_theory probability_theory big_operators namespace measure_theory variables {Ω E ι : Type*} [preorder ι] {m0 : measurable_space Ω} {μ : measure Ω} [normed_add_comm_group E] [normed_space ℝ E] [complete_space E] {f g : ι → Ω → E} {ℱ : filtration ι m0} /-- A family of functions `f : ι → Ω → E` is a martingale with respect to a filtration `ℱ` if `f` is adapted with respect to `ℱ` and for all `i ≤ j`, `μ[f j | ℱ i] =ᵐ[μ] f i`. -/ def martingale (f : ι → Ω → E) (ℱ : filtration ι m0) (μ : measure Ω . volume_tac) : Prop := adapted ℱ f ∧ ∀ i j, i ≤ j → μ[f j | ℱ i] =ᵐ[μ] f i /-- A family of integrable functions `f : ι → Ω → E` is a supermartingale with respect to a filtration `ℱ` if `f` is adapted with respect to `ℱ` and for all `i ≤ j`, `μ[f j | ℱ.le i] ≤ᵐ[μ] f i`. -/ def supermartingale [has_le E] (f : ι → Ω → E) (ℱ : filtration ι m0) (μ : measure Ω . volume_tac) : Prop := adapted ℱ f ∧ (∀ i j, i ≤ j → μ[f j | ℱ i] ≤ᵐ[μ] f i) ∧ ∀ i, integrable (f i) μ /-- A family of integrable functions `f : ι → Ω → E` is a submartingale with respect to a filtration `ℱ` if `f` is adapted with respect to `ℱ` and for all `i ≤ j`, `f i ≤ᵐ[μ] μ[f j | ℱ.le i]`. -/ def submartingale [has_le E] (f : ι → Ω → E) (ℱ : filtration ι m0) (μ : measure Ω . volume_tac) : Prop := adapted ℱ f ∧ (∀ i j, i ≤ j → f i ≤ᵐ[μ] μ[f j | ℱ i]) ∧ ∀ i, integrable (f i) μ lemma martingale_const (ℱ : filtration ι m0) (μ : measure Ω) [is_finite_measure μ] (x : E) : martingale (λ _ _, x) ℱ μ := ⟨adapted_const ℱ _, λ i j hij, by rw condexp_const (ℱ.le _)⟩ lemma martingale_const_fun [order_bot ι] (ℱ : filtration ι m0) (μ : measure Ω) [is_finite_measure μ] {f : Ω → E} (hf : strongly_measurable[ℱ ⊥] f) (hfint : integrable f μ) : martingale (λ _, f) ℱ μ := begin refine ⟨λ i, hf.mono $ ℱ.mono bot_le, λ i j hij, _⟩, rw condexp_of_strongly_measurable (ℱ.le _) (hf.mono $ ℱ.mono bot_le) hfint, apply_instance, end variables (E) lemma martingale_zero (ℱ : filtration ι m0) (μ : measure Ω) : martingale (0 : ι → Ω → E) ℱ μ := ⟨adapted_zero E ℱ, λ i j hij, by { rw [pi.zero_apply, condexp_zero], simp, }⟩ variables {E} namespace martingale @[protected] lemma adapted (hf : martingale f ℱ μ) : adapted ℱ f := hf.1 @[protected] lemma strongly_measurable (hf : martingale f ℱ μ) (i : ι) : strongly_measurable[ℱ i] (f i) := hf.adapted i lemma condexp_ae_eq (hf : martingale f ℱ μ) {i j : ι} (hij : i ≤ j) : μ[f j | ℱ i] =ᵐ[μ] f i := hf.2 i j hij @[protected] lemma integrable (hf : martingale f ℱ μ) (i : ι) : integrable (f i) μ := integrable_condexp.congr (hf.condexp_ae_eq (le_refl i)) lemma set_integral_eq [sigma_finite_filtration μ ℱ] (hf : martingale f ℱ μ) {i j : ι} (hij : i ≤ j) {s : set Ω} (hs : measurable_set[ℱ i] s) : ∫ ω in s, f i ω ∂μ = ∫ ω in s, f j ω ∂μ := begin rw ← @set_integral_condexp _ _ _ _ _ (ℱ i) m0 _ _ _ (ℱ.le i) _ (hf.integrable j) hs, refine set_integral_congr_ae (ℱ.le i s hs) _, filter_upwards [hf.2 i j hij] with _ heq _ using heq.symm, end lemma add (hf : martingale f ℱ μ) (hg : martingale g ℱ μ) : martingale (f + g) ℱ μ := begin refine ⟨hf.adapted.add hg.adapted, λ i j hij, _⟩, exact (condexp_add (hf.integrable j) (hg.integrable j)).trans ((hf.2 i j hij).add (hg.2 i j hij)), end lemma neg (hf : martingale f ℱ μ) : martingale (-f) ℱ μ := ⟨hf.adapted.neg, λ i j hij, (condexp_neg (f j)).trans ((hf.2 i j hij).neg)⟩ lemma sub (hf : martingale f ℱ μ) (hg : martingale g ℱ μ) : martingale (f - g) ℱ μ := by { rw sub_eq_add_neg, exact hf.add hg.neg, } lemma smul (c : ℝ) (hf : martingale f ℱ μ) : martingale (c • f) ℱ μ := begin refine ⟨hf.adapted.smul c, λ i j hij, _⟩, refine (condexp_smul c (f j)).trans ((hf.2 i j hij).mono (λ x hx, _)), rw [pi.smul_apply, hx, pi.smul_apply, pi.smul_apply], end lemma supermartingale [preorder E] (hf : martingale f ℱ μ) : supermartingale f ℱ μ := ⟨hf.1, λ i j hij, (hf.2 i j hij).le, λ i, hf.integrable i⟩ lemma submartingale [preorder E] (hf : martingale f ℱ μ) : submartingale f ℱ μ := ⟨hf.1, λ i j hij, (hf.2 i j hij).symm.le, λ i, hf.integrable i⟩ end martingale lemma martingale_iff [partial_order E] : martingale f ℱ μ ↔ supermartingale f ℱ μ ∧ submartingale f ℱ μ := ⟨λ hf, ⟨hf.supermartingale, hf.submartingale⟩, λ ⟨hf₁, hf₂⟩, ⟨hf₁.1, λ i j hij, (hf₁.2.1 i j hij).antisymm (hf₂.2.1 i j hij)⟩⟩ lemma martingale_condexp (f : Ω → E) (ℱ : filtration ι m0) (μ : measure Ω) [sigma_finite_filtration μ ℱ] : martingale (λ i, μ[f | ℱ i]) ℱ μ := ⟨λ i, strongly_measurable_condexp, λ i j hij, condexp_condexp_of_le (ℱ.mono hij) (ℱ.le j)⟩ namespace supermartingale @[protected] lemma adapted [has_le E] (hf : supermartingale f ℱ μ) : adapted ℱ f := hf.1 @[protected] lemma strongly_measurable [has_le E] (hf : supermartingale f ℱ μ) (i : ι) : strongly_measurable[ℱ i] (f i) := hf.adapted i @[protected] lemma integrable [has_le E] (hf : supermartingale f ℱ μ) (i : ι) : integrable (f i) μ := hf.2.2 i lemma condexp_ae_le [has_le E] (hf : supermartingale f ℱ μ) {i j : ι} (hij : i ≤ j) : μ[f j | ℱ i] ≤ᵐ[μ] f i := hf.2.1 i j hij lemma set_integral_le [sigma_finite_filtration μ ℱ] {f : ι → Ω → ℝ} (hf : supermartingale f ℱ μ) {i j : ι} (hij : i ≤ j) {s : set Ω} (hs : measurable_set[ℱ i] s) : ∫ ω in s, f j ω ∂μ ≤ ∫ ω in s, f i ω ∂μ := begin rw ← set_integral_condexp (ℱ.le i) (hf.integrable j) hs, refine set_integral_mono_ae integrable_condexp.integrable_on (hf.integrable i).integrable_on _, filter_upwards [hf.2.1 i j hij] with _ heq using heq, end lemma add [preorder E] [covariant_class E E (+) (≤)] (hf : supermartingale f ℱ μ) (hg : supermartingale g ℱ μ) : supermartingale (f + g) ℱ μ := begin refine ⟨hf.1.add hg.1, λ i j hij, _, λ i, (hf.2.2 i).add (hg.2.2 i)⟩, refine (condexp_add (hf.integrable j) (hg.integrable j)).le.trans _, filter_upwards [hf.2.1 i j hij, hg.2.1 i j hij], intros, refine add_le_add _ _; assumption, end lemma add_martingale [preorder E] [covariant_class E E (+) (≤)] (hf : supermartingale f ℱ μ) (hg : martingale g ℱ μ) : supermartingale (f + g) ℱ μ := hf.add hg.supermartingale lemma neg [preorder E] [covariant_class E E (+) (≤)] (hf : supermartingale f ℱ μ) : submartingale (-f) ℱ μ := begin refine ⟨hf.1.neg, λ i j hij, _, λ i, (hf.2.2 i).neg⟩, refine eventually_le.trans _ (condexp_neg (f j)).symm.le, filter_upwards [hf.2.1 i j hij] with _ _, simpa, end end supermartingale namespace submartingale @[protected] lemma adapted [has_le E] (hf : submartingale f ℱ μ) : adapted ℱ f := hf.1 @[protected] lemma strongly_measurable [has_le E] (hf : submartingale f ℱ μ) (i : ι) : strongly_measurable[ℱ i] (f i) := hf.adapted i @[protected] lemma integrable [has_le E] (hf : submartingale f ℱ μ) (i : ι) : integrable (f i) μ := hf.2.2 i lemma ae_le_condexp [has_le E] (hf : submartingale f ℱ μ) {i j : ι} (hij : i ≤ j) : f i ≤ᵐ[μ] μ[f j | ℱ i] := hf.2.1 i j hij lemma add [preorder E] [covariant_class E E (+) (≤)] (hf : submartingale f ℱ μ) (hg : submartingale g ℱ μ) : submartingale (f + g) ℱ μ := begin refine ⟨hf.1.add hg.1, λ i j hij, _, λ i, (hf.2.2 i).add (hg.2.2 i)⟩, refine eventually_le.trans _ (condexp_add (hf.integrable j) (hg.integrable j)).symm.le, filter_upwards [hf.2.1 i j hij, hg.2.1 i j hij], intros, refine add_le_add _ _; assumption, end lemma add_martingale [preorder E] [covariant_class E E (+) (≤)] (hf : submartingale f ℱ μ) (hg : martingale g ℱ μ) : submartingale (f + g) ℱ μ := hf.add hg.submartingale lemma neg [preorder E] [covariant_class E E (+) (≤)] (hf : submartingale f ℱ μ) : supermartingale (-f) ℱ μ := begin refine ⟨hf.1.neg, λ i j hij, (condexp_neg (f j)).le.trans _, λ i, (hf.2.2 i).neg⟩, filter_upwards [hf.2.1 i j hij] with _ _, simpa, end /-- The converse of this lemma is `measure_theory.submartingale_of_set_integral_le`. -/ lemma set_integral_le [sigma_finite_filtration μ ℱ] {f : ι → Ω → ℝ} (hf : submartingale f ℱ μ) {i j : ι} (hij : i ≤ j) {s : set Ω} (hs : measurable_set[ℱ i] s) : ∫ ω in s, f i ω ∂μ ≤ ∫ ω in s, f j ω ∂μ := begin rw [← neg_le_neg_iff, ← integral_neg, ← integral_neg], exact supermartingale.set_integral_le hf.neg hij hs, end lemma sub_supermartingale [preorder E] [covariant_class E E (+) (≤)] (hf : submartingale f ℱ μ) (hg : supermartingale g ℱ μ) : submartingale (f - g) ℱ μ := by { rw sub_eq_add_neg, exact hf.add hg.neg } lemma sub_martingale [preorder E] [covariant_class E E (+) (≤)] (hf : submartingale f ℱ μ) (hg : martingale g ℱ μ) : submartingale (f - g) ℱ μ := hf.sub_supermartingale hg.supermartingale protected lemma sup {f g : ι → Ω → ℝ} (hf : submartingale f ℱ μ) (hg : submartingale g ℱ μ) : submartingale (f ⊔ g) ℱ μ := begin refine ⟨λ i, @strongly_measurable.sup _ _ _ _ (ℱ i) _ _ _ (hf.adapted i) (hg.adapted i), λ i j hij, _, λ i, integrable.sup (hf.integrable _) (hg.integrable _)⟩, refine eventually_le.sup_le _ _, { exact eventually_le.trans (hf.2.1 i j hij) (condexp_mono (hf.integrable _) (integrable.sup (hf.integrable j) (hg.integrable j)) (eventually_of_forall (λ x, le_max_left _ _))) }, { exact eventually_le.trans (hg.2.1 i j hij) (condexp_mono (hg.integrable _) (integrable.sup (hf.integrable j) (hg.integrable j)) (eventually_of_forall (λ x, le_max_right _ _))) } end protected lemma pos {f : ι → Ω → ℝ} (hf : submartingale f ℱ μ) : submartingale (f⁺) ℱ μ := hf.sup (martingale_zero _ _ _).submartingale end submartingale section submartingale lemma submartingale_of_set_integral_le [is_finite_measure μ] {f : ι → Ω → ℝ} (hadp : adapted ℱ f) (hint : ∀ i, integrable (f i) μ) (hf : ∀ i j : ι, i ≤ j → ∀ s : set Ω, measurable_set[ℱ i] s → ∫ ω in s, f i ω ∂μ ≤ ∫ ω in s, f j ω ∂μ) : submartingale f ℱ μ := begin refine ⟨hadp, λ i j hij, _, hint⟩, suffices : f i ≤ᵐ[μ.trim (ℱ.le i)] μ[f j| ℱ i], { exact ae_le_of_ae_le_trim this }, suffices : 0 ≤ᵐ[μ.trim (ℱ.le i)] μ[f j| ℱ i] - f i, { filter_upwards [this] with x hx, rwa ← sub_nonneg }, refine ae_nonneg_of_forall_set_integral_nonneg ((integrable_condexp.sub (hint i)).trim _ (strongly_measurable_condexp.sub $ hadp i)) (λ s hs h's, _), specialize hf i j hij s hs, rwa [← set_integral_trim _ (strongly_measurable_condexp.sub $ hadp i) hs, integral_sub' integrable_condexp.integrable_on (hint i).integrable_on, sub_nonneg, set_integral_condexp (ℱ.le i) (hint j) hs], end lemma submartingale_of_condexp_sub_nonneg [is_finite_measure μ] {f : ι → Ω → ℝ} (hadp : adapted ℱ f) (hint : ∀ i, integrable (f i) μ) (hf : ∀ i j, i ≤ j → 0 ≤ᵐ[μ] μ[f j - f i | ℱ i]) : submartingale f ℱ μ := begin refine ⟨hadp, λ i j hij, _, hint⟩, rw [← condexp_of_strongly_measurable (ℱ.le _) (hadp _) (hint _), ← eventually_sub_nonneg], exact eventually_le.trans (hf i j hij) (condexp_sub (hint _) (hint _)).le, apply_instance end lemma submartingale.condexp_sub_nonneg {f : ι → Ω → ℝ} (hf : submartingale f ℱ μ) {i j : ι} (hij : i ≤ j) : 0 ≤ᵐ[μ] μ[f j - f i | ℱ i] := begin by_cases h : sigma_finite (μ.trim (ℱ.le i)), swap, { rw condexp_of_not_sigma_finite (ℱ.le i) h }, refine eventually_le.trans _ (condexp_sub (hf.integrable _) (hf.integrable _)).symm.le, rw [eventually_sub_nonneg, condexp_of_strongly_measurable (ℱ.le _) (hf.adapted _) (hf.integrable _)], { exact hf.2.1 i j hij }, { exact h } end lemma submartingale_iff_condexp_sub_nonneg [is_finite_measure μ] {f : ι → Ω → ℝ} : submartingale f ℱ μ ↔ adapted ℱ f ∧ (∀ i, integrable (f i) μ) ∧ ∀ i j, i ≤ j → 0 ≤ᵐ[μ] μ[f j - f i | ℱ i] := ⟨λ h, ⟨h.adapted, h.integrable, λ i j, h.condexp_sub_nonneg⟩, λ ⟨hadp, hint, h⟩, submartingale_of_condexp_sub_nonneg hadp hint h⟩ end submartingale namespace supermartingale lemma sub_submartingale [preorder E] [covariant_class E E (+) (≤)] (hf : supermartingale f ℱ μ) (hg : submartingale g ℱ μ) : supermartingale (f - g) ℱ μ := by { rw sub_eq_add_neg, exact hf.add hg.neg } lemma sub_martingale [preorder E] [covariant_class E E (+) (≤)] (hf : supermartingale f ℱ μ) (hg : martingale g ℱ μ) : supermartingale (f - g) ℱ μ := hf.sub_submartingale hg.submartingale section variables {F : Type*} [normed_lattice_add_comm_group F] [normed_space ℝ F] [complete_space F] [ordered_smul ℝ F] lemma smul_nonneg {f : ι → Ω → F} {c : ℝ} (hc : 0 ≤ c) (hf : supermartingale f ℱ μ) : supermartingale (c • f) ℱ μ := begin refine ⟨hf.1.smul c, λ i j hij, _, λ i, (hf.2.2 i).smul c⟩, refine (condexp_smul c (f j)).le.trans _, filter_upwards [hf.2.1 i j hij] with _ hle, simp_rw [pi.smul_apply], exact smul_le_smul_of_nonneg hle hc, end lemma smul_nonpos {f : ι → Ω → F} {c : ℝ} (hc : c ≤ 0) (hf : supermartingale f ℱ μ) : submartingale (c • f) ℱ μ := begin rw [← neg_neg c, (by { ext i x, simp } : - -c • f = -(-c • f))], exact (hf.smul_nonneg $ neg_nonneg.2 hc).neg, end end end supermartingale namespace submartingale section variables {F : Type*} [normed_lattice_add_comm_group F] [normed_space ℝ F] [complete_space F] [ordered_smul ℝ F] lemma smul_nonneg {f : ι → Ω → F} {c : ℝ} (hc : 0 ≤ c) (hf : submartingale f ℱ μ) : submartingale (c • f) ℱ μ := begin rw [← neg_neg c, (by { ext i x, simp } : - -c • f = -(c • -f))], exact supermartingale.neg (hf.neg.smul_nonneg hc), end lemma smul_nonpos {f : ι → Ω → F} {c : ℝ} (hc : c ≤ 0) (hf : submartingale f ℱ μ) : supermartingale (c • f) ℱ μ := begin rw [← neg_neg c, (by { ext i x, simp } : - -c • f = -(-c • f))], exact (hf.smul_nonneg $ neg_nonneg.2 hc).neg, end end end submartingale section nat variables {𝒢 : filtration ℕ m0} lemma submartingale_of_set_integral_le_succ [is_finite_measure μ] {f : ℕ → Ω → ℝ} (hadp : adapted 𝒢 f) (hint : ∀ i, integrable (f i) μ) (hf : ∀ i, ∀ s : set Ω, measurable_set[𝒢 i] s → ∫ ω in s, f i ω ∂μ ≤ ∫ ω in s, f (i + 1) ω ∂μ) : submartingale f 𝒢 μ := begin refine submartingale_of_set_integral_le hadp hint (λ i j hij s hs, _), induction hij with k hk₁ hk₂, { exact le_rfl }, { exact le_trans hk₂ (hf k s (𝒢.mono hk₁ _ hs)) } end lemma supermartingale_of_set_integral_succ_le [is_finite_measure μ] {f : ℕ → Ω → ℝ} (hadp : adapted 𝒢 f) (hint : ∀ i, integrable (f i) μ) (hf : ∀ i, ∀ s : set Ω, measurable_set[𝒢 i] s → ∫ ω in s, f (i + 1) ω ∂μ ≤ ∫ ω in s, f i ω ∂μ) : supermartingale f 𝒢 μ := begin rw ← neg_neg f, refine (submartingale_of_set_integral_le_succ hadp.neg (λ i, (hint i).neg) _).neg, simpa only [integral_neg, pi.neg_apply, neg_le_neg_iff], end lemma martingale_of_set_integral_eq_succ [is_finite_measure μ] {f : ℕ → Ω → ℝ} (hadp : adapted 𝒢 f) (hint : ∀ i, integrable (f i) μ) (hf : ∀ i, ∀ s : set Ω, measurable_set[𝒢 i] s → ∫ ω in s, f i ω ∂μ = ∫ ω in s, f (i + 1) ω ∂μ) : martingale f 𝒢 μ := martingale_iff.2 ⟨supermartingale_of_set_integral_succ_le hadp hint $ λ i s hs, (hf i s hs).ge, submartingale_of_set_integral_le_succ hadp hint $ λ i s hs, (hf i s hs).le⟩ lemma submartingale_nat [is_finite_measure μ] {f : ℕ → Ω → ℝ} (hadp : adapted 𝒢 f) (hint : ∀ i, integrable (f i) μ) (hf : ∀ i, f i ≤ᵐ[μ] μ[f (i + 1) | 𝒢 i]) : submartingale f 𝒢 μ := begin refine submartingale_of_set_integral_le_succ hadp hint (λ i s hs, _), have : ∫ ω in s, f (i + 1) ω ∂μ = ∫ ω in s, μ[f (i + 1)|𝒢 i] ω ∂μ := (set_integral_condexp (𝒢.le i) (hint _) hs).symm, rw this, exact set_integral_mono_ae (hint i).integrable_on integrable_condexp.integrable_on (hf i), end lemma supermartingale_nat [is_finite_measure μ] {f : ℕ → Ω → ℝ} (hadp : adapted 𝒢 f) (hint : ∀ i, integrable (f i) μ) (hf : ∀ i, μ[f (i + 1) | 𝒢 i] ≤ᵐ[μ] f i) : supermartingale f 𝒢 μ := begin rw ← neg_neg f, refine (submartingale_nat hadp.neg (λ i, (hint i).neg) $ λ i, eventually_le.trans _ (condexp_neg _).symm.le).neg, filter_upwards [hf i] with x hx using neg_le_neg hx, end lemma martingale_nat [is_finite_measure μ] {f : ℕ → Ω → ℝ} (hadp : adapted 𝒢 f) (hint : ∀ i, integrable (f i) μ) (hf : ∀ i, f i =ᵐ[μ] μ[f (i + 1) | 𝒢 i]) : martingale f 𝒢 μ := martingale_iff.2 ⟨supermartingale_nat hadp hint $ λ i, (hf i).symm.le, submartingale_nat hadp hint $ λ i, (hf i).le⟩ lemma submartingale_of_condexp_sub_nonneg_nat [is_finite_measure μ] {f : ℕ → Ω → ℝ} (hadp : adapted 𝒢 f) (hint : ∀ i, integrable (f i) μ) (hf : ∀ i, 0 ≤ᵐ[μ] μ[f (i + 1) - f i | 𝒢 i]) : submartingale f 𝒢 μ := begin refine submartingale_nat hadp hint (λ i, _), rw [← condexp_of_strongly_measurable (𝒢.le _) (hadp _) (hint _), ← eventually_sub_nonneg], exact eventually_le.trans (hf i) (condexp_sub (hint _) (hint _)).le, apply_instance end lemma supermartingale_of_condexp_sub_nonneg_nat [is_finite_measure μ] {f : ℕ → Ω → ℝ} (hadp : adapted 𝒢 f) (hint : ∀ i, integrable (f i) μ) (hf : ∀ i, 0 ≤ᵐ[μ] μ[f i - f (i + 1) | 𝒢 i]) : supermartingale f 𝒢 μ := begin rw ← neg_neg f, refine (submartingale_of_condexp_sub_nonneg_nat hadp.neg (λ i, (hint i).neg) _).neg, simpa only [pi.zero_apply, pi.neg_apply, neg_sub_neg] end lemma martingale_of_condexp_sub_eq_zero_nat [is_finite_measure μ] {f : ℕ → Ω → ℝ} (hadp : adapted 𝒢 f) (hint : ∀ i, integrable (f i) μ) (hf : ∀ i, μ[f (i + 1) - f i | 𝒢 i] =ᵐ[μ] 0) : martingale f 𝒢 μ := begin refine martingale_iff.2 ⟨supermartingale_of_condexp_sub_nonneg_nat hadp hint $ λ i, _, submartingale_of_condexp_sub_nonneg_nat hadp hint $ λ i, (hf i).symm.le⟩, rw ← neg_sub, refine (eventually_eq.trans _ (condexp_neg _).symm).le, filter_upwards [hf i] with x hx, simpa only [pi.zero_apply, pi.neg_apply, zero_eq_neg], end -- Note that one cannot use `submartingale.zero_le_of_predictable` to prove the other two -- corresponding lemmas without imposing more restrictions to the ordering of `E` /-- A predictable submartingale is a.e. greater equal than its initial state. -/ lemma submartingale.zero_le_of_predictable [preorder E] [sigma_finite_filtration μ 𝒢] {f : ℕ → Ω → E} (hfmgle : submartingale f 𝒢 μ) (hfadp : adapted 𝒢 (λ n, f (n + 1))) (n : ℕ) : f 0 ≤ᵐ[μ] f n := begin induction n with k ih, { refl }, { exact ih.trans ((hfmgle.2.1 k (k + 1) k.le_succ).trans_eq $ germ.coe_eq.mp $ congr_arg coe $ condexp_of_strongly_measurable (𝒢.le _) (hfadp _) $ hfmgle.integrable _) } end /-- A predictable supermartingale is a.e. less equal than its initial state. -/ lemma supermartingale.le_zero_of_predictable [preorder E] [sigma_finite_filtration μ 𝒢] {f : ℕ → Ω → E} (hfmgle : supermartingale f 𝒢 μ) (hfadp : adapted 𝒢 (λ n, f (n + 1))) (n : ℕ) : f n ≤ᵐ[μ] f 0 := begin induction n with k ih, { refl }, { exact ((germ.coe_eq.mp $ congr_arg coe $ condexp_of_strongly_measurable (𝒢.le _) (hfadp _) $ hfmgle.integrable _).symm.trans_le (hfmgle.2.1 k (k + 1) k.le_succ)).trans ih } end /-- A predictable martingale is a.e. equal to its initial state. -/ lemma martingale.eq_zero_of_predictable [sigma_finite_filtration μ 𝒢] {f : ℕ → Ω → E} (hfmgle : martingale f 𝒢 μ) (hfadp : adapted 𝒢 (λ n, f (n + 1))) (n : ℕ) : f n =ᵐ[μ] f 0 := begin induction n with k ih, { refl }, { exact ((germ.coe_eq.mp (congr_arg coe $ condexp_of_strongly_measurable (𝒢.le _) (hfadp _) (hfmgle.integrable _))).symm.trans (hfmgle.2 k (k + 1) k.le_succ)).trans ih } end namespace submartingale @[protected] lemma integrable_stopped_value [has_le E] {f : ℕ → Ω → E} (hf : submartingale f 𝒢 μ) {τ : Ω → ℕ} (hτ : is_stopping_time 𝒢 τ) {N : ℕ} (hbdd : ∀ ω, τ ω ≤ N) : integrable (stopped_value f τ) μ := integrable_stopped_value ℕ hτ hf.integrable hbdd end submartingale lemma submartingale.sum_mul_sub [is_finite_measure μ] {R : ℝ} {ξ f : ℕ → Ω → ℝ} (hf : submartingale f 𝒢 μ) (hξ : adapted 𝒢 ξ) (hbdd : ∀ n ω, ξ n ω ≤ R) (hnonneg : ∀ n ω, 0 ≤ ξ n ω) : submartingale (λ n, ∑ k in finset.range n, ξ k * (f (k + 1) - f k)) 𝒢 μ := begin have hξbdd : ∀ i, ∃ C, ∀ ω, |ξ i ω| ≤ C := λ i, ⟨R, λ ω, (abs_of_nonneg (hnonneg i ω)).trans_le (hbdd i ω)⟩, have hint : ∀ m, integrable (∑ k in finset.range m, ξ k * (f (k + 1) - f k)) μ := λ m, integrable_finset_sum' _ (λ i hi, integrable.bdd_mul ((hf.integrable _).sub (hf.integrable _)) hξ.strongly_measurable.ae_strongly_measurable (hξbdd _)), have hadp : adapted 𝒢 (λ n, ∑ k in finset.range n, ξ k * (f (k + 1) - f k)), { intro m, refine finset.strongly_measurable_sum' _ (λ i hi, _), rw finset.mem_range at hi, exact (hξ.strongly_measurable_le hi.le).mul ((hf.adapted.strongly_measurable_le (nat.succ_le_of_lt hi)).sub (hf.adapted.strongly_measurable_le hi.le)) }, refine submartingale_of_condexp_sub_nonneg_nat hadp hint (λ i, _), simp only [← finset.sum_Ico_eq_sub _ (nat.le_succ _), finset.sum_apply, pi.mul_apply, pi.sub_apply, nat.Ico_succ_singleton, finset.sum_singleton], exact eventually_le.trans (eventually_le.mul_nonneg (eventually_of_forall (hnonneg _)) (hf.condexp_sub_nonneg (nat.le_succ _))) (condexp_strongly_measurable_mul (hξ _) (((hf.integrable _).sub (hf.integrable _)).bdd_mul hξ.strongly_measurable.ae_strongly_measurable (hξbdd _)) ((hf.integrable _).sub (hf.integrable _))).symm.le, end /-- Given a discrete submartingale `f` and a predictable process `ξ` (i.e. `ξ (n + 1)` is adapted) the process defined by `λ n, ∑ k in finset.range n, ξ (k + 1) * (f (k + 1) - f k)` is also a submartingale. -/ lemma submartingale.sum_mul_sub' [is_finite_measure μ] {R : ℝ} {ξ f : ℕ → Ω → ℝ} (hf : submartingale f 𝒢 μ) (hξ : adapted 𝒢 (λ n, ξ (n + 1))) (hbdd : ∀ n ω, ξ n ω ≤ R) (hnonneg : ∀ n ω, 0 ≤ ξ n ω) : submartingale (λ n, ∑ k in finset.range n, ξ (k + 1) * (f (k + 1) - f k)) 𝒢 μ := hf.sum_mul_sub hξ (λ n, hbdd _) (λ n, hnonneg _) end nat end measure_theory
fe0f63b99b852de3db63ac95d8fe3a8b9e41e81a
957a80ea22c5abb4f4670b250d55534d9db99108
/library/data/stream.lean
032643cf0341cad49192f6ddd90a7c9d8824c77c
[ "Apache-2.0" ]
permissive
GaloisInc/lean
aa1e64d604051e602fcf4610061314b9a37ab8cd
f1ec117a24459b59c6ff9e56a1d09d9e9e60a6c0
refs/heads/master
1,592,202,909,807
1,504,624,387,000
1,504,624,387,000
75,319,626
2
1
Apache-2.0
1,539,290,164,000
1,480,616,104,000
C++
UTF-8
Lean
false
false
21,723
lean
/- Copyright (c) 2015 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura -/ open nat function option universes u v w def stream (α : Type u) := nat → α namespace stream variables {α : Type u} {β : Type v} {δ : Type w} def cons (a : α) (s : stream α) : stream α := λ i, match i with | 0 := a | succ n := s n end notation h :: t := cons h t @[reducible] def head (s : stream α) : α := s 0 def tail (s : stream α) : stream α := λ i, s (i+1) def drop (n : nat) (s : stream α) : stream α := λ i, s (i+n) @[reducible] def nth (n : nat) (s : stream α) : α := s n protected theorem eta (s : stream α) : head s :: tail s = s := funext (λ i, begin cases i, repeat {refl} end) theorem nth_zero_cons (a : α) (s : stream α) : nth 0 (a :: s) = a := rfl theorem head_cons (a : α) (s : stream α) : head (a :: s) = a := rfl theorem tail_cons (a : α) (s : stream α) : tail (a :: s) = s := rfl theorem tail_drop (n : nat) (s : stream α) : tail (drop n s) = drop n (tail s) := funext (λ i, begin unfold tail drop, simp end) theorem nth_drop (n m : nat) (s : stream α) : nth n (drop m s) = nth (n+m) s := rfl theorem tail_eq_drop (s : stream α) : tail s = drop 1 s := rfl theorem drop_drop (n m : nat) (s : stream α) : drop n (drop m s) = drop (n+m) s := funext (λ i, begin unfold drop, rw add_assoc end) theorem nth_succ (n : nat) (s : stream α) : nth (succ n) s = nth n (tail s) := rfl theorem drop_succ (n : nat) (s : stream α) : drop (succ n) s = drop n (tail s) := rfl protected theorem ext {s₁ s₂ : stream α} : (∀ n, nth n s₁ = nth n s₂) → s₁ = s₂ := assume h, funext h def all (p : α → Prop) (s : stream α) := ∀ n, p (nth n s) def any (p : α → Prop) (s : stream α) := ∃ n, p (nth n s) theorem all_def (p : α → Prop) (s : stream α) : all p s = ∀ n, p (nth n s) := rfl theorem any_def (p : α → Prop) (s : stream α) : any p s = ∃ n, p (nth n s) := rfl protected def mem (a : α) (s : stream α) := any (λ b, a = b) s instance : has_mem α (stream α) := ⟨stream.mem⟩ theorem mem_cons (a : α) (s : stream α) : a ∈ (a::s) := exists.intro 0 rfl theorem mem_cons_of_mem {a : α} {s : stream α} (b : α) : a ∈ s → a ∈ b :: s := assume ⟨n, h⟩, exists.intro (succ n) (by rw [nth_succ, tail_cons, h]) theorem eq_or_mem_of_mem_cons {a b : α} {s : stream α} : a ∈ b::s → a = b ∨ a ∈ s := assume ⟨n, h⟩, begin cases n with n', {left, exact h}, {right, rw [nth_succ, tail_cons] at h, exact ⟨n', h⟩} end theorem mem_of_nth_eq {n : nat} {s : stream α} {a : α} : a = nth n s → a ∈ s := assume h, exists.intro n h section map variable (f : α → β) def map (s : stream α) : stream β := λ n, f (nth n s) theorem drop_map (n : nat) (s : stream α) : drop n (map f s) = map f (drop n s) := stream.ext (λ i, rfl) theorem nth_map (n : nat) (s : stream α) : nth n (map f s) = f (nth n s) := rfl theorem tail_map (s : stream α) : tail (map f s) = map f (tail s) := begin rw tail_eq_drop, refl end theorem head_map (s : stream α) : head (map f s) = f (head s) := rfl theorem map_eq (s : stream α) : map f s = f (head s) :: map f (tail s) := by rw [← stream.eta (map f s), tail_map, head_map] theorem map_cons (a : α) (s : stream α) : map f (a :: s) = f a :: map f s := begin rw [← stream.eta (map f (a :: s)), map_eq], refl end theorem map_id (s : stream α) : map id s = s := rfl theorem map_map (g : β → δ) (f : α → β) (s : stream α) : map g (map f s) = map (g ∘ f) s := rfl theorem map_tail (s : stream α) : map f (tail s) = tail (map f s) := rfl theorem mem_map {a : α} {s : stream α} : a ∈ s → f a ∈ map f s := assume ⟨n, h⟩, exists.intro n (by rw [nth_map, h]) theorem exists_of_mem_map {f} {b : β} {s : stream α} : b ∈ map f s → ∃ a, a ∈ s ∧ f a = b := assume ⟨n, h⟩, ⟨nth n s, ⟨n, rfl⟩, h.symm⟩ end map section zip variable (f : α → β → δ) def zip (s₁ : stream α) (s₂ : stream β) : stream δ := λ n, f (nth n s₁) (nth n s₂) theorem drop_zip (n : nat) (s₁ : stream α) (s₂ : stream β) : drop n (zip f s₁ s₂) = zip f (drop n s₁) (drop n s₂) := stream.ext (λ i, rfl) theorem nth_zip (n : nat) (s₁ : stream α) (s₂ : stream β) : nth n (zip f s₁ s₂) = f (nth n s₁) (nth n s₂) := rfl theorem head_zip (s₁ : stream α) (s₂ : stream β) : head (zip f s₁ s₂) = f (head s₁) (head s₂) := rfl theorem tail_zip (s₁ : stream α) (s₂ : stream β) : tail (zip f s₁ s₂) = zip f (tail s₁) (tail s₂) := rfl theorem zip_eq (s₁ : stream α) (s₂ : stream β) : zip f s₁ s₂ = f (head s₁) (head s₂) :: zip f (tail s₁) (tail s₂) := begin rw [← stream.eta (zip f s₁ s₂)], refl end end zip def const (a : α) : stream α := λ n, a theorem mem_const (a : α) : a ∈ const a := exists.intro 0 rfl theorem const_eq (a : α) : const a = a :: const a := begin apply stream.ext, intro n, cases n, repeat {refl} end theorem tail_const (a : α) : tail (const a) = const a := suffices tail (a :: const a) = const a, by rwa [← const_eq] at this, rfl theorem map_const (f : α → β) (a : α) : map f (const a) = const (f a) := rfl theorem nth_const (n : nat) (a : α) : nth n (const a) = a := rfl theorem drop_const (n : nat) (a : α) : drop n (const a) = const a := stream.ext (λ i, rfl) def iterate (f : α → α) (a : α) : stream α := λ n, nat.rec_on n a (λ n r, f r) theorem head_iterate (f : α → α) (a : α) : head (iterate f a) = a := rfl theorem tail_iterate (f : α → α) (a : α) : tail (iterate f a) = iterate f (f a) := begin apply funext, intro n, induction n with n' ih, {refl}, {unfold tail iterate, unfold tail iterate at ih, rw add_one at ih, dsimp at ih, rw add_one, dsimp, rw ih} end theorem iterate_eq (f : α → α) (a : α) : iterate f a = a :: iterate f (f a) := begin rw [← stream.eta (iterate f a)], rw tail_iterate, refl end theorem nth_zero_iterate (f : α → α) (a : α) : nth 0 (iterate f a) = a := rfl theorem nth_succ_iterate (n : nat) (f : α → α) (a : α) : nth (succ n) (iterate f a) = nth n (iterate f (f a)) := by rw [nth_succ, tail_iterate] section bisim variable (R : stream α → stream α → Prop) local infix ~ := R def is_bisimulation := ∀ ⦃s₁ s₂⦄, s₁ ~ s₂ → head s₁ = head s₂ ∧ tail s₁ ~ tail s₂ theorem nth_of_bisim (bisim : is_bisimulation R) : ∀ {s₁ s₂} n, s₁ ~ s₂ → nth n s₁ = nth n s₂ ∧ drop (n+1) s₁ ~ drop (n+1) s₂ | s₁ s₂ 0 h := bisim h | s₁ s₂ (n+1) h := match bisim h with | ⟨h₁, trel⟩ := nth_of_bisim n trel end -- If two streams are bisimilar, then they are equal theorem eq_of_bisim (bisim : is_bisimulation R) : ∀ {s₁ s₂}, s₁ ~ s₂ → s₁ = s₂ := λ s₁ s₂ r, stream.ext (λ n, and.elim_left (nth_of_bisim R bisim n r)) end bisim theorem bisim_simple (s₁ s₂ : stream α) : head s₁ = head s₂ → s₁ = tail s₁ → s₂ = tail s₂ → s₁ = s₂ := assume hh ht₁ ht₂, eq_of_bisim (λ s₁ s₂, head s₁ = head s₂ ∧ s₁ = tail s₁ ∧ s₂ = tail s₂) (λ s₁ s₂ ⟨h₁, h₂, h₃⟩, begin constructor, exact h₁, rw [← h₂, ← h₃], repeat {constructor, repeat {assumption}} end) (and.intro hh (and.intro ht₁ ht₂)) theorem coinduction {s₁ s₂ : stream α} : head s₁ = head s₂ → (∀ (β : Type u) (fr : stream α → β), fr s₁ = fr s₂ → fr (tail s₁) = fr (tail s₂)) → s₁ = s₂ := assume hh ht, eq_of_bisim (λ s₁ s₂, head s₁ = head s₂ ∧ ∀ (β : Type u) (fr : stream α → β), fr s₁ = fr s₂ → fr (tail s₁) = fr (tail s₂)) (λ s₁ s₂ h, have h₁ : head s₁ = head s₂, from and.elim_left h, have h₂ : head (tail s₁) = head (tail s₂), from and.elim_right h α (@head α) h₁, have h₃ : ∀ (β : Type u) (fr : stream α → β), fr (tail s₁) = fr (tail s₂) → fr (tail (tail s₁)) = fr (tail (tail s₂)), from λ β fr, and.elim_right h β (λ s, fr (tail s)), and.intro h₁ (and.intro h₂ h₃)) (and.intro hh ht) theorem iterate_id (a : α) : iterate id a = const a := coinduction rfl (λ β fr ch, begin rw [tail_iterate, tail_const], exact ch end) local attribute [reducible] stream theorem map_iterate (f : α → α) (a : α) : iterate f (f a) = map f (iterate f a) := begin apply funext, intro n, induction n with n' ih, {refl}, { unfold map iterate nth, dsimp, unfold map iterate nth at ih, dsimp at ih, rw ih } end section corec def corec (f : α → β) (g : α → α) : α → stream β := λ a, map f (iterate g a) def corec_on (a : α) (f : α → β) (g : α → α) : stream β := corec f g a theorem corec_def (f : α → β) (g : α → α) (a : α) : corec f g a = map f (iterate g a) := rfl theorem corec_eq (f : α → β) (g : α → α) (a : α) : corec f g a = f a :: corec f g (g a) := begin rw [corec_def, map_eq, head_iterate, tail_iterate], refl end theorem corec_id_id_eq_const (a : α) : corec id id a = const a := by rw [corec_def, map_id, iterate_id] theorem corec_id_f_eq_iterate (f : α → α) (a : α) : corec id f a = iterate f a := rfl end corec section corec' def corec' (f : α → β × α) : α → stream β := corec (prod.fst ∘ f) (prod.snd ∘ f) theorem corec'_eq (f : α → β × α) (a : α) : corec' f a = (f a).1 :: corec' f (f a).2 := corec_eq _ _ _ end corec' -- corec is also known as unfold def unfolds (g : α → β) (f : α → α) (a : α) : stream β := corec g f a theorem unfolds_eq (g : α → β) (f : α → α) (a : α) : unfolds g f a = g a :: unfolds g f (f a) := begin unfold unfolds, rw [corec_eq] end theorem nth_unfolds_head_tail : ∀ (n : nat) (s : stream α), nth n (unfolds head tail s) = nth n s := begin intro n, induction n with n' ih, {intro s, refl}, {intro s, rw [nth_succ, nth_succ, unfolds_eq, tail_cons, ih]} end theorem unfolds_head_eq : ∀ (s : stream α), unfolds head tail s = s := λ s, stream.ext (λ n, nth_unfolds_head_tail n s) def interleave (s₁ s₂ : stream α) : stream α := corec_on (s₁, s₂) (λ ⟨s₁, s₂⟩, head s₁) (λ ⟨s₁, s₂⟩, (s₂, tail s₁)) infix `⋈`:65 := interleave theorem interleave_eq (s₁ s₂ : stream α) : s₁ ⋈ s₂ = head s₁ :: head s₂ :: (tail s₁ ⋈ tail s₂) := begin unfold interleave corec_on, rw corec_eq, dsimp, rw corec_eq, refl end theorem tail_interleave (s₁ s₂ : stream α) : tail (s₁ ⋈ s₂) = s₂ ⋈ (tail s₁) := begin unfold interleave corec_on, rw corec_eq, refl end theorem interleave_tail_tail (s₁ s₂ : stream α) : tail s₁ ⋈ tail s₂ = tail (tail (s₁ ⋈ s₂)) := begin rw [interleave_eq s₁ s₂], refl end theorem nth_interleave_left : ∀ (n : nat) (s₁ s₂ : stream α), nth (2*n) (s₁ ⋈ s₂) = nth n s₁ | 0 s₁ s₂ := rfl | (succ n) s₁ s₂ := begin change nth (succ (succ (2*n))) (s₁ ⋈ s₂) = nth (succ n) s₁, rw [nth_succ, nth_succ, interleave_eq, tail_cons, tail_cons, nth_interleave_left], refl end theorem nth_interleave_right : ∀ (n : nat) (s₁ s₂ : stream α), nth (2*n+1) (s₁ ⋈ s₂) = nth n s₂ | 0 s₁ s₂ := rfl | (succ n) s₁ s₂ := begin change nth (succ (succ (2*n+1))) (s₁ ⋈ s₂) = nth (succ n) s₂, rw [nth_succ, nth_succ, interleave_eq, tail_cons, tail_cons, nth_interleave_right], refl end theorem mem_interleave_left {a : α} {s₁ : stream α} (s₂ : stream α) : a ∈ s₁ → a ∈ s₁ ⋈ s₂ := assume ⟨n, h⟩, exists.intro (2*n) (by rw [h, nth_interleave_left]) theorem mem_interleave_right {a : α} {s₁ : stream α} (s₂ : stream α) : a ∈ s₂ → a ∈ s₁ ⋈ s₂ := assume ⟨n, h⟩, exists.intro (2*n+1) (by rw [h, nth_interleave_right]) def even (s : stream α) : stream α := corec (λ s, head s) (λ s, tail (tail s)) s def odd (s : stream α) : stream α := even (tail s) theorem odd_eq (s : stream α) : odd s = even (tail s) := rfl theorem head_even (s : stream α) : head (even s) = head s := rfl theorem tail_even (s : stream α) : tail (even s) = even (tail (tail s)) := begin unfold even, rw corec_eq, refl end theorem even_cons_cons (a₁ a₂ : α) (s : stream α) : even (a₁ :: a₂ :: s) = a₁ :: even s := begin unfold even, rw corec_eq, refl end theorem even_tail (s : stream α) : even (tail s) = odd s := rfl theorem even_interleave (s₁ s₂ : stream α) : even (s₁ ⋈ s₂) = s₁ := eq_of_bisim (λ s₁' s₁, ∃ s₂, s₁' = even (s₁ ⋈ s₂)) (λ s₁' s₁ ⟨s₂, h₁⟩, begin rw h₁, constructor, {refl}, {exact ⟨tail s₂, by rw [interleave_eq, even_cons_cons, tail_cons]⟩} end) (exists.intro s₂ rfl) theorem interleave_even_odd (s₁ : stream α) : even s₁ ⋈ odd s₁ = s₁ := eq_of_bisim (λ s' s, s' = even s ⋈ odd s) (λ s' s (h : s' = even s ⋈ odd s), begin rw h, constructor, {refl}, {simp [odd_eq, odd_eq, tail_interleave, tail_even]} end) rfl theorem nth_even : ∀ (n : nat) (s : stream α), nth n (even s) = nth (2*n) s | 0 s := rfl | (succ n) s := begin change nth (succ n) (even s) = nth (succ (succ (2 * n))) s, rw [nth_succ, nth_succ, tail_even, nth_even], refl end theorem nth_odd : ∀ (n : nat) (s : stream α), nth n (odd s) = nth (2*n + 1) s := λ n s, begin rw [odd_eq, nth_even], refl end theorem mem_of_mem_even (a : α) (s : stream α) : a ∈ even s → a ∈ s := assume ⟨n, h⟩, exists.intro (2*n) (by rw [h, nth_even]) theorem mem_of_mem_odd (a : α) (s : stream α) : a ∈ odd s → a ∈ s := assume ⟨n, h⟩, exists.intro (2*n+1) (by rw [h, nth_odd]) def append_stream : list α → stream α → stream α | [] s := s | (list.cons a l) s := a :: append_stream l s theorem nil_append_stream (s : stream α) : append_stream [] s = s := rfl theorem cons_append_stream (a : α) (l : list α) (s : stream α) : append_stream (a::l) s = a :: append_stream l s := rfl infix `++ₛ`:65 := append_stream theorem append_append_stream : ∀ (l₁ l₂ : list α) (s : stream α), (l₁ ++ l₂) ++ₛ s = l₁ ++ₛ (l₂ ++ₛ s) | [] l₂ s := rfl | (list.cons a l₁) l₂ s := by rw [list.cons_append, cons_append_stream, cons_append_stream, append_append_stream] theorem map_append_stream (f : α → β) : ∀ (l : list α) (s : stream α), map f (l ++ₛ s) = list.map f l ++ₛ map f s | [] s := rfl | (list.cons a l) s := by rw [cons_append_stream, list.map_cons, map_cons, cons_append_stream, map_append_stream] theorem drop_append_stream : ∀ (l : list α) (s : stream α), drop l.length (l ++ₛ s) = s | [] s := by refl | (list.cons a l) s := by rw [list.length_cons, add_one, drop_succ, cons_append_stream, tail_cons, drop_append_stream] theorem append_stream_head_tail (s : stream α) : [head s] ++ₛ tail s = s := by rw [cons_append_stream, nil_append_stream, stream.eta] theorem mem_append_stream_right : ∀ {a : α} (l : list α) {s : stream α}, a ∈ s → a ∈ l ++ₛ s | a [] s h := h | a (list.cons b l) s h := have ih : a ∈ l ++ₛ s, from mem_append_stream_right l h, mem_cons_of_mem _ ih theorem mem_append_stream_left : ∀ {a : α} {l : list α} (s : stream α), a ∈ l → a ∈ l ++ₛ s | a [] s h := absurd h (list.not_mem_nil _) | a (list.cons b l) s h := or.elim (list.eq_or_mem_of_mem_cons h) (λ (aeqb : a = b), exists.intro 0 aeqb) (λ (ainl : a ∈ l), mem_cons_of_mem b (mem_append_stream_left s ainl)) def approx : nat → stream α → list α | 0 s := [] | (n+1) s := list.cons (head s) (approx n (tail s)) theorem approx_zero (s : stream α) : approx 0 s = [] := rfl theorem approx_succ (n : nat) (s : stream α) : approx (succ n) s = head s :: approx n (tail s) := rfl theorem nth_approx : ∀ (n : nat) (s : stream α), list.nth (approx (succ n) s) n = some (nth n s) | 0 s := rfl | (n+1) s := begin rw [approx_succ, add_one, list.nth, nth_approx], refl end theorem append_approx_drop : ∀ (n : nat) (s : stream α), append_stream (approx n s) (drop n s) = s := begin intro n, induction n with n' ih, {intro s, refl}, {intro s, rw [approx_succ, drop_succ, cons_append_stream, ih (tail s), stream.eta]} end -- Take theorem reduces a proof of equality of infinite streams to an -- induction over all their finite approximations. theorem take_theorem (s₁ s₂ : stream α) : (∀ (n : nat), approx n s₁ = approx n s₂) → s₁ = s₂ := begin intro h, apply stream.ext, intro n, induction n with n ih, { have aux := h 1, unfold approx at aux, injection aux }, { have h₁ : some (nth (succ n) s₁) = some (nth (succ n) s₂), { rw [← nth_approx, ← nth_approx, h (succ (succ n))] }, injection h₁ } end -- auxiliary def for cycle corecursive def private def cycle_f : α × list α × α × list α → α | (v, _, _, _) := v -- auxiliary def for cycle corecursive def private def cycle_g : α × list α × α × list α → α × list α × α × list α | (v₁, [], v₀, l₀) := (v₀, l₀, v₀, l₀) | (v₁, list.cons v₂ l₂, v₀, l₀) := (v₂, l₂, v₀, l₀) private lemma cycle_g_cons (a : α) (a₁ : α) (l₁ : list α) (a₀ : α) (l₀ : list α) : cycle_g (a, a₁::l₁, a₀, l₀) = (a₁, l₁, a₀, l₀) := rfl def cycle : Π (l : list α), l ≠ [] → stream α | [] h := absurd rfl h | (list.cons a l) h := corec cycle_f cycle_g (a, l, a, l) theorem cycle_eq : ∀ (l : list α) (h : l ≠ []), cycle l h = l ++ₛ cycle l h | [] h := absurd rfl h | (list.cons a l) h := have gen : ∀ l' a', corec cycle_f cycle_g (a', l', a, l) = (a' :: l') ++ₛ corec cycle_f cycle_g (a, l, a, l), begin intro l', induction l' with a₁ l₁ ih, {intros, rw [corec_eq], refl}, {intros, rw [corec_eq, cycle_g_cons, ih a₁], refl} end, gen l a theorem mem_cycle {a : α} {l : list α} : ∀ (h : l ≠ []), a ∈ l → a ∈ cycle l h := assume h ainl, begin rw [cycle_eq], exact mem_append_stream_left _ ainl end theorem cycle_singleton (a : α) (h : [a] ≠ []) : cycle [a] h = const a := coinduction rfl (λ β fr ch, by rwa [cycle_eq, const_eq]) def tails (s : stream α) : stream (stream α) := corec id tail (tail s) theorem tails_eq (s : stream α) : tails s = tail s :: tails (tail s) := by unfold tails; rw [corec_eq]; refl theorem nth_tails : ∀ (n : nat) (s : stream α), nth n (tails s) = drop n (tail s) := begin intro n, induction n with n' ih, {intros, refl}, {intro s, rw [nth_succ, drop_succ, tails_eq, tail_cons, ih]} end theorem tails_eq_iterate (s : stream α) : tails s = iterate tail (tail s) := rfl def inits_core (l : list α) (s : stream α) : stream (list α) := corec_on (l, s) (λ ⟨a, b⟩, a) (λ p, match p with (l', s') := (l' ++ [head s'], tail s') end) def inits (s : stream α) : stream (list α) := inits_core [head s] (tail s) theorem inits_core_eq (l : list α) (s : stream α) : inits_core l s = l :: inits_core (l ++ [head s]) (tail s) := begin unfold inits_core corec_on, rw [corec_eq], refl end theorem tail_inits (s : stream α) : tail (inits s) = inits_core [head s, head (tail s)] (tail (tail s)) := begin unfold inits, rw inits_core_eq, refl end theorem inits_tail (s : stream α) : inits (tail s) = inits_core [head (tail s)] (tail (tail s)) := rfl theorem cons_nth_inits_core : ∀ (a : α) (n : nat) (l : list α) (s : stream α), a :: nth n (inits_core l s) = nth n (inits_core (a::l) s) := begin intros a n, induction n with n' ih, {intros, refl}, {intros l s, rw [nth_succ, inits_core_eq, tail_cons, ih, inits_core_eq (a::l) s], refl } end theorem nth_inits : ∀ (n : nat) (s : stream α), nth n (inits s) = approx (succ n) s := begin intro n, induction n with n' ih, {intros, refl}, {intros, rw [nth_succ, approx_succ, ← ih, tail_inits, inits_tail, cons_nth_inits_core]} end theorem inits_eq (s : stream α) : inits s = [head s] :: map (list.cons (head s)) (inits (tail s)) := begin apply stream.ext, intro n, cases n, {refl}, {rw [nth_inits, nth_succ, tail_cons, nth_map, nth_inits], refl} end theorem zip_inits_tails (s : stream α) : zip append_stream (inits s) (tails s) = const s := begin apply stream.ext, intro n, rw [nth_zip, nth_inits, nth_tails, nth_const, approx_succ, cons_append_stream, append_approx_drop, stream.eta] end def pure (a : α) : stream α := const a def apply (f : stream (α → β)) (s : stream α) : stream β := λ n, (nth n f) (nth n s) infix `⊛`:75 := apply -- input as \o* theorem identity (s : stream α) : pure id ⊛ s = s := rfl theorem composition (g : stream (β → δ)) (f : stream (α → β)) (s : stream α) : pure comp ⊛ g ⊛ f ⊛ s = g ⊛ (f ⊛ s) := rfl theorem homomorphism (f : α → β) (a : α) : pure f ⊛ pure a = pure (f a) := rfl theorem interchange (fs : stream (α → β)) (a : α) : fs ⊛ pure a = pure (λ f : α → β, f a) ⊛ fs := rfl theorem map_eq_apply (f : α → β) (s : stream α) : map f s = pure f ⊛ s := rfl def nats : stream nat := λ n, n theorem nth_nats (n : nat) : nth n nats = n := rfl theorem nats_eq : nats = 0 :: map succ nats := begin apply stream.ext, intro n, cases n, refl, rw [nth_succ], refl end end stream
265e28fabd8a3453132333fe644ae459b816ca45
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/src/lake/examples/deps/foo/Main.lean
a97c51c767be5dabbe27e61c9853311085059f81
[ "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
73
lean
import Foo def main : IO Unit := IO.println s!"Hello, {foo} {a} {b}!"
fb9e1855e694ef1b86159bb9f3ab57ac7f6503ed
a5271082abc327bbe26fc4acdaa885da9582cefa
/src/interactive.lean
4e6e9307079ee2f6cf6d273e85acf17545e8a91a
[ "Apache-2.0" ]
permissive
avigad/embed
9ee7d104609eeded173ca1e6e7a1925897b1652a
0e3612028d4039d29d06239ef03bc50576ca0f8b
refs/heads/master
1,584,548,951,613
1,527,883,346,000
1,527,883,346,000
134,967,973
0
0
null
null
null
null
UTF-8
Lean
false
false
3,237
lean
-- adapted from tests/interactive/my_tactic_class.lean import .prop .print .parser open prop -- keep the extra state around just in case meta def gentzen := state_t nat tactic section local attribute [reducible] gentzen meta instance : monad gentzen := by apply_instance meta instance : monad_state nat gentzen := by apply_instance meta instance : has_monad_lift tactic gentzen := by apply_instance end meta instance (α : Type) : has_coe (tactic α) (gentzen α) := ⟨monad_lift⟩ namespace gentzen meta def show_goal (e : expr) : tactic format := do et ← tactic.infer_type e, match et with | `(prop.thm %%sq) := do sq' ← tactic.eval_expr (seq symb) sq, pure $ sqt2str fml2str sq'.1 sq'.2 | _ := pure ("not a Gentzen sequent: " ++ et.to_string) end meta def show_goals_aux : list expr → tactic format | [] := pure "" | (h::t) := do hd ← show_goal h, tl ← show_goals_aux t, pure (hd ++ format.line ++ tl) meta def show_goals : tactic format := do g ← tactic.get_goals, if g = [] then pure "No goals!" else show_goals_aux g meta def step {α : Type} (t : gentzen α) : gentzen unit := t >> return () -- TODO: not updated meta def istep {α : Type} (line0 col0 line col : nat) (t : gentzen α) : gentzen unit := ⟨λ v s, result.cases_on (@scope_trace _ line col (λ_, t.run v s)) (λ ⟨a, v⟩ new_s, result.success ((), v) new_s) (λ opt_msg_thunk e new_s, match opt_msg_thunk with | some msg_thunk := let msg := λ _ : unit, msg_thunk () ++ format.line ++ to_fmt "state:" ++ format.line ++ match show_goals new_s with | (result.success fmt _) := fmt | _ := new_s^.to_format end in interaction_monad.result.exception (some msg) (some ⟨line, col⟩) new_s | none := interaction_monad.silent_fail new_s end)⟩ meta def execute (tac : gentzen unit) : tactic unit := tac.run 0 >> return () meta def save_info (p : pos) : gentzen unit := do v ← get, s ← tactic.read, fmt ← show_goals, tactic.save_info_thunk p (λ _, fmt) namespace interactive /- meta def intros : gentzen unit := tactic.intros >> return () meta def constructor : gentzen unit := tactic.constructor >> return () meta def trace (s : string) : gentzen unit := tactic.trace s meta def assumption : gentzen unit := tactic.assumption meta def inc : gentzen punit := modify (+1) -/ meta def id : tactic unit := do tactic.applyc ``thm.id <|> tactic.fail "id tactic doesn't apply" meta def truer : gentzen unit := do tactic.applyc ``thm.truer meta def falsel : gentzen unit := do tactic.applyc ``thm.falsel meta def andl : gentzen unit := do tactic.applyc ``thm.andl meta def andr : gentzen unit := do tactic.applyc ``thm.andr meta def orl : gentzen unit := do tactic.applyc ``thm.orl meta def orr : gentzen unit := do tactic.applyc ``thm.orr meta def impl : gentzen unit := do tactic.applyc ``thm.impl meta def impr : gentzen unit := do tactic.applyc ``thm.impr meta def rl (n : nat) : gentzen unit := do tactic.apply `(@thm.rl symb _ n).to_expr, tactic.skip meta def rr (n : nat) : gentzen unit := do tactic.apply `(@thm.rr symb _ n).to_expr, tactic.skip end interactive end gentzen
01acd2d6363b867378f4d5491ad950bd9f37f042
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/topology/algebra/module/multilinear.lean
ce7001ade4021b64835f4b1532078563cf3dad9c
[ "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
17,220
lean
/- Copyright (c) 2020 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sébastien Gouëzel -/ import topology.algebra.module.basic import linear_algebra.multilinear.basic /-! # Continuous multilinear maps We define continuous multilinear maps as maps from `Π(i : ι), M₁ i` to `M₂` which are multilinear and continuous, by extending the space of multilinear maps with a continuity assumption. Here, `M₁ i` and `M₂` are modules over a ring `R`, and `ι` is an arbitrary type, and all these spaces are also topological spaces. ## Main definitions * `continuous_multilinear_map R M₁ M₂` is the space of continuous multilinear maps from `Π(i : ι), M₁ i` to `M₂`. We show that it is an `R`-module. ## Implementation notes We mostly follow the API of multilinear maps. ## Notation We introduce the notation `M [×n]→L[R] M'` for the space of continuous `n`-multilinear maps from `M^n` to `M'`. This is a particular case of the general notion (where we allow varying dependent types as the arguments of our continuous multilinear maps), but arguably the most important one, especially when defining iterated derivatives. -/ open function fin set open_locale big_operators universes u v w w₁ w₁' w₂ w₃ w₄ variables {R : Type u} {ι : Type v} {n : ℕ} {M : fin n.succ → Type w} {M₁ : ι → Type w₁} {M₁' : ι → Type w₁'} {M₂ : Type w₂} {M₃ : Type w₃} {M₄ : Type w₄} [decidable_eq ι] /-- Continuous multilinear maps over the ring `R`, from `Πi, M₁ i` to `M₂` where `M₁ i` and `M₂` are modules over `R` with a topological structure. In applications, there will be compatibility conditions between the algebraic and the topological structures, but this is not needed for the definition. -/ structure continuous_multilinear_map (R : Type u) {ι : Type v} (M₁ : ι → Type w₁) (M₂ : Type w₂) [decidable_eq ι] [semiring R] [∀i, add_comm_monoid (M₁ i)] [add_comm_monoid M₂] [∀i, module R (M₁ i)] [module R M₂] [∀i, topological_space (M₁ i)] [topological_space M₂] extends multilinear_map R M₁ M₂ := (cont : continuous to_fun) notation M `[×`:25 n `]→L[`:25 R `] ` M' := continuous_multilinear_map R (λ (i : fin n), M) M' namespace continuous_multilinear_map section semiring variables [semiring R] [Πi, add_comm_monoid (M i)] [Πi, add_comm_monoid (M₁ i)] [Πi, add_comm_monoid (M₁' i)] [add_comm_monoid M₂] [add_comm_monoid M₃] [add_comm_monoid M₄] [Π i, module R (M i)] [Π i, module R (M₁ i)] [Π i, module R (M₁' i)] [module R M₂] [module R M₃] [module R M₄] [Π i, topological_space (M i)] [Π i, topological_space (M₁ i)] [Π i, topological_space (M₁' i)] [topological_space M₂] [topological_space M₃] [topological_space M₄] (f f' : continuous_multilinear_map R M₁ M₂) instance : has_coe_to_fun (continuous_multilinear_map R M₁ M₂) (λ _, (Π i, M₁ i) → M₂) := ⟨λ f, f.to_fun⟩ @[continuity] lemma coe_continuous : continuous (f : (Π i, M₁ i) → M₂) := f.cont @[simp] lemma coe_coe : (f.to_multilinear_map : (Π i, M₁ i) → M₂) = f := rfl theorem to_multilinear_map_inj : function.injective (continuous_multilinear_map.to_multilinear_map : continuous_multilinear_map R M₁ M₂ → multilinear_map R M₁ M₂) | ⟨f, hf⟩ ⟨g, hg⟩ rfl := rfl @[ext] theorem ext {f f' : continuous_multilinear_map R M₁ M₂} (H : ∀ x, f x = f' x) : f = f' := to_multilinear_map_inj $ multilinear_map.ext H @[simp] lemma map_add (m : Πi, M₁ i) (i : ι) (x y : M₁ i) : f (update m i (x + y)) = f (update m i x) + f (update m i y) := f.map_add' m i x y @[simp] lemma map_smul (m : Πi, M₁ i) (i : ι) (c : R) (x : M₁ i) : f (update m i (c • x)) = c • f (update m i x) := f.map_smul' m i c x lemma map_coord_zero {m : Πi, M₁ i} (i : ι) (h : m i = 0) : f m = 0 := f.to_multilinear_map.map_coord_zero i h @[simp] lemma map_zero [nonempty ι] : f 0 = 0 := f.to_multilinear_map.map_zero instance : has_zero (continuous_multilinear_map R M₁ M₂) := ⟨{ cont := continuous_const, ..(0 : multilinear_map R M₁ M₂) }⟩ instance : inhabited (continuous_multilinear_map R M₁ M₂) := ⟨0⟩ @[simp] lemma zero_apply (m : Πi, M₁ i) : (0 : continuous_multilinear_map R M₁ M₂) m = 0 := rfl section has_continuous_add variable [has_continuous_add M₂] instance : has_add (continuous_multilinear_map R M₁ M₂) := ⟨λ f f', ⟨f.to_multilinear_map + f'.to_multilinear_map, f.cont.add f'.cont⟩⟩ @[simp] lemma add_apply (m : Πi, M₁ i) : (f + f') m = f m + f' m := rfl @[simp] lemma to_multilinear_map_add (f g : continuous_multilinear_map R M₁ M₂) : (f + g).to_multilinear_map = f.to_multilinear_map + g.to_multilinear_map := rfl instance add_comm_monoid : add_comm_monoid (continuous_multilinear_map R M₁ M₂) := to_multilinear_map_inj.add_comm_monoid _ rfl (λ _ _, rfl) /-- Evaluation of a `continuous_multilinear_map` at a vector as an `add_monoid_hom`. -/ def apply_add_hom (m : Π i, M₁ i) : continuous_multilinear_map R M₁ M₂ →+ M₂ := ⟨λ f, f m, rfl, λ _ _, rfl⟩ @[simp] lemma sum_apply {α : Type*} (f : α → continuous_multilinear_map R M₁ M₂) (m : Πi, M₁ i) {s : finset α} : (∑ a in s, f a) m = ∑ a in s, f a m := (apply_add_hom m).map_sum f s end has_continuous_add /-- If `f` is a continuous multilinear map, then `f.to_continuous_linear_map m i` is the continuous linear map obtained by fixing all coordinates but `i` equal to those of `m`, and varying the `i`-th coordinate. -/ def to_continuous_linear_map (m : Πi, M₁ i) (i : ι) : M₁ i →L[R] M₂ := { cont := f.cont.comp (continuous_const.update i continuous_id), .. f.to_multilinear_map.to_linear_map m i } /-- The cartesian product of two continuous multilinear maps, as a continuous multilinear map. -/ def prod (f : continuous_multilinear_map R M₁ M₂) (g : continuous_multilinear_map R M₁ M₃) : continuous_multilinear_map R M₁ (M₂ × M₃) := { cont := f.cont.prod_mk g.cont, .. f.to_multilinear_map.prod g.to_multilinear_map } @[simp] lemma prod_apply (f : continuous_multilinear_map R M₁ M₂) (g : continuous_multilinear_map R M₁ M₃) (m : Πi, M₁ i) : (f.prod g) m = (f m, g m) := rfl /-- Combine a family of continuous multilinear maps with the same domain and codomains `M' i` into a continuous multilinear map taking values in the space of functions `Π i, M' i`. -/ def pi {ι' : Type*} {M' : ι' → Type*} [Π i, add_comm_monoid (M' i)] [Π i, topological_space (M' i)] [Π i, module R (M' i)] (f : Π i, continuous_multilinear_map R M₁ (M' i)) : continuous_multilinear_map R M₁ (Π i, M' i) := { cont := continuous_pi $ λ i, (f i).coe_continuous, to_multilinear_map := multilinear_map.pi (λ i, (f i).to_multilinear_map) } @[simp] lemma coe_pi {ι' : Type*} {M' : ι' → Type*} [Π i, add_comm_monoid (M' i)] [Π i, topological_space (M' i)] [Π i, module R (M' i)] (f : Π i, continuous_multilinear_map R M₁ (M' i)) : ⇑(pi f) = λ m j, f j m := rfl lemma pi_apply {ι' : Type*} {M' : ι' → Type*} [Π i, add_comm_monoid (M' i)] [Π i, topological_space (M' i)] [Π i, module R (M' i)] (f : Π i, continuous_multilinear_map R M₁ (M' i)) (m : Π i, M₁ i) (j : ι') : pi f m j = f j m := rfl /-- If `g` is continuous multilinear and `f` is a collection of continuous linear maps, then `g (f₁ m₁, ..., fₙ mₙ)` is again a continuous multilinear map, that we call `g.comp_continuous_linear_map f`. -/ def comp_continuous_linear_map (g : continuous_multilinear_map R M₁' M₄) (f : Π i : ι, M₁ i →L[R] M₁' i) : continuous_multilinear_map R M₁ M₄ := { cont := g.cont.comp $ continuous_pi $ λj, (f j).cont.comp $ continuous_apply _, .. g.to_multilinear_map.comp_linear_map (λ i, (f i).to_linear_map) } @[simp] lemma comp_continuous_linear_map_apply (g : continuous_multilinear_map R M₁' M₄) (f : Π i : ι, M₁ i →L[R] M₁' i) (m : Π i, M₁ i) : g.comp_continuous_linear_map f m = g (λ i, f i $ m i) := rfl /-- Composing a continuous multilinear map with a continuous linear map gives again a continuous multilinear map. -/ def _root_.continuous_linear_map.comp_continuous_multilinear_map (g : M₂ →L[R] M₃) (f : continuous_multilinear_map R M₁ M₂) : continuous_multilinear_map R M₁ M₃ := { cont := g.cont.comp f.cont, .. g.to_linear_map.comp_multilinear_map f.to_multilinear_map } @[simp] lemma _root_.continuous_linear_map.comp_continuous_multilinear_map_coe (g : M₂ →L[R] M₃) (f : continuous_multilinear_map R M₁ M₂) : ((g.comp_continuous_multilinear_map f) : (Πi, M₁ i) → M₃) = (g : M₂ → M₃) ∘ (f : (Πi, M₁ i) → M₂) := by { ext m, refl } /-- `continuous_multilinear_map.pi` as an `equiv`. -/ @[simps] def pi_equiv {ι' : Type*} {M' : ι' → Type*} [Π i, add_comm_monoid (M' i)] [Π i, topological_space (M' i)] [Π i, module R (M' i)] : (Π i, continuous_multilinear_map R M₁ (M' i)) ≃ continuous_multilinear_map R M₁ (Π i, M' i) := { to_fun := continuous_multilinear_map.pi, inv_fun := λ f i, (continuous_linear_map.proj i : _ →L[R] M' i).comp_continuous_multilinear_map f, left_inv := λ f, by { ext, refl }, right_inv := λ f, by { ext, refl } } /-- In the specific case of continuous multilinear maps on spaces indexed by `fin (n+1)`, where one can build an element of `Π(i : fin (n+1)), M i` using `cons`, one can express directly the additivity of a multilinear map along the first variable. -/ lemma cons_add (f : continuous_multilinear_map R M M₂) (m : Π(i : fin n), M i.succ) (x y : M 0) : f (cons (x+y) m) = f (cons x m) + f (cons y m) := f.to_multilinear_map.cons_add m x y /-- In the specific case of continuous multilinear maps on spaces indexed by `fin (n+1)`, where one can build an element of `Π(i : fin (n+1)), M i` using `cons`, one can express directly the multiplicativity of a multilinear map along the first variable. -/ lemma cons_smul (f : continuous_multilinear_map R M M₂) (m : Π(i : fin n), M i.succ) (c : R) (x : M 0) : f (cons (c • x) m) = c • f (cons x m) := f.to_multilinear_map.cons_smul m c x lemma map_piecewise_add (m m' : Πi, M₁ i) (t : finset ι) : f (t.piecewise (m + m') m') = ∑ s in t.powerset, f (s.piecewise m m') := f.to_multilinear_map.map_piecewise_add _ _ _ /-- Additivity of a continuous multilinear map along all coordinates at the same time, writing `f (m + m')` as the sum of `f (s.piecewise m m')` over all sets `s`. -/ lemma map_add_univ [fintype ι] (m m' : Πi, M₁ i) : f (m + m') = ∑ s : finset ι, f (s.piecewise m m') := f.to_multilinear_map.map_add_univ _ _ section apply_sum open fintype finset variables {α : ι → Type*} [fintype ι] (g : Π i, α i → M₁ i) (A : Π i, finset (α i)) /-- If `f` is continuous multilinear, then `f (Σ_{j₁ ∈ A₁} g₁ j₁, ..., Σ_{jₙ ∈ Aₙ} gₙ jₙ)` is the sum of `f (g₁ (r 1), ..., gₙ (r n))` where `r` ranges over all functions with `r 1 ∈ A₁`, ..., `r n ∈ Aₙ`. This follows from multilinearity by expanding successively with respect to each coordinate. -/ lemma map_sum_finset : f (λ i, ∑ j in A i, g i j) = ∑ r in pi_finset A, f (λ i, g i (r i)) := f.to_multilinear_map.map_sum_finset _ _ /-- If `f` is continuous multilinear, then `f (Σ_{j₁} g₁ j₁, ..., Σ_{jₙ} gₙ jₙ)` is the sum of `f (g₁ (r 1), ..., gₙ (r n))` where `r` ranges over all functions `r`. This follows from multilinearity by expanding successively with respect to each coordinate. -/ lemma map_sum [∀ i, fintype (α i)] : f (λ i, ∑ j, g i j) = ∑ r : Π i, α i, f (λ i, g i (r i)) := f.to_multilinear_map.map_sum _ end apply_sum section restrict_scalar variables (R) {A : Type*} [semiring A] [has_scalar R A] [Π (i : ι), module A (M₁ i)] [module A M₂] [∀ i, is_scalar_tower R A (M₁ i)] [is_scalar_tower R A M₂] /-- Reinterpret an `A`-multilinear map as an `R`-multilinear map, if `A` is an algebra over `R` and their actions on all involved modules agree with the action of `R` on `A`. -/ def restrict_scalars (f : continuous_multilinear_map A M₁ M₂) : continuous_multilinear_map R M₁ M₂ := { to_multilinear_map := f.to_multilinear_map.restrict_scalars R, cont := f.cont } @[simp] lemma coe_restrict_scalars (f : continuous_multilinear_map A M₁ M₂) : ⇑(f.restrict_scalars R) = f := rfl end restrict_scalar end semiring section ring variables [ring R] [∀i, add_comm_group (M₁ i)] [add_comm_group M₂] [∀i, module R (M₁ i)] [module R M₂] [∀i, topological_space (M₁ i)] [topological_space M₂] (f f' : continuous_multilinear_map R M₁ M₂) @[simp] lemma map_sub (m : Πi, M₁ i) (i : ι) (x y : M₁ i) : f (update m i (x - y)) = f (update m i x) - f (update m i y) := f.to_multilinear_map.map_sub _ _ _ _ section topological_add_group variable [topological_add_group M₂] instance : has_neg (continuous_multilinear_map R M₁ M₂) := ⟨λ f, {cont := f.cont.neg, ..(-f.to_multilinear_map)}⟩ @[simp] lemma neg_apply (m : Πi, M₁ i) : (-f) m = - (f m) := rfl instance : has_sub (continuous_multilinear_map R M₁ M₂) := ⟨λ f g, { cont := f.cont.sub g.cont, .. (f.to_multilinear_map - g.to_multilinear_map) }⟩ @[simp] lemma sub_apply (m : Πi, M₁ i) : (f - f') m = f m - f' m := rfl instance : add_comm_group (continuous_multilinear_map R M₁ M₂) := to_multilinear_map_inj.add_comm_group _ rfl (λ _ _, rfl) (λ _, rfl) (λ _ _, rfl) end topological_add_group end ring section comm_semiring variables [comm_semiring R] [∀i, add_comm_monoid (M₁ i)] [add_comm_monoid M₂] [∀i, module R (M₁ i)] [module R M₂] [∀i, topological_space (M₁ i)] [topological_space M₂] (f : continuous_multilinear_map R M₁ M₂) lemma map_piecewise_smul (c : ι → R) (m : Πi, M₁ i) (s : finset ι) : f (s.piecewise (λ i, c i • m i) m) = (∏ i in s, c i) • f m := f.to_multilinear_map.map_piecewise_smul _ _ _ /-- Multiplicativity of a continuous multilinear map along all coordinates at the same time, writing `f (λ i, c i • m i)` as `(∏ i, c i) • f m`. -/ lemma map_smul_univ [fintype ι] (c : ι → R) (m : Πi, M₁ i) : f (λ i, c i • m i) = (∏ i, c i) • f m := f.to_multilinear_map.map_smul_univ _ _ variables {R' A : Type*} [comm_semiring R'] [semiring A] [algebra R' A] [Π i, module A (M₁ i)] [module R' M₂] [module A M₂] [is_scalar_tower R' A M₂] [topological_space R'] [has_continuous_smul R' M₂] instance : has_scalar R' (continuous_multilinear_map A M₁ M₂) := ⟨λ c f, { cont := continuous_const.smul f.cont, .. c • f.to_multilinear_map }⟩ @[simp] lemma smul_apply (f : continuous_multilinear_map A M₁ M₂) (c : R') (m : Πi, M₁ i) : (c • f) m = c • f m := rfl @[simp] lemma to_multilinear_map_smul (c : R') (f : continuous_multilinear_map A M₁ M₂) : (c • f).to_multilinear_map = c • f.to_multilinear_map := rfl instance {R''} [comm_semiring R''] [has_scalar R' R''] [algebra R'' A] [module R'' M₂] [is_scalar_tower R'' A M₂] [is_scalar_tower R' R'' M₂] [topological_space R''] [has_continuous_smul R'' M₂]: is_scalar_tower R' R'' (continuous_multilinear_map A M₁ M₂) := ⟨λ c₁ c₂ f, ext $ λ x, smul_assoc _ _ _⟩ variable [has_continuous_add M₂] /-- The space of continuous multilinear maps over an algebra over `R` is a module over `R`, for the pointwise addition and scalar multiplication. -/ instance : module R' (continuous_multilinear_map A M₁ M₂) := { one_smul := λ f, ext $ λ x, one_smul _ _, mul_smul := λ c₁ c₂ f, ext $ λ x, mul_smul _ _ _, smul_zero := λ r, ext $ λ x, smul_zero _, smul_add := λ r f₁ f₂, ext $ λ x, smul_add _ _ _, add_smul := λ r₁ r₂ f, ext $ λ x, add_smul _ _ _, zero_smul := λ f, ext $ λ x, zero_smul _ _ } /-- Linear map version of the map `to_multilinear_map` associating to a continuous multilinear map the corresponding multilinear map. -/ @[simps] def to_multilinear_map_linear : (continuous_multilinear_map A M₁ M₂) →ₗ[R'] (multilinear_map A M₁ M₂) := { to_fun := λ f, f.to_multilinear_map, map_add' := λ f g, rfl, map_smul' := λ c f, rfl } /-- `continuous_multilinear_map.pi` as a `linear_equiv`. -/ @[simps {simp_rhs := tt}] def pi_linear_equiv {ι' : Type*} {M' : ι' → Type*} [Π i, add_comm_monoid (M' i)] [Π i, topological_space (M' i)] [∀ i, has_continuous_add (M' i)] [Π i, module R' (M' i)] [Π i, module A (M' i)] [∀ i, is_scalar_tower R' A (M' i)] [Π i, has_continuous_smul R' (M' i)] : -- typeclass search doesn't find this instance, presumably due to struggles converting -- `Π i, module R (M' i)` to `Π i, has_scalar R (M' i)` in dependent arguments. let inst : has_continuous_smul R' (Π i, M' i) := pi.has_continuous_smul in (Π i, continuous_multilinear_map A M₁ (M' i)) ≃ₗ[R'] continuous_multilinear_map A M₁ (Π i, M' i) := { map_add' := λ x y, rfl, map_smul' := λ c x, rfl, .. pi_equiv } end comm_semiring end continuous_multilinear_map
f6c182f99a0dfc1950296172b2c5d1595878fd0e
b36920261fbaa674569b063969dd398ce0f5ea51
/src/quiz03.lean
0ea6a44784c575bb7a57ad0c53d5dfdf114cc71f
[]
no_license
UVM-M52/quiz-3-wharvey1
c16b6926ea0ec487d30a9758e8ba5f597760eeed
fe6ef54093e5982e03b7e343f3ad963bfe6ba772
refs/heads/master
1,610,153,132,281
1,582,305,504,000
1,582,305,504,000
242,192,661
0
0
null
null
null
null
UTF-8
Lean
false
false
660
lean
-- Math 52: Quiz 3 -- Open this file in a folder that contains 'utils'. import utils.int_refl definition is_even (n : ℤ) : Prop := ∃ (k : ℤ), n = 2 * k definition is_odd (n : ℤ) : Prop := ∃ (k : ℤ), n = 2 * k + 1 axiom even_or_odd (n : ℤ) : is_even n ∨ is_odd n theorem main : ∀ (n : ℤ), is_even (n * n + 3 * n + 2) := begin intro n, have H := even_or_odd n, cases H, { unfold is_even at H, unfold is_even, cases H with i Hi, existsi (2 * i * i + 3 * i + 1 : ℤ), rw Hi, int_refl [i], }, { unfold is_odd at H, unfold is_even, cases H with j Hj, existsi (2 * j * j + 5 * j + 3 : ℤ), rw Hj, int_refl [j], }, end
f5a1e68a411c95b569e7fa364ac5ebbf0bd4c302
b7f22e51856f4989b970961f794f1c435f9b8f78
/tests/lean/quot_ind_bug.lean
31b060c78b828da040ffdb5d9938a4c3cca84545
[ "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
169
lean
open quot variables {A : Type} [s : setoid A] {B : quot s → Prop} (c : ∀ (a : A), B (quot.mk a)) (a : A) check quot.ind c ⟦a⟧ check c a eval quot.ind c ⟦a⟧
753641afddc1a24724b855cad732f643d852bcaa
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/run/meta1.lean
da46919903a0998b1e926dc3518cf2ccbeb72755
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
leanprover/lean4
4bdf9790294964627eb9be79f5e8f6157780b4cc
f1f9dc0f2f531af3312398999d8b8303fa5f096b
refs/heads/master
1,693,360,665,786
1,693,350,868,000
1,693,350,868,000
129,571,436
2,827
311
Apache-2.0
1,694,716,156,000
1,523,760,560,000
Lean
UTF-8
Lean
false
false
4,724
lean
import Lean.Meta open Lean open Lean.Meta unsafe def tstInferType (mods : List Name) (e : Expr) : IO Unit := withImportModules (mods.map $ fun m => {module := m}) {} 0 fun env => do let (type, _, _) ← (inferType e : MetaM _).toIO { fileName := "", fileMap := default } { env := env } {} {}; IO.println (toString e ++ " : " ++ toString type) unsafe def tstWHNF (mods : List Name) (e : Expr) (t := TransparencyMode.default) : IO Unit := withImportModules (mods.map $ fun m => {module := m}) {} 0 fun env => do let (s, _, _) ← (whnf e : MetaM _).toIO { fileName := "", fileMap := default } { env := env }; IO.println (toString e ++ " ==> " ++ toString s) unsafe def tstIsProp (mods : List Name) (e : Expr) : IO Unit := withImportModules (mods.map $ fun m => {module := m}) {} 0 fun env => do let (b, _, _) ← (isProp e : MetaM _).toIO { fileName := "", fileMap := default } { env := env }; IO.println (toString e ++ ", isProp: " ++ toString b) def t1 : Expr := let map := mkConst `List.map [levelOne, levelOne]; let nat := mkConst `Nat []; let bool := mkConst `Bool []; mkAppN map #[nat, bool] #eval tstInferType [`Init.Data.List] t1 def t2 : Expr := let prop := mkSort levelZero; mkForall `x BinderInfo.default prop prop #eval tstInferType [`Init.Core] t2 def t3 : Expr := let nat := mkConst `Nat []; let natLe := mkConst `Nat.le []; let zero := mkLit (Literal.natVal 0); let p := mkAppN natLe #[mkBVar 0, zero]; mkForall `x BinderInfo.default nat p #eval tstInferType [`Init.Data.Nat] t3 def t4 : Expr := let nat := mkConst `Nat []; let p := mkAppN (mkConst `Nat.succ []) #[mkBVar 0]; mkLambda `x BinderInfo.default nat p #eval tstInferType [`Init.Core] t4 def t5 : Expr := let add := mkConst `Nat.add []; mkAppN add #[mkLit (Literal.natVal 3), mkLit (Literal.natVal 5)] #eval tstWHNF [`Init.Data.Nat] t5 #eval tstWHNF [`Init.Data.Nat] t5 TransparencyMode.reducible set_option pp.all true #check @List.cons Nat def t6 : Expr := let map := mkConst `List.map [levelOne, levelOne]; let nat := mkConst `Nat []; let add := mkConst `Nat.add []; let f := mkLambda `x BinderInfo.default nat (mkAppN add #[mkBVar 0, mkLit (Literal.natVal 1)]); let cons := mkApp (mkConst `List.cons [levelZero]) nat; let nil := mkApp (mkConst `List.nil [levelZero]) nat; let one := mkLit (Literal.natVal 1); let four := mkLit (Literal.natVal 4); let xs := mkApp (mkApp cons one) (mkApp (mkApp cons four) nil); mkAppN map #[nat, nat, f, xs] #eval tstInferType [`Init.Data.List] t6 #eval tstWHNF [`Init.Data.List] t6 #eval tstInferType [] $ mkSort levelZero #eval tstInferType [`Init.Data.List] $ mkLambda `a BinderInfo.implicit (mkSort levelOne) (mkLambda `x BinderInfo.default (mkBVar 0) (mkLambda `xs BinderInfo.default (mkApp (mkConst `List [levelZero]) (mkBVar 1)) (mkBVar 0))) def t7 : Expr := let nat := mkConst `Nat []; let one := mkLit (Literal.natVal 1); mkLet `x nat one one #eval tstInferType [`Init.Core] $ t7 #eval tstWHNF [`Init.Core] $ t7 def t8 : Expr := let nat := mkConst `Nat []; let one := mkLit (Literal.natVal 1); let add := mkConst `Nat.add []; mkLet `x nat one (mkAppN add #[one, mkBVar 0]) #eval tstInferType [`Init.Core] $ t8 #eval tstWHNF [`Init.Core] $ t8 def t9 : Expr := let nat := mkConst `Nat []; mkLet `a (mkSort levelOne) nat (mkForall `x BinderInfo.default (mkBVar 0) (mkBVar 1)) #eval tstInferType [`Init.Core] $ t9 #eval tstWHNF [`Init.Core] $ t9 #eval tstInferType [`Init.Core] $ mkLit (Literal.natVal 10) #eval tstInferType [`Init.Core] $ mkLit (Literal.strVal "hello") #eval tstInferType [`Init.Core] $ mkMData {} $ mkLit (Literal.natVal 10) def t10 : Expr := let nat := mkConst `Nat []; let refl := mkApp (mkConst `Eq.refl [levelOne]) nat; mkLambda `a BinderInfo.default nat (mkApp refl (mkBVar 0)) #eval tstInferType [`Init.Core] t10 #eval tstIsProp [`Init.Core] t10 #eval tstIsProp [`Init.Core] (mkAppN (mkConst `And []) #[mkConst `True [], mkConst `True []]) #eval tstIsProp [`Init.Core] (mkConst `And []) -- Example where isPropQuick fails #eval tstIsProp [`Init.Core] (mkAppN (mkConst `id [levelZero]) #[mkSort levelZero, mkAppN (mkConst `And []) #[mkConst `True [], mkConst `True []]]) #eval tstIsProp [`Init.Core] (mkAppN (mkConst `Eq [levelOne]) #[mkConst `Nat [], mkLit (Literal.natVal 0), mkLit (Literal.natVal 1)]) #eval tstIsProp [`Init.Core] $ mkForall `x BinderInfo.default (mkConst `Nat []) (mkAppN (mkConst `Eq [levelOne]) #[mkConst `Nat [], mkBVar 0, mkLit (Literal.natVal 1)]) #eval tstIsProp [`Init.Core] $ mkApp (mkLambda `x BinderInfo.default (mkConst `Nat []) (mkAppN (mkConst `Eq [levelOne]) #[mkConst `Nat [], mkBVar 0, mkLit (Literal.natVal 1)])) (mkLit (Literal.natVal 0))
8b650f436ada55d402bc46143ebe4a70e36ae971
957a80ea22c5abb4f4670b250d55534d9db99108
/library/init/category/alternative.lean
b949938fabbfd78c3e6b605ce9a93e8767cd03b6
[ "Apache-2.0" ]
permissive
GaloisInc/lean
aa1e64d604051e602fcf4610061314b9a37ab8cd
f1ec117a24459b59c6ff9e56a1d09d9e9e60a6c0
refs/heads/master
1,592,202,909,807
1,504,624,387,000
1,504,624,387,000
75,319,626
2
1
Apache-2.0
1,539,290,164,000
1,480,616,104,000
C++
UTF-8
Lean
false
false
1,265
lean
/- Copyright (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura -/ prelude import init.logic init.category.applicative universes u v class has_orelse (f : Type u → Type v) : Type (max (u+1) v) := (orelse : Π {α : Type u}, f α → f α → f α) infixr ` <|> `:2 := has_orelse.orelse class alternative (f : Type u → Type v) extends applicative f, has_orelse f : Type (max (u+1) v) := (failure : Π {α : Type u}, f α) section variables {f : Type u → Type v} [alternative f] {α : Type u} @[inline] def failure : f α := alternative.failure f @[inline] def guard {f : Type → Type v} [alternative f] (p : Prop) [decidable p] : f unit := if p then pure () else failure @[inline] def assert {f : Type → Type v} [alternative f] (p : Prop) [decidable p] : f (inhabited p) := if h : p then pure ⟨h⟩ else failure /- Later we define a coercion from bool to Prop, but this version will still be useful. Given (t : tactic bool), we can write t >>= guardb -/ @[inline] def guardb {f : Type → Type v} [alternative f] : bool → f unit | tt := pure () | ff := failure @[inline] def optional (x : f α) : f (option α) := some <$> x <|> pure none end
4360cfaf81b0c051b92dcad19bb204ac96e9087c
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/order/directed.lean
1f75f6bbcfe2f2072177c021e4c2fb0399be8e38
[ "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
8,719
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 data.set.basic import order.lattice import order.max /-! # Directed indexed families and sets This file defines directed indexed families and directed sets. An indexed family/set is directed iff each pair of elements has a shared upper bound. ## Main declarations * `directed r f`: Predicate stating that the indexed family `f` is `r`-directed. * `directed_on r s`: Predicate stating that the set `s` is `r`-directed. * `is_directed α r`: Prop-valued mixin stating that `α` is `r`-directed. Follows the style of the unbundled relation classes such as `is_total`. -/ open function universes u v w variables {α : Type u} {β : Type v} {ι : Sort w} (r r' s : α → α → Prop) local infix ` ≼ ` : 50 := r /-- A family of elements of α is directed (with respect to a relation `≼` on α) if there is a member of the family `≼`-above any pair in the family. -/ def directed (f : ι → α) := ∀ x y, ∃ z, f x ≼ f z ∧ f y ≼ f z /-- A subset of α is directed if there is an element of the set `≼`-above any pair of elements in the set. -/ def directed_on (s : set α) := ∀ (x ∈ s) (y ∈ s), ∃ z ∈ s, x ≼ z ∧ y ≼ z variables {r r'} theorem directed_on_iff_directed {s} : @directed_on α r s ↔ directed r (coe : s → α) := by simp [directed, directed_on]; refine ball_congr (λ x hx, by simp; refl) alias directed_on_iff_directed ↔ directed_on.directed_coe _ theorem directed_on_image {s} {f : β → α} : directed_on r (f '' s) ↔ directed_on (f ⁻¹'o r) s := by simp only [directed_on, set.ball_image_iff, set.bex_image_iff, order.preimage] lemma directed_on.mono' {s : set α} (hs : directed_on r s) (h : ∀ ⦃a⦄, a ∈ s → ∀ ⦃b⦄, b ∈ s → r a b → r' a b) : directed_on r' s := λ x hx y hy, let ⟨z, hz, hxz, hyz⟩ := hs _ hx _ hy in ⟨z, hz, h hx hz hxz, h hy hz hyz⟩ lemma directed_on.mono {s : set α} (h : directed_on r s) (H : ∀ {a b}, r a b → r' a b) : directed_on r' s := h.mono' $ λ _ _ _ _, H theorem directed_comp {ι} {f : ι → β} {g : β → α} : directed r (g ∘ f) ↔ directed (g ⁻¹'o r) f := iff.rfl theorem directed.mono {s : α → α → Prop} {ι} {f : ι → α} (H : ∀ a b, r a b → s a b) (h : directed r f) : directed s f := λ a b, let ⟨c, h₁, h₂⟩ := h a b in ⟨c, H _ _ h₁, H _ _ h₂⟩ theorem directed.mono_comp {ι} {rb : β → β → Prop} {g : α → β} {f : ι → α} (hg : ∀ ⦃x y⦄, x ≼ y → rb (g x) (g y)) (hf : directed r f) : directed rb (g ∘ f) := directed_comp.2 $ hf.mono hg /-- A monotone function on a sup-semilattice is directed. -/ lemma directed_of_sup [semilattice_sup α] {f : α → β} {r : β → β → Prop} (H : ∀ ⦃i j⦄, i ≤ j → r (f i) (f j)) : directed r f := λ a b, ⟨a ⊔ b, H le_sup_left, H le_sup_right⟩ lemma monotone.directed_le [semilattice_sup α] [preorder β] {f : α → β} : monotone f → directed (≤) f := directed_of_sup lemma antitone.directed_ge [semilattice_sup α] [preorder β] {f : α → β} (hf : antitone f) : directed (≥) f := directed_of_sup hf /-- A set stable by supremum is `≤`-directed. -/ lemma directed_on_of_sup_mem [semilattice_sup α] {S : set α} (H : ∀ ⦃i j⦄, i ∈ S → j ∈ S → i ⊔ j ∈ S) : directed_on (≤) S := λ a ha b hb, ⟨a ⊔ b, H ha hb, le_sup_left, le_sup_right⟩ lemma directed.extend_bot [preorder α] [order_bot α] {e : ι → β} {f : ι → α} (hf : directed (≤) f) (he : function.injective e) : directed (≤) (function.extend e f ⊥) := begin intros a b, rcases (em (∃ i, e i = a)).symm with ha | ⟨i, rfl⟩, { use b, simp [function.extend_apply' _ _ _ ha] }, rcases (em (∃ i, e i = b)).symm with hb | ⟨j, rfl⟩, { use e i, simp [function.extend_apply' _ _ _ hb] }, rcases hf i j with ⟨k, hi, hj⟩, use (e k), simp only [he.extend_apply, *, true_and] end /-- An antitone function on an inf-semilattice is directed. -/ lemma directed_of_inf [semilattice_inf α] {r : β → β → Prop} {f : α → β} (hf : ∀ a₁ a₂, a₁ ≤ a₂ → r (f a₂) (f a₁)) : directed r f := λ x y, ⟨x ⊓ y, hf _ _ inf_le_left, hf _ _ inf_le_right⟩ lemma monotone.directed_ge [semilattice_inf α] [preorder β] {f : α → β} (hf : monotone f) : directed (≥) f := directed_of_inf hf lemma antitone.directed_le [semilattice_inf α] [preorder β] {f : α → β} (hf : antitone f) : directed (≤) f := directed_of_inf hf /-- A set stable by infimum is `≥`-directed. -/ lemma directed_on_of_inf_mem [semilattice_inf α] {S : set α} (H : ∀ ⦃i j⦄, i ∈ S → j ∈ S → i ⊓ j ∈ S) : directed_on (≥) S := λ a ha b hb, ⟨a ⊓ b, H ha hb, inf_le_left, inf_le_right⟩ /-- `is_directed α r` states that for any elements `a`, `b` there exists an element `c` such that `r a c` and `r b c`. -/ class is_directed (α : Type*) (r : α → α → Prop) : Prop := (directed (a b : α) : ∃ c, r a c ∧ r b c) lemma directed_of (r : α → α → Prop) [is_directed α r] (a b : α) : ∃ c, r a c ∧ r b c := is_directed.directed _ _ lemma directed_id [is_directed α r] : directed r id := by convert directed_of r lemma directed_id_iff : directed r id ↔ is_directed α r := ⟨λ h, ⟨h⟩, @directed_id _ _⟩ lemma directed_on_univ [is_directed α r] : directed_on r set.univ := λ a _ b _, let ⟨c, hc⟩ := directed_of r a b in ⟨c, trivial, hc⟩ lemma directed_on_univ_iff : directed_on r set.univ ↔ is_directed α r := ⟨λ h, ⟨λ a b, let ⟨c, _, hc⟩ := h a trivial b trivial in ⟨c, hc⟩⟩, @directed_on_univ _ _⟩ @[priority 100] -- see Note [lower instance priority] instance is_total.to_is_directed [is_total α r] : is_directed α r := ⟨λ a b, or.cases_on (total_of r a b) (λ h, ⟨b, h, refl _⟩) (λ h, ⟨a, refl _, h⟩)⟩ lemma is_directed_mono [is_directed α r] (h : ∀ ⦃a b⦄, r a b → s a b) : is_directed α s := ⟨λ a b, let ⟨c, ha, hb⟩ := is_directed.directed a b in ⟨c, h ha, h hb⟩⟩ lemma exists_ge_ge [has_le α] [is_directed α (≤)] (a b : α) : ∃ c, a ≤ c ∧ b ≤ c := directed_of (≤) a b lemma exists_le_le [has_le α] [is_directed α (≥)] (a b : α) : ∃ c, c ≤ a ∧ c ≤ b := directed_of (≥) a b instance order_dual.is_directed_ge [has_le α] [is_directed α (≤)] : is_directed αᵒᵈ (≥) := by assumption instance order_dual.is_directed_le [has_le α] [is_directed α (≥)] : is_directed αᵒᵈ (≤) := by assumption section preorder variables [preorder α] {a : α} protected lemma is_min.is_bot [is_directed α (≥)] (h : is_min a) : is_bot a := λ b, let ⟨c, hca, hcb⟩ := exists_le_le a b in (h hca).trans hcb protected lemma is_max.is_top [is_directed α (≤)] (h : is_max a) : is_top a := h.to_dual.is_bot lemma is_top_or_exists_gt [is_directed α (≤)] (a : α) : is_top a ∨ (∃ b, a < b) := (em (is_max a)).imp is_max.is_top not_is_max_iff.mp lemma is_bot_or_exists_lt [is_directed α (≥)] (a : α) : is_bot a ∨ (∃ b, b < a) := @is_top_or_exists_gt αᵒᵈ _ _ a lemma is_bot_iff_is_min [is_directed α (≥)] : is_bot a ↔ is_min a := ⟨is_bot.is_min, is_min.is_bot⟩ lemma is_top_iff_is_max [is_directed α (≤)] : is_top a ↔ is_max a := ⟨is_top.is_max, is_max.is_top⟩ variables (β) [partial_order β] theorem exists_lt_of_directed_ge [is_directed β (≥)] [nontrivial β] : ∃ a b : β, a < b := begin rcases exists_pair_ne β with ⟨a, b, hne⟩, rcases is_bot_or_exists_lt a with ha|⟨c, hc⟩, exacts [⟨a, b, (ha b).lt_of_ne hne⟩, ⟨_, _, hc⟩] end theorem exists_lt_of_directed_le [is_directed β (≤)] [nontrivial β] : ∃ a b : β, a < b := let ⟨a, b, h⟩ := exists_lt_of_directed_ge βᵒᵈ in ⟨b, a, h⟩ end preorder @[priority 100] -- see Note [lower instance priority] instance semilattice_sup.to_is_directed_le [semilattice_sup α] : is_directed α (≤) := ⟨λ a b, ⟨a ⊔ b, le_sup_left, le_sup_right⟩⟩ @[priority 100] -- see Note [lower instance priority] instance semilattice_inf.to_is_directed_ge [semilattice_inf α] : is_directed α (≥) := ⟨λ a b, ⟨a ⊓ b, inf_le_left, inf_le_right⟩⟩ @[priority 100] -- see Note [lower instance priority] instance order_top.to_is_directed_le [has_le α] [order_top α] : is_directed α (≤) := ⟨λ a b, ⟨⊤, le_top, le_top⟩⟩ @[priority 100] -- see Note [lower instance priority] instance order_bot.to_is_directed_ge [has_le α] [order_bot α] : is_directed α (≥) := ⟨λ a b, ⟨⊥, bot_le, bot_le⟩⟩
b9bc1a023e304c847fc363530c0b461cb7395a6e
86f6f4f8d827a196a32bfc646234b73328aeb306
/examples/basics/unnamed_439.lean
a185e4120e2db1b67916ec3147312a248b7e398a
[]
no_license
jamescheuk91/mathematics_in_lean
09f1f87d2b0dce53464ff0cbe592c568ff59cf5e
4452499264e2975bca2f42565c0925506ba5dda3
refs/heads/master
1,679,716,410,967
1,613,957,947,000
1,613,957,947,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
339
lean
import data.real.basic variables a b c d : ℝ -- BEGIN example : (c * b) * a = b * (a * c) := by ring example : (a + b) * (a + b) = a * a + 2 * (a * b) + b * b := by ring example : (a + b) * (a - b) = a^2 - b^2 := by ring example (hyp : c = d * a + b) (hyp' : b = a * d) : c = 2 * a * d := begin rw [hyp, hyp'], ring end -- END
829fde300b53e1bf9b838a48523aafdd15a71212
c777c32c8e484e195053731103c5e52af26a25d1
/src/algebra/modeq.lean
26f397630e57b60075e100d67e29598dc28bbde4
[ "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
9,136
lean
/- Copyright (c) 2023 Yaël Dillies. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yaël Dillies -/ import data.int.modeq import group_theory.quotient_group /-! # Equality modulo an element This file defines equality modulo an element in a commutative group. ## Main definitions * `a ≡ b [PMOD p]`: `a` and `b` are congruent modulo a`p`. ## See also `smodeq` is a generalisation to arbitrary submodules. ## TODO Delete `int.modeq` in favour of `add_comm_group.modeq`. Generalise `smodeq` to `add_subgroup` and redefine `add_comm_group.modeq` using it. Once this is done, we can rename `add_comm_group.modeq` to `add_subgroup.modeq` and multiplicativise it. Longer term, we could generalise to submonoids and also unify with `nat.modeq`. -/ namespace add_comm_group variables {α : Type*} section add_comm_group variables [add_comm_group α] {p a a₁ a₂ b b₁ b₂ c : α} {n : ℕ} {z : ℤ} /-- `a ≡ b [PMOD p]` means that `b` is congruent to `a` modulo `p`. Equivalently (as shown in `algebra.order.to_interval_mod`), `b` does not lie in the open interval `(a, a + p)` modulo `p`, or `to_Ico_mod hp a` disagrees with `to_Ioc_mod hp a` at `b`, or `to_Ico_div hp a` disagrees with `to_Ioc_div hp a` at `b`. -/ def modeq (p a b : α) : Prop := ∃ z : ℤ, b - a = z • p notation a ` ≡ `:50 b ` [PMOD `:50 p `]`:0 := modeq p a b @[refl, simp] lemma modeq_refl (a : α) : a ≡ a [PMOD p] := ⟨0, by simp⟩ lemma modeq_rfl : a ≡ a [PMOD p] := modeq_refl _ lemma modeq_comm : a ≡ b [PMOD p] ↔ b ≡ a [PMOD p] := (equiv.neg _).exists_congr_left.trans $ by simp [modeq, ←neg_eq_iff_eq_neg] alias modeq_comm ↔ modeq.symm _ attribute [symm] modeq.symm @[trans] lemma modeq.trans : a ≡ b [PMOD p] → b ≡ c [PMOD p] → a ≡ c [PMOD p] := λ ⟨m, hm⟩ ⟨n, hn⟩, ⟨m + n, by simp [add_smul, ←hm, ←hn]⟩ instance : is_refl _ (modeq p) := ⟨modeq_refl⟩ @[simp] lemma neg_modeq_neg : -a ≡ -b [PMOD p] ↔ a ≡ b [PMOD p] := modeq_comm.trans $ by simp [modeq] alias neg_modeq_neg ↔ modeq.of_neg modeq.neg @[simp] lemma modeq_neg : a ≡ b [PMOD -p] ↔ a ≡ b [PMOD p] := modeq_comm.trans $ by simp [modeq, ←neg_eq_iff_eq_neg] alias modeq_neg ↔ modeq.of_neg' modeq.neg' lemma modeq_sub (a b : α) : a ≡ b [PMOD b - a] := ⟨1, (one_smul _ _).symm⟩ @[simp] lemma modeq_zero : a ≡ b [PMOD 0] ↔ a = b := by simp [modeq, sub_eq_zero, eq_comm] @[simp] lemma self_modeq_zero : p ≡ 0 [PMOD p] := ⟨-1, by simp⟩ @[simp] lemma zsmul_modeq_zero (z : ℤ) : z • p ≡ 0 [PMOD p] := ⟨-z, by simp⟩ lemma add_zsmul_modeq (z : ℤ) : a + z • p ≡ a [PMOD p] := ⟨-z, by simp⟩ lemma zsmul_add_modeq (z : ℤ) : z • p + a ≡ a [PMOD p] := ⟨-z, by simp⟩ lemma add_nsmul_modeq (n : ℕ) : a + n • p ≡ a [PMOD p] := ⟨-n, by simp⟩ lemma nsmul_add_modeq (n : ℕ) : n • p + a ≡ a [PMOD p] := ⟨-n, by simp⟩ namespace modeq protected lemma add_zsmul (z : ℤ) : a ≡ b [PMOD p] → a + z • p ≡ b [PMOD p] := (add_zsmul_modeq _).trans protected lemma zsmul_add (z : ℤ) : a ≡ b [PMOD p] → z • p + a ≡ b [PMOD p] := (zsmul_add_modeq _).trans protected lemma add_nsmul (n : ℕ) : a ≡ b [PMOD p] → a + n • p ≡ b [PMOD p] := (add_nsmul_modeq _).trans protected lemma nsmul_add (n : ℕ) : a ≡ b [PMOD p] → n • p + a ≡ b [PMOD p] := (nsmul_add_modeq _).trans protected lemma of_zsmul : a ≡ b [PMOD (z • p)] → a ≡ b [PMOD p] := λ ⟨m, hm⟩, ⟨m * z, by rwa [mul_smul]⟩ protected lemma of_nsmul : a ≡ b [PMOD (n • p)] → a ≡ b [PMOD p] := λ ⟨m, hm⟩, ⟨m * n, by rwa [mul_smul, coe_nat_zsmul]⟩ protected lemma zsmul : a ≡ b [PMOD p] → z • a ≡ z • b [PMOD (z • p)] := Exists.imp $ λ m hm, by rw [←smul_sub, hm, smul_comm] protected lemma nsmul : a ≡ b [PMOD p] → n • a ≡ n • b [PMOD (n • p)] := Exists.imp $ λ m hm, by rw [←smul_sub, hm, smul_comm] end modeq @[simp] lemma zsmul_modeq_zsmul [no_zero_smul_divisors ℤ α] (hn : z ≠ 0) : z • a ≡ z • b [PMOD (z • p)] ↔ a ≡ b [PMOD p] := exists_congr $ λ m, by rw [←smul_sub, smul_comm, smul_right_inj hn]; apply_instance @[simp] lemma nsmul_modeq_nsmul [no_zero_smul_divisors ℕ α] (hn : n ≠ 0) : n • a ≡ n • b [PMOD (n • p)] ↔ a ≡ b [PMOD p] := exists_congr $ λ m, by rw [←smul_sub, smul_comm, smul_right_inj hn]; apply_instance alias zsmul_modeq_zsmul ↔ modeq.zsmul_cancel _ alias nsmul_modeq_nsmul ↔ modeq.nsmul_cancel _ namespace modeq @[simp] protected lemma add_iff_left : a₁ ≡ b₁ [PMOD p] → (a₁ + a₂ ≡ b₁ + b₂ [PMOD p] ↔ a₂ ≡ b₂ [PMOD p]) := λ ⟨m, hm⟩, (equiv.add_left m).symm.exists_congr_left.trans $ by simpa [add_sub_add_comm, hm, add_smul] @[simp] protected lemma add_iff_right : a₂ ≡ b₂ [PMOD p] → (a₁ + a₂ ≡ b₁ + b₂ [PMOD p] ↔ a₁ ≡ b₁ [PMOD p]) := λ ⟨m, hm⟩, (equiv.add_right m).symm.exists_congr_left.trans $ by simpa [add_sub_add_comm, hm, add_smul] @[simp] protected lemma sub_iff_left : a₁ ≡ b₁ [PMOD p] → (a₁ - a₂ ≡ b₁ - b₂ [PMOD p] ↔ a₂ ≡ b₂ [PMOD p]) := λ ⟨m, hm⟩, (equiv.sub_left m).symm.exists_congr_left.trans $ by simpa [sub_sub_sub_comm, hm, sub_smul] @[simp] protected lemma sub_iff_right : a₂ ≡ b₂ [PMOD p] → (a₁ - a₂ ≡ b₁ - b₂ [PMOD p] ↔ a₁ ≡ b₁ [PMOD p]) := λ ⟨m, hm⟩, (equiv.sub_right m).symm.exists_congr_left.trans $ by simpa [sub_sub_sub_comm, hm, sub_smul] alias modeq.add_iff_left ↔ add_left_cancel add alias modeq.add_iff_right ↔ add_right_cancel _ alias modeq.sub_iff_left ↔ sub_left_cancel sub alias modeq.sub_iff_right ↔ sub_right_cancel _ attribute [protected] add_left_cancel add_right_cancel add sub_left_cancel sub_right_cancel sub protected lemma add_left (c : α) (h : a ≡ b [PMOD p]) : c + a ≡ c + b [PMOD p] := modeq_rfl.add h protected lemma sub_left (c : α) (h : a ≡ b [PMOD p]) : c - a ≡ c - b [PMOD p] := modeq_rfl.sub h protected lemma add_right (c : α) (h : a ≡ b [PMOD p]) : a + c ≡ b + c [PMOD p] := h.add modeq_rfl protected lemma sub_right (c : α) (h : a ≡ b [PMOD p]) : a - c ≡ b - c [PMOD p] := h.sub modeq_rfl protected lemma add_left_cancel' (c : α) : c + a ≡ c + b [PMOD p] → a ≡ b [PMOD p] := modeq_rfl.add_left_cancel protected lemma add_right_cancel' (c : α) : a + c ≡ b + c [PMOD p] → a ≡ b [PMOD p] := modeq_rfl.add_right_cancel protected lemma sub_left_cancel' (c : α) : c - a ≡ c - b [PMOD p] → a ≡ b [PMOD p] := modeq_rfl.sub_left_cancel protected lemma sub_right_cancel' (c : α) : a - c ≡ b - c [PMOD p] → a ≡ b [PMOD p] := modeq_rfl.sub_right_cancel end modeq lemma modeq_sub_iff_add_modeq' : a ≡ b - c [PMOD p] ↔ c + a ≡ b [PMOD p] := by simp [modeq, sub_sub] lemma modeq_sub_iff_add_modeq : a ≡ b - c [PMOD p] ↔ a + c ≡ b [PMOD p] := modeq_sub_iff_add_modeq'.trans $ by rw add_comm lemma sub_modeq_iff_modeq_add' : a - b ≡ c [PMOD p] ↔ a ≡ b + c [PMOD p] := modeq_comm.trans $ modeq_sub_iff_add_modeq'.trans modeq_comm lemma sub_modeq_iff_modeq_add : a - b ≡ c [PMOD p] ↔ a ≡ c + b [PMOD p] := modeq_comm.trans $ modeq_sub_iff_add_modeq.trans modeq_comm @[simp] lemma sub_modeq_zero : a - b ≡ 0 [PMOD p] ↔ a ≡ b [PMOD p] := by simp [sub_modeq_iff_modeq_add] @[simp] lemma add_modeq_left : a + b ≡ a [PMOD p] ↔ b ≡ 0 [PMOD p] := by simp [←modeq_sub_iff_add_modeq'] @[simp] lemma add_modeq_right : a + b ≡ b [PMOD p] ↔ a ≡ 0 [PMOD p] := by simp [←modeq_sub_iff_add_modeq] lemma modeq_iff_eq_add_zsmul : a ≡ b [PMOD p] ↔ ∃ z : ℤ, b = a + z • p := by simp_rw [modeq, sub_eq_iff_eq_add'] lemma not_modeq_iff_ne_add_zsmul : ¬a ≡ b [PMOD p] ↔ ∀ z : ℤ, b ≠ a + z • p := by rw [modeq_iff_eq_add_zsmul, not_exists] lemma modeq_iff_eq_mod_zmultiples : a ≡ b [PMOD p] ↔ (b : α ⧸ add_subgroup.zmultiples p) = a := by simp_rw [modeq_iff_eq_add_zsmul, quotient_add_group.eq_iff_sub_mem, add_subgroup.mem_zmultiples_iff, eq_sub_iff_add_eq', eq_comm] lemma not_modeq_iff_ne_mod_zmultiples : ¬a ≡ b [PMOD p] ↔ (b : α ⧸ add_subgroup.zmultiples p) ≠ a := modeq_iff_eq_mod_zmultiples.not end add_comm_group @[simp] lemma modeq_iff_int_modeq {a b z : ℤ} : a ≡ b [PMOD z] ↔ a ≡ b [ZMOD z] := by simp [modeq, dvd_iff_exists_eq_mul_left, int.modeq_iff_dvd] section add_comm_group_with_one variables [add_comm_group_with_one α] [char_zero α] @[simp, norm_cast] lemma int_cast_modeq_int_cast {a b z : ℤ} : a ≡ b [PMOD (z : α)] ↔ a ≡ b [PMOD z] := by simp_rw [modeq, ←int.cast_mul_eq_zsmul_cast]; norm_cast @[simp, norm_cast] lemma nat_cast_modeq_nat_cast {a b n : ℕ} : a ≡ b [PMOD (n : α)] ↔ a ≡ b [MOD n] := by simp_rw [←int.coe_nat_modeq_iff, ←modeq_iff_int_modeq, ←@int_cast_modeq_int_cast α, int.cast_coe_nat] alias int_cast_modeq_int_cast ↔ modeq.of_int_cast modeq.int_cast alias nat_cast_modeq_nat_cast ↔ _root_.nat.modeq.of_nat_cast modeq.nat_cast end add_comm_group_with_one end add_comm_group
8530d3e0adabc76122111b9519ed4defef535d46
21871395eaf77834250a3f1b20624be105ae17be
/adj.lean
7561cccc05555f9e43443bb548ef90721c8c89ab
[]
no_license
daniel-carranza/2-adj-lean-workspace
a60a16d99993351a08860575831ec7c5b801c39f
e3e9b99883e5056d2de1856b8adcb2f4625546e6
refs/heads/master
1,666,176,695,426
1,592,006,470,000
1,592,006,470,000
271,910,711
0
0
null
null
null
null
UTF-8
Lean
false
false
7,824
lean
/- Authors: Daniel Carranza, Jonathon Chang, Ryan Sandford Under the supervision of Chris Kapulkin Theorems about half-adjoint equivalences, including a proof that the left half-adjoint type is a proposition and is equivalent to the built-in equivalence type Last updated: 2020-06-12 -/ import hott.init hott.types.sigma hott.types.prod hott.types.pi hott.types.equiv .prelim .hty_rec open hott hott.eq hott_theory universes u v namespace equiv variables {A B: Type u} @[hott] def linv (g : B → A) (f : A → B) := Π(a : A), g (f a) = a @[hott] def rinv (g : B → A) (f : A → B) := Π(b : B), f (g b) = b @[hott] def qinv (f : A → B) := Σ(g : B → A), linv g f × rinv g f @[hott, instance] def is_contr_linv (f : A → B) [H : is_equiv f] : is_contr Σ(g : B → A), linv g f := begin apply is_trunc.is_trunc_equiv_closed -2, exact sigma.sigma_equiv_sigma_right (λ g: B → A, (eq_equiv_homotopy (g ∘ f) id)), apply is_trunc.is_trunc_equiv_closed -2, exact @fiber.sigma_char _ _ (pi.precompose f) id, exact @is_equiv.is_contr_fiber_of_is_equiv _ _ (pi.precompose f) (pi.precompose_equiv_is_equiv f) id end @[hott] def qinv_id_equiv_sigma_prod : qinv (@id A) ≃ Σ(g : A → A), g = id × g = id := sigma.sigma_equiv_sigma_right (λg, prod.prod_equiv_prod ((eq_equiv_homotopy g id)⁻¹ᵉ) (eq_equiv_homotopy g id)⁻¹ᵉ) @[hott] def qinv_id_sigma_prod_equiv_sigma_sigma : (Σ(g: A → A), g = id × g = id) ≃ Σ(g : A → A) (h : g = id), g = id := sigma.sigma_equiv_sigma_right (λg, (sigma.equiv_prod _ _)⁻¹ᵉ) @[hott] def qinv_id_sigma_sigma_equiv_id_eq : (Σ(g: A → A) (h : g = id), g = id) ≃ @id A = id := sigma.sigma_assoc_equiv (λh : Σg : A → A, g = id, h.1 = id) ⬝e sigma.sigma_equiv_of_is_contr_left (λh : Σg : A → A, g = id, h.1 = id) -- qinv is not a mere proposition @[hott] def qinv_equiv_pi_eq (f: A ≃ B) : qinv f.to_fun ≃ Π(x : A), x = x := by apply equiv.rec_on_ua_idp f; exact qinv_id_equiv_sigma_prod ⬝e qinv_id_sigma_prod_equiv_sigma_sigma ⬝e qinv_id_sigma_sigma_equiv_id_eq ⬝e (eq_equiv_homotopy _ _) @[hott] def rcoh (f : A → B) (h: qinv f) (x : A) := ap f (h.2.1 x) = h.2.2 (f x) @[hott] def lcoh (f : A → B) (h: qinv f) (y : B) := h.2.1 (h.1 y) = ap h.1 (h.2.2 y) -- Definition of a left half-adjoint equivalence @[hott] def is_hadj_l (f : A → B) := Σ(g : B → A) (η : linv g f) (ε : rinv g f), Π(y : B), lcoh f ⟨g, (η, ε)⟩ y -- Note: A proof of a similar statement is found under types.equiv -- This proof is included here for compatibility --- with the definitions above and in two_adj.lean @[hott, instance] def is_contr_rcoh (f : A → B) [H : is_equiv f] (u : Σ(g : B → A), rinv g f) : is_contr(Σ(l : linv u.1 f), Π(x : A), rcoh f ⟨u.1, (l, u.2)⟩ x) := begin apply @is_trunc.is_trunc_equiv_closed_rev _ (Σ(l : linv u.1 f), Π(x : A), u.2 (f x) = ap f (l x)) -2, apply sigma.sigma_equiv_sigma_right, intro η, apply pi.pi_equiv_pi_right, intro x, apply (eq_equiv_eq_symm (u.2 (f x)) (ap f (η x)))⁻¹ᵉ, exact is_equiv.is_contr_right_coherence f u end @[hott, instance] def is_contr_lcoh (f : A → B) [H : is_equiv f] (u : Σ(g : B → A), linv g f) : is_contr(Σ(r : rinv u.1 f), Π(y : B), lcoh f ⟨u.1, (u.2, r)⟩ y) := begin apply is_trunc.is_trunc_equiv_closed_rev -2 (sigma.sigma_pi_equiv_pi_sigma (λy, λr : f (u.1 y) = y, u.2 (u.1 y) = ap u.1 r)), apply is_trunc.is_trunc_equiv_closed -2 (pi.pi_equiv_pi_right ( λy : B, @fiber.fiber_eq_equiv _ _ u.1 (u.1 y) (fiber.mk (f (u.1 y)) (u.2 (u.1 y))) (fiber.mk y rfl) )), have : f⁻¹ᶠ = u.1 := (@is_trunc.eq_of_is_contr _ (is_contr_linv f) ⟨f⁻¹ᶠ, is_equiv.left_inv f⟩ u)..1, have : is_equiv u.1 := is_equiv.is_equiv_eq_closed this, exact @pi.is_trunc_pi _ _ -2 (λy, @is_trunc.is_contr_eq _ (@is_equiv.is_contr_fiber_of_is_equiv _ _ u.1 this (u.1 y)) (fiber.mk (f (u.1 y)) (u.2 (u.1 y))) (fiber.mk y rfl)) end -- Left half-adjoint equivalence is a mere proposition @[hott, instance] def is_prop_hadj_l (f : A → B) : is_prop (is_hadj_l f) := begin apply is_trunc.is_prop_of_imp_is_contr, intro h, apply is_trunc.is_trunc_equiv_closed_rev -2 ( sigma.sigma_assoc_equiv (λu: Σ(g : B → A), linv g f, Σ(r : rinv u.1 f), Π(y : B), lcoh f ⟨u.1, (u.2, r)⟩ y) ), have H : is_equiv f := is_equiv.adjointify f h.1 h.2.2.1 h.2.1, apply is_trunc.is_trunc_equiv_closed_rev -2 ( @sigma.sigma_equiv_of_is_contr_left _ (λu : Σ(g : B → A), linv g f, Σ(r : rinv u.1 f), Π(y : B), lcoh f ⟨u.1, (u.2, r)⟩ y) (@is_contr_linv _ _ f H)), exact @is_contr_lcoh _ _ f H _ end -- Left half-adjoint equivalence is equivalent to is_equiv @[hott] def is_hadj_l_equiv_is_equiv (f : A → B) : is_hadj_l f ≃ is_equiv f := is_trunc.equiv_of_is_prop (λh : is_hadj_l f, is_equiv.adjointify f h.1 h.2.2.1 h.2.1) (λH : is_equiv f, have Σ(r : rinv H.inv f), Π(y : B), lcoh f ⟨H.inv, (H.left_inv, r)⟩ y, from @is_trunc.center _ (@is_contr_lcoh _ _ f H ⟨H.inv, H.left_inv⟩), ⟨H.inv, ⟨H.left_inv, this⟩⟩) -- Promoting qinv to a left half-adjoint @[hott] def adjointify_left (f : A → B) (inv : B → A) (left_inv : linv inv f) (right_inv : rinv inv f) : is_hadj_l f := is_equiv.inv (is_hadj_l_equiv_is_equiv f) (is_equiv.adjointify f inv right_inv left_inv) -- Definition of a full-adjoint equivalence @[hott] def adj (f : A → B) := Σ(g : B → A) (η : g ∘ f ~ id) (ε : f ∘ g ~ id), (Π(x : A), rcoh f ⟨g, (η, ε)⟩ x) × (Π(y : B), lcoh f ⟨g, (η, ε)⟩ y) @[hott] def id_adj_equiv_no_linv : adj (@id A) ≃ Σ(ε : @id A ~ id), (Π(x : A), rfl = ε x) × (Π(x : A), rfl = ap id (ε x)) := sigma.sigma_assoc_equiv (λu : Σ(g : A → A), g ~ id, Σ(ε : u.1 ~ id), (Π(x : A), ap id (u.2 x) = ε x) × (Π(x : A), u.2 (u.1 x) = ap u.1 (ε x))) ⬝e @sigma.sigma_equiv_of_is_contr_left _ (λu : Σ(g : A → A), g ~ id, Σ(ε : u.1 ~ id), (Π(x : A), ap id (u.2 x) = ε x) × (Π(x : A), u.2 (u.1 x) = ap u.1 (ε x))) (is_trunc.sigma_hty_is_contr_right id) @[hott] def id_adj_equiv_no_rcoh : (Σ(ε : @id A ~ id), (Π(x : A), rfl = ε x) × (Π(x : A), rfl = ap id (ε x))) ≃ Π(x : A), hott.eq.refl x = rfl := @sigma.sigma_equiv_sigma_right (@id A ~ id) (λε, (Π(x : A), rfl = ε x) × (Π(x : A), rfl = ap id (ε x))) _ (λε, (sigma.equiv_prod (Π(x : A), rfl = ε x) (Π(x : A), rfl = ap id (ε x)))⁻¹ᵉ) ⬝e sigma.sigma_assoc_equiv (λu : Σ(ε : @id A ~ id), Π(x : A), rfl = ε x, Π(x : A), rfl = ap id (u.1 x)) ⬝e @sigma.sigma_equiv_of_is_contr_left _ (λu : Σ(ε : @id A ~ id), Π(x : A), rfl = ε x, Π(x : A), rfl = ap id (u.1 x)) (is_trunc.sigma_hty_is_contr hott.eq.refl) -- Full-adjoint equivalence is not a mere proposition -- Note: This is a formalization of exercise 4.1 in the HoTT book @[hott] def adj_equiv_pi_refl_eq (f: A ≃ B) : adj f ≃ Π(x: A), refl x = refl x := by apply equiv.rec_on_ua_idp f; exact id_adj_equiv_no_linv ⬝e id_adj_equiv_no_rcoh end equiv
248b14763d9510c1fbd1009fe233a4b43b423189
957a80ea22c5abb4f4670b250d55534d9db99108
/library/init/data/setoid.lean
e6459853eeaff0e1abf2080dec319c46caba91f0
[ "Apache-2.0" ]
permissive
GaloisInc/lean
aa1e64d604051e602fcf4610061314b9a37ab8cd
f1ec117a24459b59c6ff9e56a1d09d9e9e60a6c0
refs/heads/master
1,592,202,909,807
1,504,624,387,000
1,504,624,387,000
75,319,626
2
1
Apache-2.0
1,539,290,164,000
1,480,616,104,000
C++
UTF-8
Lean
false
false
812
lean
/- Copyright (c) 2015 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude import init.logic universes u class setoid (α : Sort u) := (r : α → α → Prop) (iseqv : equivalence r) namespace setoid infix ` ≈ ` := setoid.r variable {α : Sort u} variable [s : setoid α] include s @[refl] lemma refl (a : α) : a ≈ a := match setoid.iseqv α with | ⟨h_refl, h_symm, h_trans⟩ := h_refl a end @[symm] lemma symm {a b : α} (hab : a ≈ b) : b ≈ a := match setoid.iseqv α with | ⟨h_refl, h_symm, h_trans⟩ := h_symm hab end @[trans] lemma trans {a b c : α} (hab : a ≈ b) (hbc : b ≈ c) : a ≈ c := match setoid.iseqv α with | ⟨h_refl, h_symm, h_trans⟩ := h_trans hab hbc end end setoid
c55d45340ee5148814043cf037e842097759b8cd
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/measure_theory/covering/besicovitch.lean
e9026f3d122903909a00fe0886d9fdb1f936e38f
[ "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
60,324
lean
/- Copyright (c) 2021 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 measure_theory.covering.differentiation import measure_theory.covering.vitali_family import measure_theory.integral.lebesgue import measure_theory.measure.regular import set_theory.ordinal_arithmetic import topology.metric_space.basic /-! # Besicovitch covering theorems The topological Besicovitch covering theorem ensures that, in a nice metric space, there exists a number `N` such that, from any family of balls with bounded radii, one can extract `N` families, each made of disjoint balls, covering together all the centers of the initial family. By "nice metric space", we mean a technical property stated as follows: there exists no satellite configuration of `N + 1` points (with a given parameter `τ > 1`). Such a configuration is a family of `N + 1` balls, where the first `N` balls all intersect the last one, but none of them contains the center of another one and their radii are controlled. This property is for instance satisfied by finite-dimensional real vector spaces. In this file, we prove the topological Besicovitch covering theorem, in `besicovitch.exist_disjoint_covering_families`. The measurable Besicovitch theorem ensures that, in the same class of metric spaces, if at every point one considers a class of balls of arbitrarily small radii, called admissible balls, then one can cover almost all the space by a family of disjoint admissible balls. It is deduced from the topological Besicovitch theorem, and proved in `besicovitch.exists_disjoint_closed_ball_covering_ae`. This implies that balls of small radius form a Vitali family in such spaces. Therefore, theorems on differentiation of measures hold as a consequence of general results. We restate them in this context to make them more easily usable. ## Main definitions and results * `satellite_config α N τ` is the type of all satellite configurations of `N + 1` points in the metric space `α`, with parameter `τ`. * `has_besicovitch_covering` is a class recording that there exist `N` and `τ > 1` such that there is no satellite configuration of `N + 1` points with parameter `τ`. * `exist_disjoint_covering_families` is the topological Besicovitch covering theorem: from any family of balls one can extract finitely many disjoint subfamilies covering the same set. * `exists_disjoint_closed_ball_covering` is the measurable Besicovitch covering theorem: from any family of balls with arbitrarily small radii at every point, one can extract countably many disjoint balls covering almost all the space. While the value of `N` is relevant for the precise statement of the topological Besicovitch theorem, it becomes irrelevant for the measurable one. Therefore, this statement is expressed using the `Prop`-valued typeclass `has_besicovitch_covering`. We also restate the following specialized versions of general theorems on differentiation of measures: * `besicovitch.ae_tendsto_rn_deriv` ensures that `ρ (closed_ball x r) / μ (closed_ball x r)` tends almost surely to the Radon-Nikodym derivative of `ρ` with respect to `μ` at `x`. * `besicovitch.ae_tendsto_measure_inter_div` states that almost every point in an arbitrary set `s` is a Lebesgue density point, i.e., `μ (s ∩ closed_ball x r) / μ (closed_ball x r)` tends to `1` as `r` tends to `0`. A stronger version for measurable sets is given in `besicovitch.ae_tendsto_measure_inter_div_of_measurable_set`. ## Implementation #### Sketch of proof of the topological Besicovitch theorem: We choose balls in a greedy way. First choose a ball with maximal radius (or rather, since there is no guarantee the maximal radius is realized, a ball with radius within a factor `τ` of the supremum). Then, remove all balls whose center is covered by the first ball, and choose among the remaining ones a ball with radius close to maximum. Go on forever until there is no available center (this is a transfinite induction in general). Then define inductively a coloring of the balls. A ball will be of color `i` if it intersects already chosen balls of color `0`, ..., `i - 1`, but none of color `i`. In this way, balls of the same color form a disjoint family, and the space is covered by the families of the different colors. The nontrivial part is to show that at most `N` colors are used. If one needs `N + 1` colors, consider the first time this happens. Then the corresponding ball intersects `N` balls of the different colors. Moreover, the inductive construction ensures that the radii of all the balls are controlled: they form a satellite configuration with `N + 1` balls (essentially by definition of satellite configurations). Since we assume that there are no such configurations, this is a contradiction. #### Sketch of proof of the measurable Besicovitch theorem: From the topological Besicovitch theorem, one can find a disjoint countable family of balls covering a proportion `> 1 / (N + 1)` of the space. Taking a large enough finite subset of these balls, one gets the same property for finitely many balls. Their union is closed. Therefore, any point in the complement has around it an admissible ball not intersecting these finitely many balls. Applying again the topological Besicovitch theorem, one extracts from these a disjoint countable subfamily covering a proportion `> 1 / (N + 1)` of the remaining points, and then even a disjoint finite subfamily. Then one goes on again and again, covering at each step a positive proportion of the remaining points, while remaining disjoint from the already chosen balls. The union of all these balls is the desired almost everywhere covering. -/ noncomputable theory universe u open metric set filter fin measure_theory topological_space open_locale topological_space classical big_operators ennreal measure_theory nnreal /-! ### Satellite configurations -/ /-- A satellite configuration is a configuration of `N+1` points that shows up in the inductive construction for the Besicovitch covering theorem. It depends on some parameter `τ ≥ 1`. This is a family of balls (indexed by `i : fin N.succ`, with center `c i` and radius `r i`) such that the last ball intersects all the other balls (condition `inter`), and given any two balls there is an order between them, ensuring that the first ball does not contain the center of the other one, and the radius of the second ball can not be larger than the radius of the first ball (up to a factor `τ`). This order corresponds to the order of choice in the inductive construction: otherwise, the second ball would have been chosen before. This is the condition `h`. Finally, the last ball is chosen after all the other ones, meaning that `h` can be strengthened by keeping only one side of the alternative in `hlast`. -/ structure besicovitch.satellite_config (α : Type*) [metric_space α] (N : ℕ) (τ : ℝ) := (c : fin N.succ → α) (r : fin N.succ → ℝ) (rpos : ∀ i, 0 < r i) (h : ∀ i j, i ≠ j → (r i ≤ dist (c i) (c j) ∧ r j ≤ τ * r i) ∨ (r j ≤ dist (c j) (c i) ∧ r i ≤ τ * r j)) (hlast : ∀ i < last N, r i ≤ dist (c i) (c (last N)) ∧ r (last N) ≤ τ * r i) (inter : ∀ i < last N, dist (c i) (c (last N)) ≤ r i + r (last N)) /-- A metric space has the Besicovitch covering property if there exist `N` and `τ > 1` such that there are no satellite configuration of parameter `τ` with `N+1` points. This is the condition that guarantees that the measurable Besicovitch covering theorem holds. It is satified by finite-dimensional real vector spaces. -/ class has_besicovitch_covering (α : Type*) [metric_space α] : Prop := (no_satellite_config [] : ∃ (N : ℕ) (τ : ℝ), 1 < τ ∧ is_empty (besicovitch.satellite_config α N τ)) /-- There is always a satellite configuration with a single point. -/ instance {α : Type*} {τ : ℝ} [inhabited α] [metric_space α] : inhabited (besicovitch.satellite_config α 0 τ) := ⟨{ c := λ i, default, r := λ i, 1, rpos := λ i, zero_lt_one, h := λ i j hij, (hij (subsingleton.elim i j)).elim, hlast := λ i hi, by { rw subsingleton.elim i (last 0) at hi, exact (lt_irrefl _ hi).elim }, inter := λ i hi, by { rw subsingleton.elim i (last 0) at hi, exact (lt_irrefl _ hi).elim } }⟩ namespace besicovitch namespace satellite_config variables {α : Type*} [metric_space α] {N : ℕ} {τ : ℝ} (a : satellite_config α N τ) lemma inter' (i : fin N.succ) : dist (a.c i) (a.c (last N)) ≤ a.r i + a.r (last N) := begin rcases lt_or_le i (last N) with H|H, { exact a.inter i H }, { have I : i = last N := top_le_iff.1 H, have := (a.rpos (last N)).le, simp only [I, add_nonneg this this, dist_self] } end lemma hlast' (i : fin N.succ) (h : 1 ≤ τ) : a.r (last N) ≤ τ * a.r i := begin rcases lt_or_le i (last N) with H|H, { exact (a.hlast i H).2 }, { have : i = last N := top_le_iff.1 H, rw this, exact le_mul_of_one_le_left (a.rpos _).le h } end end satellite_config /-! ### Extracting disjoint subfamilies from a ball covering -/ /-- A ball package is a family of balls in a metric space with positive bounded radii. -/ structure ball_package (β : Type*) (α : Type*) := (c : β → α) (r : β → ℝ) (rpos : ∀ b, 0 < r b) (r_bound : ℝ) (r_le : ∀ b, r b ≤ r_bound) /-- The ball package made of unit balls. -/ def unit_ball_package (α : Type*) : ball_package α α := { c := id, r := λ _, 1, rpos := λ _, zero_lt_one, r_bound := 1, r_le := λ _, le_rfl } instance (α : Type*) : inhabited (ball_package α α) := ⟨unit_ball_package α⟩ /-- A Besicovitch tau-package is a family of balls in a metric space with positive bounded radii, together with enough data to proceed with the Besicovitch greedy algorithm. We register this in a single structure to make sure that all our constructions in this algorithm only depend on one variable. -/ structure tau_package (β : Type*) (α : Type*) extends ball_package β α := (τ : ℝ) (one_lt_tau : 1 < τ) instance (α : Type*) : inhabited (tau_package α α) := ⟨{ τ := 2, one_lt_tau := one_lt_two, .. unit_ball_package α }⟩ variables {α : Type*} [metric_space α] {β : Type u} namespace tau_package variables [nonempty β] (p : tau_package β α) include p /-- Choose inductively large balls with centers that are not contained in the union of already chosen balls. This is a transfinite induction. -/ noncomputable def index : ordinal.{u} → β | i := -- `Z` is the set of points that are covered by already constructed balls let Z := ⋃ (j : {j // j < i}), ball (p.c (index j)) (p.r (index j)), -- `R` is the supremum of the radii of balls with centers not in `Z` R := supr (λ b : {b : β // p.c b ∉ Z}, p.r b) in -- return an index `b` for which the center `c b` is not in `Z`, and the radius is at -- least `R / τ`, if such an index exists (and garbage otherwise). classical.epsilon (λ b : β, p.c b ∉ Z ∧ R ≤ p.τ * p.r b) using_well_founded {dec_tac := `[exact j.2]} /-- The set of points that are covered by the union of balls selected at steps `< i`. -/ def Union_up_to (i : ordinal.{u}) : set α := ⋃ (j : {j // j < i}), ball (p.c (p.index j)) (p.r (p.index j)) lemma monotone_Union_up_to : monotone p.Union_up_to := begin assume i j hij, simp only [Union_up_to], exact Union_mono' (λ r, ⟨⟨r, r.2.trans_le hij⟩, subset.rfl⟩), end /-- Supremum of the radii of balls whose centers are not yet covered at step `i`. -/ def R (i : ordinal.{u}) : ℝ := supr (λ b : {b : β // p.c b ∉ p.Union_up_to i}, p.r b) /-- Group the balls into disjoint families, by assigning to a ball the smallest color for which it does not intersect any already chosen ball of this color. -/ noncomputable def color : ordinal.{u} → ℕ | i := let A : set ℕ := ⋃ (j : {j // j < i}) (hj : (closed_ball (p.c (p.index j)) (p.r (p.index j)) ∩ closed_ball (p.c (p.index i)) (p.r (p.index i))).nonempty), {color j} in Inf (univ \ A) using_well_founded {dec_tac := `[exact j.2]} /-- `p.last_step` is the first ordinal where the construction stops making sense, i.e., `f` returns garbage since there is no point left to be chosen. We will only use ordinals before this step. -/ def last_step : ordinal.{u} := Inf {i | ¬ ∃ (b : β), p.c b ∉ p.Union_up_to i ∧ p.R i ≤ p.τ * p.r b} lemma last_step_nonempty : {i | ¬ ∃ (b : β), p.c b ∉ p.Union_up_to i ∧ p.R i ≤ p.τ * p.r b}.nonempty := begin by_contra, suffices H : function.injective p.index, from not_injective_of_ordinal p.index H, assume x y hxy, wlog x_le_y : x ≤ y := le_total x y using [x y, y x], rcases eq_or_lt_of_le x_le_y with rfl|H, { refl }, simp only [nonempty_def, not_exists, exists_prop, not_and, not_lt, not_le, mem_set_of_eq, not_forall] at h, specialize h y, have A : p.c (p.index y) ∉ p.Union_up_to y, { have : p.index y = classical.epsilon (λ b : β, p.c b ∉ p.Union_up_to y ∧ p.R y ≤ p.τ * p.r b), by { rw [tau_package.index], refl }, rw this, exact (classical.epsilon_spec h).1 }, simp only [Union_up_to, not_exists, exists_prop, mem_Union, mem_closed_ball, not_and, not_le, subtype.exists, subtype.coe_mk] at A, specialize A x H, simp [hxy] at A, exact (lt_irrefl _ ((p.rpos (p.index y)).trans_le A)).elim end /-- Every point is covered by chosen balls, before `p.last_step`. -/ lemma mem_Union_up_to_last_step (x : β) : p.c x ∈ p.Union_up_to p.last_step := begin have A : ∀ (z : β), p.c z ∈ p.Union_up_to p.last_step ∨ p.τ * p.r z < p.R p.last_step, { have : p.last_step ∈ {i | ¬ ∃ (b : β), p.c b ∉ p.Union_up_to i ∧ p.R i ≤ p.τ * p.r b} := Inf_mem p.last_step_nonempty, simpa only [not_exists, mem_set_of_eq, not_and_distrib, not_le, not_not_mem] }, by_contra, rcases A x with H|H, { exact h H }, have Rpos : 0 < p.R p.last_step, { apply lt_trans (mul_pos (_root_.zero_lt_one.trans p.one_lt_tau) (p.rpos _)) H }, have B : p.τ⁻¹ * p.R p.last_step < p.R p.last_step, { conv_rhs { rw ← one_mul (p.R p.last_step) }, exact mul_lt_mul (inv_lt_one p.one_lt_tau) le_rfl Rpos zero_le_one }, obtain ⟨y, hy1, hy2⟩ : ∃ (y : β), p.c y ∉ p.Union_up_to p.last_step ∧ (p.τ)⁻¹ * p.R p.last_step < p.r y, { simpa only [exists_prop, mem_range, exists_exists_and_eq_and, subtype.exists, subtype.coe_mk] using exists_lt_of_lt_cSup _ B, rw [← image_univ, nonempty_image_iff], exact ⟨⟨_, h⟩, mem_univ _⟩ }, rcases A y with Hy|Hy, { exact hy1 Hy }, { rw ← div_eq_inv_mul at hy2, have := (div_le_iff' (_root_.zero_lt_one.trans p.one_lt_tau)).1 hy2.le, exact lt_irrefl _ (Hy.trans_le this) } end /-- If there are no configurations of satellites with `N+1` points, one never uses more than `N` distinct families in the Besicovitch inductive construction. -/ lemma color_lt {i : ordinal.{u}} (hi : i < p.last_step) {N : ℕ} (hN : is_empty (satellite_config α N p.τ)) : p.color i < N := begin /- By contradiction, consider the first ordinal `i` for which one would have `p.color i = N`. Choose for each `k < N` a ball with color `k` that intersects the ball at color `i` (there is such a ball, otherwise one would have used the color `k` and not `N`). Then this family of `N+1` balls forms a satellite configuration, which is forbidden by the assumption `hN`. -/ induction i using ordinal.induction with i IH, let A : set ℕ := ⋃ (j : {j // j < i}) (hj : (closed_ball (p.c (p.index j)) (p.r (p.index j)) ∩ closed_ball (p.c (p.index i)) (p.r (p.index i))).nonempty), {p.color j}, have color_i : p.color i = Inf (univ \ A), by rw [color], rw color_i, have N_mem : N ∈ univ \ A, { simp only [not_exists, true_and, exists_prop, mem_Union, mem_singleton_iff, mem_closed_ball, not_and, mem_univ, mem_diff, subtype.exists, subtype.coe_mk], assume j ji hj, exact (IH j ji (ji.trans hi)).ne' }, suffices : Inf (univ \ A) ≠ N, { rcases (cInf_le (order_bot.bdd_below (univ \ A)) N_mem).lt_or_eq with H|H, { exact H }, { exact (this H).elim } }, assume Inf_eq_N, have : ∀ k, k < N → ∃ j, j < i ∧ (closed_ball (p.c (p.index j)) (p.r (p.index j)) ∩ closed_ball (p.c (p.index i)) (p.r (p.index i))).nonempty ∧ k = p.color j, { assume k hk, rw ← Inf_eq_N at hk, have : k ∈ A, by simpa only [true_and, mem_univ, not_not, mem_diff] using nat.not_mem_of_lt_Inf hk, simp at this, simpa only [exists_prop, mem_Union, mem_singleton_iff, mem_closed_ball, subtype.exists, subtype.coe_mk] }, choose! g hg using this, -- Choose for each `k < N` an ordinal `G k < i` giving a ball of color `k` intersecting -- the last ball. let G : ℕ → ordinal := λ n, if n = N then i else g n, have color_G : ∀ n, n ≤ N → p.color (G n) = n, { assume n hn, unfreezingI { rcases hn.eq_or_lt with rfl|H }, { simp only [G], simp only [color_i, Inf_eq_N, if_true, eq_self_iff_true] }, { simp only [G], simp only [H.ne, (hg n H).right.right.symm, if_false] } }, have G_lt_last : ∀ n, n ≤ N → G n < p.last_step, { assume n hn, unfreezingI { rcases hn.eq_or_lt with rfl|H }, { simp only [G], simp only [hi, if_true, eq_self_iff_true], }, { simp only [G], simp only [H.ne, (hg n H).left.trans hi, if_false] } }, have fGn : ∀ n, n ≤ N → p.c (p.index (G n)) ∉ p.Union_up_to (G n) ∧ p.R (G n) ≤ p.τ * p.r (p.index (G n)), { assume n hn, have: p.index (G n) = classical.epsilon (λ t, p.c t ∉ p.Union_up_to (G n) ∧ p.R (G n) ≤ p.τ * p.r t), by { rw index, refl }, rw this, have : ∃ t, p.c t ∉ p.Union_up_to (G n) ∧ p.R (G n) ≤ p.τ * p.r t, by simpa only [not_exists, exists_prop, not_and, not_lt, not_le, mem_set_of_eq, not_forall] using not_mem_of_lt_cInf (G_lt_last n hn) (order_bot.bdd_below _), exact classical.epsilon_spec this }, -- the balls with indices `G k` satisfy the characteristic property of satellite configurations. have Gab : ∀ (a b : fin (nat.succ N)), G a < G b → p.r (p.index (G a)) ≤ dist (p.c (p.index (G a))) (p.c (p.index (G b))) ∧ p.r (p.index (G b)) ≤ p.τ * p.r (p.index (G a)), { assume a b G_lt, have ha : (a : ℕ) ≤ N := nat.lt_succ_iff.1 a.2, have hb : (b : ℕ) ≤ N := nat.lt_succ_iff.1 b.2, split, { have := (fGn b hb).1, simp only [Union_up_to, not_exists, exists_prop, mem_Union, mem_closed_ball, not_and, not_le, subtype.exists, subtype.coe_mk] at this, simpa only [dist_comm, mem_ball, not_lt] using this (G a) G_lt }, { apply le_trans _ (fGn a ha).2, have B : p.c (p.index (G b)) ∉ p.Union_up_to (G a), { assume H, exact (fGn b hb).1 (p.monotone_Union_up_to G_lt.le H) }, let b' : {t // p.c t ∉ p.Union_up_to (G a)} := ⟨p.index (G b), B⟩, apply @le_csupr _ _ _ (λ t : {t // p.c t ∉ p.Union_up_to (G a)}, p.r t) _ b', refine ⟨p.r_bound, λ t ht, _⟩, simp only [exists_prop, mem_range, subtype.exists, subtype.coe_mk] at ht, rcases ht with ⟨u, hu⟩, rw ← hu.2, exact p.r_le _ } }, -- therefore, one may use them to construct a satellite configuration with `N+1` points let sc : satellite_config α N p.τ := { c := λ k, p.c (p.index (G k)), r := λ k, p.r (p.index (G k)), rpos := λ k, p.rpos (p.index (G k)), h := begin assume a b a_ne_b, wlog G_le : G a ≤ G b := le_total (G a) (G b) using [a b, b a] tactic.skip, { have G_lt : G a < G b, { rcases G_le.lt_or_eq with H|H, { exact H }, have A : (a : ℕ) ≠ b := fin.coe_injective.ne a_ne_b, rw [← color_G a (nat.lt_succ_iff.1 a.2), ← color_G b (nat.lt_succ_iff.1 b.2), H] at A, exact (A rfl).elim }, exact or.inl (Gab a b G_lt) }, { assume a_ne_b, rw or_comm, exact this a_ne_b.symm } end, hlast := begin assume a ha, have I : (a : ℕ) < N := ha, have : G a < G (fin.last N), by { dsimp [G], simp [I.ne, (hg a I).1] }, exact Gab _ _ this, end, inter := begin assume a ha, have I : (a : ℕ) < N := ha, have J : G (fin.last N) = i, by { dsimp [G], simp only [if_true, eq_self_iff_true], }, have K : G a = g a, { dsimp [G], simp [I.ne, (hg a I).1] }, convert dist_le_add_of_nonempty_closed_ball_inter_closed_ball (hg _ I).2.1, end }, -- this is a contradiction exact (hN.false : _) sc end end tau_package open tau_package /-- The topological Besicovitch covering theorem: there exist finitely many families of disjoint balls covering all the centers in a package. More specifically, one can use `N` families if there are no satellite configurations with `N+1` points. -/ theorem exist_disjoint_covering_families {N : ℕ} {τ : ℝ} (hτ : 1 < τ) (hN : is_empty (satellite_config α N τ)) (q : ball_package β α) : ∃ s : fin N → set β, (∀ (i : fin N), (s i).pairwise_disjoint (λ j, closed_ball (q.c j) (q.r j))) ∧ (range q.c ⊆ ⋃ (i : fin N), ⋃ (j ∈ s i), ball (q.c j) (q.r j)) := begin -- first exclude the trivial case where `β` is empty (we need non-emptiness for the transfinite -- induction, to be able to choose garbage when there is no point left). casesI is_empty_or_nonempty β, { refine ⟨λ i, ∅, λ i, pairwise_disjoint_empty, _⟩, rw [← image_univ, eq_empty_of_is_empty (univ : set β)], simp }, -- Now, assume `β` is nonempty. let p : tau_package β α := { τ := τ, one_lt_tau := hτ, .. q }, -- we use for `s i` the balls of color `i`. let s := λ (i : fin N), ⋃ (k : ordinal.{u}) (hk : k < p.last_step) (h'k : p.color k = i), ({p.index k} : set β), refine ⟨s, λ i, _, _⟩, { -- show that balls of the same color are disjoint assume x hx y hy x_ne_y, obtain ⟨jx, jx_lt, jxi, rfl⟩ : ∃ (jx : ordinal), jx < p.last_step ∧ p.color jx = i ∧ x = p.index jx, by simpa only [exists_prop, mem_Union, mem_singleton_iff] using hx, obtain ⟨jy, jy_lt, jyi, rfl⟩ : ∃ (jy : ordinal), jy < p.last_step ∧ p.color jy = i ∧ y = p.index jy, by simpa only [exists_prop, mem_Union, mem_singleton_iff] using hy, wlog jxy : jx ≤ jy := le_total jx jy using [jx jy, jy jx] tactic.skip, swap, { assume h1 h2 h3 h4 h5 h6 h7, rw [function.on_fun, disjoint.comm], exact this h4 h5 h6 h1 h2 h3 h7.symm }, replace jxy : jx < jy, by { rcases lt_or_eq_of_le jxy with H|rfl, { exact H }, { exact (x_ne_y rfl).elim } }, let A : set ℕ := ⋃ (j : {j // j < jy}) (hj : (closed_ball (p.c (p.index j)) (p.r (p.index j)) ∩ closed_ball (p.c (p.index jy)) (p.r (p.index jy))).nonempty), {p.color j}, have color_j : p.color jy = Inf (univ \ A), by rw [tau_package.color], have : p.color jy ∈ univ \ A, { rw color_j, apply Inf_mem, refine ⟨N, _⟩, simp only [not_exists, true_and, exists_prop, mem_Union, mem_singleton_iff, not_and, mem_univ, mem_diff, subtype.exists, subtype.coe_mk], assume k hk H, exact (p.color_lt (hk.trans jy_lt) hN).ne' }, simp only [not_exists, true_and, exists_prop, mem_Union, mem_singleton_iff, not_and, mem_univ, mem_diff, subtype.exists, subtype.coe_mk] at this, specialize this jx jxy, contrapose! this, simpa only [jxi, jyi, and_true, eq_self_iff_true, ← not_disjoint_iff_nonempty_inter] }, { -- show that the balls of color at most `N` cover every center. refine range_subset_iff.2 (λ b, _), obtain ⟨a, ha⟩ : ∃ (a : ordinal), a < p.last_step ∧ dist (p.c b) (p.c (p.index a)) < p.r (p.index a), by simpa only [Union_up_to, exists_prop, mem_Union, mem_ball, subtype.exists, subtype.coe_mk] using p.mem_Union_up_to_last_step b, simp only [exists_prop, mem_Union, mem_ball, mem_singleton_iff, bUnion_and', exists_eq_left, Union_exists, exists_and_distrib_left], exact ⟨⟨p.color a, p.color_lt ha.1 hN⟩, a, rfl, ha⟩ } end /-! ### The measurable Besicovitch covering theorem -/ open_locale nnreal variables [second_countable_topology α] [measurable_space α] [opens_measurable_space α] /-- Consider, for each `x` in a set `s`, a radius `r x ∈ (0, 1]`. Then one can find finitely many disjoint balls of the form `closed_ball x (r x)` covering a proportion `1/(N+1)` of `s`, if there are no satellite configurations with `N+1` points. -/ lemma exist_finset_disjoint_balls_large_measure (μ : measure α) [is_finite_measure μ] {N : ℕ} {τ : ℝ} (hτ : 1 < τ) (hN : is_empty (satellite_config α N τ)) (s : set α) (r : α → ℝ) (rpos : ∀ x ∈ s, 0 < r x) (rle : ∀ x ∈ s, r x ≤ 1) : ∃ (t : finset α), (↑t ⊆ s) ∧ μ (s \ (⋃ (x ∈ t), closed_ball x (r x))) ≤ N/(N+1) * μ s ∧ (t : set α).pairwise_disjoint (λ x, closed_ball x (r x)) := begin -- exclude the trivial case where `μ s = 0`. rcases le_or_lt (μ s) 0 with hμs|hμs, { have : μ s = 0 := le_bot_iff.1 hμs, refine ⟨∅, by simp only [finset.coe_empty, empty_subset], _, _⟩, { simp only [this, diff_empty, Union_false, Union_empty, nonpos_iff_eq_zero, mul_zero] }, { simp only [finset.coe_empty, pairwise_disjoint_empty], } }, casesI is_empty_or_nonempty α, { simp only [eq_empty_of_is_empty s, measure_empty] at hμs, exact (lt_irrefl _ hμs).elim }, have Npos : N ≠ 0, { unfreezingI { rintros rfl }, inhabit α, exact (not_is_empty_of_nonempty _) hN }, -- introduce a measurable superset `o` with the same measure, for measure computations obtain ⟨o, so, omeas, μo⟩ : ∃ (o : set α), s ⊆ o ∧ measurable_set o ∧ μ o = μ s := exists_measurable_superset μ s, /- We will apply the topological Besicovitch theorem, giving `N` disjoint subfamilies of balls covering `s`. Among these, one of them covers a proportion at least `1/N` of `s`. A large enough finite subfamily will then cover a proportion at least `1/(N+1)`. -/ let a : ball_package s α := { c := λ x, x, r := λ x, r x, rpos := λ x, rpos x x.2, r_bound := 1, r_le := λ x, rle x x.2 }, rcases exist_disjoint_covering_families hτ hN a with ⟨u, hu, hu'⟩, have u_count : ∀ i, countable (u i), { assume i, refine (hu i).countable_of_nonempty_interior (λ j hj, _), have : (ball (j : α) (r j)).nonempty := nonempty_ball.2 (a.rpos _), exact this.mono ball_subset_interior_closed_ball }, let v : fin N → set α := λ i, ⋃ (x : s) (hx : x ∈ u i), closed_ball x (r x), have : ∀ i, measurable_set (v i) := λ i, measurable_set.bUnion (u_count i) (λ b hb, measurable_set_closed_ball), have A : s = ⋃ (i : fin N), s ∩ v i, { refine subset.antisymm _ (Union_subset (λ i, inter_subset_left _ _)), assume x hx, obtain ⟨i, y, hxy, h'⟩ : ∃ (i : fin N) (i_1 : ↥s) (i : i_1 ∈ u i), x ∈ ball ↑i_1 (r ↑i_1), { have : x ∈ range a.c, by simpa only [subtype.range_coe_subtype, set_of_mem_eq], simpa only [mem_Union] using hu' this }, refine mem_Union.2 ⟨i, ⟨hx, _⟩⟩, simp only [v, exists_prop, mem_Union, set_coe.exists, exists_and_distrib_right, subtype.coe_mk], exact ⟨y, ⟨y.2, by simpa only [subtype.coe_eta]⟩, ball_subset_closed_ball h'⟩ }, have S : ∑ (i : fin N), μ s / N ≤ ∑ i, μ (s ∩ v i) := calc ∑ (i : fin N), μ s / N = μ s : begin simp only [finset.card_fin, finset.sum_const, nsmul_eq_mul], rw ennreal.mul_div_cancel', { simp only [Npos, ne.def, nat.cast_eq_zero, not_false_iff] }, { exact ennreal.coe_nat_ne_top } end ... ≤ ∑ i, μ (s ∩ v i) : by { conv_lhs { rw A }, apply measure_Union_fintype_le }, -- choose an index `i` of a subfamily covering at least a proportion `1/N` of `s`. obtain ⟨i, -, hi⟩ : ∃ (i : fin N) (hi : i ∈ finset.univ), μ s / N ≤ μ (s ∩ v i), { apply ennreal.exists_le_of_sum_le _ S, exact ⟨⟨0, bot_lt_iff_ne_bot.2 Npos⟩, finset.mem_univ _⟩ }, replace hi : μ s / (N + 1) < μ (s ∩ v i), { apply lt_of_lt_of_le _ hi, apply (ennreal.mul_lt_mul_left hμs.ne' (measure_lt_top μ s).ne).2, rw ennreal.inv_lt_inv, conv_lhs {rw ← add_zero (N : ℝ≥0∞) }, exact ennreal.add_lt_add_left (ennreal.nat_ne_top N) ennreal.zero_lt_one }, have B : μ (o ∩ v i) = ∑' (x : u i), μ (o ∩ closed_ball x (r x)), { have : o ∩ v i = ⋃ (x : s) (hx : x ∈ u i), o ∩ closed_ball x (r x), by simp only [inter_Union], rw [this, measure_bUnion (u_count i)], { refl }, { exact (hu i).mono (λ k, inter_subset_right _ _) }, { exact λ b hb, omeas.inter measurable_set_closed_ball } }, -- A large enough finite subfamily of `u i` will also cover a proportion `> 1/(N+1)` of `s`. -- Since `s` might not be measurable, we express this in terms of the measurable superset `o`. obtain ⟨w, hw⟩ : ∃ (w : finset (u i)), μ s / (N + 1) < ∑ (x : u i) in w, μ (o ∩ closed_ball (x : α) (r (x : α))), { have C : has_sum (λ (x : u i), μ (o ∩ closed_ball x (r x))) (μ (o ∩ v i)), by { rw B, exact ennreal.summable.has_sum }, have : μ s / (N+1) < μ (o ∩ v i) := hi.trans_le (measure_mono (inter_subset_inter_left _ so)), exact ((tendsto_order.1 C).1 _ this).exists }, -- Bring back the finset `w i` of `↑(u i)` to a finset of `α`, and check that it works by design. refine ⟨finset.image (λ (x : u i), x) w, _, _, _⟩, -- show that the finset is included in `s`. { simp only [image_subset_iff, coe_coe, finset.coe_image], assume y hy, simp only [subtype.coe_prop, mem_preimage] }, -- show that it covers a large enough proportion of `s`. For measure computations, we do not -- use `s` (which might not be measurable), but its measurable superset `o`. Since their measures -- are the same, this does not spoil the estimates { suffices H : μ (o \ ⋃ x ∈ w, closed_ball ↑x (r ↑x)) ≤ N/(N+1) * μ s, { rw [finset.set_bUnion_finset_image], exact le_trans (measure_mono (diff_subset_diff so (subset.refl _))) H }, rw [← diff_inter_self_eq_diff, measure_diff_le_iff_le_add _ (inter_subset_right _ _) ((measure_lt_top μ _).ne)], swap, { apply measurable_set.inter _ omeas, haveI : encodable (u i) := (u_count i).to_encodable, exact measurable_set.Union (λ b, measurable_set.Union_Prop (λ hb, measurable_set_closed_ball)) }, calc μ o = 1/(N+1) * μ s + N/(N+1) * μ s : by { rw [μo, ← add_mul, ennreal.div_add_div_same, add_comm, ennreal.div_self, one_mul]; simp } ... ≤ μ ((⋃ (x ∈ w), closed_ball ↑x (r ↑x)) ∩ o) + N/(N+1) * μ s : begin refine add_le_add _ le_rfl, rw [div_eq_mul_inv, one_mul, mul_comm, ← div_eq_mul_inv], apply hw.le.trans (le_of_eq _), rw [← finset.set_bUnion_coe, inter_comm _ o, inter_Union₂, finset.set_bUnion_coe, measure_bUnion_finset], { have : (w : set (u i)).pairwise_disjoint (λ (b : u i), closed_ball (b : α) (r (b : α))), by { assume k hk l hl hkl, exact hu i k.2 l.2 (subtype.coe_injective.ne hkl) }, exact this.mono (λ k, inter_subset_right _ _) }, { assume b hb, apply omeas.inter measurable_set_closed_ball } end }, -- show that the balls are disjoint { assume k hk l hl hkl, obtain ⟨k', k'w, rfl⟩ : ∃ (k' : u i), k' ∈ w ∧ ↑↑k' = k, by simpa only [mem_image, finset.mem_coe, coe_coe, finset.coe_image] using hk, obtain ⟨l', l'w, rfl⟩ : ∃ (l' : u i), l' ∈ w ∧ ↑↑l' = l, by simpa only [mem_image, finset.mem_coe, coe_coe, finset.coe_image] using hl, have k'nel' : (k' : s) ≠ l', by { assume h, rw h at hkl, exact hkl rfl }, exact hu i k'.2 l'.2 k'nel' } end variable [has_besicovitch_covering α] /-- The measurable Besicovitch covering theorem. Assume that, for any `x` in a set `s`, one is given a set of admissible closed balls centered at `x`, with arbitrarily small radii. Then there exists a disjoint covering of almost all `s` by admissible closed balls centered at some points of `s`. This version requires that the underlying measure is finite, and that the space has the Besicovitch covering property (which is satisfied for instance by normed real vector spaces). It expresses the conclusion in a slightly awkward form (with a subset of `α × ℝ`) coming from the proof technique. For a version assuming that the measure is sigma-finite, see `exists_disjoint_closed_ball_covering_ae_aux`. For a version giving the conclusion in a nicer form, see `exists_disjoint_closed_ball_covering_ae`. -/ theorem exists_disjoint_closed_ball_covering_ae_of_finite_measure_aux (μ : measure α) [is_finite_measure μ] (f : α → set ℝ) (s : set α) (hf : ∀ x ∈ s, ∀ δ > 0, (f x ∩ Ioo 0 δ).nonempty) : ∃ (t : set (α × ℝ)), (countable t) ∧ (∀ (p : α × ℝ), p ∈ t → p.1 ∈ s) ∧ (∀ (p : α × ℝ), p ∈ t → p.2 ∈ f p.1) ∧ μ (s \ (⋃ (p : α × ℝ) (hp : p ∈ t), closed_ball p.1 p.2)) = 0 ∧ t.pairwise_disjoint (λ p, closed_ball p.1 p.2) := begin rcases has_besicovitch_covering.no_satellite_config α with ⟨N, τ, hτ, hN⟩, /- Introduce a property `P` on finsets saying that we have a nice disjoint covering of a subset of `s` by admissible balls. -/ let P : finset (α × ℝ) → Prop := λ t, (t : set (α × ℝ)).pairwise_disjoint (λ p, closed_ball p.1 p.2) ∧ (∀ (p : α × ℝ), p ∈ t → p.1 ∈ s) ∧ (∀ (p : α × ℝ), p ∈ t → p.2 ∈ f p.1), /- Given a finite good covering of a subset `s`, one can find a larger finite good covering, covering additionally a proportion at least `1/(N+1)` of leftover points. This follows from `exist_finset_disjoint_balls_large_measure` applied to balls not intersecting the initial covering. -/ have : ∀ (t : finset (α × ℝ)), P t → ∃ (u : finset (α × ℝ)), t ⊆ u ∧ P u ∧ μ (s \ (⋃ (p : α × ℝ) (hp : p ∈ u), closed_ball p.1 p.2)) ≤ N/(N+1) * μ (s \ (⋃ (p : α × ℝ) (hp : p ∈ t), closed_ball p.1 p.2)), { assume t ht, set B := ⋃ (p : α × ℝ) (hp : p ∈ t), closed_ball p.1 p.2 with hB, have B_closed : is_closed B := is_closed_bUnion (finset.finite_to_set _) (λ i hi, is_closed_ball), set s' := s \ B with hs', have : ∀ x ∈ s', ∃ r ∈ f x ∩ Ioo 0 1, disjoint B (closed_ball x r), { assume x hx, have xs : x ∈ s := ((mem_diff x).1 hx).1, rcases eq_empty_or_nonempty B with hB|hB, { have : (0 : ℝ) < 1 := zero_lt_one, rcases hf x xs 1 zero_lt_one with ⟨r, hr, h'r⟩, exact ⟨r, ⟨hr, h'r⟩, by simp only [hB, empty_disjoint]⟩ }, { let R := inf_dist x B, have : 0 < min R 1 := lt_min ((B_closed.not_mem_iff_inf_dist_pos hB).1 ((mem_diff x).1 hx).2) zero_lt_one, rcases hf x xs _ this with ⟨r, hr, h'r⟩, refine ⟨r, ⟨hr, ⟨h'r.1, h'r.2.trans_le (min_le_right _ _)⟩⟩, _⟩, rw disjoint.comm, exact disjoint_closed_ball_of_lt_inf_dist (h'r.2.trans_le (min_le_left _ _)) } }, choose! r hr using this, obtain ⟨v, vs', hμv, hv⟩ : ∃ (v : finset α), ↑v ⊆ s' ∧ μ (s' \ ⋃ (x ∈ v), closed_ball x (r x)) ≤ N/(N+1) * μ s' ∧ (v : set α).pairwise_disjoint (λ (x : α), closed_ball x (r x)), { have rI : ∀ x ∈ s', r x ∈ Ioo (0 : ℝ) 1 := λ x hx, (hr x hx).1.2, exact exist_finset_disjoint_balls_large_measure μ hτ hN s' r (λ x hx, (rI x hx).1) (λ x hx, (rI x hx).2.le) }, refine ⟨t ∪ (finset.image (λ x, (x, r x)) v), finset.subset_union_left _ _, ⟨_, _, _⟩, _⟩, { simp only [finset.coe_union, pairwise_disjoint_union, ht.1, true_and, finset.coe_image], split, { assume p hp q hq hpq, rcases (mem_image _ _ _).1 hp with ⟨p', p'v, rfl⟩, rcases (mem_image _ _ _).1 hq with ⟨q', q'v, rfl⟩, refine hv p'v q'v (λ hp'q', _), rw [hp'q'] at hpq, exact hpq rfl }, { assume p hp q hq hpq, rcases (mem_image _ _ _).1 hq with ⟨q', q'v, rfl⟩, apply disjoint_of_subset_left _ (hr q' (vs' q'v)).2, rw [hB, ← finset.set_bUnion_coe], exact subset_bUnion_of_mem hp } }, { assume p hp, rcases finset.mem_union.1 hp with h'p|h'p, { exact ht.2.1 p h'p }, { rcases finset.mem_image.1 h'p with ⟨p', p'v, rfl⟩, exact ((mem_diff _).1 (vs' (finset.mem_coe.2 p'v))).1 } }, { assume p hp, rcases finset.mem_union.1 hp with h'p|h'p, { exact ht.2.2 p h'p }, { rcases finset.mem_image.1 h'p with ⟨p', p'v, rfl⟩, exact (hr p' (vs' p'v)).1.1 } }, { convert hμv using 2, rw [finset.set_bUnion_union, ← diff_diff, finset.set_bUnion_finset_image] } }, /- Define `F` associating to a finite good covering the above enlarged good covering, covering a proportion `1/(N+1)` of leftover points. Iterating `F`, one will get larger and larger good coverings, missing in the end only a measure-zero set. -/ choose! F hF using this, let u := λ n, F^[n] ∅, have u_succ : ∀ (n : ℕ), u n.succ = F (u n) := λ n, by simp only [u, function.comp_app, function.iterate_succ'], have Pu : ∀ n, P (u n), { assume n, induction n with n IH, { simp only [u, P, prod.forall, id.def, function.iterate_zero], simp only [finset.not_mem_empty, forall_false_left, finset.coe_empty, forall_2_true_iff, and_self, pairwise_disjoint_empty] }, { rw u_succ, exact (hF (u n) IH).2.1 } }, refine ⟨⋃ n, u n, countable_Union (λ n, (u n).countable_to_set), _, _, _, _⟩, { assume p hp, rcases mem_Union.1 hp with ⟨n, hn⟩, exact (Pu n).2.1 p (finset.mem_coe.1 hn) }, { assume p hp, rcases mem_Union.1 hp with ⟨n, hn⟩, exact (Pu n).2.2 p (finset.mem_coe.1 hn) }, { have A : ∀ n, μ (s \ ⋃ (p : α × ℝ) (hp : p ∈ ⋃ (n : ℕ), (u n : set (α × ℝ))), closed_ball p.fst p.snd) ≤ μ (s \ ⋃ (p : α × ℝ) (hp : p ∈ u n), closed_ball p.fst p.snd), { assume n, apply measure_mono, apply diff_subset_diff (subset.refl _), exact bUnion_subset_bUnion_left (subset_Union (λ i, (u i : set (α × ℝ))) n) }, have B : ∀ n, μ (s \ ⋃ (p : α × ℝ) (hp : p ∈ u n), closed_ball p.fst p.snd) ≤ (N/(N+1))^n * μ s, { assume n, induction n with n IH, { simp only [le_refl, diff_empty, one_mul, Union_false, Union_empty, pow_zero] }, calc μ (s \ ⋃ (p : α × ℝ) (hp : p ∈ u n.succ), closed_ball p.fst p.snd) ≤ (N/(N+1)) * μ (s \ ⋃ (p : α × ℝ) (hp : p ∈ u n), closed_ball p.fst p.snd) : by { rw u_succ, exact (hF (u n) (Pu n)).2.2 } ... ≤ (N/(N+1))^n.succ * μ s : by { rw [pow_succ, mul_assoc], exact ennreal.mul_le_mul le_rfl IH } }, have C : tendsto (λ (n : ℕ), ((N : ℝ≥0∞)/(N+1))^n * μ s) at_top (𝓝 (0 * μ s)), { apply ennreal.tendsto.mul_const _ (or.inr (measure_lt_top μ s).ne), apply ennreal.tendsto_pow_at_top_nhds_0_of_lt_1, rw [ennreal.div_lt_iff, one_mul], { conv_lhs {rw ← add_zero (N : ℝ≥0∞) }, exact ennreal.add_lt_add_left (ennreal.nat_ne_top N) ennreal.zero_lt_one }, { simp only [true_or, add_eq_zero_iff, ne.def, not_false_iff, one_ne_zero, and_false] }, { simp only [ennreal.nat_ne_top, ne.def, not_false_iff, or_true] } }, rw zero_mul at C, apply le_bot_iff.1, exact le_of_tendsto_of_tendsto' tendsto_const_nhds C (λ n, (A n).trans (B n)) }, { refine (pairwise_disjoint_Union _).2 (λ n, (Pu n).1), apply (monotone_nat_of_le_succ (λ n, _)).directed_le, rw u_succ, exact (hF (u n) (Pu n)).1 } end /-- The measurable Besicovitch covering theorem. Assume that, for any `x` in a set `s`, one is given a set of admissible closed balls centered at `x`, with arbitrarily small radii. Then there exists a disjoint covering of almost all `s` by admissible closed balls centered at some points of `s`. This version requires that the underlying measure is sigma-finite, and that the space has the Besicovitch covering property (which is satisfied for instance by normed real vector spaces). It expresses the conclusion in a slightly awkward form (with a subset of `α × ℝ`) coming from the proof technique. For a version giving the conclusion in a nicer form, see `exists_disjoint_closed_ball_covering_ae`. -/ theorem exists_disjoint_closed_ball_covering_ae_aux (μ : measure α) [sigma_finite μ] (f : α → set ℝ) (s : set α) (hf : ∀ x ∈ s, ∀ δ > 0, (f x ∩ Ioo 0 δ).nonempty) : ∃ (t : set (α × ℝ)), (countable t) ∧ (∀ (p : α × ℝ), p ∈ t → p.1 ∈ s) ∧ (∀ (p : α × ℝ), p ∈ t → p.2 ∈ f p.1) ∧ μ (s \ (⋃ (p : α × ℝ) (hp : p ∈ t), closed_ball p.1 p.2)) = 0 ∧ t.pairwise_disjoint (λ p, closed_ball p.1 p.2) := begin /- This is deduced from the finite measure case, by using a finite measure with respect to which the initial sigma-finite measure is absolutely continuous. -/ unfreezingI { rcases exists_absolutely_continuous_is_finite_measure μ with ⟨ν, hν, hμν⟩ }, rcases exists_disjoint_closed_ball_covering_ae_of_finite_measure_aux ν f s hf with ⟨t, t_count, ts, tr, tν, tdisj⟩, exact ⟨t, t_count, ts, tr, hμν tν, tdisj⟩, end /-- The measurable Besicovitch covering theorem. Assume that, for any `x` in a set `s`, one is given a set of admissible closed balls centered at `x`, with arbitrarily small radii. Then there exists a disjoint covering of almost all `s` by admissible closed balls centered at some points of `s`. We can even require that the radius at `x` is bounded by a given function `R x`. (Take `R = 1` if you don't need this additional feature). This version requires that the underlying measure is sigma-finite, and that the space has the Besicovitch covering property (which is satisfied for instance by normed real vector spaces). -/ theorem exists_disjoint_closed_ball_covering_ae (μ : measure α) [sigma_finite μ] (f : α → set ℝ) (s : set α) (hf : ∀ x ∈ s, ∀ δ > 0, (f x ∩ Ioo 0 δ).nonempty) (R : α → ℝ) (hR : ∀ x ∈ s, 0 < R x): ∃ (t : set α) (r : α → ℝ), countable t ∧ t ⊆ s ∧ (∀ x ∈ t, r x ∈ f x ∩ Ioo 0 (R x)) ∧ μ (s \ (⋃ (x ∈ t), closed_ball x (r x))) = 0 ∧ t.pairwise_disjoint (λ x, closed_ball x (r x)) := begin let g := λ x, f x ∩ Ioo 0 (R x), have hg : ∀ x ∈ s, ∀ δ > 0, (g x ∩ Ioo 0 δ).nonempty, { assume x hx δ δpos, rcases hf x hx (min δ (R x)) (lt_min δpos (hR x hx)) with ⟨r, hr⟩, exact ⟨r, ⟨⟨hr.1, hr.2.1, hr.2.2.trans_le (min_le_right _ _)⟩, ⟨hr.2.1, hr.2.2.trans_le (min_le_left _ _)⟩⟩⟩ }, rcases exists_disjoint_closed_ball_covering_ae_aux μ g s hg with ⟨v, v_count, vs, vg, μv, v_disj⟩, let t := prod.fst '' v, have : ∀ x ∈ t, ∃ (r : ℝ), (x, r) ∈ v, { assume x hx, rcases (mem_image _ _ _).1 hx with ⟨⟨p, q⟩, hp, rfl⟩, exact ⟨q, hp⟩ }, choose! r hr using this, have im_t : (λ x, (x, r x)) '' t = v, { have I : ∀ (p : α × ℝ), p ∈ v → 0 ≤ p.2 := λ p hp, (vg p hp).2.1.le, apply subset.antisymm, { simp only [image_subset_iff], rintros ⟨x, p⟩ hxp, simp only [mem_preimage], exact hr _ (mem_image_of_mem _ hxp) }, { rintros ⟨x, p⟩ hxp, have hxrx : (x, r x) ∈ v := hr _ (mem_image_of_mem _ hxp), have : p = r x, { by_contra, have A : (x, p) ≠ (x, r x), by simpa only [true_and, prod.mk.inj_iff, eq_self_iff_true, ne.def] using h, have H := v_disj hxp hxrx A, contrapose H, rw not_disjoint_iff_nonempty_inter, refine ⟨x, by simp [I _ hxp, I _ hxrx]⟩ }, rw this, apply mem_image_of_mem, exact mem_image_of_mem _ hxp } }, refine ⟨t, r, v_count.image _, _, _, _, _⟩, { assume x hx, rcases (mem_image _ _ _).1 hx with ⟨⟨p, q⟩, hp, rfl⟩, exact vs _ hp }, { assume x hx, rcases (mem_image _ _ _).1 hx with ⟨⟨p, q⟩, hp, rfl⟩, exact vg _ (hr _ hx) }, { have : (⋃ (x : α) (H : x ∈ t), closed_ball x (r x)) = (⋃ (p : α × ℝ) (H : p ∈ (λ x, (x, r x)) '' t), closed_ball p.1 p.2), by conv_rhs { rw bUnion_image }, rw [this, im_t], exact μv }, { have A : inj_on (λ x : α, (x, r x)) t, by simp only [inj_on, prod.mk.inj_iff, implies_true_iff, eq_self_iff_true] {contextual := tt}, rwa [← im_t, A.pairwise_disjoint_image] at v_disj } end /-- In a space with the Besicovitch property, any set `s` can be covered with balls whose measures add up to at most `μ s + ε`, for any positive `ε`. This works even if one restricts the set of allowed radii around a point `x` to a set `f x` which accumulates at `0`. -/ theorem exists_closed_ball_covering_tsum_measure_le (μ : measure α) [sigma_finite μ] [measure.outer_regular μ] {ε : ℝ≥0∞} (hε : ε ≠ 0) (f : α → set ℝ) (s : set α) (hf : ∀ x ∈ s, ∀ δ > 0, (f x ∩ Ioo 0 δ).nonempty) : ∃ (t : set α) (r : α → ℝ), countable t ∧ t ⊆ s ∧ (∀ x ∈ t, r x ∈ f x) ∧ s ⊆ (⋃ (x ∈ t), closed_ball x (r x)) ∧ ∑' (x : t), μ (closed_ball x (r x)) ≤ μ s + ε := begin /- For the proof, first cover almost all `s` with disjoint balls thanks to the usual Besicovitch theorem. Taking the balls included in a well-chosen open neighborhood `u` of `s`, one may ensure that their measures add at most to `μ s + ε / 2`. Let `s'` be the remaining set, of measure `0`. Applying the other version of Besicovitch, one may cover it with at most `N` disjoint subfamilies. Making sure that they are all included in a neighborhood `v` of `s'` of measure at most `ε / (2 N)`, the sum of their measures is at most `ε / 2`, completing the proof. -/ obtain ⟨u, su, u_open, μu⟩ : ∃ U ⊇ s, is_open U ∧ μ U ≤ μ s + ε / 2 := set.exists_is_open_le_add _ _ (by simpa only [or_false, ne.def, ennreal.div_zero_iff, ennreal.one_ne_top, ennreal.bit0_eq_top_iff] using hε), have : ∀ x ∈ s, ∃ R > 0, ball x R ⊆ u := λ x hx, metric.mem_nhds_iff.1 (u_open.mem_nhds (su hx)), choose! R hR using this, obtain ⟨t0, r0, t0_count, t0s, hr0, μt0, t0_disj⟩ : ∃ (t0 : set α) (r0 : α → ℝ), countable t0 ∧ t0 ⊆ s ∧ (∀ x ∈ t0, r0 x ∈ f x ∩ Ioo 0 (R x)) ∧ μ (s \ (⋃ (x ∈ t0), closed_ball x (r0 x))) = 0 ∧ t0.pairwise_disjoint (λ x, closed_ball x (r0 x)) := exists_disjoint_closed_ball_covering_ae μ f s hf R (λ x hx, (hR x hx).1), -- we have constructed an almost everywhere covering of `s` by disjoint balls. Let `s'` be the -- remaining set. let s' := s \ (⋃ (x ∈ t0), closed_ball x (r0 x)), have s's : s' ⊆ s := diff_subset _ _, obtain ⟨N, τ, hτ, H⟩ : ∃ N τ, 1 < τ ∧ is_empty (besicovitch.satellite_config α N τ) := has_besicovitch_covering.no_satellite_config α, obtain ⟨v, s'v, v_open, μv⟩ : ∃ v ⊇ s', is_open v ∧ μ v ≤ μ s' + (ε / 2) / N := set.exists_is_open_le_add _ _ (by simp only [hε, ennreal.nat_ne_top, with_top.mul_eq_top_iff, ne.def, ennreal.div_zero_iff, ennreal.one_ne_top, not_false_iff, and_false, false_and, or_self, ennreal.bit0_eq_top_iff]), have : ∀ x ∈ s', ∃ r1 ∈ (f x ∩ Ioo (0 : ℝ) 1), closed_ball x r1 ⊆ v, { assume x hx, rcases metric.mem_nhds_iff.1 (v_open.mem_nhds (s'v hx)) with ⟨r, rpos, hr⟩, rcases hf x (s's hx) (min r 1) (lt_min rpos zero_lt_one) with ⟨R', hR'⟩, exact ⟨R', ⟨hR'.1, hR'.2.1, hR'.2.2.trans_le (min_le_right _ _)⟩, subset.trans (closed_ball_subset_ball (hR'.2.2.trans_le (min_le_left _ _))) hr⟩, }, choose! r1 hr1 using this, let q : ball_package s' α := { c := λ x, x, r := λ x, r1 x, rpos := λ x, (hr1 x.1 x.2).1.2.1, r_bound := 1, r_le := λ x, (hr1 x.1 x.2).1.2.2.le }, -- by Besicovitch, we cover `s'` with at most `N` families of disjoint balls, all included in -- a suitable neighborhood `v` of `s'`. obtain ⟨S, S_disj, hS⟩ : ∃ S : fin N → set s', (∀ (i : fin N), (S i).pairwise_disjoint (λ j, closed_ball (q.c j) (q.r j))) ∧ (range q.c ⊆ ⋃ (i : fin N), ⋃ (j ∈ S i), ball (q.c j) (q.r j)) := exist_disjoint_covering_families hτ H q, have S_count : ∀ i, countable (S i), { assume i, apply (S_disj i).countable_of_nonempty_interior (λ j hj, _), have : (ball (j : α) (r1 j)).nonempty := nonempty_ball.2 (q.rpos _), exact this.mono ball_subset_interior_closed_ball }, let r := λ x, if x ∈ s' then r1 x else r0 x, have r_t0 : ∀ x ∈ t0, r x = r0 x, { assume x hx, have : ¬ (x ∈ s'), { simp only [not_exists, exists_prop, mem_Union, mem_closed_ball, not_and, not_lt, not_le, mem_diff, not_forall], assume h'x, refine ⟨x, hx, _⟩, rw dist_self, exact (hr0 x hx).2.1.le }, simp only [r, if_neg this] }, -- the desired covering set is given by the union of the families constructed in the first and -- second steps. refine ⟨t0 ∪ (⋃ (i : fin N), (coe : s' → α) '' (S i)), r, _, _, _, _, _⟩, -- it remains to check that they have the desired properties { exact t0_count.union (countable_Union (λ i, (S_count i).image _)) }, { simp only [t0s, true_and, union_subset_iff, image_subset_iff, Union_subset_iff], assume i x hx, exact s's x.2 }, { assume x hx, cases hx, { rw r_t0 x hx, exact (hr0 _ hx).1 }, { have h'x : x ∈ s', { simp only [mem_Union, mem_image] at hx, rcases hx with ⟨i, y, ySi, rfl⟩, exact y.2 }, simp only [r, if_pos h'x, (hr1 x h'x).1.1] } }, { assume x hx, by_cases h'x : x ∈ s', { obtain ⟨i, y, ySi, xy⟩ : ∃ (i : fin N) (y : ↥s') (ySi : y ∈ S i), x ∈ ball (y : α) (r1 y), { have A : x ∈ range q.c, by simpa only [not_exists, exists_prop, mem_Union, mem_closed_ball, not_and, not_le, mem_set_of_eq, subtype.range_coe_subtype, mem_diff] using h'x, simpa only [mem_Union, mem_image] using hS A }, refine mem_Union₂.2 ⟨y, or.inr _, _⟩, { simp only [mem_Union, mem_image], exact ⟨i, y, ySi, rfl⟩ }, { have : (y : α) ∈ s' := y.2, simp only [r, if_pos this], exact ball_subset_closed_ball xy } }, { obtain ⟨y, yt0, hxy⟩ : ∃ (y : α), y ∈ t0 ∧ x ∈ closed_ball y (r0 y), by simpa [hx, -mem_closed_ball] using h'x, refine mem_Union₂.2 ⟨y, or.inl yt0, _⟩, rwa r_t0 _ yt0 } }, -- the only nontrivial property is the measure control, which we check now { -- the sets in the first step have measure at most `μ s + ε / 2` have A : ∑' (x : t0), μ (closed_ball x (r x)) ≤ μ s + ε / 2 := calc ∑' (x : t0), μ (closed_ball x (r x)) = ∑' (x : t0), μ (closed_ball x (r0 x)) : by { congr' 1, ext x, rw r_t0 x x.2 } ... = μ (⋃ (x : t0), closed_ball x (r0 x)) : begin haveI : encodable t0 := t0_count.to_encodable, rw measure_Union, { exact (pairwise_subtype_iff_pairwise_set _ _).2 t0_disj }, { exact λ i, measurable_set_closed_ball } end ... ≤ μ u : begin apply measure_mono, simp only [set_coe.forall, subtype.coe_mk, Union_subset_iff], assume x hx, apply subset.trans (closed_ball_subset_ball (hr0 x hx).2.2) (hR x (t0s hx)).2, end ... ≤ μ s + ε / 2 : μu, -- each subfamily in the second step has measure at most `ε / (2 N)`. have B : ∀ (i : fin N), ∑' (x : (coe : s' → α) '' (S i)), μ (closed_ball x (r x)) ≤ (ε / 2) / N := λ i, calc ∑' (x : (coe : s' → α) '' (S i)), μ (closed_ball x (r x)) = ∑' (x : S i), μ (closed_ball x (r x)) : begin have : inj_on (coe : s' → α) (S i) := subtype.coe_injective.inj_on _, let F : S i ≃ (coe : s' → α) '' (S i) := this.bij_on_image.equiv _, exact (F.tsum_eq (λ x, μ (closed_ball x (r x)))).symm, end ... = ∑' (x : S i), μ (closed_ball x (r1 x)) : by { congr' 1, ext x, have : (x : α) ∈ s' := x.1.2, simp only [r, if_pos this] } ... = μ (⋃ (x : S i), closed_ball x (r1 x)) : begin haveI : encodable (S i) := (S_count i).to_encodable, rw measure_Union, { exact (pairwise_subtype_iff_pairwise_set _ _).2 (S_disj i) }, { exact λ i, measurable_set_closed_ball } end ... ≤ μ v : begin apply measure_mono, simp only [set_coe.forall, subtype.coe_mk, Union_subset_iff], assume x xs' xSi, exact (hr1 x xs').2, end ... ≤ (ε / 2) / N : by { have : μ s' = 0 := μt0, rwa [this, zero_add] at μv }, -- add up all these to prove the desired estimate calc ∑' (x : (t0 ∪ ⋃ (i : fin N), (coe : s' → α) '' S i)), μ (closed_ball x (r x)) ≤ ∑' (x : t0), μ (closed_ball x (r x)) + ∑' (x : ⋃ (i : fin N), (coe : s' → α) '' S i), μ (closed_ball x (r x)) : ennreal.tsum_union_le (λ x, μ (closed_ball x (r x))) _ _ ... ≤ ∑' (x : t0), μ (closed_ball x (r x)) + ∑ (i : fin N), ∑' (x : (coe : s' → α) '' S i), μ (closed_ball x (r x)) : add_le_add le_rfl (ennreal.tsum_Union_le (λ x, μ (closed_ball x (r x))) _) ... ≤ (μ s + ε / 2) + ∑ (i : fin N), (ε / 2) / N : begin refine add_le_add A _, refine finset.sum_le_sum _, assume i hi, exact B i end ... ≤ (μ s + ε / 2) + ε / 2 : begin refine add_le_add le_rfl _, simp only [finset.card_fin, finset.sum_const, nsmul_eq_mul, ennreal.mul_div_le], end ... = μ s + ε : by rw [add_assoc, ennreal.add_halves] } end /-! ### Consequences on differentiation of measures -/ /-- In a space with the Besicovitch covering property, the set of closed balls with positive radius forms a Vitali family. This is essentially a restatement of the measurable Besicovitch theorem. -/ protected def vitali_family (μ : measure α) [sigma_finite μ] : vitali_family μ := { sets_at := λ x, (λ (r : ℝ), closed_ball x r) '' (Ioi (0 : ℝ)), measurable_set' := begin assume x y hy, obtain ⟨r, rpos, rfl⟩ : ∃ (r : ℝ), 0 < r ∧ closed_ball x r = y, by simpa only [mem_image, mem_Ioi] using hy, exact is_closed_ball.measurable_set end, nonempty_interior := begin assume x y hy, obtain ⟨r, rpos, rfl⟩ : ∃ (r : ℝ), 0 < r ∧ closed_ball x r = y, by simpa only [mem_image, mem_Ioi] using hy, simp only [nonempty.mono ball_subset_interior_closed_ball, rpos, nonempty_ball], end, nontrivial := λ x ε εpos, ⟨closed_ball x ε, mem_image_of_mem _ εpos, subset.refl _⟩, covering := begin assume s f fsubset ffine, let g : α → set ℝ := λ x, {r | 0 < r ∧ closed_ball x r ∈ f x}, have A : ∀ x ∈ s, ∀ δ > 0, (g x ∩ Ioo 0 δ).nonempty, { assume x xs δ δpos, obtain ⟨t, tf, ht⟩ : ∃ (t : set α) (H : t ∈ f x), t ⊆ closed_ball x (δ/2) := ffine x xs (δ/2) (half_pos δpos), obtain ⟨r, rpos, rfl⟩ : ∃ (r : ℝ), 0 < r ∧ closed_ball x r = t, by simpa using fsubset x xs tf, rcases le_total r (δ/2) with H|H, { exact ⟨r, ⟨rpos, tf⟩, ⟨rpos, H.trans_lt (half_lt_self δpos)⟩⟩ }, { have : closed_ball x r = closed_ball x (δ/2) := subset.antisymm ht (closed_ball_subset_closed_ball H), rw this at tf, refine ⟨δ/2, ⟨half_pos δpos, tf⟩, ⟨half_pos δpos, half_lt_self δpos⟩⟩ } }, obtain ⟨t, r, t_count, ts, tg, μt, tdisj⟩ : ∃ (t : set α) (r : α → ℝ), countable t ∧ t ⊆ s ∧ (∀ x ∈ t, r x ∈ g x ∩ Ioo 0 1) ∧ μ (s \ (⋃ (x ∈ t), closed_ball x (r x))) = 0 ∧ t.pairwise_disjoint (λ x, closed_ball x (r x)) := exists_disjoint_closed_ball_covering_ae μ g s A (λ _, 1) (λ _ _, zero_lt_one), exact ⟨t, λ x, closed_ball x (r x), ts, tdisj, λ x xt, (tg x xt).1.2, μt⟩, end } /-- The main feature of the Besicovitch Vitali family is that its filter at a point `x` corresponds to convergence along closed balls. We record one of the two implications here, which will enable us to deduce specific statements on differentiation of measures in this context from the general versions. -/ lemma tendsto_filter_at (μ : measure α) [sigma_finite μ] (x : α) : tendsto (λ r, closed_ball x r) (𝓝[>] 0) ((besicovitch.vitali_family μ).filter_at x) := begin assume s hs, simp only [mem_map], obtain ⟨ε, εpos, hε⟩ : ∃ (ε : ℝ) (H : ε > 0), ∀ (a : set α), a ∈ (besicovitch.vitali_family μ).sets_at x → a ⊆ closed_ball x ε → a ∈ s := (vitali_family.mem_filter_at_iff _).1 hs, have : Ioc (0 : ℝ) ε ∈ 𝓝[>] (0 : ℝ) := Ioc_mem_nhds_within_Ioi ⟨le_rfl, εpos⟩, filter_upwards [this] with _ hr, apply hε, { exact mem_image_of_mem _ hr.1 }, { exact closed_ball_subset_closed_ball hr.2 } end variables [metric_space β] [measurable_space β] [borel_space β] [sigma_compact_space β] [has_besicovitch_covering β] /-- In a space with the Besicovitch covering property, the ratio of the measure of balls converges almost surely to to the Radon-Nikodym derivative. -/ lemma ae_tendsto_rn_deriv (ρ μ : measure β) [is_locally_finite_measure μ] [is_locally_finite_measure ρ] : ∀ᵐ x ∂μ, tendsto (λ r, ρ (closed_ball x r) / μ (closed_ball x r)) (𝓝[>] 0) (𝓝 (ρ.rn_deriv μ x)) := begin haveI : second_countable_topology β := emetric.second_countable_of_sigma_compact β, filter_upwards [vitali_family.ae_tendsto_rn_deriv (besicovitch.vitali_family μ) ρ] with x hx, exact hx.comp (tendsto_filter_at μ x) end /-- Given a measurable set `s`, then `μ (s ∩ closed_ball x r) / μ (closed_ball x r)` converges when `r` tends to `0`, for almost every `x`. The limit is `1` for `x ∈ s` and `0` for `x ∉ s`. This shows that almost every point of `s` is a Lebesgue density point for `s`. A version for non-measurable sets holds, but it only gives the first conclusion, see `ae_tendsto_measure_inter_div`. -/ lemma ae_tendsto_measure_inter_div_of_measurable_set (μ : measure β) [is_locally_finite_measure μ] {s : set β} (hs : measurable_set s) : ∀ᵐ x ∂μ, tendsto (λ r, μ (s ∩ closed_ball x r) / μ (closed_ball x r)) (𝓝[>] 0) (𝓝 (s.indicator 1 x)) := begin haveI : second_countable_topology β := emetric.second_countable_of_sigma_compact β, filter_upwards [vitali_family.ae_tendsto_measure_inter_div_of_measurable_set (besicovitch.vitali_family μ) hs], assume x hx, exact hx.comp (tendsto_filter_at μ x) end /-- Given an arbitrary set `s`, then `μ (s ∩ closed_ball x r) / μ (closed_ball x r)` converges to `1` when `r` tends to `0`, for almost every `x` in `s`. This shows that almost every point of `s` is a Lebesgue density point for `s`. A stronger version holds for measurable sets, see `ae_tendsto_measure_inter_div_of_measurable_set`. -/ lemma ae_tendsto_measure_inter_div (μ : measure β) [is_locally_finite_measure μ] (s : set β) : ∀ᵐ x ∂(μ.restrict s), tendsto (λ r, μ (s ∩ (closed_ball x r)) / μ (closed_ball x r)) (𝓝[>] 0) (𝓝 1) := begin haveI : second_countable_topology β := emetric.second_countable_of_sigma_compact β, filter_upwards [vitali_family.ae_tendsto_measure_inter_div (besicovitch.vitali_family μ)] with x hx using hx.comp (tendsto_filter_at μ x), end end besicovitch
29d10c47582beeaa13ecd92ed2b1c54cc193503f
a4673261e60b025e2c8c825dfa4ab9108246c32e
/src/Lean/Data/KVMap.lean
9bb879dc430770cd374be85eedcd0c42c6a4c3d9
[ "Apache-2.0" ]
permissive
jcommelin/lean4
c02dec0cc32c4bccab009285475f265f17d73228
2909313475588cc20ac0436e55548a4502050d0a
refs/heads/master
1,674,129,550,893
1,606,415,348,000
1,606,415,348,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
5,996
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 -/ import Lean.Data.Name namespace Lean inductive DataValue := | ofString (v : String) | ofBool (v : Bool) | ofName (v : Name) | ofNat (v : Nat) | ofInt (v : Int) @[export lean_mk_bool_data_value] def mkBoolDataValueEx (b : Bool) : DataValue := DataValue.ofBool b @[export lean_data_value_bool] def DataValue.getBoolEx : DataValue → Bool | DataValue.ofBool b => b | _ => false def DataValue.beq : DataValue → DataValue → Bool | DataValue.ofString s₁, DataValue.ofString s₂ => s₁ = s₂ | DataValue.ofNat n₁, DataValue.ofNat n₂ => n₂ = n₂ | DataValue.ofBool b₁, DataValue.ofBool b₂ => b₁ = b₂ | _, _ => false def DataValue.sameCtor : DataValue → DataValue → Bool | DataValue.ofString _, DataValue.ofString _ => true | DataValue.ofBool _, DataValue.ofBool _ => true | DataValue.ofName _, DataValue.ofName _ => true | DataValue.ofNat _, DataValue.ofNat _ => true | DataValue.ofInt _, DataValue.ofInt _ => true | _, _ => false instance : BEq DataValue := ⟨DataValue.beq⟩ @[export lean_data_value_to_string] def DataValue.str : DataValue → String | DataValue.ofString v => v | DataValue.ofBool v => toString v | DataValue.ofName v => toString v | DataValue.ofNat v => toString v | DataValue.ofInt v => toString v instance : ToString DataValue := ⟨DataValue.str⟩ instance : Coe String DataValue := ⟨DataValue.ofString⟩ instance : Coe Bool DataValue := ⟨DataValue.ofBool⟩ instance : Coe Name DataValue := ⟨DataValue.ofName⟩ instance : Coe Nat DataValue := ⟨DataValue.ofNat⟩ instance : Coe Int DataValue := ⟨DataValue.ofInt⟩ /- Remark: we do not use RBMap here because we need to manipulate KVMap objects in C++ and RBMap is implemented in Lean. So, we use just a List until we can generate C++ code from Lean code. -/ structure KVMap := (entries : List (Name × DataValue) := []) namespace KVMap instance : Inhabited KVMap := ⟨{}⟩ instance : ToString KVMap := ⟨fun m => toString m.entries⟩ def empty : KVMap := {} def isEmpty : KVMap → Bool | ⟨m⟩ => m.isEmpty def size (m : KVMap) : Nat := m.entries.length def findCore : List (Name × DataValue) → Name → Option DataValue | [], k' => none | (k,v)::m, k' => if k == k' then some v else findCore m k' def find : KVMap → Name → Option DataValue | ⟨m⟩, k => findCore m k def findD (m : KVMap) (k : Name) (d₀ : DataValue) : DataValue := (m.find k).getD d₀ def insertCore : List (Name × DataValue) → Name → DataValue → List (Name × DataValue) | [], k', v' => [(k',v')] | (k,v)::m, k', v' => if k == k' then (k, v') :: m else (k, v) :: insertCore m k' v' def insert : KVMap → Name → DataValue → KVMap | ⟨m⟩, k, v => ⟨insertCore m k v⟩ def contains (m : KVMap) (n : Name) : Bool := (m.find n).isSome def getString (m : KVMap) (k : Name) (defVal := "") : String := match m.find k with | some (DataValue.ofString v) => v | _ => defVal def getNat (m : KVMap) (k : Name) (defVal := 0) : Nat := match m.find k with | some (DataValue.ofNat v) => v | _ => defVal def getInt (m : KVMap) (k : Name) (defVal : Int := 0) : Int := match m.find k with | some (DataValue.ofInt v) => v | _ => defVal def getBool (m : KVMap) (k : Name) (defVal := false) : Bool := match m.find k with | some (DataValue.ofBool v) => v | _ => defVal def getName (m : KVMap) (k : Name) (defVal := Name.anonymous) : Name := match m.find k with | some (DataValue.ofName v) => v | _ => defVal def setString (m : KVMap) (k : Name) (v : String) : KVMap := m.insert k (DataValue.ofString v) def setNat (m : KVMap) (k : Name) (v : Nat) : KVMap := m.insert k (DataValue.ofNat v) def setInt (m : KVMap) (k : Name) (v : Int) : KVMap := m.insert k (DataValue.ofInt v) def setBool (m : KVMap) (k : Name) (v : Bool) : KVMap := m.insert k (DataValue.ofBool v) def setName (m : KVMap) (k : Name) (v : Name) : KVMap := m.insert k (DataValue.ofName v) @[inline] def forIn.{w, w'} {δ : Type w} {m : Type w → Type w'} [Monad m] (kv : KVMap) (init : δ) (f : Name × DataValue → δ → m (ForInStep δ)) : m δ := kv.entries.forIn init f def subsetAux : List (Name × DataValue) → KVMap → Bool | [], m₂ => true | (k, v₁)::m₁, m₂ => match m₂.find k with | some v₂ => v₁ == v₂ && subsetAux m₁ m₂ | none => false def subset : KVMap → KVMap → Bool | ⟨m₁⟩, m₂ => subsetAux m₁ m₂ def eqv (m₁ m₂ : KVMap) : Bool := subset m₁ m₂ && subset m₂ m₁ instance : BEq KVMap := ⟨eqv⟩ class KVMapVal (α : Type) := (defVal : α) (set : KVMap → Name → α → KVMap) (get : KVMap → Name → α → α) export KVMapVal (set) @[inline] def get {α : Type} [s : KVMapVal α] (m : KVMap) (k : Name) (defVal := s.defVal) : α := KVMapVal.get m k defVal @[inline] def set {α : Type} [s : KVMapVal α] (m : KVMap) (k : Name) (v : α) : KVMap := KVMapVal.set m k v instance : KVMapVal Bool := { defVal := false, set := setBool, get := fun k n v => getBool k n v } instance : KVMapVal Nat := { defVal := 0, set := setNat, get := fun k n v => getNat k n v } instance : KVMapVal Int := { defVal := 0, set := setInt, get := fun k n v => getInt k n v } instance : KVMapVal Name := { defVal := Name.anonymous, set := setName, get := fun k n v => getName k n v } instance : KVMapVal String := { defVal := "", set := setString, get := fun k n v => getString k n v } end Lean.KVMap
b6179f6e95fd93d724f9250784ba57f0a8392544
54deab7025df5d2df4573383df7e1e5497b7a2c2
/logic/basic.lean
66527397775d7bf8cb14f95ce009119fc3315890
[ "Apache-2.0" ]
permissive
HGldJ1966/mathlib
f8daac93a5b4ae805cfb0ecebac21a9ce9469009
c5c5b504b918a6c5e91e372ee29ed754b0513e85
refs/heads/master
1,611,340,395,683
1,503,040,489,000
1,503,040,489,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
18,192
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 Theorems that require decidability hypotheses are in the namespace "decidable". Classical versions are in the namespace "classical". Note: in the presence of automation, this whole file may be unnecessary. On the other hand, maybe it is useful for writing automation. -/ /- miscellany TODO: move elsewhere -/ section miscellany universes u v variables {α : Type u} {β : Type v} theorem eq_iff_le_and_le {α : Type u} [partial_order α] {a b : α} : a = b ↔ (a ≤ b ∧ b ≤ a) := ⟨assume eq, eq ▸ ⟨le_refl a, le_refl a⟩, assume ⟨ab, ba⟩, le_antisymm ab ba⟩ @[simp] theorem prod.mk.inj_iff {α : Type u} {β : Type v} {a₁ a₂ : α} {b₁ b₂ : β} : (a₁, b₁) = (a₂, b₂) ↔ (a₁ = a₂ ∧ b₁ = b₂) := ⟨prod.mk.inj, by cc⟩ @[simp] theorem prod.forall {α : Type u} {β : Type v} {p : α × β → Prop} : (∀x, p x) ↔ (∀a b, p (a, b)) := ⟨assume h a b, h (a, b), assume h ⟨a, b⟩, h a b⟩ @[simp] theorem prod.exists {α : Type u} {β : Type v} {p : α × β → Prop} : (∃x, p x) ↔ (∃a b, p (a, b)) := ⟨assume ⟨⟨a, b⟩, h⟩, ⟨a, b, h⟩, assume ⟨a, b, h⟩, ⟨⟨a, b⟩, h⟩⟩ @[simp] theorem set_of_subset_set_of {p q : α → Prop} : {a | p a} ⊆ {a | q a} = (∀a, p a → q a) := rfl end miscellany /- propositional connectives -/ @[simp] lemma false_neq_true : false ≠ true := begin intro h, rw [h], trivial end section propositional variables {a b c d : Prop} /- implies -/ theorem implies_self (h : a) : a := h theorem implies_intro (h : a) (h₂ : b) : a := h theorem implies_false_iff (a : Prop) : (a → false) ↔ ¬ a := iff.rfl theorem implies_and_iff (p q r : Prop) : (p → q ∧ r) ↔ (p → q) ∧ (p → r) := iff.intro (λ h, ⟨λ hp, (h hp).left, λ hp, (h hp).right⟩) (λ h hp, ⟨h.left hp, h.right hp⟩) theorem and_implies_iff (p q r : Prop) : (p ∧ q → r) ↔ (p → q → r) := iff.intro (λ h hp hq, h ⟨hp, hq⟩) (λ h ⟨hp, hq⟩, h hp hq) theorem iff_def (p q : Prop) : (p ↔ q) ↔ (p → q) ∧ (q → p) := ⟨ λh, ⟨h.1, h.2⟩, λ ⟨h₁, h₂⟩, ⟨h₁, h₂⟩ ⟩ @[simp] lemma {u v} implies_implies_true_iff {α : Sort u} {β : Sort v} : (α → β → true) ↔ true := ⟨assume _, trivial, assume _ _ _ , trivial⟩ /- not -/ theorem {u} not_elim {A : Sort u} (H1 : ¬a) (H2 : a) : A := absurd H2 H1 theorem not_not_of_not_implies : ¬(a → b) → ¬¬a := mt not_elim theorem not_of_not_implies : ¬(a → b) → ¬b := mt implies_intro theorem dec_em (p : Prop) [decidable p] : p ∨ ¬p := decidable.em p theorem by_contradiction {p} [decidable p] : (¬p → false) → p := decidable.by_contradiction theorem not_not_iff [decidable a] : ¬¬a ↔ a := iff.intro by_contradiction not_not_intro theorem not_not_elim [decidable a] : ¬¬a → a := by_contradiction theorem of_not_implies [decidable a] (h : ¬ (a → b)) : a := by_contradiction (not_not_of_not_implies h) /- and -/ theorem not_and_of_not_left (b : Prop) : ¬a → ¬(a ∧ b) := mt and.left theorem not_and_of_not_right (a : Prop) {b : Prop} : ¬b → ¬(a ∧ b) := mt and.right theorem and_implies_left (h : a → b) : a ∧ c → b ∧ c := and_implies h implies_self theorem and_implies_right (h : a → b) : c ∧ a → c ∧ b := and_implies implies_self h theorem and_of_and_of_implies_of_implies (h₁ : a ∧ b) (h₂ : a → c) (h₃ : b → d) : c ∧ d := and_implies h₂ h₃ h₁ theorem and_of_and_of_imp_left (h₁ : a ∧ c) (h : a → b) : b ∧ c := and_implies_left h h₁ theorem and_of_and_of_imp_right (h₁ : c ∧ a) (h : a → b) : c ∧ b := and_implies_right h h₁ theorem and_imp_iff (a b c : Prop) : (a ∧ b → c) ↔ (a → b → c) := iff.intro (λ h a b, h ⟨a, b⟩) and.rec theorem and_not_self_iff (a : Prop) : a ∧ ¬ a ↔ false := iff.intro (assume h, (h.right) (h.left)) (assume h, h.elim) theorem not_and_self_iff (a : Prop) : ¬ a ∧ a ↔ false := iff.intro (assume ⟨hna, ha⟩, hna ha) false.elim /- or -/ theorem or_of_or_of_implies_of_implies (h₁ : a ∨ b) (h₂ : a → c) (h₃ : b → d) : c ∨ d := or.imp h₂ h₃ h₁ theorem or_of_or_of_implies_left (h₁ : a ∨ c) (h : a → b) : b ∨ c := or.imp_left h h₁ theorem or_of_or_of_implies_right (h₁ : c ∨ a) (h : a → b) : c ∨ b := or.imp_right h h₁ theorem or.elim3 (h : a ∨ b ∨ c) (ha : a → d) (hb : b → d) (hc : c → d) : d := or.elim h ha (assume h₂, or.elim h₂ hb hc) theorem or_resolve_right (h₁ : a ∨ b) (h₂ : ¬a) : b := or.elim h₁ (not_elim h₂) implies_self theorem or_resolve_left (h₁ : a ∨ b) (h₂ : ¬b) : a := or_resolve_right h₁.symm h₂ theorem or_implies_distrib (a b c : Prop) : ((a ∨ b) → c) ↔ ((a → c) ∧ (b → c)) := iff.intro (λh, and.intro (implies.trans or.inl h) (implies.trans or.inr h)) (and.rec or.rec) theorem or_iff_or (h1 : a ↔ c) (h2 : b ↔ d) : (a ∨ b) ↔ (c ∨ d) := iff.intro (or.imp (iff.mp h1) (iff.mp h2)) (or.imp (iff.mpr h1) (iff.mpr h2)) theorem or_of_not_implies {a b : Prop} [decidable a] (h : ¬ a → b) : a ∨ b := dite _ or.inl (or.inr ∘ h) theorem or_of_not_implies' {a b : Prop} [decidable b] (h : ¬ b → a) : a ∨ b := dite _ or.inr (or.inl ∘ h) theorem not_imp_iff_not_imp {a b : Prop} [decidable a] : (¬ a → ¬ b) ↔ (b → a) := ⟨assume h hb, by_contradiction $ assume na, h na hb, mt⟩ /- distributivity -/ theorem and_distrib (a b c : Prop) : a ∧ (b ∨ c) ↔ (a ∧ b) ∨ (a ∧ c) := iff.intro (and.rec (λh, or.imp (and.intro h) (and.intro h))) (or.rec (and_implies_right or.inl) (and_implies_right or.inr)) theorem and_distrib_right (a b c : Prop) : (a ∨ b) ∧ c ↔ (a ∧ c) ∨ (b ∧ c) := iff.trans (iff.trans and.comm (and_distrib c a b)) (or_iff_or and.comm and.comm) theorem or_distrib (a b c : Prop) : a ∨ (b ∧ c) ↔ (a ∨ b) ∧ (a ∨ c) := iff.intro (or.rec (λh, and.intro (or.inl h) (or.inl h)) (and_implies or.inr or.inr)) (and.rec (or.rec (implies.trans or.inl implies_intro) (implies.trans and.intro or.imp_right))) theorem or_distrib_right (a b c : Prop) : (a ∧ b) ∨ c ↔ (a ∨ c) ∧ (b ∨ c) := iff.trans (iff.trans or.comm (or_distrib c a b)) (and_congr or.comm or.comm) /- iff -/ theorem implies_iff {a : Prop} (n : Prop) (ha : a) : (a → b) ↔ b := iff.intro (λf, f ha) implies_intro theorem not_or_of_implies [decidable a] (h : a → b) : ¬ a ∨ b := if ha : a then or.inr (h ha) else or.inl ha theorem implies_of_not_or (h : ¬ a ∨ b) (ha : a) : b := or.elim h (assume hna, absurd ha hna) id theorem implies_iff_not_or [decidable a] : (a → b) ↔ (¬ a ∨ b) := ⟨not_or_of_implies, implies_of_not_or⟩ theorem not_implies_of_and_not (h : a ∧ ¬ b) : ¬ (a → b) := assume h₁, and.right h (h₁ (and.left h)) theorem and_not_of_not_implies [decidable a] (h : ¬ (a → b)) : a ∧ ¬ b := ⟨of_not_implies h, not_of_not_implies h⟩ theorem not_implies_iff [decidable a] : ¬(a → b) ↔ a ∧ ¬b := ⟨and_not_of_not_implies, not_implies_of_and_not⟩ theorem peirce (a b : Prop) [decidable a] : ((a → b) → a) → a := if ha : a then λ h, ha else λ h, h (λ h', absurd h' ha) theorem peirce' {a : Prop} (H : ∀ b : Prop, (a → b) → a) : a := H _ id /- de morgan's laws -/ theorem not_and_of_not_or_not (h : ¬ a ∨ ¬ b) : ¬ (a ∧ b) := assume ⟨ha, hb⟩, or.elim h (assume hna, hna ha) (assume hnb, hnb hb) theorem not_or_not_of_not_and [decidable a] (h : ¬ (a ∧ b)) : ¬ a ∨ ¬ b := if ha : a then or.inr (show ¬ b, from assume hb, h ⟨ha, hb⟩) else or.inl ha theorem not_or_not_of_not_and' [decidable b] (h : ¬ (a ∧ b)) : ¬ a ∨ ¬ b := if hb : b then or.inl (show ¬ a, from assume ha, h ⟨ha, hb⟩) else or.inr hb theorem not_and_iff [decidable a] : ¬ (a ∧ b) ↔ ¬a ∨ ¬b := iff.intro not_or_not_of_not_and not_and_of_not_or_not theorem not_and_iff_imp_not {p q : Prop} : ¬ (p ∧ q) ↔ (p → ¬ q) := ⟨assume h hp hq, h ⟨hp, hq⟩, assume h ⟨hp, hq⟩, h hp hq⟩ theorem not_or_of_not_and_not (h : ¬ a ∧ ¬ b) : ¬ (a ∨ b) := assume h₁, or.elim h₁ (assume ha, and.left h ha) (assume hb, and.right h hb) theorem not_and_not_of_not_or (h : ¬ (a ∨ b)) : ¬ a ∧ ¬ b := and.intro (assume ha, h (or.inl ha)) (assume hb, h (or.inr hb)) theorem not_or_iff : ¬ (a ∨ b) ↔ ¬ a ∧ ¬ b := iff.intro not_and_not_of_not_or not_or_of_not_and_not theorem or_iff_not_and_not [decidable a] [decidable b] : a ∨ b ↔ ¬ (¬a ∧ ¬b) := by rewrite [←not_or_iff, not_not_iff] theorem and_iff_not_or_not [decidable a] [decidable b] : a ∧ b ↔ ¬ (¬ a ∨ ¬ b) := by rewrite [←not_and_iff, not_not_iff] /- other identities -/ theorem or_imp_iff_and_imp {a b c : Prop} : ((a ∨ b) → c) ↔ ((a → c) ∧ (b → c)) := ⟨assume h, ⟨assume ha, h (or.inl ha), assume hb, h (or.inr hb)⟩, assume ⟨ha, hb⟩, or.rec ha hb⟩ end propositional /- quantifiers -/ section quantifiers universe variable u variables {α : Type u} {p q : α → Prop} {b : Prop} theorem forall_of_forall (h : ∀ x, (p x → q x)) (h₁ : ∀ x, p x) : ∀ x, q x := assume x, h x (h₁ x) theorem exists_of_exists (h : ∀ x, (p x → q x)) (h₁ : ∃ x, p x) : ∃ x, q x := match h₁ with ⟨x, hpx⟩ := ⟨x, h x hpx⟩ end theorem forall_implies_of_exists_implies (h : (∃ x, p x) → b) : ∀ x, p x → b := assume x, assume hpx, h ⟨x, hpx⟩ theorem exists_implies_of_forall_implies (h : ∀ x, p x → b) : (∃ x, p x) → b := Exists.rec h theorem exists_implies_distrib (p : α → Prop) (b : Prop) : ((∃ x, p x) → b) ↔ (∀ x, p x → b) := iff.intro forall_implies_of_exists_implies exists_implies_of_forall_implies --theorem forall_not_of_not_exists (h : ¬ ∃ x, p x) : ∀ x, ¬ p x := --forall_implies_of_exists_implies h theorem not_exists_of_forall_not (h : ∀ x, ¬ p x) : ¬ ∃ x, p x := exists_implies_of_forall_implies h theorem not_exists_iff {p : α → Prop} : (¬ ∃ x, p x) ↔ (∀ x, ¬ p x) := exists_implies_distrib p false theorem exists_not_of_not_forall [decidable (∃ x, ¬ p x)] [∀ x, decidable (p x)] (h : ¬ ∀ x, p x) : ∃ x, ¬ p x := by_contradiction (assume h₁, h (assume x, by_contradiction (assume hnpx, h₁ ⟨x, hnpx⟩))) theorem not_forall_of_exists_not (h : ∃ x, ¬ p x) : ¬ ∀ x, p x := assume h₁, match h with ⟨x, hnpx⟩ := hnpx (h₁ x) end theorem not_forall_iff {p : α → Prop} [decidable (∃ x, ¬ p x)] [∀ x, decidable (p x)] : (¬ ∀ x, p x) ↔ (∃ x, ¬ p x) := iff.intro exists_not_of_not_forall not_forall_of_exists_not theorem forall_true_iff : (∀ x : α, true) ↔ true := iff_true_intro (λ h, trivial) @[simp] theorem forall_p_iff_p (α : Type u) [inhabited α] (p : Prop) : (∀ x : α, p) ↔ p := iff.intro (λ h, h (inhabited.default α)) (λ hp x, hp) @[simp] theorem exists_p_iff_p (α : Type u) [inhabited α] (p : Prop) : (∃ x : α, p) ↔ p := iff.intro (Exists.rec (λ x (hpx : p), hpx)) (λ hp, ⟨default α, hp⟩) theorem forall_and_distrib (p q : α → Prop) : (∀ x, p x ∧ q x) ↔ (∀ x, p x) ∧ (∀ x, q x) := iff.intro (assume h, ⟨(assume x, (h x).left), (assume x, (h x).right)⟩) (assume h x, ⟨h.left x, h.right x⟩) theorem exists_or_distrib (p q : α → Prop) : (∃ x, p x ∨ q x) ↔ (∃ x, p x) ∨ (∃ x, q x) := iff.intro (assume ⟨x, hpq⟩, or.elim hpq (assume hpx, or.inl (exists.intro x hpx)) (assume hqx, or.inr (exists.intro x hqx))) (assume hepq, or.elim hepq (assume hepx, match hepx : _ → ∃ x, p x ∨ q x with ⟨x, hpx⟩ := ⟨x, or.inl hpx⟩ end) (assume ⟨x, hqx⟩, ⟨x, or.inr hqx⟩)) @[simp] theorem exists_and_distrib_left {q : Prop} {p : α → Prop} : (∃x, q ∧ p x) ↔ q ∧ (∃x, p x) := ⟨assume ⟨x, hq, hp⟩, ⟨hq, x, hp⟩, assume ⟨hq, x, hp⟩, ⟨x, hq, hp⟩⟩ theorem forall_eq {α : Type u} {p : α → Prop} {a' : α} : (∀a, a = a' → p a) ↔ p a' := ⟨assume h, h a' rfl, assume h a eq, eq.symm ▸ h⟩ theorem forall_or_distrib_left {q : Prop} {p : α → Prop} [decidable q] : (∀x, q ∨ p x) ↔ q ∨ (∀x, p x) := ⟨assume h, if hq : q then or.inl hq else or.inr $ assume x, or.resolve_left (h x) hq, assume h x, or.imp_right (assume : ∀x, p x, this x) h⟩ @[simp] theorem exists_prop_iff (p q : Prop) : (∃ h : p, q) ↔ p ∧ q := iff.intro begin intro h', cases h', split, repeat { assumption } end begin intro h', cases h', split, repeat { assumption } end end quantifiers /- classical versions -/ namespace classical universe variable u variables {α : Type u} {p : α → Prop} local attribute [instance] prop_decidable theorem exists_not_of_not_forall (h : ¬ ∀ x, p x) : ∃ x, ¬ p x := exists_not_of_not_forall h theorem not_forall_iff : (¬ ∀ x, p x) ↔ (∃ x, ¬ p x) := not_forall_iff theorem forall_or_distrib_left {q : Prop} {p : α → Prop} : (∀x, q ∨ p x) ↔ q ∨ (∀x, p x) := forall_or_distrib_left lemma cases {p : Prop → Prop} (h1 : p true) (h2 : p false) : ∀a, p a := assume a, cases_on a h1 h2 end classical /- bounded quantifiers -/ section bounded_quantifiers universe variable u variables {α : Type u} {r p q : α → Prop} {b : Prop} theorem bexists_def {α : Type u} (p q : α → Prop) : (∃ x (h : p x), q x) ↔ ∃ x, p x ∧ q x := ⟨λ ⟨x, px, qx⟩, ⟨x, px, qx⟩, λ ⟨x, px, qx⟩, ⟨x, px, qx⟩⟩ theorem bexists.elim {b : Prop} (h : ∃ x : α, ∃ h : p x, q x) (h' : ∀ (a : α), p a → q a → b) : b := exists.elim h (λ a h₁, exists.elim h₁ (h' a)) theorem bexists.intro (a : α) (h₁ : p a) (h₂ : q a) : ∃ x, ∃ h : p x, q x := exists.intro a (exists.intro h₁ h₂) theorem bforall_congr (h : ∀ x (hrx : r x), p x ↔ q x) : (∀ x (hrx : r x), p x) ↔ (∀ x (hrx : r x), q x) := begin apply forall_congr, intro x, apply forall_congr, apply h end theorem bexists_congr (h : ∀ x (hrx : r x), p x ↔ q x) : (∃ x (hrx : r x), p x) ↔ (∃ x (hrx : r x), q x) := begin apply exists_congr, intros, apply exists_congr, apply h end theorem bforall_of_bforall (h : ∀ x (hrx : r x), (p x → q x)) (h₁ : ∀ x (hrx : r x), p x) : ∀ x (hrx : r x), q x := assume x, assume hrx, h x hrx (h₁ x hrx) theorem bexists_of_bexists {α : Type} {p q : α → Prop} (h : ∀ x, (p x → q x)) (h₁ : ∃ x, p x) : ∃ x, q x := match h₁ with ⟨x, hpx⟩ := ⟨x, h x hpx⟩ end theorem bforall_of_forall (h : ∀ x, p x) : ∀ x (hrx : r x), p x := λ x hrx, h x theorem forall_of_bforall (h : ∀ x (ht : true), p x) : ∀ x, p x := λ x, h x trivial theorem bexists_of_exists (h : ∃ x, p x) : ∃ x (ht : true), p x := match h with ⟨x, hpx⟩ := ⟨x, trivial, hpx⟩ end theorem exists_of_bexists (h : ∃ x (hrx : r x), p x) : ∃ x, p x := match h with ⟨x, hrx, hpx⟩ := ⟨x, hpx⟩ end theorem bforall_implies_of_bexists_implies (h : (∃ x (hrx : r x), p x) → b) : ∀ x (hrx : r x), p x → b := λ x hrx hpx, h ⟨x, hrx, hpx⟩ theorem bexists_implies_of_bforall_implies (h : ∀ x (hrx : r x), p x → b) : (∃ x (hrx : r x), p x) → b := assume ⟨x, hrx, hpx⟩, h x hrx hpx theorem bexists_implies_distrib (r p : α → Prop) (b : Prop) : ((∃ x (hrx : r x), p x) → b) ↔ (∀ x (hrx : r x), p x → b) := iff.intro bforall_implies_of_bexists_implies bexists_implies_of_bforall_implies theorem bforall_not_of_not_bexists (h : ¬ ∃ x (hrx : r x), p x) : ∀ x (hrx : r x), ¬ p x := bforall_implies_of_bexists_implies h theorem not_bexists_of_bforall_not (h : ∀ x (hrx : r x), ¬ p x) : ¬ ∃ x (hrx : r x), p x := bexists_implies_of_bforall_implies h theorem not_bexists_iff_bforall_not (r p : α → Prop) : (¬ ∃ x (hrx : r x) , p x) ↔ (∀ x (h : r x), ¬ p x) := bexists_implies_distrib r p false theorem bexists_not_of_not_bforall [decidable (∃ x (hrx : r x), ¬ p x)] [∀ x, decidable (p x)] (h : ¬ ∀ x (hrx : r x), p x) : ∃ x (hr : r x), ¬ p x := by_contradiction (assume h₁, h (assume x, assume hrx, by_contradiction (assume hnpx, h₁ ⟨x, hrx, hnpx⟩))) theorem not_bforall_of_bexists_not (h : ∃ x (hrx : r x), ¬ p x) : ¬ ∀ x (hrx : r x), p x := assume h₁, match h with ⟨x, hrx, hnpx⟩ := hnpx (h₁ x hrx) end theorem not_bforall_iff_bexists_not (r p : α → Prop) [decidable (∃ x (hrx : r x), ¬ p x)] [∀ x, decidable (p x)] : (¬ ∀ x (hrx : r x), p x) ↔ (∃ x (hrx : r x), ¬ p x) := iff.intro bexists_not_of_not_bforall not_bforall_of_bexists_not theorem bforall_true_iff (r : α → Prop): (∀ x (hrx : r x), true) ↔ true := iff_true_intro (λ h hrx, trivial) theorem bforall_and_distrib : (∀ x, p x ∧ q x) ↔ (∀ x, p x) ∧ (∀ x, q x) := iff.intro (assume h, ⟨(assume x, (h x).left), (assume x, (h x).right)⟩) (assume h x, ⟨h.left x, h.right x⟩) theorem bexists_or_distrib (r p q : α → Prop) : (∃ x (hrx : r x), p x ∨ q x) ↔ (∃ x (hrx : r x), p x) ∨ (∃ x (hrx : r x), q x) := iff.intro (assume ⟨x, hrx, hpq⟩, or.elim hpq (assume hpx, or.inl (exists.intro x (exists.intro hrx hpx))) (assume hqx, or.inr (exists.intro x (exists.intro hrx hqx)))) (assume hepq, or.elim hepq (assume hepx, match hepx : _ → ∃ x (hrx : r x), p x ∨ q x with ⟨x, hrx, hpx⟩ := ⟨x, hrx, or.inl hpx⟩ end) (assume ⟨x, hrx, hqx⟩, ⟨x, hrx, or.inr hqx⟩)) end bounded_quantifiers namespace classical universe variable u variables {α : Type u} {r p : α → Prop} local attribute [instance] prop_decidable theorem bexists_not_of_not_bforall (h : ¬ ∀ x (hrx : r x), p x) : ∃ x (hr : r x), ¬ p x := bexists_not_of_not_bforall h theorem not_bforall_iff_bexists_not (r p : α → Prop) : (¬ ∀ x (hrx : r x), p x) ↔ (∃ x (hrx : r x), ¬ p x) := not_bforall_iff_bexists_not r p end classical
3422ee9cdb8bf2d3d78efef51725000601598d4f
02005f45e00c7ecf2c8ca5db60251bd1e9c860b5
/src/algebra/regular.lean
455f5a9ee2046a2e70ae8bc96a5fe758fdf7a620
[ "Apache-2.0" ]
permissive
anthony2698/mathlib
03cd69fe5c280b0916f6df2d07c614c8e1efe890
407615e05814e98b24b2ff322b14e8e3eb5e5d67
refs/heads/master
1,678,792,774,873
1,614,371,563,000
1,614,371,563,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
10,824
lean
/- Copyright (c) 2021 Damiano Testa. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Damiano Testa -/ import algebra.group import algebra.group_power.basic import algebra.iterate_hom /-! # Regular elements We introduce left-regular, right-regular and regular elements. By definition, a regular element in a commutative ring is a non-zero divisor. Lemma `is_regular_of_ne_zero` implies that every non-zero element of an integral domain is regular. Since it assumes that the ring is a `cancel_monoid_with_zero` it applies also, for instance, to `ℕ`. The lemmas in Section `mul_zero_class` show that the `0` element is (left/right-)regular if and only if the `mul_zero_class` is trivial. This is useful when figuring out stopping conditions for regular sequences: if `0` is ever an element of a regular sequence, then we can extend the sequence by adding one further `0`. The final goal is to develop part of the API to prove, eventually, results about non-zero-divisors. -/ variables {R : Type*} {a b : R} section has_mul variable [has_mul R] /-- A left-regular element is an element `c` such that multiplication on the left by `c` is injective on the left. -/ def is_left_regular (c : R) := function.injective ((*) c) /-- A right-regular element is an element `c` such that multiplication on the right by `c` is injective on the right. -/ def is_right_regular (c : R) := function.injective (* c) /-- A regular element is an element `c` such that multiplication by `c` both on the left and on the right is injective. -/ structure is_regular (c : R) : Prop := (left : is_left_regular c) (right : is_right_regular c) end has_mul section semigroup variable [semigroup R] /-- In a semigroup, then the product of left-regular elements is left-regular. -/ lemma is_left_regular.mul (lra : is_left_regular a) (lrb : is_left_regular b) : is_left_regular (a * b) := show function.injective ((*) (a * b)), from (comp_mul_left a b) ▸ lra.comp lrb /-- In a semigroup, then the product of right-regular elements is right-regular. -/ lemma is_right_regular.mul (rra : is_right_regular a) (rrb : is_right_regular b) : is_right_regular (a * b) := show function.injective (* (a * b)), from (comp_mul_right b a) ▸ rrb.comp rra /-- If an element `b` becomes left-regular after multiplying it on the left by a left-regular element, then `b` is left-regular. -/ lemma is_left_regular.of_mul (ab : is_left_regular (a * b)) : is_left_regular b := function.injective.of_comp (by rwa comp_mul_left a b) /-- An element is left-regular if and only if multiplying it on the left by a left-regular element is left-regular. -/ @[simp] lemma mul_is_left_regular_iff (b : R) (ha : is_left_regular a) : is_left_regular (a * b) ↔ is_left_regular b := ⟨λ ab, is_left_regular.of_mul ab, λ ab, is_left_regular.mul ha ab⟩ /-- If an element `b` becomes right-regular after multiplying it on the right by a right-regular element, then `b` is right-regular. -/ lemma is_right_regular.of_mul (ab : is_right_regular (b * a)) : is_right_regular b := begin refine λ x y xy, ab (_ : x * (b * a) = y * (b * a)), rw [← mul_assoc, ← mul_assoc], exact congr_fun (congr_arg has_mul.mul xy) a, end /-- An element is right-regular if and only if multiplying it on the right with a right-regular element is right-regular. -/ @[simp] lemma mul_is_right_regular_iff (b : R) (ha : is_right_regular a) : is_right_regular (b * a) ↔ is_right_regular b := ⟨λ ab, is_right_regular.of_mul ab, λ ab, is_right_regular.mul ab ha⟩ /-- Two elements `a` and `b` are regular if and only if both products `a * b` and `b * a` are regular. -/ lemma is_regular_mul_and_mul_iff : is_regular (a * b) ∧ is_regular (b * a) ↔ is_regular a ∧ is_regular b := begin refine ⟨_, _⟩, { rintros ⟨ab, ba⟩, exact ⟨⟨is_left_regular.of_mul ba.left, is_right_regular.of_mul ab.right⟩, ⟨is_left_regular.of_mul ab.left, is_right_regular.of_mul ba.right⟩⟩ }, { rintros ⟨ha, hb⟩, exact ⟨⟨(mul_is_left_regular_iff _ ha.left).mpr hb.left, (mul_is_right_regular_iff _ hb.right).mpr ha.right⟩, ⟨(mul_is_left_regular_iff _ hb.left).mpr ha.left, (mul_is_right_regular_iff _ ha.right).mpr hb.right⟩⟩ } end /-- The "most used" implication of `mul_and_mul_iff`, with split hypotheses, instead of `∧`. -/ lemma is_regular.and_of_mul_of_mul (ab : is_regular (a * b)) (ba : is_regular (b * a)) : is_regular a ∧ is_regular b := is_regular_mul_and_mul_iff.mp ⟨ab, ba⟩ end semigroup section monoid variable [monoid R] /-- Any power of a left-regular element is left-regular. -/ lemma is_left_regular.pow (n : ℕ) (rla : is_left_regular a) : is_left_regular (a ^ n) := by simp [is_left_regular, ← mul_left_iterate, rla.iterate n] /-- Any power of a right-regular element is right-regular. -/ lemma is_right_regular.pow (n : ℕ) (rra : is_right_regular a) : is_right_regular (a ^ n) := by simp [is_right_regular, ← mul_right_iterate, rra.iterate n] /-- Any power of a regular element is regular. -/ lemma is_regular.pow (n : ℕ) (ra : is_regular a) : is_regular (a ^ n) := ⟨is_left_regular.pow n ra.left, is_right_regular.pow n ra.right⟩ /-- An element `a` is left-regular if and only if a positive power of `a` is left-regular. -/ lemma is_left_regular.pow_iff {n : ℕ} (n0 : 0 < n) : is_left_regular (a ^ n) ↔ is_left_regular a := begin refine ⟨_, is_left_regular.pow n⟩, rw [← nat.succ_pred_eq_of_pos n0, pow_succ'], exact is_left_regular.of_mul, end /-- An element `a` is right-regular if and only if a positive power of `a` is right-regular. -/ lemma is_right_regular.pow_iff {n : ℕ} (n0 : 0 < n) : is_right_regular (a ^ n) ↔ is_right_regular a := begin refine ⟨_, is_right_regular.pow n⟩, rw [← nat.succ_pred_eq_of_pos n0, pow_succ], exact is_right_regular.of_mul, end /-- An element `a` is regular if and only if a positive power of `a` is regular. -/ lemma is_regular.pow_iff {n : ℕ} (n0 : 0 < n) : is_regular (a ^ n) ↔ is_regular a := ⟨λ h, ⟨(is_left_regular.pow_iff n0).mp h.left, (is_right_regular.pow_iff n0).mp h.right⟩, λ h, ⟨is_left_regular.pow n h.left, is_right_regular.pow n h.right⟩⟩ end monoid section mul_zero_class variables [mul_zero_class R] /-- The element `0` is left-regular if and only if `R` is trivial. -/ lemma is_left_regular.subsingleton (h : is_left_regular (0 : R)) : subsingleton R := ⟨λ a b, h $ eq.trans (zero_mul a) (zero_mul b).symm⟩ /-- The element `0` is right-regular if and only if `R` is trivial. -/ lemma is_right_regular.subsingleton (h : is_right_regular (0 : R)) : subsingleton R := ⟨λ a b, h $ eq.trans (mul_zero a) (mul_zero b).symm⟩ /-- The element `0` is regular if and only if `R` is trivial. -/ lemma is_regular.subsingleton (h : is_regular (0 : R)) : subsingleton R := h.left.subsingleton /-- The element `0` is left-regular if and only if `R` is trivial. -/ lemma is_left_regular_zero_iff_subsingleton : is_left_regular (0 : R) ↔ subsingleton R := begin refine ⟨λ h, h.subsingleton, _⟩, intros H a b h, exact @subsingleton.elim _ H a b end /-- In a non-trivial `mul_zero_class`, the `0` element is not left-regular. -/ lemma not_is_left_regular_zero_iff : ¬ is_left_regular (0 : R) ↔ nontrivial R := begin rw [nontrivial_iff, not_iff_comm, is_left_regular_zero_iff_subsingleton, subsingleton_iff], push_neg, exact iff.rfl end /-- The element `0` is right-regular if and only if `R` is trivial. -/ lemma is_right_regular_zero_iff_subsingleton : is_right_regular (0 : R) ↔ subsingleton R := begin refine ⟨λ h, h.subsingleton, _⟩, intros H a b h, exact @subsingleton.elim _ H a b end /-- In a non-trivial `mul_zero_class`, the `0` element is not right-regular. -/ lemma not_is_right_regular_zero_iff : ¬ is_right_regular (0 : R) ↔ nontrivial R := begin rw [nontrivial_iff, not_iff_comm, is_right_regular_zero_iff_subsingleton, subsingleton_iff], push_neg, exact iff.rfl end /-- The element `0` is regular if and only if `R` is trivial. -/ lemma is_regular_iff_subsingleton : is_regular (0 : R) ↔ subsingleton R := ⟨λ h, h.left.subsingleton, λ h, ⟨is_left_regular_zero_iff_subsingleton.mpr h, is_right_regular_zero_iff_subsingleton.mpr h⟩⟩ end mul_zero_class section comm_semigroup variable [comm_semigroup R] /-- A product is regular if and only if the factors are. -/ lemma is_regular_mul_iff : is_regular (a * b) ↔ is_regular a ∧ is_regular b := begin refine iff.trans _ is_regular_mul_and_mul_iff, refine ⟨λ ab, ⟨ab, by rwa mul_comm⟩, λ rab, rab.1⟩ end end comm_semigroup section monoid variables [monoid R] /-- In a monoid, `1` is regular. -/ lemma is_regular_one : is_regular (1 : R) := ⟨λ a b ab, (one_mul a).symm.trans (eq.trans ab (one_mul b)), λ a b ab, (mul_one a).symm.trans (eq.trans ab (mul_one b))⟩ /-- An element admitting a left inverse is left-regular. -/ lemma is_left_regular_of_mul_eq_one (h : b * a = 1) : is_left_regular a := @is_left_regular.of_mul R _ a _ (by { rw h, exact is_regular_one.left }) /-- An element admitting a right inverse is right-regular. -/ lemma is_right_regular_of_mul_eq_one (h : a * b = 1) : is_right_regular a := @is_right_regular.of_mul R _ a _ (by { rw h, exact is_regular_one.right }) /-- If `R` is a monoid, an element in `units R` is regular. -/ lemma units.is_regular (a : units R) : is_regular (a : R) := ⟨is_left_regular_of_mul_eq_one a.inv_mul, is_right_regular_of_mul_eq_one a.mul_inv⟩ /-- A unit in a monoid is regular. -/ lemma is_unit.is_regular (ua : is_unit a) : is_regular a := begin rcases ua with ⟨a, rfl⟩, exact units.is_regular a, end end monoid section left_or_right_cancel_semigroup /-- Elements of a left cancel semigroup are left regular. -/ lemma is_left_regular_of_left_cancel_semigroup [left_cancel_semigroup R] (g : R) : is_left_regular g := mul_right_injective g /-- Elements of a right cancel semigroup are right regular. -/ lemma is_right_regular_of_right_cancel_semigroup [right_cancel_semigroup R] (g : R) : is_right_regular g := mul_left_injective g end left_or_right_cancel_semigroup section cancel_monoid variables [cancel_monoid R] /-- Elements of a cancel monoid are regular. Cancel semigroups do not appear to exist. -/ lemma is_regular_of_cancel_monoid (g : R) : is_regular g := ⟨mul_right_injective g, mul_left_injective g⟩ end cancel_monoid section cancel_monoid_with_zero variables [cancel_monoid_with_zero R] /-- Non-zero elements of an integral domain are regular. -/ lemma is_regular_of_ne_zero (a0 : a ≠ 0) : is_regular a := ⟨λ b c, (mul_right_inj' a0).mp, λ b c, (mul_left_inj' a0).mp⟩ end cancel_monoid_with_zero
e63d867666180fbbcd3720c70490cc5432df0a3b
75db7e3219bba2fbf41bf5b905f34fcb3c6ca3f2
/library/theories/number_theory/prime_factorization.lean
a7a9a4106b9915a0ce5ba0df27cad699bc467b0e
[ "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
14,113
lean
/- Copyright (c) 2015 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad Multiplicity and prime factors. We have: mult p n := the greatest power of p dividing n if p > 1 and n > 0, and 0 otherwise. prime_factors n := the finite set of prime factors of n, assuming n > 0 -/ import data.nat data.finset .primes algebra.group_bigops open eq.ops finset well_founded decidable namespace nat -- TODO: this should be proved more generally in ring_bigops theorem Prod_pos {A : Type} [deceqA : decidable_eq A] {s : finset A} {f : A → ℕ} (fpos : ∀ n, n ∈ s → f n > 0) : (∏ n ∈ s, f n) > 0 := begin induction s with a s anins ih, {rewrite Prod_empty; exact zero_lt_one}, rewrite [!Prod_insert_of_not_mem anins], exact (mul_pos (fpos a (mem_insert a _)) (ih (forall_of_forall_insert fpos))) end /- multiplicity -/ theorem mult_rec_decreasing {p n : ℕ} (Hp : p > 1) (Hn : n > 0) : n / p < n := have H' : n < n * p, by rewrite [-mul_one n at {1}]; apply mul_lt_mul_of_pos_left Hp Hn, nat.div_lt_of_lt_mul H' private definition mult.F (p : ℕ) (n : ℕ) (f: Π {m : ℕ}, m < n → ℕ) : ℕ := if H : (p > 1 ∧ n > 0) ∧ p ∣ n then succ (f (mult_rec_decreasing (and.left (and.left H)) (and.right (and.left H)))) else 0 definition mult (p n : ℕ) : ℕ := fix (mult.F p) n theorem mult_rec {p n : ℕ} (pgt1 : p > 1) (ngt0 : n > 0) (pdivn : p ∣ n) : mult p n = succ (mult p (n / p)) := have (p > 1 ∧ n > 0) ∧ p ∣ n, from and.intro (and.intro pgt1 ngt0) pdivn, eq.trans (well_founded.fix_eq (mult.F p) n) (dif_pos this) private theorem mult_base {p n : ℕ} (H : ¬ ((p > 1 ∧ n > 0) ∧ p ∣ n)) : mult p n = 0 := eq.trans (well_founded.fix_eq (mult.F p) n) (dif_neg H) theorem mult_zero_right (p : ℕ) : mult p 0 = 0 := mult_base (assume H, !lt.irrefl (and.right (and.left H))) theorem mult_eq_zero_of_not_dvd {p n : ℕ} (H : ¬ p ∣ n) : mult p n = 0 := mult_base (assume H', H (and.right H')) theorem mult_eq_zero_of_le_one {p : ℕ} (n : ℕ) (H : p ≤ 1) : mult p n = 0 := mult_base (assume H', not_lt_of_ge H (and.left (and.left H'))) theorem mult_zero_left (n : ℕ) : mult 0 n = 0 := mult_eq_zero_of_le_one n !dec_trivial theorem mult_one_left (n : ℕ) : mult 1 n = 0 := mult_eq_zero_of_le_one n !dec_trivial theorem mult_pos_of_dvd {p n : ℕ} (pgt1 : p > 1) (npos : n > 0) (pdvdn : p ∣ n) : mult p n > 0 := by rewrite (mult_rec pgt1 npos pdvdn); apply succ_pos theorem not_dvd_of_mult_eq_zero {p n : ℕ} (pgt1 : p > 1) (npos : n > 0) (H : mult p n = 0) : ¬ p ∣ n := suppose p ∣ n, ne_of_gt (mult_pos_of_dvd pgt1 npos this) H theorem dvd_of_mult_pos {p n : ℕ} (H : mult p n > 0) : p ∣ n := by_contradiction (suppose ¬ p ∣ n, ne_of_gt H (mult_eq_zero_of_not_dvd this)) /- properties of mult -/ theorem mult_eq_zero_of_prime_of_ne {p q : ℕ} (primep : prime p) (primeq : prime q) (pneq : p ≠ q) : mult p q = 0 := mult_eq_zero_of_not_dvd (not_dvd_of_prime_of_coprime primep (coprime_primes primep primeq pneq)) theorem pow_mult_dvd (p n : ℕ) : p^(mult p n) ∣ n := begin induction n using nat.strong_induction_on with [n, ih], cases eq_zero_or_pos n with [nz, npos], {rewrite nz, apply dvd_zero}, cases le_or_gt p 1 with [ple1, pgt1], {rewrite [!mult_eq_zero_of_le_one ple1, pow_zero], apply one_dvd}, cases (or.swap (em (p ∣ n))) with [pndvdn, pdvdn], {rewrite [mult_eq_zero_of_not_dvd pndvdn, pow_zero], apply one_dvd}, show p ^ (mult p n) ∣ n, from dvd.elim pdvdn (take n', suppose n = p * n', have p > 0, from lt.trans zero_lt_one pgt1, assert n / p = n', from !nat.div_eq_of_eq_mul_right this `n = p * n'`, assert n' < n, by rewrite -this; apply mult_rec_decreasing pgt1 npos, begin rewrite [mult_rec pgt1 npos pdvdn, `n / p = n'`, pow_succ], subst n, apply mul_dvd_mul !dvd.refl, apply ih _ this end) end theorem mult_one_right (p : ℕ) : mult p 1 = 0:= assert H : p^(mult p 1) = 1, from eq_one_of_dvd_one !pow_mult_dvd, or.elim (le_or_gt p 1) (suppose p ≤ 1, by rewrite [!mult_eq_zero_of_le_one this]) (suppose p > 1, by_contradiction (suppose mult p 1 ≠ 0, have mult p 1 > 0, from pos_of_ne_zero this, assert p^(mult p 1) > 1, from pow_gt_one `p > 1` this, show false, by rewrite H at this; apply !lt.irrefl this)) private theorem mult_pow_mul {p n : ℕ} (i : ℕ) (pgt1 : p > 1) (npos : n > 0) : mult p (p^i * n) = i + mult p n := begin induction i with [i, ih], {krewrite [pow_zero, one_mul, zero_add]}, have p > 0, from lt.trans zero_lt_one pgt1, have psin_pos : p^(succ i) * n > 0, from mul_pos (!pow_pos_of_pos this) npos, have p ∣ p^(succ i) * n, by rewrite [pow_succ, mul.assoc]; apply dvd_mul_right, rewrite [mult_rec pgt1 psin_pos this, pow_succ', mul.right_comm, !nat.mul_div_cancel `p > 0`, ih], rewrite [add.comm i, add.comm (succ i)] end theorem mult_pow_self {p : ℕ} (i : ℕ) (pgt1 : p > 1) : mult p (p^i) = i := by rewrite [-(mul_one (p^i)), mult_pow_mul i pgt1 zero_lt_one, mult_one_right] theorem mult_self {p : ℕ} (pgt1 : p > 1) : mult p p = 1 := by rewrite [-pow_one p at {2}]; apply mult_pow_self 1 pgt1 theorem le_mult {p i n : ℕ} (pgt1 : p > 1) (npos : n > 0) (pidvd : p^i ∣ n) : i ≤ mult p n := dvd.elim pidvd (take m, suppose n = p^i * m, assert m > 0, from pos_of_mul_pos_left (this ▸ npos), by subst n; rewrite [mult_pow_mul i pgt1 this]; apply le_add_right) theorem not_dvd_div_pow_mult {p n : ℕ} (pgt1 : p > 1) (npos : n > 0) : ¬ p ∣ n / p^(mult p n) := assume pdvd : p ∣ n / p^(mult p n), obtain m (H : n / p^(mult p n) = p * m), from exists_eq_mul_right_of_dvd pdvd, assert n = p^(succ (mult p n)) * m, from calc n = p^mult p n * (n / p^mult p n) : by rewrite (nat.mul_div_cancel' !pow_mult_dvd) ... = p^(succ (mult p n)) * m : by rewrite [H, pow_succ', mul.assoc], have p^(succ (mult p n)) ∣ n, by rewrite this at {2}; apply dvd_mul_right, have succ (mult p n) ≤ mult p n, from le_mult pgt1 npos this, show false, from !not_succ_le_self this theorem mult_mul {p m n : ℕ} (primep : prime p) (mpos : m > 0) (npos : n > 0) : mult p (m * n) = mult p m + mult p n := let m' := m / p^mult p m, n' := n / p^mult p n in assert p > 1, from gt_one_of_prime primep, assert meq : m = p^mult p m * m', by rewrite (nat.mul_div_cancel' !pow_mult_dvd), assert neq : n = p^mult p n * n', by rewrite (nat.mul_div_cancel' !pow_mult_dvd), have m'pos : m' > 0, from pos_of_mul_pos_left (meq ▸ mpos), have n'pos : n' > 0, from pos_of_mul_pos_left (neq ▸ npos), have npdvdm' : ¬ p ∣ m', from !not_dvd_div_pow_mult `p > 1` mpos, have npdvdn' : ¬ p ∣ n', from !not_dvd_div_pow_mult `p > 1` npos, assert npdvdm'n' : ¬ p ∣ m' * n', from not_dvd_mul_of_prime primep npdvdm' npdvdn', assert m'n'pos : m' * n' > 0, from mul_pos m'pos n'pos, assert multm'n' : mult p (m' * n') = 0, from mult_eq_zero_of_not_dvd npdvdm'n', calc mult p (m * n) = mult p (p^(mult p m + mult p n) * (m' * n')) : by rewrite [pow_add, mul.right_comm, -mul.assoc, -meq, mul.assoc, mul.comm (n / _), -neq] ... = mult p m + mult p n : by rewrite [!mult_pow_mul `p > 1` m'n'pos, multm'n'] theorem mult_pow {p m : ℕ} (n : ℕ) (mpos : m > 0) (primep : prime p) : mult p (m^n) = n * mult p m := begin induction n with n ih, krewrite [pow_zero, mult_one_right, zero_mul], rewrite [pow_succ, mult_mul primep mpos (!pow_pos_of_pos mpos), ih, succ_mul, add.comm] end theorem dvd_of_forall_prime_mult_le {m n : ℕ} (mpos : m > 0) (H : ∀ {p}, prime p → mult p m ≤ mult p n) : m ∣ n := begin revert H, revert n, induction m using nat.strong_induction_on with [m, ih], cases (decidable.em (m = 1)) with [meq, mneq], {intros, rewrite meq, apply one_dvd}, have mgt1 : m > 1, from lt_of_le_of_ne (succ_le_of_lt mpos) (ne.symm mneq), have mge2 : m ≥ 2, from succ_le_of_lt mgt1, have hpd : ∃ p, prime p ∧ p ∣ m, from exists_prime_and_dvd mge2, cases hpd with [p, H1], cases H1 with [primep, pdvdm], intro n, cases (eq_zero_or_pos n) with [nz, npos], {intros; rewrite nz; apply dvd_zero}, assume H : ∀ {p : ℕ}, prime p → mult p m ≤ mult p n, obtain m' (meq : m = p * m'), from exists_eq_mul_right_of_dvd pdvdm, assert pgt1 : p > 1, from gt_one_of_prime primep, assert m'pos : m' > 0, from pos_of_ne_zero (assume m'z, by revert mpos; rewrite [meq, m'z, mul_zero]; apply not_lt_zero), have m'ltm : m' < m, by rewrite [meq, -one_mul m' at {1}]; apply mul_lt_mul_of_lt_of_le m'pos pgt1 !le.refl, have multpm : mult p m ≥ 1, from le_mult pgt1 mpos (by rewrite pow_one; apply pdvdm), have multpn : mult p n ≥ 1, from le.trans multpm (H primep), obtain n' (neq : n = p * n'), from exists_eq_mul_right_of_dvd (dvd_of_mult_pos (lt_of_succ_le multpn)), assert n'pos : n' > 0, from pos_of_ne_zero (assume n'z, by revert npos; rewrite [neq, n'z, mul_zero]; apply not_lt_zero), have ∀q, prime q → mult q m' ≤ mult q n', from (take q, assume primeq : prime q, have multqm : mult q m = mult q p + mult q m', by rewrite [meq, mult_mul primeq (pos_of_prime primep) m'pos], have multqn : mult q n = mult q p + mult q n', by rewrite [neq, mult_mul primeq (pos_of_prime primep) n'pos], show mult q m' ≤ mult q n', from le_of_add_le_add_left (multqm ▸ multqn ▸ H primeq)), assert m'dvdn' : m' ∣ n', from ih m' m'ltm m'pos n' this, show m ∣ n, by rewrite [meq, neq]; apply mul_dvd_mul !dvd.refl m'dvdn' end theorem eq_of_forall_prime_mult_eq {m n : ℕ} (mpos : m > 0) (npos : n > 0) (H : ∀ p, prime p → mult p m = mult p n) : m = n := dvd.antisymm (dvd_of_forall_prime_mult_le mpos (take p, assume primep, H _ primep ▸ !le.refl)) (dvd_of_forall_prime_mult_le npos (take p, assume primep, H _ primep ▸ !le.refl)) /- prime factors -/ definition prime_factors (n : ℕ) : finset ℕ := { p ∈ upto (succ n) | prime p ∧ p ∣ n } theorem prime_of_mem_prime_factors {p n : ℕ} (H : p ∈ prime_factors n) : prime p := and.left (of_mem_sep H) theorem dvd_of_mem_prime_factors {p n : ℕ} (H : p ∈ prime_factors n) : p ∣ n := and.right (of_mem_sep H) theorem mem_prime_factors {p n : ℕ} (npos : n > 0) (primep : prime p) (pdvdn : p ∣ n) : p ∈ prime_factors n := have plen : p ≤ n, from le_of_dvd npos pdvdn, mem_sep_of_mem (mem_upto_of_lt (lt_succ_of_le plen)) (and.intro primep pdvdn) /- prime factorization -/ theorem mult_pow_eq_zero_of_prime_of_ne {p q : ℕ} (primep : prime p) (primeq : prime q) (pneq : p ≠ q) (i : ℕ) : mult p (q^i) = 0 := begin induction i with i ih, {krewrite [pow_zero, mult_one_right]}, have qpos : q > 0, from pos_of_prime primeq, have qipos : q^i > 0, from !pow_pos_of_pos qpos, rewrite [pow_succ', mult_mul primep qipos qpos, ih, mult_eq_zero_of_prime_of_ne primep primeq pneq] end theorem mult_prod_pow_of_not_mem {p : ℕ} (primep : prime p) {s : finset ℕ} (sprimes : ∀ p, p ∈ s → prime p) (f : ℕ → ℕ) (pns : p ∉ s) : mult p (∏ q ∈ s, q^(f q)) = 0 := begin induction s with a s anins ih, {rewrite [Prod_empty, mult_one_right]}, have pnea : p ≠ a, from assume peqa, by rewrite peqa at pns; exact pns !mem_insert, have primea : prime a, from sprimes a !mem_insert, have afapos : a ^ f a > 0, from !pow_pos_of_pos (pos_of_prime primea), have prodpos : (∏ q ∈ s, q ^ f q) > 0, from Prod_pos (take q, assume qs, !pow_pos_of_pos (pos_of_prime (forall_of_forall_insert sprimes q qs))), rewrite [!Prod_insert_of_not_mem anins, mult_mul primep afapos prodpos], rewrite (mult_pow_eq_zero_of_prime_of_ne primep primea pnea), rewrite (ih (forall_of_forall_insert sprimes) (λ H, pns (!mem_insert_of_mem H))) end theorem mult_prod_pow_of_mem {p : ℕ} (primep : prime p) {s : finset ℕ} (sprimes : ∀ p, p ∈ s → prime p) (f : ℕ → ℕ) (ps : p ∈ s) : mult p (∏ q ∈ s, q^(f q)) = f p := begin induction s with a s anins ih, {exact absurd ps !not_mem_empty}, have primea : prime a, from sprimes a !mem_insert, have afapos : a ^ f a > 0, from !pow_pos_of_pos (pos_of_prime primea), have prodpos : (∏ q ∈ s, q ^ f q) > 0, from Prod_pos (take q, assume qs, !pow_pos_of_pos (pos_of_prime (forall_of_forall_insert sprimes q qs))), rewrite [!Prod_insert_of_not_mem anins, mult_mul primep afapos prodpos], cases eq_or_mem_of_mem_insert ps with peqa pins, {rewrite [peqa, !mult_pow_self (gt_one_of_prime primea)], rewrite [mult_prod_pow_of_not_mem primea (forall_of_forall_insert sprimes) _ anins]}, have pnea : p ≠ a, from by intro peqa; rewrite peqa at pins; exact anins pins, rewrite [mult_pow_eq_zero_of_prime_of_ne primep primea pnea, zero_add], exact (ih (forall_of_forall_insert sprimes) pins) end theorem eq_prime_factorization {n : ℕ} (npos : n > 0) : n = (∏ p ∈ prime_factors n, p^(mult p n)) := let nprod := ∏ p ∈ prime_factors n, p^(mult p n) in assert primefactors : ∀ p, p ∈ prime_factors n → prime p, from take p, @prime_of_mem_prime_factors p n, have prodpos : (∏ q ∈ prime_factors n, q^(mult q n)) > 0, from Prod_pos (take q, assume qpf, !pow_pos_of_pos (pos_of_prime (prime_of_mem_prime_factors qpf))), eq_of_forall_prime_mult_eq npos prodpos (take p, assume primep, decidable.by_cases (assume pprimefactors : p ∈ prime_factors n, eq.symm (mult_prod_pow_of_mem primep primefactors (λ p, mult p n) pprimefactors)) (assume pnprimefactors : p ∉ prime_factors n, have ¬ p ∣ n, from assume H, pnprimefactors (mem_prime_factors npos primep H), assert mult p n = 0, from mult_eq_zero_of_not_dvd this, by rewrite [this, mult_prod_pow_of_not_mem primep primefactors _ pnprimefactors])) end nat
01abf6bc70071016fe6b85cc740dad0073d4a420
4b846d8dabdc64e7ea03552bad8f7fa74763fc67
/library/init/meta/interaction_monad.lean
06c3c2e1372436eb5e374f2bf6d14f85f6b8afb4
[ "Apache-2.0" ]
permissive
pacchiano/lean
9324b33f3ac3b5c5647285160f9f6ea8d0d767dc
fdadada3a970377a6df8afcd629a6f2eab6e84e8
refs/heads/master
1,611,357,380,399
1,489,870,101,000
1,489,870,101,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
3,314
lean
/- Copyright (c) 2017 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura, Sebastian Ullrich -/ prelude import init.function init.data.option.basic init.util import init.category.combinators init.category.monad init.category.alternative init.category.monad_fail import init.data.nat.div init.meta.exceptional init.meta.format init.meta.environment import init.meta.pexpr init.data.to_string init.data.string.basic universes u v meta inductive interaction_monad.result (state : Type) (α : Type u) | success : α → state → interaction_monad.result | exception {} : option (unit → format) → option pos → state → interaction_monad.result open interaction_monad.result section variables {state : Type} {α : Type u} variables [has_to_string α] meta def interaction_monad.result_to_string : result state α → string | (success a s) := to_string a | (exception (some t) ref s) := "Exception: " ++ to_string (t ()) | (exception none ref s) := "[silent exception]" meta instance interaction_monad.result_has_string : has_to_string (result state α) := ⟨interaction_monad.result_to_string⟩ end @[reducible] meta def interaction_monad (state : Type) (α : Type u) := state → result state α section parameter {state : Type} variables {α : Type u} {β : Type v} local notation `m` := interaction_monad state @[inline] meta def interaction_monad_fmap (f : α → β) (t : m α) : m β := λ s, interaction_monad.result.cases_on (t s) (λ a s', success (f a) s') (λ e s', exception e s') @[inline] meta def interaction_monad_bind (t₁ : m α) (t₂ : α → m β) : m β := λ s, interaction_monad.result.cases_on (t₁ s) (λ a s', t₂ a s') (λ e s', exception e s') @[inline] meta def interaction_monad_return (a : α) : m α := λ s, success a s meta def interaction_monad_orelse {α : Type u} (t₁ t₂ : m α) : m α := λ s, interaction_monad.result.cases_on (t₁ s) success (λ e₁ ref₁ s', interaction_monad.result.cases_on (t₂ s) success exception) @[inline] meta def interaction_monad_seq (t₁ : m α) (t₂ : m β) : m β := interaction_monad_bind t₁ (λ a, t₂) meta instance interaction_monad.monad : monad m := {map := @interaction_monad_fmap, pure := @interaction_monad_return, bind := @interaction_monad_bind} meta def interaction_monad.mk_exception {α : Type u} {β : Type v} [has_to_format β] (msg : β) (ref : option expr) (s : state) : result state α := exception (some (λ _, to_fmt msg)) none s meta def interaction_monad.fail {α : Type u} {β : Type v} [has_to_format β] (msg : β) : m α := λ s, interaction_monad.mk_exception msg none s meta def interaction_monad.silent_fail {α : Type u} : m α := λ s, exception none none s meta def interaction_monad.failed {α : Type u} : m α := interaction_monad.fail "failed" meta instance interaction_monad.monad_fail : monad_fail m := { interaction_monad.monad with fail := λ α s, interaction_monad.fail (to_fmt s) } -- TODO: unify `parser` and `tactic` behavior? -- meta instance interaction_monad.alternative : alternative m := -- ⟨@interaction_monad_fmap, (λ α a s, success a s), (@fapp _ _), @interaction_monad.failed, @interaction_monad_orelse⟩ end
c21bf5ed28b79ad140d43af30221b46bb719b5ea
07c6143268cfb72beccd1cc35735d424ebcb187b
/src/analysis/convex/specific_functions.lean
974fdec0751041eee9d87ed526cf3605a5a0951b
[ "Apache-2.0" ]
permissive
khoek/mathlib
bc49a842910af13a3c372748310e86467d1dc766
aa55f8b50354b3e11ba64792dcb06cccb2d8ee28
refs/heads/master
1,588,232,063,837
1,587,304,803,000
1,587,304,803,000
176,688,517
0
0
Apache-2.0
1,553,070,585,000
1,553,070,585,000
null
UTF-8
Lean
false
false
4,182
lean
/- Copyright (c) 2020 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudryashov -/ import analysis.calculus.mean_value data.nat.parity analysis.complex.exponential /-! # Collection of convex functions In this file we prove that the following functions are convex: * `convex_on_exp` : the exponential function is convex on $(-∞, +∞)$; * `convex_on_pow_of_even` : given an even natural number $n$, the function $f(x)=x^n$ is convex on $(-∞, +∞)$; * `convex_on_pow` : for a natural $n$, the function $f(x)=x^n$ is convex on $[0, +∞)$; * `convex_on_fpow` : for an integer $m$, the function $f(x)=x^m$ is convex on $(0, +∞)$. ## TODO * `convex_on_rpow : ∀ r : ℝ, (r ≤ 0 ∨ 1 ≤ r) → convex_on (Ioi 0) (λ x, x ^ r)` -/ open real set /-- `exp` is convex on the whole real line -/ lemma convex_on_exp : convex_on univ exp := convex_on_univ_of_deriv2_nonneg differentiable_exp (by simp) (assume x, (iter_deriv_exp 2).symm ▸ le_of_lt (exp_pos x)) /-- `x^n`, `n : ℕ` is convex on the whole real line whenever `n` is even -/ lemma convex_on_pow_of_even {n : ℕ} (hn : n.even) : convex_on set.univ (λ x, x^n) := begin apply convex_on_univ_of_deriv2_nonneg differentiable_pow, { simp only [deriv_pow', differentiable.mul, differentiable_const, differentiable_pow] }, { intro x, rcases hn.sub (nat.even_bit0 1) with ⟨k, hk⟩, simp only [iter_deriv_pow, finset.prod_range_succ, finset.prod_range_zero, nat.sub_zero, mul_one, hk, pow_mul', pow_two], exact mul_nonneg (nat.cast_nonneg _) (mul_self_nonneg _) } end /-- `x^n`, `n : ℕ` is convex on `[0, +∞)` for all `n` -/ lemma convex_on_pow (n : ℕ) : convex_on (Ici 0) (λ x, x^n) := begin apply convex_on_of_deriv2_nonneg (convex_Ici _) (continuous_pow n).continuous_on; simp only [interior_Ici, differentiable_on_pow, deriv_pow', differentiable_on_const, differentiable_on.mul, iter_deriv_pow], intros x hx, exact mul_nonneg (nat.cast_nonneg _) (pow_nonneg (le_of_lt hx) _) end lemma finset.prod_nonneg_of_card_nonpos_even {α β : Type*} [linear_ordered_comm_ring β] {f : α → β} [decidable_pred (λ x, f x ≤ 0)] {s : finset α} (h0 : (s.filter (λ x, f x ≤ 0)).card.even) : 0 ≤ s.prod f := calc 0 ≤ s.prod (λ x, (if f x ≤ 0 then (-1:β) else 1) * f x) : finset.prod_nonneg (λ x _, by { split_ifs with hx hx, by simp [hx], simp at hx ⊢, exact le_of_lt hx }) ... = _ : by rw [finset.prod_mul_distrib, finset.prod_ite, finset.prod_const_one, mul_one, finset.prod_const, neg_one_pow_eq_pow_mod_two, nat.even_iff.1 h0, pow_zero, one_mul] lemma int_prod_range_nonneg (m : ℤ) (n : ℕ) (hn : n.even) : 0 ≤ (finset.range n).prod (λ k, m - k) := begin cases (le_or_lt ↑n m) with hnm hmn, { exact finset.prod_nonneg (λ k hk, sub_nonneg.2 (le_trans (int.coe_nat_le.2 $ le_of_lt $ finset.mem_range.1 hk) hnm)) }, cases le_or_lt 0 m with hm hm, { lift m to ℕ using hm, exact le_of_eq (eq.symm $ finset.prod_eq_zero (finset.mem_range.2 $ int.coe_nat_lt.1 hmn) (sub_self _)) }, clear hmn, apply finset.prod_nonneg_of_card_nonpos_even, convert hn, convert finset.card_range n, ext k, simp only [finset.mem_filter, finset.mem_range], refine ⟨and.left, λ hk, ⟨hk, sub_nonpos.2 $ le_trans (le_of_lt hm) _⟩⟩, exact int.coe_nat_nonneg k end /-- `x^m`, `m : ℤ` is convex on `(0, +∞)` for all `m` -/ lemma convex_on_fpow (m : ℤ) : convex_on (Ioi 0) (λ x, x^m) := begin apply convex_on_of_deriv2_nonneg (convex_Ioi 0); try { rw [interior_Ioi] }, { exact (differentiable_on_fpow $ lt_irrefl _).continuous_on }, { exact differentiable_on_fpow (lt_irrefl _) }, { have : eq_on (deriv (λx:ℝ, x^m)) (λx, ↑m * x^(m-1)) (Ioi 0), from λ x hx, deriv_fpow (ne_of_gt hx), refine (differentiable_on_congr this).2 _, exact (differentiable_on_fpow (lt_irrefl _)).const_mul _ }, { intros x hx, simp only [iter_deriv_fpow (ne_of_gt hx)], refine mul_nonneg (int.cast_nonneg.2 _) (fpow_nonneg_of_nonneg (le_of_lt hx) _), exact int_prod_range_nonneg _ _ (nat.even_bit0 1) } end
6bd113de6e6f7e14781c65242e012fb557d4aa42
b7f22e51856f4989b970961f794f1c435f9b8f78
/tests/lean/run/tactic22.lean
51c5555464e6b7d8f4a8d5843b5650af00a043a3
[ "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
281
lean
import logic open tactic notation `(` h `|` r:(foldl `|` (e r, tactic.or_else r e) h) `)` := r infixl `;`:15 := tactic.and_then theorem T (a b c d : Prop) (Ha : a) (Hb : b) (Hc : c) (Hd : d) : a ∧ b ∧ c ∧ d := by fixpoint (λ f, (apply and.intro; f | assumption; f | id))
85e485016218fa916e84c8258ed34c2cc7c4396e
dc253be9829b840f15d96d986e0c13520b085033
/algebra/cogroup.hlean
5cd60fd154d401328b6f35c28041d34d5cd123bd
[ "Apache-2.0" ]
permissive
cmu-phil/Spectral
4ce68e5c1ef2a812ffda5260e9f09f41b85ae0ea
3b078f5f1de251637decf04bd3fc8aa01930a6b3
refs/heads/master
1,685,119,195,535
1,684,169,772,000
1,684,169,772,000
46,450,197
42
13
null
1,505,516,767,000
1,447,883,921,000
Lean
UTF-8
Lean
false
false
7,414
hlean
import algebra.group_theory ..pointed ..homotopy.smash open eq pointed algebra group eq equiv is_trunc is_conn prod prod.ops smash susp unit pushout trunc prod section variables {A B C : Type*} definition prod.pair_pmap (f : C →* A) (g : C →* B) : C →* A ×* B := pmap.mk (λ c, (f c, g c)) (pair_eq (respect_pt f) (respect_pt g)) -- ×* is the product in Type* definition pmap_prod_equiv : (C →* A ×* B) ≃ (C →* A) × (C →* B) := begin apply equiv.MK (λ f, (ppr1 ∘* f, ppr2 ∘* f)) (λ w, prod.elim w prod.pair_pmap), { intro p, induction p with f g, apply pair_eq, { apply eq_of_phomotopy, fapply phomotopy.mk, { intro x, reflexivity }, { symmetry, apply trans (prod_eq_pr1 (respect_pt f) (respect_pt g)), apply inverse, apply idp_con } }, { apply eq_of_phomotopy, fapply phomotopy.mk, { intro x, reflexivity }, { symmetry, apply trans (prod_eq_pr2 (respect_pt f) (respect_pt g)), apply inverse, apply idp_con } } }, { intro f, apply eq_of_phomotopy, fapply phomotopy.mk, { intro x, apply prod.eta }, { symmetry, exact prod.pair_eq_eta (respect_pt f) } } end -- since ~* is the identity type of pointed maps, -- the following follows by univalence, but we give a direct proof -- if we really have to, we could prove the uncurried version -- is an equivalence, but it's a pain without eta for products definition pair_phomotopy {f g : C →* A ×* B} (h : ppr1 ∘* f ~* ppr1 ∘* g) (k : ppr2 ∘* f ~* ppr2 ∘* g) : f ~* g := phomotopy.mk (λ x, prod_eq (h x) (k x)) begin apply prod.prod_eq_assemble, { esimp, rewrite [prod.eq_pr1_concat,prod_eq_pr1], exact to_homotopy_pt h }, { esimp, rewrite [prod.eq_pr2_concat,prod_eq_pr2], exact to_homotopy_pt k } end end -- should be in wedge definition or_of_wedge {A B : Type*} (w : wedge A B) : trunc.or (Σ a, w = inl a) (Σ b, w = inr b) := begin induction w with a b, { exact trunc.tr (sum.inl (sigma.mk a idp)) }, { exact trunc.tr (sum.inr (sigma.mk b idp)) }, { apply is_prop.elimo } end namespace group -- is this the correct namespace? -- TODO: modify h_space to match -- TODO: move these to appropriate places definition pdiag (A : Type*) : A →* (A ×* A) := pmap.mk (λ a, (a, a)) idp section prod variables (A B : Type*) definition wpr1 (A B : Type*) : (A ∨ B) →* A := pmap.mk (wedge.elim (pid A) (pconst B A) idp) idp definition wpr2 (A B : Type*) : (A ∨ B) →* B := pmap.mk (wedge.elim (pconst A B) (pid B) idp) idp definition ppr1_pprod_of_wedge (A B : Type*) : ppr1 ∘* pprod_of_wedge A B ~* wpr1 A B := begin fconstructor, { intro w, induction w with a b, { reflexivity }, { reflexivity }, { apply eq_pathover, apply hdeg_square, apply trans (ap_compose ppr1 (pprod_of_wedge A B) (pushout.glue star)), krewrite pushout.elim_glue, krewrite pushout.elim_glue } }, { reflexivity } end definition ppr2_pprod_of_wedge (A B : Type*) : ppr2 ∘* pprod_of_wedge A B ~* wpr2 A B := begin fconstructor, { intro w, induction w with a b, { reflexivity }, { reflexivity }, { apply eq_pathover, apply hdeg_square, apply trans (ap_compose ppr2 (pprod_of_wedge A B) (pushout.glue star)), krewrite pushout.elim_glue, krewrite pushout.elim_glue } }, { reflexivity } end end prod structure co_h_space [class] (A : Type*) := (comul : A →* (A ∨ A)) (colaw : pprod_of_wedge A A ∘* comul ~* pdiag A) open co_h_space definition co_h_space_of_counit_laws {A : Type*} (c : A →* (A ∨ A)) (l : wpr1 A A ∘* c ~* pid A) (r : wpr2 A A ∘* c ~* pid A) : co_h_space A := co_h_space.mk c (pair_phomotopy (calc ppr1 ∘* pprod_of_wedge A A ∘* c ~* (ppr1 ∘* pprod_of_wedge A A) ∘* c : (passoc ppr1 (pprod_of_wedge A A) c)⁻¹* ... ~* wpr1 A A ∘* c : pwhisker_right c (ppr1_pprod_of_wedge A A) ... ~* pid A : l) (calc ppr2 ∘* pprod_of_wedge A A ∘* c ~* (ppr2 ∘* pprod_of_wedge A A) ∘* c : (passoc ppr2 (pprod_of_wedge A A) c)⁻¹* ... ~* wpr2 A A ∘* c : pwhisker_right c (ppr2_pprod_of_wedge A A) ... ~* pid A : r)) section variables (A : Type*) [H : co_h_space A] include H definition counit_left : wpr1 A A ∘* comul A ~* pid A := calc wpr1 A A ∘* comul A ~* (ppr1 ∘* (pprod_of_wedge A A)) ∘* comul A : (pwhisker_right (comul A) (ppr1_pprod_of_wedge A A))⁻¹* ... ~* ppr1 ∘* ((pprod_of_wedge A A) ∘* comul A) : passoc ppr1 (pprod_of_wedge A A) (comul A) ... ~* pid A : pwhisker_left ppr1 (colaw A) definition counit_right : wpr2 A A ∘* comul A ~* pid A := calc wpr2 A A ∘* comul A ~* (ppr2 ∘* (pprod_of_wedge A A)) ∘* comul A : (pwhisker_right (comul A) (ppr2_pprod_of_wedge A A))⁻¹* ... ~* ppr2 ∘* ((pprod_of_wedge A A) ∘* comul A) : passoc ppr2 (pprod_of_wedge A A) (comul A) ... ~* pid A : pwhisker_left ppr2 (colaw A) definition is_conn_co_h_space : is_conn 0 A := begin apply is_contr.mk (trunc.tr pt), intro ta, induction ta with a, have t : trunc -1 ((Σ b, comul A a = inl b) ⊎ (Σ c, comul A a = inr c)), from (or_of_wedge (comul A a)), induction t with s, induction s with bp cp, { induction bp with b p, apply ap trunc.tr, exact (ap (wpr2 A A) p)⁻¹ ⬝ (counit_right A a) }, { induction cp with c p, apply ap trunc.tr, exact (ap (wpr1 A A) p)⁻¹ ⬝ (counit_left A a) } end end section variable (A : Type*) definition pinch : ⅀ A →* wedge (⅀ A) (⅀ A) := begin fapply pmap.mk, { intro sa, induction sa with a, { exact inl north }, { exact inr south }, { exact ap inl (glue a ⬝ (glue pt)⁻¹) ⬝ glue star ⬝ ap inr (glue a) } }, { reflexivity } end definition co_h_space_susp : co_h_space (⅀ A) := co_h_space_of_counit_laws (pinch A) begin fapply phomotopy.mk, { intro sa, induction sa with a, { reflexivity }, { exact glue pt }, { apply eq_pathover, krewrite [ap_id,-ap_compose' (wpr1 (⅀ A) (⅀ A)) (pinch A)], krewrite elim_merid, rewrite ap_con, krewrite [pushout.elim_inr,ap_constant], rewrite ap_con, krewrite [pushout.elim_inl,pushout.elim_glue,ap_id], apply square_of_eq, apply trans !idp_con, apply inverse, apply trans (con.assoc (merid a) (glue pt)⁻¹ (glue pt)), exact whisker_left (merid a) (con.left_inv (glue pt)) } }, { reflexivity } end begin fapply phomotopy.mk, { intro sa, induction sa with a, { reflexivity }, { reflexivity }, { apply eq_pathover, krewrite [ap_id,-ap_compose' (wpr2 (⅀ A) (⅀ A)) (pinch A)], krewrite elim_merid, rewrite ap_con, krewrite [pushout.elim_inr,ap_id], rewrite ap_con, krewrite [pushout.elim_inl,pushout.elim_glue,ap_constant], apply square_of_eq, apply trans !idp_con, apply inverse, exact idp_con (merid a) } }, { reflexivity } end end /- terminology: magma, comagma? co_h_space/co_h_space? pre_inf_group? pre_inf_cogroup? ghs (for group-like H-space?) cgcohs (cogroup-like co-H-space?) cogroup_like_co_h_space? -/ end group
a28b403502702a02d47e6b5b59f8c870bc60f1e8
d48477f6d2a5f434203448f53a910b09488d752b
/src/integral_limits.lean
bfb745a07f355ef71c90602ec809777e953507ab
[]
no_license
ADedecker/gauss
2576868db8bf338155c8742f17cd06ba72091ee9
d44d482d49d4755b1d238f3e8a67d22a605970a9
refs/heads/master
1,685,610,013,938
1,625,525,246,000
1,625,525,246,000
338,175,066
1
0
null
null
null
null
UTF-8
Lean
false
false
20,146
lean
import measure_theory.integration import measure_theory.bochner_integration import measure_theory.lebesgue_measure import measure_theory.interval_integral open measure_theory filter set open_locale ennreal nnreal topological_space section growing_family variables {α : Type*} [measurable_space α] (μ : measure α) structure growing_family (φ : ℕ → set α) : Prop := (ae_eventually_mem : ∀ᵐ x ∂μ, ∀ᶠ n in at_top, x ∈ φ n) (mono : monotone φ) (measurable : ∀ n, measurable_set $ φ n) variables {μ} section Icc variables [preorder α] [topological_space α] [order_closed_topology α] [opens_measurable_space α] {a b : ℕ → α} (ha₁ : ∀ ⦃x y⦄, x ≤ y → a y ≤ a x) (ha₂ : tendsto a at_top at_bot) (hb₁ : monotone b) (hb₂ : tendsto b at_top at_top) lemma growing_family_Icc : growing_family μ (λ n, Icc (a n) (b n)) := { ae_eventually_mem := ae_of_all μ (λ x, (ha₂.eventually $ eventually_le_at_bot x).mp $ (hb₂.eventually $ eventually_ge_at_top x).mono $ λ n hbn han, ⟨han, hbn⟩ ), mono := λ i j hij, Icc_subset_Icc (ha₁ hij) (hb₁ hij), measurable := λ n, measurable_set_Icc } end Icc section Ixx variables [linear_order α] [topological_space α] [order_closed_topology α] [opens_measurable_space α] {a b : ℕ → α} (ha₁ : ∀ ⦃x y⦄, x ≤ y → a y ≤ a x) (ha₂ : tendsto a at_top at_bot) (hb₁ : monotone b) (hb₂ : tendsto b at_top at_top) lemma growing_family_Ioo [no_bot_order α] [no_top_order α] : growing_family μ (λ n, Ioo (a n) (b n)) := { ae_eventually_mem := ae_of_all μ (λ x, (ha₂.eventually $ eventually_lt_at_bot x).mp $ (hb₂.eventually $ eventually_gt_at_top x).mono $ λ n hbn han, ⟨han, hbn⟩ ), mono := λ i j hij, Ioo_subset_Ioo (ha₁ hij) (hb₁ hij), measurable := λ n, measurable_set_Ioo } lemma growing_family_Ioc [no_bot_order α] : growing_family μ (λ n, Ioc (a n) (b n)) := { ae_eventually_mem := ae_of_all μ (λ x, (ha₂.eventually $ eventually_lt_at_bot x).mp $ (hb₂.eventually $ eventually_ge_at_top x).mono $ λ n hbn han, ⟨han, hbn⟩ ), mono := λ i j hij, Ioc_subset_Ioc (ha₁ hij) (hb₁ hij), measurable := λ n, measurable_set_Ioc } lemma growing_family_Ico [no_top_order α] : growing_family μ (λ n, Ico (a n) (b n)) := { ae_eventually_mem := ae_of_all μ (λ x, (ha₂.eventually $ eventually_le_at_bot x).mp $ (hb₂.eventually $ eventually_gt_at_top x).mono $ λ n hbn han, ⟨han, hbn⟩ ), mono := λ i j hij, Ico_subset_Ico (ha₁ hij) (hb₁ hij), measurable := λ n, measurable_set_Ico } end Ixx section Ixi_Iix lemma growing_family_Ici [preorder α] [topological_space α] [order_closed_topology α] [opens_measurable_space α] {a : ℕ → α} (ha₁ : ∀ ⦃x y⦄, x ≤ y → a y ≤ a x) (ha₂ : tendsto a at_top at_bot) : growing_family μ (λ n, Ici $ a n) := { ae_eventually_mem := ae_of_all μ (λ x, (ha₂.eventually $ eventually_le_at_bot x).mono $ λ n han, han ), mono := λ i j hij, Ici_subset_Ici.mpr (ha₁ hij), measurable := λ n, measurable_set_Ici } lemma growing_family_Ioi [linear_order α] [topological_space α] [order_closed_topology α] [opens_measurable_space α] {a : ℕ → α} (ha₁ : ∀ ⦃x y⦄, x ≤ y → a y ≤ a x) (ha₂ : tendsto a at_top at_bot) [no_bot_order α] : growing_family μ (λ n, Ioi $ a n) := { ae_eventually_mem := ae_of_all μ (λ x, (ha₂.eventually $ eventually_lt_at_bot x).mono $ λ n han, han ), mono := λ i j hij, Ioi_subset_Ioi (ha₁ hij), measurable := λ n, measurable_set_Ioi } lemma growing_family_Iic [preorder α] [topological_space α] [order_closed_topology α] [opens_measurable_space α] {a : ℕ → α} (ha₁ : monotone a) (ha₂ : tendsto a at_top at_top) : growing_family μ (λ n, Iic $ a n) := { ae_eventually_mem := ae_of_all μ (λ x, (ha₂.eventually $ eventually_ge_at_top x).mono $ λ n han, han ), mono := λ i j hij, Iic_subset_Iic.mpr (ha₁ hij), measurable := λ n, measurable_set_Iic } lemma growing_family_Iio [linear_order α] [topological_space α] [order_closed_topology α] [opens_measurable_space α] {a : ℕ → α} (ha₁ : monotone a) (ha₂ : tendsto a at_top at_top) [no_top_order α] : growing_family μ (λ n, Iio $ a n) := { ae_eventually_mem := ae_of_all μ (λ x, (ha₂.eventually $ eventually_gt_at_top x).mono $ λ n han, han ), mono := λ i j hij, Iio_subset_Iio (ha₁ hij), measurable := λ n, measurable_set_Iio } end Ixi_Iix lemma growing_family.ae_tendsto_indicator {β : Type*} [has_zero β] [topological_space β] {f : α → β} {φ : ℕ → set α} (hφ : growing_family μ φ) : ∀ᵐ x ∂μ, tendsto (λ n, (φ n).indicator f x) at_top (𝓝 $ f x) := hφ.ae_eventually_mem.mono (λ x hx, tendsto_const_nhds.congr' $ hx.mono $ λ n hn, (indicator_of_mem hn _).symm) lemma growing_family_restrict_of_ae_imp {s : set α} {φ : ℕ → set α} (hs : measurable_set s) (ae_eventually_mem : ∀ᵐ x ∂μ, x ∈ s → ∀ᶠ n in at_top, x ∈ φ n) (mono : monotone φ) (measurable : ∀ n, measurable_set $ φ n) : growing_family (μ.restrict s) φ := { ae_eventually_mem := by rwa ae_restrict_iff' hs, mono := mono, measurable := measurable } lemma growing_family.inter_restrict {φ : ℕ → set α} (hφ : growing_family μ φ) {s : set α} (hs : measurable_set s) : growing_family (μ.restrict s) (λ n, φ n ∩ s) := growing_family_restrict_of_ae_imp hs (hφ.ae_eventually_mem.mono (λ x hx hxs, hx.mono $ λ n hn, ⟨hn, hxs⟩)) (λ i j hij, inter_subset_inter_left s (hφ.mono hij)) (λ n, (hφ.measurable n).inter hs) end growing_family section integral_limits variables {α : Type*} [measurable_space α] {μ : measure α} lemma lintegral_eq_supr {φ : ℕ → set α} (hφ : growing_family μ φ) {f : α → ℝ≥0∞} (hfm : measurable f) : ∫⁻ x, f x ∂μ = ⨆ (n : ℕ), ∫⁻ x in φ n, f x ∂μ := begin let F := λ n, indicator (φ n) f, have F_tendsto : ∀ᵐ x ∂μ, tendsto (λ n, F n x) at_top (𝓝 $ f x) := hφ.ae_tendsto_indicator, have F_mono : ∀ x, monotone (λ n, F n x) := λ x i j hij, indicator_le_indicator_of_subset (hφ.mono hij) (λ _, zero_le _) x, have f_eq_supr_F : ∀ᵐ x ∂μ, f x = ⨆ (n : ℕ), F n x := F_tendsto.mono (λ x hx, tendsto_nhds_unique hx (tendsto_at_top_csupr (F_mono x) ⟨⊤, λ _ _, le_top⟩)), have lintegral_F_eq : ∀ n, ∫⁻ (x : α), F n x ∂μ = ∫⁻ x in φ n, f x ∂μ := λ n, lintegral_indicator _ (hφ.measurable n), rw lintegral_congr_ae f_eq_supr_F, conv_rhs {congr, funext, rw ← lintegral_F_eq}, exact lintegral_supr (λ n, hfm.indicator $ hφ.measurable n) (λ i j hij x, F_mono x hij) end lemma tendsto_set_lintegral_of_monotone_set {φ : ℕ → set α} (hφ : monotone φ) {f : α → ℝ≥0∞} : tendsto (λ n, ∫⁻ x in φ n, f x ∂μ) at_top (𝓝 $ ⨆ (n : ℕ), ∫⁻ x in φ n, f x ∂μ) := tendsto_at_top_csupr (λ i j hij, lintegral_mono' (measure.restrict_mono (hφ hij) (le_refl _)) (le_refl _)) ⟨⊤, λ _ _, le_top⟩ lemma lintegral_eq_of_tendsto_lintegral {φ : ℕ → set α} (hφ : growing_family μ φ) {f : α → ℝ≥0∞} (I : ℝ≥0∞) (hfm : measurable f) (h : tendsto (λ n, ∫⁻ x in φ n, f x ∂μ) at_top (𝓝 I)) : ∫⁻ x, f x ∂μ = I := begin convert lintegral_eq_supr hφ hfm, refine tendsto_nhds_unique h (tendsto_set_lintegral_of_monotone_set hφ.mono) end lemma eventually_ne_of_tendsto_nhds {β : Type*} [topological_space β] [t1_space β] {f : α → β} {b b' : β} (hbb' : b ≠ b') {l : filter α} (hf : tendsto f l (𝓝 b)) : ∀ᶠ x in l, f x ≠ b' := hf (compl_singleton_mem_nhds hbb') lemma eventually_le_of_tendsto_of_tendsto_of_lt {β : Type*} [linear_order β] [topological_space β] [order_topology β] {f g : α → β} {b b' : β} (hbb' : b < b') {l : filter α} (hf : tendsto f l (𝓝 b)) (hg : tendsto g l (𝓝 b')) : f ≤ᶠ[l] g := begin rcases order_separated hbb' with ⟨u, v, hu, hv, hub, hvb', huv⟩, have hfu : f ⁻¹' u ∈ l := hf (mem_nhds_sets hu hub), have hgv : g ⁻¹' v ∈ l := hg (mem_nhds_sets hv hvb'), exact eventually_of_mem (inter_mem_sets hfu hgv) (λ x ⟨hxu, hxv⟩, (huv _ hxu _ hxv).le), end lemma le_of_tendsto_of_monotone {β : Type*} [preorder α] [linear_order β] [topological_space β] [order_closed_topology β] {f : ℕ → β} {b : β} (hmono : monotone f) (hf : tendsto f at_top (𝓝 b)) : ∀ x, f x ≤ b := λ x, ge_of_tendsto hf ((eventually_ge_at_top x).mono $ λ _ h, hmono h) lemma ge_of_tendsto_of_antimono {β : Type*} [preorder α] [linear_order β] [topological_space β] [order_closed_topology β] {f : ℕ → β} {b : β} (hanti : ∀ ⦃x y⦄, x ≤ y → f y ≤ f x) (hf : tendsto f at_top (𝓝 b)) : ∀ x, b ≤ f x := λ x, le_of_tendsto hf ((eventually_ge_at_top x).mono $ λ _ h, hanti h) variables {E : Type*} [normed_group E] [topological_space.second_countable_topology E] [normed_space ℝ E] [complete_space E] [measurable_space E] [borel_space E] lemma integrable_of_tendsto_lintegral_nnnorm {φ : ℕ → set α} (hφ : growing_family μ φ) {f : α → E} (I : ℝ) (hfm : measurable f) (h : tendsto (λ n, ∫⁻ x in φ n, nnnorm (f x) ∂μ) at_top (𝓝 $ ennreal.of_real I)) : integrable f μ := begin refine ⟨hfm.ae_measurable, _⟩, unfold has_finite_integral, rw lintegral_eq_of_tendsto_lintegral hφ _ (measurable_ennreal_coe_iff.mpr (measurable_nnnorm.comp hfm)) h, exact ennreal.of_real_lt_top end lemma integrable_of_tendsto_lintegral_nnnorm' {φ : ℕ → set α} (hφ : growing_family μ φ) {f : α → E} (I : ℝ≥0) (hfm : measurable f) (h : tendsto (λ n, ∫⁻ x in φ n, nnnorm (f x) ∂μ) at_top (𝓝 I)) : integrable f μ := begin refine integrable_of_tendsto_lintegral_nnnorm hφ (I : ℝ) hfm _, convert h, exact ennreal.of_real_coe_nnreal end lemma integrable_of_tendsto_integral_norm {φ : ℕ → set α} (hφ : growing_family μ φ) {f : α → E} (I : ℝ) (hfm : measurable f) (hfi : ∀ n, integrable_on f (φ n) μ) (h : tendsto (λ n, ∫ x in φ n, ∥f x∥ ∂μ) at_top (𝓝 I)) : integrable f μ := begin conv at h in (integral _ _) { rw integral_eq_lintegral_of_nonneg_ae (ae_of_all _ (λ x, @norm_nonneg E _ (f x))) hfm.norm.ae_measurable }, conv at h in (ennreal.of_real _) { dsimp, rw ← coe_nnnorm, rw ennreal.of_real_coe_nnreal }, have h' : tendsto (λ (n : ℕ), (∫⁻ (a : α) in φ n, nnnorm (f a) ∂μ)) at_top (𝓝 $ ennreal.of_real I), { convert ennreal.tendsto_of_real h, ext n : 1, rw ennreal.of_real_to_real _, exact ne_top_of_lt (hfi n).2 }, exact integrable_of_tendsto_lintegral_nnnorm hφ I hfm h' end lemma integrable_of_tendsto_integral_of_nonneg_ae {φ : ℕ → set α} (hφ : growing_family μ φ) {f : α → ℝ} (I : ℝ) (hf : 0 ≤ᵐ[μ] f) (hfm : measurable f) (hfi : ∀ n, integrable_on f (φ n) μ) (h : tendsto (λ n, ∫ x in φ n, f x ∂μ) at_top (𝓝 I)) : integrable f μ := integrable_of_tendsto_integral_norm hφ I hfm hfi (h.congr $ λ n, integral_congr_ae $ ae_restrict_of_ae $ hf.mono $ λ x hx, (real.norm_of_nonneg hx).symm) lemma integral_eq_supr_max_sub_supr_min {φ : ℕ → set α} (hφ : growing_family μ φ) {f : α → ℝ} (hfm : measurable f) (hfi : integrable f μ) : ∫ x, f x ∂μ = (⨆ (n : ℕ), ∫⁻ x in φ n, ennreal.of_real (max (f x) 0) ∂μ).to_real - (⨆ (n : ℕ), ∫⁻ x in φ n, ennreal.of_real (- min (f x) 0) ∂μ).to_real := begin rw [integral_eq_lintegral_max_sub_lintegral_min hfi, lintegral_eq_supr hφ _, lintegral_eq_supr hφ _], { exact ennreal.measurable_of_real.comp (measurable_neg.comp $ hfm.min measurable_zero) }, { exact ennreal.measurable_of_real.comp (hfm.max measurable_zero) } end lemma integral_eq_of_tendsto_integral {φ : ℕ → set α} (hφ : growing_family μ φ) {f : α → E} (I : E) (hfm : measurable f) (hfi : integrable f μ) (h : tendsto (λ n, ∫ x in φ n, f x ∂μ) at_top (𝓝 I)) : ∫ x, f x ∂μ = I := begin refine tendsto_nhds_unique _ h, suffices : tendsto (λ (n : ℕ), ∫ (x : α), (φ n).indicator f x ∂μ) at_top (𝓝 (∫ (x : α), f x ∂μ)), { convert this, ext n, rw integral_indicator (hφ.measurable n) }, exact tendsto_integral_of_dominated_convergence (λ x, ∥f x∥) (λ n, (hfm.indicator $ hφ.measurable n).ae_measurable) hfm.ae_measurable hfi.norm (λ n, ae_of_all _ $ norm_indicator_le_norm_self f) hφ.ae_tendsto_indicator end lemma integral_eq_of_tendsto_integral_of_nonneg_ae {φ : ℕ → set α} (hφ : growing_family μ φ) {f : α → ℝ} (I : ℝ) (hf : 0 ≤ᵐ[μ] f) (hfm : measurable f) (hfi : ∀ n, integrable_on f (φ n) μ) (h : tendsto (λ n, ∫ x in φ n, f x ∂μ) at_top (𝓝 I)) : ∫ x, f x ∂μ = I := have hfi' : integrable f μ, from integrable_of_tendsto_integral_of_nonneg_ae hφ I hf hfm hfi h, integral_eq_of_tendsto_integral hφ I hfm hfi' h end integral_limits section interval_integral variables {α : Type*} {E : Type*} [topological_space α] [linear_order α] [order_closed_topology α] [measurable_space α] [no_bot_order α] [opens_measurable_space α] [measurable_space E] [normed_group E] [topological_space.second_countable_topology E] [complete_space E] [normed_space ℝ E] [borel_space E] {μ : measure α} {a b : ℕ → α} (ha₁ : ∀ ⦃x y⦄, x ≤ y → a y ≤ a x) (hb₁ : monotone b) {f : α → E} (hfm : measurable f) include ha₁ hb₁ lemma monotone_ite_le_interval : monotone (λ n, if a n ≤ b n then Ioc (a n) (b n) else ∅) := begin intros i j hij, by_cases hi : a i ≤ b i, { have hj : a j ≤ b j := (ha₁ hij).trans (hi.trans (hb₁ hij)), simp [hi, hj, Ioc_subset_Ioc (ha₁ hij) (hb₁ hij)] }, { by_cases hj : a j ≤ b j; simp[hi, hj] } end include hfm -- TODO : unduplicate proofs lemma integral_eq_of_tendsto_interval_integral (I : E) (hfi : integrable f μ) (ha₂ : tendsto a at_top at_bot) (hb₂ : tendsto b at_top at_top) (h : tendsto (λ n, ∫ x in a n .. b n, f x ∂μ) at_top (𝓝 $ I)) : ∫ x, f x ∂μ = I := begin let φ := λ n, Ioc (a n) (b n), have hφ : growing_family μ φ := growing_family_Ioc ha₁ ha₂ hb₁ hb₂, refine integral_eq_of_tendsto_integral hφ _ hfm hfi (h.congr' _), filter_upwards [ha₂.eventually (eventually_le_at_bot $ b 0)], intros n han, have : a n ≤ b n := han.trans (hb₁ $ zero_le n), exact interval_integral.integral_of_le this end lemma integrable_of_tendsto_interval_integral_norm (I : ℝ) (hfi : ∀ n, integrable_on f (Ioc (a n) (b n)) μ) (ha₂ : tendsto a at_top at_bot) (hb₂ : tendsto b at_top at_top) (h : tendsto (λ n, ∫ x in a n .. b n, ∥f x∥ ∂μ) at_top (𝓝 $ I)) : integrable f μ := begin let φ := λ n, Ioc (a n) (b n), have hφ : growing_family μ φ := growing_family_Ioc ha₁ ha₂ hb₁ hb₂, refine integrable_of_tendsto_integral_norm hφ _ hfm hfi (h.congr' _), filter_upwards [ha₂.eventually (eventually_le_at_bot $ b 0)], intros n han, have : a n ≤ b n := han.trans (hb₁ $ zero_le n), exact interval_integral.integral_of_le this end omit hb₁ lemma integral_Iic_eq_of_tendsto_interval_integral (I : E) (b : α) (hfi : integrable_on f (Iic b) μ) (ha₂ : tendsto a at_top at_bot) (h : tendsto (λ n, ∫ x in a n .. b, f x ∂μ) at_top (𝓝 $ I)) : ∫ x in Iic b, f x ∂μ = I := begin let φ := λ n, Ioi (a n), have hφ : growing_family (μ.restrict $ Iic b) φ := growing_family_Ioi ha₁ ha₂, refine integral_eq_of_tendsto_integral hφ _ hfm hfi (h.congr' _), filter_upwards [ha₂.eventually (eventually_le_at_bot $ b)], intros n han, rw [interval_integral.integral_of_le han, measure.restrict_restrict (hφ.measurable n)], refl end lemma integrable_on_Iic_of_tendsto_interval_integral_norm (I : ℝ) (b : α) (hfi : ∀ n, integrable_on f (Ioc (a n) b) μ) (ha₂ : tendsto a at_top at_bot) (h : tendsto (λ n, ∫ x in a n .. b, ∥f x∥ ∂μ) at_top (𝓝 $ I)) : integrable_on f (Iic b) μ := begin let φ := λ n, Ioi (a n), have hφ : growing_family (μ.restrict $ Iic b) φ := growing_family_Ioi ha₁ ha₂, have hfi : ∀ n, integrable_on f (φ n) (μ.restrict $ Iic b), { intro n, rw [integrable_on, measure.restrict_restrict (hφ.measurable n)], exact hfi n }, refine integrable_of_tendsto_integral_norm hφ _ hfm hfi (h.congr' _), filter_upwards [ha₂.eventually (eventually_le_at_bot $ b)], intros n han, rw [interval_integral.integral_of_le han, measure.restrict_restrict (hφ.measurable n)], refl end omit ha₁ include hb₁ lemma integral_Ioi_eq_of_tendsto_interval_integral (I : E) (a : α) (hfi : integrable_on f (Ioi a) μ) (hb₂ : tendsto b at_top at_top) (h : tendsto (λ n, ∫ x in a .. b n, f x ∂μ) at_top (𝓝 $ I)) : ∫ x in Ioi a, f x ∂μ = I := begin let φ := λ n, Iic (b n), have hφ : growing_family (μ.restrict $ Ioi a) φ := growing_family_Iic hb₁ hb₂, refine integral_eq_of_tendsto_integral hφ _ hfm hfi (h.congr' _), filter_upwards [hb₂.eventually (eventually_ge_at_top $ a)], intros n hbn, rw [interval_integral.integral_of_le hbn, measure.restrict_restrict (hφ.measurable n), inter_comm], refl end lemma integrable_on_Ioi_of_tendsto_interval_integral_norm (I : ℝ) (a : α) (hfi : ∀ n, integrable_on f (Ioc a (b n)) μ) (hb₂ : tendsto b at_top at_top) (h : tendsto (λ n, ∫ x in a .. b n, ∥f x∥ ∂μ) at_top (𝓝 $ I)) : integrable_on f (Ioi a) μ := begin let φ := λ n, Iic (b n), have hφ : growing_family (μ.restrict $ Ioi a) φ := growing_family_Iic hb₁ hb₂, have hfi : ∀ n, integrable_on f (φ n) (μ.restrict $ Ioi a), { intro n, rw [integrable_on, measure.restrict_restrict (hφ.measurable n), inter_comm], exact hfi n }, refine integrable_of_tendsto_integral_norm hφ _ hfm hfi (h.congr' _), filter_upwards [hb₂.eventually (eventually_ge_at_top $ a)], intros n hbn, rw [interval_integral.integral_of_le hbn, measure.restrict_restrict (hφ.measurable n), inter_comm], refl end --lemma interval_integral_eq_of_tendsto_interval_integral [order_topology α] -- [has_no_atoms μ] {la lb : α} (hl : la < lb) -- (hfi : interval_integrable f μ la lb) (ha₂ : tendsto a at_top (𝓝 la)) -- (hb₂ : tendsto b at_top (𝓝 lb)) -- (h : tendsto (λ n, ∫ x in a n .. b n, f x ∂μ) at_top (𝓝 $ I)) : -- ∫ x in la..lb, f x ∂μ = I := --begin -- let φ := λ n, if a n ≤ b n then Ioc (a n) (b n) else ∅, -- have hφ : growing_family (μ.restrict $ Ioc la lb) φ := -- growing_family_restrict_of_ae_imp measurable_set_Ioc -- ( -- begin -- refine Ioo_ae_eq_Ioc.mono (λ x (heq : (x ∈ Ioo la lb) = (x ∈ Ioc la lb)) hx, _), -- have hx : x ∈ Ioo la lb := heq.symm ▸ hx, -- refine (eventually_le_of_tendsto_lt hx.1 ha₂).mp _, -- refine (eventually_ge_of_tendsto_gt hx.2 hb₂).mono _, -- intros n hbx hax, -- dsimp only [φ], -- split_ifs, -- end -- ) -- (monotone_ite_le_interval ha₁ hb₁) -- _, -- rw interval_integral.integral_of_le hl.le, -- refine integral_eq_of_tendsto_integral hφ _ hfm hfi.1 (h.congr' _), -- filter_upwards [eventually_le_of_tendsto_of_tendsto_of_lt hl ha₂ hb₂], -- intros n han, -- have hφ₂ : φ n = Ioc (a n) (b n), -- { dsimp only [φ], -- split_ifs, -- refl }, -- have ha₃ := ge_of_tendsto_of_antimono ha₁ ha₂ n, -- have hb₃ := le_of_tendsto_of_monotone hb₁ hb₂ n, -- have : φ n ⊆ Ioc la lb := hφ₂.symm ▸ Ioc_subset_Ioc ha₃ hb₃, -- rw [measure.restrict_restrict, inter_eq_self_of_subset_left this, hφ₂], -- exact interval_integral.integral_of_le han, --end end interval_integral
4947b1721cf945e9fe19859fc24225bd531e365f
ce89339993655da64b6ccb555c837ce6c10f9ef4
/zeptometer/topprover/5.lean
a1ddb8829d89f8f38c730f8582e4e3b17e8bea7c
[]
no_license
zeptometer/LearnLean
ef32dc36a22119f18d843f548d0bb42f907bff5d
bb84d5dbe521127ba134d4dbf9559b294a80b9f7
refs/heads/master
1,625,710,824,322
1,601,382,570,000
1,601,382,570,000
195,228,870
2
0
null
null
null
null
UTF-8
Lean
false
false
105
lean
open nat example : ∀ n m, n * succ m = n + n * m := begin intros, rw [mul_succ, add_comm] end
3fd0120c7cc098d2673001e76adf07020e105377
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/perf/perm_ac_op_50.lean
0297513d490cf22843a4e0fea6568dba0ee4fab5
[ "Apache-2.0" ]
permissive
leanprover-community/lean
12b87f69d92e614daea8bcc9d4de9a9ace089d0e
cce7990ea86a78bdb383e38ed7f9b5ba93c60ce0
refs/heads/master
1,687,508,156,644
1,684,951,104,000
1,684,951,104,000
169,960,991
457
107
Apache-2.0
1,686,744,372,000
1,549,790,268,000
C++
UTF-8
Lean
false
false
1,457
lean
open tactic constants (A : Type.{1}) constants (op : A → A → A) (op.comm : ∀ x y, op x y = op y x) (op.assoc : ∀ x y z, op (op x y) z = op x (op y z)) (op.left_comm : ∀ x y z, op x (op y z) = op y (op x z)) attribute op.comm [simp] attribute op.assoc [simp] attribute op.left_comm [simp] set_option simplify.max_steps 1000000 constants (x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 x10 x11 x12 x13 x14 x15 x16 x17 x18 x19 x20 x21 x22 x23 x24 x25 x26 x27 x28 x29 x30 x31 x32 x33 x34 x35 x36 x37 x38 x39 x40 x41 x42 x43 x44 x45 x46 x47 x48 x49 x50 : A) example : (op x1 (op x2 (op x3 (op x4 (op x5 (op x6 (op x7 (op x8 (op x9 (op x10 (op x11 (op x12 (op x13 (op x14 (op x15 (op x16 (op x17 (op x18 (op x19 (op x20 (op x21 (op x22 (op x23 (op x24 (op x25 (op x26 (op x27 (op x28 (op x29 (op x30 (op x31 (op x32 (op x33 (op x34 (op x35 (op x36 (op x37 (op x38 (op x39 (op x40 (op x41 (op x42 (op x43 (op x44 (op x45 (op x46 (op x47 (op x48 (op x49 (op x50 x0)))))))))))))))))))))))))))))))))))))))))))))))))) = (op x50 (op x49 (op x48 (op x47 (op x46 (op x45 (op x44 (op x43 (op x42 (op x41 (op x40 (op x39 (op x38 (op x37 (op x36 (op x35 (op x34 (op x33 (op x32 (op x31 (op x30 (op x29 (op x28 (op x27 (op x26 (op x25 (op x24 (op x23 (op x22 (op x21 (op x20 (op x19 (op x18 (op x17 (op x16 (op x15 (op x14 (op x13 (op x12 (op x11 (op x10 (op x9 (op x8 (op x7 (op x6 (op x5 (op x4 (op x3 (op x2 (op x1 x0)))))))))))))))))))))))))))))))))))))))))))))))))) := by simp
b486601569d58d528baebd557e10101798268967
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/dunfold_constant.lean
cb6c3ca0e5219c511ded75a03c8967ba556c6ae9
[ "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
66
lean
def foo : list ℕ := [2] lemma bar : foo = foo := by dunfold foo
e20ba843b18bae465af6b950ee486077efc34126
592ee40978ac7604005a4e0d35bbc4b467389241
/Library/generated/mathscheme-lean/Rack.lean
6350e5f87f1fbc120485e2e54fe9b28092b91245
[]
no_license
ysharoda/Deriving-Definitions
3e149e6641fae440badd35ac110a0bd705a49ad2
dfecb27572022de3d4aa702cae8db19957523a59
refs/heads/master
1,679,127,857,700
1,615,939,007,000
1,615,939,007,000
229,785,731
4
0
null
null
null
null
UTF-8
Lean
false
false
8,616
lean
import init.data.nat.basic import init.data.fin.basic import data.vector import .Prelude open Staged open nat open fin open vector section Rack structure Rack (A : Type) : Type := (linv : (A → (A → A))) (rinv : (A → (A → A))) (leftDistributive : (∀ {x y z : A} , (linv x (linv y z)) = (linv (linv x y) (linv x z)))) (rightDistributive : (∀ {x y z : A} , (rinv (rinv y z) x) = (rinv (rinv y x) (rinv z x)))) (leftInverse : (∀ {x y : A} , (rinv (linv x y) x) = y)) (rightInverse : (∀ {x y : A} , (linv x (rinv y x)) = y)) open Rack structure Sig (AS : Type) : Type := (linvS : (AS → (AS → AS))) (rinvS : (AS → (AS → AS))) structure Product (A : Type) : Type := (linvP : ((Prod A A) → ((Prod A A) → (Prod A A)))) (rinvP : ((Prod A A) → ((Prod A A) → (Prod A A)))) (leftDistributiveP : (∀ {xP yP zP : (Prod A A)} , (linvP xP (linvP yP zP)) = (linvP (linvP xP yP) (linvP xP zP)))) (rightDistributiveP : (∀ {xP yP zP : (Prod A A)} , (rinvP (rinvP yP zP) xP) = (rinvP (rinvP yP xP) (rinvP zP xP)))) (leftInverseP : (∀ {xP yP : (Prod A A)} , (rinvP (linvP xP yP) xP) = yP)) (rightInverseP : (∀ {xP yP : (Prod A A)} , (linvP xP (rinvP yP xP)) = yP)) structure Hom {A1 : Type} {A2 : Type} (Ra1 : (Rack A1)) (Ra2 : (Rack A2)) : Type := (hom : (A1 → A2)) (pres_linv : (∀ {x1 x2 : A1} , (hom ((linv Ra1) x1 x2)) = ((linv Ra2) (hom x1) (hom x2)))) (pres_rinv : (∀ {x1 x2 : A1} , (hom ((rinv Ra1) x1 x2)) = ((rinv Ra2) (hom x1) (hom x2)))) structure RelInterp {A1 : Type} {A2 : Type} (Ra1 : (Rack A1)) (Ra2 : (Rack A2)) : Type 1 := (interp : (A1 → (A2 → Type))) (interp_linv : (∀ {x1 x2 : A1} {y1 y2 : A2} , ((interp x1 y1) → ((interp x2 y2) → (interp ((linv Ra1) x1 x2) ((linv Ra2) y1 y2)))))) (interp_rinv : (∀ {x1 x2 : A1} {y1 y2 : A2} , ((interp x1 y1) → ((interp x2 y2) → (interp ((rinv Ra1) x1 x2) ((rinv Ra2) y1 y2)))))) inductive RackTerm : Type | linvL : (RackTerm → (RackTerm → RackTerm)) | rinvL : (RackTerm → (RackTerm → RackTerm)) open RackTerm inductive ClRackTerm (A : Type) : Type | sing : (A → ClRackTerm) | linvCl : (ClRackTerm → (ClRackTerm → ClRackTerm)) | rinvCl : (ClRackTerm → (ClRackTerm → ClRackTerm)) open ClRackTerm inductive OpRackTerm (n : ℕ) : Type | v : ((fin n) → OpRackTerm) | linvOL : (OpRackTerm → (OpRackTerm → OpRackTerm)) | rinvOL : (OpRackTerm → (OpRackTerm → OpRackTerm)) open OpRackTerm inductive OpRackTerm2 (n : ℕ) (A : Type) : Type | v2 : ((fin n) → OpRackTerm2) | sing2 : (A → OpRackTerm2) | linvOL2 : (OpRackTerm2 → (OpRackTerm2 → OpRackTerm2)) | rinvOL2 : (OpRackTerm2 → (OpRackTerm2 → OpRackTerm2)) open OpRackTerm2 def simplifyCl {A : Type} : ((ClRackTerm A) → (ClRackTerm A)) | (linvCl x1 x2) := (linvCl (simplifyCl x1) (simplifyCl x2)) | (rinvCl x1 x2) := (rinvCl (simplifyCl x1) (simplifyCl x2)) | (sing x1) := (sing x1) def simplifyOpB {n : ℕ} : ((OpRackTerm n) → (OpRackTerm n)) | (linvOL x1 x2) := (linvOL (simplifyOpB x1) (simplifyOpB x2)) | (rinvOL x1 x2) := (rinvOL (simplifyOpB x1) (simplifyOpB x2)) | (v x1) := (v x1) def simplifyOp {n : ℕ} {A : Type} : ((OpRackTerm2 n A) → (OpRackTerm2 n A)) | (linvOL2 x1 x2) := (linvOL2 (simplifyOp x1) (simplifyOp x2)) | (rinvOL2 x1 x2) := (rinvOL2 (simplifyOp x1) (simplifyOp x2)) | (v2 x1) := (v2 x1) | (sing2 x1) := (sing2 x1) def evalB {A : Type} : ((Rack A) → (RackTerm → A)) | Ra (linvL x1 x2) := ((linv Ra) (evalB Ra x1) (evalB Ra x2)) | Ra (rinvL x1 x2) := ((rinv Ra) (evalB Ra x1) (evalB Ra x2)) def evalCl {A : Type} : ((Rack A) → ((ClRackTerm A) → A)) | Ra (sing x1) := x1 | Ra (linvCl x1 x2) := ((linv Ra) (evalCl Ra x1) (evalCl Ra x2)) | Ra (rinvCl x1 x2) := ((rinv Ra) (evalCl Ra x1) (evalCl Ra x2)) def evalOpB {A : Type} {n : ℕ} : ((Rack A) → ((vector A n) → ((OpRackTerm n) → A))) | Ra vars (v x1) := (nth vars x1) | Ra vars (linvOL x1 x2) := ((linv Ra) (evalOpB Ra vars x1) (evalOpB Ra vars x2)) | Ra vars (rinvOL x1 x2) := ((rinv Ra) (evalOpB Ra vars x1) (evalOpB Ra vars x2)) def evalOp {A : Type} {n : ℕ} : ((Rack A) → ((vector A n) → ((OpRackTerm2 n A) → A))) | Ra vars (v2 x1) := (nth vars x1) | Ra vars (sing2 x1) := x1 | Ra vars (linvOL2 x1 x2) := ((linv Ra) (evalOp Ra vars x1) (evalOp Ra vars x2)) | Ra vars (rinvOL2 x1 x2) := ((rinv Ra) (evalOp Ra vars x1) (evalOp Ra vars x2)) def inductionB {P : (RackTerm → Type)} : ((∀ (x1 x2 : RackTerm) , ((P x1) → ((P x2) → (P (linvL x1 x2))))) → ((∀ (x1 x2 : RackTerm) , ((P x1) → ((P x2) → (P (rinvL x1 x2))))) → (∀ (x : RackTerm) , (P x)))) | plinvl prinvl (linvL x1 x2) := (plinvl _ _ (inductionB plinvl prinvl x1) (inductionB plinvl prinvl x2)) | plinvl prinvl (rinvL x1 x2) := (prinvl _ _ (inductionB plinvl prinvl x1) (inductionB plinvl prinvl x2)) def inductionCl {A : Type} {P : ((ClRackTerm A) → Type)} : ((∀ (x1 : A) , (P (sing x1))) → ((∀ (x1 x2 : (ClRackTerm A)) , ((P x1) → ((P x2) → (P (linvCl x1 x2))))) → ((∀ (x1 x2 : (ClRackTerm A)) , ((P x1) → ((P x2) → (P (rinvCl x1 x2))))) → (∀ (x : (ClRackTerm A)) , (P x))))) | psing plinvcl prinvcl (sing x1) := (psing x1) | psing plinvcl prinvcl (linvCl x1 x2) := (plinvcl _ _ (inductionCl psing plinvcl prinvcl x1) (inductionCl psing plinvcl prinvcl x2)) | psing plinvcl prinvcl (rinvCl x1 x2) := (prinvcl _ _ (inductionCl psing plinvcl prinvcl x1) (inductionCl psing plinvcl prinvcl x2)) def inductionOpB {n : ℕ} {P : ((OpRackTerm n) → Type)} : ((∀ (fin : (fin n)) , (P (v fin))) → ((∀ (x1 x2 : (OpRackTerm n)) , ((P x1) → ((P x2) → (P (linvOL x1 x2))))) → ((∀ (x1 x2 : (OpRackTerm n)) , ((P x1) → ((P x2) → (P (rinvOL x1 x2))))) → (∀ (x : (OpRackTerm n)) , (P x))))) | pv plinvol prinvol (v x1) := (pv x1) | pv plinvol prinvol (linvOL x1 x2) := (plinvol _ _ (inductionOpB pv plinvol prinvol x1) (inductionOpB pv plinvol prinvol x2)) | pv plinvol prinvol (rinvOL x1 x2) := (prinvol _ _ (inductionOpB pv plinvol prinvol x1) (inductionOpB pv plinvol prinvol x2)) def inductionOp {n : ℕ} {A : Type} {P : ((OpRackTerm2 n A) → Type)} : ((∀ (fin : (fin n)) , (P (v2 fin))) → ((∀ (x1 : A) , (P (sing2 x1))) → ((∀ (x1 x2 : (OpRackTerm2 n A)) , ((P x1) → ((P x2) → (P (linvOL2 x1 x2))))) → ((∀ (x1 x2 : (OpRackTerm2 n A)) , ((P x1) → ((P x2) → (P (rinvOL2 x1 x2))))) → (∀ (x : (OpRackTerm2 n A)) , (P x)))))) | pv2 psing2 plinvol2 prinvol2 (v2 x1) := (pv2 x1) | pv2 psing2 plinvol2 prinvol2 (sing2 x1) := (psing2 x1) | pv2 psing2 plinvol2 prinvol2 (linvOL2 x1 x2) := (plinvol2 _ _ (inductionOp pv2 psing2 plinvol2 prinvol2 x1) (inductionOp pv2 psing2 plinvol2 prinvol2 x2)) | pv2 psing2 plinvol2 prinvol2 (rinvOL2 x1 x2) := (prinvol2 _ _ (inductionOp pv2 psing2 plinvol2 prinvol2 x1) (inductionOp pv2 psing2 plinvol2 prinvol2 x2)) def stageB : (RackTerm → (Staged RackTerm)) | (linvL x1 x2) := (stage2 linvL (codeLift2 linvL) (stageB x1) (stageB x2)) | (rinvL x1 x2) := (stage2 rinvL (codeLift2 rinvL) (stageB x1) (stageB x2)) def stageCl {A : Type} : ((ClRackTerm A) → (Staged (ClRackTerm A))) | (sing x1) := (Now (sing x1)) | (linvCl x1 x2) := (stage2 linvCl (codeLift2 linvCl) (stageCl x1) (stageCl x2)) | (rinvCl x1 x2) := (stage2 rinvCl (codeLift2 rinvCl) (stageCl x1) (stageCl x2)) def stageOpB {n : ℕ} : ((OpRackTerm n) → (Staged (OpRackTerm n))) | (v x1) := (const (code (v x1))) | (linvOL x1 x2) := (stage2 linvOL (codeLift2 linvOL) (stageOpB x1) (stageOpB x2)) | (rinvOL x1 x2) := (stage2 rinvOL (codeLift2 rinvOL) (stageOpB x1) (stageOpB x2)) def stageOp {n : ℕ} {A : Type} : ((OpRackTerm2 n A) → (Staged (OpRackTerm2 n A))) | (sing2 x1) := (Now (sing2 x1)) | (v2 x1) := (const (code (v2 x1))) | (linvOL2 x1 x2) := (stage2 linvOL2 (codeLift2 linvOL2) (stageOp x1) (stageOp x2)) | (rinvOL2 x1 x2) := (stage2 rinvOL2 (codeLift2 rinvOL2) (stageOp x1) (stageOp x2)) structure StagedRepr (A : Type) (Repr : (Type → Type)) : Type := (linvT : ((Repr A) → ((Repr A) → (Repr A)))) (rinvT : ((Repr A) → ((Repr A) → (Repr A)))) end Rack
bf3f60773b6a99e883e7dc733a2663b80dcbb44d
dd0f5513e11c52db157d2fcc8456d9401a6cd9da
/03_Propositions_and_Proofs.org.8.lean
47400f8058d6819b05c1ef340b9649a8124c1e6a
[]
no_license
cjmazey/lean-tutorial
ba559a49f82aa6c5848b9bf17b7389bf7f4ba645
381f61c9fcac56d01d959ae0fa6e376f2c4e3b34
refs/heads/master
1,610,286,098,832
1,447,124,923,000
1,447,124,923,000
43,082,433
0
0
null
null
null
null
UTF-8
Lean
false
false
145
lean
/- page 36 -/ import standard constants p q : Prop -- BEGIN theorem t1 : p → q → p := assume Hp : p, assume Hq : q, show p, from Hp -- END
35232d56a1fdbc52f0d3e0a12459b95aa488914e
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/data/real/ereal.lean
601af72b47aed0b82354ea89aeaad0e951c3430c
[]
no_license
AurelienSaue/Mathlib4_auto
f538cfd0980f65a6361eadea39e6fc639e9dae14
590df64109b08190abe22358fabc3eae000943f2
refs/heads/master
1,683,906,849,776
1,622,564,669,000
1,622,564,669,000
371,723,747
0
0
null
null
null
null
UTF-8
Lean
false
false
3,478
lean
/- Copyright (c) 2019 Kevin Buzzard. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kevin Buzzard -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.data.real.basic import Mathlib.PostPort namespace Mathlib /-! # The extended reals [-∞, ∞]. This file defines `ereal`, the real numbers together with a top and bottom element, referred to as ⊤ and ⊥. It is implemented as `with_top (with_bot ℝ)` Addition and multiplication are problematic in the presence of ±∞, but negation has a natural definition and satisfies the usual properties. An addition is derived, but `ereal` is not even a monoid (there is no identity). `ereal` is a `complete_lattice`; this is now deduced by type class inference from the fact that `with_top (with_bot L)` is a complete lattice if `L` is a conditionally complete lattice. ## Tags real, ereal, complete lattice ## TODO abs : ereal → ennreal In Isabelle they define + - * and / (making junk choices for things like -∞ + ∞) and then prove whatever bits of the ordered ring/field axioms still hold. They also do some limits stuff (liminf/limsup etc). See https://isabelle.in.tum.de/dist/library/HOL/HOL-Library/Extended_Real.html -/ /-- ereal : The type `[-∞, ∞]` -/ def ereal := with_top (with_bot ℝ) namespace ereal protected instance has_coe : has_coe ℝ ereal := has_coe.mk (some ∘ some) @[simp] protected theorem coe_real_le {x : ℝ} {y : ℝ} : ↑x ≤ ↑y ↔ x ≤ y := sorry @[simp] protected theorem coe_real_lt {x : ℝ} {y : ℝ} : ↑x < ↑y ↔ x < y := sorry @[simp] protected theorem coe_real_inj' {x : ℝ} {y : ℝ} : ↑x = ↑y ↔ x = y := sorry protected instance has_zero : HasZero ereal := { zero := ↑0 } protected instance inhabited : Inhabited ereal := { default := 0 } /-! ### Negation -/ /-- negation on ereal -/ protected def neg : ereal → ereal := sorry protected instance has_neg : Neg ereal := { neg := ereal.neg } protected theorem neg_def (x : ℝ) : ↑(-x) = -↑x := rfl /-- - -a = a on ereal -/ protected theorem neg_neg (a : ereal) : --a = a := sorry theorem neg_inj (a : ereal) (b : ereal) (h : -a = -b) : a = b := eq.mpr (id (Eq._oldrec (Eq.refl (a = b)) (Eq.symm (ereal.neg_neg a)))) (eq.mpr (id (Eq._oldrec (Eq.refl ( --a = b)) h)) (eq.mpr (id (Eq._oldrec (Eq.refl ( --b = b)) (ereal.neg_neg b))) (Eq.refl b))) /-- Even though ereal is not an additive group, -a = b ↔ -b = a still holds -/ theorem neg_eq_iff_neg_eq {a : ereal} {b : ereal} : -a = b ↔ -b = a := { mp := fun (h : -a = b) => eq.mpr (id (Eq._oldrec (Eq.refl (-b = a)) (Eq.symm h))) (ereal.neg_neg a), mpr := fun (h : -b = a) => eq.mpr (id (Eq._oldrec (Eq.refl (-a = b)) (Eq.symm h))) (ereal.neg_neg b) } /-- if -a ≤ b then -b ≤ a on ereal -/ protected theorem neg_le_of_neg_le {a : ereal} {b : ereal} (h : -a ≤ b) : -b ≤ a := sorry /-- -a ≤ b ↔ -b ≤ a on ereal-/ protected theorem neg_le {a : ereal} {b : ereal} : -a ≤ b ↔ -b ≤ a := { mp := ereal.neg_le_of_neg_le, mpr := ereal.neg_le_of_neg_le } /-- a ≤ -b → b ≤ -a on ereal -/ theorem le_neg_of_le_neg {a : ereal} {b : ereal} (h : a ≤ -b) : b ≤ -a := eq.mpr (id (Eq._oldrec (Eq.refl (b ≤ -a)) (Eq.symm (ereal.neg_neg b)))) (eq.mpr (id (Eq._oldrec (Eq.refl ( --b ≤ -a)) (propext ereal.neg_le))) (eq.mpr (id (Eq._oldrec (Eq.refl ( --a ≤ -b)) (ereal.neg_neg a))) h))
9261406147f2029f979bc14461da6cba2798efb2
d29d82a0af640c937e499f6be79fc552eae0aa13
/src/data/dfinsupp.lean
3ef16fbbd197474bbc72fc16ba0bf10cc009ad22
[ "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
54,350
lean
/- Copyright (c) 2018 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Kenny Lau -/ import algebra.module.pi import algebra.big_operators.basic import data.set.finite import group_theory.submonoid.membership /-! # Dependent functions with finite support For a non-dependent version see `data/finsupp.lean`. -/ universes u u₁ u₂ v v₁ v₂ v₃ w x y l open_locale big_operators variables (ι : Type u) (β : ι → Type v) {β₁ : ι → Type v₁} {β₂ : ι → Type v₂} namespace dfinsupp variable [Π i, has_zero (β i)] structure pre : Type (max u v) := (to_fun : Π i, β i) (pre_support : multiset ι) (zero : ∀ i, i ∈ pre_support ∨ to_fun i = 0) instance inhabited_pre : inhabited (pre ι β) := ⟨⟨λ i, 0, ∅, λ i, or.inr rfl⟩⟩ instance : setoid (pre ι β) := { r := λ x y, ∀ i, x.to_fun i = y.to_fun i, iseqv := ⟨λ f i, rfl, λ f g H i, (H i).symm, λ f g h H1 H2 i, (H1 i).trans (H2 i)⟩ } end dfinsupp variable {ι} /-- A dependent function `Π i, β i` with finite support. -/ @[reducible] def dfinsupp [Π i, has_zero (β i)] : Type* := quotient (dfinsupp.pre.setoid ι β) variable {β} notation `Π₀` binders `, ` r:(scoped f, dfinsupp f) := r infix ` →ₚ `:25 := dfinsupp namespace dfinsupp section basic variables [Π i, has_zero (β i)] [Π i, has_zero (β₁ i)] [Π i, has_zero (β₂ i)] instance : has_coe_to_fun (Π₀ i, β i) := ⟨λ _, Π i, β i, λ f, quotient.lift_on f pre.to_fun $ λ _ _, funext⟩ instance : has_zero (Π₀ i, β i) := ⟨⟦⟨0, ∅, λ i, or.inr rfl⟩⟧⟩ instance : inhabited (Π₀ i, β i) := ⟨0⟩ @[simp] lemma coe_pre_mk (f : Π i, β i) (s : multiset ι) (hf) : ⇑(⟦⟨f, s, hf⟩⟧ : Π₀ i, β i) = f := rfl @[simp] lemma coe_zero : ⇑(0 : Π₀ i, β i) = 0 := rfl lemma zero_apply (i : ι) : (0 : Π₀ i, β i) i = 0 := rfl lemma coe_fn_injective : @function.injective (Π₀ i, β i) (Π i, β i) coe_fn := λ f g H, quotient.induction_on₂ f g (λ _ _ H, quotient.sound H) (congr_fun H) @[ext] lemma ext {f g : Π₀ i, β i} (H : ∀ i, f i = g i) : f = g := coe_fn_injective (funext H) lemma ext_iff {f g : Π₀ i, β i} : f = g ↔ ∀ i, f i = g i := coe_fn_injective.eq_iff.symm.trans function.funext_iff /-- The composition of `f : β₁ → β₂` and `g : Π₀ i, β₁ i` is `map_range f hf g : Π₀ i, β₂ i`, well defined when `f 0 = 0`. This preserves the structure on `f`, and exists in various bundled forms for when `f` is itself bundled: * `dfinsupp.map_range.add_monoid_hom` * `dfinsupp.map_range.add_equiv` * `dfinsupp.map_range.linear_map` * `dfinsupp.map_range.linear_equiv` -/ def map_range (f : Π i, β₁ i → β₂ i) (hf : ∀ i, f i 0 = 0) (g : Π₀ i, β₁ i) : Π₀ i, β₂ i := quotient.lift_on g (λ x, ⟦(⟨λ i, f i (x.1 i), x.2, λ i, or.cases_on (x.3 i) or.inl $ λ H, or.inr $ by rw [H, hf]⟩ : pre ι β₂)⟧) $ λ x y H, quotient.sound $ λ i, by simp only [H i] @[simp] lemma map_range_apply (f : Π i, β₁ i → β₂ i) (hf : ∀ i, f i 0 = 0) (g : Π₀ i, β₁ i) (i : ι) : map_range f hf g i = f i (g i) := quotient.induction_on g $ λ x, rfl @[simp] lemma map_range_id (h : ∀ i, id (0 : β₁ i) = 0 := λ i, rfl) (g : Π₀ (i : ι), β₁ i) : map_range (λ i, (id : β₁ i → β₁ i)) h g = g := by { ext, simp only [map_range_apply, id.def] } lemma map_range_comp (f : Π i, β₁ i → β₂ i) (f₂ : Π i, β i → β₁ i) (hf : ∀ i, f i 0 = 0) (hf₂ : ∀ i, f₂ i 0 = 0) (h : ∀ i, (f i ∘ f₂ i) 0 = 0) (g : Π₀ (i : ι), β i) : map_range (λ i, f i ∘ f₂ i) h g = map_range f hf (map_range f₂ hf₂ g) := by { ext, simp only [map_range_apply] } @[simp] lemma map_range_zero (f : Π i, β₁ i → β₂ i) (hf : ∀ i, f i 0 = 0) : map_range f hf (0 : Π₀ i, β₁ i) = 0 := by { ext, simp only [map_range_apply, coe_zero, pi.zero_apply, hf] } /-- Let `f i` be a binary operation `β₁ i → β₂ i → β i` such that `f i 0 0 = 0`. Then `zip_with f hf` is a binary operation `Π₀ i, β₁ i → Π₀ i, β₂ i → Π₀ i, β i`. -/ def zip_with (f : Π i, β₁ i → β₂ i → β i) (hf : ∀ i, f i 0 0 = 0) (g₁ : Π₀ i, β₁ i) (g₂ : Π₀ i, β₂ i) : (Π₀ i, β i) := begin refine quotient.lift_on₂ g₁ g₂ (λ x y, ⟦(⟨λ i, f i (x.1 i) (y.1 i), x.2 + y.2, λ i, _⟩ : pre ι β)⟧) _, { cases x.3 i with h1 h1, { left, rw multiset.mem_add, left, exact h1 }, cases y.3 i with h2 h2, { left, rw multiset.mem_add, right, exact h2 }, right, rw [h1, h2, hf] }, exact λ x₁ x₂ y₁ y₂ H1 H2, quotient.sound $ λ i, by simp only [H1 i, H2 i] end @[simp] lemma zip_with_apply (f : Π i, β₁ i → β₂ i → β i) (hf : ∀ i, f i 0 0 = 0) (g₁ : Π₀ i, β₁ i) (g₂ : Π₀ i, β₂ i) (i : ι) : zip_with f hf g₁ g₂ i = f i (g₁ i) (g₂ i) := quotient.induction_on₂ g₁ g₂ $ λ _ _, rfl end basic section algebra instance [Π i, add_zero_class (β i)] : has_add (Π₀ i, β i) := ⟨zip_with (λ _, (+)) (λ _, add_zero 0)⟩ lemma add_apply [Π i, add_zero_class (β i)] (g₁ g₂ : Π₀ i, β i) (i : ι) : (g₁ + g₂) i = g₁ i + g₂ i := zip_with_apply _ _ g₁ g₂ i @[simp] lemma coe_add [Π i, add_zero_class (β i)] (g₁ g₂ : Π₀ i, β i) : ⇑(g₁ + g₂) = g₁ + g₂ := funext $ add_apply g₁ g₂ instance [Π i, add_zero_class (β i)] : add_zero_class (Π₀ i, β i) := { zero := 0, add := (+), zero_add := λ f, ext $ λ i, by simp only [add_apply, zero_apply, zero_add], add_zero := λ f, ext $ λ i, by simp only [add_apply, zero_apply, add_zero] } instance [Π i, add_monoid (β i)] : add_monoid (Π₀ i, β i) := { add_monoid . zero := 0, add := (+), add_assoc := λ f g h, ext $ λ i, by simp only [add_apply, add_assoc], .. dfinsupp.add_zero_class } /-- Coercion from a `dfinsupp` to a pi type is an `add_monoid_hom`. -/ def coe_fn_add_monoid_hom [Π i, add_zero_class (β i)] : (Π₀ i, β i) →+ (Π i, β i) := { to_fun := coe_fn, map_zero' := coe_zero, map_add' := coe_add } /-- Evaluation at a point is an `add_monoid_hom`. This is the finitely-supported version of `pi.eval_add_monoid_hom`. -/ def eval_add_monoid_hom [Π i, add_zero_class (β i)] (i : ι) : (Π₀ i, β i) →+ β i := (pi.eval_add_monoid_hom β i).comp coe_fn_add_monoid_hom instance is_add_monoid_hom [Π i, add_zero_class (β i)] {i : ι} : is_add_monoid_hom (λ g : Π₀ i : ι, β i, g i) := (eval_add_monoid_hom i).is_add_monoid_hom instance [Π i, add_group (β i)] : has_neg (Π₀ i, β i) := ⟨λ f, f.map_range (λ _, has_neg.neg) (λ _, neg_zero)⟩ instance [Π i, add_comm_monoid (β i)] : add_comm_monoid (Π₀ i, β i) := { add_comm := λ f g, ext $ λ i, by simp only [add_apply, add_comm], .. dfinsupp.add_monoid } @[simp] lemma coe_finset_sum {α} [Π i, add_comm_monoid (β i)] (s : finset α) (g : α → Π₀ i, β i) : ⇑(∑ a in s, g a) = ∑ a in s, g a := (coe_fn_add_monoid_hom : _ →+ (Π i, β i)).map_sum g s @[simp] lemma finset_sum_apply {α} [Π i, add_comm_monoid (β i)] (s : finset α) (g : α → Π₀ i, β i) (i : ι) : (∑ a in s, g a) i = ∑ a in s, g a i := (eval_add_monoid_hom i : _ →+ β i).map_sum g s lemma neg_apply [Π i, add_group (β i)] (g : Π₀ i, β i) (i : ι) : (- g) i = - g i := map_range_apply _ _ g i @[simp] lemma coe_neg [Π i, add_group (β i)] (g : Π₀ i, β i) : ⇑(- g) = - g := funext $ neg_apply g instance [Π i, add_group (β i)] : add_group (Π₀ i, β i) := { add_left_neg := λ f, ext $ λ i, by simp only [add_apply, neg_apply, zero_apply, add_left_neg], .. dfinsupp.add_monoid, .. (infer_instance : has_neg (Π₀ i, β i)) } lemma sub_apply [Π i, add_group (β i)] (g₁ g₂ : Π₀ i, β i) (i : ι) : (g₁ - g₂) i = g₁ i - g₂ i := by rw [sub_eq_add_neg]; simp [sub_eq_add_neg] @[simp] lemma coe_sub [Π i, add_group (β i)] (g₁ g₂ : Π₀ i, β i) : ⇑(g₁ - g₂) = g₁ - g₂ := funext $ sub_apply g₁ g₂ instance [Π i, add_comm_group (β i)] : add_comm_group (Π₀ i, β i) := { add_comm := λ f g, ext $ λ i, by simp only [add_apply, add_comm], ..dfinsupp.add_group } /-- Dependent functions with finite support inherit a semiring action from an action on each coordinate. -/ instance {γ : Type w} [monoid γ] [Π i, add_monoid (β i)] [Π i, distrib_mul_action γ (β i)] : has_scalar γ (Π₀ i, β i) := ⟨λc v, v.map_range (λ _, (•) c) (λ _, smul_zero _)⟩ lemma smul_apply {γ : Type w} [monoid γ] [Π i, add_monoid (β i)] [Π i, distrib_mul_action γ (β i)] (b : γ) (v : Π₀ i, β i) (i : ι) : (b • v) i = b • (v i) := map_range_apply _ _ v i @[simp] lemma coe_smul {γ : Type w} [monoid γ] [Π i, add_monoid (β i)] [Π i, distrib_mul_action γ (β i)] (b : γ) (v : Π₀ i, β i) : ⇑(b • v) = b • v := funext $ smul_apply b v instance {γ : Type w} {δ : Type*} [monoid γ] [monoid δ] [Π i, add_monoid (β i)] [Π i, distrib_mul_action γ (β i)] [Π i, distrib_mul_action δ (β i)] [Π i, smul_comm_class γ δ (β i)] : smul_comm_class γ δ (Π₀ i, β i) := { smul_comm := λ r s m, ext $ λ i, by simp only [smul_apply, smul_comm r s (m i)] } instance {γ : Type w} {δ : Type*} [monoid γ] [monoid δ] [Π i, add_monoid (β i)] [Π i, distrib_mul_action γ (β i)] [Π i, distrib_mul_action δ (β i)] [has_scalar γ δ] [Π i, is_scalar_tower γ δ (β i)] : is_scalar_tower γ δ (Π₀ i, β i) := { smul_assoc := λ r s m, ext $ λ i, by simp only [smul_apply, smul_assoc r s (m i)] } /-- Dependent functions with finite support inherit a `distrib_mul_action` structure from such a structure on each coordinate. -/ instance {γ : Type w} [monoid γ] [Π i, add_monoid (β i)] [Π i, distrib_mul_action γ (β i)] : distrib_mul_action γ (Π₀ i, β i) := { smul_zero := λ c, ext $ λ i, by simp only [smul_apply, smul_zero, zero_apply], smul_add := λ c x y, ext $ λ i, by simp only [add_apply, smul_apply, smul_add], one_smul := λ x, ext $ λ i, by simp only [smul_apply, one_smul], mul_smul := λ r s x, ext $ λ i, by simp only [smul_apply, smul_smul], ..dfinsupp.has_scalar } /-- Dependent functions with finite support inherit a module structure from such a structure on each coordinate. -/ instance {γ : Type w} [semiring γ] [Π i, add_comm_monoid (β i)] [Π i, module γ (β i)] : module γ (Π₀ i, β i) := { zero_smul := λ c, ext $ λ i, by simp only [smul_apply, zero_smul, zero_apply], add_smul := λ c x y, ext $ λ i, by simp only [add_apply, smul_apply, add_smul], ..dfinsupp.distrib_mul_action } end algebra section filter_and_subtype_domain /-- `filter p f` is the function which is `f i` if `p i` is true and 0 otherwise. -/ def filter [Π i, has_zero (β i)] (p : ι → Prop) [decidable_pred p] (f : Π₀ i, β i) : Π₀ i, β i := quotient.lift_on f (λ x, ⟦(⟨λ i, if p i then x.1 i else 0, x.2, λ i, or.cases_on (x.3 i) or.inl $ λ H, or.inr $ by rw [H, if_t_t]⟩ : pre ι β)⟧) $ λ x y H, quotient.sound $ λ i, by simp only [H i] @[simp] lemma filter_apply [Π i, has_zero (β i)] (p : ι → Prop) [decidable_pred p] (i : ι) (f : Π₀ i, β i) : f.filter p i = if p i then f i else 0 := quotient.induction_on f $ λ x, rfl lemma filter_apply_pos [Π i, has_zero (β i)] {p : ι → Prop} [decidable_pred p] (f : Π₀ i, β i) {i : ι} (h : p i) : f.filter p i = f i := by simp only [filter_apply, if_pos h] lemma filter_apply_neg [Π i, has_zero (β i)] {p : ι → Prop} [decidable_pred p] (f : Π₀ i, β i) {i : ι} (h : ¬ p i) : f.filter p i = 0 := by simp only [filter_apply, if_neg h] lemma filter_pos_add_filter_neg [Π i, add_zero_class (β i)] (f : Π₀ i, β i) (p : ι → Prop) [decidable_pred p] : f.filter p + f.filter (λi, ¬ p i) = f := ext $ λ i, by simp only [add_apply, filter_apply]; split_ifs; simp only [add_zero, zero_add] /-- `subtype_domain p f` is the restriction of the finitely supported function `f` to the subtype `p`. -/ def subtype_domain [Π i, has_zero (β i)] (p : ι → Prop) [decidable_pred p] (f : Π₀ i, β i) : Π₀ i : subtype p, β i := begin fapply quotient.lift_on f, { intro x, refine ⟦⟨λ i, x.1 (i : ι), (x.2.filter p).attach.map $ λ j, ⟨j, (multiset.mem_filter.1 j.2).2⟩, _⟩⟧, refine λ i, or.cases_on (x.3 i) (λ H, _) or.inr, left, rw multiset.mem_map, refine ⟨⟨i, multiset.mem_filter.2 ⟨H, i.2⟩⟩, _, subtype.eta _ _⟩, apply multiset.mem_attach }, intros x y H, exact quotient.sound (λ i, H i) end @[simp] lemma subtype_domain_zero [Π i, has_zero (β i)] {p : ι → Prop} [decidable_pred p] : subtype_domain p (0 : Π₀ i, β i) = 0 := rfl @[simp] lemma subtype_domain_apply [Π i, has_zero (β i)] {p : ι → Prop} [decidable_pred p] {i : subtype p} {v : Π₀ i, β i} : (subtype_domain p v) i = v i := quotient.induction_on v $ λ x, rfl @[simp] lemma subtype_domain_add [Π i, add_zero_class (β i)] {p : ι → Prop} [decidable_pred p] {v v' : Π₀ i, β i} : (v + v').subtype_domain p = v.subtype_domain p + v'.subtype_domain p := ext $ λ i, by simp only [add_apply, subtype_domain_apply] instance subtype_domain.is_add_monoid_hom [Π i, add_zero_class (β i)] {p : ι → Prop} [decidable_pred p] : is_add_monoid_hom (subtype_domain p : (Π₀ i : ι, β i) → Π₀ i : subtype p, β i) := { map_add := λ _ _, subtype_domain_add, map_zero := subtype_domain_zero } @[simp] lemma subtype_domain_neg [Π i, add_group (β i)] {p : ι → Prop} [decidable_pred p] {v : Π₀ i, β i} : (- v).subtype_domain p = - v.subtype_domain p := ext $ λ i, by simp only [neg_apply, subtype_domain_apply] @[simp] lemma subtype_domain_sub [Π i, add_group (β i)] {p : ι → Prop} [decidable_pred p] {v v' : Π₀ i, β i} : (v - v').subtype_domain p = v.subtype_domain p - v'.subtype_domain p := ext $ λ i, by simp only [sub_apply, subtype_domain_apply] end filter_and_subtype_domain variable [dec : decidable_eq ι] include dec section basic variable [Π i, has_zero (β i)] omit dec lemma finite_support (f : Π₀ i, β i) : set.finite {i | f i ≠ 0} := begin classical, exact quotient.induction_on f (λ x, x.2.to_finset.finite_to_set.subset (λ i H, multiset.mem_to_finset.2 ((x.3 i).resolve_right H))) end include dec /-- Create an element of `Π₀ i, β i` from a finset `s` and a function `x` defined on this `finset`. -/ def mk (s : finset ι) (x : Π i : (↑s : set ι), β (i : ι)) : Π₀ i, β i := ⟦⟨λ i, if H : i ∈ s then x ⟨i, H⟩ else 0, s.1, λ i, if H : i ∈ s then or.inl H else or.inr $ dif_neg H⟩⟧ @[simp] lemma mk_apply {s : finset ι} {x : Π i : (↑s : set ι), β i} {i : ι} : (mk s x : Π i, β i) i = if H : i ∈ s then x ⟨i, H⟩ else 0 := rfl theorem mk_injective (s : finset ι) : function.injective (@mk ι β _ _ s) := begin intros x y H, ext i, have h1 : (mk s x : Π i, β i) i = (mk s y : Π i, β i) i, {rw H}, cases i with i hi, change i ∈ s at hi, dsimp only [mk_apply, subtype.coe_mk] at h1, simpa only [dif_pos hi] using h1 end /-- The function `single i b : Π₀ i, β i` sends `i` to `b` and all other points to `0`. -/ def single (i : ι) (b : β i) : Π₀ i, β i := mk {i} $ λ j, eq.rec_on (finset.mem_singleton.1 j.prop).symm b @[simp] lemma single_apply {i i' b} : (single i b : Π₀ i, β i) i' = (if h : i = i' then eq.rec_on h b else 0) := begin dsimp only [single], by_cases h : i = i', { have h1 : i' ∈ ({i} : finset ι) := finset.mem_singleton.2 h.symm, simp only [mk_apply, dif_pos h, dif_pos h1], refl }, { have h1 : i' ∉ ({i} : finset ι) := finset.not_mem_singleton.2 (ne.symm h), simp only [mk_apply, dif_neg h, dif_neg h1] } end @[simp] lemma single_zero (i) : (single i 0 : Π₀ i, β i) = 0 := quotient.sound $ λ j, if H : j ∈ ({i} : finset _) then by dsimp only; rw [dif_pos H]; cases finset.mem_singleton.1 H; refl else dif_neg H @[simp] lemma single_eq_same {i b} : (single i b : Π₀ i, β i) i = b := by simp only [single_apply, dif_pos rfl] lemma single_eq_of_ne {i i' b} (h : i ≠ i') : (single i b : Π₀ i, β i) i' = 0 := by simp only [single_apply, dif_neg h] lemma single_injective {i} : function.injective (single i : β i → Π₀ i, β i) := λ x y H, congr_fun (mk_injective _ H) ⟨i, by simp⟩ /-- Like `finsupp.single_eq_single_iff`, but with a `heq` due to dependent types -/ lemma single_eq_single_iff (i j : ι) (xi : β i) (xj : β j) : dfinsupp.single i xi = dfinsupp.single j xj ↔ i = j ∧ xi == xj ∨ xi = 0 ∧ xj = 0 := begin split, { intro h, by_cases hij : i = j, { subst hij, exact or.inl ⟨rfl, heq_of_eq (dfinsupp.single_injective h)⟩, }, { have h_coe : ⇑(dfinsupp.single i xi) = dfinsupp.single j xj := congr_arg coe_fn h, have hci := congr_fun h_coe i, have hcj := congr_fun h_coe j, rw dfinsupp.single_eq_same at hci hcj, rw dfinsupp.single_eq_of_ne (ne.symm hij) at hci, rw dfinsupp.single_eq_of_ne (hij) at hcj, exact or.inr ⟨hci, hcj.symm⟩, }, }, { rintros (⟨hi, hxi⟩ | ⟨hi, hj⟩), { subst hi, rw eq_of_heq hxi, }, { rw [hi, hj, dfinsupp.single_zero, dfinsupp.single_zero], }, }, end @[simp] lemma single_eq_zero {i : ι} {xi : β i} : single i xi = 0 ↔ xi = 0 := begin rw [←single_zero i, single_eq_single_iff], simp, end /-- Equality of sigma types is sufficient (but not necessary) to show equality of `dfinsupp`s. -/ lemma single_eq_of_sigma_eq {i j} {xi : β i} {xj : β j} (h : (⟨i, xi⟩ : sigma β) = ⟨j, xj⟩) : dfinsupp.single i xi = dfinsupp.single j xj := by { cases h, refl } /-- Redefine `f i` to be `0`. -/ def erase (i : ι) (f : Π₀ i, β i) : Π₀ i, β i := quotient.lift_on f (λ x, ⟦(⟨λ j, if j = i then 0 else x.1 j, x.2, λ j, or.cases_on (x.3 j) or.inl $ λ H, or.inr $ by simp only [H, if_t_t]⟩ : pre ι β)⟧) $ λ x y H, quotient.sound $ λ j, if h : j = i then by simp only [if_pos h] else by simp only [if_neg h, H j] @[simp] lemma erase_apply {i j : ι} {f : Π₀ i, β i} : (f.erase i) j = if j = i then 0 else f j := quotient.induction_on f $ λ x, rfl @[simp] lemma erase_same {i : ι} {f : Π₀ i, β i} : (f.erase i) i = 0 := by simp lemma erase_ne {i i' : ι} {f : Π₀ i, β i} (h : i' ≠ i) : (f.erase i) i' = f i' := by simp [h] end basic section add_monoid variable [Π i, add_zero_class (β i)] @[simp] lemma single_add (i : ι) (b₁ b₂ : β i) : single i (b₁ + b₂) = single i b₁ + single i b₂ := ext $ assume i', begin by_cases h : i = i', { subst h, simp only [add_apply, single_eq_same] }, { simp only [add_apply, single_eq_of_ne h, zero_add] } end variables (β) /-- `dfinsupp.single` as an `add_monoid_hom`. -/ @[simps] def single_add_hom (i : ι) : β i →+ Π₀ i, β i := { to_fun := single i, map_zero' := single_zero i, map_add' := single_add i } variables {β} lemma single_add_erase {i : ι} {f : Π₀ i, β i} : single i (f i) + f.erase i = f := ext $ λ i', if h : i = i' then by subst h; simp only [add_apply, single_apply, erase_apply, dif_pos rfl, if_pos, add_zero] else by simp only [add_apply, single_apply, erase_apply, dif_neg h, if_neg (ne.symm h), zero_add] lemma erase_add_single {i : ι} {f : Π₀ i, β i} : f.erase i + single i (f i) = f := ext $ λ i', if h : i = i' then by subst h; simp only [add_apply, single_apply, erase_apply, dif_pos rfl, if_pos, zero_add] else by simp only [add_apply, single_apply, erase_apply, dif_neg h, if_neg (ne.symm h), add_zero] protected theorem induction {p : (Π₀ i, β i) → Prop} (f : Π₀ i, β i) (h0 : p 0) (ha : ∀i b (f : Π₀ i, β i), f i = 0 → b ≠ 0 → p f → p (single i b + f)) : p f := begin refine quotient.induction_on f (λ x, _), cases x with f s H, revert f H, apply multiset.induction_on s, { intros f H, convert h0, ext i, exact (H i).resolve_left id }, intros i s ih f H, by_cases H1 : i ∈ s, { have H2 : ∀ j, j ∈ s ∨ f j = 0, { intro j, cases H j with H2 H2, { cases multiset.mem_cons.1 H2 with H3 H3, { left, rw H3, exact H1 }, { left, exact H3 } }, right, exact H2 }, have H3 : (⟦{to_fun := f, pre_support := i ::ₘ s, zero := H}⟧ : Π₀ i, β i) = ⟦{to_fun := f, pre_support := s, zero := H2}⟧, { exact quotient.sound (λ i, rfl) }, rw H3, apply ih }, have H2 : p (erase i ⟦{to_fun := f, pre_support := i ::ₘ s, zero := H}⟧), { dsimp only [erase, quotient.lift_on_mk], have H2 : ∀ j, j ∈ s ∨ ite (j = i) 0 (f j) = 0, { intro j, cases H j with H2 H2, { cases multiset.mem_cons.1 H2 with H3 H3, { right, exact if_pos H3 }, { left, exact H3 } }, right, split_ifs; [refl, exact H2] }, have H3 : (⟦{to_fun := λ (j : ι), ite (j = i) 0 (f j), pre_support := i ::ₘ s, zero := _}⟧ : Π₀ i, β i) = ⟦{to_fun := λ (j : ι), ite (j = i) 0 (f j), pre_support := s, zero := H2}⟧ := quotient.sound (λ i, rfl), rw H3, apply ih }, have H3 : single i _ + _ = (⟦{to_fun := f, pre_support := i ::ₘ s, zero := H}⟧ : Π₀ i, β i) := single_add_erase, rw ← H3, change p (single i (f i) + _), cases classical.em (f i = 0) with h h, { rw [h, single_zero, zero_add], exact H2 }, refine ha _ _ _ _ h H2, rw erase_same end lemma induction₂ {p : (Π₀ i, β i) → Prop} (f : Π₀ i, β i) (h0 : p 0) (ha : ∀i b (f : Π₀ i, β i), f i = 0 → b ≠ 0 → p f → p (f + single i b)) : p f := dfinsupp.induction f h0 $ λ i b f h1 h2 h3, have h4 : f + single i b = single i b + f, { ext j, by_cases H : i = j, { subst H, simp [h1] }, { simp [H] } }, eq.rec_on h4 $ ha i b f h1 h2 h3 @[simp] lemma add_closure_Union_range_single : add_submonoid.closure (⋃ i : ι, set.range (single i : β i → (Π₀ i, β i))) = ⊤ := top_unique $ λ x hx, (begin apply dfinsupp.induction x, exact add_submonoid.zero_mem _, exact λ a b f ha hb hf, add_submonoid.add_mem _ (add_submonoid.subset_closure $ set.mem_Union.2 ⟨a, set.mem_range_self _⟩) hf end) /-- If two additive homomorphisms from `Π₀ i, β i` are equal on each `single a b`, then they are equal. -/ lemma add_hom_ext {γ : Type w} [add_zero_class γ] ⦃f g : (Π₀ i, β i) →+ γ⦄ (H : ∀ (i : ι) (y : β i), f (single i y) = g (single i y)) : f = g := begin refine add_monoid_hom.eq_of_eq_on_mdense add_closure_Union_range_single (λ f hf, _), simp only [set.mem_Union, set.mem_range] at hf, rcases hf with ⟨x, y, rfl⟩, apply H end /-- If two additive homomorphisms from `Π₀ i, β i` are equal on each `single a b`, then they are equal. See note [partially-applied ext lemmas]. -/ @[ext] lemma add_hom_ext' {γ : Type w} [add_zero_class γ] ⦃f g : (Π₀ i, β i) →+ γ⦄ (H : ∀ x, f.comp (single_add_hom β x) = g.comp (single_add_hom β x)) : f = g := add_hom_ext $ λ x, add_monoid_hom.congr_fun (H x) end add_monoid @[simp] lemma mk_add [Π i, add_zero_class (β i)] {s : finset ι} {x y : Π i : (↑s : set ι), β i} : mk s (x + y) = mk s x + mk s y := ext $ λ i, by simp only [add_apply, mk_apply]; split_ifs; [refl, rw zero_add] @[simp] lemma mk_zero [Π i, has_zero (β i)] {s : finset ι} : mk s (0 : Π i : (↑s : set ι), β i.1) = 0 := ext $ λ i, by simp only [mk_apply]; split_ifs; refl @[simp] lemma mk_neg [Π i, add_group (β i)] {s : finset ι} {x : Π i : (↑s : set ι), β i.1} : mk s (-x) = -mk s x := ext $ λ i, by simp only [neg_apply, mk_apply]; split_ifs; [refl, rw neg_zero] @[simp] lemma mk_sub [Π i, add_group (β i)] {s : finset ι} {x y : Π i : (↑s : set ι), β i.1} : mk s (x - y) = mk s x - mk s y := ext $ λ i, by simp only [sub_apply, mk_apply]; split_ifs; [refl, rw sub_zero] instance [Π i, add_group (β i)] {s : finset ι} : is_add_group_hom (@mk ι β _ _ s) := { map_add := λ _ _, mk_add } section variables (γ : Type w) [semiring γ] [Π i, add_comm_monoid (β i)] [Π i, module γ (β i)] include γ @[simp] lemma mk_smul {s : finset ι} {c : γ} (x : Π i : (↑s : set ι), β i.1) : mk s (c • x) = c • mk s x := ext $ λ i, by simp only [smul_apply, mk_apply]; split_ifs; [refl, rw smul_zero] @[simp] lemma single_smul {i : ι} {c : γ} {x : β i} : single i (c • x) = c • single i x := ext $ λ i, by simp only [smul_apply, single_apply]; split_ifs; [cases h, rw smul_zero]; refl end section support_basic variables [Π i, has_zero (β i)] [Π i (x : β i), decidable (x ≠ 0)] /-- Set `{i | f x ≠ 0}` as a `finset`. -/ def support (f : Π₀ i, β i) : finset ι := quotient.lift_on f (λ x, x.2.to_finset.filter $ λ i, x.1 i ≠ 0) $ begin intros x y Hxy, ext i, split, { intro H, rcases finset.mem_filter.1 H with ⟨h1, h2⟩, rw Hxy i at h2, exact finset.mem_filter.2 ⟨multiset.mem_to_finset.2 $ (y.3 i).resolve_right h2, h2⟩ }, { intro H, rcases finset.mem_filter.1 H with ⟨h1, h2⟩, rw ← Hxy i at h2, exact finset.mem_filter.2 ⟨multiset.mem_to_finset.2 $ (x.3 i).resolve_right h2, h2⟩ }, end @[simp] theorem support_mk_subset {s : finset ι} {x : Π i : (↑s : set ι), β i.1} : (mk s x).support ⊆ s := λ i H, multiset.mem_to_finset.1 (finset.mem_filter.1 H).1 @[simp] theorem mem_support_to_fun (f : Π₀ i, β i) (i) : i ∈ f.support ↔ f i ≠ 0 := begin refine quotient.induction_on f (λ x, _), dsimp only [support, quotient.lift_on_mk], rw [finset.mem_filter, multiset.mem_to_finset], exact and_iff_right_of_imp (x.3 i).resolve_right end theorem eq_mk_support (f : Π₀ i, β i) : f = mk f.support (λ i, f i) := begin change f = mk f.support (λ i, f i.1), ext i, by_cases h : f i ≠ 0; [skip, rw [not_not] at h]; simp [h] end @[simp] lemma support_zero : (0 : Π₀ i, β i).support = ∅ := rfl lemma mem_support_iff (f : Π₀ i, β i) : ∀i:ι, i ∈ f.support ↔ f i ≠ 0 := f.mem_support_to_fun @[simp] lemma support_eq_empty {f : Π₀ i, β i} : f.support = ∅ ↔ f = 0 := ⟨λ H, ext $ by simpa [finset.ext_iff] using H, by simp {contextual:=tt}⟩ instance decidable_zero : decidable_pred (eq (0 : Π₀ i, β i)) := λ f, decidable_of_iff _ $ support_eq_empty.trans eq_comm lemma support_subset_iff {s : set ι} {f : Π₀ i, β i} : ↑f.support ⊆ s ↔ (∀i∉s, f i = 0) := by simp [set.subset_def]; exact forall_congr (assume i, not_imp_comm) lemma support_single_ne_zero {i : ι} {b : β i} (hb : b ≠ 0) : (single i b).support = {i} := begin ext j, by_cases h : i = j, { subst h, simp [hb] }, simp [ne.symm h, h] end lemma support_single_subset {i : ι} {b : β i} : (single i b).support ⊆ {i} := support_mk_subset section map_range_and_zip_with variables [Π i, has_zero (β₁ i)] [Π i, has_zero (β₂ i)] lemma map_range_def [Π i (x : β₁ i), decidable (x ≠ 0)] {f : Π i, β₁ i → β₂ i} {hf : ∀ i, f i 0 = 0} {g : Π₀ i, β₁ i} : map_range f hf g = mk g.support (λ i, f i.1 (g i.1)) := begin ext i, by_cases h : g i ≠ 0; simp at h; simp [h, hf] end @[simp] lemma map_range_single {f : Π i, β₁ i → β₂ i} {hf : ∀ i, f i 0 = 0} {i : ι} {b : β₁ i} : map_range f hf (single i b) = single i (f i b) := dfinsupp.ext $ λ i', by by_cases i = i'; [{subst i', simp}, simp [h, hf]] variables [Π i (x : β₁ i), decidable (x ≠ 0)] [Π i (x : β₂ i), decidable (x ≠ 0)] lemma support_map_range {f : Π i, β₁ i → β₂ i} {hf : ∀ i, f i 0 = 0} {g : Π₀ i, β₁ i} : (map_range f hf g).support ⊆ g.support := by simp [map_range_def] lemma zip_with_def {f : Π i, β₁ i → β₂ i → β i} {hf : ∀ i, f i 0 0 = 0} {g₁ : Π₀ i, β₁ i} {g₂ : Π₀ i, β₂ i} : zip_with f hf g₁ g₂ = mk (g₁.support ∪ g₂.support) (λ i, f i.1 (g₁ i.1) (g₂ i.1)) := begin ext i, by_cases h1 : g₁ i ≠ 0; by_cases h2 : g₂ i ≠ 0; simp only [not_not, ne.def] at h1 h2; simp [h1, h2, hf] end lemma support_zip_with {f : Π i, β₁ i → β₂ i → β i} {hf : ∀ i, f i 0 0 = 0} {g₁ : Π₀ i, β₁ i} {g₂ : Π₀ i, β₂ i} : (zip_with f hf g₁ g₂).support ⊆ g₁.support ∪ g₂.support := by simp [zip_with_def] end map_range_and_zip_with lemma erase_def (i : ι) (f : Π₀ i, β i) : f.erase i = mk (f.support.erase i) (λ j, f j.1) := by { ext j, by_cases h1 : j = i; by_cases h2 : f j ≠ 0; simp at h2; simp [h1, h2] } @[simp] lemma support_erase (i : ι) (f : Π₀ i, β i) : (f.erase i).support = f.support.erase i := by { ext j, by_cases h1 : j = i; by_cases h2 : f j ≠ 0; simp at h2; simp [h1, h2] } section filter_and_subtype_domain variables {p : ι → Prop} [decidable_pred p] lemma filter_def (f : Π₀ i, β i) : f.filter p = mk (f.support.filter p) (λ i, f i.1) := by ext i; by_cases h1 : p i; by_cases h2 : f i ≠ 0; simp at h2; simp [h1, h2] @[simp] lemma support_filter (f : Π₀ i, β i) : (f.filter p).support = f.support.filter p := by ext i; by_cases h : p i; simp [h] lemma subtype_domain_def (f : Π₀ i, β i) : f.subtype_domain p = mk (f.support.subtype p) (λ i, f i) := by ext i; by_cases h1 : p i; by_cases h2 : f i ≠ 0; try {simp at h2}; dsimp; simp [h1, h2, ← subtype.val_eq_coe] @[simp] lemma support_subtype_domain {f : Π₀ i, β i} : (subtype_domain p f).support = f.support.subtype p := by ext i; by_cases h1 : p i; by_cases h2 : f i ≠ 0; try {simp at h2}; dsimp; simp [h1, h2] end filter_and_subtype_domain end support_basic lemma support_add [Π i, add_zero_class (β i)] [Π i (x : β i), decidable (x ≠ 0)] {g₁ g₂ : Π₀ i, β i} : (g₁ + g₂).support ⊆ g₁.support ∪ g₂.support := support_zip_with @[simp] lemma support_neg [Π i, add_group (β i)] [Π i (x : β i), decidable (x ≠ 0)] {f : Π₀ i, β i} : support (-f) = support f := by ext i; simp lemma support_smul {γ : Type w} [semiring γ] [Π i, add_comm_monoid (β i)] [Π i, module γ (β i)] [Π ( i : ι) (x : β i), decidable (x ≠ 0)] (b : γ) (v : Π₀ i, β i) : (b • v).support ⊆ v.support := support_map_range instance [Π i, has_zero (β i)] [Π i, decidable_eq (β i)] : decidable_eq (Π₀ i, β i) := assume f g, decidable_of_iff (f.support = g.support ∧ (∀i∈f.support, f i = g i)) ⟨assume ⟨h₁, h₂⟩, ext $ assume i, if h : i ∈ f.support then h₂ i h else have hf : f i = 0, by rwa [f.mem_support_iff, not_not] at h, have hg : g i = 0, by rwa [h₁, g.mem_support_iff, not_not] at h, by rw [hf, hg], by intro h; subst h; simp⟩ section prod_and_sum variables {γ : Type w} -- [to_additive sum] for dfinsupp.prod doesn't work, the equation lemmas are not generated /-- `sum f g` is the sum of `g i (f i)` over the support of `f`. -/ def sum [Π i, has_zero (β i)] [Π i (x : β i), decidable (x ≠ 0)] [add_comm_monoid γ] (f : Π₀ i, β i) (g : Π i, β i → γ) : γ := ∑ i in f.support, g i (f i) /-- `prod f g` is the product of `g i (f i)` over the support of `f`. -/ @[to_additive] def prod [Π i, has_zero (β i)] [Π i (x : β i), decidable (x ≠ 0)] [comm_monoid γ] (f : Π₀ i, β i) (g : Π i, β i → γ) : γ := ∏ i in f.support, g i (f i) @[to_additive] lemma prod_map_range_index {β₁ : ι → Type v₁} {β₂ : ι → Type v₂} [Π i, has_zero (β₁ i)] [Π i, has_zero (β₂ i)] [Π i (x : β₁ i), decidable (x ≠ 0)] [Π i (x : β₂ i), decidable (x ≠ 0)] [comm_monoid γ] {f : Π i, β₁ i → β₂ i} {hf : ∀ i, f i 0 = 0} {g : Π₀ i, β₁ i} {h : Π i, β₂ i → γ} (h0 : ∀i, h i 0 = 1) : (map_range f hf g).prod h = g.prod (λi b, h i (f i b)) := begin rw [map_range_def], refine (finset.prod_subset support_mk_subset _).trans _, { intros i h1 h2, dsimp, simp [h1] at h2, dsimp at h2, simp [h1, h2, h0] }, { refine finset.prod_congr rfl _, intros i h1, simp [h1] } end @[to_additive] lemma prod_zero_index [Π i, add_comm_monoid (β i)] [Π i (x : β i), decidable (x ≠ 0)] [comm_monoid γ] {h : Π i, β i → γ} : (0 : Π₀ i, β i).prod h = 1 := rfl @[to_additive] lemma prod_single_index [Π i, has_zero (β i)] [Π i (x : β i), decidable (x ≠ 0)] [comm_monoid γ] {i : ι} {b : β i} {h : Π i, β i → γ} (h_zero : h i 0 = 1) : (single i b).prod h = h i b := begin by_cases h : b ≠ 0, { simp [dfinsupp.prod, support_single_ne_zero h] }, { rw [not_not] at h, simp [h, prod_zero_index, h_zero], refl } end @[to_additive] lemma prod_neg_index [Π i, add_group (β i)] [Π i (x : β i), decidable (x ≠ 0)] [comm_monoid γ] {g : Π₀ i, β i} {h : Π i, β i → γ} (h0 : ∀i, h i 0 = 1) : (-g).prod h = g.prod (λi b, h i (- b)) := prod_map_range_index h0 omit dec @[to_additive] lemma prod_comm {ι₁ ι₂ : Sort*} {β₁ : ι₁ → Type*} {β₂ : ι₂ → Type*} [decidable_eq ι₁] [decidable_eq ι₂] [Π i, has_zero (β₁ i)] [Π i, has_zero (β₂ i)] [Π i (x : β₁ i), decidable (x ≠ 0)] [Π i (x : β₂ i), decidable (x ≠ 0)] [comm_monoid γ] (f₁ : Π₀ i, β₁ i) (f₂ : Π₀ i, β₂ i) (h : Π i, β₁ i → Π i, β₂ i → γ) : f₁.prod (λ i₁ x₁, f₂.prod $ λ i₂ x₂, h i₁ x₁ i₂ x₂) = f₂.prod (λ i₂ x₂, f₁.prod $ λ i₁ x₁, h i₁ x₁ i₂ x₂) := finset.prod_comm @[simp] lemma sum_apply {ι₁ : Type u₁} [decidable_eq ι₁] {β₁ : ι₁ → Type v₁} [Π i₁, has_zero (β₁ i₁)] [Π i (x : β₁ i), decidable (x ≠ 0)] [Π i, add_comm_monoid (β i)] {f : Π₀ i₁, β₁ i₁} {g : Π i₁, β₁ i₁ → Π₀ i, β i} {i₂ : ι} : (f.sum g) i₂ = f.sum (λi₁ b, g i₁ b i₂) := (f.support.sum_hom (λf : Π₀ i, β i, f i₂)).symm include dec lemma support_sum {ι₁ : Type u₁} [decidable_eq ι₁] {β₁ : ι₁ → Type v₁} [Π i₁, has_zero (β₁ i₁)] [Π i (x : β₁ i), decidable (x ≠ 0)] [Π i, add_comm_monoid (β i)] [Π i (x : β i), decidable (x ≠ 0)] {f : Π₀ i₁, β₁ i₁} {g : Π i₁, β₁ i₁ → Π₀ i, β i} : (f.sum g).support ⊆ f.support.bUnion (λi, (g i (f i)).support) := have ∀i₁ : ι, f.sum (λ (i : ι₁) (b : β₁ i), (g i b) i₁) ≠ 0 → (∃ (i : ι₁), f i ≠ 0 ∧ ¬ (g i (f i)) i₁ = 0), from assume i₁ h, let ⟨i, hi, ne⟩ := finset.exists_ne_zero_of_sum_ne_zero h in ⟨i, (f.mem_support_iff i).mp hi, ne⟩, by simpa [finset.subset_iff, mem_support_iff, finset.mem_bUnion, sum_apply] using this @[simp, to_additive] lemma prod_one [Π i, add_comm_monoid (β i)] [Π i (x : β i), decidable (x ≠ 0)] [comm_monoid γ] {f : Π₀ i, β i} : f.prod (λi b, (1 : γ)) = 1 := finset.prod_const_one @[simp, to_additive] lemma prod_mul [Π i, add_comm_monoid (β i)] [Π i (x : β i), decidable (x ≠ 0)] [comm_monoid γ] {f : Π₀ i, β i} {h₁ h₂ : Π i, β i → γ} : f.prod (λi b, h₁ i b * h₂ i b) = f.prod h₁ * f.prod h₂ := finset.prod_mul_distrib @[simp, to_additive] lemma prod_inv [Π i, add_comm_monoid (β i)] [Π i (x : β i), decidable (x ≠ 0)] [comm_group γ] {f : Π₀ i, β i} {h : Π i, β i → γ} : f.prod (λi b, (h i b)⁻¹) = (f.prod h)⁻¹ := f.support.prod_hom (@has_inv.inv γ _) @[to_additive] lemma prod_add_index [Π i, add_comm_monoid (β i)] [Π i (x : β i), decidable (x ≠ 0)] [comm_monoid γ] {f g : Π₀ i, β i} {h : Π i, β i → γ} (h_zero : ∀i, h i 0 = 1) (h_add : ∀i b₁ b₂, h i (b₁ + b₂) = h i b₁ * h i b₂) : (f + g).prod h = f.prod h * g.prod h := have f_eq : ∏ i in f.support ∪ g.support, h i (f i) = f.prod h, from (finset.prod_subset (finset.subset_union_left _ _) $ by simp [mem_support_iff, h_zero] {contextual := tt}).symm, have g_eq : ∏ i in f.support ∪ g.support, h i (g i) = g.prod h, from (finset.prod_subset (finset.subset_union_right _ _) $ by simp [mem_support_iff, h_zero] {contextual := tt}).symm, calc ∏ i in (f + g).support, h i ((f + g) i) = ∏ i in f.support ∪ g.support, h i ((f + g) i) : finset.prod_subset support_add $ by simp [mem_support_iff, h_zero] {contextual := tt} ... = (∏ i in f.support ∪ g.support, h i (f i)) * (∏ i in f.support ∪ g.support, h i (g i)) : by simp [h_add, finset.prod_mul_distrib] ... = _ : by rw [f_eq, g_eq] @[to_additive] lemma _root_.submonoid.dfinsupp_prod_mem [Π i, has_zero (β i)] [Π i (x : β i), decidable (x ≠ 0)] [comm_monoid γ] (S : submonoid γ) (f : Π₀ i, β i) (g : Π i, β i → γ) (h : ∀ c, f c ≠ 0 → g c (f c) ∈ S) : f.prod g ∈ S := S.prod_mem $ λ i hi, h _ $ (f.mem_support_iff _).mp hi /-- When summing over an `add_monoid_hom`, the decidability assumption is not needed, and the result is also an `add_monoid_hom`. -/ def sum_add_hom [Π i, add_zero_class (β i)] [add_comm_monoid γ] (φ : Π i, β i →+ γ) : (Π₀ i, β i) →+ γ := { to_fun := (λ f, quotient.lift_on f (λ x, ∑ i in x.2.to_finset, φ i (x.1 i)) $ λ x y H, begin have H1 : x.2.to_finset ∩ y.2.to_finset ⊆ x.2.to_finset, from finset.inter_subset_left _ _, have H2 : x.2.to_finset ∩ y.2.to_finset ⊆ y.2.to_finset, from finset.inter_subset_right _ _, refine (finset.sum_subset H1 _).symm.trans ((finset.sum_congr rfl _).trans (finset.sum_subset H2 _)), { intros i H1 H2, rw finset.mem_inter at H2, rw H i, simp only [multiset.mem_to_finset] at H1 H2, rw [(y.3 i).resolve_left (mt (and.intro H1) H2), add_monoid_hom.map_zero] }, { intros i H1, rw H i }, { intros i H1 H2, rw finset.mem_inter at H2, rw ← H i, simp only [multiset.mem_to_finset] at H1 H2, rw [(x.3 i).resolve_left (mt (λ H3, and.intro H3 H1) H2), add_monoid_hom.map_zero] } end), map_add' := assume f g, begin refine quotient.induction_on f (λ x, _), refine quotient.induction_on g (λ y, _), change ∑ i in _, _ = (∑ i in _, _) + (∑ i in _, _), simp only, conv { to_lhs, congr, skip, funext, rw add_monoid_hom.map_add }, simp only [finset.sum_add_distrib], congr' 1, { refine (finset.sum_subset _ _).symm, { intro i, simp only [multiset.mem_to_finset, multiset.mem_add], exact or.inl }, { intros i H1 H2, simp only [multiset.mem_to_finset, multiset.mem_add] at H2, rw [(x.3 i).resolve_left H2, add_monoid_hom.map_zero] } }, { refine (finset.sum_subset _ _).symm, { intro i, simp only [multiset.mem_to_finset, multiset.mem_add], exact or.inr }, { intros i H1 H2, simp only [multiset.mem_to_finset, multiset.mem_add] at H2, rw [(y.3 i).resolve_left H2, add_monoid_hom.map_zero] } } end, map_zero' := rfl } @[simp] lemma sum_add_hom_single [Π i, add_zero_class (β i)] [add_comm_monoid γ] (φ : Π i, β i →+ γ) (i) (x : β i) : sum_add_hom φ (single i x) = φ i x := (add_zero _).trans $ congr_arg (φ i) $ show (if H : i ∈ ({i} : finset _) then x else 0) = x, from dif_pos $ finset.mem_singleton_self i @[simp] lemma sum_add_hom_comp_single [Π i, add_zero_class (β i)] [add_comm_monoid γ] (f : Π i, β i →+ γ) (i : ι) : (sum_add_hom f).comp (single_add_hom β i) = f i := add_monoid_hom.ext $ λ x, sum_add_hom_single f i x /-- While we didn't need decidable instances to define it, we do to reduce it to a sum -/ lemma sum_add_hom_apply [Π i, add_zero_class (β i)] [Π i (x : β i), decidable (x ≠ 0)] [add_comm_monoid γ] (φ : Π i, β i →+ γ) (f : Π₀ i, β i) : sum_add_hom φ f = f.sum (λ x, φ x) := begin refine quotient.induction_on f (λ x, _), change ∑ i in _, _ = (∑ i in finset.filter _ _, _), rw [finset.sum_filter, finset.sum_congr rfl], intros i _, dsimp only, split_ifs, refl, rw [(not_not.mp h), add_monoid_hom.map_zero], end lemma _root_.add_submonoid.dfinsupp_sum_add_hom_mem [Π i, add_zero_class (β i)] [add_comm_monoid γ] (S : add_submonoid γ) (f : Π₀ i, β i) (g : Π i, β i →+ γ) (h : ∀ c, f c ≠ 0 → g c (f c) ∈ S) : dfinsupp.sum_add_hom g f ∈ S := begin classical, rw dfinsupp.sum_add_hom_apply, convert S.dfinsupp_sum_mem _ _ _, exact h end /-- The supremum of a family of commutative additive submonoids is equal to the range of `finsupp.sum_add_hom`; that is, every element in the `supr` can be produced from taking a finite number of non-zero elements of `p i`, coercing them to `γ`, and summing them. -/ lemma _root_.add_submonoid.supr_eq_mrange_dfinsupp_sum_add_hom [add_comm_monoid γ] (p : ι → add_submonoid γ) : supr p = (dfinsupp.sum_add_hom (λ i, (p i).subtype)).mrange := begin apply le_antisymm, { apply supr_le _, intros i y hy, exact ⟨dfinsupp.single i ⟨y, hy⟩, dfinsupp.sum_add_hom_single _ _ _⟩, }, { rintros x ⟨v, rfl⟩, exact add_submonoid.dfinsupp_sum_add_hom_mem _ v _ (λ i _, (le_supr p i : p i ≤ _) (v i).prop) } end lemma _root_.add_submonoid.mem_supr_iff_exists_dfinsupp [add_comm_monoid γ] (p : ι → add_submonoid γ) (x : γ) : x ∈ supr p ↔ ∃ f : Π₀ i, p i, dfinsupp.sum_add_hom (λ i, (p i).subtype) f = x := set_like.ext_iff.mp (add_submonoid.supr_eq_mrange_dfinsupp_sum_add_hom p) x /-- A variant of `add_submonoid.mem_supr_iff_exists_dfinsupp` with the RHS fully unfolded. -/ lemma _root_.add_submonoid.mem_supr_iff_exists_dfinsupp' [add_comm_monoid γ] (p : ι → add_submonoid γ) [Π i (x : p i), decidable (x ≠ 0)] (x : γ) : x ∈ supr p ↔ ∃ f : Π₀ i, p i, f.sum (λ i xi, ↑xi) = x := begin rw add_submonoid.mem_supr_iff_exists_dfinsupp, simp_rw sum_add_hom_apply, congr', end omit dec lemma sum_add_hom_comm {ι₁ ι₂ : Sort*} {β₁ : ι₁ → Type*} {β₂ : ι₂ → Type*} {γ : Type*} [decidable_eq ι₁] [decidable_eq ι₂] [Π i, add_zero_class (β₁ i)] [Π i, add_zero_class (β₂ i)] [add_comm_monoid γ] (f₁ : Π₀ i, β₁ i) (f₂ : Π₀ i, β₂ i) (h : Π i j, β₁ i →+ β₂ j →+ γ) : sum_add_hom (λ i₂, sum_add_hom (λ i₁, h i₁ i₂) f₁) f₂ = sum_add_hom (λ i₁, sum_add_hom (λ i₂, (h i₁ i₂).flip) f₂) f₁ := begin refine quotient.induction_on₂ f₁ f₂ (λ x₁ x₂, _), simp only [sum_add_hom, add_monoid_hom.finset_sum_apply, quotient.lift_on_mk, add_monoid_hom.coe_mk, add_monoid_hom.flip_apply], exact finset.sum_comm, end include dec /-- The `dfinsupp` version of `finsupp.lift_add_hom`,-/ @[simps apply symm_apply] def lift_add_hom [Π i, add_zero_class (β i)] [add_comm_monoid γ] : (Π i, β i →+ γ) ≃+ ((Π₀ i, β i) →+ γ) := { to_fun := sum_add_hom, inv_fun := λ F i, F.comp (single_add_hom β i), left_inv := λ x, by { ext, simp }, right_inv := λ ψ, by { ext, simp }, map_add' := λ F G, by { ext, simp } } /-- The `dfinsupp` version of `finsupp.lift_add_hom_single_add_hom`,-/ @[simp] lemma lift_add_hom_single_add_hom [Π i, add_comm_monoid (β i)] : lift_add_hom (single_add_hom β) = add_monoid_hom.id (Π₀ i, β i) := lift_add_hom.to_equiv.apply_eq_iff_eq_symm_apply.2 rfl /-- The `dfinsupp` version of `finsupp.lift_add_hom_apply_single`,-/ lemma lift_add_hom_apply_single [Π i, add_zero_class (β i)] [add_comm_monoid γ] (f : Π i, β i →+ γ) (i : ι) (x : β i) : lift_add_hom f (single i x) = f i x := by simp /-- The `dfinsupp` version of `finsupp.lift_add_hom_comp_single`,-/ lemma lift_add_hom_comp_single [Π i, add_zero_class (β i)] [add_comm_monoid γ] (f : Π i, β i →+ γ) (i : ι) : (lift_add_hom f).comp (single_add_hom β i) = f i := by simp /-- The `dfinsupp` version of `finsupp.comp_lift_add_hom`,-/ lemma comp_lift_add_hom {δ : Type*} [Π i, add_zero_class (β i)] [add_comm_monoid γ] [add_comm_monoid δ] (g : γ →+ δ) (f : Π i, β i →+ γ) : g.comp (lift_add_hom f) = lift_add_hom (λ a, g.comp (f a)) := lift_add_hom.symm_apply_eq.1 $ funext $ λ a, by rw [lift_add_hom_symm_apply, add_monoid_hom.comp_assoc, lift_add_hom_comp_single] @[simp] lemma sum_add_hom_zero [Π i, add_zero_class (β i)] [add_comm_monoid γ] : sum_add_hom (λ i, (0 : β i →+ γ)) = 0 := (lift_add_hom : (Π i, β i →+ γ) ≃+ _).map_zero @[simp] lemma sum_add_hom_add [Π i, add_zero_class (β i)] [add_comm_monoid γ] (g : Π i, β i →+ γ) (h : Π i, β i →+ γ) : sum_add_hom (λ i, g i + h i) = sum_add_hom g + sum_add_hom h := lift_add_hom.map_add _ _ @[simp] lemma sum_add_hom_single_add_hom [Π i, add_comm_monoid (β i)] : sum_add_hom (single_add_hom β) = add_monoid_hom.id _ := lift_add_hom_single_add_hom lemma comp_sum_add_hom {δ : Type*} [Π i, add_zero_class (β i)] [add_comm_monoid γ] [add_comm_monoid δ] (g : γ →+ δ) (f : Π i, β i →+ γ) : g.comp (sum_add_hom f) = sum_add_hom (λ a, g.comp (f a)) := comp_lift_add_hom _ _ lemma sum_sub_index [Π i, add_group (β i)] [Π i (x : β i), decidable (x ≠ 0)] [add_comm_group γ] {f g : Π₀ i, β i} {h : Π i, β i → γ} (h_sub : ∀i b₁ b₂, h i (b₁ - b₂) = h i b₁ - h i b₂) : (f - g).sum h = f.sum h - g.sum h := begin have := (lift_add_hom (λ a, add_monoid_hom.of_map_sub (h a) (h_sub a))).map_sub f g, rw [lift_add_hom_apply, sum_add_hom_apply, sum_add_hom_apply, sum_add_hom_apply] at this, exact this, end @[to_additive] lemma prod_finset_sum_index {γ : Type w} {α : Type x} [Π i, add_comm_monoid (β i)] [Π i (x : β i), decidable (x ≠ 0)] [comm_monoid γ] {s : finset α} {g : α → Π₀ i, β i} {h : Π i, β i → γ} (h_zero : ∀i, h i 0 = 1) (h_add : ∀i b₁ b₂, h i (b₁ + b₂) = h i b₁ * h i b₂) : ∏ i in s, (g i).prod h = (∑ i in s, g i).prod h := begin classical, exact finset.induction_on s (by simp [prod_zero_index]) (by simp [prod_add_index, h_zero, h_add] {contextual := tt}) end @[to_additive] lemma prod_sum_index {ι₁ : Type u₁} [decidable_eq ι₁] {β₁ : ι₁ → Type v₁} [Π i₁, has_zero (β₁ i₁)] [Π i (x : β₁ i), decidable (x ≠ 0)] [Π i, add_comm_monoid (β i)] [Π i (x : β i), decidable (x ≠ 0)] [comm_monoid γ] {f : Π₀ i₁, β₁ i₁} {g : Π i₁, β₁ i₁ → Π₀ i, β i} {h : Π i, β i → γ} (h_zero : ∀i, h i 0 = 1) (h_add : ∀i b₁ b₂, h i (b₁ + b₂) = h i b₁ * h i b₂) : (f.sum g).prod h = f.prod (λi b, (g i b).prod h) := (prod_finset_sum_index h_zero h_add).symm @[simp] lemma sum_single [Π i, add_comm_monoid (β i)] [Π i (x : β i), decidable (x ≠ 0)] {f : Π₀ i, β i} : f.sum single = f := begin have := add_monoid_hom.congr_fun lift_add_hom_single_add_hom f, rw [lift_add_hom_apply, sum_add_hom_apply] at this, exact this, end @[to_additive] lemma prod_subtype_domain_index [Π i, has_zero (β i)] [Π i (x : β i), decidable (x ≠ 0)] [comm_monoid γ] {v : Π₀ i, β i} {p : ι → Prop} [decidable_pred p] {h : Π i, β i → γ} (hp : ∀ x ∈ v.support, p x) : (v.subtype_domain p).prod (λi b, h i b) = v.prod h := finset.prod_bij (λp _, p) (by simp) (by simp) (assume ⟨a₀, ha₀⟩ ⟨a₁, ha₁⟩, by simp) (λ i hi, ⟨⟨i, hp i hi⟩, by simpa using hi, rfl⟩) omit dec lemma subtype_domain_sum [Π i, add_comm_monoid (β i)] {s : finset γ} {h : γ → Π₀ i, β i} {p : ι → Prop} [decidable_pred p] : (∑ c in s, h c).subtype_domain p = ∑ c in s, (h c).subtype_domain p := eq.symm (s.sum_hom _) lemma subtype_domain_finsupp_sum {δ : γ → Type x} [decidable_eq γ] [Π c, has_zero (δ c)] [Π c (x : δ c), decidable (x ≠ 0)] [Π i, add_comm_monoid (β i)] {p : ι → Prop} [decidable_pred p] {s : Π₀ c, δ c} {h : Π c, δ c → Π₀ i, β i} : (s.sum h).subtype_domain p = s.sum (λc d, (h c d).subtype_domain p) := subtype_domain_sum end prod_and_sum /-! ### Bundled versions of `dfinsupp.map_range` The names should match the equivalent bundled `finsupp.map_range` definitions. -/ section map_range omit dec variables [Π i, add_zero_class (β i)] [Π i, add_zero_class (β₁ i)] [Π i, add_zero_class (β₂ i)] lemma map_range_add (f : Π i, β₁ i → β₂ i) (hf : ∀ i, f i 0 = 0) (hf' : ∀ i x y, f i (x + y) = f i x + f i y) (g₁ g₂ : Π₀ i, β₁ i): map_range f hf (g₁ + g₂) = map_range f hf g₁ + map_range f hf g₂ := begin ext, simp only [map_range_apply f, coe_add, pi.add_apply, hf'] end /-- `dfinsupp.map_range` as an `add_monoid_hom`. -/ @[simps apply] def map_range.add_monoid_hom (f : Π i, β₁ i →+ β₂ i) : (Π₀ i, β₁ i) →+ (Π₀ i, β₂ i) := { to_fun := map_range (λ i x, f i x) (λ i, (f i).map_zero), map_zero' := map_range_zero _ _, map_add' := map_range_add _ _ (λ i, (f i).map_add) } @[simp] lemma map_range.add_monoid_hom_id : map_range.add_monoid_hom (λ i, add_monoid_hom.id (β₂ i)) = add_monoid_hom.id _ := add_monoid_hom.ext map_range_id lemma map_range.add_monoid_hom_comp (f : Π i, β₁ i →+ β₂ i) (f₂ : Π i, β i →+ β₁ i): map_range.add_monoid_hom (λ i, (f i).comp (f₂ i)) = (map_range.add_monoid_hom f).comp (map_range.add_monoid_hom f₂) := add_monoid_hom.ext $ map_range_comp (λ i x, f i x) (λ i x, f₂ i x) _ _ _ /-- `dfinsupp.map_range.add_monoid_hom` as an `add_equiv`. -/ @[simps apply] def map_range.add_equiv (e : Π i, β₁ i ≃+ β₂ i) : (Π₀ i, β₁ i) ≃+ (Π₀ i, β₂ i) := { to_fun := map_range (λ i x, e i x) (λ i, (e i).map_zero), inv_fun := map_range (λ i x, (e i).symm x) (λ i, (e i).symm.map_zero), left_inv := λ x, by rw ←map_range_comp; { simp_rw add_equiv.symm_comp_self, simp }, right_inv := λ x, by rw ←map_range_comp; { simp_rw add_equiv.self_comp_symm, simp }, .. map_range.add_monoid_hom (λ i, (e i).to_add_monoid_hom) } @[simp] lemma map_range.add_equiv_refl : (map_range.add_equiv $ λ i, add_equiv.refl (β₁ i)) = add_equiv.refl _ := add_equiv.ext map_range_id lemma map_range.add_equiv_trans (f : Π i, β i ≃+ β₁ i) (f₂ : Π i, β₁ i ≃+ β₂ i): map_range.add_equiv (λ i, (f i).trans (f₂ i)) = (map_range.add_equiv f).trans (map_range.add_equiv f₂) := add_equiv.ext $ map_range_comp (λ i x, f₂ i x) (λ i x, f i x) _ _ _ @[simp] lemma map_range.add_equiv_symm (e : Π i, β₁ i ≃+ β₂ i) : (map_range.add_equiv e).symm = map_range.add_equiv (λ i, (e i).symm) := rfl end map_range end dfinsupp /-! ### Product and sum lemmas for bundled morphisms. In this section, we provide analogues of `add_monoid_hom.map_sum`, `add_monoid_hom.coe_sum`, and `add_monoid_hom.sum_apply` for `dfinsupp.sum` and `dfinsupp.sum_add_hom` instead of `finset.sum`. We provide these for `add_monoid_hom`, `monoid_hom`, `ring_hom`, `add_equiv`, and `mul_equiv`. Lemmas for `linear_map` and `linear_equiv` are in another file. -/ section variables [decidable_eq ι] namespace monoid_hom variables {R S : Type*} variables [Π i, has_zero (β i)] [Π i (x : β i), decidable (x ≠ 0)] @[simp, to_additive] lemma map_dfinsupp_prod [comm_monoid R] [comm_monoid S] (h : R →* S) (f : Π₀ i, β i) (g : Π i, β i → R) : h (f.prod g) = f.prod (λ a b, h (g a b)) := h.map_prod _ _ @[to_additive] lemma coe_dfinsupp_prod [monoid R] [comm_monoid S] (f : Π₀ i, β i) (g : Π i, β i → R →* S) : ⇑(f.prod g) = f.prod (λ a b, (g a b)) := coe_prod _ _ @[simp, to_additive] lemma dfinsupp_prod_apply [monoid R] [comm_monoid S] (f : Π₀ i, β i) (g : Π i, β i → R →* S) (r : R) : (f.prod g) r = f.prod (λ a b, (g a b) r) := finset_prod_apply _ _ _ end monoid_hom namespace ring_hom variables {R S : Type*} variables [Π i, has_zero (β i)] [Π i (x : β i), decidable (x ≠ 0)] @[simp] lemma map_dfinsupp_prod [comm_semiring R] [comm_semiring S] (h : R →+* S) (f : Π₀ i, β i) (g : Π i, β i → R) : h (f.prod g) = f.prod (λ a b, h (g a b)) := h.map_prod _ _ @[simp] lemma map_dfinsupp_sum [non_assoc_semiring R] [non_assoc_semiring S] (h : R →+* S) (f : Π₀ i, β i) (g : Π i, β i → R) : h (f.sum g) = f.sum (λ a b, h (g a b)) := h.map_sum _ _ end ring_hom namespace mul_equiv variables {R S : Type*} variables [Π i, has_zero (β i)] [Π i (x : β i), decidable (x ≠ 0)] @[simp, to_additive] lemma map_dfinsupp_prod [comm_monoid R] [comm_monoid S] (h : R ≃* S) (f : Π₀ i, β i) (g : Π i, β i → R) : h (f.prod g) = f.prod (λ a b, h (g a b)) := h.map_prod _ _ end mul_equiv /-! The above lemmas, repeated for `dfinsupp.sum_add_hom`. -/ namespace add_monoid_hom variables {R S : Type*} open dfinsupp @[simp] lemma map_dfinsupp_sum_add_hom [add_comm_monoid R] [add_comm_monoid S] [Π i, add_zero_class (β i)] (h : R →+ S) (f : Π₀ i, β i) (g : Π i, β i →+ R) : h (sum_add_hom g f) = sum_add_hom (λ i, h.comp (g i)) f := congr_fun (comp_lift_add_hom h g) f @[simp] lemma dfinsupp_sum_add_hom_apply [add_zero_class R] [add_comm_monoid S] [Π i, add_zero_class (β i)] (f : Π₀ i, β i) (g : Π i, β i →+ R →+ S) (r : R) : (sum_add_hom g f) r = sum_add_hom (λ i, (eval r).comp (g i)) f := map_dfinsupp_sum_add_hom (eval r) f g lemma coe_dfinsupp_sum_add_hom [add_zero_class R] [add_comm_monoid S] [Π i, add_zero_class (β i)] (f : Π₀ i, β i) (g : Π i, β i →+ R →+ S) : ⇑(sum_add_hom g f) = sum_add_hom (λ i, (coe_fn R S).comp (g i)) f := map_dfinsupp_sum_add_hom (coe_fn R S) f g end add_monoid_hom namespace ring_hom variables {R S : Type*} open dfinsupp @[simp] lemma map_dfinsupp_sum_add_hom [non_assoc_semiring R] [non_assoc_semiring S] [Π i, add_zero_class (β i)] (h : R →+* S) (f : Π₀ i, β i) (g : Π i, β i →+ R) : h (sum_add_hom g f) = sum_add_hom (λ i, h.to_add_monoid_hom.comp (g i)) f := add_monoid_hom.congr_fun (comp_lift_add_hom h.to_add_monoid_hom g) f end ring_hom namespace add_equiv variables {R S : Type*} open dfinsupp @[simp] lemma map_dfinsupp_sum_add_hom [add_comm_monoid R] [add_comm_monoid S] [Π i, add_zero_class (β i)] (h : R ≃+ S) (f : Π₀ i, β i) (g : Π i, β i →+ R) : h (sum_add_hom g f) = sum_add_hom (λ i, h.to_add_monoid_hom.comp (g i)) f := add_monoid_hom.congr_fun (comp_lift_add_hom h.to_add_monoid_hom g) f end add_equiv end
c85cc93b42e19205673efd6337f4a1b49da2e8b6
0d5245bb84af879a64c762b60787e72ed1ccad4f
/makefile.lean
653830505b063cd10dbff995db47524ffd3f574c
[]
no_license
Selfnet/self-control-powerswitch
fb6194e5825da7d79962ad135246d2a379ecfba3
d3ea964593cfd52fd989e12192ec18066b8d5376
refs/heads/master
1,588,876,855,313
1,377,978,429,000
1,377,978,429,000
10,155,759
1
0
null
null
null
null
UTF-8
Lean
false
false
1,126
lean
TCPREFIX = ../gnu-gcc-arm/arm-toolchain/bin/arm-none-eabi- CC = $(TCPREFIX)gcc LD = $(TCPREFIX)ld -v CP = $(TCPREFIX)objcopy OD = $(TCPREFIX)objdump GDBTUI = $(TCPREFIX)gdbtui STM32FLASH = ./stm32_flash.py FLASHLOC = 0x08000000 LINKERSCRIPT = startup_src/stm32.ld # -mfix-cortex-m3-ldrd should be enabled by default for Cortex M3. CFLAGS = -I. -c -fno-common -O0 -g -mcpu=cortex-m3 -mthumb LFLAGS = -T$(LINKERSCRIPT) -nostartfiles CPFLAGS = -Obinary ODFLAGS = -S all: run clean: -rm -f src/main.lst src/*.o src/main.elf src/main.lst src/main.bin run: src/main.bin $(STM32FLASH) src/main.bin $(FLASHLOC) src/main.bin: src/main.elf @echo "...copying" $(CP) $(CPFLAGS) src/main.elf src/main.bin $(OD) $(ODFLAGS) src/main.elf > src/main.lst src/main.elf: src/main.o $(LINKERSCRIPT) @echo "..linking" $(LD) $(LFLAGS) -o src/main.elf src/main.o src/main.o: src/main.c @echo ".compiling" $(CC) $(CFLAGS) src/main.c -o src/main.o debug: $(GDBTUI) -ex "target remote localhost:3333" \ -ex "set remote hardware-breakpoint-limit 6" \ -ex "set remote hardware-watchpoint-limit 4" src/main.elf
df5749e4462167c618cb368e5ad7563d765832a7
82e44445c70db0f03e30d7be725775f122d72f3e
/src/algebra/homology/image_to_kernel.lean
c04df91faeed6ba1c511c4fe200e203024c7d397
[ "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
11,618
lean
/- Copyright (c) 2021 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import category_theory.subobject.limits /-! # Image-to-kernel comparison maps Whenever `f : A ⟶ B` and `g : B ⟶ C` satisfy `w : f ≫ g = 0`, we have `image_le_kernel f g w : image_subobject f ≤ kernel_subobject g` (assuming the appropriate images and kernels exist). `image_to_kernel f g w` is the corresponding morphism between objects in `C`. We define `homology f g w` of such a pair as the cokernel of `image_to_kernel f g w`. -/ universes v u open category_theory category_theory.limits variables {ι : Type*} variables {V : Type u} [category.{v} V] [has_zero_morphisms V] open_locale classical noncomputable theory section variables {A B C : V} (f : A ⟶ B) [has_image f] (g : B ⟶ C) [has_kernel g] lemma image_le_kernel (w : f ≫ g = 0) : image_subobject f ≤ kernel_subobject g := image_subobject_le_mk _ _ (kernel.lift _ _ w) (by simp) /-- The canonical morphism `image_subobject f ⟶ kernel_subobject g` when `f ≫ g = 0`. -/ @[derive mono] def image_to_kernel (w : f ≫ g = 0) : (image_subobject f : V) ⟶ (kernel_subobject g : V) := (subobject.of_le _ _ (image_le_kernel _ _ w)) /-- Prefer `image_to_kernel`. -/ @[simp] lemma subobject_of_le_as_image_to_kernel (w : f ≫ g = 0) (h) : subobject.of_le (image_subobject f) (kernel_subobject g) h = image_to_kernel f g w := rfl @[simp, reassoc] lemma image_to_kernel_arrow (w : f ≫ g = 0) : image_to_kernel f g w ≫ (kernel_subobject g).arrow = (image_subobject f).arrow := by simp [image_to_kernel] -- This is less useful as a `simp` lemma than it initially appears, -- as it "loses" the information the morphism factors through the image. lemma factor_thru_image_subobject_comp_image_to_kernel (w : f ≫ g = 0) : factor_thru_image_subobject f ≫ image_to_kernel f g w = factor_thru_kernel_subobject g f w := by { ext, simp, } end section variables {A B C : V} (f : A ⟶ B) (g : B ⟶ C) @[simp] lemma image_to_kernel_zero_left [has_kernels V] [has_zero_object V] {w} : image_to_kernel (0 : A ⟶ B) g w = 0 := by { ext, simp, } lemma image_to_kernel_zero_right [has_images V] {w} : image_to_kernel f (0 : B ⟶ C) w = (image_subobject f).arrow ≫ inv (kernel_subobject (0 : B ⟶ C)).arrow := by { ext, simp } section variables [has_kernels V] [has_images V] lemma image_to_kernel_comp_right {D : V} (h : C ⟶ D) (w : f ≫ g = 0) : image_to_kernel f (g ≫ h) (by simp [reassoc_of w]) = image_to_kernel f g w ≫ subobject.of_le _ _ (kernel_subobject_comp_le g h) := by { ext, simp } lemma image_to_kernel_comp_left {Z : V} (h : Z ⟶ A) (w : f ≫ g = 0) : image_to_kernel (h ≫ f) g (by simp [w]) = subobject.of_le _ _ (image_subobject_comp_le h f) ≫ image_to_kernel f g w := by { ext, simp } @[simp] lemma image_to_kernel_comp_mono {D : V} (h : C ⟶ D) [mono h] (w) : image_to_kernel f (g ≫ h) w = image_to_kernel f g ((cancel_mono h).mp (by simpa using w : (f ≫ g) ≫ h = 0 ≫ h)) ≫ (subobject.iso_of_eq _ _ (kernel_subobject_comp_mono g h)).inv := by { ext, simp, } @[simp] lemma image_to_kernel_epi_comp {Z : V} (h : Z ⟶ A) [epi h] (w) : image_to_kernel (h ≫ f) g w = subobject.of_le _ _ (image_subobject_comp_le h f) ≫ image_to_kernel f g ((cancel_epi h).mp (by simpa using w : h ≫ f ≫ g = h ≫ 0)) := by { ext, simp, } end @[simp] lemma image_to_kernel_comp_hom_inv_comp [has_equalizers V] [has_images V] {Z : V} {i : B ≅ Z} (w) : image_to_kernel (f ≫ i.hom) (i.inv ≫ g) w = (image_subobject_comp_iso _ _).hom ≫ image_to_kernel f g (by simpa using w) ≫ (kernel_subobject_iso_comp i.inv g).inv := by { ext, simp, } open_locale zero_object /-- `image_to_kernel` for `A --0--> B --g--> C`, where `g` is a mono is itself an epi (i.e. the sequence is exact at `B`). -/ instance image_to_kernel_epi_of_zero_of_mono [has_kernels V] [has_zero_object V] [mono g] : epi (image_to_kernel (0 : A ⟶ B) g (by simp)) := epi_of_target_iso_zero _ (kernel_subobject_iso g ≪≫ kernel.of_mono g) /-- `image_to_kernel` for `A --f--> B --0--> C`, where `g` is an epi is itself an epi (i.e. the sequence is exact at `B`). -/ instance image_to_kernel_epi_of_epi_of_zero [has_images V] [epi f] : epi (image_to_kernel f (0 : B ⟶ C) (by simp)) := begin simp only [image_to_kernel_zero_right], haveI := epi_image_of_epi f, rw ←image_subobject_arrow, refine @epi_comp _ _ _ _ _ _ (epi_comp _ _) _ _, end end section variables {A B C : V} (f : A ⟶ B) [has_image f] (g : B ⟶ C) [has_kernel g] /-- The homology of a pair of morphisms `f : A ⟶ B` and `g : B ⟶ C` satisfying `f ≫ g = 0` is the cokernel of the `image_to_kernel` morphism for `f` and `g`. -/ def homology {A B C : V} (f : A ⟶ B) [has_image f] (g : B ⟶ C) [has_kernel g] (w : f ≫ g = 0) [has_cokernel (image_to_kernel f g w)] : V := cokernel (image_to_kernel f g w) section variables (w : f ≫ g = 0) [has_cokernel (image_to_kernel f g w)] /-- The morphism from cycles to homology. -/ def homology.π : (kernel_subobject g : V) ⟶ homology f g w := cokernel.π _ @[simp] lemma homology.condition : image_to_kernel f g w ≫ homology.π f g w = 0 := cokernel.condition _ /-- To construct a map out of homology, it suffices to construct a map out of the cycles which vanishes on boundaries. -/ def homology.desc {D : V} (k : (kernel_subobject g : V) ⟶ D) (p : image_to_kernel f g w ≫ k = 0) : homology f g w ⟶ D := cokernel.desc _ k p @[simp, reassoc] lemma homology.π_desc {D : V} (k : (kernel_subobject g : V) ⟶ D) (p : image_to_kernel f g w ≫ k = 0) : homology.π f g w ≫ homology.desc f g w k p = k := by { simp [homology.π, homology.desc], } /-- To check two morphisms out of `homology f g w` are equal, it suffices to check on cycles. -/ @[ext] lemma homology.ext {D : V} {k k' : homology f g w ⟶ D} (p : homology.π f g w ≫ k = homology.π f g w ≫ k') : k = k' := by { ext, exact p, } /-- `homology 0 0 _` is just the middle object. -/ @[simps] def homology_zero_zero [has_zero_object V] [has_image (0 : A ⟶ B)] [has_cokernel (image_to_kernel (0 : A ⟶ B) (0 : B ⟶ C) (by simp))] : homology (0 : A ⟶ B) (0 : B ⟶ C) (by simp) ≅ B := { hom := homology.desc (0 : A ⟶ B) (0 : B ⟶ C) (by simp) (kernel_subobject 0).arrow (by simp), inv := inv (kernel_subobject 0).arrow ≫ homology.π _ _ _, } end section variables {f g} (w : f ≫ g = 0) {A' B' C' : V} {f' : A' ⟶ B'} [has_image f'] {g' : B' ⟶ C'} [has_kernel g'] (w' : f' ≫ g' = 0) (α : arrow.mk f ⟶ arrow.mk f') [has_image_map α] (β : arrow.mk g ⟶ arrow.mk g') /-- Given compatible commutative squares between a pair `f g` and a pair `f' g'` satisfying `f ≫ g = 0` and `f' ≫ g' = 0`, the `image_to_kernel` morphisms intertwine the induced map on kernels and the induced map on images. -/ @[reassoc] lemma image_subobject_map_comp_image_to_kernel (p : α.right = β.left) : image_to_kernel f g w ≫ kernel_subobject_map β = image_subobject_map α ≫ image_to_kernel f' g' w' := by { ext, simp [p], } variables [has_cokernel (image_to_kernel f g w)] [has_cokernel (image_to_kernel f' g' w')] /-- Given compatible commutative squares between a pair `f g` and a pair `f' g'` satisfying `f ≫ g = 0` and `f' ≫ g' = 0`, we get a morphism on homology. -/ def homology.map (p : α.right = β.left) : homology f g w ⟶ homology f' g' w' := cokernel.desc _ (kernel_subobject_map β ≫ cokernel.π _) begin rw [image_subobject_map_comp_image_to_kernel_assoc w w' α β p], simp, end @[simp, reassoc] lemma homology.π_map (p : α.right = β.left) : homology.π f g w ≫ homology.map w w' α β p = kernel_subobject_map β ≫ homology.π f' g' w' := by { simp [homology.π, homology.map], } @[simp, reassoc] lemma homology.map_desc (p : α.right = β.left) {D : V} (k : (kernel_subobject g' : V) ⟶ D) (z : image_to_kernel f' g' w' ≫ k = 0) : homology.map w w' α β p ≫ homology.desc f' g' w' k z = homology.desc f g w (kernel_subobject_map β ≫ k) (by simp [image_subobject_map_comp_image_to_kernel_assoc w w' α β p, z]) := by { ext, simp, } end end section variables {A B C : V} {f : A ⟶ B} {g : B ⟶ C} (w : f ≫ g = 0) {f' : A ⟶ B} {g' : B ⟶ C} (w' : f' ≫ g' = 0) [has_kernels V] [has_cokernels V] [has_images V] [has_image_maps V] /-- `homology f g w ≅ homology f' g' w'` if `f = f'` and `g = g'`. (Note the objects are not changing here.) -/ @[simps] def homology.congr (pf : f = f') (pg : g = g') : homology f g w ≅ homology f' g' w' := { hom := homology.map w w' { left := 𝟙 _, right := 𝟙 _, } { left := 𝟙 _, right := 𝟙 _, } rfl, inv := homology.map w' w { left := 𝟙 _, right := 𝟙 _, } { left := 𝟙 _, right := 𝟙 _, } rfl, hom_inv_id' := begin ext, simp_rw [category.comp_id, homology.π_map_assoc, homology.π_map, ←category.assoc, ←kernel_subobject_map_comp], convert category.id_comp _, convert kernel_subobject_map_id, ext; simp, end, inv_hom_id' := begin ext, simp_rw [category.comp_id, homology.π_map_assoc, homology.π_map, ←category.assoc, ←kernel_subobject_map_comp], convert category.id_comp _, convert kernel_subobject_map_id, ext; simp, end, } end /-! We provide a variant `image_to_kernel' : image f ⟶ kernel g`, and use this to give alternative formulas for `homology f g w`. -/ section image_to_kernel' variables {A B C : V} (f : A ⟶ B) (g : B ⟶ C) (w : f ≫ g = 0) [has_kernels V] [has_images V] /-- While `image_to_kernel f g w` provides a morphism `image_subobject f ⟶ kernel_subobject g` in terms of the subobject API, this variant provides a morphism `image f ⟶ kernel g`, which is sometimes more convenient. -/ def image_to_kernel' (w : f ≫ g = 0) : image f ⟶ kernel g := kernel.lift g (image.ι f) (by { ext, simpa using w, }) @[simp] lemma image_subobject_iso_image_to_kernel' (w : f ≫ g = 0) : (image_subobject_iso f).hom ≫ image_to_kernel' f g w = image_to_kernel f g w ≫ (kernel_subobject_iso g).hom := by { ext, simp [image_to_kernel'], } @[simp] lemma image_to_kernel'_kernel_subobject_iso (w : f ≫ g = 0) : image_to_kernel' f g w ≫ (kernel_subobject_iso g).inv = (image_subobject_iso f).inv ≫ image_to_kernel f g w := by { ext, simp [image_to_kernel'], } variables [has_cokernels V] /-- `homology f g w` can be computed as the cokernel of `image_to_kernel' f g w`. -/ def homology_iso_cokernel_image_to_kernel' (w : f ≫ g = 0) : homology f g w ≅ cokernel (image_to_kernel' f g w) := { hom := cokernel.map _ _ (image_subobject_iso f).hom (kernel_subobject_iso g).hom (by tidy), inv := cokernel.map _ _ (image_subobject_iso f).inv (kernel_subobject_iso g).inv (by tidy), hom_inv_id' := begin apply coequalizer.hom_ext, simp only [iso.hom_inv_id_assoc, cokernel.π_desc, cokernel.π_desc_assoc, category.assoc, coequalizer_as_cokernel], exact (category.comp_id _).symm, end, } variables [has_equalizers V] /-- `homology f g w` can be computed as the cokernel of `kernel.lift g f w`. -/ def homology_iso_cokernel_lift (w : f ≫ g = 0) : homology f g w ≅ cokernel (kernel.lift g f w) := begin refine homology_iso_cokernel_image_to_kernel' f g w ≪≫ _, have p : factor_thru_image f ≫ image_to_kernel' f g w = kernel.lift g f w, { ext, simp [image_to_kernel'], }, exact (cokernel_epi_comp _ _).symm ≪≫ cokernel_iso_of_eq p, end end image_to_kernel'
1d63a99e5b364ef1fc084c371fafc7e6ce4b9433
1abd1ed12aa68b375cdef28959f39531c6e95b84
/src/analysis/box_integral/partition/basic.lean
90d2165967d904a0a3c9f768a3ae9118aa267924
[ "Apache-2.0" ]
permissive
jumpy4/mathlib
d3829e75173012833e9f15ac16e481e17596de0f
af36f1a35f279f0e5b3c2a77647c6bf2cfd51a13
refs/heads/master
1,693,508,842,818
1,636,203,271,000
1,636,203,271,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
29,254
lean
/- Copyright (c) 2021 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudryashov -/ import analysis.box_integral.box.basic /-! # Partitions of rectangular boxes in `ℝⁿ` In this file we define (pre)partitions of rectangular boxes in `ℝⁿ`. A partition of a box `I` in `ℝⁿ` (see `box_integral.prepartition` and `box_integral.prepartition.is_partition`) is a finite set of pairwise disjoint boxes such that their union is exactly `I`. We use `boxes : finset (box ι)` to store the set of boxes. Many lemmas about box integrals deal with pairwise disjoint collections of subboxes, so we define a structure `box_integral.prepartition (I : box_integral.box ι)` that stores a collection of boxes such that * each box `J ∈ boxes` is a subbox of `I`; * the boxes are pairwise disjoint as sets in `ℝⁿ`. Then we define a predicate `box_integral.prepartition.is_partition`; `π.is_partition` means that the boxes of `π` actually cover the whole `I`. We also define some operations on prepartitions: * `box_integral.partition.bUnion`: split each box of a partition into smaller boxes; * `box_integral.partition.restrict`: restrict a partition to a smaller box. We also define a `semilattice_inf_top` structure on `box_integral.partition I` for all `I : box_integral.box ι`. ## Tags rectangular box, partition -/ open set finset function open_locale classical nnreal big_operators noncomputable theory namespace box_integral variables {ι : Type*} /-- A prepartition of `I : box_integral.box ι` is a finite set of pairwise disjoint subboxes of `I`. -/ structure prepartition (I : box ι) := (boxes : finset (box ι)) (le_of_mem' : ∀ J ∈ boxes, J ≤ I) (pairwise_disjoint : set.pairwise ↑boxes (disjoint on (coe : box ι → set (ι → ℝ)))) namespace prepartition variables {I J J₁ J₂ : box ι} (π : prepartition I) {π₁ π₂ : prepartition I} {x : ι → ℝ} instance : has_mem (box ι) (prepartition I) := ⟨λ J π, J ∈ π.boxes⟩ @[simp] lemma mem_boxes : J ∈ π.boxes ↔ J ∈ π := iff.rfl @[simp] lemma mem_mk {s h₁ h₂} : J ∈ (mk s h₁ h₂ : prepartition I) ↔ J ∈ s := iff.rfl lemma disjoint_coe_of_mem (h₁ : J₁ ∈ π) (h₂ : J₂ ∈ π) (h : J₁ ≠ J₂) : disjoint (J₁ : set (ι → ℝ)) J₂ := π.pairwise_disjoint J₁ h₁ J₂ h₂ h lemma eq_of_mem_of_mem (h₁ : J₁ ∈ π) (h₂ : J₂ ∈ π) (hx₁ : x ∈ J₁) (hx₂ : x ∈ J₂) : J₁ = J₂ := by_contra $ λ H, π.disjoint_coe_of_mem h₁ h₂ H ⟨hx₁, hx₂⟩ lemma eq_of_le_of_le (h₁ : J₁ ∈ π) (h₂ : J₂ ∈ π) (hle₁ : J ≤ J₁) (hle₂ : J ≤ J₂) : J₁ = J₂ := π.eq_of_mem_of_mem h₁ h₂ (hle₁ J.upper_mem) (hle₂ J.upper_mem) lemma eq_of_le (h₁ : J₁ ∈ π) (h₂ : J₂ ∈ π) (hle : J₁ ≤ J₂) : J₁ = J₂ := π.eq_of_le_of_le h₁ h₂ le_rfl hle lemma le_of_mem (hJ : J ∈ π) : J ≤ I := π.le_of_mem' J hJ lemma lower_le_lower (hJ : J ∈ π) : I.lower ≤ J.lower := box.antitone_lower (π.le_of_mem hJ) lemma upper_le_upper (hJ : J ∈ π) : J.upper ≤ I.upper := box.monotone_upper (π.le_of_mem hJ) lemma injective_boxes : function.injective (boxes : prepartition I → finset (box ι)) := by { rintro ⟨s₁, h₁, h₁'⟩ ⟨s₂, h₂, h₂'⟩ (rfl : s₁ = s₂), refl } @[ext] lemma ext (h : ∀ J, J ∈ π₁ ↔ J ∈ π₂) : π₁ = π₂ := injective_boxes $ finset.ext h /-- The singleton prepartition `{J}`, `J ≤ I`. -/ @[simps] def single (I J : box ι) (h : J ≤ I) : prepartition I := ⟨{J}, by simpa, by simp⟩ @[simp] lemma mem_single {J'} (h : J ≤ I) : J' ∈ single I J h ↔ J' = J := mem_singleton /-- We say that `π ≤ π'` if each box of `π` is a subbox of some box of `π'`. -/ instance : has_le (prepartition I) := ⟨λ π π', ∀ ⦃I⦄, I ∈ π → ∃ I' ∈ π', I ≤ I'⟩ instance : order_top (prepartition I) := { le := (≤), le_refl := λ π I hI, ⟨I, hI, le_rfl⟩, le_trans := λ π₁ π₂ π₃ h₁₂ h₂₃ I₁ hI₁, let ⟨I₂, hI₂, hI₁₂⟩ := h₁₂ hI₁, ⟨I₃, hI₃, hI₂₃⟩ := h₂₃ hI₂ in ⟨I₃, hI₃, hI₁₂.trans hI₂₃⟩, le_antisymm := begin suffices : ∀ {π₁ π₂ : prepartition I}, π₁ ≤ π₂ → π₂ ≤ π₁ → π₁.boxes ⊆ π₂.boxes, from λ π₁ π₂ h₁ h₂, injective_boxes (subset.antisymm (this h₁ h₂) (this h₂ h₁)), intros π₁ π₂ h₁ h₂ J hJ, rcases h₁ hJ with ⟨J', hJ', hle⟩, rcases h₂ hJ' with ⟨J'', hJ'', hle'⟩, obtain rfl : J = J'', from π₁.eq_of_le hJ hJ'' (hle.trans hle'), obtain rfl : J' = J, from le_antisymm ‹_› ‹_›, assumption end, top := single I I le_rfl, le_top := λ π J hJ, ⟨I, by simp, π.le_of_mem hJ⟩ } instance : order_bot (prepartition I) := { bot := ⟨∅, λ J hJ, false.elim hJ, λ J hJ, false.elim hJ⟩, bot_le := λ π J hJ, false.elim hJ, .. prepartition.order_top } instance : inhabited (prepartition I) := ⟨⊤⟩ lemma le_def : π₁ ≤ π₂ ↔ ∀ J ∈ π₁, ∃ J' ∈ π₂, J ≤ J' := iff.rfl @[simp] lemma mem_top : J ∈ (⊤ : prepartition I) ↔ J = I := mem_singleton @[simp] lemma top_boxes : (⊤ : prepartition I).boxes = {I} := rfl @[simp] lemma not_mem_bot : J ∉ (⊥ : prepartition I) := id @[simp] lemma bot_boxes : (⊥ : prepartition I).boxes = ∅ := rfl /-- An auxiliary lemma used to prove that the same point can't belong to more than `2 ^ fintype.card ι` closed boxes of a prepartition. -/ lemma inj_on_set_of_mem_Icc_set_of_lower_eq (x : ι → ℝ) : inj_on (λ J : box ι, {i | J.lower i = x i}) {J | J ∈ π ∧ x ∈ J.Icc} := begin rintros J₁ ⟨h₁, hx₁⟩ J₂ ⟨h₂, hx₂⟩ (H : {i | J₁.lower i = x i} = {i | J₂.lower i = x i}), suffices : ∀ i, (Ioc (J₁.lower i) (J₁.upper i) ∩ Ioc (J₂.lower i) (J₂.upper i)).nonempty, { choose y hy₁ hy₂, exact π.eq_of_mem_of_mem h₁ h₂ hy₁ hy₂ }, intro i, simp only [set.ext_iff, mem_set_of_eq] at H, cases (hx₁.1 i).eq_or_lt with hi₁ hi₁, { have hi₂ : J₂.lower i = x i, from (H _).1 hi₁, have H₁ : x i < J₁.upper i, by simpa only [hi₁] using J₁.lower_lt_upper i, have H₂ : x i < J₂.upper i, by simpa only [hi₂] using J₂.lower_lt_upper i, rw [Ioc_inter_Ioc, hi₁, hi₂, sup_idem, set.nonempty_Ioc], exact lt_min H₁ H₂ }, { have hi₂ : J₂.lower i < x i, from (hx₂.1 i).lt_of_ne (mt (H _).2 hi₁.ne), exact ⟨x i, ⟨hi₁, hx₁.2 i⟩, ⟨hi₂, hx₂.2 i⟩⟩ } end /-- The set of boxes of a prepartition that contain `x` in their closures has cardinality at most `2 ^ fintype.card ι`. -/ lemma card_filter_mem_Icc_le [fintype ι] (x : ι → ℝ) : (π.boxes.filter (λ J : box ι, x ∈ J.Icc)).card ≤ 2 ^ fintype.card ι := begin rw [← fintype.card_set], refine finset.card_le_card_of_inj_on (λ J : box ι, {i | J.lower i = x i}) (λ _ _, finset.mem_univ _) _, simpa only [finset.mem_filter] using π.inj_on_set_of_mem_Icc_set_of_lower_eq x end /-- Given a prepartition `π : box_integral.prepartition I`, `π.Union` is the part of `I` covered by the boxes of `π`. -/ protected def Union : set (ι → ℝ) := ⋃ J ∈ π, ↑J lemma Union_def : π.Union = ⋃ J ∈ π, ↑J := rfl lemma Union_def' : π.Union = ⋃ J ∈ π.boxes, ↑J := rfl @[simp] lemma mem_Union : x ∈ π.Union ↔ ∃ J ∈ π, x ∈ J := set.mem_bUnion_iff @[simp] lemma Union_single (h : J ≤ I) : (single I J h).Union = J := by simp [Union_def] @[simp] lemma Union_top : (⊤ : prepartition I).Union = I := by simp [prepartition.Union] @[simp] lemma Union_eq_empty : π₁.Union = ∅ ↔ π₁ = ⊥ := by simp [← injective_boxes.eq_iff, finset.ext_iff, prepartition.Union, imp_false] @[simp] lemma Union_bot : (⊥ : prepartition I).Union = ∅ := Union_eq_empty.2 rfl lemma subset_Union (h : J ∈ π) : ↑J ⊆ π.Union := subset_bUnion_of_mem h lemma Union_subset : π.Union ⊆ I := bUnion_subset π.le_of_mem' @[mono] lemma Union_mono (h : π₁ ≤ π₂) : π₁.Union ⊆ π₂.Union := λ x hx, let ⟨J₁, hJ₁, hx⟩ := π₁.mem_Union.1 hx, ⟨J₂, hJ₂, hle⟩ := h hJ₁ in π₂.mem_Union.2 ⟨J₂, hJ₂, hle hx⟩ lemma disjoint_boxes_of_disjoint_Union (h : disjoint π₁.Union π₂.Union) : disjoint π₁.boxes π₂.boxes := finset.disjoint_left.2 $ λ J h₁ h₂, h.mono (π₁.subset_Union h₁) (π₂.subset_Union h₂) ⟨J.upper_mem, J.upper_mem⟩ lemma le_iff_nonempty_imp_le_and_Union_subset : π₁ ≤ π₂ ↔ (∀ (J ∈ π₁) (J' ∈ π₂), (J ∩ J' : set (ι → ℝ)).nonempty → J ≤ J') ∧ π₁.Union ⊆ π₂.Union := begin fsplit, { refine λ H, ⟨λ J hJ J' hJ' Hne, _, Union_mono H⟩, rcases H hJ with ⟨J'', hJ'', Hle⟩, rcases Hne with ⟨x, hx, hx'⟩, rwa π₂.eq_of_mem_of_mem hJ' hJ'' hx' (Hle hx) }, { rintro ⟨H, HU⟩ J hJ, simp only [set.subset_def, mem_Union] at HU, rcases HU J.upper ⟨J, hJ, J.upper_mem⟩ with ⟨J₂, hJ₂, hx⟩, exact ⟨J₂, hJ₂, H _ hJ _ hJ₂ ⟨_, J.upper_mem, hx⟩⟩ } end lemma eq_of_boxes_subset_Union_superset (h₁ : π₁.boxes ⊆ π₂.boxes) (h₂ : π₂.Union ⊆ π₁.Union) : π₁ = π₂ := le_antisymm (λ J hJ, ⟨J, h₁ hJ, le_rfl⟩) $ le_iff_nonempty_imp_le_and_Union_subset.2 ⟨λ J₁ hJ₁ J₂ hJ₂ Hne, (π₂.eq_of_mem_of_mem hJ₁ (h₁ hJ₂) Hne.some_spec.1 Hne.some_spec.2).le, h₂⟩ /-- Given a prepartition `π` of a box `I` and a collection of prepartitions `πi J` of all boxes `J ∈ π`, returns the prepartition of `I` into the union of the boxes of all `πi J`. Though we only use the values of `πi` on the boxes of `π`, we require `πi` to be a globally defined function. -/ @[simps] def bUnion (πi : Π J : box ι, prepartition J) : prepartition I := { boxes := π.boxes.bUnion $ λ J, (πi J).boxes, le_of_mem' := λ J hJ, begin simp only [finset.mem_bUnion, exists_prop, mem_boxes] at hJ, rcases hJ with ⟨J', hJ', hJ⟩, exact ((πi J').le_of_mem hJ).trans (π.le_of_mem hJ') end, pairwise_disjoint := begin simp only [set.pairwise, finset.mem_coe, finset.mem_bUnion], rintro J₁' ⟨J₁, hJ₁, hJ₁'⟩ J₂' ⟨J₂, hJ₂, hJ₂'⟩ Hne x ⟨hx₁, hx₂⟩, apply Hne, obtain rfl : J₁ = J₂, from π.eq_of_mem_of_mem hJ₁ hJ₂ ((πi J₁).le_of_mem hJ₁' hx₁) ((πi J₂).le_of_mem hJ₂' hx₂), exact (πi J₁).eq_of_mem_of_mem hJ₁' hJ₂' hx₁ hx₂ end } variables {πi πi₁ πi₂ : Π J : box ι, prepartition J} @[simp] lemma mem_bUnion : J ∈ π.bUnion πi ↔ ∃ J' ∈ π, J ∈ πi J' := by simp [bUnion] lemma bUnion_le (πi : Π J, prepartition J) : π.bUnion πi ≤ π := λ J hJ, let ⟨J', hJ', hJ⟩ := π.mem_bUnion.1 hJ in ⟨J', hJ', (πi J').le_of_mem hJ⟩ @[simp] lemma bUnion_top : π.bUnion (λ _, ⊤) = π := by { ext, simp } @[congr] lemma bUnion_congr (h : π₁ = π₂) (hi : ∀ J ∈ π₁, πi₁ J = πi₂ J) : π₁.bUnion πi₁ = π₂.bUnion πi₂ := by { subst π₂, ext J, simp [hi] { contextual := tt } } lemma bUnion_congr_of_le (h : π₁ = π₂) (hi : ∀ J ≤ I, πi₁ J = πi₂ J) : π₁.bUnion πi₁ = π₂.bUnion πi₂ := bUnion_congr h $ λ J hJ, hi J (π₁.le_of_mem hJ) @[simp] lemma Union_bUnion (πi : Π J : box ι, prepartition J) : (π.bUnion πi).Union = ⋃ J ∈ π, (πi J).Union := by simp [prepartition.Union] @[simp] lemma sum_bUnion_boxes {M : Type*} [add_comm_monoid M] (π : prepartition I) (πi : Π J, prepartition J) (f : box ι → M) : ∑ J in π.boxes.bUnion (λ J, (πi J).boxes), f J = ∑ J in π.boxes, ∑ J' in (πi J).boxes, f J' := begin refine finset.sum_bUnion (λ J₁ h₁ J₂ h₂ hne, finset.disjoint_left.2 $ λ J' h₁' h₂', _), exact hne (π.eq_of_le_of_le h₁ h₂ ((πi J₁).le_of_mem h₁') ((πi J₂).le_of_mem h₂')) end /-- Given a box `J ∈ π.bUnion πi`, returns the box `J' ∈ π` such that `J ∈ πi J'`. For `J ∉ π.bUnion πi`, returns `I`. -/ def bUnion_index (πi : Π J, prepartition J) (J : box ι) : box ι := if hJ : J ∈ π.bUnion πi then (π.mem_bUnion.1 hJ).some else I lemma bUnion_index_mem (hJ : J ∈ π.bUnion πi) : π.bUnion_index πi J ∈ π := by { rw [bUnion_index, dif_pos hJ], exact (π.mem_bUnion.1 hJ).some_spec.fst } lemma bUnion_index_le (πi : Π J, prepartition J) (J : box ι) : π.bUnion_index πi J ≤ I := begin by_cases hJ : J ∈ π.bUnion πi, { exact π.le_of_mem (π.bUnion_index_mem hJ) }, { rw [bUnion_index, dif_neg hJ], exact le_rfl } end lemma mem_bUnion_index (hJ : J ∈ π.bUnion πi) : J ∈ πi (π.bUnion_index πi J) := by convert (π.mem_bUnion.1 hJ).some_spec.snd; exact dif_pos hJ lemma le_bUnion_index (hJ : J ∈ π.bUnion πi) : J ≤ π.bUnion_index πi J := le_of_mem _ (π.mem_bUnion_index hJ) /-- Uniqueness property of `box_integral.partition.bUnion_index`. -/ lemma bUnion_index_of_mem (hJ : J ∈ π) {J'} (hJ' : J' ∈ πi J) : π.bUnion_index πi J' = J := have J' ∈ π.bUnion πi, from π.mem_bUnion.2 ⟨J, hJ, hJ'⟩, π.eq_of_le_of_le (π.bUnion_index_mem this) hJ (π.le_bUnion_index this) (le_of_mem _ hJ') lemma bUnion_assoc (πi : Π J, prepartition J) (πi' : box ι → Π J : box ι, prepartition J) : π.bUnion (λ J, (πi J).bUnion (πi' J)) = (π.bUnion πi).bUnion (λ J, πi' (π.bUnion_index πi J) J) := begin ext J, simp only [mem_bUnion, exists_prop], fsplit, { rintro ⟨J₁, hJ₁, J₂, hJ₂, hJ⟩, refine ⟨J₂, ⟨J₁, hJ₁, hJ₂⟩, _⟩, rwa π.bUnion_index_of_mem hJ₁ hJ₂ }, { rintro ⟨J₁, ⟨J₂, hJ₂, hJ₁⟩, hJ⟩, refine ⟨J₂, hJ₂, J₁, hJ₁, _⟩, rwa π.bUnion_index_of_mem hJ₂ hJ₁ at hJ } end /-- Create a `box_integral.prepartition` from a collection of possibly empty boxes by filtering out the empty one if it exists. -/ def of_with_bot (boxes : finset (with_bot (box ι))) (le_of_mem : ∀ J ∈ boxes, (J : with_bot (box ι)) ≤ I) (pairwise_disjoint : set.pairwise (boxes : set (with_bot (box ι))) disjoint) : prepartition I := { boxes := boxes.erase_none, le_of_mem' := λ J hJ, begin rw mem_erase_none at hJ, simpa only [with_bot.some_eq_coe, with_bot.coe_le_coe] using le_of_mem _ hJ end, pairwise_disjoint := λ J₁ h₁ J₂ h₂ hne, begin simp only [mem_coe, mem_erase_none] at h₁ h₂, exact box.disjoint_coe.1 (pairwise_disjoint _ h₁ _ h₂ (mt option.some_inj.1 hne)) end } @[simp] lemma mem_of_with_bot {boxes : finset (with_bot (box ι))} {h₁ h₂} : J ∈ (of_with_bot boxes h₁ h₂ : prepartition I) ↔ (J : with_bot (box ι)) ∈ boxes := mem_erase_none @[simp] lemma Union_of_with_bot (boxes : finset (with_bot (box ι))) (le_of_mem : ∀ J ∈ boxes, (J : with_bot (box ι)) ≤ I) (pairwise_disjoint : set.pairwise (boxes : set (with_bot (box ι))) disjoint) : (of_with_bot boxes le_of_mem pairwise_disjoint).Union = ⋃ J ∈ boxes, ↑J := begin suffices : (⋃ (J : box ι) (hJ : ↑J ∈ boxes), ↑J) = ⋃ J ∈ boxes, ↑J, by simpa [of_with_bot, prepartition.Union], simp only [← box.bUnion_coe_eq_coe, @Union_comm _ _ (box ι), @Union_comm _ _ (@eq _ _ _), Union_Union_eq_right] end lemma of_with_bot_le {boxes : finset (with_bot (box ι))} {le_of_mem : ∀ J ∈ boxes, (J : with_bot (box ι)) ≤ I} {pairwise_disjoint : set.pairwise (boxes : set (with_bot (box ι))) disjoint} (H : ∀ J ∈ boxes, J ≠ ⊥ → ∃ J' ∈ π, J ≤ ↑J') : of_with_bot boxes le_of_mem pairwise_disjoint ≤ π := have ∀ (J : box ι), ↑J ∈ boxes → ∃ J' ∈ π, J ≤ J', from λ J hJ, by simpa only [with_bot.coe_le_coe] using H J hJ (with_bot.coe_ne_bot J), by simpa [of_with_bot, le_def] lemma le_of_with_bot {boxes : finset (with_bot (box ι))} {le_of_mem : ∀ J ∈ boxes, (J : with_bot (box ι)) ≤ I} {pairwise_disjoint : set.pairwise (boxes : set (with_bot (box ι))) disjoint} (H : ∀ J ∈ π, ∃ J' ∈ boxes, ↑J ≤ J') : π ≤ of_with_bot boxes le_of_mem pairwise_disjoint := begin intros J hJ, rcases H J hJ with ⟨J', J'mem, hle⟩, lift J' to box ι using ne_bot_of_le_ne_bot (with_bot.coe_ne_bot _) hle, exact ⟨J', mem_of_with_bot.2 J'mem, with_bot.coe_le_coe.1 hle⟩ end lemma of_with_bot_mono {boxes₁ : finset (with_bot (box ι))} {le_of_mem₁ : ∀ J ∈ boxes₁, (J : with_bot (box ι)) ≤ I} {pairwise_disjoint₁ : set.pairwise (boxes₁ : set (with_bot (box ι))) disjoint} {boxes₂ : finset (with_bot (box ι))} {le_of_mem₂ : ∀ J ∈ boxes₂, (J : with_bot (box ι)) ≤ I} {pairwise_disjoint₂ : set.pairwise (boxes₂ : set (with_bot (box ι))) disjoint} (H : ∀ J ∈ boxes₁, J ≠ ⊥ → ∃ J' ∈ boxes₂, J ≤ J') : of_with_bot boxes₁ le_of_mem₁ pairwise_disjoint₁ ≤ of_with_bot boxes₂ le_of_mem₂ pairwise_disjoint₂ := le_of_with_bot _ $ λ J hJ, H J (mem_of_with_bot.1 hJ) (with_bot.coe_ne_bot _) lemma sum_of_with_bot {M : Type*} [add_comm_monoid M] (boxes : finset (with_bot (box ι))) (le_of_mem : ∀ J ∈ boxes, (J : with_bot (box ι)) ≤ I) (pairwise_disjoint : set.pairwise (boxes : set (with_bot (box ι))) disjoint) (f : box ι → M) : ∑ J in (of_with_bot boxes le_of_mem pairwise_disjoint).boxes, f J = ∑ J in boxes, option.elim J 0 f := finset.sum_erase_none _ _ /-- Restrict a prepartition to a box. -/ def restrict (π : prepartition I) (J : box ι) : prepartition J := of_with_bot (π.boxes.image (λ J', J ⊓ J')) (λ J' hJ', by { rcases finset.mem_image.1 hJ' with ⟨J', -, rfl⟩, exact inf_le_left }) begin simp only [set.pairwise, on_fun, finset.mem_coe, finset.mem_image], rintro _ ⟨J₁, h₁, rfl⟩ _ ⟨J₂, h₂, rfl⟩ Hne, have : J₁ ≠ J₂, by { rintro rfl, exact Hne rfl }, exact ((box.disjoint_coe.2 $ π.disjoint_coe_of_mem h₁ h₂ this).inf_left' _).inf_right' _ end @[simp] lemma mem_restrict : J₁ ∈ π.restrict J ↔ ∃ (J' ∈ π), (J₁ : with_bot (box ι)) = J ⊓ J' := by simp [restrict, eq_comm] lemma mem_restrict' : J₁ ∈ π.restrict J ↔ ∃ (J' ∈ π), (J₁ : set (ι → ℝ)) = J ∩ J' := by simp only [mem_restrict, ← box.with_bot_coe_inj, box.coe_inf, box.coe_coe] @[mono] lemma restrict_mono {π₁ π₂ : prepartition I} (Hle : π₁ ≤ π₂) : π₁.restrict J ≤ π₂.restrict J := begin refine of_with_bot_mono (λ J₁ hJ₁ hne, _), rw finset.mem_image at hJ₁, rcases hJ₁ with ⟨J₁, hJ₁, rfl⟩, rcases Hle hJ₁ with ⟨J₂, hJ₂, hle⟩, exact ⟨_, finset.mem_image_of_mem _ hJ₂, inf_le_inf_left _ $ with_bot.coe_le_coe.2 hle⟩ end lemma monotone_restrict : monotone (λ π : prepartition I, restrict π J) := λ π₁ π₂, restrict_mono /-- Restricting to a larger box does not change the set of boxes. We cannot claim equality of prepartitions because they have different types. -/ lemma restrict_boxes_of_le (π : prepartition I) (h : I ≤ J) : (π.restrict J).boxes = π.boxes := begin simp only [restrict, of_with_bot, erase_none_eq_bUnion], refine finset.image_bUnion.trans _, refine (finset.bUnion_congr rfl _).trans finset.bUnion_singleton_eq_self, intros J' hJ', rw [inf_of_le_right, ← with_bot.some_eq_coe, option.to_finset_some], exact with_bot.coe_le_coe.2 ((π.le_of_mem hJ').trans h) end @[simp] lemma restrict_self : π.restrict I = π := injective_boxes $ restrict_boxes_of_le π le_rfl @[simp] lemma Union_restrict : (π.restrict J).Union = J ∩ π.Union := by simp [restrict, ← inter_Union, ← Union_def] @[simp] lemma restrict_bUnion (πi : Π J, prepartition J) (hJ : J ∈ π) : (π.bUnion πi).restrict J = πi J := begin refine (eq_of_boxes_subset_Union_superset (λ J₁ h₁, _) _).symm, { refine (mem_restrict _).2 ⟨J₁, π.mem_bUnion.2 ⟨J, hJ, h₁⟩, (inf_of_le_right _).symm⟩, exact with_bot.coe_le_coe.2 (le_of_mem _ h₁) }, { simp only [Union_restrict, Union_bUnion, set.subset_def, set.mem_inter_eq, set.mem_Union], rintro x ⟨hxJ, J₁, h₁, hx⟩, obtain rfl : J = J₁, from π.eq_of_mem_of_mem hJ h₁ hxJ (Union_subset _ hx), exact hx } end lemma bUnion_le_iff {πi : Π J, prepartition J} {π' : prepartition I} : π.bUnion πi ≤ π' ↔ ∀ J ∈ π, πi J ≤ π'.restrict J := begin fsplit; intros H J hJ, { rw ← π.restrict_bUnion πi hJ, exact restrict_mono H }, { rw mem_bUnion at hJ, rcases hJ with ⟨J₁, h₁, hJ⟩, rcases H J₁ h₁ hJ with ⟨J₂, h₂, Hle⟩, rcases π'.mem_restrict.mp h₂ with ⟨J₃, h₃, H⟩, exact ⟨J₃, h₃, Hle.trans $ with_bot.coe_le_coe.1 $ H.trans_le inf_le_right⟩ } end lemma le_bUnion_iff {πi : Π J, prepartition J} {π' : prepartition I} : π' ≤ π.bUnion πi ↔ π' ≤ π ∧ ∀ J ∈ π, π'.restrict J ≤ πi J := begin refine ⟨λ H, ⟨H.trans (π.bUnion_le πi), λ J hJ, _⟩, _⟩, { rw ← π.restrict_bUnion πi hJ, exact restrict_mono H }, { rintro ⟨H, Hi⟩ J' hJ', rcases H hJ' with ⟨J, hJ, hle⟩, have : J' ∈ π'.restrict J, from π'.mem_restrict.2 ⟨J', hJ', (inf_of_le_right $ with_bot.coe_le_coe.2 hle).symm⟩, rcases Hi J hJ this with ⟨Ji, hJi, hlei⟩, exact ⟨Ji, π.mem_bUnion.2 ⟨J, hJ, hJi⟩, hlei⟩ } end instance : has_inf (prepartition I) := ⟨λ π₁ π₂, π₁.bUnion (λ J, π₂.restrict J)⟩ lemma inf_def (π₁ π₂ : prepartition I) : π₁ ⊓ π₂ = π₁.bUnion (λ J, π₂.restrict J) := rfl @[simp] lemma mem_inf {π₁ π₂ : prepartition I} : J ∈ π₁ ⊓ π₂ ↔ ∃ (J₁ ∈ π₁) (J₂ ∈ π₂), (J : with_bot (box ι)) = J₁ ⊓ J₂ := by simp only [inf_def, mem_bUnion, mem_restrict] @[simp] lemma Union_inf (π₁ π₂ : prepartition I) : (π₁ ⊓ π₂).Union = π₁.Union ∩ π₂.Union := by simp only [inf_def, Union_bUnion, Union_restrict, ← Union_inter, ← Union_def] instance : semilattice_inf_top (prepartition I) := { inf_le_left := λ π₁ π₂, π₁.bUnion_le _, inf_le_right := λ π₁ π₂, (bUnion_le_iff _).2 (λ J hJ, le_rfl), le_inf := λ π π₁ π₂ h₁ h₂, π₁.le_bUnion_iff.2 ⟨h₁, λ J hJ, restrict_mono h₂⟩, .. prepartition.order_top, .. prepartition.has_inf } instance : semilattice_inf_bot (prepartition I) := { .. prepartition.order_bot, .. prepartition.semilattice_inf_top } /-- The prepartition with boxes `{J ∈ π | p J}`. -/ @[simps] def filter (π : prepartition I) (p : box ι → Prop) : prepartition I := { boxes := π.boxes.filter p, le_of_mem' := λ J hJ, π.le_of_mem (mem_filter.1 hJ).1, pairwise_disjoint := λ J₁ h₁ J₂ h₂, π.disjoint_coe_of_mem (mem_filter.1 h₁).1 (mem_filter.1 h₂).1 } @[simp] lemma mem_filter {p : box ι → Prop} : J ∈ π.filter p ↔ J ∈ π ∧ p J := finset.mem_filter lemma filter_le (π : prepartition I) (p : box ι → Prop) : π.filter p ≤ π := λ J hJ, let ⟨hπ, hp⟩ := π.mem_filter.1 hJ in ⟨J, hπ, le_rfl⟩ lemma filter_of_true {p : box ι → Prop} (hp : ∀ J ∈ π, p J) : π.filter p = π := by { ext J, simpa using hp J } @[simp] lemma filter_true : π.filter (λ _, true) = π := π.filter_of_true (λ _ _, trivial) @[simp] lemma Union_filter_not (π : prepartition I) (p : box ι → Prop) : (π.filter (λ J, ¬p J)).Union = π.Union \ (π.filter p).Union := begin simp only [prepartition.Union], convert (@set.bUnion_diff_bUnion_eq _ (box ι) π.boxes (π.filter p).boxes coe _).symm, { ext J x, simp { contextual := tt } }, { convert π.pairwise_disjoint, simp } end lemma sum_fiberwise {α M} [add_comm_monoid M] (π : prepartition I) (f : box ι → α) (g : box ι → M) : ∑ y in π.boxes.image f, ∑ J in (π.filter (λ J, f J = y)).boxes, g J = ∑ J in π.boxes, g J := by convert sum_fiberwise_of_maps_to (λ _, finset.mem_image_of_mem f) g /-- Union of two disjoint prepartitions. -/ @[simps] def disj_union (π₁ π₂ : prepartition I) (h : disjoint π₁.Union π₂.Union) : prepartition I := { boxes := π₁.boxes ∪ π₂.boxes, le_of_mem' := λ J hJ, (finset.mem_union.1 hJ).elim π₁.le_of_mem π₂.le_of_mem, pairwise_disjoint := suffices ∀ (J₁ ∈ π₁) (J₂ ∈ π₂), J₁ ≠ J₂ → disjoint (J₁ : set (ι → ℝ)) J₂, by simpa [pairwise_union_of_symmetric (symmetric_disjoint.comap _), pairwise_disjoint], λ J₁ h₁ J₂ h₂ _, h.mono (π₁.subset_Union h₁) (π₂.subset_Union h₂) } @[simp] lemma mem_disj_union (H : disjoint π₁.Union π₂.Union) : J ∈ π₁.disj_union π₂ H ↔ J ∈ π₁ ∨ J ∈ π₂ := finset.mem_union @[simp] lemma Union_disj_union (h : disjoint π₁.Union π₂.Union) : (π₁.disj_union π₂ h).Union = π₁.Union ∪ π₂.Union := by simp [disj_union, prepartition.Union, Union_or, Union_union_distrib] @[simp] lemma sum_disj_union_boxes {M : Type*} [add_comm_monoid M] (h : disjoint π₁.Union π₂.Union) (f : box ι → M) : ∑ J in π₁.boxes ∪ π₂.boxes, f J = ∑ J in π₁.boxes, f J + ∑ J in π₂.boxes, f J := sum_union $ disjoint_boxes_of_disjoint_Union h section distortion variable [fintype ι] /-- The distortion of a prepartition is the maximum of the distortions of the boxes of this prepartition. -/ def distortion : ℝ≥0 := π.boxes.sup box.distortion lemma distortion_le_of_mem (h : J ∈ π) : J.distortion ≤ π.distortion := le_sup h lemma distortion_le_iff {c : ℝ≥0} : π.distortion ≤ c ↔ ∀ J ∈ π, box.distortion J ≤ c := sup_le_iff lemma distortion_bUnion (π : prepartition I) (πi : Π J, prepartition J) : (π.bUnion πi).distortion = π.boxes.sup (λ J, (πi J).distortion) := sup_bUnion _ _ @[simp] lemma distortion_disj_union (h : disjoint π₁.Union π₂.Union) : (π₁.disj_union π₂ h).distortion = max π₁.distortion π₂.distortion := sup_union lemma distortion_of_const {c} (h₁ : π.boxes.nonempty) (h₂ : ∀ J ∈ π, box.distortion J = c) : π.distortion = c := (sup_congr rfl h₂).trans (sup_const h₁ _) @[simp] lemma distortion_top (I : box ι) : distortion (⊤ : prepartition I) = I.distortion := sup_singleton @[simp] lemma distortion_bot (I : box ι) : distortion (⊥ : prepartition I) = 0 := sup_empty end distortion /-- A prepartition `π` of `I` is a partition if the boxes of `π` cover the whole `I`. -/ def is_partition (π : prepartition I) := ∀ x ∈ I, ∃ J ∈ π, x ∈ J lemma is_partition_iff_Union_eq {π : prepartition I} : π.is_partition ↔ π.Union = I := by simp_rw [is_partition, set.subset.antisymm_iff, π.Union_subset, true_and, set.subset_def, mem_Union, box.mem_coe] @[simp] lemma is_partition_single_iff (h : J ≤ I) : is_partition (single I J h) ↔ J = I := by simp [is_partition_iff_Union_eq] lemma is_partition_top (I : box ι) : is_partition (⊤ : prepartition I) := λ x hx, ⟨I, mem_top.2 rfl, hx⟩ namespace is_partition variables {π} lemma Union_eq (h : π.is_partition) : π.Union = I := is_partition_iff_Union_eq.1 h lemma Union_subset (h : π.is_partition) (π₁ : prepartition I) : π₁.Union ⊆ π.Union := h.Union_eq.symm ▸ π₁.Union_subset protected lemma exists_unique (h : π.is_partition) (hx : x ∈ I) : ∃! J ∈ π, x ∈ J := begin rcases h x hx with ⟨J, h, hx⟩, exact exists_unique.intro2 J h hx (λ J' h' hx', π.eq_of_mem_of_mem h' h hx' hx), end lemma nonempty_boxes (h : π.is_partition) : π.boxes.nonempty := let ⟨J, hJ, _⟩ := h _ I.upper_mem in ⟨J, hJ⟩ lemma eq_of_boxes_subset (h₁ : π₁.is_partition) (h₂ : π₁.boxes ⊆ π₂.boxes) : π₁ = π₂ := eq_of_boxes_subset_Union_superset h₂ $ h₁.Union_subset _ lemma le_iff (h : π₂.is_partition) : π₁ ≤ π₂ ↔ ∀ (J ∈ π₁) (J' ∈ π₂), (J ∩ J' : set (ι → ℝ)).nonempty → J ≤ J' := le_iff_nonempty_imp_le_and_Union_subset.trans $ and_iff_left $ h.Union_subset _ protected lemma bUnion (h : is_partition π) (hi : ∀ J ∈ π, is_partition (πi J)) : is_partition (π.bUnion πi) := λ x hx, let ⟨J, hJ, hxi⟩ := h x hx, ⟨Ji, hJi, hx⟩ := hi J hJ x hxi in ⟨Ji, π.mem_bUnion.2 ⟨J, hJ, hJi⟩, hx⟩ protected lemma restrict (h : is_partition π) (hJ : J ≤ I) : is_partition (π.restrict J) := is_partition_iff_Union_eq.2 $ by simp [h.Union_eq, hJ] protected lemma inf (h₁ : is_partition π₁) (h₂ : is_partition π₂) : is_partition (π₁ ⊓ π₂) := is_partition_iff_Union_eq.2 $ by simp [h₁.Union_eq, h₂.Union_eq] end is_partition lemma Union_bUnion_partition (h : ∀ J ∈ π, (πi J).is_partition) : (π.bUnion πi).Union = π.Union := (Union_bUnion _ _).trans $ Union_congr id surjective_id $ λ J, Union_congr id surjective_id $ λ hJ, (h J hJ).Union_eq lemma is_partition_disj_union_of_eq_diff (h : π₂.Union = I \ π₁.Union) : is_partition (π₁.disj_union π₂ (h.symm ▸ disjoint_diff)) := is_partition_iff_Union_eq.2 $ (Union_disj_union _).trans $ by simp [h, π₁.Union_subset] end prepartition end box_integral
2d00ccc77426566ae45e592b7cbcc1923b82b339
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/doc/examples/ICERM2022/ctor.lean
fa7fdd8b8df3e4ff16851713e5bb508adb4be854
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
leanprover/lean4
4bdf9790294964627eb9be79f5e8f6157780b4cc
f1f9dc0f2f531af3312398999d8b8303fa5f096b
refs/heads/master
1,693,360,665,786
1,693,350,868,000
1,693,350,868,000
129,571,436
2,827
311
Apache-2.0
1,694,716,156,000
1,523,760,560,000
Lean
UTF-8
Lean
false
false
1,292
lean
import Lean open Lean Meta def ctor (mvarId : MVarId) (idx : Nat) : MetaM (List MVarId) := do /- Set `MetaM` context using `mvarId` -/ withMVarContext mvarId do /- Fail if the metavariable is already assigned. -/ checkNotAssigned mvarId `ctor /- Retrieve the target type, instantiateMVars, and use `whnf`. -/ let target ← getMVarType' mvarId let .const declName us := target.getAppFn | throwTacticEx `ctor mvarId "target is not an inductive datatype" let .inductInfo { ctors, .. } ← getConstInfo declName | throwTacticEx `ctor mvarId "target is not an inductive datatype" if idx = 0 then throwTacticEx `ctor mvarId "invalid index, it must be > 0" else if h : idx - 1 < ctors.length then apply mvarId (.const ctors[idx - 1] us) else throwTacticEx `ctor mvarId "invalid index, inductive datatype has only {ctors.length} contructors" open Elab Tactic elab "ctor" idx:num : tactic => liftMetaTactic (ctor · idx.getNat) example (p : Prop) : p := by ctor 1 -- Error example (h : q) : p ∨ q := by ctor 0 -- Error exact h example (h : q) : p ∨ q := by ctor 3 -- Error exact h example (h : q) : p ∨ q := by ctor 2 exact h example (h : q) : p ∨ q := by ctor 1 exact h -- Error
bb90bbb25fbfc2a296baa05a7f5f56e271280ab5
367134ba5a65885e863bdc4507601606690974c1
/src/number_theory/sum_four_squares.lean
49c3522a0e576017a8fdc7dce9f47aa25a1f6518
[ "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
11,899
lean
/- Copyright (c) 2019 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes -/ import algebra.group_power.identities import data.zmod.basic import field_theory.finite.basic import data.int.parity import data.fintype.card /-! # Lagrange's four square theorem The main result in this file is `sum_four_squares`, a proof that every natural number is the sum of four square numbers. ## Implementation Notes The proof used is close to Lagrange's original proof. -/ open finset polynomial finite_field equiv open_locale big_operators namespace int lemma sum_two_squares_of_two_mul_sum_two_squares {m x y : ℤ} (h : 2 * m = x^2 + y^2) : m = ((x - y) / 2) ^ 2 + ((x + y) / 2) ^ 2 := have even (x^2 + y^2), by simp [h.symm, even_mul], have hxaddy : even (x + y), by simpa [pow_two] with parity_simps, have hxsuby : even (x - y), by simpa [pow_two] with parity_simps, (mul_right_inj' (show (2*2 : ℤ) ≠ 0, from dec_trivial)).1 $ calc 2 * 2 * m = (x - y)^2 + (x + y)^2 : by rw [mul_assoc, h]; ring ... = (2 * ((x - y) / 2))^2 + (2 * ((x + y) / 2))^2 : by rw [int.mul_div_cancel' hxsuby, int.mul_div_cancel' hxaddy] ... = 2 * 2 * (((x - y) / 2) ^ 2 + ((x + y) / 2) ^ 2) : by simp [mul_add, pow_succ, mul_comm, mul_assoc, mul_left_comm] lemma exists_sum_two_squares_add_one_eq_k (p : ℕ) [hp : fact p.prime] : ∃ (a b : ℤ) (k : ℕ), a^2 + b^2 + 1 = k * p ∧ k < p := hp.eq_two_or_odd.elim (λ hp2, hp2.symm ▸ ⟨1, 0, 1, rfl, dec_trivial⟩) $ λ hp1, let ⟨a, b, hab⟩ := zmod.sum_two_squares p (-1) in have hab' : (p : ℤ) ∣ a.val_min_abs ^ 2 + b.val_min_abs ^ 2 + 1, from (char_p.int_cast_eq_zero_iff (zmod p) p _).1 $ by simpa [eq_neg_iff_add_eq_zero] using hab, let ⟨k, hk⟩ := hab' in have hk0 : 0 ≤ k, from nonneg_of_mul_nonneg_left (by rw ← hk; exact (add_nonneg (add_nonneg (pow_two_nonneg _) (pow_two_nonneg _)) zero_le_one)) (int.coe_nat_pos.2 hp.pos), ⟨a.val_min_abs, b.val_min_abs, k.nat_abs, by rw [hk, int.nat_abs_of_nonneg hk0, mul_comm], lt_of_mul_lt_mul_left (calc p * k.nat_abs = a.val_min_abs.nat_abs ^ 2 + b.val_min_abs.nat_abs ^ 2 + 1 : by rw [← int.coe_nat_inj', int.coe_nat_add, int.coe_nat_add, int.coe_nat_pow, int.coe_nat_pow, int.nat_abs_pow_two, int.nat_abs_pow_two, int.coe_nat_one, hk, int.coe_nat_mul, int.nat_abs_of_nonneg hk0] ... ≤ (p / 2) ^ 2 + (p / 2)^2 + 1 : add_le_add (add_le_add (nat.pow_le_pow_of_le_left (zmod.nat_abs_val_min_abs_le _) _) (nat.pow_le_pow_of_le_left (zmod.nat_abs_val_min_abs_le _) _)) (le_refl _) ... < (p / 2) ^ 2 + (p / 2)^ 2 + (p % 2)^2 + ((2 * (p / 2)^2 + (4 * (p / 2) * (p % 2)))) : by rw [hp1, one_pow, mul_one]; exact (lt_add_iff_pos_right _).2 (add_pos_of_nonneg_of_pos (nat.zero_le _) (mul_pos dec_trivial (nat.div_pos hp.two_le dec_trivial))) ... = p * p : by { conv_rhs { rw [← nat.mod_add_div p 2] }, ring }) (show 0 ≤ p, from nat.zero_le _)⟩ end int namespace nat open int open_locale classical private lemma sum_four_squares_of_two_mul_sum_four_squares {m a b c d : ℤ} (h : a^2 + b^2 + c^2 + d^2 = 2 * m) : ∃ w x y z : ℤ, w^2 + x^2 + y^2 + z^2 = m := have ∀ f : fin 4 → zmod 2, (f 0)^2 + (f 1)^2 + (f 2)^2 + (f 3)^2 = 0 → ∃ i : (fin 4), (f i)^2 + f (swap i 0 1)^2 = 0 ∧ f (swap i 0 2)^2 + f (swap i 0 3)^2 = 0, from dec_trivial, let f : fin 4 → ℤ := vector.nth (a ::ᵥ b ::ᵥ c ::ᵥ d ::ᵥ vector.nil) in let ⟨i, hσ⟩ := this (coe ∘ f) (by rw [← @zero_mul (zmod 2) _ m, ← show ((2 : ℤ) : zmod 2) = 0, from rfl, ← int.cast_mul, ← h]; simp only [int.cast_add, int.cast_pow]; refl) in let σ := swap i 0 in have h01 : 2 ∣ f (σ 0) ^ 2 + f (σ 1) ^ 2, from (char_p.int_cast_eq_zero_iff (zmod 2) 2 _).1 $ by simpa [σ] using hσ.1, have h23 : 2 ∣ f (σ 2) ^ 2 + f (σ 3) ^ 2, from (char_p.int_cast_eq_zero_iff (zmod 2) 2 _).1 $ by simpa using hσ.2, let ⟨x, hx⟩ := h01 in let ⟨y, hy⟩ := h23 in ⟨(f (σ 0) - f (σ 1)) / 2, (f (σ 0) + f (σ 1)) / 2, (f (σ 2) - f (σ 3)) / 2, (f (σ 2) + f (σ 3)) / 2, begin rw [← int.sum_two_squares_of_two_mul_sum_two_squares hx.symm, add_assoc, ← int.sum_two_squares_of_two_mul_sum_two_squares hy.symm, ← mul_right_inj' (show (2 : ℤ) ≠ 0, from dec_trivial), ← h, mul_add, ← hx, ← hy], have : ∑ x, f (σ x)^2 = ∑ x, f x^2, { conv_rhs { rw ← σ.sum_comp } }, have fin4univ : (univ : finset (fin 4)).1 = 0 ::ₘ 1 ::ₘ 2 ::ₘ 3 ::ₘ 0, from dec_trivial, simpa [finset.sum_eq_multiset_sum, fin4univ, multiset.sum_cons, f, add_assoc] end⟩ private lemma prime_sum_four_squares (p : ℕ) [hp : _root_.fact p.prime] : ∃ a b c d : ℤ, a^2 + b^2 + c^2 + d^2 = p := have hm : ∃ m < p, 0 < m ∧ ∃ a b c d : ℤ, a^2 + b^2 + c^2 + d^2 = m * p, from let ⟨a, b, k, hk⟩ := exists_sum_two_squares_add_one_eq_k p in ⟨k, hk.2, nat.pos_of_ne_zero $ (λ hk0, by { rw [hk0, int.coe_nat_zero, zero_mul] at hk, exact ne_of_gt (show a^2 + b^2 + 1 > 0, from add_pos_of_nonneg_of_pos (add_nonneg (pow_two_nonneg _) (pow_two_nonneg _)) zero_lt_one) hk.1 }), a, b, 1, 0, by simpa [pow_two] using hk.1⟩, let m := nat.find hm in let ⟨a, b, c, d, (habcd : a^2 + b^2 + c^2 + d^2 = m * p)⟩ := (nat.find_spec hm).snd.2 in by haveI hm0 : _root_.fact (0 < m) := (nat.find_spec hm).snd.1; exact have hmp : m < p, from (nat.find_spec hm).fst, m.mod_two_eq_zero_or_one.elim (λ hm2 : m % 2 = 0, let ⟨k, hk⟩ := (nat.dvd_iff_mod_eq_zero _ _).2 hm2 in have hk0 : 0 < k, from nat.pos_of_ne_zero $ λ _, by { simp [*, lt_irrefl] at * }, have hkm : k < m, { rw [hk, two_mul], exact (lt_add_iff_pos_left _).2 hk0 }, false.elim $ nat.find_min hm hkm ⟨lt_trans hkm hmp, hk0, sum_four_squares_of_two_mul_sum_four_squares (show a^2 + b^2 + c^2 + d^2 = 2 * (k * p), by { rw [habcd, hk, int.coe_nat_mul, mul_assoc], simp })⟩) (λ hm2 : m % 2 = 1, if hm1 : m = 1 then ⟨a, b, c, d, by simp only [hm1, habcd, int.coe_nat_one, one_mul]⟩ else let w := (a : zmod m).val_min_abs, x := (b : zmod m).val_min_abs, y := (c : zmod m).val_min_abs, z := (d : zmod m).val_min_abs in have hnat_abs : w^2 + x^2 + y^2 + z^2 = (w.nat_abs^2 + x.nat_abs^2 + y.nat_abs ^2 + z.nat_abs ^ 2 : ℕ), by simp [pow_two], have hwxyzlt : w^2 + x^2 + y^2 + z^2 < m^2, from calc w^2 + x^2 + y^2 + z^2 = (w.nat_abs^2 + x.nat_abs^2 + y.nat_abs ^2 + z.nat_abs ^ 2 : ℕ) : hnat_abs ... ≤ ((m / 2) ^ 2 + (m / 2) ^ 2 + (m / 2) ^ 2 + (m / 2) ^ 2 : ℕ) : int.coe_nat_le.2 $ add_le_add (add_le_add (add_le_add (nat.pow_le_pow_of_le_left (zmod.nat_abs_val_min_abs_le _) _) (nat.pow_le_pow_of_le_left (zmod.nat_abs_val_min_abs_le _) _)) (nat.pow_le_pow_of_le_left (zmod.nat_abs_val_min_abs_le _) _)) (nat.pow_le_pow_of_le_left (zmod.nat_abs_val_min_abs_le _) _) ... = 4 * (m / 2 : ℕ) ^ 2 : by simp [pow_two, bit0, bit1, mul_add, add_mul, add_assoc] ... < 4 * (m / 2 : ℕ) ^ 2 + ((4 * (m / 2) : ℕ) * (m % 2 : ℕ) + (m % 2 : ℕ)^2) : (lt_add_iff_pos_right _).2 (by { rw [hm2, int.coe_nat_one, one_pow, mul_one], exact add_pos_of_nonneg_of_pos (int.coe_nat_nonneg _) zero_lt_one }) ... = m ^ 2 : by { conv_rhs {rw [← nat.mod_add_div m 2]}, simp [-nat.mod_add_div, mul_add, add_mul, bit0, bit1, mul_comm, mul_assoc, mul_left_comm, pow_add, add_comm, add_left_comm] }, have hwxyzabcd : ((w^2 + x^2 + y^2 + z^2 : ℤ) : zmod m) = ((a^2 + b^2 + c^2 + d^2 : ℤ) : zmod m), by simp [w, x, y, z, pow_two], have hwxyz0 : ((w^2 + x^2 + y^2 + z^2 : ℤ) : zmod m) = 0, by rw [hwxyzabcd, habcd, int.cast_mul, cast_coe_nat, zmod.nat_cast_self, zero_mul], let ⟨n, hn⟩ := ((char_p.int_cast_eq_zero_iff _ m _).1 hwxyz0) in have hn0 : 0 < n.nat_abs, from int.nat_abs_pos_of_ne_zero (λ hn0, have hwxyz0 : (w.nat_abs^2 + x.nat_abs^2 + y.nat_abs^2 + z.nat_abs^2 : ℕ) = 0, by { rw [← int.coe_nat_eq_zero, ← hnat_abs], rwa [hn0, mul_zero] at hn }, have habcd0 : (m : ℤ) ∣ a ∧ (m : ℤ) ∣ b ∧ (m : ℤ) ∣ c ∧ (m : ℤ) ∣ d, by simpa [@add_eq_zero_iff_eq_zero_of_nonneg ℤ _ _ _ (pow_two_nonneg _) (pow_two_nonneg _), pow_two, w, x, y, z, (char_p.int_cast_eq_zero_iff _ m _), and.assoc] using hwxyz0, let ⟨ma, hma⟩ := habcd0.1, ⟨mb, hmb⟩ := habcd0.2.1, ⟨mc, hmc⟩ := habcd0.2.2.1, ⟨md, hmd⟩ := habcd0.2.2.2 in have hmdvdp : m ∣ p, from int.coe_nat_dvd.1 ⟨ma^2 + mb^2 + mc^2 + md^2, (mul_right_inj' (show (m : ℤ) ≠ 0, from int.coe_nat_ne_zero_iff_pos.2 hm0)).1 $ by { rw [← habcd, hma, hmb, hmc, hmd], ring }⟩, (hp.2 _ hmdvdp).elim hm1 (λ hmeqp, by simpa [lt_irrefl, hmeqp] using hmp)), have hawbxcydz : ((m : ℕ) : ℤ) ∣ a * w + b * x + c * y + d * z, from (char_p.int_cast_eq_zero_iff (zmod m) m _).1 $ by { rw [← hwxyz0], simp, ring }, have haxbwczdy : ((m : ℕ) : ℤ) ∣ a * x - b * w - c * z + d * y, from (char_p.int_cast_eq_zero_iff (zmod m) m _).1 $ by { simp [sub_eq_add_neg], ring }, have haybzcwdx : ((m : ℕ) : ℤ) ∣ a * y + b * z - c * w - d * x, from (char_p.int_cast_eq_zero_iff (zmod m) m _).1 $ by { simp [sub_eq_add_neg], ring }, have hazbycxdw : ((m : ℕ) : ℤ) ∣ a * z - b * y + c * x - d * w, from (char_p.int_cast_eq_zero_iff (zmod m) m _).1 $ by { simp [sub_eq_add_neg], ring }, let ⟨s, hs⟩ := hawbxcydz, ⟨t, ht⟩ := haxbwczdy, ⟨u, hu⟩ := haybzcwdx, ⟨v, hv⟩ := hazbycxdw in have hn_nonneg : 0 ≤ n, from nonneg_of_mul_nonneg_left (by { erw [← hn], repeat {try {refine add_nonneg _ _}, try {exact pow_two_nonneg _}} }) (int.coe_nat_pos.2 hm0), have hnm : n.nat_abs < m, from int.coe_nat_lt.1 (lt_of_mul_lt_mul_left (by { rw [int.nat_abs_of_nonneg hn_nonneg, ← hn, ← pow_two], exact hwxyzlt }) (int.coe_nat_nonneg m)), have hstuv : s^2 + t^2 + u^2 + v^2 = n.nat_abs * p, from (mul_right_inj' (show (m^2 : ℤ) ≠ 0, from pow_ne_zero 2 (int.coe_nat_ne_zero_iff_pos.2 hm0))).1 $ calc (m : ℤ)^2 * (s^2 + t^2 + u^2 + v^2) = ((m : ℕ) * s)^2 + ((m : ℕ) * t)^2 + ((m : ℕ) * u)^2 + ((m : ℕ) * v)^2 : by { simp [mul_pow], ring } ... = (w^2 + x^2 + y^2 + z^2) * (a^2 + b^2 + c^2 + d^2) : by { simp only [hs.symm, ht.symm, hu.symm, hv.symm], ring } ... = _ : by { rw [hn, habcd, int.nat_abs_of_nonneg hn_nonneg], dsimp [m], ring }, false.elim $ nat.find_min hm hnm ⟨lt_trans hnm hmp, hn0, s, t, u, v, hstuv⟩) lemma sum_four_squares : ∀ n : ℕ, ∃ a b c d : ℕ, a^2 + b^2 + c^2 + d^2 = n | 0 := ⟨0, 0, 0, 0, rfl⟩ | 1 := ⟨1, 0, 0, 0, rfl⟩ | n@(k+2) := have hm : _root_.fact (min_fac (k+2)).prime := min_fac_prime dec_trivial, have n / min_fac n < n := factors_lemma, let ⟨a, b, c, d, h₁⟩ := show ∃ a b c d : ℤ, a^2 + b^2 + c^2 + d^2 = min_fac n, by exactI prime_sum_four_squares (min_fac (k+2)) in let ⟨w, x, y, z, h₂⟩ := sum_four_squares (n / min_fac n) in ⟨(a * w - b * x - c * y - d * z).nat_abs, (a * x + b * w + c * z - d * y).nat_abs, (a * y - b * z + c * w + d * x).nat_abs, (a * z + b * y - c * x + d * w).nat_abs, begin rw [← int.coe_nat_inj', ← nat.mul_div_cancel' (min_fac_dvd (k+2)), int.coe_nat_mul, ← h₁, ← h₂], simp [sum_four_sq_mul_sum_four_sq], end⟩ end nat
108de06241ac3749576ec0a732c69ce31f221832
63abd62053d479eae5abf4951554e1064a4c45b4
/src/data/nat/dist.lean
7c2e8a276065cc7f5c834746b0c2d732d163a709
[ "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
4,017
lean
/- Copyright (c) 2014 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn, Jeremy Avigad Distance function on the natural numbers. -/ import data.nat.basic namespace nat /- distance -/ /-- Distance (absolute value of difference) between natural numbers. -/ def dist (n m : ℕ) := (n - m) + (m - n) theorem dist.def (n m : ℕ) : dist n m = (n - m) + (m - n) := rfl theorem dist_comm (n m : ℕ) : dist n m = dist m n := by simp [dist.def, add_comm] @[simp] theorem dist_self (n : ℕ) : dist n n = 0 := by simp [dist.def, nat.sub_self] theorem eq_of_dist_eq_zero {n m : ℕ} (h : dist n m = 0) : n = m := have n - m = 0, from eq_zero_of_add_eq_zero_right h, have n ≤ m, from nat.le_of_sub_eq_zero this, have m - n = 0, from eq_zero_of_add_eq_zero_left h, have m ≤ n, from nat.le_of_sub_eq_zero this, le_antisymm ‹n ≤ m› ‹m ≤ n› theorem dist_eq_zero {n m : ℕ} (h : n = m) : dist n m = 0 := begin rw [h, dist_self] end theorem dist_eq_sub_of_le {n m : ℕ} (h : n ≤ m) : dist n m = m - n := begin rw [dist.def, sub_eq_zero_of_le h, zero_add] end theorem dist_eq_sub_of_le_right {n m : ℕ} (h : m ≤ n) : dist n m = n - m := begin rw [dist_comm], apply dist_eq_sub_of_le h end theorem dist_zero_right (n : ℕ) : dist n 0 = n := eq.trans (dist_eq_sub_of_le_right (zero_le n)) (nat.sub_zero n) theorem dist_zero_left (n : ℕ) : dist 0 n = n := eq.trans (dist_eq_sub_of_le (zero_le n)) (nat.sub_zero n) theorem dist_add_add_right (n k m : ℕ) : dist (n + k) (m + k) = dist n m := calc dist (n + k) (m + k) = ((n + k) - (m + k)) + ((m + k)-(n + k)) : rfl ... = (n - m) + ((m + k) - (n + k)) : by rw nat.add_sub_add_right ... = (n - m) + (m - n) : by rw nat.add_sub_add_right theorem dist_add_add_left (k n m : ℕ) : dist (k + n) (k + m) = dist n m := begin rw [add_comm k n, add_comm k m], apply dist_add_add_right end theorem dist_eq_intro {n m k l : ℕ} (h : n + m = k + l) : dist n k = dist l m := calc dist n k = dist (n + m) (k + m) : by rw dist_add_add_right ... = dist (k + l) (k + m) : by rw h ... = dist l m : by rw dist_add_add_left protected theorem sub_lt_sub_add_sub (n m k : ℕ) : n - k ≤ (n - m) + (m - k) := or.elim (le_total k m) (assume : k ≤ m, begin rw ←nat.add_sub_assoc this, apply nat.sub_le_sub_right, apply nat.le_sub_add end) (assume : k ≥ m, begin rw [sub_eq_zero_of_le this, add_zero], apply nat.sub_le_sub_left, exact this end) theorem dist.triangle_inequality (n m k : ℕ) : dist n k ≤ dist n m + dist m k := have dist n m + dist m k = (n - m) + (m - k) + ((k - m) + (m - n)), by simp [dist.def, add_comm, add_left_comm], begin rw [this, dist.def], apply add_le_add, repeat { apply nat.sub_lt_sub_add_sub } end theorem dist_mul_right (n k m : ℕ) : dist (n * k) (m * k) = dist n m * k := by rw [dist.def, dist.def, right_distrib, nat.mul_sub_right_distrib, nat.mul_sub_right_distrib] theorem dist_mul_left (k n m : ℕ) : dist (k * n) (k * m) = k * dist n m := by rw [mul_comm k n, mul_comm k m, dist_mul_right, mul_comm] -- TODO(Jeremy): do when we have max and minx --theorem dist_eq_max_sub_min {i j : nat} : dist i j = (max i j) - min i j := --sorry /- or.elim (lt_or_ge i j) (assume : i < j, by rw [max_eq_right_of_lt this, min_eq_left_of_lt this, dist_eq_sub_of_lt this]) (assume : i ≥ j, by rw [max_eq_left this , min_eq_right this, dist_eq_sub_of_le_right this]) -/ theorem dist_succ_succ {i j : nat} : dist (succ i) (succ j) = dist i j := by simp [dist.def, succ_sub_succ] theorem dist_pos_of_ne {i j : nat} : i ≠ j → 0 < dist i j := assume hne, nat.lt_by_cases (assume : i < j, begin rw [dist_eq_sub_of_le (le_of_lt this)], apply nat.sub_pos_of_lt this end) (assume : i = j, by contradiction) (assume : i > j, begin rw [dist_eq_sub_of_le_right (le_of_lt this)], apply nat.sub_pos_of_lt this end) end nat
5e64a8634c83242072e5200cd574d352893b0131
8f0ea954c1cc4f4cda83826954d6186c68fc9536
/library/data/rat/basic.lean
c2ed324b64b21296b790651acc8c97c995282bed
[ "Apache-2.0" ]
permissive
piyush-kurur/lean
fb3cbd339dfa8c70c49559fbea88ac0d3102b8ca
a8db8bc61a0b00379b3d0be8ecaf0d0858dc82ee
refs/heads/master
1,594,387,140,961
1,457,548,608,000
1,457,909,538,000
53,615,930
0
0
null
1,457,642,939,000
1,457,642,939,000
null
UTF-8
Lean
false
false
24,025
lean
/- Copyright (c) 2014 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Jeremy Avigad The rational numbers as a field generated by the integers, defined as the usual quotient. -/ import data.int algebra.field open int quot eq.ops record prerat : Type := (num : ℤ) (denom : ℤ) (denom_pos : denom > 0) /- prerat: the representations of the rationals as integers num, denom, with denom > 0. note: names are not protected, because it is not expected that users will open prerat. -/ namespace prerat /- the equivalence relation -/ definition equiv (a b : prerat) : Prop := num a * denom b = num b * denom a infix ≡ := equiv theorem equiv.refl [refl] (a : prerat) : a ≡ a := rfl theorem equiv.symm [symm] {a b : prerat} (H : a ≡ b) : b ≡ a := !eq.symm H theorem num_eq_zero_of_equiv {a b : prerat} (H : a ≡ b) (na_zero : num a = 0) : num b = 0 := have num a * denom b = 0, from !zero_mul ▸ na_zero ▸ rfl, have num b * denom a = 0, from H ▸ this, show num b = 0, from or_resolve_left (eq_zero_or_eq_zero_of_mul_eq_zero this) (ne_of_gt (denom_pos a)) theorem num_pos_of_equiv {a b : prerat} (H : a ≡ b) (na_pos : num a > 0) : num b > 0 := have num a * denom b > 0, from mul_pos na_pos (denom_pos b), have num b * denom a > 0, from H ▸ this, show num b > 0, from pos_of_mul_pos_right this (le_of_lt (denom_pos a)) theorem num_neg_of_equiv {a b : prerat} (H : a ≡ b) (na_neg : num a < 0) : num b < 0 := have H₁ : num a * denom b = num b * denom a, from H, have num a * denom b < 0, from mul_neg_of_neg_of_pos na_neg (denom_pos b), have -(-num b * denom a) < 0, begin rewrite [neg_mul_eq_neg_mul, neg_neg, -H₁], exact this end, have -num b > 0, from pos_of_mul_pos_right (pos_of_neg_neg this) (le_of_lt (denom_pos a)), neg_of_neg_pos this theorem equiv_of_num_eq_zero {a b : prerat} (H1 : num a = 0) (H2 : num b = 0) : a ≡ b := by rewrite [↑equiv, H1, H2, *zero_mul] theorem equiv.trans [trans] {a b c : prerat} (H1 : a ≡ b) (H2 : b ≡ c) : a ≡ c := decidable.by_cases (suppose num b = 0, have num a = 0, from num_eq_zero_of_equiv (equiv.symm H1) `num b = 0`, have num c = 0, from num_eq_zero_of_equiv H2 `num b = 0`, equiv_of_num_eq_zero `num a = 0` `num c = 0`) (suppose num b ≠ 0, have H3 : num b * denom b ≠ 0, from mul_ne_zero this (ne_of_gt (denom_pos b)), have H4 : (num b * denom b) * (num a * denom c) = (num b * denom b) * (num c * denom a), from calc (num b * denom b) * (num a * denom c) = (num a * denom b) * (num b * denom c) : by rewrite [*mul.assoc, *mul.left_comm (num a), *mul.left_comm (num b)] ... = (num b * denom a) * (num b * denom c) : {H1} ... = (num b * denom a) * (num c * denom b) : {H2} ... = (num b * denom b) * (num c * denom a) : by rewrite [*mul.assoc, *mul.left_comm (denom a), *mul.left_comm (denom b), mul.comm (denom a)], eq_of_mul_eq_mul_left H3 H4) theorem equiv.is_equivalence : equivalence equiv := mk_equivalence equiv equiv.refl @equiv.symm @equiv.trans definition setoid : setoid prerat := setoid.mk equiv equiv.is_equivalence /- field operations -/ definition of_int (i : int) : prerat := prerat.mk i 1 !of_nat_succ_pos definition zero : prerat := of_int 0 definition one : prerat := of_int 1 private theorem mul_denom_pos (a b : prerat) : denom a * denom b > 0 := mul_pos (denom_pos a) (denom_pos b) definition add (a b : prerat) : prerat := prerat.mk (num a * denom b + num b * denom a) (denom a * denom b) (mul_denom_pos a b) definition mul (a b : prerat) : prerat := prerat.mk (num a * num b) (denom a * denom b) (mul_denom_pos a b) definition neg (a : prerat) : prerat := prerat.mk (- num a) (denom a) (denom_pos a) definition smul (a : ℤ) (b : prerat) (H : a > 0) : prerat := prerat.mk (a * num b) (a * denom b) (mul_pos H (denom_pos b)) theorem of_int_add (a b : ℤ) : of_int (a + b) ≡ add (of_int a) (of_int b) := by esimp [equiv, num, denom, one, add, of_int]; rewrite [*int.mul_one] theorem of_int_mul (a b : ℤ) : of_int (a * b) ≡ mul (of_int a) (of_int b) := !equiv.refl theorem of_int_neg (a : ℤ) : of_int (-a) ≡ neg (of_int a) := !equiv.refl theorem of_int.inj {a b : ℤ} : of_int a ≡ of_int b → a = b := by rewrite [↑of_int, ↑equiv, *mul_one]; intros; assumption definition inv : prerat → prerat | inv (prerat.mk nat.zero d dp) := zero | inv (prerat.mk (nat.succ n) d dp) := prerat.mk d (nat.succ n) !of_nat_succ_pos | inv (prerat.mk -[1+n] d dp) := prerat.mk (-d) (nat.succ n) !of_nat_succ_pos theorem equiv_zero_of_num_eq_zero {a : prerat} (H : num a = 0) : a ≡ zero := by rewrite [↑equiv, H, ↑zero, ↑num, ↑of_int, *zero_mul] theorem num_eq_zero_of_equiv_zero {a : prerat} : a ≡ zero → num a = 0 := by rewrite [↑equiv, ↑zero, ↑of_int, mul_one, zero_mul]; intro H; exact H theorem inv_zero {d : int} (dp : d > 0) : inv (mk nat.zero d dp) = zero := begin rewrite [↑inv, ▸*] end theorem inv_zero' : inv zero = zero := inv_zero (of_nat_succ_pos nat.zero) open nat theorem inv_of_pos {n d : int} (np : n > 0) (dp : d > 0) : inv (mk n d dp) ≡ mk d n np := obtain (n' : nat) (Hn' : n = of_nat n'), from exists_eq_of_nat (le_of_lt np), have (n' > nat.zero), from lt_of_of_nat_lt_of_nat (Hn' ▸ np), obtain (k : nat) (Hk : n' = nat.succ k), from nat.exists_eq_succ_of_lt this, have d * n = d * nat.succ k, by rewrite [Hn', Hk], Hn'⁻¹ ▸ (Hk⁻¹ ▸ this) theorem inv_neg {n d : int} (np : n > 0) (dp : d > 0) : inv (mk (-n) d dp) ≡ mk (-d) n np := obtain (n' : nat) (Hn' : n = of_nat n'), from exists_eq_of_nat (le_of_lt np), have (n' > nat.zero), from lt_of_of_nat_lt_of_nat (Hn' ▸ np), obtain (k : nat) (Hk : n' = nat.succ k), from nat.exists_eq_succ_of_lt this, have -d * n = -d * nat.succ k, by rewrite [Hn', Hk], have H3 : inv (mk -[1+k] d dp) ≡ mk (-d) n np, from this, have H4 : -[1+k] = -n, from calc -[1+k] = -(nat.succ k) : rfl ... = -n : by rewrite [Hk⁻¹, Hn'], H4 ▸ H3 theorem inv_of_neg {n d : int} (nn : n < 0) (dp : d > 0) : inv (mk n d dp) ≡ mk (-d) (-n) (neg_pos_of_neg nn) := have inv (mk (-(-n)) d dp) ≡ mk (-d) (-n) (neg_pos_of_neg nn), from inv_neg (neg_pos_of_neg nn) dp, !neg_neg ▸ this /- operations respect equiv -/ theorem add_equiv_add {a1 b1 a2 b2 : prerat} (eqv1 : a1 ≡ a2) (eqv2 : b1 ≡ b2) : add a1 b1 ≡ add a2 b2 := calc (num a1 * denom b1 + num b1 * denom a1) * (denom a2 * denom b2) = num a1 * denom a2 * denom b1 * denom b2 + num b1 * denom b2 * denom a1 * denom a2 : by rewrite [right_distrib, *mul.assoc, mul.left_comm (denom b1), mul.comm (denom b2), *mul.assoc] ... = num a2 * denom a1 * denom b1 * denom b2 + num b2 * denom b1 * denom a1 * denom a2 : by rewrite [↑equiv at *, eqv1, eqv2] ... = (num a2 * denom b2 + num b2 * denom a2) * (denom a1 * denom b1) : by rewrite [right_distrib, *mul.assoc, *mul.left_comm (denom b2), *mul.comm (denom b1), *mul.assoc, mul.left_comm (denom a2)] theorem mul_equiv_mul {a1 b1 a2 b2 : prerat} (eqv1 : a1 ≡ a2) (eqv2 : b1 ≡ b2) : mul a1 b1 ≡ mul a2 b2 := calc (num a1 * num b1) * (denom a2 * denom b2) = (num a1 * denom a2) * (num b1 * denom b2) : by rewrite [*mul.assoc, mul.left_comm (num b1)] ... = (num a2 * denom a1) * (num b2 * denom b1) : by rewrite [↑equiv at *, eqv1, eqv2] ... = (num a2 * num b2) * (denom a1 * denom b1) : by rewrite [*mul.assoc, mul.left_comm (num b2)] theorem neg_equiv_neg {a b : prerat} (eqv : a ≡ b) : neg a ≡ neg b := calc -num a * denom b = -(num a * denom b) : neg_mul_eq_neg_mul ... = -(num b * denom a) : {eqv} ... = -num b * denom a : neg_mul_eq_neg_mul theorem inv_equiv_inv : ∀{a b : prerat}, a ≡ b → inv a ≡ inv b | (mk an ad adp) (mk bn bd bdp) := assume H, lt.by_cases (assume an_neg : an < 0, have bn_neg : bn < 0, from num_neg_of_equiv H an_neg, calc inv (mk an ad adp) ≡ mk (-ad) (-an) (neg_pos_of_neg an_neg) : inv_of_neg an_neg adp ... ≡ mk (-bd) (-bn) (neg_pos_of_neg bn_neg) : by rewrite [↑equiv at *, ▸*, *neg_mul_neg, mul.comm ad, mul.comm bd, H] ... ≡ inv (mk bn bd bdp) : (inv_of_neg bn_neg bdp)⁻¹) (assume an_zero : an = 0, have bn_zero : bn = 0, from num_eq_zero_of_equiv H an_zero, eq.subst (calc inv (mk an ad adp) = inv (mk 0 ad adp) : {an_zero} ... = zero : inv_zero adp ... = inv (mk 0 bd bdp) : inv_zero bdp ... = inv (mk bn bd bdp) : bn_zero) !equiv.refl) (assume an_pos : an > 0, have bn_pos : bn > 0, from num_pos_of_equiv H an_pos, calc inv (mk an ad adp) ≡ mk ad an an_pos : inv_of_pos an_pos adp ... ≡ mk bd bn bn_pos : by rewrite [↑equiv at *, ▸*, mul.comm ad, mul.comm bd, H] ... ≡ inv (mk bn bd bdp) : (inv_of_pos bn_pos bdp)⁻¹) theorem smul_equiv {a : ℤ} {b : prerat} (H : a > 0) : smul a b H ≡ b := by esimp[equiv, smul]; rewrite[mul.assoc, mul.left_comm] /- properties -/ protected theorem add.comm (a b : prerat) : add a b ≡ add b a := by rewrite [↑add, ↑equiv, ▸*, add.comm, mul.comm (denom a)] protected theorem add.assoc (a b c : prerat) : add (add a b) c ≡ add a (add b c) := by rewrite [↑add, ↑equiv, ▸*, *(mul.comm (num c)), *(λy, mul.comm y (denom a)), *left_distrib, *right_distrib, *mul.assoc, *add.assoc] protected theorem add_zero (a : prerat) : add a zero ≡ a := by rewrite [↑add, ↑equiv, ↑zero, ↑of_int, ▸*, *mul_one, zero_mul, add_zero] protected theorem add_left_inv (a : prerat) : add (neg a) a ≡ zero := by rewrite [↑add, ↑equiv, ↑neg, ↑zero, ↑of_int, ▸*, -neg_mul_eq_neg_mul, add.left_inv, *zero_mul] protected theorem mul_comm (a b : prerat) : mul a b ≡ mul b a := by rewrite [↑mul, ↑equiv, mul.comm (num a), mul.comm (denom a)] protected theorem mul_assoc (a b c : prerat) : mul (mul a b) c ≡ mul a (mul b c) := by rewrite [↑mul, ↑equiv, *mul.assoc] protected theorem mul_one (a : prerat) : mul a one ≡ a := by rewrite [↑mul, ↑one, ↑of_int, ↑equiv, ▸*, *mul_one] protected theorem mul_left_distrib (a b c : prerat) : mul a (add b c) ≡ add (mul a b) (mul a c) := have H : smul (denom a) (mul a (add b c)) (denom_pos a) = add (mul a b) (mul a c), from begin rewrite[↑smul, ↑mul, ↑add], congruence, rewrite[*left_distrib, *right_distrib, -+(int.mul_assoc)], have T : ∀ {x y z w : ℤ}, x*y*z*w=y*z*x*w, from λx y z w, (!int.mul_assoc ⬝ !int.mul_comm) ▸ rfl, exact !congr_arg2 T T, rewrite [mul.left_comm (denom a) (denom b) (denom c)], rewrite int.mul_assoc end, equiv.symm (H ▸ smul_equiv (denom_pos a)) theorem mul_inv_cancel : ∀{a : prerat}, ¬ a ≡ zero → mul a (inv a) ≡ one | (mk an ad adp) := assume H, let a := mk an ad adp in lt.by_cases (assume an_neg : an < 0, let ia := mk (-ad) (-an) (neg_pos_of_neg an_neg) in calc mul a (inv a) ≡ mul a ia : mul_equiv_mul !equiv.refl (inv_of_neg an_neg adp) ... ≡ one : begin esimp [equiv, num, denom, one, mul, of_int], rewrite [*int.mul_one, *int.one_mul, mul.comm, neg_mul_comm] end) (assume an_zero : an = 0, absurd (equiv_zero_of_num_eq_zero an_zero) H) (assume an_pos : an > 0, let ia := mk ad an an_pos in calc mul a (inv a) ≡ mul a ia : mul_equiv_mul !equiv.refl (inv_of_pos an_pos adp) ... ≡ one : begin esimp [equiv, num, denom, one, mul, of_int], rewrite [*int.mul_one, *int.one_mul, mul.comm] end) theorem zero_not_equiv_one : ¬ zero ≡ one := begin esimp [equiv, zero, one, of_int], rewrite [zero_mul, int.mul_one], exact zero_ne_one end theorem mul_denom_equiv (a : prerat) : mul a (of_int (denom a)) ≡ of_int (num a) := by esimp [mul, of_int, equiv]; rewrite [*int.mul_one] /- Reducing a fraction to lowest terms. Needed to choose a canonical representative of rat, and define numerator and denominator. -/ definition reduce : prerat → prerat | (mk an ad adpos) := have pos : ad / gcd an ad > 0, from div_pos_of_pos_of_dvd adpos !gcd_nonneg !gcd_dvd_right, if an = 0 then prerat.zero else mk (an / gcd an ad) (ad / gcd an ad) pos protected theorem eq {a b : prerat} (Hn : num a = num b) (Hd : denom a = denom b) : a = b := begin cases a with [an, ad, adpos], cases b with [bn, bd, bdpos], generalize adpos, generalize bdpos, esimp at *, rewrite [Hn, Hd], intros, apply rfl end theorem reduce_equiv : ∀ a : prerat, reduce a ≡ a | (mk an ad adpos) := decidable.by_cases (assume anz : an = 0, begin rewrite [↑reduce, if_pos anz, ↑equiv, anz], krewrite zero_mul end) (assume annz : an ≠ 0, by rewrite [↑reduce, if_neg annz, ↑equiv, mul.comm, -!int.mul_div_assoc !gcd_dvd_left, -!int.mul_div_assoc !gcd_dvd_right, mul.comm]) theorem reduce_eq_reduce : ∀ {a b : prerat}, a ≡ b → reduce a = reduce b | (mk an ad adpos) (mk bn bd bdpos) := assume H : an * bd = bn * ad, decidable.by_cases (assume anz : an = 0, have H' : bn * ad = 0, by rewrite [-H, anz, zero_mul], have bnz : bn = 0, from or_resolve_left (eq_zero_or_eq_zero_of_mul_eq_zero H') (ne_of_gt adpos), by rewrite [↑reduce, if_pos anz, if_pos bnz]) (assume annz : an ≠ 0, have bnnz : bn ≠ 0, from assume bnz, have H' : an * bd = 0, by rewrite [H, bnz, zero_mul], have anz : an = 0, from or_resolve_left (eq_zero_or_eq_zero_of_mul_eq_zero H') (ne_of_gt bdpos), show false, from annz anz, begin rewrite [↑reduce, if_neg annz, if_neg bnnz], apply prerat.eq, {apply div_gcd_eq_div_gcd H adpos bdpos}, {esimp, rewrite [gcd.comm, gcd.comm bn], apply div_gcd_eq_div_gcd_of_nonneg, rewrite [mul.comm, -H, mul.comm], apply annz, apply bnnz, apply le_of_lt adpos, apply le_of_lt bdpos}, end) end prerat /- the rationals -/ definition rat : Type.{1} := quot prerat.setoid notation `ℚ` := rat local attribute prerat.setoid [instance] namespace rat /- operations -/ definition of_int [coercion] (i : ℤ) : ℚ := ⟦prerat.of_int i⟧ definition of_nat [coercion] (n : ℕ) : ℚ := n definition of_num [coercion] [reducible] (n : num) : ℚ := n protected definition prio := num.pred int.prio definition rat_has_zero [instance] [priority rat.prio] : has_zero rat := has_zero.mk (of_int 0) definition rat_has_one [instance] [priority rat.prio] : has_one rat := has_one.mk (of_int 1) theorem of_int_zero : of_int (0:int) = (0:rat) := rfl theorem of_int_one : of_int (1:int) = (1:rat) := rfl protected definition add : ℚ → ℚ → ℚ := quot.lift₂ (λ a b : prerat, ⟦prerat.add a b⟧) (take a1 a2 b1 b2, assume H1 H2, quot.sound (prerat.add_equiv_add H1 H2)) protected definition mul : ℚ → ℚ → ℚ := quot.lift₂ (λ a b : prerat, ⟦prerat.mul a b⟧) (take a1 a2 b1 b2, assume H1 H2, quot.sound (prerat.mul_equiv_mul H1 H2)) protected definition neg : ℚ → ℚ := quot.lift (λ a : prerat, ⟦prerat.neg a⟧) (take a1 a2, assume H, quot.sound (prerat.neg_equiv_neg H)) protected definition inv : ℚ → ℚ := quot.lift (λ a : prerat, ⟦prerat.inv a⟧) (take a1 a2, assume H, quot.sound (prerat.inv_equiv_inv H)) definition reduce : ℚ → prerat := quot.lift (λ a : prerat, prerat.reduce a) @prerat.reduce_eq_reduce definition num (a : ℚ) : ℤ := prerat.num (reduce a) definition denom (a : ℚ) : ℤ := prerat.denom (reduce a) theorem denom_pos (a : ℚ): denom a > 0 := prerat.denom_pos (reduce a) definition rat_has_add [instance] [priority rat.prio] : has_add rat := has_add.mk rat.add definition rat_has_mul [instance] [priority rat.prio] : has_mul rat := has_mul.mk rat.mul definition rat_has_neg [instance] [priority rat.prio] : has_neg rat := has_neg.mk rat.neg definition rat_has_inv [instance] [priority rat.prio] : has_inv rat := has_inv.mk rat.inv protected definition sub [reducible] (a b : ℚ) : rat := a + (-b) definition rat_has_sub [instance] [priority rat.prio] : has_sub rat := has_sub.mk rat.sub lemma sub.def (a b : ℚ) : a - b = a + (-b) := rfl /- properties -/ theorem of_int_add (a b : ℤ) : of_int (a + b) = of_int a + of_int b := quot.sound (prerat.of_int_add a b) theorem of_int_mul (a b : ℤ) : of_int (a * b) = of_int a * of_int b := quot.sound (prerat.of_int_mul a b) theorem of_int_neg (a : ℤ) : of_int (-a) = -(of_int a) := quot.sound (prerat.of_int_neg a) theorem of_int_sub (a b : ℤ) : of_int (a - b) = of_int a - of_int b := calc of_int (a - b) = of_int a + of_int (-b) : of_int_add ... = of_int a - of_int b : {of_int_neg b} theorem of_int.inj {a b : ℤ} (H : of_int a = of_int b) : a = b := prerat.of_int.inj (quot.exact H) theorem eq_of_of_int_eq_of_int {a b : ℤ} (H : of_int a = of_int b) : a = b := of_int.inj H theorem of_int_eq_of_int_iff (a b : ℤ) : of_int a = of_int b ↔ a = b := iff.intro eq_of_of_int_eq_of_int !congr_arg theorem of_nat_eq (a : ℕ) : of_nat a = of_int (int.of_nat a) := rfl open nat theorem of_nat_add (a b : ℕ) : of_nat (a + b) = of_nat a + of_nat b := by rewrite [of_nat_eq, int.of_nat_add, rat.of_int_add] theorem of_nat_mul (a b : ℕ) : of_nat (a * b) = of_nat a * of_nat b := by rewrite [of_nat_eq, int.of_nat_mul, rat.of_int_mul] theorem of_nat_sub {a b : ℕ} (H : a ≥ b) : of_nat (a - b) = of_nat a - of_nat b := begin rewrite of_nat_eq, rewrite [int.of_nat_sub H], rewrite [rat.of_int_sub] end theorem of_nat.inj {a b : ℕ} (H : of_nat a = of_nat b) : a = b := int.of_nat.inj (of_int.inj H) theorem eq_of_of_nat_eq_of_nat {a b : ℕ} (H : of_nat a = of_nat b) : a = b := of_nat.inj H theorem of_nat_eq_of_nat_iff (a b : ℕ) : of_nat a = of_nat b ↔ a = b := iff.intro of_nat.inj !congr_arg protected theorem add_comm (a b : ℚ) : a + b = b + a := quot.induction_on₂ a b (take u v, quot.sound !prerat.add.comm) protected theorem add_assoc (a b c : ℚ) : a + b + c = a + (b + c) := quot.induction_on₃ a b c (take u v w, quot.sound !prerat.add.assoc) protected theorem add_zero (a : ℚ) : a + 0 = a := quot.induction_on a (take u, quot.sound !prerat.add_zero) protected theorem zero_add (a : ℚ) : 0 + a = a := !rat.add_comm ▸ !rat.add_zero protected theorem add_left_inv (a : ℚ) : -a + a = 0 := quot.induction_on a (take u, quot.sound !prerat.add_left_inv) protected theorem mul_comm (a b : ℚ) : a * b = b * a := quot.induction_on₂ a b (take u v, quot.sound !prerat.mul_comm) protected theorem mul_assoc (a b c : ℚ) : a * b * c = a * (b * c) := quot.induction_on₃ a b c (take u v w, quot.sound !prerat.mul_assoc) protected theorem mul_one (a : ℚ) : a * 1 = a := quot.induction_on a (take u, quot.sound !prerat.mul_one) protected theorem one_mul (a : ℚ) : 1 * a = a := !rat.mul_comm ▸ !rat.mul_one protected theorem left_distrib (a b c : ℚ) : a * (b + c) = a * b + a * c := quot.induction_on₃ a b c (take u v w, quot.sound !prerat.mul_left_distrib) protected theorem right_distrib (a b c : ℚ) : (a + b) * c = a * c + b * c := by rewrite [rat.mul_comm, rat.left_distrib, *rat.mul_comm c] protected theorem mul_inv_cancel {a : ℚ} : a ≠ 0 → a * a⁻¹ = 1 := quot.induction_on a (take u, assume H, quot.sound (!prerat.mul_inv_cancel (assume H1, H (quot.sound H1)))) protected theorem inv_mul_cancel {a : ℚ} (H : a ≠ 0) : a⁻¹ * a = 1 := !rat.mul_comm ▸ rat.mul_inv_cancel H protected theorem zero_ne_one : (0 : ℚ) ≠ 1 := assume H, prerat.zero_not_equiv_one (quot.exact H) definition has_decidable_eq [instance] : decidable_eq ℚ := take a b, quot.rec_on_subsingleton₂ a b (take u v, if H : prerat.num u * prerat.denom v = prerat.num v * prerat.denom u then decidable.inl (quot.sound H) else decidable.inr (assume H1, H (quot.exact H1))) protected theorem inv_zero : inv 0 = (0 : ℚ) := quot.sound (prerat.inv_zero' ▸ !prerat.equiv.refl) theorem quot_reduce (a : ℚ) : ⟦reduce a⟧ = a := quot.induction_on a (take u, quot.sound !prerat.reduce_equiv) section local attribute rat [reducible] theorem mul_denom (a : ℚ) : a * denom a = num a := have H : ⟦reduce a⟧ * of_int (denom a) = of_int (num a), from quot.sound (!prerat.mul_denom_equiv), quot_reduce a ▸ H end theorem coprime_num_denom (a : ℚ) : coprime (num a) (denom a) := decidable.by_cases (suppose a = 0, by substvars) (quot.induction_on a (take u H, have H' : prerat.num u ≠ 0, from take H'', H (quot.sound (prerat.equiv_zero_of_num_eq_zero H'')), begin cases u with un ud udpos, rewrite [▸*, ↑num, ↑denom, ↑reduce, ↑prerat.reduce, if_neg H', ▸*], have gcd un ud ≠ 0, from ne_of_gt (!gcd_pos_of_ne_zero_left H'), apply coprime_div_gcd_div_gcd this end)) protected definition discrete_field [trans_instance] : discrete_field rat := ⦃discrete_field, add := rat.add, add_assoc := rat.add_assoc, zero := 0, zero_add := rat.zero_add, add_zero := rat.add_zero, neg := rat.neg, add_left_inv := rat.add_left_inv, add_comm := rat.add_comm, mul := rat.mul, mul_assoc := rat.mul_assoc, one := 1, one_mul := rat.one_mul, mul_one := rat.mul_one, left_distrib := rat.left_distrib, right_distrib := rat.right_distrib, mul_comm := rat.mul_comm, mul_inv_cancel := @rat.mul_inv_cancel, inv_mul_cancel := @rat.inv_mul_cancel, zero_ne_one := rat.zero_ne_one, inv_zero := rat.inv_zero, has_decidable_eq := has_decidable_eq⦄ definition rat_has_div [instance] [priority rat.prio] : has_div rat := has_div.mk has_div.div definition rat_has_pow_nat [instance] [priority rat.prio] : has_pow_nat rat := has_pow_nat.mk has_pow_nat.pow_nat theorem eq_num_div_denom (a : ℚ) : a = num a / denom a := have H : of_int (denom a) ≠ 0, from assume H', ne_of_gt (denom_pos a) (of_int.inj H'), iff.mpr (!eq_div_iff_mul_eq H) (mul_denom a) theorem of_int_div {a b : ℤ} (H : b ∣ a) : of_int (a / b) = of_int a / of_int b := decidable.by_cases (assume bz : b = 0, by rewrite [bz, int.div_zero, of_int_zero, div_zero]) (assume bnz : b ≠ 0, have bnz' : of_int b ≠ 0, from assume oibz, bnz (of_int.inj oibz), have H' : of_int (a / b) * of_int b = of_int a, from dvd.elim H (take c, assume Hc : a = b * c, by rewrite [Hc, !int.mul_div_cancel_left bnz, mul.comm]), iff.mpr (!eq_div_iff_mul_eq bnz') H') theorem of_nat_div {a b : ℕ} (H : b ∣ a) : of_nat (a / b) = of_nat a / of_nat b := have H' : (int.of_nat b ∣ int.of_nat a), by rewrite [int.of_nat_dvd_of_nat_iff]; exact H, by rewrite [of_nat_eq, int.of_nat_div, of_int_div H'] theorem of_int_pow (a : ℤ) (n : ℕ) : of_int (a^n) = (of_int a)^n := begin induction n with n ih, apply eq.refl, rewrite [pow_succ, pow_succ, of_int_mul, ih] end theorem of_nat_pow (a : ℕ) (n : ℕ) : of_nat (a^n) = (of_nat a)^n := by rewrite [of_nat_eq, int.of_nat_pow, of_int_pow] end rat
b6ded15b7905f2767b96e7df7f78ca930966c4dd
63abd62053d479eae5abf4951554e1064a4c45b4
/src/algebra/archimedean.lean
302382195edf134f6c7be978b3f56b8492c9355d
[ "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
11,732
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro Archimedean groups and fields. -/ import algebra.field_power import data.rat variables {α : Type*} /-- An ordered additive commutative monoid is called `archimedean` if for any two elements `x`, `y` such that `0 < y` there exists a natural number `n` such that `x ≤ n •ℕ y`. -/ class archimedean (α) [ordered_add_comm_monoid α] : Prop := (arch : ∀ (x : α) {y}, 0 < y → ∃ n : ℕ, x ≤ n •ℕ y) namespace linear_ordered_add_comm_group variables [linear_ordered_add_comm_group α] [archimedean α] /-- An archimedean decidable linearly ordered `add_comm_group` has a version of the floor: for `a > 0`, any `g` in the group lies between some two consecutive multiples of `a`. -/ lemma exists_int_smul_near_of_pos {a : α} (ha : 0 < a) (g : α) : ∃ k, k •ℤ a ≤ g ∧ g < (k + 1) •ℤ a := begin let s : set ℤ := {n : ℤ | n •ℤ a ≤ g}, obtain ⟨k, hk : -g ≤ k •ℕ a⟩ := archimedean.arch (-g) ha, have h_ne : s.nonempty := ⟨-k, by simpa using neg_le_neg hk⟩, obtain ⟨k, hk⟩ := archimedean.arch g ha, have h_bdd : ∀ n ∈ s, n ≤ (k : ℤ) := λ n hn, (gsmul_le_gsmul_iff ha).mp (le_trans hn hk : n •ℤ a ≤ k •ℤ a), obtain ⟨m, hm, hm'⟩ := int.exists_greatest_of_bdd ⟨k, h_bdd⟩ h_ne, refine ⟨m, hm, _⟩, by_contra H, linarith [hm' _ $ not_lt.mp H] end lemma exists_int_smul_near_of_pos' {a : α} (ha : 0 < a) (g : α) : ∃ k, 0 ≤ g - k •ℤ a ∧ g - k •ℤ a < a := begin obtain ⟨k, h1, h2⟩ := exists_int_smul_near_of_pos ha g, refine ⟨k, sub_nonneg.mpr h1, _⟩, have : g < k •ℤ a + 1 •ℤ a, by rwa ← add_gsmul a k 1, simpa [sub_lt_iff_lt_add'] end end linear_ordered_add_comm_group theorem exists_nat_gt [linear_ordered_semiring α] [archimedean α] (x : α) : ∃ n : ℕ, x < n := let ⟨n, h⟩ := archimedean.arch x zero_lt_one in ⟨n+1, lt_of_le_of_lt (by rwa ← nsmul_one) (nat.cast_lt.2 (nat.lt_succ_self _))⟩ theorem exists_nat_ge [linear_ordered_semiring α] [archimedean α] (x : α) : ∃ n : ℕ, x ≤ n := (exists_nat_gt x).imp $ λ n, le_of_lt lemma add_one_pow_unbounded_of_pos [linear_ordered_semiring α] [archimedean α] (x : α) {y : α} (hy : 0 < y) : ∃ n : ℕ, x < (y + 1) ^ n := let ⟨n, h⟩ := archimedean.arch x hy in ⟨n, calc x ≤ n •ℕ y : h ... < 1 + n •ℕ y : lt_one_add _ ... ≤ (1 + y) ^ n : one_add_mul_le_pow' (mul_nonneg (le_of_lt hy) (le_of_lt hy)) (le_of_lt $ lt_trans hy (lt_one_add y)) _ ... = (y + 1) ^ n : by rw [add_comm]⟩ section linear_ordered_ring variables [linear_ordered_ring α] [archimedean α] lemma pow_unbounded_of_one_lt (x : α) {y : α} (hy1 : 1 < y) : ∃ n : ℕ, x < y ^ n := sub_add_cancel y 1 ▸ add_one_pow_unbounded_of_pos _ (sub_pos.2 hy1) /-- Every x greater than or equal to 1 is between two successive natural-number powers of every y greater than one. -/ lemma exists_nat_pow_near {x : α} {y : α} (hx : 1 ≤ x) (hy : 1 < y) : ∃ n : ℕ, y ^ n ≤ x ∧ x < y ^ (n + 1) := have h : ∃ n : ℕ, x < y ^ n, from pow_unbounded_of_one_lt _ hy, by classical; exact let n := nat.find h in have hn : x < y ^ n, from nat.find_spec h, have hnp : 0 < n, from nat.pos_iff_ne_zero.2 (λ hn0, by rw [hn0, pow_zero] at hn; exact (not_le_of_gt hn hx)), have hnsp : nat.pred n + 1 = n, from nat.succ_pred_eq_of_pos hnp, have hltn : nat.pred n < n, from nat.pred_lt (ne_of_gt hnp), ⟨nat.pred n, le_of_not_lt (nat.find_min h hltn), by rwa hnsp⟩ theorem exists_int_gt (x : α) : ∃ n : ℤ, x < n := let ⟨n, h⟩ := exists_nat_gt x in ⟨n, by rwa ← coe_coe⟩ theorem exists_int_lt (x : α) : ∃ n : ℤ, (n : α) < x := let ⟨n, h⟩ := exists_int_gt (-x) in ⟨-n, by rw int.cast_neg; exact neg_lt.1 h⟩ theorem exists_floor (x : α) : ∃ (fl : ℤ), ∀ (z : ℤ), z ≤ fl ↔ (z : α) ≤ x := begin haveI := classical.prop_decidable, have : ∃ (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⟩), refine this.imp (λ fl h z, _), cases h with h₁ h₂, exact ⟨λ h, le_trans (int.cast_le.2 h) h₁, h₂ z⟩, end end linear_ordered_ring section linear_ordered_field /-- Every positive x is between two successive integer powers of another y greater than one. This is the same as `exists_int_pow_near'`, but with ≤ and < the other way around. -/ lemma exists_int_pow_near [linear_ordered_field α] [archimedean α] {x : α} {y : α} (hx : 0 < x) (hy : 1 < y) : ∃ n : ℤ, y ^ n ≤ x ∧ x < y ^ (n + 1) := by classical; exact let ⟨N, hN⟩ := pow_unbounded_of_one_lt x⁻¹ hy in have he: ∃ m : ℤ, y ^ m ≤ x, from ⟨-N, le_of_lt (by rw [(fpow_neg y (↑N))]; exact (inv_lt hx (lt_trans (inv_pos.2 hx) hN)).1 hN)⟩, let ⟨M, hM⟩ := pow_unbounded_of_one_lt x hy in have hb: ∃ b : ℤ, ∀ m, y ^ m ≤ x → m ≤ b, from ⟨M, λ m hm, le_of_not_lt (λ hlt, not_lt_of_ge (fpow_le_of_le (le_of_lt hy) (le_of_lt hlt)) (lt_of_le_of_lt hm hM))⟩, let ⟨n, hn₁, hn₂⟩ := int.exists_greatest_of_bdd hb he in ⟨n, hn₁, lt_of_not_ge (λ hge, not_le_of_gt (int.lt_succ _) (hn₂ _ hge))⟩ /-- Every positive x is between two successive integer powers of another y greater than one. This is the same as `exists_int_pow_near`, but with ≤ and < the other way around. -/ lemma exists_int_pow_near' [linear_ordered_field α] [archimedean α] {x : α} {y : α} (hx : 0 < x) (hy : 1 < y) : ∃ n : ℤ, y ^ n < x ∧ x ≤ y ^ (n + 1) := let ⟨m, hle, hlt⟩ := exists_int_pow_near (inv_pos.2 hx) hy in have hyp : 0 < y, from lt_trans zero_lt_one hy, ⟨-(m+1), by rwa [fpow_neg, inv_lt (fpow_pos_of_pos hyp _) hx], by rwa [neg_add, neg_add_cancel_right, fpow_neg, le_inv hx (fpow_pos_of_pos hyp _)]⟩ variables [linear_ordered_field α] [floor_ring α] lemma sub_floor_div_mul_nonneg (x : α) {y : α} (hy : 0 < y) : 0 ≤ x - ⌊x / y⌋ * y := begin conv in x {rw ← div_mul_cancel x (ne_of_lt hy).symm}, rw ← sub_mul, exact mul_nonneg (sub_nonneg.2 (floor_le _)) (le_of_lt hy) end lemma sub_floor_div_mul_lt (x : α) {y : α} (hy : 0 < y) : x - ⌊x / y⌋ * y < y := sub_lt_iff_lt_add.2 begin conv in y {rw ← one_mul y}, conv in x {rw ← div_mul_cancel x (ne_of_lt hy).symm}, rw ← add_mul, exact (mul_lt_mul_right hy).2 (by rw add_comm; exact lt_floor_add_one _), end end linear_ordered_field instance : archimedean ℕ := ⟨λ n m m0, ⟨n, by simpa only [mul_one, nat.nsmul_eq_mul] using nat.mul_le_mul_left n m0⟩⟩ instance : archimedean ℤ := ⟨λ n m m0, ⟨n.to_nat, le_trans (int.le_to_nat _) $ by simpa only [nsmul_eq_mul, int.nat_cast_eq_coe_nat, zero_add, mul_one] using mul_le_mul_of_nonneg_left (int.add_one_le_iff.2 m0) (int.coe_zero_le n.to_nat)⟩⟩ /-- A linear ordered archimedean ring is a floor ring. This is not an `instance` because in some cases we have a computable `floor` function. -/ noncomputable def archimedean.floor_ring (α) [linear_ordered_ring α] [archimedean α] : floor_ring α := { floor := λ x, classical.some (exists_floor x), le_floor := λ z x, classical.some_spec (exists_floor x) z } section linear_ordered_field variables [linear_ordered_field α] theorem archimedean_iff_nat_lt : archimedean α ↔ ∀ x : α, ∃ n : ℕ, x < n := ⟨@exists_nat_gt α _, λ H, ⟨λ x y y0, (H (x / y)).imp $ λ n h, le_of_lt $ by rwa [div_lt_iff y0, ← nsmul_eq_mul] at h⟩⟩ theorem archimedean_iff_nat_le : archimedean α ↔ ∀ x : α, ∃ n : ℕ, x ≤ n := archimedean_iff_nat_lt.trans ⟨λ H x, (H x).imp $ λ _, le_of_lt, λ H x, let ⟨n, h⟩ := H x in ⟨n+1, lt_of_le_of_lt h (nat.cast_lt.2 (lt_add_one _))⟩⟩ theorem exists_rat_gt [archimedean α] (x : α) : ∃ q : ℚ, x < q := let ⟨n, h⟩ := exists_nat_gt x in ⟨n, by rwa rat.cast_coe_nat⟩ theorem archimedean_iff_rat_lt : archimedean α ↔ ∀ x : α, ∃ q : ℚ, x < q := ⟨@exists_rat_gt α _, λ H, archimedean_iff_nat_lt.2 $ λ x, let ⟨q, h⟩ := H x in ⟨nat_ceil q, lt_of_lt_of_le h $ by simpa only [rat.cast_coe_nat] using (@rat.cast_le α _ _ _).2 (le_nat_ceil _)⟩⟩ theorem archimedean_iff_rat_le : archimedean α ↔ ∀ x : α, ∃ q : ℚ, x ≤ q := archimedean_iff_rat_lt.trans ⟨λ H x, (H x).imp $ λ _, le_of_lt, λ H x, let ⟨n, h⟩ := H x in ⟨n+1, lt_of_le_of_lt h (rat.cast_lt.2 (lt_add_one _))⟩⟩ variable [archimedean α] theorem exists_rat_lt (x : α) : ∃ q : ℚ, (q : α) < x := let ⟨n, h⟩ := exists_int_lt x in ⟨n, by rwa rat.cast_coe_int⟩ theorem exists_rat_btwn {x y : α} (h : x < y) : ∃ q : ℚ, x < q ∧ (q:α) < y := begin cases exists_nat_gt (y - x)⁻¹ with n nh, cases exists_floor (x * n) with z zh, refine ⟨(z + 1 : ℤ) / n, _⟩, have n0 := nat.cast_pos.1 (lt_trans (inv_pos.2 (sub_pos.2 h)) nh), have n0' := (@nat.cast_pos α _ _).2 n0, rw [rat.cast_div_of_ne_zero, rat.cast_coe_nat, rat.cast_coe_int, div_lt_iff n0'], refine ⟨(lt_div_iff n0').2 $ (lt_iff_lt_of_le_iff_le (zh _)).1 (lt_add_one _), _⟩, rw [int.cast_add, int.cast_one], refine lt_of_le_of_lt (add_le_add_right ((zh _).1 (le_refl _)) _) _, rwa [← lt_sub_iff_add_lt', ← sub_mul, ← div_lt_iff' (sub_pos.2 h), one_div], { rw [rat.coe_int_denom, nat.cast_one], exact one_ne_zero }, { intro H, rw [rat.coe_nat_num, ← coe_coe, nat.cast_eq_zero] at H, subst H, cases n0 }, { rw [rat.coe_nat_denom, nat.cast_one], exact one_ne_zero } end theorem exists_nat_one_div_lt {ε : α} (hε : 0 < ε) : ∃ n : ℕ, 1 / (n + 1: α) < ε := begin cases exists_nat_gt (1/ε) with n hn, use n, rw [div_lt_iff, ← div_lt_iff' hε], { apply hn.trans, simp [zero_lt_one] }, { exact n.cast_add_one_pos } end theorem exists_pos_rat_lt {x : α} (x0 : 0 < x) : ∃ q : ℚ, 0 < q ∧ (q : α) < x := by simpa only [rat.cast_pos] using exists_rat_btwn x0 include α @[simp] theorem rat.cast_floor (x : ℚ) : by haveI := archimedean.floor_ring α; exact ⌊(x:α)⌋ = ⌊x⌋ := begin haveI := archimedean.floor_ring α, apply le_antisymm, { rw [le_floor, ← @rat.cast_le α, rat.cast_coe_int], apply floor_le }, { rw [le_floor, ← rat.cast_coe_int, rat.cast_le], apply floor_le } end end linear_ordered_field section variables [linear_ordered_field α] /-- `round` rounds a number to the nearest integer. `round (1 / 2) = 1` -/ def round [floor_ring α] (x : α) : ℤ := ⌊x + 1 / 2⌋ lemma abs_sub_round [floor_ring α] (x : α) : abs (x - round x) ≤ 1 / 2 := begin rw [round, abs_sub_le_iff], have := floor_le (x + 1 / 2), have := lt_floor_add_one (x + 1 / 2), split; linarith end variable [archimedean α] theorem exists_rat_near (x : α) {ε : α} (ε0 : 0 < ε) : ∃ q : ℚ, abs (x - q) < ε := let ⟨q, h₁, h₂⟩ := exists_rat_btwn $ lt_trans ((sub_lt_self_iff x).2 ε0) ((lt_add_iff_pos_left x).2 ε0) in ⟨q, abs_sub_lt_iff.2 ⟨sub_lt.1 h₁, sub_lt_iff_lt_add.2 h₂⟩⟩ instance : archimedean ℚ := archimedean_iff_rat_le.2 $ λ q, ⟨q, by rw rat.cast_id⟩ @[simp] theorem rat.cast_round (x : ℚ) : by haveI := archimedean.floor_ring α; exact round (x:α) = round x := have ((x + (1 : ℚ) / (2 : ℚ) : ℚ) : α) = x + 1 / 2, by simp, by rw [round, round, ← this, rat.cast_floor] end