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
6cc484a63153a1938e7485d7e3691c031868b38f
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/topology/metric_space/hausdorff_distance.lean
50613568802f185f8e6157ebabf08fa86993ee4f
[ "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
33,559
lean
/- Copyright (c) 2019 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sébastien Gouëzel -/ import topology.metric_space.isometry import topology.instances.ennreal import analysis.specific_limits /-! # Hausdorff distance The Hausdorff distance on subsets of a metric (or emetric) space. Given two subsets `s` and `t` of a metric space, their Hausdorff distance is the smallest `d` such that any point `s` is within `d` of a point in `t`, and conversely. This quantity is often infinite (think of `s` bounded and `t` unbounded), and therefore better expressed in the setting of emetric spaces. ## Main definitions This files introduces: * `inf_edist x s`, the infimum edistance of a point `x` to a set `s` in an emetric space * `Hausdorff_edist s t`, the Hausdorff edistance of two sets in an emetric space * Versions of these notions on metric spaces, called respectively `inf_dist` and `Hausdorff_dist`. -/ noncomputable theory open_locale classical nnreal ennreal topological_space universes u v w open classical set function topological_space filter namespace emetric section inf_edist variables {α : Type u} {β : Type v} [pseudo_emetric_space α] [pseudo_emetric_space β] {x y : α} {s t : set α} {Φ : α → β} /-! ### Distance of a point to a set as a function into `ℝ≥0∞`. -/ /-- The minimal edistance of a point to a set -/ def inf_edist (x : α) (s : set α) : ℝ≥0∞ := ⨅ y ∈ s, edist x y @[simp] lemma inf_edist_empty : inf_edist x ∅ = ∞ := infi_emptyset lemma le_inf_edist {d} : d ≤ inf_edist x s ↔ ∀ y ∈ s, d ≤ edist x y := by simp only [inf_edist, le_infi_iff] /-- The edist to a union is the minimum of the edists -/ @[simp] lemma inf_edist_union : inf_edist x (s ∪ t) = inf_edist x s ⊓ inf_edist x t := infi_union /-- The edist to a singleton is the edistance to the single point of this singleton -/ @[simp] lemma inf_edist_singleton : inf_edist x {y} = edist x y := infi_singleton /-- The edist to a set is bounded above by the edist to any of its points -/ lemma inf_edist_le_edist_of_mem (h : y ∈ s) : inf_edist x s ≤ edist x y := binfi_le _ h /-- If a point `x` belongs to `s`, then its edist to `s` vanishes -/ lemma inf_edist_zero_of_mem (h : x ∈ s) : inf_edist x s = 0 := nonpos_iff_eq_zero.1 $ @edist_self _ _ x ▸ inf_edist_le_edist_of_mem h /-- The edist is monotonous with respect to inclusion -/ lemma inf_edist_le_inf_edist_of_subset (h : s ⊆ t) : inf_edist x t ≤ inf_edist x s := infi_le_infi_of_subset h /-- If the edist to a set is `< r`, there exists a point in the set at edistance `< r` -/ lemma exists_edist_lt_of_inf_edist_lt {r : ℝ≥0∞} (h : inf_edist x s < r) : ∃y∈s, edist x y < r := by simpa only [inf_edist, infi_lt_iff] using h /-- The edist of `x` to `s` is bounded by the sum of the edist of `y` to `s` and the edist from `x` to `y` -/ lemma inf_edist_le_inf_edist_add_edist : inf_edist x s ≤ inf_edist y s + edist x y := calc (⨅ z ∈ s, edist x z) ≤ ⨅ z ∈ s, edist y z + edist x y : binfi_le_binfi $ λ z hz, (edist_triangle _ _ _).trans_eq (add_comm _ _) ... = (⨅ z ∈ s, edist y z) + edist x y : by simp only [ennreal.infi_add] /-- The edist to a set depends continuously on the point -/ @[continuity] lemma continuous_inf_edist : continuous (λx, inf_edist x s) := continuous_of_le_add_edist 1 (by simp) $ by simp only [one_mul, inf_edist_le_inf_edist_add_edist, forall_2_true_iff] /-- The edist to a set and to its closure coincide -/ lemma inf_edist_closure : inf_edist x (closure s) = inf_edist x s := begin refine le_antisymm (inf_edist_le_inf_edist_of_subset subset_closure) _, refine ennreal.le_of_forall_pos_le_add (λε εpos h, _), have ε0 : 0 < (ε / 2 : ℝ≥0∞) := by simpa [pos_iff_ne_zero] using εpos, have : inf_edist x (closure s) < inf_edist x (closure s) + ε/2, from ennreal.lt_add_right h.ne ε0.ne', rcases exists_edist_lt_of_inf_edist_lt this with ⟨y, ycs, hy⟩, -- y : α, ycs : y ∈ closure s, hy : edist x y < inf_edist x (closure s) + ↑ε / 2 rcases emetric.mem_closure_iff.1 ycs (ε/2) ε0 with ⟨z, zs, dyz⟩, -- z : α, zs : z ∈ s, dyz : edist y z < ↑ε / 2 calc inf_edist x s ≤ edist x z : inf_edist_le_edist_of_mem zs ... ≤ edist x y + edist y z : edist_triangle _ _ _ ... ≤ (inf_edist x (closure s) + ε / 2) + (ε/2) : add_le_add (le_of_lt hy) (le_of_lt dyz) ... = inf_edist x (closure s) + ↑ε : by rw [add_assoc, ennreal.add_halves] end /-- A point belongs to the closure of `s` iff its infimum edistance to this set vanishes -/ lemma mem_closure_iff_inf_edist_zero : x ∈ closure s ↔ inf_edist x s = 0 := ⟨λh, by rw ← inf_edist_closure; exact inf_edist_zero_of_mem h, λh, emetric.mem_closure_iff.2 $ λε εpos, exists_edist_lt_of_inf_edist_lt (by rwa h)⟩ /-- Given a closed set `s`, a point belongs to `s` iff its infimum edistance to this set vanishes -/ lemma mem_iff_inf_edist_zero_of_closed (h : is_closed s) : x ∈ s ↔ inf_edist x s = 0 := begin convert ← mem_closure_iff_inf_edist_zero, exact h.closure_eq end lemma disjoint_closed_ball_of_lt_inf_edist {r : ℝ≥0∞} (h : r < inf_edist x s) : disjoint (closed_ball x r) s := begin rw disjoint_left, assume y hy h'y, apply lt_irrefl (inf_edist x s), calc inf_edist x s ≤ edist x y : inf_edist_le_edist_of_mem h'y ... ≤ r : by rwa [mem_closed_ball, edist_comm] at hy ... < inf_edist x s : h end /-- The infimum edistance is invariant under isometries -/ lemma inf_edist_image (hΦ : isometry Φ) : inf_edist (Φ x) (Φ '' t) = inf_edist x t := by simp only [inf_edist, infi_image, hΦ.edist_eq] lemma _root_.is_open.exists_Union_is_closed {U : set α} (hU : is_open U) : ∃ F : ℕ → set α, (∀ n, is_closed (F n)) ∧ (∀ n, F n ⊆ U) ∧ ((⋃ n, F n) = U) ∧ (monotone F) := begin obtain ⟨a, a_pos, a_lt_one⟩ : ∃ (a : ℝ≥0∞), 0 < a ∧ a < 1 := exists_between (ennreal.zero_lt_one), let F := λ (n : ℕ), (λ x, inf_edist x Uᶜ) ⁻¹' (Ici (a^n)), have F_subset : ∀ n, F n ⊆ U, { assume n x hx, by_contra h, rw [← mem_compl_iff, mem_iff_inf_edist_zero_of_closed (is_open.is_closed_compl hU)] at h, have : 0 < inf_edist x Uᶜ := lt_of_lt_of_le (ennreal.pow_pos a_pos _) hx, rw h at this, exact lt_irrefl _ this }, refine ⟨F, λ n, is_closed.preimage continuous_inf_edist is_closed_Ici, F_subset, _, _⟩, show monotone F, { assume m n hmn x hx, simp only [mem_Ici, mem_preimage] at hx ⊢, apply le_trans (ennreal.pow_le_pow_of_le_one a_lt_one.le hmn) hx }, show (⋃ n, F n) = U, { refine subset.antisymm (by simp only [Union_subset_iff, F_subset, forall_const]) (λ x hx, _), have : ¬(x ∈ Uᶜ), by simpa using hx, rw mem_iff_inf_edist_zero_of_closed (is_open.is_closed_compl hU) at this, have B : 0 < inf_edist x Uᶜ, by simpa [pos_iff_ne_zero] using this, have : filter.tendsto (λ n, a^n) at_top (𝓝 0) := ennreal.tendsto_pow_at_top_nhds_0_of_lt_1 a_lt_one, rcases ((tendsto_order.1 this).2 _ B).exists with ⟨n, hn⟩, simp only [mem_Union, mem_Ici, mem_preimage], exact ⟨n, hn.le⟩ }, end end inf_edist --section /-! ### The Hausdorff distance as a function into `ℝ≥0∞`. -/ /-- The Hausdorff edistance between two sets is the smallest `r` such that each set is contained in the `r`-neighborhood of the other one -/ @[irreducible] def Hausdorff_edist {α : Type u} [pseudo_emetric_space α] (s t : set α) : ℝ≥0∞ := (⨆ x ∈ s, inf_edist x t) ⊔ (⨆ y ∈ t, inf_edist y s) lemma Hausdorff_edist_def {α : Type u} [pseudo_emetric_space α] (s t : set α) : Hausdorff_edist s t = (⨆ x ∈ s, inf_edist x t) ⊔ (⨆ y ∈ t, inf_edist y s) := by rw Hausdorff_edist section Hausdorff_edist variables {α : Type u} {β : Type v} [pseudo_emetric_space α] [pseudo_emetric_space β] {x y : α} {s t u : set α} {Φ : α → β} /-- The Hausdorff edistance of a set to itself vanishes -/ @[simp] lemma Hausdorff_edist_self : Hausdorff_edist s s = 0 := begin simp only [Hausdorff_edist_def, sup_idem, ennreal.supr_eq_zero], exact λ x hx, inf_edist_zero_of_mem hx end /-- The Haudorff edistances of `s` to `t` and of `t` to `s` coincide -/ lemma Hausdorff_edist_comm : Hausdorff_edist s t = Hausdorff_edist t s := by unfold Hausdorff_edist; apply sup_comm /-- Bounding the Hausdorff edistance by bounding the edistance of any point in each set to the other set -/ lemma Hausdorff_edist_le_of_inf_edist {r : ℝ≥0∞} (H1 : ∀x ∈ s, inf_edist x t ≤ r) (H2 : ∀x ∈ t, inf_edist x s ≤ r) : Hausdorff_edist s t ≤ r := begin simp only [Hausdorff_edist, sup_le_iff, supr_le_iff], exact ⟨H1, H2⟩ end /-- Bounding the Hausdorff edistance by exhibiting, for any point in each set, another point in the other set at controlled distance -/ lemma Hausdorff_edist_le_of_mem_edist {r : ℝ≥0∞} (H1 : ∀x ∈ s, ∃y ∈ t, edist x y ≤ r) (H2 : ∀x ∈ t, ∃y ∈ s, edist x y ≤ r) : Hausdorff_edist s t ≤ r := begin refine Hausdorff_edist_le_of_inf_edist _ _, { assume x xs, rcases H1 x xs with ⟨y, yt, hy⟩, exact le_trans (inf_edist_le_edist_of_mem yt) hy }, { assume x xt, rcases H2 x xt with ⟨y, ys, hy⟩, exact le_trans (inf_edist_le_edist_of_mem ys) hy } end /-- The distance to a set is controlled by the Hausdorff distance -/ lemma inf_edist_le_Hausdorff_edist_of_mem (h : x ∈ s) : inf_edist x t ≤ Hausdorff_edist s t := begin rw Hausdorff_edist_def, refine le_trans _ le_sup_left, exact le_bsupr x h end /-- If the Hausdorff distance is `<r`, then any point in one of the sets has a corresponding point at distance `<r` in the other set -/ lemma exists_edist_lt_of_Hausdorff_edist_lt {r : ℝ≥0∞} (h : x ∈ s) (H : Hausdorff_edist s t < r) : ∃y∈t, edist x y < r := exists_edist_lt_of_inf_edist_lt $ calc inf_edist x t ≤ Hausdorff_edist s t : inf_edist_le_Hausdorff_edist_of_mem h ... < r : H /-- The distance from `x` to `s` or `t` is controlled in terms of the Hausdorff distance between `s` and `t` -/ lemma inf_edist_le_inf_edist_add_Hausdorff_edist : inf_edist x t ≤ inf_edist x s + Hausdorff_edist s t := ennreal.le_of_forall_pos_le_add $ λε εpos h, begin have ε0 : (ε / 2 : ℝ≥0∞) ≠ 0 := by simpa [pos_iff_ne_zero] using εpos, have : inf_edist x s < inf_edist x s + ε/2 := ennreal.lt_add_right (ennreal.add_lt_top.1 h).1.ne ε0, rcases exists_edist_lt_of_inf_edist_lt this with ⟨y, ys, dxy⟩, -- y : α, ys : y ∈ s, dxy : edist x y < inf_edist x s + ↑ε / 2 have : Hausdorff_edist s t < Hausdorff_edist s t + ε/2 := ennreal.lt_add_right (ennreal.add_lt_top.1 h).2.ne ε0, rcases exists_edist_lt_of_Hausdorff_edist_lt ys this with ⟨z, zt, dyz⟩, -- z : α, zt : z ∈ t, dyz : edist y z < Hausdorff_edist s t + ↑ε / 2 calc inf_edist x t ≤ edist x z : inf_edist_le_edist_of_mem zt ... ≤ edist x y + edist y z : edist_triangle _ _ _ ... ≤ (inf_edist x s + ε/2) + (Hausdorff_edist s t + ε/2) : add_le_add dxy.le dyz.le ... = inf_edist x s + Hausdorff_edist s t + ε : by simp [ennreal.add_halves, add_comm, add_left_comm] end /-- The Hausdorff edistance is invariant under eisometries -/ lemma Hausdorff_edist_image (h : isometry Φ) : Hausdorff_edist (Φ '' s) (Φ '' t) = Hausdorff_edist s t := by simp only [Hausdorff_edist_def, supr_image, inf_edist_image h] /-- The Hausdorff distance is controlled by the diameter of the union -/ lemma Hausdorff_edist_le_ediam (hs : s.nonempty) (ht : t.nonempty) : Hausdorff_edist s t ≤ diam (s ∪ t) := begin rcases hs with ⟨x, xs⟩, rcases ht with ⟨y, yt⟩, refine Hausdorff_edist_le_of_mem_edist _ _, { intros z hz, exact ⟨y, yt, edist_le_diam_of_mem (subset_union_left _ _ hz) (subset_union_right _ _ yt)⟩ }, { intros z hz, exact ⟨x, xs, edist_le_diam_of_mem (subset_union_right _ _ hz) (subset_union_left _ _ xs)⟩ } end /-- The Hausdorff distance satisfies the triangular inequality -/ lemma Hausdorff_edist_triangle : Hausdorff_edist s u ≤ Hausdorff_edist s t + Hausdorff_edist t u := begin rw Hausdorff_edist_def, simp only [sup_le_iff, supr_le_iff], split, show ∀x ∈ s, inf_edist x u ≤ Hausdorff_edist s t + Hausdorff_edist t u, from λx xs, calc inf_edist x u ≤ inf_edist x t + Hausdorff_edist t u : inf_edist_le_inf_edist_add_Hausdorff_edist ... ≤ Hausdorff_edist s t + Hausdorff_edist t u : add_le_add_right (inf_edist_le_Hausdorff_edist_of_mem xs) _, show ∀x ∈ u, inf_edist x s ≤ Hausdorff_edist s t + Hausdorff_edist t u, from λx xu, calc inf_edist x s ≤ inf_edist x t + Hausdorff_edist t s : inf_edist_le_inf_edist_add_Hausdorff_edist ... ≤ Hausdorff_edist u t + Hausdorff_edist t s : add_le_add_right (inf_edist_le_Hausdorff_edist_of_mem xu) _ ... = Hausdorff_edist s t + Hausdorff_edist t u : by simp [Hausdorff_edist_comm, add_comm] end /-- Two sets are at zero Hausdorff edistance if and only if they have the same closure -/ lemma Hausdorff_edist_zero_iff_closure_eq_closure : Hausdorff_edist s t = 0 ↔ closure s = closure t := calc Hausdorff_edist s t = 0 ↔ s ⊆ closure t ∧ t ⊆ closure s : by simp only [Hausdorff_edist_def, ennreal.sup_eq_zero, ennreal.supr_eq_zero, ← mem_closure_iff_inf_edist_zero, subset_def] ... ↔ closure s = closure t : ⟨λ h, subset.antisymm (closure_minimal h.1 is_closed_closure) (closure_minimal h.2 is_closed_closure), λ h, ⟨h ▸ subset_closure, h.symm ▸ subset_closure⟩⟩ /-- The Hausdorff edistance between a set and its closure vanishes -/ @[simp, priority 1100] lemma Hausdorff_edist_self_closure : Hausdorff_edist s (closure s) = 0 := by rw [Hausdorff_edist_zero_iff_closure_eq_closure, closure_closure] /-- Replacing a set by its closure does not change the Hausdorff edistance. -/ @[simp] lemma Hausdorff_edist_closure₁ : Hausdorff_edist (closure s) t = Hausdorff_edist s t := begin refine le_antisymm _ _, { calc _ ≤ Hausdorff_edist (closure s) s + Hausdorff_edist s t : Hausdorff_edist_triangle ... = Hausdorff_edist s t : by simp [Hausdorff_edist_comm] }, { calc _ ≤ Hausdorff_edist s (closure s) + Hausdorff_edist (closure s) t : Hausdorff_edist_triangle ... = Hausdorff_edist (closure s) t : by simp } end /-- Replacing a set by its closure does not change the Hausdorff edistance. -/ @[simp] lemma Hausdorff_edist_closure₂ : Hausdorff_edist s (closure t) = Hausdorff_edist s t := by simp [@Hausdorff_edist_comm _ _ s _] /-- The Hausdorff edistance between sets or their closures is the same -/ @[simp] lemma Hausdorff_edist_closure : Hausdorff_edist (closure s) (closure t) = Hausdorff_edist s t := by simp /-- Two closed sets are at zero Hausdorff edistance if and only if they coincide -/ lemma Hausdorff_edist_zero_iff_eq_of_closed (hs : is_closed s) (ht : is_closed t) : Hausdorff_edist s t = 0 ↔ s = t := by rw [Hausdorff_edist_zero_iff_closure_eq_closure, hs.closure_eq, ht.closure_eq] /-- The Haudorff edistance to the empty set is infinite -/ lemma Hausdorff_edist_empty (ne : s.nonempty) : Hausdorff_edist s ∅ = ∞ := begin rcases ne with ⟨x, xs⟩, have : inf_edist x ∅ ≤ Hausdorff_edist s ∅ := inf_edist_le_Hausdorff_edist_of_mem xs, simpa using this, end /-- If a set is at finite Hausdorff edistance of a nonempty set, it is nonempty -/ lemma nonempty_of_Hausdorff_edist_ne_top (hs : s.nonempty) (fin : Hausdorff_edist s t ≠ ⊤) : t.nonempty := t.eq_empty_or_nonempty.elim (λ ht, (fin $ ht.symm ▸ Hausdorff_edist_empty hs).elim) id lemma empty_or_nonempty_of_Hausdorff_edist_ne_top (fin : Hausdorff_edist s t ≠ ⊤) : s = ∅ ∧ t = ∅ ∨ s.nonempty ∧ t.nonempty := begin cases s.eq_empty_or_nonempty with hs hs, { cases t.eq_empty_or_nonempty with ht ht, { exact or.inl ⟨hs, ht⟩ }, { rw Hausdorff_edist_comm at fin, exact or.inr ⟨nonempty_of_Hausdorff_edist_ne_top ht fin, ht⟩ } }, { exact or.inr ⟨hs, nonempty_of_Hausdorff_edist_ne_top hs fin⟩ } end end Hausdorff_edist -- section end emetric --namespace /-! Now, we turn to the same notions in metric spaces. To avoid the difficulties related to `Inf` and `Sup` on `ℝ` (which is only conditionally complete), we use the notions in `ℝ≥0∞` formulated in terms of the edistance, and coerce them to `ℝ`. Then their properties follow readily from the corresponding properties in `ℝ≥0∞`, modulo some tedious rewriting of inequalities from one to the other. -/ namespace metric section variables {α : Type u} {β : Type v} [pseudo_metric_space α] [pseudo_metric_space β] {s t u : set α} {x y : α} {Φ : α → β} open emetric /-! ### Distance of a point to a set as a function into `ℝ`. -/ /-- The minimal distance of a point to a set -/ def inf_dist (x : α) (s : set α) : ℝ := ennreal.to_real (inf_edist x s) /-- the minimal distance is always nonnegative -/ lemma inf_dist_nonneg : 0 ≤ inf_dist x s := by simp [inf_dist] /-- the minimal distance to the empty set is 0 (if you want to have the more reasonable value ∞ instead, use `inf_edist`, which takes values in ℝ≥0∞) -/ @[simp] lemma inf_dist_empty : inf_dist x ∅ = 0 := by simp [inf_dist] /-- In a metric space, the minimal edistance to a nonempty set is finite -/ lemma inf_edist_ne_top (h : s.nonempty) : inf_edist x s ≠ ⊤ := begin rcases h with ⟨y, hy⟩, apply lt_top_iff_ne_top.1, calc inf_edist x s ≤ edist x y : inf_edist_le_edist_of_mem hy ... < ⊤ : lt_top_iff_ne_top.2 (edist_ne_top _ _) end /-- The minimal distance of a point to a set containing it vanishes -/ lemma inf_dist_zero_of_mem (h : x ∈ s) : inf_dist x s = 0 := by simp [inf_edist_zero_of_mem h, inf_dist] /-- The minimal distance to a singleton is the distance to the unique point in this singleton -/ @[simp] lemma inf_dist_singleton : inf_dist x {y} = dist x y := by simp [inf_dist, inf_edist, dist_edist] /-- The minimal distance to a set is bounded by the distance to any point in this set -/ lemma inf_dist_le_dist_of_mem (h : y ∈ s) : inf_dist x s ≤ dist x y := begin rw [dist_edist, inf_dist, ennreal.to_real_le_to_real (inf_edist_ne_top ⟨_, h⟩) (edist_ne_top _ _)], exact inf_edist_le_edist_of_mem h end /-- The minimal distance is monotonous with respect to inclusion -/ lemma inf_dist_le_inf_dist_of_subset (h : s ⊆ t) (hs : s.nonempty) : inf_dist x t ≤ inf_dist x s := begin have ht : t.nonempty := hs.mono h, rw [inf_dist, inf_dist, ennreal.to_real_le_to_real (inf_edist_ne_top ht) (inf_edist_ne_top hs)], exact inf_edist_le_inf_edist_of_subset h end /-- If the minimal distance to a set is `<r`, there exists a point in this set at distance `<r` -/ lemma exists_dist_lt_of_inf_dist_lt {r : real} (h : inf_dist x s < r) (hs : s.nonempty) : ∃y∈s, dist x y < r := begin have rpos : 0 < r := lt_of_le_of_lt inf_dist_nonneg h, have : inf_edist x s < ennreal.of_real r, { rwa [inf_dist, ← ennreal.to_real_of_real (le_of_lt rpos), ennreal.to_real_lt_to_real (inf_edist_ne_top hs)] at h, simp }, rcases exists_edist_lt_of_inf_edist_lt this with ⟨y, ys, hy⟩, rw [edist_dist, ennreal.of_real_lt_of_real_iff rpos] at hy, exact ⟨y, ys, hy⟩, end /-- The minimal distance from `x` to `s` is bounded by the distance from `y` to `s`, modulo the distance between `x` and `y` -/ lemma inf_dist_le_inf_dist_add_dist : inf_dist x s ≤ inf_dist y s + dist x y := begin cases s.eq_empty_or_nonempty with hs hs, { by simp [hs, dist_nonneg] }, { rw [inf_dist, inf_dist, dist_edist, ← ennreal.to_real_add (inf_edist_ne_top hs) (edist_ne_top _ _), ennreal.to_real_le_to_real (inf_edist_ne_top hs)], { apply inf_edist_le_inf_edist_add_edist }, { simp [ennreal.add_eq_top, inf_edist_ne_top hs, edist_ne_top] }} end lemma disjoint_closed_ball_of_lt_inf_dist {r : ℝ} (h : r < inf_dist x s) : disjoint (closed_ball x r) s := begin rw disjoint_left, assume y hy h'y, apply lt_irrefl (inf_dist x s), calc inf_dist x s ≤ dist x y : inf_dist_le_dist_of_mem h'y ... ≤ r : by rwa [mem_closed_ball, dist_comm] at hy ... < inf_dist x s : h end variable (s) /-- The minimal distance to a set is Lipschitz in point with constant 1 -/ lemma lipschitz_inf_dist_pt : lipschitz_with 1 (λx, inf_dist x s) := lipschitz_with.of_le_add $ λ x y, inf_dist_le_inf_dist_add_dist /-- The minimal distance to a set is uniformly continuous in point -/ lemma uniform_continuous_inf_dist_pt : uniform_continuous (λx, inf_dist x s) := (lipschitz_inf_dist_pt s).uniform_continuous /-- The minimal distance to a set is continuous in point -/ @[continuity] lemma continuous_inf_dist_pt : continuous (λx, inf_dist x s) := (uniform_continuous_inf_dist_pt s).continuous variable {s} /-- The minimal distance to a set and its closure coincide -/ lemma inf_dist_eq_closure : inf_dist x (closure s) = inf_dist x s := by simp [inf_dist, inf_edist_closure] /-- A point belongs to the closure of `s` iff its infimum distance to this set vanishes -/ lemma mem_closure_iff_inf_dist_zero (h : s.nonempty) : x ∈ closure s ↔ inf_dist x s = 0 := by simp [mem_closure_iff_inf_edist_zero, inf_dist, ennreal.to_real_eq_zero_iff, inf_edist_ne_top h] /-- Given a closed set `s`, a point belongs to `s` iff its infimum distance to this set vanishes -/ lemma _root_.is_closed.mem_iff_inf_dist_zero (h : is_closed s) (hs : s.nonempty) : x ∈ s ↔ inf_dist x s = 0 := begin have := @mem_closure_iff_inf_dist_zero _ _ s x hs, rwa h.closure_eq at this end /-- Given a closed set `s`, a point belongs to `s` iff its infimum distance to this set vanishes -/ lemma _root_.is_closed.not_mem_iff_inf_dist_pos (h : is_closed s) (hs : s.nonempty) : x ∉ s ↔ 0 < inf_dist x s := begin rw ← not_iff_not, push_neg, simp [h.mem_iff_inf_dist_zero hs, le_antisymm_iff, inf_dist_nonneg], end /-- The infimum distance is invariant under isometries -/ lemma inf_dist_image (hΦ : isometry Φ) : inf_dist (Φ x) (Φ '' t) = inf_dist x t := by simp [inf_dist, inf_edist_image hΦ] /-! ### Distance of a point to a set as a function into `ℝ≥0`. -/ /-- The minimal distance of a point to a set as a `ℝ≥0` -/ def inf_nndist (x : α) (s : set α) : ℝ≥0 := ennreal.to_nnreal (inf_edist x s) @[simp] lemma coe_inf_nndist : (inf_nndist x s : ℝ) = inf_dist x s := rfl /-- The minimal distance to a set (as `ℝ≥0`) is Lipschitz in point with constant 1 -/ lemma lipschitz_inf_nndist_pt (s : set α) : lipschitz_with 1 (λx, inf_nndist x s) := lipschitz_with.of_le_add $ λ x y, inf_dist_le_inf_dist_add_dist /-- The minimal distance to a set (as `ℝ≥0`) is uniformly continuous in point -/ lemma uniform_continuous_inf_nndist_pt (s : set α) : uniform_continuous (λx, inf_nndist x s) := (lipschitz_inf_nndist_pt s).uniform_continuous /-- The minimal distance to a set (as `ℝ≥0`) is continuous in point -/ lemma continuous_inf_nndist_pt (s : set α) : continuous (λx, inf_nndist x s) := (uniform_continuous_inf_nndist_pt s).continuous /-! ### The Hausdorff distance as a function into `ℝ`. -/ /-- The Hausdorff distance between two sets is the smallest nonnegative `r` such that each set is included in the `r`-neighborhood of the other. If there is no such `r`, it is defined to be `0`, arbitrarily -/ def Hausdorff_dist (s t : set α) : ℝ := ennreal.to_real (Hausdorff_edist s t) /-- The Hausdorff distance is nonnegative -/ lemma Hausdorff_dist_nonneg : 0 ≤ Hausdorff_dist s t := by simp [Hausdorff_dist] /-- If two sets are nonempty and bounded in a metric space, they are at finite Hausdorff edistance. -/ lemma Hausdorff_edist_ne_top_of_nonempty_of_bounded (hs : s.nonempty) (ht : t.nonempty) (bs : bounded s) (bt : bounded t) : Hausdorff_edist s t ≠ ⊤ := begin rcases hs with ⟨cs, hcs⟩, rcases ht with ⟨ct, hct⟩, rcases (bounded_iff_subset_ball ct).1 bs with ⟨rs, hrs⟩, rcases (bounded_iff_subset_ball cs).1 bt with ⟨rt, hrt⟩, have : Hausdorff_edist s t ≤ ennreal.of_real (max rs rt), { apply Hausdorff_edist_le_of_mem_edist, { assume x xs, existsi [ct, hct], have : dist x ct ≤ max rs rt := le_trans (hrs xs) (le_max_left _ _), rwa [edist_dist, ennreal.of_real_le_of_real_iff], exact le_trans dist_nonneg this }, { assume x xt, existsi [cs, hcs], have : dist x cs ≤ max rs rt := le_trans (hrt xt) (le_max_right _ _), rwa [edist_dist, ennreal.of_real_le_of_real_iff], exact le_trans dist_nonneg this }}, exact ne_top_of_le_ne_top ennreal.of_real_ne_top this end /-- The Hausdorff distance between a set and itself is zero -/ @[simp] lemma Hausdorff_dist_self_zero : Hausdorff_dist s s = 0 := by simp [Hausdorff_dist] /-- The Hausdorff distance from `s` to `t` and from `t` to `s` coincide -/ lemma Hausdorff_dist_comm : Hausdorff_dist s t = Hausdorff_dist t s := by simp [Hausdorff_dist, Hausdorff_edist_comm] /-- The Hausdorff distance to the empty set vanishes (if you want to have the more reasonable value ∞ instead, use `Hausdorff_edist`, which takes values in ℝ≥0∞) -/ @[simp] lemma Hausdorff_dist_empty : Hausdorff_dist s ∅ = 0 := begin cases s.eq_empty_or_nonempty with h h, { simp [h] }, { simp [Hausdorff_dist, Hausdorff_edist_empty h] } end /-- The Hausdorff distance to the empty set vanishes (if you want to have the more reasonable value ∞ instead, use `Hausdorff_edist`, which takes values in ℝ≥0∞) -/ @[simp] lemma Hausdorff_dist_empty' : Hausdorff_dist ∅ s = 0 := by simp [Hausdorff_dist_comm] /-- Bounding the Hausdorff distance by bounding the distance of any point in each set to the other set -/ lemma Hausdorff_dist_le_of_inf_dist {r : ℝ} (hr : 0 ≤ r) (H1 : ∀x ∈ s, inf_dist x t ≤ r) (H2 : ∀x ∈ t, inf_dist x s ≤ r) : Hausdorff_dist s t ≤ r := begin by_cases h1 : Hausdorff_edist s t = ⊤, by rwa [Hausdorff_dist, h1, ennreal.top_to_real], cases s.eq_empty_or_nonempty with hs hs, by rwa [hs, Hausdorff_dist_empty'], cases t.eq_empty_or_nonempty with ht ht, by rwa [ht, Hausdorff_dist_empty], have : Hausdorff_edist s t ≤ ennreal.of_real r, { apply Hausdorff_edist_le_of_inf_edist _ _, { assume x hx, have I := H1 x hx, rwa [inf_dist, ← ennreal.to_real_of_real hr, ennreal.to_real_le_to_real (inf_edist_ne_top ht) ennreal.of_real_ne_top] at I }, { assume x hx, have I := H2 x hx, rwa [inf_dist, ← ennreal.to_real_of_real hr, ennreal.to_real_le_to_real (inf_edist_ne_top hs) ennreal.of_real_ne_top] at I }}, rwa [Hausdorff_dist, ← ennreal.to_real_of_real hr, ennreal.to_real_le_to_real h1 ennreal.of_real_ne_top] end /-- Bounding the Hausdorff distance by exhibiting, for any point in each set, another point in the other set at controlled distance -/ lemma Hausdorff_dist_le_of_mem_dist {r : ℝ} (hr : 0 ≤ r) (H1 : ∀x ∈ s, ∃y ∈ t, dist x y ≤ r) (H2 : ∀x ∈ t, ∃y ∈ s, dist x y ≤ r) : Hausdorff_dist s t ≤ r := begin apply Hausdorff_dist_le_of_inf_dist hr, { assume x xs, rcases H1 x xs with ⟨y, yt, hy⟩, exact le_trans (inf_dist_le_dist_of_mem yt) hy }, { assume x xt, rcases H2 x xt with ⟨y, ys, hy⟩, exact le_trans (inf_dist_le_dist_of_mem ys) hy } end /-- The Hausdorff distance is controlled by the diameter of the union -/ lemma Hausdorff_dist_le_diam (hs : s.nonempty) (bs : bounded s) (ht : t.nonempty) (bt : bounded t) : Hausdorff_dist s t ≤ diam (s ∪ t) := begin rcases hs with ⟨x, xs⟩, rcases ht with ⟨y, yt⟩, refine Hausdorff_dist_le_of_mem_dist diam_nonneg _ _, { exact λz hz, ⟨y, yt, dist_le_diam_of_mem (bounded_union.2 ⟨bs, bt⟩) (subset_union_left _ _ hz) (subset_union_right _ _ yt)⟩ }, { exact λz hz, ⟨x, xs, dist_le_diam_of_mem (bounded_union.2 ⟨bs, bt⟩) (subset_union_right _ _ hz) (subset_union_left _ _ xs)⟩ } end /-- The distance to a set is controlled by the Hausdorff distance -/ lemma inf_dist_le_Hausdorff_dist_of_mem (hx : x ∈ s) (fin : Hausdorff_edist s t ≠ ⊤) : inf_dist x t ≤ Hausdorff_dist s t := begin have ht : t.nonempty := nonempty_of_Hausdorff_edist_ne_top ⟨x, hx⟩ fin, rw [Hausdorff_dist, inf_dist, ennreal.to_real_le_to_real (inf_edist_ne_top ht) fin], exact inf_edist_le_Hausdorff_edist_of_mem hx end /-- If the Hausdorff distance is `<r`, then any point in one of the sets is at distance `<r` of a point in the other set -/ lemma exists_dist_lt_of_Hausdorff_dist_lt {r : ℝ} (h : x ∈ s) (H : Hausdorff_dist s t < r) (fin : Hausdorff_edist s t ≠ ⊤) : ∃y∈t, dist x y < r := begin have r0 : 0 < r := lt_of_le_of_lt (Hausdorff_dist_nonneg) H, have : Hausdorff_edist s t < ennreal.of_real r, by rwa [Hausdorff_dist, ← ennreal.to_real_of_real (le_of_lt r0), ennreal.to_real_lt_to_real fin (ennreal.of_real_ne_top)] at H, rcases exists_edist_lt_of_Hausdorff_edist_lt h this with ⟨y, hy, yr⟩, rw [edist_dist, ennreal.of_real_lt_of_real_iff r0] at yr, exact ⟨y, hy, yr⟩ end /-- If the Hausdorff distance is `<r`, then any point in one of the sets is at distance `<r` of a point in the other set -/ lemma exists_dist_lt_of_Hausdorff_dist_lt' {r : ℝ} (h : y ∈ t) (H : Hausdorff_dist s t < r) (fin : Hausdorff_edist s t ≠ ⊤) : ∃x∈s, dist x y < r := begin rw Hausdorff_dist_comm at H, rw Hausdorff_edist_comm at fin, simpa [dist_comm] using exists_dist_lt_of_Hausdorff_dist_lt h H fin end /-- The infimum distance to `s` and `t` are the same, up to the Hausdorff distance between `s` and `t` -/ lemma inf_dist_le_inf_dist_add_Hausdorff_dist (fin : Hausdorff_edist s t ≠ ⊤) : inf_dist x t ≤ inf_dist x s + Hausdorff_dist s t := begin rcases empty_or_nonempty_of_Hausdorff_edist_ne_top fin with ⟨hs,ht⟩|⟨hs,ht⟩, { simp only [hs, ht, Hausdorff_dist_empty, inf_dist_empty, zero_add] }, rw [inf_dist, inf_dist, Hausdorff_dist, ← ennreal.to_real_add (inf_edist_ne_top hs) fin, ennreal.to_real_le_to_real (inf_edist_ne_top ht)], { exact inf_edist_le_inf_edist_add_Hausdorff_edist }, { exact ennreal.add_ne_top.2 ⟨inf_edist_ne_top hs, fin⟩ } end /-- The Hausdorff distance is invariant under isometries -/ lemma Hausdorff_dist_image (h : isometry Φ) : Hausdorff_dist (Φ '' s) (Φ '' t) = Hausdorff_dist s t := by simp [Hausdorff_dist, Hausdorff_edist_image h] /-- The Hausdorff distance satisfies the triangular inequality -/ lemma Hausdorff_dist_triangle (fin : Hausdorff_edist s t ≠ ⊤) : Hausdorff_dist s u ≤ Hausdorff_dist s t + Hausdorff_dist t u := begin by_cases Hausdorff_edist s u = ⊤, { calc Hausdorff_dist s u = 0 + 0 : by simp [Hausdorff_dist, h] ... ≤ Hausdorff_dist s t + Hausdorff_dist t u : add_le_add (Hausdorff_dist_nonneg) (Hausdorff_dist_nonneg) }, { have Dtu : Hausdorff_edist t u < ⊤ := calc Hausdorff_edist t u ≤ Hausdorff_edist t s + Hausdorff_edist s u : Hausdorff_edist_triangle ... = Hausdorff_edist s t + Hausdorff_edist s u : by simp [Hausdorff_edist_comm] ... < ⊤ : by simp [lt_top_iff_ne_top, *], rw [Hausdorff_dist, Hausdorff_dist, Hausdorff_dist, ← ennreal.to_real_add fin Dtu.ne, ennreal.to_real_le_to_real h], { exact Hausdorff_edist_triangle }, { simp [ennreal.add_eq_top, lt_top_iff_ne_top.1 Dtu, fin] }} end /-- The Hausdorff distance satisfies the triangular inequality -/ lemma Hausdorff_dist_triangle' (fin : Hausdorff_edist t u ≠ ⊤) : Hausdorff_dist s u ≤ Hausdorff_dist s t + Hausdorff_dist t u := begin rw Hausdorff_edist_comm at fin, have I : Hausdorff_dist u s ≤ Hausdorff_dist u t + Hausdorff_dist t s := Hausdorff_dist_triangle fin, simpa [add_comm, Hausdorff_dist_comm] using I end /-- The Hausdorff distance between a set and its closure vanish -/ @[simp, priority 1100] lemma Hausdorff_dist_self_closure : Hausdorff_dist s (closure s) = 0 := by simp [Hausdorff_dist] /-- Replacing a set by its closure does not change the Hausdorff distance. -/ @[simp] lemma Hausdorff_dist_closure₁ : Hausdorff_dist (closure s) t = Hausdorff_dist s t := by simp [Hausdorff_dist] /-- Replacing a set by its closure does not change the Hausdorff distance. -/ @[simp] lemma Hausdorff_dist_closure₂ : Hausdorff_dist s (closure t) = Hausdorff_dist s t := by simp [Hausdorff_dist] /-- The Hausdorff distance between two sets and their closures coincide -/ @[simp] lemma Hausdorff_dist_closure : Hausdorff_dist (closure s) (closure t) = Hausdorff_dist s t := by simp [Hausdorff_dist] /-- Two sets are at zero Hausdorff distance if and only if they have the same closures -/ lemma Hausdorff_dist_zero_iff_closure_eq_closure (fin : Hausdorff_edist s t ≠ ⊤) : Hausdorff_dist s t = 0 ↔ closure s = closure t := by simp [Hausdorff_edist_zero_iff_closure_eq_closure.symm, Hausdorff_dist, ennreal.to_real_eq_zero_iff, fin] /-- Two closed sets are at zero Hausdorff distance if and only if they coincide -/ lemma _root_.is_closed.Hausdorff_dist_zero_iff_eq (hs : is_closed s) (ht : is_closed t) (fin : Hausdorff_edist s t ≠ ⊤) : Hausdorff_dist s t = 0 ↔ s = t := by simp [(Hausdorff_edist_zero_iff_eq_of_closed hs ht).symm, Hausdorff_dist, ennreal.to_real_eq_zero_iff, fin] end --section end metric --namespace
9674e04b1d4d9060771d24dadb1f258872b6bf3b
2eab05920d6eeb06665e1a6df77b3157354316ad
/src/topology/instances/real.lean
ef0db9e4096851a9143bf4c804ee67c915c5d61e
[ "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
16,388
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Mario Carneiro -/ import topology.metric_space.basic import topology.algebra.uniform_group import topology.algebra.ring import ring_theory.subring import group_theory.archimedean import algebra.periodic /-! # Topological properties of ℝ -/ noncomputable theory open classical filter int metric set topological_space open_locale classical topological_space filter uniformity interval universes u v w variables {α : Type u} {β : Type v} {γ : Type w} instance : metric_space ℚ := metric_space.induced coe rat.cast_injective real.metric_space namespace rat theorem dist_eq (x y : ℚ) : dist x y = |x - y| := rfl @[norm_cast, simp] lemma dist_cast (x y : ℚ) : dist (x : ℝ) y = dist x y := rfl theorem uniform_continuous_coe_real : uniform_continuous (coe : ℚ → ℝ) := uniform_continuous_comap theorem uniform_embedding_coe_real : uniform_embedding (coe : ℚ → ℝ) := uniform_embedding_comap rat.cast_injective theorem dense_embedding_coe_real : dense_embedding (coe : ℚ → ℝ) := uniform_embedding_coe_real.dense_embedding $ λ x, mem_closure_iff_nhds.2 $ λ t ht, let ⟨ε,ε0, hε⟩ := metric.mem_nhds_iff.1 ht in let ⟨q, h⟩ := exists_rat_near x ε0 in ⟨_, hε (mem_ball'.2 h), q, rfl⟩ theorem embedding_coe_real : embedding (coe : ℚ → ℝ) := dense_embedding_coe_real.to_embedding theorem continuous_coe_real : continuous (coe : ℚ → ℝ) := uniform_continuous_coe_real.continuous end rat namespace int instance : has_dist ℤ := ⟨λ x y, dist (x : ℝ) y⟩ theorem dist_eq (x y : ℤ) : dist x y = |x - y| := rfl @[norm_cast, simp] theorem dist_cast_real (x y : ℤ) : dist (x : ℝ) y = dist x y := rfl @[norm_cast, simp] theorem dist_cast_rat (x y : ℤ) : dist (x : ℚ) y = dist x y := by rw [← int.dist_cast_real, ← rat.dist_cast]; congr' 1; norm_cast lemma pairwise_one_le_dist : pairwise (λ m n : ℤ, 1 ≤ dist m n) := begin intros m n hne, rw dist_eq, norm_cast, rwa [← zero_add (1 : ℤ), int.add_one_le_iff, abs_pos, sub_ne_zero] end lemma uniform_embedding_coe_rat : uniform_embedding (coe : ℤ → ℚ) := uniform_embedding_bot_of_pairwise_le_dist zero_lt_one $ by simpa using pairwise_one_le_dist lemma closed_embedding_coe_rat : closed_embedding (coe : ℤ → ℚ) := closed_embedding_of_pairwise_le_dist zero_lt_one $ by simpa using pairwise_one_le_dist lemma uniform_embedding_coe_real : uniform_embedding (coe : ℤ → ℝ) := uniform_embedding_bot_of_pairwise_le_dist zero_lt_one pairwise_one_le_dist lemma closed_embedding_coe_real : closed_embedding (coe : ℤ → ℝ) := closed_embedding_of_pairwise_le_dist zero_lt_one pairwise_one_le_dist instance : metric_space ℤ := int.uniform_embedding_coe_real.comap_metric_space _ theorem preimage_ball (x : ℤ) (r : ℝ) : coe ⁻¹' (ball (x : ℝ) r) = ball x r := rfl theorem preimage_closed_ball (x : ℤ) (r : ℝ) : coe ⁻¹' (closed_ball (x : ℝ) r) = closed_ball x r := rfl theorem ball_eq (x : ℤ) (r : ℝ) : ball x r = Ioo ⌊↑x - r⌋ ⌈↑x + r⌉ := by rw [← preimage_ball, real.ball_eq, preimage_Ioo] theorem closed_ball_eq (x : ℤ) (r : ℝ) : closed_ball x r = Icc ⌈↑x - r⌉ ⌊↑x + r⌋ := by rw [← preimage_closed_ball, real.closed_ball_eq, preimage_Icc] instance : proper_space ℤ := ⟨ begin intros x r, rw closed_ball_eq, exact (set.finite_Icc _ _).is_compact, end ⟩ instance : noncompact_space ℤ := begin rw [← not_compact_space_iff, metric.compact_space_iff_bounded_univ], rintro ⟨r, hr⟩, refine (hr (⌊r⌋ + 1) 0 trivial trivial).not_lt _, simpa [dist_eq] using (lt_floor_add_one r).trans_le (le_abs_self _) end end int instance : noncompact_space ℚ := int.closed_embedding_coe_rat.noncompact_space instance : noncompact_space ℝ := int.closed_embedding_coe_real.noncompact_space theorem real.uniform_continuous_add : uniform_continuous (λp : ℝ × ℝ, p.1 + p.2) := metric.uniform_continuous_iff.2 $ λ ε ε0, let ⟨δ, δ0, Hδ⟩ := rat_add_continuous_lemma abs ε0 in ⟨δ, δ0, λ a b h, let ⟨h₁, h₂⟩ := max_lt_iff.1 h in Hδ h₁ h₂⟩ -- TODO(Mario): Find a way to use rat_add_continuous_lemma theorem rat.uniform_continuous_add : uniform_continuous (λp : ℚ × ℚ, p.1 + p.2) := rat.uniform_embedding_coe_real.to_uniform_inducing.uniform_continuous_iff.2 $ by simp only [(∘), rat.cast_add]; exact real.uniform_continuous_add.comp (rat.uniform_continuous_coe_real.prod_map rat.uniform_continuous_coe_real) theorem real.uniform_continuous_neg : uniform_continuous (@has_neg.neg ℝ _) := metric.uniform_continuous_iff.2 $ λ ε ε0, ⟨_, ε0, λ a b h, by rw dist_comm at h; simpa [real.dist_eq] using h⟩ theorem rat.uniform_continuous_neg : uniform_continuous (@has_neg.neg ℚ _) := metric.uniform_continuous_iff.2 $ λ ε ε0, ⟨_, ε0, λ a b h, by rw dist_comm at h; simpa [rat.dist_eq] using h⟩ instance : uniform_add_group ℝ := uniform_add_group.mk' real.uniform_continuous_add real.uniform_continuous_neg instance : uniform_add_group ℚ := uniform_add_group.mk' rat.uniform_continuous_add rat.uniform_continuous_neg -- short-circuit type class inference instance : topological_add_group ℝ := by apply_instance instance : topological_add_group ℚ := by apply_instance instance : order_topology ℚ := induced_order_topology _ (λ x y, rat.cast_lt) (@exists_rat_btwn _ _ _) instance : proper_space ℝ := { is_compact_closed_ball := λx r, by { rw real.closed_ball_eq, apply is_compact_Icc } } instance : second_countable_topology ℝ := second_countable_of_proper lemma real.is_topological_basis_Ioo_rat : @is_topological_basis ℝ _ (⋃(a b : ℚ) (h : a < b), {Ioo a b}) := is_topological_basis_of_open_of_nhds (by simp [is_open_Ioo] {contextual:=tt}) (assume a v hav hv, let ⟨l, u, ⟨hl, hu⟩, h⟩ := mem_nhds_iff_exists_Ioo_subset.mp (is_open.mem_nhds hv hav), ⟨q, hlq, hqa⟩ := exists_rat_btwn hl, ⟨p, hap, hpu⟩ := exists_rat_btwn hu in ⟨Ioo q p, by { simp only [mem_Union], exact ⟨q, p, rat.cast_lt.1 $ hqa.trans hap, rfl⟩ }, ⟨hqa, hap⟩, assume a' ⟨hqa', ha'p⟩, h ⟨hlq.trans hqa', ha'p.trans hpu⟩⟩) /- TODO(Mario): Prove that these are uniform isomorphisms instead of uniform embeddings lemma uniform_embedding_add_rat {r : ℚ} : uniform_embedding (λp:ℚ, p + r) := _ lemma uniform_embedding_mul_rat {q : ℚ} (hq : q ≠ 0) : uniform_embedding ((*) q) := _ -/ lemma real.mem_closure_iff {s : set ℝ} {x : ℝ} : x ∈ closure s ↔ ∀ ε > 0, ∃ y ∈ s, |y - x| < ε := by simp [mem_closure_iff_nhds_basis nhds_basis_ball, real.dist_eq] lemma real.uniform_continuous_inv (s : set ℝ) {r : ℝ} (r0 : 0 < r) (H : ∀ x ∈ s, r ≤ |x|) : uniform_continuous (λp:s, p.1⁻¹) := metric.uniform_continuous_iff.2 $ λ ε ε0, let ⟨δ, δ0, Hδ⟩ := rat_inv_continuous_lemma abs ε0 r0 in ⟨δ, δ0, λ a b h, Hδ (H _ a.2) (H _ b.2) h⟩ lemma real.uniform_continuous_abs : uniform_continuous (abs : ℝ → ℝ) := metric.uniform_continuous_iff.2 $ λ ε ε0, ⟨ε, ε0, λ a b, lt_of_le_of_lt (abs_abs_sub_abs_le_abs_sub _ _)⟩ lemma rat.uniform_continuous_abs : uniform_continuous (abs : ℚ → ℚ) := metric.uniform_continuous_iff.2 $ λ ε ε0, ⟨ε, ε0, λ a b h, lt_of_le_of_lt (by simpa [rat.dist_eq] using abs_abs_sub_abs_le_abs_sub _ _) h⟩ lemma real.tendsto_inv {r : ℝ} (r0 : r ≠ 0) : tendsto (λq, q⁻¹) (𝓝 r) (𝓝 r⁻¹) := by rw ← abs_pos at r0; exact tendsto_of_uniform_continuous_subtype (real.uniform_continuous_inv {x | |r| / 2 < |x|} (half_pos r0) (λ x h, le_of_lt h)) (is_open.mem_nhds ((is_open_lt' (|r| / 2)).preimage continuous_abs) (half_lt_self r0)) lemma real.continuous_inv : continuous (λa:{r:ℝ // r ≠ 0}, a.val⁻¹) := continuous_iff_continuous_at.mpr $ assume ⟨r, hr⟩, tendsto.comp (real.tendsto_inv hr) (continuous_iff_continuous_at.mp continuous_subtype_val _) lemma real.continuous.inv [topological_space α] {f : α → ℝ} (h : ∀a, f a ≠ 0) (hf : continuous f) : continuous (λa, (f a)⁻¹) := show continuous ((has_inv.inv ∘ @subtype.val ℝ (λr, r ≠ 0)) ∘ λa, ⟨f a, h a⟩), from real.continuous_inv.comp (continuous_subtype_mk _ hf) lemma real.uniform_continuous_mul_const {x : ℝ} : uniform_continuous ((*) x) := metric.uniform_continuous_iff.2 $ λ ε ε0, begin cases no_top (|x|) with y xy, have y0 := lt_of_le_of_lt (abs_nonneg _) xy, refine ⟨_, div_pos ε0 y0, λ a b h, _⟩, rw [real.dist_eq, ← mul_sub, abs_mul, ← mul_div_cancel' ε (ne_of_gt y0)], exact mul_lt_mul' (le_of_lt xy) h (abs_nonneg _) y0 end lemma real.uniform_continuous_mul (s : set (ℝ × ℝ)) {r₁ r₂ : ℝ} (H : ∀ x ∈ s, |(x : ℝ × ℝ).1| < r₁ ∧ |x.2| < r₂) : uniform_continuous (λp:s, p.1.1 * p.1.2) := metric.uniform_continuous_iff.2 $ λ ε ε0, let ⟨δ, δ0, Hδ⟩ := rat_mul_continuous_lemma abs ε0 in ⟨δ, δ0, λ a b h, let ⟨h₁, h₂⟩ := max_lt_iff.1 h in Hδ (H _ a.2).1 (H _ b.2).2 h₁ h₂⟩ protected lemma real.continuous_mul : continuous (λp : ℝ × ℝ, p.1 * p.2) := continuous_iff_continuous_at.2 $ λ ⟨a₁, a₂⟩, tendsto_of_uniform_continuous_subtype (real.uniform_continuous_mul ({x | |x| < |a₁| + 1}.prod {x | |x| < |a₂| + 1}) (λ x, id)) (is_open.mem_nhds (((is_open_gt' (|a₁| + 1)).preimage continuous_abs).prod ((is_open_gt' (|a₂| + 1)).preimage continuous_abs )) ⟨lt_add_one (|a₁|), lt_add_one (|a₂|)⟩) instance : topological_ring ℝ := { continuous_mul := real.continuous_mul, ..real.topological_add_group } lemma rat.continuous_mul : continuous (λp : ℚ × ℚ, p.1 * p.2) := rat.embedding_coe_real.continuous_iff.2 $ by simp [(∘)]; exact real.continuous_mul.comp ((rat.continuous_coe_real.prod_map rat.continuous_coe_real)) instance : topological_ring ℚ := { continuous_mul := rat.continuous_mul, ..rat.topological_add_group } theorem real.ball_eq_Ioo (x ε : ℝ) : ball x ε = Ioo (x - ε) (x + ε) := set.ext $ λ y, by rw [mem_ball, real.dist_eq, abs_sub_lt_iff, sub_lt_iff_lt_add', and_comm, sub_lt]; refl theorem real.Ioo_eq_ball (x y : ℝ) : Ioo x y = ball ((x + y) / 2) ((y - x) / 2) := by rw [real.ball_eq_Ioo, ← sub_div, add_comm, ← sub_add, add_sub_cancel', add_self_div_two, ← add_div, add_assoc, add_sub_cancel'_right, add_self_div_two] instance : complete_space ℝ := begin apply complete_of_cauchy_seq_tendsto, intros u hu, let c : cau_seq ℝ abs := ⟨u, metric.cauchy_seq_iff'.1 hu⟩, refine ⟨c.lim, λ s h, _⟩, rcases metric.mem_nhds_iff.1 h with ⟨ε, ε0, hε⟩, have := c.equiv_lim ε ε0, simp only [mem_map, mem_at_top_sets, mem_set_of_eq], refine this.imp (λ N hN n hn, hε (hN n hn)) end lemma real.totally_bounded_ball (x ε : ℝ) : totally_bounded (ball x ε) := by rw real.ball_eq_Ioo; apply totally_bounded_Ioo lemma rat.totally_bounded_Icc (a b : ℚ) : totally_bounded (Icc a b) := begin have := totally_bounded_preimage rat.uniform_embedding_coe_real (totally_bounded_Icc a b), rwa (set.ext (λ q, _) : Icc _ _ = _), simp end section lemma closure_of_rat_image_lt {q : ℚ} : closure ((coe:ℚ → ℝ) '' {x | q < x}) = {r | ↑q ≤ r} := subset.antisymm ((is_closed_ge' _).closure_subset_iff.2 (image_subset_iff.2 $ λ p h, le_of_lt $ (@rat.cast_lt ℝ _ _ _).2 h)) $ λ x hx, mem_closure_iff_nhds.2 $ λ t ht, let ⟨ε, ε0, hε⟩ := metric.mem_nhds_iff.1 ht in let ⟨p, h₁, h₂⟩ := exists_rat_btwn ((lt_add_iff_pos_right x).2 ε0) in ⟨_, hε (show abs _ < _, by rwa [abs_of_nonneg (le_of_lt $ sub_pos.2 h₁), sub_lt_iff_lt_add']), p, rat.cast_lt.1 (@lt_of_le_of_lt ℝ _ _ _ _ hx h₁), rfl⟩ /- TODO(Mario): Put these back only if needed later lemma closure_of_rat_image_le_eq {q : ℚ} : closure ((coe:ℚ → ℝ) '' {x | q ≤ x}) = {r | ↑q ≤ r} := _ lemma closure_of_rat_image_le_le_eq {a b : ℚ} (hab : a ≤ b) : closure (of_rat '' {q:ℚ | a ≤ q ∧ q ≤ b}) = {r:ℝ | of_rat a ≤ r ∧ r ≤ of_rat b} := _-/ lemma real.bounded_iff_bdd_below_bdd_above {s : set ℝ} : bounded s ↔ bdd_below s ∧ bdd_above s := ⟨begin assume bdd, rcases (bounded_iff_subset_ball 0).1 bdd with ⟨r, hr⟩, -- hr : s ⊆ closed_ball 0 r rw real.closed_ball_eq at hr, -- hr : s ⊆ Icc (0 - r) (0 + r) exact ⟨bdd_below_Icc.mono hr, bdd_above_Icc.mono hr⟩ end, begin intro h, rcases bdd_below_bdd_above_iff_subset_Icc.1 h with ⟨m, M, I : s ⊆ Icc m M⟩, exact (bounded_Icc m M).mono I end⟩ lemma real.subset_Icc_Inf_Sup_of_bounded {s : set ℝ} (h : bounded s) : s ⊆ Icc (Inf s) (Sup s) := subset_Icc_cInf_cSup (real.bounded_iff_bdd_below_bdd_above.1 h).1 (real.bounded_iff_bdd_below_bdd_above.1 h).2 end section periodic namespace function lemma periodic.compact_of_continuous' [topological_space α] {f : ℝ → α} {c : ℝ} (hp : periodic f c) (hc : 0 < c) (hf : continuous f) : is_compact (range f) := begin convert is_compact_Icc.image hf, ext x, refine ⟨_, mem_range_of_mem_image f (Icc 0 c)⟩, rintros ⟨y, h1⟩, obtain ⟨z, hz, h2⟩ := hp.exists_mem_Ico hc y, exact ⟨z, mem_Icc_of_Ico hz, h2.symm.trans h1⟩, end /-- A continuous, periodic function has compact range. -/ lemma periodic.compact_of_continuous [topological_space α] {f : ℝ → α} {c : ℝ} (hp : periodic f c) (hc : c ≠ 0) (hf : continuous f) : is_compact (range f) := begin cases lt_or_gt_of_ne hc with hneg hpos, exacts [hp.neg.compact_of_continuous' (neg_pos.mpr hneg) hf, hp.compact_of_continuous' hpos hf], end /-- A continuous, periodic function is bounded. -/ lemma periodic.bounded_of_continuous [pseudo_metric_space α] {f : ℝ → α} {c : ℝ} (hp : periodic f c) (hc : c ≠ 0) (hf : continuous f) : bounded (range f) := (hp.compact_of_continuous hc hf).bounded end function end periodic section subgroups /-- Given a nontrivial subgroup `G ⊆ ℝ`, if `G ∩ ℝ_{>0}` has no minimum then `G` is dense. -/ lemma real.subgroup_dense_of_no_min {G : add_subgroup ℝ} {g₀ : ℝ} (g₀_in : g₀ ∈ G) (g₀_ne : g₀ ≠ 0) (H' : ¬ ∃ a : ℝ, is_least {g : ℝ | g ∈ G ∧ 0 < g} a) : dense (G : set ℝ) := begin let G_pos := {g : ℝ | g ∈ G ∧ 0 < g}, push_neg at H', intros x, suffices : ∀ ε > (0 : ℝ), ∃ g ∈ G, |x - g| < ε, by simpa only [real.mem_closure_iff, abs_sub_comm], intros ε ε_pos, obtain ⟨g₁, g₁_in, g₁_pos⟩ : ∃ g₁ : ℝ, g₁ ∈ G ∧ 0 < g₁, { cases lt_or_gt_of_ne g₀_ne with Hg₀ Hg₀, { exact ⟨-g₀, G.neg_mem g₀_in, neg_pos.mpr Hg₀⟩ }, { exact ⟨g₀, g₀_in, Hg₀⟩ } }, obtain ⟨a, ha⟩ : ∃ a, is_glb G_pos a := ⟨Inf G_pos, is_glb_cInf ⟨g₁, g₁_in, g₁_pos⟩ ⟨0, λ _ hx, le_of_lt hx.2⟩⟩, have a_notin : a ∉ G_pos, { intros H, exact H' a ⟨H, ha.1⟩ }, obtain ⟨g₂, g₂_in, g₂_pos, g₂_lt⟩ : ∃ g₂ : ℝ, g₂ ∈ G ∧ 0 < g₂ ∧ g₂ < ε, { obtain ⟨b, hb, hb', hb''⟩ := ha.exists_between_self_add' a_notin ε_pos, obtain ⟨c, hc, hc', hc''⟩ := ha.exists_between_self_add' a_notin (sub_pos.2 hb'), refine ⟨b - c, G.sub_mem hb.1 hc.1, _, _⟩ ; linarith }, refine ⟨floor (x/g₂) * g₂, _, _⟩, { exact add_subgroup.int_mul_mem _ g₂_in }, { rw abs_of_nonneg (sub_floor_div_mul_nonneg x g₂_pos), linarith [sub_floor_div_mul_lt x g₂_pos] } end /-- Subgroups of `ℝ` are either dense or cyclic. See `real.subgroup_dense_of_no_min` and `subgroup_cyclic_of_min` for more precise statements. -/ lemma real.subgroup_dense_or_cyclic (G : add_subgroup ℝ) : dense (G : set ℝ) ∨ ∃ a : ℝ, G = add_subgroup.closure {a} := begin cases add_subgroup.bot_or_exists_ne_zero G with H H, { right, use 0, rw [H, add_subgroup.closure_singleton_zero] }, { let G_pos := {g : ℝ | g ∈ G ∧ 0 < g}, by_cases H' : ∃ a, is_least G_pos a, { right, rcases H' with ⟨a, ha⟩, exact ⟨a, add_subgroup.cyclic_of_min ha⟩ }, { left, rcases H with ⟨g₀, g₀_in, g₀_ne⟩, exact real.subgroup_dense_of_no_min g₀_in g₀_ne H' } } end end subgroups
d66ac3feb5c7e725ab6cd55222aff014d5d9eca2
c777c32c8e484e195053731103c5e52af26a25d1
/src/testing/slim_check/sampleable.lean
c14c317264fde201c7c5f4b045643146de333ede
[ "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
31,336
lean
/- Copyright (c) 2020 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Simon Hudon -/ import data.lazy_list.basic import data.tree import data.pnat.basic import control.bifunctor import control.ulift import testing.slim_check.gen import tactic.linarith /-! # `sampleable` Class This class permits the creation samples of a given type controlling the size of those values using the `gen` monad`. It also helps minimize examples by creating smaller versions of given values. When testing a proposition like `∀ n : ℕ, prime n → n ≤ 100`, `slim_check` requires that `ℕ` have an instance of `sampleable` and for `prime n` to be decidable. `slim_check` will then use the instance of `sampleable` to generate small examples of ℕ and progressively increase in size. For each example `n`, `prime n` is tested. If it is false, the example will be rejected (not a test success nor a failure) and `slim_check` will move on to other examples. If `prime n` is true, `n ≤ 100` will be tested. If it is false, `n` is a counter-example of `∀ n : ℕ, prime n → n ≤ 100` and the test fails. If `n ≤ 100` is true, the test passes and `slim_check` moves on to trying more examples. This is a port of the Haskell QuickCheck library. ## Main definitions * `sampleable` class * `sampleable_functor` and `sampleable_bifunctor` class * `sampleable_ext` class ### `sampleable` `sampleable α` provides ways of creating examples of type `α`, and given such an example `x : α`, gives us a way to shrink it and find simpler examples. ### `sampleable_ext` `sampleable_ext` generalizes the behavior of `sampleable` and makes it possible to express instances for types that do not lend themselves to introspection, such as `ℕ → ℕ`. If we test a quantification over functions the counter-examples cannot be shrunken or printed meaningfully. For that purpose, `sampleable_ext` provides a proxy representation `proxy_repr` that can be printed and shrunken as well as interpreted (using `interp`) as an object of the right type. ### `sampleable_functor` and `sampleable_bifunctor` `sampleable_functor F` and `sampleable_bifunctor F` makes it possible to create samples of and shrink `F α` given a sampling function and a shrinking function for arbitrary `α`. This allows us to separate the logic for generating the shape of a collection from the logic for generating its contents. Specifically, the contents could be generated using either `sampleable` or `sampleable_ext` instance and the `sampleable_(bi)functor` does not need to use that information ## Shrinking Shrinking happens when `slim_check` find a counter-example to a property. It is likely that the example will be more complicated than necessary so `slim_check` proceeds to shrink it as much as possible. Although equally valid, a smaller counter-example is easier for a user to understand and use. The `sampleable` class, beside having the `sample` function, has a `shrink` function so that we can use specialized knowledge while shrinking a value. It is not responsible for the whole shrinking process however. It only has to take one step in the shrinking process. `slim_check` will repeatedly call `shrink` until no more steps can be taken. Because `shrink` guarantees that the size of the candidates it produces is strictly smaller than the argument, we know that `slim_check` is guaranteed to terminate. ## Tags random testing ## References * https://hackage.haskell.org/package/QuickCheck -/ universes u v w namespace slim_check variables (α : Type u) local infix ` ≺ `:50 := has_well_founded.r /-- `sizeof_lt x y` compares the sizes of `x` and `y`. -/ def sizeof_lt {α} [has_sizeof α] (x y : α) := sizeof x < sizeof y /-- `shrink_fn α` is the type of functions that shrink an argument of type `α` -/ @[reducible] def shrink_fn (α : Type*) [has_sizeof α] := Π x : α, lazy_list { y : α // sizeof_lt y x } /-- `sampleable α` provides ways of creating examples of type `α`, and given such an example `x : α`, gives us a way to shrink it and find simpler examples. -/ class sampleable := [wf : has_sizeof α] (sample [] : gen α) (shrink : Π x : α, lazy_list { y : α // @sizeof _ wf y < @sizeof _ wf x } := λ _, lazy_list.nil) attribute [instance, priority 100] has_well_founded_of_has_sizeof default_has_sizeof attribute [instance, priority 200] sampleable.wf /-- `sampleable_functor F` makes it possible to create samples of and shrink `F α` given a sampling function and a shrinking function for arbitrary `α` -/ class sampleable_functor (F : Type u → Type v) [functor F] := [wf : Π α [has_sizeof α], has_sizeof (F α)] (sample [] : ∀ {α}, gen α → gen (F α)) (shrink : ∀ α [has_sizeof α], shrink_fn α → shrink_fn (F α)) (p_repr : ∀ α, has_repr α → has_repr (F α)) /-- `sampleable_bifunctor F` makes it possible to create samples of and shrink `F α β` given a sampling function and a shrinking function for arbitrary `α` and `β` -/ class sampleable_bifunctor (F : Type u → Type v → Type w) [bifunctor F] := [wf : Π α β [has_sizeof α] [has_sizeof β], has_sizeof (F α β)] (sample [] : ∀ {α β}, gen α → gen β → gen (F α β)) (shrink : ∀ α β [has_sizeof α] [has_sizeof β], shrink_fn α → shrink_fn β → shrink_fn (F α β)) (p_repr : ∀ α β, has_repr α → has_repr β → has_repr (F α β)) export sampleable (sample shrink) /-- This function helps infer the proxy representation and interpretation in `sampleable_ext` instances. -/ meta def sampleable.mk_trivial_interp : tactic unit := tactic.refine ``(id) /-- `sampleable_ext` generalizes the behavior of `sampleable` and makes it possible to express instances for types that do not lend themselves to introspection, such as `ℕ → ℕ`. If we test a quantification over functions the counter-examples cannot be shrunken or printed meaningfully. For that purpose, `sampleable_ext` provides a proxy representation `proxy_repr` that can be printed and shrunken as well as interpreted (using `interp`) as an object of the right type. -/ class sampleable_ext (α : Sort u) := (proxy_repr : Type v) [wf : has_sizeof proxy_repr] (interp [] : proxy_repr → α . sampleable.mk_trivial_interp) [p_repr : has_repr proxy_repr] (sample [] : gen proxy_repr) (shrink : shrink_fn proxy_repr) attribute [instance, priority 100] sampleable_ext.p_repr sampleable_ext.wf open nat lazy_list section prio open sampleable_ext set_option default_priority 50 instance sampleable_ext.of_sampleable {α} [sampleable α] [has_repr α] : sampleable_ext α := { proxy_repr := α, sample := sampleable.sample α, shrink := shrink } instance sampleable.functor {α} {F} [functor F] [sampleable_functor F] [sampleable α] : sampleable (F α) := { wf := _, sample := sampleable_functor.sample F (sampleable.sample α), shrink := sampleable_functor.shrink α sampleable.shrink } instance sampleable.bifunctor {α β} {F} [bifunctor F] [sampleable_bifunctor F] [sampleable α] [sampleable β] : sampleable (F α β) := { wf := _, sample := sampleable_bifunctor.sample F (sampleable.sample α) (sampleable.sample β), shrink := sampleable_bifunctor.shrink α β sampleable.shrink sampleable.shrink } set_option default_priority 100 instance sampleable_ext.functor {α} {F} [functor F] [sampleable_functor F] [sampleable_ext α] : sampleable_ext (F α) := { wf := _, proxy_repr := F (proxy_repr α), interp := functor.map (interp _), sample := sampleable_functor.sample F (sampleable_ext.sample α), shrink := sampleable_functor.shrink _ sampleable_ext.shrink, p_repr := sampleable_functor.p_repr _ sampleable_ext.p_repr } instance sampleable_ext.bifunctor {α β} {F} [bifunctor F] [sampleable_bifunctor F] [sampleable_ext α] [sampleable_ext β] : sampleable_ext (F α β) := { wf := _, proxy_repr := F (proxy_repr α) (proxy_repr β), interp := bifunctor.bimap (interp _) (interp _), sample := sampleable_bifunctor.sample F (sampleable_ext.sample α) (sampleable_ext.sample β), shrink := sampleable_bifunctor.shrink _ _ sampleable_ext.shrink sampleable_ext.shrink, p_repr := sampleable_bifunctor.p_repr _ _ sampleable_ext.p_repr sampleable_ext.p_repr } end prio /-- `nat.shrink' k n` creates a list of smaller natural numbers by successively dividing `n` by 2 and subtracting the difference from `k`. For example, `nat.shrink 100 = [50, 75, 88, 94, 97, 99]`. -/ def nat.shrink' (k : ℕ) : Π n : ℕ, n ≤ k → list { m : ℕ // has_well_founded.r m k } → list { m : ℕ // has_well_founded.r m k } | n hn ls := if h : n ≤ 1 then ls.reverse else have h₂ : 0 < n, by linarith, have 1 * n / 2 < n, from nat.div_lt_of_lt_mul (nat.mul_lt_mul_of_pos_right (by norm_num) h₂), have n / 2 < n, by simpa, let m := n / 2 in have h₀ : m ≤ k, from le_trans (le_of_lt this) hn, have h₃ : 0 < m, by simp only [m, lt_iff_add_one_le, zero_add]; rw [nat.le_div_iff_mul_le]; linarith, have h₁ : k - m < k, from nat.sub_lt (lt_of_lt_of_le h₂ hn) h₃, nat.shrink' m h₀ (⟨k - m, h₁⟩ :: ls) /-- `nat.shrink n` creates a list of smaller natural numbers by successively dividing by 2 and subtracting the difference from `n`. For example, `nat.shrink 100 = [50, 75, 88, 94, 97, 99]`. -/ def nat.shrink (n : ℕ) : list { m : ℕ // has_well_founded.r m n } := if h : n > 0 then have ∀ k, 1 < k → n / k < n, from λ k hk, nat.div_lt_of_lt_mul (suffices 1 * n < k * n, by simpa, nat.mul_lt_mul_of_pos_right hk h), ⟨n/11, this _ (by norm_num)⟩ :: ⟨n/3, this _ (by norm_num)⟩ :: nat.shrink' n n le_rfl [] else [] open gen /-- Transport a `sampleable` instance from a type `α` to a type `β` using functions between the two, going in both directions. Function `g` is used to define the well-founded order that `shrink` is expected to follow. -/ def sampleable.lift (α : Type u) {β : Type u} [sampleable α] (f : α → β) (g : β → α) (h : ∀ (a : α), sizeof (g (f a)) ≤ sizeof a) : sampleable β := { wf := ⟨ sizeof ∘ g ⟩, sample := f <$> sample α, shrink := λ x, have ∀ a, sizeof a < sizeof (g x) → sizeof (g (f a)) < sizeof (g x), by introv h'; solve_by_elim [lt_of_le_of_lt], subtype.map f this <$> shrink (g x) } instance nat.sampleable : sampleable ℕ := { sample := sized $ λ sz, freq [(1, coe <$> choose_any (fin $ succ (sz^3))), (3, coe <$> choose_any (fin $ succ sz))] dec_trivial, shrink := λ x, lazy_list.of_list $ nat.shrink x } /-- `iterate_shrink p x` takes a decidable predicate `p` and a value `x` of some sampleable type and recursively shrinks `x`. It first calls `shrink x` to get a list of candidate sample, finds the first that satisfies `p` and recursively tries to shrink that one. -/ def iterate_shrink {α} [has_to_string α] [sampleable α] (p : α → Prop) [decidable_pred p] : α → option α := well_founded.fix has_well_founded.wf $ λ x f_rec, do trace sformat!"{x} : {(shrink x).to_list}" $ pure (), y ← (shrink x).find (λ a, p a), f_rec y y.property <|> some y.val . instance fin.sampleable {n : ℕ} [ne_zero n] : sampleable (fin n) := sampleable.lift ℕ fin.of_nat' fin.val $ λ i, (mod_le _ _ : i % n ≤ i) @[priority 100] instance fin.sampleable' {n} : sampleable (fin (succ n)) := sampleable.lift ℕ fin.of_nat fin.val $ λ i, (mod_le _ _ : i % succ n ≤ i) instance pnat.sampleable : sampleable ℕ+ := sampleable.lift ℕ nat.succ_pnat pnat.nat_pred $ λ a, by unfold_wf; simp only [pnat.nat_pred, succ_pnat, pnat.mk_coe, tsub_zero, succ_sub_succ_eq_sub] /-- Redefine `sizeof` for `int` to make it easier to use with `nat` -/ def int.has_sizeof : has_sizeof ℤ := ⟨ int.nat_abs ⟩ local attribute [instance, priority 2000] int.has_sizeof instance int.sampleable : sampleable ℤ := { wf := _, sample := sized $ λ sz, freq [(1, subtype.val <$> choose (-(sz^3 + 1) : ℤ) (sz^3 + 1) (neg_le_self dec_trivial)), (3, subtype.val <$> choose (-(sz + 1)) (sz + 1) (neg_le_self dec_trivial))] dec_trivial, shrink := λ x, lazy_list.of_list $ (nat.shrink $ int.nat_abs x).bind $ λ ⟨y,h⟩, [⟨y, h⟩, ⟨-y, by dsimp [sizeof,has_sizeof.sizeof]; rw int.nat_abs_neg; exact h ⟩] } instance bool.sampleable : sampleable bool := { wf := ⟨ λ b, if b then 1 else 0 ⟩, sample := do { x ← choose_any bool, return x }, shrink := λ b, if h : b then lazy_list.singleton ⟨ff, by cases h; unfold_wf⟩ else lazy_list.nil } /-- Provided two shrinking functions `prod.shrink` shrinks a pair `(x, y)` by first shrinking `x` and pairing the results with `y` and then shrinking `y` and pairing the results with `x`. All pairs either contain `x` untouched or `y` untouched. We rely on shrinking being repeated for `x` to get maximally shrunken and then for `y` to get shrunken too. -/ def prod.shrink {α β} [has_sizeof α] [has_sizeof β] (shr_a : shrink_fn α) (shr_b : shrink_fn β) : shrink_fn (α × β) | ⟨x₀,x₁⟩ := let xs₀ : lazy_list { y : α × β // sizeof_lt y (x₀,x₁) } := (shr_a x₀).map $ subtype.map (λ a, (a, x₁)) (λ x h, by dsimp [sizeof_lt]; unfold_wf; apply h), xs₁ : lazy_list { y : α × β // sizeof_lt y (x₀,x₁) } := (shr_b x₁).map $ subtype.map (λ a, (x₀, a)) (λ x h, by dsimp [sizeof_lt]; unfold_wf; apply h) in xs₀.append xs₁ instance prod.sampleable : sampleable_bifunctor.{u v} prod := { wf := _, sample := λ α β sama samb, do { ⟨x⟩ ← (uliftable.up $ sama : gen (ulift.{max u v} α)), ⟨y⟩ ← (uliftable.up $ samb : gen (ulift.{max u v} β)), pure (x,y) }, shrink := @prod.shrink, p_repr := @prod.has_repr } instance sigma.sampleable {α β} [sampleable α] [sampleable β] : sampleable (Σ _ : α, β) := sampleable.lift (α × β) (λ ⟨x,y⟩, ⟨x,y⟩) (λ ⟨x,y⟩, ⟨x,y⟩) $ λ ⟨x,y⟩, le_rfl /-- shrinking function for sum types -/ def sum.shrink {α β} [has_sizeof α] [has_sizeof β] (shrink_α : shrink_fn α) (shrink_β : shrink_fn β) : shrink_fn (α ⊕ β) | (sum.inr x) := (shrink_β x).map $ subtype.map sum.inr $ λ a, by dsimp [sizeof_lt]; unfold_wf; solve_by_elim | (sum.inl x) := (shrink_α x).map $ subtype.map sum.inl $ λ a, by dsimp [sizeof_lt]; unfold_wf; solve_by_elim instance sum.sampleable : sampleable_bifunctor.{u v} sum := { wf := _, sample := λ (α : Type u) (β : Type v) sam_α sam_β, (@uliftable.up_map gen.{u} gen.{max u v} _ _ _ _ (@sum.inl α β) sam_α <|> @uliftable.up_map gen.{v} gen.{max v u} _ _ _ _ (@sum.inr α β) sam_β), shrink := λ α β Iα Iβ shr_α shr_β, @sum.shrink _ _ Iα Iβ shr_α shr_β, p_repr := @sum.has_repr } instance rat.sampleable : sampleable ℚ := sampleable.lift (ℤ × ℕ+) (λ x, prod.cases_on x rat.mk_pnat) (λ r, (r.num, ⟨r.denom, r.pos⟩)) $ begin intro i, rcases i with ⟨x,⟨y,hy⟩⟩; unfold_wf; dsimp [rat.mk_pnat], mono*, { rw [← int.coe_nat_le, int.coe_nat_abs, int.coe_nat_abs], apply int.abs_div_le_abs }, { change _ - 1 ≤ y-1, apply tsub_le_tsub_right, apply nat.div_le_of_le_mul, suffices : 1 * y ≤ x.nat_abs.gcd y * y, { simpa }, apply nat.mul_le_mul_right, apply gcd_pos_of_pos_right _ hy } end /-- `sampleable_char` can be specialized into customized `sampleable char` instances. The resulting instance has `1 / length` chances of making an unrestricted choice of characters and it otherwise chooses a character from `characters` with uniform probabilities. -/ def sampleable_char (length : nat) (characters : string) : sampleable char := { sample := do { x ← choose_nat 0 length dec_trivial, if x.val = 0 then do n ← sample ℕ, pure $ char.of_nat n else do i ← choose_nat 0 (characters.length - 1) dec_trivial, pure (characters.mk_iterator.nextn i).curr }, shrink := λ _, lazy_list.nil } instance char.sampleable : sampleable char := sampleable_char 3 " 0123abcABC:,;`\\/" variables {α} section list_shrink variables [has_sizeof α] (shr : Π x : α, lazy_list { y : α // sizeof_lt y x }) lemma list.sizeof_drop_lt_sizeof_of_lt_length {xs : list α} {k} (hk : 0 < k) (hk' : k < xs.length) : sizeof (list.drop k xs) < sizeof xs := begin induction xs with x xs generalizing k, { cases hk' }, cases k, { cases hk }, have : sizeof xs < sizeof (x :: xs), { unfold_wf }, cases k, { simp only [this, list.drop] }, { simp only [list.drop], transitivity, { solve_by_elim [xs_ih, lt_of_succ_lt_succ hk', zero_lt_succ] }, { assumption } } end lemma list.sizeof_cons_lt_right (a b : α) {xs : list α} (h : sizeof a < sizeof b) : sizeof (a :: xs) < sizeof (b :: xs) := by unfold_wf; assumption lemma list.sizeof_cons_lt_left (x : α) {xs xs' : list α} (h : sizeof xs < sizeof xs') : sizeof (x :: xs) < sizeof (x :: xs') := by unfold_wf; assumption lemma list.sizeof_append_lt_left {xs ys ys' : list α} (h : sizeof ys < sizeof ys') : sizeof (xs ++ ys) < sizeof (xs ++ ys') := begin induction xs, { apply h }, { unfold_wf, simp only [list.sizeof, add_lt_add_iff_left], exact xs_ih } end lemma list.one_le_sizeof (xs : list α) : 1 ≤ sizeof xs := by cases xs; unfold_wf; linarith /-- `list.shrink_removes` shrinks a list by removing chunks of size `k` in the middle of the list. -/ def list.shrink_removes (k : ℕ) (hk : 0 < k) : Π (xs : list α) n, n = xs.length → lazy_list { ys : list α // sizeof_lt ys xs } | xs n hn := if hkn : k > n then lazy_list.nil else if hkn' : k = n then have 1 < xs.sizeof, by { subst_vars, cases xs, { contradiction }, unfold_wf, apply lt_of_lt_of_le, show 1 < 1 + has_sizeof.sizeof xs_hd + 1, { linarith }, { mono, apply list.one_le_sizeof, } }, lazy_list.singleton ⟨[], this ⟩ else have h₂ : k < xs.length, from hn ▸ lt_of_le_of_ne (le_of_not_gt hkn) hkn', match list.split_at k xs, rfl : Π ys, ys = list.split_at k xs → _ with | ⟨xs₁,xs₂⟩, h := have h₄ : xs₁ = xs.take k, by simp only [list.split_at_eq_take_drop, prod.mk.inj_iff] at h; tauto, have h₃ : xs₂ = xs.drop k, by simp only [list.split_at_eq_take_drop, prod.mk.inj_iff] at h; tauto, have sizeof xs₂ < sizeof xs, by rw h₃; solve_by_elim [list.sizeof_drop_lt_sizeof_of_lt_length], have h₁ : n - k = xs₂.length, by simp only [h₃, ←hn, list.length_drop], have h₅ : ∀ (a : list α), sizeof_lt a xs₂ → sizeof_lt (xs₁ ++ a) xs, by intros a h; rw [← list.take_append_drop k xs, ← h₃, ← h₄]; solve_by_elim [list.sizeof_append_lt_left], lazy_list.cons ⟨xs₂, this⟩ $ subtype.map ((++) xs₁) h₅ <$> list.shrink_removes xs₂ (n - k) h₁ end /-- `list.shrink_one xs` shrinks list `xs` by shrinking only one item in the list. -/ def list.shrink_one : shrink_fn (list α) | [] := lazy_list.nil | (x :: xs) := lazy_list.append (subtype.map (λ x', x' :: xs) (λ a, list.sizeof_cons_lt_right _ _) <$> shr x) (subtype.map ((::) x) (λ _, list.sizeof_cons_lt_left _) <$> list.shrink_one xs) /-- `list.shrink_with shrink_f xs` shrinks `xs` by first considering `xs` with chunks removed in the middle (starting with chunks of size `xs.length` and halving down to `1`) and then shrinks only one element of the list. This strategy is taken directly from Haskell's QuickCheck -/ def list.shrink_with (xs : list α) : lazy_list { ys : list α // sizeof_lt ys xs } := let n := xs.length in lazy_list.append ((lazy_list.cons n $ (shrink n).reverse.map subtype.val).bind (λ k, if hk : 0 < k then list.shrink_removes k hk xs n rfl else lazy_list.nil )) (list.shrink_one shr _) end list_shrink instance list.sampleable : sampleable_functor list.{u} := { wf := _, sample := λ α sam_α, list_of sam_α, shrink := λ α Iα shr_α, @list.shrink_with _ Iα shr_α, p_repr := @list.has_repr } instance Prop.sampleable_ext : sampleable_ext Prop := { proxy_repr := bool, interp := coe, sample := choose_any bool, shrink := λ _, lazy_list.nil } /-- `no_shrink` is a type annotation to signal that a certain type is not to be shrunk. It can be useful in combination with other types: e.g. `xs : list (no_shrink ℤ)` will result in the list being cut down but individual integers being kept as is. -/ def no_shrink (α : Type*) := α instance no_shrink.inhabited {α} [inhabited α] : inhabited (no_shrink α) := ⟨ (default : α) ⟩ /-- Introduction of the `no_shrink` type. -/ def no_shrink.mk {α} (x : α) : no_shrink α := x /-- Selector of the `no_shrink` type. -/ def no_shrink.get {α} (x : no_shrink α) : α := x instance no_shrink.sampleable {α} [sampleable α] : sampleable (no_shrink α) := { sample := no_shrink.mk <$> sample α } instance string.sampleable : sampleable string := { sample := do { x ← list_of (sample char), pure x.as_string }, .. sampleable.lift (list char) list.as_string string.to_list $ λ _, le_rfl } /-- implementation of `sampleable (tree α)` -/ def tree.sample (sample : gen α) : ℕ → gen (tree α) | n := if h : n > 0 then have n / 2 < n, from div_lt_self h (by norm_num), tree.node <$> sample <*> tree.sample (n / 2) <*> tree.sample (n / 2) else pure tree.nil /-- `rec_shrink x f_rec` takes the recursive call `f_rec` introduced by `well_founded.fix` and turns it into a shrinking function whose result is adequate to use in a recursive call. -/ def rec_shrink {α : Type*} [has_sizeof α] (t : α) (sh : Π x : α, sizeof_lt x t → lazy_list { y : α // sizeof_lt y x }) : shrink_fn { t' : α // sizeof_lt t' t } | ⟨t',ht'⟩ := (λ t'' : { y : α // sizeof_lt y t' }, ⟨⟨t''.val, lt_trans t''.property ht'⟩, t''.property⟩ ) <$> sh t' ht' lemma tree.one_le_sizeof {α} [has_sizeof α] (t : tree α) : 1 ≤ sizeof t := by cases t; unfold_wf; linarith instance : functor tree := { map := @tree.map } /-- Recursion principle for shrinking tree-like structures. -/ def rec_shrink_with [has_sizeof α] (shrink_a : Π x : α, shrink_fn { y : α // sizeof_lt y x } → list (lazy_list { y : α // sizeof_lt y x })) : shrink_fn α := well_founded.fix (sizeof_measure_wf _) $ λ t f_rec, lazy_list.join (lazy_list.of_list $ shrink_a t $ λ ⟨t', h⟩, rec_shrink _ f_rec _) lemma rec_shrink_with_eq [has_sizeof α] (shrink_a : Π x : α, shrink_fn { y : α // sizeof_lt y x } → list (lazy_list { y : α // sizeof_lt y x })) (x : α) : rec_shrink_with shrink_a x = lazy_list.join (lazy_list.of_list $ shrink_a x $ λ t', rec_shrink _ (λ x h', rec_shrink_with shrink_a x) _) := begin conv_lhs { rw [rec_shrink_with, well_founded.fix_eq], }, congr, ext ⟨y, h⟩, refl end /-- `tree.shrink_with shrink_f t` shrinks `xs` by using the empty tree, each subtrees, and by shrinking the subtree to recombine them. This strategy is taken directly from Haskell's QuickCheck -/ def tree.shrink_with [has_sizeof α] (shrink_a : shrink_fn α) : shrink_fn (tree α) := rec_shrink_with $ λ t, match t with | tree.nil := λ f_rec, [] | (tree.node x t₀ t₁) := λ f_rec, have h₂ : sizeof_lt tree.nil (tree.node x t₀ t₁), by clear _match; have := tree.one_le_sizeof t₀; dsimp [sizeof_lt, sizeof, has_sizeof.sizeof] at *; unfold_wf; linarith, have h₀ : sizeof_lt t₀ (tree.node x t₀ t₁), by dsimp [sizeof_lt]; unfold_wf; linarith, have h₁ : sizeof_lt t₁ (tree.node x t₀ t₁), by dsimp [sizeof_lt]; unfold_wf; linarith, [lazy_list.of_list [⟨tree.nil, h₂⟩, ⟨t₀, h₀⟩, ⟨t₁, h₁⟩], (prod.shrink shrink_a (prod.shrink f_rec f_rec) (x, ⟨t₀, h₀⟩, ⟨t₁, h₁⟩)).map $ λ ⟨⟨y,⟨t'₀, _⟩,⟨t'₁, _⟩⟩,hy⟩, ⟨tree.node y t'₀ t'₁, by revert hy; dsimp [sizeof_lt]; unfold_wf; intro; linarith⟩] end instance sampleable_tree : sampleable_functor tree := { wf := _, sample := λ α sam_α, sized $ tree.sample sam_α, shrink := λ α Iα shr_α, @tree.shrink_with _ Iα shr_α, p_repr := @tree.has_repr } /-- Type tag that signals to `slim_check` to use small values for a given type. -/ def small (α : Type*) := α /-- Add the `small` type tag -/ def small.mk {α} (x : α) : small α := x /-- Type tag that signals to `slim_check` to use large values for a given type. -/ def large (α : Type*) := α /-- Add the `large` type tag -/ def large.mk {α} (x : α) : large α := x instance small.functor : functor small := id.monad.to_functor instance large.functor : functor large := id.monad.to_functor instance small.inhabited [inhabited α] : inhabited (small α) := ⟨ (default : α) ⟩ instance large.inhabited [inhabited α] : inhabited (large α) := ⟨ (default : α) ⟩ instance small.sampleable_functor : sampleable_functor small := { wf := _, sample := λ α samp, gen.resize (λ n, n / 5 + 5) samp, shrink := λ α _, id, p_repr := λ α, id } instance large.sampleable_functor : sampleable_functor large := { wf := _, sample := λ α samp, gen.resize (λ n, n * 5) samp, shrink := λ α _, id, p_repr := λ α, id } instance ulift.sampleable_functor : sampleable_functor ulift.{u v} := { wf := λ α h, ⟨ λ ⟨x⟩, @sizeof α h x ⟩, sample := λ α samp, uliftable.up_map ulift.up $ samp, shrink := λ α _ shr ⟨x⟩, (shr x).map (subtype.map ulift.up (λ a h, h)), p_repr := λ α h, ⟨ @repr α h ∘ ulift.down ⟩ } /-! ## Subtype instances The following instances are meant to improve the testing of properties of the form `∀ i j, i ≤ j, ...` The naive way to test them is to choose two numbers `i` and `j` and check that the proper ordering is satisfied. Instead, the following instances make it so that `j` will be chosen with considerations to the required ordering constraints. The benefit is that we will not have to discard any choice of `j`. -/ /-! ### Subtypes of `ℕ` -/ instance nat_le.sampleable {y} : slim_check.sampleable { x : ℕ // x ≤ y } := { sample := do { ⟨x,h⟩ ← slim_check.gen.choose_nat 0 y dec_trivial, pure ⟨x, h.2⟩}, shrink := λ ⟨x, h⟩, (λ a : subtype _, subtype.rec_on a $ λ x' h', ⟨⟨x', le_trans (le_of_lt h') h⟩, h'⟩) <$> shrink x } instance nat_ge.sampleable {x} : slim_check.sampleable { y : ℕ // x ≤ y } := { sample := do { (y : ℕ) ← slim_check.sampleable.sample ℕ, pure ⟨x+y, by norm_num⟩ }, shrink := λ ⟨y, h⟩, (λ a : { y' // sizeof y' < sizeof (y - x) }, subtype.rec_on a $ λ δ h', ⟨⟨x + δ, nat.le_add_right _ _⟩, lt_tsub_iff_left.mp h'⟩) <$> shrink (y - x) } /- there is no `nat_lt.sampleable` instance because if `y = 0`, there is no valid choice to satisfy `x < y` -/ instance nat_gt.sampleable {x} : slim_check.sampleable { y : ℕ // x < y } := { sample := do { (y : ℕ) ← slim_check.sampleable.sample ℕ, pure ⟨x+y+1, by linarith⟩ }, shrink := λ x, shrink _ } /-! ### Subtypes of any `linear_ordered_add_comm_group` -/ instance le.sampleable {y : α} [sampleable α] [linear_ordered_add_comm_group α] : slim_check.sampleable { x : α // x ≤ y } := { sample := do { x ← sample α, pure ⟨y - |x|, sub_le_self _ (abs_nonneg _) ⟩ }, shrink := λ _, lazy_list.nil } instance ge.sampleable {x : α} [sampleable α] [linear_ordered_add_comm_group α] : slim_check.sampleable { y : α // x ≤ y } := { sample := do { y ← sample α, pure ⟨x + |y|, by norm_num [abs_nonneg]⟩ }, shrink := λ _, lazy_list.nil } /-! ### Subtypes of `ℤ` Specializations of `le.sampleable` and `ge.sampleable` for `ℤ` to help instance search. -/ instance int_le.sampleable {y : ℤ} : slim_check.sampleable { x : ℤ // x ≤ y } := sampleable.lift ℕ (λ n, ⟨y - n, int.sub_left_le_of_le_add $ by simp⟩) (λ ⟨i, h⟩, (y - i).nat_abs) (λ n, by unfold_wf; simp [int_le.sampleable._match_1]; ring) instance int_ge.sampleable {x : ℤ} : slim_check.sampleable { y : ℤ // x ≤ y } := sampleable.lift ℕ (λ n, ⟨x + n, by simp⟩) (λ ⟨i, h⟩, (i - x).nat_abs) (λ n, by unfold_wf; simp [int_ge.sampleable._match_1]; ring) instance int_lt.sampleable {y} : slim_check.sampleable { x : ℤ // x < y } := sampleable.lift ℕ (λ n, ⟨y - (n+1), int.sub_left_lt_of_lt_add $ by linarith [int.coe_nat_nonneg n]⟩) (λ ⟨i, h⟩, (y - i - 1).nat_abs) (λ n, by unfold_wf; simp [int_lt.sampleable._match_1]; ring) instance int_gt.sampleable {x} : slim_check.sampleable { y : ℤ // x < y } := sampleable.lift ℕ (λ n, ⟨x + (n+1), by linarith⟩) (λ ⟨i, h⟩, (i - x - 1).nat_abs) (λ n, by unfold_wf; simp [int_gt.sampleable._match_1]; ring) /-! ### Subtypes of any `list` -/ instance perm.slim_check {xs : list α} : slim_check.sampleable { ys : list α // list.perm xs ys } := { sample := permutation_of xs, shrink := λ _, lazy_list.nil } instance perm'.slim_check {xs : list α} : slim_check.sampleable { ys : list α // list.perm ys xs } := { sample := subtype.map id (@list.perm.symm α _) <$> permutation_of xs, shrink := λ _, lazy_list.nil } setup_tactic_parser open tactic /-- Print (at most) 10 samples of a given type to stdout for debugging. -/ def print_samples {t : Type u} [has_repr t] (g : gen t) : io unit := do xs ← io.run_rand $ uliftable.down $ do { xs ← (list.range 10).mmap $ g.run ∘ ulift.up, pure ⟨xs.map repr⟩ }, xs.mmap' io.put_str_ln /-- Create a `gen α` expression from the argument of `#sample` -/ meta def mk_generator (e : expr) : tactic (expr × expr) := do t ← infer_type e, match t with | `(gen %%t) := do repr_inst ← mk_app ``has_repr [t] >>= mk_instance, pure (repr_inst, e) | _ := do samp_inst ← to_expr ``(sampleable_ext %%e) >>= mk_instance, repr_inst ← mk_mapp ``sampleable_ext.p_repr [e, samp_inst], gen ← mk_mapp ``sampleable_ext.sample [none, samp_inst], pure (repr_inst, gen) end /-- `#sample my_type`, where `my_type` has an instance of `sampleable`, prints ten random values of type `my_type` of using an increasing size parameter. ```lean #sample nat -- prints -- 0 -- 0 -- 2 -- 24 -- 64 -- 76 -- 5 -- 132 -- 8 -- 449 -- or some other sequence of numbers #sample list int -- prints -- [] -- [1, 1] -- [-7, 9, -6] -- [36] -- [-500, 105, 260] -- [-290] -- [17, 156] -- [-2364, -7599, 661, -2411, -3576, 5517, -3823, -968] -- [-643] -- [11892, 16329, -15095, -15461] -- or whatever ``` -/ @[user_command] meta def sample_cmd (_ : parse $ tk "#sample") : lean.parser unit := do e ← texpr, of_tactic $ do e ← i_to_expr e, (repr_inst, gen) ← mk_generator e, print_samples ← mk_mapp ``print_samples [none, repr_inst, gen], sample ← eval_expr (io unit) print_samples, unsafe_run_io sample end slim_check
35a9b175dcfb1c73fe025731b9176928f32dc9f7
05f637fa14ac28031cb1ea92086a0f4eb23ff2b1
/examples/lean/tc.lean
f7e98136c979ae0a7894ba20a7b3716a194df2f1
[ "Apache-2.0" ]
permissive
codyroux/lean0.1
1ce92751d664aacff0529e139083304a7bbc8a71
0dc6fb974aa85ed6f305a2f4b10a53a44ee5f0ef
refs/heads/master
1,610,830,535,062
1,402,150,480,000
1,402,150,480,000
19,588,851
2
0
null
null
null
null
UTF-8
Lean
false
false
1,727
lean
import macros definition reflexive {A : TypeU} (R : A → A → Bool) := ∀ x, R x x definition transitive {A : TypeU} (R : A → A → Bool) := ∀ x y z, R x y → R y z → R x z definition subrelation {A : TypeU} (R1 : A → A → Bool) (R2 : A → A → Bool) := ∀ x y, R1 x y → R2 x y infix 50 ⊆ : subrelation -- (tcls R) is the transitive closure of relation R -- We define it as the intersection of all transitive relations containing R definition tcls {A : TypeU} (R : A → A → Bool) (a b : A) := ∀ P, (reflexive P) → (transitive P) → (R ⊆ P) → P a b notation 65 _⁺ : tcls -- use superscript + as notation for transitive closure theorem tcls_trans {A : TypeU} {R : A → A → Bool} {a b c : A} (Hab : R⁺ a b) (Hbc : R⁺ b c) : R⁺ a c := take P, assume Hrefl Htrans Hsub, let Pab : P a b := Hab P Hrefl Htrans Hsub, Pbc : P b c := Hbc P Hrefl Htrans Hsub in Htrans a b c Pab Pbc theorem tcls_refl {A : TypeU} (R : A → A → Bool) : ∀ a, R⁺ a a := take a P, assume Hrefl Htrans Hsub, Hrefl a theorem tcls_sub {A : TypeU} (R : A → A → Bool) : R ⊆ R⁺ := take a b, assume Hab : R a b, show R⁺ a b, from take P, assume Hrefl Htrans Hsub, Hsub a b Hab theorem tcls_step {A : TypeU} {R : A → A → Bool} {a b c : A} (H1 : R a b) (H2 : R⁺ b c) : R⁺ a c := take P, assume Hrefl Htrans Hsub, Htrans a b c (Hsub a b H1) (H2 P Hrefl Htrans Hsub) theorem tcls_smallest {A : TypeU} (R : A → A → Bool) : ∀ P, (reflexive P) → (transitive P) → (R ⊆ P) → (R⁺ ⊆ P) := take P, assume Hrefl Htrans Hsub, take a b, assume H : R⁺ a b, show P a b, from H P Hrefl Htrans Hsub
8433f201b9b897d4539f7e80730d750560ea5368
32a2d1642d7519c99693bc1d3b24069e4853dd1f
/logic/relation.lean
4e9ed098489ada3a41890f0843881b71da208b28
[ "Apache-2.0" ]
permissive
Cedric0099/mathlib
7edb81d5d68e280b4d21f6c0377dad1f9b8c0d71
a97101d2df5d186848075a2d0452f6a04d8a13eb
refs/heads/master
1,584,201,847,599
1,524,979,632,000
1,524,979,632,000
131,690,350
0
0
null
1,525,162,341,000
1,525,162,341,000
null
UTF-8
Lean
false
false
8,214
lean
/- Copyright (c) 2018 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl Transitive reflexive as well as reflexive closure of relations. -/ import tactic variables {α : Type*} {β : Type*} {γ : Type*} {r : α → α → Prop} {a b c d : α} namespace relation /-- `refl_trans_gen r`: reflexive closure of `r` -/ inductive refl_trans_gen (r : α → α → Prop) (a : α) : α → Prop | refl {} : refl_trans_gen a | tail (b) {c} : refl_trans_gen b → r b c → refl_trans_gen c attribute [refl] refl_trans_gen.refl /-- `refl_trans_gen r`: reflexive transitive closure of `r` -/ inductive refl_gen (r : α → α → Prop) (a : α) : α → Prop | refl {} : refl_gen a | single {b} : r a b → refl_gen b attribute [refl] refl_gen.refl lemma refl_gen.to_refl_trans_gen : ∀{a b}, refl_gen r a b → refl_trans_gen r a b | a _ refl_gen.refl := by refl | a b (refl_gen.single h) := refl_trans_gen.tail _ refl_trans_gen.refl h namespace refl_trans_gen @[trans] lemma trans (hab : refl_trans_gen r a b) (hbc : refl_trans_gen r b c) : refl_trans_gen r a c := begin induction hbc, case refl_trans_gen.refl { assumption }, case refl_trans_gen.tail : c d hbc hcd hac { exact hac.tail _ hcd } end lemma single (hab : r a b) : refl_trans_gen r a b := refl.tail _ hab lemma head (hab : r a b) (hbc : refl_trans_gen r b c) : refl_trans_gen r a c := begin induction hbc, case refl_trans_gen.refl { exact refl.tail _ hab }, case refl_trans_gen.tail : c d hbc hcd hac { exact hac.tail _ hcd } end lemma head_induction_on {P : ∀(a:α), refl_trans_gen r a b → Prop} {a : α} (h : refl_trans_gen r a b) (refl : P b refl) (head : ∀{a c} (h' : r a c) (h : refl_trans_gen r c b), P c h → P a (h.head h')) : P a h := begin induction h generalizing P, case refl_trans_gen.refl { exact refl }, case refl_trans_gen.tail : b c hab hbc ih { apply ih, show P b _, from head hbc _ refl, show ∀a a', r a a' → refl_trans_gen r a' b → P a' _ → P a _, from assume a a' hab hbc, head hab _ } end lemma trans_induction_on {P : ∀{a b : α}, refl_trans_gen r a b → Prop} {a b : α} (h : refl_trans_gen r a b) (ih₁ : ∀a, @P a a refl) (ih₂ : ∀{a b} (h : r a b), P (single h)) (ih₃ : ∀{a b c} (h₁ : refl_trans_gen r a b) (h₂ : refl_trans_gen r b c), P h₁ → P h₂ → P (h₁.trans h₂)) : P h := begin induction h, case refl_trans_gen.refl { exact ih₁ a }, case refl_trans_gen.tail : b c hab hbc ih { exact ih₃ hab (single hbc) ih (ih₂ hbc) } end lemma cases_head (h : refl_trans_gen r a b) : a = b ∨ (∃c, r a c ∧ refl_trans_gen r c b) := begin induction h using relation.refl_trans_gen.head_induction_on, { left, refl }, { right, existsi _, split; assumption } end lemma cases_head_iff : refl_trans_gen r a b ↔ a = b ∨ (∃c, r a c ∧ refl_trans_gen r c b) := begin split, { exact cases_head }, { assume h, rcases h with rfl | ⟨c, hac, hcb⟩, { refl }, { exact head hac hcb } } end lemma cases_tail (h : refl_trans_gen r a b) : a = b ∨ (∃c, refl_trans_gen r a c ∧ r c b) := begin induction h, { left, refl }, { right, existsi _, split; assumption } end lemma cases_tail_iff : refl_trans_gen r a b ↔ a = b ∨ (∃c, refl_trans_gen r a c ∧ r c b) := begin split, { exact cases_tail }, { assume h, rcases h with rfl | ⟨c, hac, hcb⟩, { refl }, { exact tail _ hac hcb } } end end refl_trans_gen section refl_trans_gen open refl_trans_gen lemma refl_trans_gen_iff_eq (h : ∀b, ¬ r a b) : refl_trans_gen r a b ↔ b = a := by rw [cases_head_iff]; simp [h, eq_comm] lemma refl_trans_gen_lift {p : β → β → Prop} {a b : α} (f : α → β) (h : ∀a b, r a b → p (f a) (f b)) (hab : refl_trans_gen r a b) : refl_trans_gen p (f a) (f b) := hab.trans_induction_on (assume a, refl) (assume a b, refl_trans_gen.single ∘ h _ _) (assume a b c _ _, trans) lemma refl_trans_gen_mono {p : α → α → Prop} : (∀a b, r a b → p a b) → refl_trans_gen r a b → refl_trans_gen p a b := refl_trans_gen_lift id lemma refl_trans_gen_refl_trans_gen : refl_trans_gen (refl_trans_gen r) = refl_trans_gen r := funext $ assume a, funext $ assume b, propext $ iff.intro (assume h, begin induction h, { refl }, { transitivity; assumption } end) (refl_trans_gen_mono (assume a b, single)) lemma reflexive_refl_trans_gen : reflexive (refl_trans_gen r) := assume a, refl lemma transitive_refl_trans_gen : transitive (refl_trans_gen r) := assume a b c, trans end refl_trans_gen def join (r : α → α → Prop) : α → α → Prop := λa b, ∃c, r a c ∧ r b c section join open refl_trans_gen refl_gen lemma church_rosser (h : ∀a b c, r a b → r a c → ∃d, refl_gen r b d ∧ refl_trans_gen r c d) (hab : refl_trans_gen r a b) (hac : refl_trans_gen r a c) : join (refl_trans_gen r) b c := begin induction hab, case refl_trans_gen.refl { exact ⟨c, hac, refl⟩ }, case refl_trans_gen.tail : d e had hde ih { clear hac had a, rcases ih with ⟨b, hdb, hcb⟩, have : ∃a, refl_trans_gen r e a ∧ refl_gen r b a, { clear hcb, induction hdb, case refl_trans_gen.refl { exact ⟨e, refl, refl_gen.single hde⟩ }, case refl_trans_gen.tail : f b hdf hfb ih { rcases ih with ⟨a, hea, hfa⟩, cases hfa with _ hfa, { exact ⟨b, hea.tail _ hfb, refl_gen.refl⟩ }, { rcases h _ _ _ hfb hfa with ⟨c, hbc, hac⟩, exact ⟨c, hea.trans hac, hbc⟩ } } }, rcases this with ⟨a, hea, hba⟩, cases hba with _ hba, { exact ⟨b, hea, hcb⟩ }, { exact ⟨a, hea, hcb.tail _ hba⟩ } } end lemma join_of_single (h : reflexive r) (hab : r a b) : join r a b := ⟨b, hab, h b⟩ lemma symmetric_join : symmetric (join r) := assume a b ⟨c, hac, hcb⟩, ⟨c, hcb, hac⟩ lemma reflexive_join (h : reflexive r) : reflexive (join r) := assume a, ⟨a, h a, h a⟩ lemma transitive_join (ht : transitive r) (h : ∀a b c, r a b → r a c → join r b c) : transitive (join r) := assume a b c ⟨x, hax, hbx⟩ ⟨y, hby, hcy⟩, let ⟨z, hxz, hyz⟩ := h b x y hbx hby in ⟨z, ht hax hxz, ht hcy hyz⟩ lemma equivalence_join (hr : reflexive r) (ht : transitive r) (h : ∀a b c, r a b → r a c → join r b c) : equivalence (join r) := ⟨reflexive_join hr, symmetric_join, transitive_join ht h⟩ lemma equivalence_join_refl_trans_gen (h : ∀a b c, r a b → r a c → ∃d, refl_gen r b d ∧ refl_trans_gen r c d) : equivalence (join (refl_trans_gen r)) := equivalence_join reflexive_refl_trans_gen transitive_refl_trans_gen (assume a b c, church_rosser h) lemma join_of_equivalence {r' : α → α → Prop} (hr : equivalence r) (h : ∀a b, r' a b → r a b) : join r' a b → r a b | ⟨c, hac, hbc⟩ := hr.2.2 (h _ _ hac) (hr.2.1 $ h _ _ hbc) lemma refl_trans_gen_of_transitive_reflexive {r' : α → α → Prop} (hr : reflexive r) (ht : transitive r) (h : ∀a b, r' a b → r a b) (h' : refl_trans_gen r' a b) : r a b := begin induction h' with b c hab hbc ih, { exact hr _ }, { exact ht ih (h _ _ hbc) } end lemma refl_trans_gen_of_equivalence {r' : α → α → Prop} (hr : equivalence r) : (∀a b, r' a b → r a b) → refl_trans_gen r' a b → r a b := refl_trans_gen_of_transitive_reflexive hr.1 hr.2.2 end join section eqv_gen lemma eqv_gen_iff_of_equivalence (h : equivalence r) : eqv_gen r a b ↔ r a b := iff.intro begin assume h, induction h, case eqv_gen.rel { assumption }, case eqv_gen.refl { exact h.1 _ }, case eqv_gen.symm { apply h.2.1, assumption }, case eqv_gen.trans : a b c _ _ hab hbc { exact h.2.2 hab hbc } end (eqv_gen.rel a b) lemma eqv_gen_mono {r p : α → α → Prop} (hrp : ∀a b, r a b → p a b) (h : eqv_gen r a b) : eqv_gen p a b := begin induction h, case eqv_gen.rel : a b h { exact eqv_gen.rel _ _ (hrp _ _ h) }, case eqv_gen.refl : { exact eqv_gen.refl _ }, case eqv_gen.symm : a b h ih { exact eqv_gen.symm _ _ ih }, case eqv_gen.trans : a b c ih1 ih2 hab hbc { exact eqv_gen.trans _ _ _ hab hbc } end end eqv_gen end relation
97984d05bff5317c679d86df138edc2416d266bc
9dc8cecdf3c4634764a18254e94d43da07142918
/src/order/interval.lean
76defaf048fa9ddc46dab9c537a1f5950c457c9d
[ "Apache-2.0" ]
permissive
jcommelin/mathlib
d8456447c36c176e14d96d9e76f39841f69d2d9b
ee8279351a2e434c2852345c51b728d22af5a156
refs/heads/master
1,664,782,136,488
1,663,638,983,000
1,663,638,983,000
132,563,656
0
0
Apache-2.0
1,663,599,929,000
1,525,760,539,000
Lean
UTF-8
Lean
false
false
16,174
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 data.set.intervals.basic import data.set.lattice import data.set_like.basic /-! # Order intervals This file defines (nonempty) closed intervals in an order (see `set.Icc`). This is a prototype for interval arithmetic. ## Main declarations * `nonempty_interval`: Nonempty intervals. Pairs where the second element is greater than the first. * `interval`: Intervals. Either `∅` or a nonempty interval. -/ open function order_dual set variables {α β γ : Type*} {ι : Sort*} {κ : ι → Sort*} /-- The nonempty closed intervals in an order. We define intervals by the pair of endpoints `fst`, `snd`. To convert intervals to the set of elements between these endpoints, use the coercion `nonempty_interval α → set α`. -/ @[ext] structure nonempty_interval (α : Type*) [has_le α] extends α × α := (fst_le_snd : fst ≤ snd) namespace nonempty_interval section has_le variables [has_le α] {s t : nonempty_interval α} /-- The injection that induces the order on intervals. -/ def to_dual_prod : nonempty_interval α → αᵒᵈ × α := to_prod @[simp] lemma to_dual_prod_apply (s : nonempty_interval α) : s.to_dual_prod = (to_dual s.fst, s.snd) := prod.mk.eta.symm lemma to_dual_prod_injective : injective (to_dual_prod : nonempty_interval α → αᵒᵈ × α) := λ s t, (ext_iff _ _).2 instance [is_empty α] : is_empty (nonempty_interval α) := ⟨λ s, is_empty_elim s.fst⟩ instance [subsingleton α] : subsingleton (nonempty_interval α) := to_dual_prod_injective.subsingleton instance : has_le (nonempty_interval α) := ⟨λ s t, t.fst ≤ s.fst ∧ s.snd ≤ t.snd⟩ lemma le_def : s ≤ t ↔ t.fst ≤ s.fst ∧ s.snd ≤ t.snd := iff.rfl /-- `to_dual_prod` as an order embedding. -/ @[simps] def to_dual_prod_hom : nonempty_interval α ↪o αᵒᵈ × α := { to_fun := to_dual_prod, inj' := to_dual_prod_injective, map_rel_iff' := λ _ _, iff.rfl } /-- Turn an interval into an interval in the dual order. -/ def dual : nonempty_interval α ≃ nonempty_interval αᵒᵈ := { to_fun := λ s, ⟨s.to_prod.swap, s.fst_le_snd⟩, inv_fun := λ s, ⟨s.to_prod.swap, s.fst_le_snd⟩, left_inv := λ s, ext _ _ $ prod.swap_swap _, right_inv := λ s, ext _ _ $ prod.swap_swap _ } @[simp] lemma fst_dual (s : nonempty_interval α) : s.dual.fst = to_dual s.snd := rfl @[simp] lemma snd_dual (s : nonempty_interval α) : s.dual.snd = to_dual s.fst := rfl end has_le section preorder variables [preorder α] [preorder β] [preorder γ] instance : preorder (nonempty_interval α) := preorder.lift to_dual_prod /-- `{a}` as an interval. -/ @[simps] def pure (a : α) : nonempty_interval α := ⟨⟨a, a⟩, le_rfl⟩ lemma pure_injective : injective (pure : α → nonempty_interval α) := λ s t, congr_arg $ prod.fst ∘ to_prod @[simp] lemma dual_pure (a : α) : (pure a).dual = pure (to_dual a) := rfl instance [inhabited α] : inhabited (nonempty_interval α) := ⟨pure default⟩ instance : ∀ [nonempty α], nonempty (nonempty_interval α) := nonempty.map pure instance [nontrivial α] : nontrivial (nonempty_interval α) := pure_injective.nontrivial /-- Pushforward of nonempty intervals. -/ @[simps] def map (f : α →o β) (a : nonempty_interval α) : nonempty_interval β := ⟨a.to_prod.map f f, f.mono a.fst_le_snd⟩ @[simp] lemma map_pure (f : α →o β) (a : α) : (pure a).map f = pure (f a) := rfl @[simp] lemma map_map (g : β →o γ) (f : α →o β) (a : nonempty_interval α) : (a.map f).map g = a.map (g.comp f) := rfl @[simp] lemma dual_map (f : α →o β) (a : nonempty_interval α) : (a.map f).dual = a.dual.map f.dual := rfl variables [bounded_order α] instance : order_top (nonempty_interval α) := { top := ⟨⟨⊥, ⊤⟩, bot_le⟩, le_top := λ a, ⟨bot_le, le_top⟩ } @[simp] lemma dual_top : (⊤ : nonempty_interval α).dual = ⊤ := rfl end preorder section partial_order variables [partial_order α] {s t : nonempty_interval α} {x : α × α} {a : α} instance : partial_order (nonempty_interval α) := partial_order.lift _ to_dual_prod_injective /-- Consider a nonempty interval `[a, b]` as the set `[a, b]`. -/ def coe_hom : nonempty_interval α ↪o set α := order_embedding.of_map_le_iff (λ s, Icc s.fst s.snd) (λ s t, Icc_subset_Icc_iff s.fst_le_snd) instance : set_like (nonempty_interval α) α := { coe := λ s, Icc s.fst s.snd, coe_injective' := coe_hom.injective } @[simp] lemma mem_mk {hx : x.1 ≤ x.2} : a ∈ mk x hx ↔ x.1 ≤ a ∧ a ≤ x.2 := iff.rfl lemma mem_def : a ∈ s ↔ s.fst ≤ a ∧ a ≤ s.snd := iff.rfl @[simp, norm_cast] lemma coe_subset_coe : (s : set α) ⊆ t ↔ s ≤ t := (@coe_hom α _).le_iff_le @[simp, norm_cast] lemma coe_ssubset_coe : (s : set α) ⊂ t ↔ s < t := (@coe_hom α _).lt_iff_lt @[simp] lemma coe_nonempty (s : nonempty_interval α) : (s : set α).nonempty := nonempty_Icc.2 s.fst_le_snd @[simp] lemma coe_coe_hom : (coe_hom : nonempty_interval α → set α) = coe := rfl @[simp, norm_cast] lemma coe_pure (s : α) : (pure s : set α) = {s} := Icc_self _ @[simp, norm_cast] lemma coe_top [bounded_order α] : ((⊤ : nonempty_interval α) : set α) = univ := Icc_bot_top @[simp, norm_cast] lemma coe_dual (s : nonempty_interval α) : (s.dual : set αᵒᵈ) = of_dual ⁻¹' s := dual_Icc end partial_order section lattice variables [lattice α] instance : has_sup (nonempty_interval α) := ⟨λ s t, ⟨⟨s.fst ⊓ t.fst, s.snd ⊔ t.snd⟩, inf_le_left.trans $ s.fst_le_snd.trans le_sup_left⟩⟩ instance : semilattice_sup (nonempty_interval α) := to_dual_prod_injective.semilattice_sup _ $ λ _ _, rfl @[simp] lemma fst_sup (s t : nonempty_interval α) : (s ⊔ t).fst = s.fst ⊓ t.fst := rfl @[simp] lemma snd_sup (s t : nonempty_interval α) : (s ⊔ t).snd = s.snd ⊔ t.snd := rfl end lattice end nonempty_interval /-- The closed intervals in an order. We represent intervals either as `⊥` or a nonempty interval given by its endpoints `fst`, `snd`. To convert intervals to the set of elements between these endpoints, use the coercion `interval α → set α`. -/ @[derive [inhabited, has_le, order_bot]] def interval (α : Type*) [has_le α] := with_bot (nonempty_interval α) namespace interval section has_le variables [has_le α] {s t : interval α} instance : has_coe_t (nonempty_interval α) (interval α) := with_bot.has_coe_t instance : can_lift (interval α) (nonempty_interval α) := with_bot.can_lift lemma coe_injective : injective (coe : nonempty_interval α → interval α) := with_bot.coe_injective @[simp, norm_cast] lemma coe_inj {s t : nonempty_interval α} : (s : interval α) = t ↔ s = t := with_bot.coe_inj @[protected] lemma «forall» {p : interval α → Prop} : (∀ s, p s) ↔ p ⊥ ∧ ∀ s : nonempty_interval α, p s := option.forall @[protected] lemma «exists» {p : interval α → Prop} : (∃ s, p s) ↔ p ⊥ ∨ ∃ s : nonempty_interval α, p s := option.exists instance [is_empty α] : unique (interval α) := option.unique /-- Turn an interval into an interval in the dual order. -/ def dual : interval α ≃ interval αᵒᵈ := nonempty_interval.dual.option_congr end has_le section preorder variables [preorder α] [preorder β] [preorder γ] instance : preorder (interval α) := with_bot.preorder /-- `{a}` as an interval. -/ def pure (a : α) : interval α := nonempty_interval.pure a lemma pure_injective : injective (pure : α → interval α) := coe_injective.comp nonempty_interval.pure_injective @[simp] lemma dual_pure (a : α) : (pure a).dual = pure (to_dual a) := rfl @[simp] lemma dual_bot : (⊥ : interval α).dual = ⊥ := rfl instance [nonempty α] : nontrivial (interval α) := option.nontrivial /-- Pushforward of intervals. -/ def map (f : α →o β) : interval α → interval β := with_bot.map (nonempty_interval.map f) @[simp] lemma map_pure (f : α →o β) (a : α) : (pure a).map f = pure (f a) := rfl @[simp] lemma map_map (g : β →o γ) (f : α →o β) (s : interval α) : (s.map f).map g = s.map (g.comp f) := option.map_map _ _ _ @[simp] lemma dual_map (f : α →o β) (s : interval α) : (s.map f).dual = s.dual.map f.dual := by { cases s, { refl }, { exact with_bot.map_comm rfl _ } } variables [bounded_order α] instance : bounded_order (interval α) := with_bot.bounded_order @[simp] lemma dual_top : (⊤ : interval α).dual = ⊤ := rfl end preorder section partial_order variables [partial_order α] {s t : interval α} instance : partial_order (interval α) := with_bot.partial_order /-- Consider a interval `[a, b]` as the set `[a, b]`. -/ def coe_hom : interval α ↪o set α := order_embedding.of_map_le_iff (λ s, match s with | ⊥ := ∅ | some s := s end) (λ s t, match s, t with | ⊥, t := iff_of_true bot_le bot_le | some s, ⊥ := iff_of_false (λ h, s.coe_nonempty.ne_empty $ le_bot_iff.1 h) (with_bot.not_coe_le_bot _) | some s, some t := (@nonempty_interval.coe_hom α _).le_iff_le.trans with_bot.some_le_some.symm end) instance : set_like (interval α) α := { coe := coe_hom, coe_injective' := coe_hom.injective } @[simp, norm_cast] lemma coe_subset_coe : (s : set α) ⊆ t ↔ s ≤ t := (@coe_hom α _).le_iff_le @[simp, norm_cast] lemma coe_ssubset_coe : (s : set α) ⊂ t ↔ s < t := (@coe_hom α _).lt_iff_lt @[simp, norm_cast] lemma coe_pure (a : α) : (pure a : set α) = {a} := Icc_self _ @[simp, norm_cast] lemma coe_coe (s : nonempty_interval α) : ((s : interval α) : set α) = s := rfl @[simp, norm_cast] lemma coe_bot : ((⊥ : interval α) : set α) = ∅ := rfl @[simp, norm_cast] lemma coe_top [bounded_order α] : ((⊤ : interval α) : set α) = univ := Icc_bot_top @[simp, norm_cast] lemma coe_dual (s : interval α) : (s.dual : set αᵒᵈ) = of_dual ⁻¹' s := by { cases s, { refl }, exact s.coe_dual } end partial_order section lattice variables [lattice α] instance : semilattice_sup (interval α) := with_bot.semilattice_sup variables [@decidable_rel α (≤)] instance : lattice (interval α) := { inf := λ s t, match s, t with | ⊥, t := ⊥ | s, ⊥ := ⊥ | some s, some t := if h : s.fst ≤ t.snd ∧ t.fst ≤ s.snd then some ⟨⟨s.fst ⊔ t.fst, s.snd ⊓ t.snd⟩, sup_le (le_inf s.fst_le_snd h.1) $ le_inf h.2 t.fst_le_snd⟩ else ⊥ end, inf_le_left := λ s t, match s, t with | ⊥, ⊥ := bot_le | ⊥, some t := bot_le | some s, ⊥ := bot_le | some s, some t := begin change dite _ _ _ ≤ _, split_ifs, { exact with_bot.some_le_some.2 ⟨le_sup_left, inf_le_left⟩ }, { exact bot_le } end end, inf_le_right := λ s t, match s, t with | ⊥, ⊥ := bot_le | ⊥, some t := bot_le | some s, ⊥ := bot_le | some s, some t := begin change dite _ _ _ ≤ _, split_ifs, { exact with_bot.some_le_some.2 ⟨le_sup_right, inf_le_right⟩ }, { exact bot_le } end end, le_inf := λ s t c, match s, t, c with | ⊥, t, c := λ _ _, bot_le | some s, t, c := λ hb hc, begin lift t to nonempty_interval α using ne_bot_of_le_ne_bot with_bot.coe_ne_bot hb, lift c to nonempty_interval α using ne_bot_of_le_ne_bot with_bot.coe_ne_bot hc, change _ ≤ dite _ _ _, simp only [with_bot.some_eq_coe, with_bot.coe_le_coe] at ⊢ hb hc, rw [dif_pos, with_bot.coe_le_coe], exact ⟨sup_le hb.1 hc.1, le_inf hb.2 hc.2⟩, exact ⟨hb.1.trans $ s.fst_le_snd.trans hc.2, hc.1.trans $ s.fst_le_snd.trans hb.2⟩, end end, ..interval.semilattice_sup } @[simp, norm_cast] lemma coe_inf (s t : interval α) : (↑(s ⊓ t) : set α) = s ∩ t := begin cases s, { rw [with_bot.none_eq_bot, bot_inf_eq], exact (empty_inter _).symm }, cases t, { rw [with_bot.none_eq_bot, inf_bot_eq], exact (inter_empty _).symm }, refine (_ : coe (dite _ _ _) = _).trans Icc_inter_Icc.symm, split_ifs, { refl }, { exact (Icc_eq_empty $ λ H, h ⟨le_sup_left.trans $ H.trans inf_le_right, le_sup_right.trans $ H.trans inf_le_left⟩).symm } end @[simp, norm_cast] lemma disjoint_coe (s t : interval α) : disjoint (s : set α) t ↔ disjoint s t := by { rw [disjoint, disjoint, le_eq_subset, ←coe_subset_coe, coe_inf], refl } end lattice end interval namespace nonempty_interval section preorder variables [preorder α] @[simp, norm_cast] lemma coe_pure_interval (s : α) : (pure s : interval α) = interval.pure s := rfl @[simp, norm_cast] lemma coe_top_interval [bounded_order α] : ((⊤ : nonempty_interval α) : interval α) = ⊤ := rfl end preorder @[simp, norm_cast] lemma mem_coe_interval [partial_order α] {s : nonempty_interval α} {x : α} : x ∈ (s : interval α) ↔ x ∈ s := iff.rfl @[simp, norm_cast] lemma coe_sup_interval [lattice α] (s t : nonempty_interval α) : (↑(s ⊔ t) : interval α) = s ⊔ t := rfl end nonempty_interval namespace interval section complete_lattice variables [complete_lattice α] noncomputable instance [@decidable_rel α (≤)] : complete_lattice (interval α) := by classical; exact { Sup := λ S, if h : S ⊆ {⊥} then ⊥ else some ⟨⟨⨅ (s : nonempty_interval α) (h : ↑s ∈ S), s.fst, ⨆ (s : nonempty_interval α) (h : ↑s ∈ S), s.snd⟩, begin obtain ⟨s, hs, ha⟩ := not_subset.1 h, lift s to nonempty_interval α using ha, exact infi₂_le_of_le s hs (le_supr₂_of_le s hs s.fst_le_snd) end⟩, le_Sup := λ s s ha, begin split_ifs, { exact (h ha).le }, cases s, { exact bot_le }, { exact with_bot.some_le_some.2 ⟨infi₂_le _ ha, le_supr₂_of_le _ ha le_rfl⟩ } end, Sup_le := λ s s ha, begin split_ifs, { exact bot_le }, obtain ⟨b, hs, hb⟩ := not_subset.1 h, lift s to nonempty_interval α using ne_bot_of_le_ne_bot hb (ha _ hs), exact with_bot.coe_le_coe.2 ⟨le_infi₂ $ λ c hc, (with_bot.coe_le_coe.1 $ ha _ hc).1, supr₂_le $ λ c hc, (with_bot.coe_le_coe.1 $ ha _ hc).2⟩, end, Inf := λ S, if h : ⊥ ∉ S ∧ ∀ ⦃s : nonempty_interval α⦄, ↑s ∈ S → ∀ ⦃t : nonempty_interval α⦄, ↑t ∈ S → s.fst ≤ t.snd then some ⟨⟨⨆ (s : nonempty_interval α) (h : ↑s ∈ S), s.fst, ⨅ (s : nonempty_interval α) (h : ↑s ∈ S), s.snd⟩, supr₂_le $ λ s hs, le_infi₂ $ h.2 hs⟩ else ⊥, Inf_le := λ s s ha, begin split_ifs, { lift s to nonempty_interval α using ne_of_mem_of_not_mem ha h.1, exact with_bot.coe_le_coe.2 ⟨le_supr₂ s ha, infi₂_le s ha⟩ }, { exact bot_le } end, le_Inf := λ S s ha, begin cases s, { exact bot_le }, split_ifs, { exact with_bot.some_le_some.2 ⟨supr₂_le $ λ t hb, (with_bot.coe_le_coe.1 $ ha _ hb).1, le_infi₂ $ λ t hb, (with_bot.coe_le_coe.1 $ ha _ hb).2⟩ }, rw [not_and_distrib, not_not] at h, cases h, { exact ha _ h }, cases h (λ t hb c hc, (with_bot.coe_le_coe.1 $ ha _ hb).1.trans $ s.fst_le_snd.trans (with_bot.coe_le_coe.1 $ ha _ hc).2), end, ..interval.lattice, ..interval.bounded_order } @[simp, norm_cast] lemma coe_Inf (S : set (interval α)) : ↑(Inf S) = ⋂ s ∈ S, (s : set α) := begin change coe (dite _ _ _) = _, split_ifs, { ext, simp [with_bot.some_eq_coe, interval.forall, h.1, ←forall_and_distrib, ←nonempty_interval.mem_def] }, simp_rw [not_and_distrib, not_not] at h, cases h, { refine (eq_empty_of_subset_empty _).symm, exact Inter₂_subset_of_subset _ h subset.rfl }, { refine (not_nonempty_iff_eq_empty.1 _).symm, rintro ⟨x, hx⟩, rw mem_Inter₂ at hx, exact h (λ s ha t hb, (hx _ ha).1.trans (hx _ hb).2) } end @[simp, norm_cast] lemma coe_infi (f : ι → interval α) : ↑(⨅ i, f i) = ⋂ i, (f i : set α) := by simp [infi] @[simp, norm_cast] lemma coe_infi₂ (f : Π i, κ i → interval α) : ↑(⨅ i j, f i j) = ⋂ i j, (f i j : set α) := by simp_rw [coe_infi] end complete_lattice end interval
a3196377f59ea829830922b938af9b15e5815681
4727251e0cd73359b15b664c3170e5d754078599
/src/algebra/homology/homotopy.lean
5d37a038749699dd10ff158e406ed1f9c9c8c1a7
[ "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
32,236
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 algebra.homology.additive import tactic.abel /-! # Chain homotopies We define chain homotopies, and prove that homotopic chain maps induce the same map on homology. -/ universes v u open_locale classical noncomputable theory open category_theory category_theory.limits homological_complex variables {ι : Type*} variables {V : Type u} [category.{v} V] [preadditive V] variables {c : complex_shape ι} {C D E : homological_complex V c} variables (f g : C ⟶ D) (h k : D ⟶ E) (i : ι) section /-- The composition of `C.d i i' ≫ f i' i` if there is some `i'` coming after `i`, and `0` otherwise. -/ def d_next (i : ι) : (Π i j, C.X i ⟶ D.X j) →+ (C.X i ⟶ D.X i) := add_monoid_hom.mk' (λ f, match c.next i with | none := 0 | some ⟨i',w⟩ := C.d i i' ≫ f i' i end) begin intros f g, rcases c.next i with _|⟨i',w⟩, exact (zero_add _).symm, exact preadditive.comp_add _ _ _ _ _ _, end /-- `f i' i` if `i'` comes after `i`, and 0 if there's no such `i'`. Hopefully there won't be much need for this, except in `d_next_eq_d_from_from_next` to see that `d_next` factors through `C.d_from i`. -/ def from_next [has_zero_object V] (i : ι) : (Π i j, C.X i ⟶ D.X j) →+ (C.X_next i ⟶ D.X i) := add_monoid_hom.mk' (λ f, match c.next i with | none := 0 | some ⟨i',w⟩ := (C.X_next_iso w).hom ≫ f i' i end) begin intros f g, rcases c.next i with _|⟨i',w⟩, exact (zero_add _).symm, exact preadditive.comp_add _ _ _ _ _ _, end @[simp] lemma d_next_eq_d_from_from_next [has_zero_object V] (f : Π i j, C.X i ⟶ D.X j) (i : ι) : d_next i f = C.d_from i ≫ from_next i f := begin dsimp [d_next, from_next], rcases c.next i with ⟨⟩|⟨⟨i', w⟩⟩; { dsimp [d_next, from_next], simp }, end lemma d_next_eq (f : Π i j, C.X i ⟶ D.X j) {i i' : ι} (w : c.rel i i') : d_next i f = C.d i i' ≫ f i' i := begin dsimp [d_next], rw c.next_eq_some w, refl, end @[simp] lemma d_next_comp_left (f : C ⟶ D) (g : Π i j, D.X i ⟶ E.X j) (i : ι) : d_next i (λ i j, f.f i ≫ g i j) = f.f i ≫ d_next i g := begin dsimp [d_next], rcases c.next i with _|⟨i',w⟩, { exact comp_zero.symm, }, { dsimp [d_next], simp, }, end @[simp] lemma d_next_comp_right (f : Π i j, C.X i ⟶ D.X j) (g : D ⟶ E) (i : ι) : d_next i (λ i j, f i j ≫ g.f j) = d_next i f ≫ g.f i := begin dsimp [d_next], rcases c.next i with _|⟨i',w⟩, { exact zero_comp.symm, }, { dsimp [d_next], simp, }, end /-- The composition of `f j j' ≫ D.d j' j` if there is some `j'` coming before `j`, and `0` otherwise. -/ def prev_d (j : ι) : (Π i j, C.X i ⟶ D.X j) →+ (C.X j ⟶ D.X j) := add_monoid_hom.mk' (λ f, match c.prev j with | none := 0 | some ⟨j',w⟩ := f j j' ≫ D.d j' j end) begin intros f g, rcases c.prev j with _|⟨j',w⟩, exact (zero_add _).symm, exact preadditive.add_comp _ _ _ _ _ _, end /-- `f j j'` if `j'` comes after `j`, and 0 if there's no such `j'`. Hopefully there won't be much need for this, except in `d_next_eq_d_from_from_next` to see that `d_next` factors through `C.d_from i`. -/ def to_prev [has_zero_object V] (j : ι) : (Π i j, C.X i ⟶ D.X j) →+ (C.X j ⟶ D.X_prev j) := add_monoid_hom.mk' (λ f, match c.prev j with | none := 0 | some ⟨j',w⟩ := f j j' ≫ (D.X_prev_iso w).inv end) begin intros f g, rcases c.prev j with _|⟨j',w⟩, exact (zero_add _).symm, exact preadditive.add_comp _ _ _ _ _ _, end @[simp] lemma prev_d_eq_to_prev_d_to [has_zero_object V] (f : Π i j, C.X i ⟶ D.X j) (j : ι) : prev_d j f = to_prev j f ≫ D.d_to j := begin dsimp [prev_d, to_prev], rcases c.prev j with ⟨⟩|⟨⟨j', w⟩⟩; { dsimp [prev_d, to_prev], simp }, end lemma prev_d_eq (f : Π i j, C.X i ⟶ D.X j) {j j' : ι} (w : c.rel j' j) : prev_d j f = f j j' ≫ D.d j' j := begin dsimp [prev_d], rw c.prev_eq_some w, refl, end @[simp] lemma prev_d_comp_left (f : C ⟶ D) (g : Π i j, D.X i ⟶ E.X j) (j : ι) : prev_d j (λ i j, f.f i ≫ g i j) = f.f j ≫ prev_d j g := begin dsimp [prev_d], rcases c.prev j with _|⟨j',w⟩, { exact comp_zero.symm, }, { dsimp [prev_d, hom.prev], simp, }, end @[simp] lemma prev_d_comp_right (f : Π i j, C.X i ⟶ D.X j) (g : D ⟶ E) (j : ι) : prev_d j (λ i j, f i j ≫ g.f j) = prev_d j f ≫ g.f j := begin dsimp [prev_d], rcases c.prev j with _|⟨j',w⟩, { exact zero_comp.symm, }, { dsimp [prev_d], simp, }, end lemma d_next_nat (C D : chain_complex V ℕ) (i : ℕ) (f : Π i j, C.X i ⟶ D.X j) : d_next i f = C.d i (i-1) ≫ f (i-1) i := begin cases i, { dsimp [d_next], rcases (complex_shape.down ℕ).next 0 with _|⟨j,hj⟩; dsimp [d_next], { rw [C.shape, zero_comp], dsimp, dec_trivial }, { dsimp at hj, exact (nat.succ_ne_zero _ hj).elim } }, rw d_next_eq, dsimp, refl end lemma prev_d_nat (C D : cochain_complex V ℕ) (i : ℕ) (f : Π i j, C.X i ⟶ D.X j) : prev_d i f = f i (i-1) ≫ D.d (i-1) i := begin cases i, { dsimp [prev_d], rcases (complex_shape.up ℕ).prev 0 with _|⟨j,hj⟩; dsimp [prev_d], { rw [D.shape, comp_zero], dsimp, dec_trivial }, { dsimp at hj, exact (nat.succ_ne_zero _ hj).elim } }, rw prev_d_eq, dsimp, refl end /-- A homotopy `h` between chain maps `f` and `g` consists of components `h i j : C.X i ⟶ D.X j` which are zero unless `c.rel j i`, satisfying the homotopy condition. -/ @[ext, nolint has_inhabited_instance] structure homotopy (f g : C ⟶ D) := (hom : Π i j, C.X i ⟶ D.X j) (zero' : ∀ i j, ¬ c.rel j i → hom i j = 0 . obviously) (comm : ∀ i, f.f i = d_next i hom + prev_d i hom + g.f i . obviously') variables {f g} namespace homotopy restate_axiom homotopy.zero' /-- `f` is homotopic to `g` iff `f - g` is homotopic to `0`. -/ def equiv_sub_zero : homotopy f g ≃ homotopy (f - g) 0 := { to_fun := λ h, { hom := λ i j, h.hom i j, zero' := λ i j w, h.zero _ _ w, comm := λ i, by simp [h.comm] }, inv_fun := λ h, { hom := λ i j, h.hom i j, zero' := λ i j w, h.zero _ _ w, comm := λ i, by simpa [sub_eq_iff_eq_add] using h.comm i }, left_inv := by tidy, right_inv := by tidy, } /-- Equal chain maps are homotopic. -/ @[simps] def of_eq (h : f = g) : homotopy f g := { hom := 0, zero' := λ _ _ _, rfl, comm := λ _, by simp only [add_monoid_hom.map_zero, zero_add, h] } /-- Every chain map is homotopic to itself. -/ @[simps, refl] def refl (f : C ⟶ D) : homotopy f f := of_eq (rfl : f = f) /-- `f` is homotopic to `g` iff `g` is homotopic to `f`. -/ @[simps, symm] def symm {f g : C ⟶ D} (h : homotopy f g) : homotopy g f := { hom := -h.hom, zero' := λ i j w, by rw [pi.neg_apply, pi.neg_apply, h.zero i j w, neg_zero], comm := λ i, by rw [add_monoid_hom.map_neg, add_monoid_hom.map_neg, h.comm, ← neg_add, ← add_assoc, neg_add_self, zero_add] } /-- homotopy is a transitive relation. -/ @[simps, trans] def trans {e f g : C ⟶ D} (h : homotopy e f) (k : homotopy f g) : homotopy e g := { hom := h.hom + k.hom, zero' := λ i j w, by rw [pi.add_apply, pi.add_apply, h.zero i j w, k.zero i j w, zero_add], comm := λ i, by { rw [add_monoid_hom.map_add, add_monoid_hom.map_add, h.comm, k.comm], abel }, } /-- the sum of two homotopies is a homotopy between the sum of the respective morphisms. -/ @[simps] def add {f₁ g₁ f₂ g₂ : C ⟶ D} (h₁ : homotopy f₁ g₁) (h₂ : homotopy f₂ g₂) : homotopy (f₁+f₂) (g₁+g₂) := { hom := h₁.hom + h₂.hom, zero' := λ i j hij, by rw [pi.add_apply, pi.add_apply, h₁.zero' i j hij, h₂.zero' i j hij, add_zero], comm := λ i, by { simp only [homological_complex.add_f_apply, h₁.comm, h₂.comm, add_monoid_hom.map_add], abel, }, } /-- homotopy is closed under composition (on the right) -/ @[simps] def comp_right {e f : C ⟶ D} (h : homotopy e f) (g : D ⟶ E) : homotopy (e ≫ g) (f ≫ g) := { hom := λ i j, h.hom i j ≫ g.f j, zero' := λ i j w, by rw [h.zero i j w, zero_comp], comm := λ i, by simp only [h.comm i, d_next_comp_right, preadditive.add_comp, prev_d_comp_right, comp_f], } /-- homotopy is closed under composition (on the left) -/ @[simps] def comp_left {f g : D ⟶ E} (h : homotopy f g) (e : C ⟶ D) : homotopy (e ≫ f) (e ≫ g) := { hom := λ i j, e.f i ≫ h.hom i j, zero' := λ i j w, by rw [h.zero i j w, comp_zero], comm := λ i, by simp only [h.comm i, d_next_comp_left, preadditive.comp_add, prev_d_comp_left, comp_f], } /-- homotopy is closed under composition -/ @[simps] def comp {C₁ C₂ C₃ : homological_complex V c} {f₁ g₁ : C₁ ⟶ C₂} {f₂ g₂ : C₂ ⟶ C₃} (h₁ : homotopy f₁ g₁) (h₂ : homotopy f₂ g₂) : homotopy (f₁ ≫ f₂) (g₁ ≫ g₂) := (h₁.comp_right _).trans (h₂.comp_left _) /-- a variant of `homotopy.comp_right` useful for dealing with homotopy equivalences. -/ @[simps] def comp_right_id {f : C ⟶ C} (h : homotopy f (𝟙 C)) (g : C ⟶ D) : homotopy (f ≫ g) g := (h.comp_right g).trans (of_eq $ category.id_comp _) /-- a variant of `homotopy.comp_left` useful for dealing with homotopy equivalences. -/ @[simps] def comp_left_id {f : D ⟶ D} (h : homotopy f (𝟙 D)) (g : C ⟶ D) : homotopy (g ≫ f) g := (h.comp_left g).trans (of_eq $ category.comp_id _) /-! Null homotopic maps can be constructed using the formula `hd+dh`. We show that these morphisms are homotopic to `0` and provide some convenient simplification lemmas that give a degreewise description of `hd+dh`, depending on whether we have two differentials going to and from a certain degree, only one, or none. -/ /-- The null homotopic map associated to a family `hom` of morphisms `C_i ⟶ D_j`. This is the same datum as for the field `hom` in the structure `homotopy`. For this definition, we do not need the field `zero` of that structure as this definition uses only the maps `C_i ⟶ C_j` when `c.rel j i`. -/ def null_homotopic_map (hom : Π i j, C.X i ⟶ D.X j) : C ⟶ D := { f := λ i, d_next i hom + prev_d i hom, comm' := λ i j hij, begin have eq1 : prev_d i hom ≫ D.d i j = 0, { rcases h : c.prev i with _|⟨i',w⟩, { dsimp [prev_d], rw h, erw zero_comp, }, { rw [prev_d_eq hom w, category.assoc, D.d_comp_d' i' i j w hij, comp_zero], }, }, have eq2 : C.d i j ≫ d_next j hom = 0, { rcases h : c.next j with _|⟨j',w⟩, { dsimp [d_next], rw h, erw comp_zero, }, { rw [d_next_eq hom w, ← category.assoc, C.d_comp_d' i j j' hij w, zero_comp], }, }, rw [d_next_eq hom hij, prev_d_eq hom hij, preadditive.comp_add, preadditive.add_comp, eq1, eq2, add_zero, zero_add, category.assoc], end } /-- Variant of `null_homotopic_map` where the input consists only of the relevant maps `C_i ⟶ D_j` such that `c.rel j i`. -/ def null_homotopic_map' (h : Π i j, c.rel j i → (C.X i ⟶ D.X j)) : C ⟶ D := null_homotopic_map (λ i j, dite (c.rel j i) (h i j) (λ _, 0)) /-- Compatibility of `null_homotopic_map` with the postcomposition by a morphism of complexes. -/ lemma null_homotopic_map_comp (hom : Π i j, C.X i ⟶ D.X j) (g : D ⟶ E) : null_homotopic_map hom ≫ g = null_homotopic_map (λ i j, hom i j ≫ g.f j) := begin ext n, dsimp [null_homotopic_map], simp only [preadditive.add_comp, d_next_comp_right, prev_d_comp_right], end /-- Compatibility of `null_homotopic_map'` with the postcomposition by a morphism of complexes. -/ lemma null_homotopic_map'_comp (hom : Π i j, c.rel j i → (C.X i ⟶ D.X j)) (g : D ⟶ E) : null_homotopic_map' hom ≫ g = null_homotopic_map' (λ i j hij, hom i j hij ≫ g.f j) := begin ext n, erw null_homotopic_map_comp, congr', ext i j, split_ifs, { refl, }, { rw zero_comp, }, end /-- Compatibility of `null_homotopic_map` with the precomposition by a morphism of complexes. -/ lemma comp_null_homotopic_map (f : C ⟶ D) (hom : Π i j, D.X i ⟶ E.X j) : f ≫ null_homotopic_map hom = null_homotopic_map (λ i j, f.f i ≫ hom i j) := begin ext n, dsimp [null_homotopic_map], simp only [preadditive.comp_add, d_next_comp_left, prev_d_comp_left], end /-- Compatibility of `null_homotopic_map'` with the precomposition by a morphism of complexes. -/ lemma comp_null_homotopic_map' (f : C ⟶ D) (hom : Π i j, c.rel j i → (D.X i ⟶ E.X j)) : f ≫ null_homotopic_map' hom = null_homotopic_map' (λ i j hij, f.f i ≫ hom i j hij) := begin ext n, erw comp_null_homotopic_map, congr', ext i j, split_ifs, { refl, }, { rw comp_zero, }, end /-- Compatibility of `null_homotopic_map` with the application of additive functors -/ lemma map_null_homotopic_map {W : Type*} [category W] [preadditive W] (G : V ⥤ W) [G.additive] (hom : Π i j, C.X i ⟶ D.X j) : (G.map_homological_complex c).map (null_homotopic_map hom) = null_homotopic_map (λ i j, G.map (hom i j)) := begin ext i, dsimp [null_homotopic_map, d_next, prev_d], rcases c.next i with _|⟨inext,wn⟩; rcases c.prev i with _|⟨iprev,wp⟩; dsimp [d_next, prev_d]; simp only [G.map_comp, functor.map_zero, functor.map_add], end /-- Compatibility of `null_homotopic_map'` with the application of additive functors -/ lemma map_null_homotopic_map' {W : Type*} [category W] [preadditive W] (G : V ⥤ W) [G.additive] (hom : Π i j, c.rel j i → (C.X i ⟶ D.X j)) : (G.map_homological_complex c).map (null_homotopic_map' hom) = null_homotopic_map' (λ i j hij, G.map (hom i j hij)) := begin ext n, erw map_null_homotopic_map, congr', ext i j, split_ifs, { refl, }, { rw G.map_zero, } end /-- Tautological construction of the `homotopy` to zero for maps constructed by `null_homotopic_map`, at least when we have the `zero'` condition. -/ @[simps] def null_homotopy (hom : Π i j, C.X i ⟶ D.X j) (zero' : ∀ i j, ¬ c.rel j i → hom i j = 0) : homotopy (null_homotopic_map hom) 0 := { hom := hom, zero' := zero', comm := by { intro i, rw [homological_complex.zero_f_apply, add_zero], refl, }, } /-- Homotopy to zero for maps constructed with `null_homotopic_map'` -/ @[simps] def null_homotopy' (h : Π i j, c.rel j i → (C.X i ⟶ D.X j)) : homotopy (null_homotopic_map' h) 0 := begin apply null_homotopy (λ i j, dite (c.rel j i) (h i j) (λ _, 0)), intros i j hij, dsimp, rw [dite_eq_right_iff], intro hij', exfalso, exact hij hij', end /-! This lemma and the following ones can be used in order to compute the degreewise morphisms induced by the null homotopic maps constructed with `null_homotopic_map` or `null_homotopic_map'` -/ @[simp] lemma null_homotopic_map_f {k₂ k₁ k₀ : ι} (r₂₁ : c.rel k₂ k₁) (r₁₀ : c.rel k₁ k₀) (hom : Π i j, C.X i ⟶ D.X j) : (null_homotopic_map hom).f k₁ = C.d k₁ k₀ ≫ hom k₀ k₁ + hom k₁ k₂ ≫ D.d k₂ k₁ := by { dsimp [null_homotopic_map], rw [d_next_eq hom r₁₀, prev_d_eq hom r₂₁], } @[simp] lemma null_homotopic_map'_f {k₂ k₁ k₀ : ι} (r₂₁ : c.rel k₂ k₁) (r₁₀ : c.rel k₁ k₀) (h : Π i j, c.rel j i → (C.X i ⟶ D.X j)) : (null_homotopic_map' h).f k₁ = C.d k₁ k₀ ≫ h k₀ k₁ r₁₀ + h k₁ k₂ r₂₁ ≫ D.d k₂ k₁ := begin simp only [← null_homotopic_map'], rw null_homotopic_map_f r₂₁ r₁₀ (λ i j, dite (c.rel j i) (h i j) (λ _, 0)), dsimp, split_ifs, refl, end @[simp] lemma null_homotopic_map_f_of_not_rel_left {k₁ k₀ : ι} (r₁₀ : c.rel k₁ k₀) (hk₀ : ∀ l : ι, ¬c.rel k₀ l) (hom : Π i j, C.X i ⟶ D.X j) : (null_homotopic_map hom).f k₀ = hom k₀ k₁ ≫ D.d k₁ k₀ := begin dsimp [null_homotopic_map], rw prev_d_eq hom r₁₀, rcases h : c.next k₀ with _|⟨l,w⟩, swap, exfalso, exact hk₀ l w, dsimp [d_next], rw h, erw zero_add, end @[simp] lemma null_homotopic_map'_f_of_not_rel_left {k₁ k₀ : ι} (r₁₀ : c.rel k₁ k₀) (hk₀ : ∀ l : ι, ¬c.rel k₀ l) (h : Π i j, c.rel j i → (C.X i ⟶ D.X j)) : (null_homotopic_map' h).f k₀ = h k₀ k₁ r₁₀ ≫ D.d k₁ k₀ := begin simp only [← null_homotopic_map'], rw null_homotopic_map_f_of_not_rel_left r₁₀ hk₀ (λ i j, dite (c.rel j i) (h i j) (λ _, 0)), dsimp, split_ifs, refl, end @[simp] lemma null_homotopic_map_f_of_not_rel_right {k₁ k₀ : ι} (r₁₀ : c.rel k₁ k₀) (hk₁ : ∀ l : ι, ¬c.rel l k₁) (hom : Π i j, C.X i ⟶ D.X j) : (null_homotopic_map hom).f k₁ = C.d k₁ k₀ ≫ hom k₀ k₁ := begin dsimp [null_homotopic_map], rw d_next_eq hom r₁₀, rcases h : c.prev k₁ with _|⟨l,w⟩, swap, exfalso, exact hk₁ l w, dsimp [prev_d], rw h, erw add_zero, end @[simp] lemma null_homotopic_map'_f_of_not_rel_right {k₁ k₀ : ι} (r₁₀ : c.rel k₁ k₀) (hk₁ : ∀ l : ι, ¬c.rel l k₁) (h : Π i j, c.rel j i → (C.X i ⟶ D.X j)) : (null_homotopic_map' h).f k₁ = C.d k₁ k₀ ≫ h k₀ k₁ r₁₀ := begin simp only [← null_homotopic_map'], rw null_homotopic_map_f_of_not_rel_right r₁₀ hk₁ (λ i j, dite (c.rel j i) (h i j) (λ _, 0)), dsimp, split_ifs, refl, end @[simp] lemma null_homotopic_map_f_eq_zero {k₀ : ι} (hk₀ : ∀ l : ι, ¬c.rel k₀ l) (hk₀' : ∀ l : ι, ¬c.rel l k₀) (hom : Π i j, C.X i ⟶ D.X j) : (null_homotopic_map hom).f k₀ = 0 := begin dsimp [null_homotopic_map], rcases h1 : c.next k₀ with _|⟨l,w⟩, swap, exfalso, exact hk₀ l w, rcases h2 : c.prev k₀ with _|⟨l,w⟩, swap, exfalso, exact hk₀' l w, dsimp [d_next, prev_d], rw [h1, h2], erw zero_add, refl, end @[simp] lemma null_homotopic_map'_f_eq_zero {k₀ : ι} (hk₀ : ∀ l : ι, ¬c.rel k₀ l) (hk₀' : ∀ l : ι, ¬c.rel l k₀) (h : Π i j, c.rel j i → (C.X i ⟶ D.X j)) : (null_homotopic_map' h).f k₀ = 0 := begin simp only [← null_homotopic_map'], exact null_homotopic_map_f_eq_zero hk₀ hk₀' (λ i j, dite (c.rel j i) (h i j) (λ _, 0)), end /-! `homotopy.mk_inductive` allows us to build a homotopy of chain complexes inductively, so that as we construct each component, we have available the previous two components, and the fact that they satisfy the homotopy condition. To simplify the situation, we only construct homotopies of the form `homotopy e 0`. `homotopy.equiv_sub_zero` can provide the general case. Notice however, that this construction does not have particularly good definitional properties: we have to insert `eq_to_hom` in several places. Hopefully this is okay in most applications, where we only need to have the existence of some homotopy. -/ section mk_inductive variables {P Q : chain_complex V ℕ} @[simp] lemma prev_d_chain_complex (f : Π i j, P.X i ⟶ Q.X j) (j : ℕ) : prev_d j f = f j (j+1) ≫ Q.d _ _ := begin dsimp [prev_d], simp only [chain_complex.prev], refl, end @[simp] lemma d_next_succ_chain_complex (f : Π i j, P.X i ⟶ Q.X j) (i : ℕ) : d_next (i+1) f = P.d _ _ ≫ f i (i+1) := begin dsimp [d_next], simp only [chain_complex.next_nat_succ], refl, end @[simp] lemma d_next_zero_chain_complex (f : Π i j, P.X i ⟶ Q.X j) : d_next 0 f = 0 := begin dsimp [d_next], simp only [chain_complex.next_nat_zero], refl, end variables (e : P ⟶ Q) (zero : P.X 0 ⟶ Q.X 1) (comm_zero : e.f 0 = zero ≫ Q.d 1 0) (one : P.X 1 ⟶ Q.X 2) (comm_one : e.f 1 = P.d 1 0 ≫ zero + one ≫ Q.d 2 1) (succ : ∀ (n : ℕ) (p : Σ' (f : P.X n ⟶ Q.X (n+1)) (f' : P.X (n+1) ⟶ Q.X (n+2)), e.f (n+1) = P.d (n+1) n ≫ f + f' ≫ Q.d (n+2) (n+1)), Σ' f'' : P.X (n+2) ⟶ Q.X (n+3), e.f (n+2) = P.d (n+2) (n+1) ≫ p.2.1 + f'' ≫ Q.d (n+3) (n+2)) include comm_one comm_zero /-- An auxiliary construction for `mk_inductive`. Here we build by induction a family of diagrams, but don't require at the type level that these successive diagrams actually agree. They do in fact agree, and we then capture that at the type level (i.e. by constructing a homotopy) in `mk_inductive`. At this stage, we don't check the homotopy condition in degree 0, because it "falls off the end", and is easier to treat using `X_next` and `X_prev`, which we do in `mk_inductive_aux₂`. -/ @[simp, nolint unused_arguments] def mk_inductive_aux₁ : Π n, Σ' (f : P.X n ⟶ Q.X (n+1)) (f' : P.X (n+1) ⟶ Q.X (n+2)), e.f (n+1) = P.d (n+1) n ≫ f + f' ≫ Q.d (n+2) (n+1) | 0 := ⟨zero, one, comm_one⟩ | 1 := ⟨one, (succ 0 ⟨zero, one, comm_one⟩).1, (succ 0 ⟨zero, one, comm_one⟩).2⟩ | (n+2) := ⟨(mk_inductive_aux₁ (n+1)).2.1, (succ (n+1) (mk_inductive_aux₁ (n+1))).1, (succ (n+1) (mk_inductive_aux₁ (n+1))).2⟩ section variable [has_zero_object V] /-- An auxiliary construction for `mk_inductive`. -/ @[simp] def mk_inductive_aux₂ : Π n, Σ' (f : P.X_next n ⟶ Q.X n) (f' : P.X n ⟶ Q.X_prev n), e.f n = P.d_from n ≫ f + f' ≫ Q.d_to n | 0 := ⟨0, zero ≫ (Q.X_prev_iso rfl).inv, by simpa using comm_zero⟩ | (n+1) := let I := mk_inductive_aux₁ e zero comm_zero one comm_one succ n in ⟨(P.X_next_iso rfl).hom ≫ I.1, I.2.1 ≫ (Q.X_prev_iso rfl).inv, by simpa using I.2.2⟩ lemma mk_inductive_aux₃ (i : ℕ) : (mk_inductive_aux₂ e zero comm_zero one comm_one succ i).2.1 ≫ (Q.X_prev_iso rfl).hom = (P.X_next_iso rfl).inv ≫ (mk_inductive_aux₂ e zero comm_zero one comm_one succ (i+1)).1 := by rcases i with (_|_|i); { dsimp, simp, } /-- A constructor for a `homotopy e 0`, for `e` a chain map between `ℕ`-indexed chain complexes, working by induction. You need to provide the components of the homotopy in degrees 0 and 1, show that these satisfy the homotopy condition, and then give a construction of each component, and the fact that it satisfies the homotopy condition, using as an inductive hypothesis the data and homotopy condition for the previous two components. -/ def mk_inductive : homotopy e 0 := { hom := λ i j, if h : i + 1 = j then (mk_inductive_aux₂ e zero comm_zero one comm_one succ i).2.1 ≫ (Q.X_prev_iso h).hom else 0, zero' := λ i j w, by rwa dif_neg, comm := λ i, begin dsimp, simp only [add_zero], convert (mk_inductive_aux₂ e zero comm_zero one comm_one succ i).2.2, { rcases i with (_|_|_|i), { dsimp, simp only [d_next_zero_chain_complex, d_from_eq_zero, limits.comp_zero], }, all_goals { simp only [d_next_succ_chain_complex], dsimp, simp only [category.comp_id, category.assoc, iso.inv_hom_id, d_from_comp_X_next_iso_assoc, dite_eq_ite, if_true, eq_self_iff_true]}, }, { cases i, all_goals { simp only [prev_d_chain_complex], dsimp, simp only [category.comp_id, category.assoc, iso.inv_hom_id, X_prev_iso_comp_d_to, dite_eq_ite, if_true, eq_self_iff_true], }, }, end, } end end mk_inductive /-! `homotopy.mk_coinductive` allows us to build a homotopy of cochain complexes inductively, so that as we construct each component, we have available the previous two components, and the fact that they satisfy the homotopy condition. -/ section mk_coinductive variables {P Q : cochain_complex V ℕ} @[simp] lemma d_next_cochain_complex (f : Π i j, P.X i ⟶ Q.X j) (j : ℕ) : d_next j f = P.d _ _ ≫ f (j+1) j := begin dsimp [d_next], simp only [cochain_complex.next], refl, end @[simp] lemma prev_d_succ_cochain_complex (f : Π i j, P.X i ⟶ Q.X j) (i : ℕ) : prev_d (i+1) f = f (i+1) _ ≫ Q.d i (i+1) := begin dsimp [prev_d], simp [cochain_complex.prev_nat_succ], refl, end @[simp] lemma prev_d_zero_cochain_complex (f : Π i j, P.X i ⟶ Q.X j) : prev_d 0 f = 0 := begin dsimp [prev_d], simp only [cochain_complex.prev_nat_zero], refl, end variables (e : P ⟶ Q) (zero : P.X 1 ⟶ Q.X 0) (comm_zero : e.f 0 = P.d 0 1 ≫ zero) (one : P.X 2 ⟶ Q.X 1) (comm_one : e.f 1 = zero ≫ Q.d 0 1 + P.d 1 2 ≫ one) (succ : ∀ (n : ℕ) (p : Σ' (f : P.X (n+1) ⟶ Q.X n) (f' : P.X (n+2) ⟶ Q.X (n+1)), e.f (n+1) = f ≫ Q.d n (n+1) + P.d (n+1) (n+2) ≫ f'), Σ' f'' : P.X (n+3) ⟶ Q.X (n+2), e.f (n+2) = p.2.1 ≫ Q.d (n+1) (n+2) + P.d (n+2) (n+3) ≫ f'') include comm_one comm_zero succ /-- An auxiliary construction for `mk_coinductive`. Here we build by induction a family of diagrams, but don't require at the type level that these successive diagrams actually agree. They do in fact agree, and we then capture that at the type level (i.e. by constructing a homotopy) in `mk_coinductive`. At this stage, we don't check the homotopy condition in degree 0, because it "falls off the end", and is easier to treat using `X_next` and `X_prev`, which we do in `mk_inductive_aux₂`. -/ @[simp, nolint unused_arguments] def mk_coinductive_aux₁ : Π n, Σ' (f : P.X (n+1) ⟶ Q.X n) (f' : P.X (n+2) ⟶ Q.X (n+1)), e.f (n+1) = f ≫ Q.d n (n+1) + P.d (n+1) (n+2) ≫ f' | 0 := ⟨zero, one, comm_one⟩ | 1 := ⟨one, (succ 0 ⟨zero, one, comm_one⟩).1, (succ 0 ⟨zero, one, comm_one⟩).2⟩ | (n+2) := ⟨(mk_coinductive_aux₁ (n+1)).2.1, (succ (n+1) (mk_coinductive_aux₁ (n+1))).1, (succ (n+1) (mk_coinductive_aux₁ (n+1))).2⟩ section variable [has_zero_object V] /-- An auxiliary construction for `mk_inductive`. -/ @[simp] def mk_coinductive_aux₂ : Π n, Σ' (f : P.X n ⟶ Q.X_prev n) (f' : P.X_next n ⟶ Q.X n), e.f n = f ≫ Q.d_to n + P.d_from n ≫ f' | 0 := ⟨0, (P.X_next_iso rfl).hom ≫ zero, by simpa using comm_zero⟩ | (n+1) := let I := mk_coinductive_aux₁ e zero comm_zero one comm_one succ n in ⟨I.1 ≫ (Q.X_prev_iso rfl).inv, (P.X_next_iso rfl).hom ≫ I.2.1, by simpa using I.2.2⟩ lemma mk_coinductive_aux₃ (i : ℕ) : (mk_coinductive_aux₂ e zero comm_zero one comm_one succ i).2.1 ≫ (Q.X_prev_iso rfl).inv = (P.X_next_iso rfl).hom ≫ (mk_coinductive_aux₂ e zero comm_zero one comm_one succ (i+1)).1 := by rcases i with (_|_|i); { dsimp, simp, } /-- A constructor for a `homotopy e 0`, for `e` a chain map between `ℕ`-indexed cochain complexes, working by induction. You need to provide the components of the homotopy in degrees 0 and 1, show that these satisfy the homotopy condition, and then give a construction of each component, and the fact that it satisfies the homotopy condition, using as an inductive hypothesis the data and homotopy condition for the previous two components. -/ def mk_coinductive : homotopy e 0 := { hom := λ i j, if h : j + 1 = i then (P.X_next_iso h).inv ≫ (mk_coinductive_aux₂ e zero comm_zero one comm_one succ j).2.1 else 0, zero' := λ i j w, by rwa dif_neg, comm := λ i, begin dsimp, rw [add_zero, add_comm], convert (mk_coinductive_aux₂ e zero comm_zero one comm_one succ i).2.2 using 2, { rcases i with (_|_|_|i), { simp only [mk_coinductive_aux₂, prev_d_zero_cochain_complex, zero_comp] }, all_goals { simp only [prev_d_succ_cochain_complex], dsimp, simp only [eq_self_iff_true, iso.inv_hom_id_assoc, dite_eq_ite, if_true, category.assoc, X_prev_iso_comp_d_to], }, }, { cases i, { dsimp, simp only [eq_self_iff_true, d_next_cochain_complex, dif_pos, d_from_comp_X_next_iso_assoc, ←comm_zero], rw mk_coinductive_aux₂, dsimp, convert comm_zero.symm, simp only [iso.inv_hom_id_assoc], }, { dsimp, simp only [eq_self_iff_true, d_next_cochain_complex, dif_pos, d_from_comp_X_next_iso_assoc], rw mk_coinductive_aux₂, dsimp only, simp only [iso.inv_hom_id_assoc], }, }, end } end end mk_coinductive end homotopy /-- A homotopy equivalence between two chain complexes consists of a chain map each way, and homotopies from the compositions to the identity chain maps. Note that this contains data; arguably it might be more useful for many applications if we truncated it to a Prop. -/ structure homotopy_equiv (C D : homological_complex V c) := (hom : C ⟶ D) (inv : D ⟶ C) (homotopy_hom_inv_id : homotopy (hom ≫ inv) (𝟙 C)) (homotopy_inv_hom_id : homotopy (inv ≫ hom) (𝟙 D)) namespace homotopy_equiv /-- Any complex is homotopy equivalent to itself. -/ @[refl] def refl (C : homological_complex V c) : homotopy_equiv C C := { hom := 𝟙 C, inv := 𝟙 C, homotopy_hom_inv_id := by simp, homotopy_inv_hom_id := by simp, } instance : inhabited (homotopy_equiv C C) := ⟨refl C⟩ /-- Being homotopy equivalent is a symmetric relation. -/ @[symm] def symm {C D : homological_complex V c} (f : homotopy_equiv C D) : homotopy_equiv D C := { hom := f.inv, inv := f.hom, homotopy_hom_inv_id := f.homotopy_inv_hom_id, homotopy_inv_hom_id := f.homotopy_hom_inv_id, } /-- Homotopy equivalence is a transitive relation. -/ @[trans] def trans {C D E : homological_complex V c} (f : homotopy_equiv C D) (g : homotopy_equiv D E) : homotopy_equiv C E := { hom := f.hom ≫ g.hom, inv := g.inv ≫ f.inv, homotopy_hom_inv_id := by simpa using ((g.homotopy_hom_inv_id.comp_right_id f.inv).comp_left f.hom).trans f.homotopy_hom_inv_id, homotopy_inv_hom_id := by simpa using ((f.homotopy_inv_hom_id.comp_right_id g.hom).comp_left g.inv).trans g.homotopy_inv_hom_id, } end homotopy_equiv variables [has_equalizers V] [has_cokernels V] [has_images V] [has_image_maps V] [has_zero_object V] /-- Homotopic maps induce the same map on homology. -/ theorem homology_map_eq_of_homotopy (h : homotopy f g) (i : ι) : (homology_functor V c i).map f = (homology_functor V c i).map g := begin dsimp [homology_functor], apply eq_of_sub_eq_zero, ext, simp only [homology.π_map, comp_zero, preadditive.comp_sub], dsimp [kernel_subobject_map], simp_rw [h.comm i], simp only [zero_add, zero_comp, d_next_eq_d_from_from_next, kernel_subobject_arrow_comp_assoc, preadditive.comp_add], rw [←preadditive.sub_comp], simp only [category_theory.subobject.factor_thru_add_sub_factor_thru_right], erw [subobject.factor_thru_of_le (D.boundaries_le_cycles i)], { simp, }, { rw [prev_d_eq_to_prev_d_to, ←category.assoc], apply image_subobject_factors_comp_self, }, end /-- Homotopy equivalent complexes have isomorphic homologies. -/ def homology_obj_iso_of_homotopy_equiv (f : homotopy_equiv C D) (i : ι) : (homology_functor V c i).obj C ≅ (homology_functor V c i).obj D := { hom := (homology_functor V c i).map f.hom, inv := (homology_functor V c i).map f.inv, hom_inv_id' := begin rw [←functor.map_comp, homology_map_eq_of_homotopy f.homotopy_hom_inv_id, category_theory.functor.map_id], end, inv_hom_id' := begin rw [←functor.map_comp, homology_map_eq_of_homotopy f.homotopy_inv_hom_id, category_theory.functor.map_id], end, } end namespace category_theory variables {W : Type*} [category W] [preadditive W] /-- An additive functor takes homotopies to homotopies. -/ @[simps] def functor.map_homotopy (F : V ⥤ W) [F.additive] {f g : C ⟶ D} (h : homotopy f g) : homotopy ((F.map_homological_complex c).map f) ((F.map_homological_complex c).map g) := { hom := λ i j, F.map (h.hom i j), zero' := λ i j w, by { rw [h.zero i j w, F.map_zero], }, comm := λ i, begin have := h.comm i, dsimp [d_next, prev_d] at *, rcases c.next i with _|⟨inext,wn⟩; rcases c.prev i with _|⟨iprev,wp⟩; dsimp [d_next, prev_d] at *; { intro h, simp [h] }, end, } /-- An additive functor preserves homotopy equivalences. -/ @[simps] def functor.map_homotopy_equiv (F : V ⥤ W) [F.additive] (h : homotopy_equiv C D) : homotopy_equiv ((F.map_homological_complex c).obj C) ((F.map_homological_complex c).obj D) := { hom := (F.map_homological_complex c).map h.hom, inv := (F.map_homological_complex c).map h.inv, homotopy_hom_inv_id := begin rw [←(F.map_homological_complex c).map_comp, ←(F.map_homological_complex c).map_id], exact F.map_homotopy h.homotopy_hom_inv_id, end, homotopy_inv_hom_id := begin rw [←(F.map_homological_complex c).map_comp, ←(F.map_homological_complex c).map_id], exact F.map_homotopy h.homotopy_inv_hom_id, end } end category_theory
43407c31f31d1b130a83fc550736b3e95a9a251d
1f6fe2f89976b14a4567ab298c35792b21f2e50b
/algebra/left_module.hlean
6dfe619a74ad02665fa1ac7da0991f30200265b9
[ "Apache-2.0" ]
permissive
jonas-frey/Spectral
e5c1c2f7bcac26aa55f7b1e041a81272a146198d
72d521091525a4bc9a31cac859840efe9461cf66
refs/heads/master
1,610,235,743,345
1,505,417,795,000
1,505,417,795,000
102,653,342
0
0
null
1,504,728,483,000
1,504,728,483,000
null
UTF-8
Lean
false
false
18,033
hlean
/- Copyright (c) 2015 Nathaniel Thomas. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Nathaniel Thomas, Jeremy Avigad, Floris van Doorn Modules prod vector spaces over a ring. (We use "left_module," which is more precise, because "module" is a keyword.) -/ import algebra.field ..move_to_lib .exactness algebra.group_power open is_trunc pointed function sigma eq algebra prod is_equiv equiv group structure has_scalar [class] (F V : Type) := (smul : F → V → V) infixl ` • `:73 := has_scalar.smul /- modules over a ring -/ namespace left_module structure left_module (R M : Type) [ringR : ring R] extends has_scalar R M, ab_group M renaming mul → add mul_assoc → add_assoc one → zero one_mul → zero_add mul_one → add_zero inv → neg mul_left_inv → add_left_inv mul_comm → add_comm := (smul_left_distrib : Π (r : R) (x y : M), smul r (add x y) = (add (smul r x) (smul r y))) (smul_right_distrib : Π (r s : R) (x : M), smul (ring.add _ r s) x = (add (smul r x) (smul s x))) (mul_smul : Π r s x, smul (mul r s) x = smul r (smul s x)) (one_smul : Π x, smul one x = x) /- we make it a class now (and not as part of the structure) to avoid left_module.to_ab_group to be an instance -/ attribute left_module [class] definition add_ab_group_of_left_module [reducible] [trans_instance] (R M : Type) [K : ring R] [H : left_module R M] : add_ab_group M := @left_module.to_ab_group R M K H definition has_scalar_of_left_module [reducible] [trans_instance] (R M : Type) [K : ring R] [H : left_module R M] : has_scalar R M := @left_module.to_has_scalar R M K H section left_module variables {R M : Type} variable [ringR : ring R] variable [moduleRM : left_module R M] include ringR moduleRM -- Note: the anonymous include does not work in the propositions below. proposition smul_left_distrib (a : R) (u v : M) : a • (u + v) = a • u + a • v := !left_module.smul_left_distrib proposition smul_right_distrib (a b : R) (u : M) : (a + b) • u = a • u + b • u := !left_module.smul_right_distrib proposition mul_smul (a : R) (b : R) (u : M) : (a * b) • u = a • (b • u) := !left_module.mul_smul proposition one_smul (u : M) : (1 : R) • u = u := !left_module.one_smul proposition zero_smul (u : M) : (0 : R) • u = 0 := have (0 : R) • u + 0 • u = 0 • u + 0, by rewrite [-smul_right_distrib, *add_zero], !add.left_cancel this proposition smul_zero (a : R) : a • (0 : M) = 0 := have a • (0:M) + a • 0 = a • 0 + 0, by rewrite [-smul_left_distrib, *add_zero], !add.left_cancel this proposition neg_smul (a : R) (u : M) : (-a) • u = - (a • u) := eq_neg_of_add_eq_zero (by rewrite [-smul_right_distrib, add.left_inv, zero_smul]) proposition neg_one_smul (u : M) : -(1 : R) • u = -u := by rewrite [neg_smul, one_smul] proposition smul_neg (a : R) (u : M) : a • (-u) = -(a • u) := by rewrite [-neg_one_smul, -mul_smul, mul_neg_one_eq_neg, neg_smul] proposition smul_sub_left_distrib (a : R) (u v : M) : a • (u - v) = a • u - a • v := by rewrite [sub_eq_add_neg, smul_left_distrib, smul_neg] proposition sub_smul_right_distrib (a b : R) (v : M) : (a - b) • v = a • v - b • v := by rewrite [sub_eq_add_neg, smul_right_distrib, neg_smul] end left_module /- vector spaces -/ structure vector_space [class] (F V : Type) [fieldF : field F] extends left_module F V /- homomorphisms -/ definition is_smul_hom [class] (R : Type) {M₁ M₂ : Type} [has_scalar R M₁] [has_scalar R M₂] (f : M₁ → M₂) : Type := ∀ r : R, ∀ a : M₁, f (r • a) = r • f a definition is_prop_is_smul_hom [instance] (R : Type) {M₁ M₂ : Type} [is_set M₂] [has_scalar R M₁] [has_scalar R M₂] (f : M₁ → M₂) : is_prop (is_smul_hom R f) := begin unfold is_smul_hom, apply _ end definition respect_smul (R : Type) {M₁ M₂ : Type} [has_scalar R M₁] [has_scalar R M₂] (f : M₁ → M₂) [H : is_smul_hom R f] : ∀ r : R, ∀ a : M₁, f (r • a) = r • f a := H definition is_module_hom [class] (R : Type) {M₁ M₂ : Type} [has_scalar R M₁] [has_scalar R M₂] [add_group M₁] [add_group M₂] (f : M₁ → M₂) := is_add_hom f × is_smul_hom R f definition is_add_hom_of_is_module_hom [instance] (R : Type) {M₁ M₂ : Type} [has_scalar R M₁] [has_scalar R M₂] [add_group M₁] [add_group M₂] (f : M₁ → M₂) [H : is_module_hom R f] : is_add_hom f := prod.pr1 H definition is_smul_hom_of_is_module_hom [instance] {R : Type} {M₁ M₂ : Type} [has_scalar R M₁] [has_scalar R M₂] [add_group M₁] [add_group M₂] (f : M₁ → M₂) [H : is_module_hom R f] : is_smul_hom R f := prod.pr2 H -- Why do we have to give the instance explicitly? definition is_prop_is_module_hom [instance] (R : Type) {M₁ M₂ : Type} [has_scalar R M₁] [has_scalar R M₂] [add_group M₁] [add_group M₂] (f : M₁ → M₂) : is_prop (is_module_hom R f) := have h₁ : is_prop (is_add_hom f), from is_prop_is_add_hom f, begin unfold is_module_hom, apply _ end section module_hom variables {R : Type} {M₁ M₂ M₃ : Type} variables [has_scalar R M₁] [has_scalar R M₂] [has_scalar R M₃] variables [add_group M₁] [add_group M₂] [add_group M₃] variables (g : M₂ → M₃) (f : M₁ → M₂) [is_module_hom R g] [is_module_hom R f] proposition is_module_hom_id : is_module_hom R (@id M₁) := pair (λ a₁ a₂, rfl) (λ r a, rfl) proposition is_module_hom_comp : is_module_hom R (g ∘ f) := pair (take a₁ a₂, begin esimp, rewrite [respect_add f, respect_add g] end) (take r a, by esimp; rewrite [respect_smul R f, respect_smul R g]) proposition respect_smul_add_smul (a b : R) (u v : M₁) : f (a • u + b • v) = a • f u + b • f v := by rewrite [respect_add f, +respect_smul R f] end module_hom section hom_constant variables {R : Type} {M₁ M₂ : Type} variables [ring R] [has_scalar R M₁] [add_group M₁] [left_module R M₂] proposition is_module_hom_constant : is_module_hom R (const M₁ (0 : M₂)) := (λm₁ m₂, !add_zero⁻¹, λr m, (smul_zero r)⁻¹ᵖ) end hom_constant structure LeftModule (R : Ring) := (carrier : Type) (struct : left_module R carrier) attribute LeftModule.struct [instance] section local attribute LeftModule.carrier [coercion] definition AddAbGroup_of_LeftModule [coercion] {R : Ring} (M : LeftModule R) : AddAbGroup := AddAbGroup.mk M (LeftModule.struct M) end definition LeftModule.struct2 [instance] {R : Ring} (M : LeftModule R) : left_module R M := LeftModule.struct M -- definition LeftModule.struct3 [instance] {R : Ring} (M : LeftModule R) : -- left_module R (AddAbGroup_of_LeftModule M) := -- _ definition pointed_LeftModule_carrier [instance] {R : Ring} (M : LeftModule R) : pointed (LeftModule.carrier M) := pointed.mk zero definition pSet_of_LeftModule {R : Ring} (M : LeftModule R) : Set* := pSet.mk' (LeftModule.carrier M) definition left_module_AddAbGroup_of_LeftModule [instance] {R : Ring} (M : LeftModule R) : left_module R (AddAbGroup_of_LeftModule M) := LeftModule.struct M definition left_module_of_ab_group {G : Type} [gG : add_ab_group G] {R : Type} [ring R] (smul : R → G → G) (h1 : Π (r : R) (x y : G), smul r (x + y) = (smul r x + smul r y)) (h2 : Π (r s : R) (x : G), smul (r + s) x = (smul r x + smul s x)) (h3 : Π r s x, smul (r * s) x = smul r (smul s x)) (h4 : Π x, smul 1 x = x) : left_module R G := left_module.mk smul _ add add.assoc 0 zero_add add_zero neg add.left_inv add.comm h1 h2 h3 h4 definition LeftModule_of_AddAbGroup {R : Ring} (G : AddAbGroup) (smul : R → G → G) (h1 h2 h3 h4) : LeftModule R := LeftModule.mk G (left_module_of_ab_group smul h1 h2 h3 h4) section variables {R : Ring} {M M₁ M₂ M₃ : LeftModule R} definition smul_homomorphism [constructor] (M : LeftModule R) (r : R) : M →a M := add_homomorphism.mk (λg, r • g) (smul_left_distrib r) proposition to_smul_left_distrib (a : R) (u v : M) : a • (u + v) = a • u + a • v := !smul_left_distrib proposition to_smul_right_distrib (a b : R) (u : M) : (a + b) • u = a • u + b • u := !smul_right_distrib proposition to_mul_smul (a : R) (b : R) (u : M) : (a * b) • u = a • (b • u) := !mul_smul proposition to_one_smul (u : M) : (1 : R) • u = u := !one_smul structure homomorphism (M₁ M₂ : LeftModule R) : Type := (fn : LeftModule.carrier M₁ → LeftModule.carrier M₂) (p : is_module_hom R fn) infix ` →lm `:55 := homomorphism definition homomorphism_fn [unfold 4] [coercion] := @homomorphism.fn definition is_module_hom_of_homomorphism [unfold 4] [instance] [priority 900] {M₁ M₂ : LeftModule R} (φ : M₁ →lm M₂) : is_module_hom R φ := homomorphism.p φ section variable (φ : M₁ →lm M₂) definition to_respect_add (x y : M₁) : φ (x + y) = φ x + φ y := respect_add φ x y definition to_respect_smul (a : R) (x : M₁) : φ (a • x) = a • (φ x) := respect_smul R φ a x definition to_respect_sub (x y : M₁) : φ (x - y) = φ x - φ y := respect_sub φ x y definition is_embedding_of_homomorphism /- φ -/ (H : Π{x}, φ x = 0 → x = 0) : is_embedding φ := is_embedding_of_is_add_hom φ @H variables (M₁ M₂) definition is_set_homomorphism [instance] : is_set (M₁ →lm M₂) := begin have H : M₁ →lm M₂ ≃ Σ(f : LeftModule.carrier M₁ → LeftModule.carrier M₂), is_module_hom (Ring.carrier R) f, begin fapply equiv.MK, { intro φ, induction φ, constructor, exact p}, { intro v, induction v with f H, constructor, exact H}, { intro v, induction v, reflexivity}, { intro φ, induction φ, reflexivity} end, have ∀ f : LeftModule.carrier M₁ → LeftModule.carrier M₂, is_set (is_module_hom (Ring.carrier R) f), from _, apply is_trunc_equiv_closed_rev, exact H end variables {M₁ M₂} definition pmap_of_homomorphism [constructor] /- φ -/ : pSet_of_LeftModule M₁ →* pSet_of_LeftModule M₂ := have H : φ 0 = 0, from respect_zero φ, pmap.mk φ begin esimp, exact H end definition homomorphism_change_fun [constructor] (φ : M₁ →lm M₂) (f : M₁ → M₂) (p : φ ~ f) : M₁ →lm M₂ := homomorphism.mk f (prod.mk (λx₁ x₂, (p (x₁ + x₂))⁻¹ ⬝ to_respect_add φ x₁ x₂ ⬝ ap011 _ (p x₁) (p x₂)) (λ a x, (p (a • x))⁻¹ ⬝ to_respect_smul φ a x ⬝ ap01 _ (p x))) definition homomorphism_eq (φ₁ φ₂ : M₁ →lm M₂) (p : φ₁ ~ φ₂) : φ₁ = φ₂ := begin induction φ₁ with φ₁ q₁, induction φ₂ with φ₂ q₂, esimp at p, induction p, exact ap (homomorphism.mk φ₁) !is_prop.elim end end section definition homomorphism.mk' [constructor] (φ : M₁ → M₂) (p : Π(g₁ g₂ : M₁), φ (g₁ + g₂) = φ g₁ + φ g₂) (q : Π(r : R) x, φ (r • x) = r • φ x) : M₁ →lm M₂ := homomorphism.mk φ (p, q) definition to_respect_zero (φ : M₁ →lm M₂) : φ 0 = 0 := respect_zero φ definition homomorphism_compose [reducible] [constructor] (f' : M₂ →lm M₃) (f : M₁ →lm M₂) : M₁ →lm M₃ := homomorphism.mk (f' ∘ f) !is_module_hom_comp variable (M) definition homomorphism_id [reducible] [constructor] [refl] : M →lm M := homomorphism.mk (@id M) !is_module_hom_id variable {M} abbreviation lmid [constructor] := homomorphism_id M infixr ` ∘lm `:75 := homomorphism_compose definition lm_constant [constructor] (M₁ M₂ : LeftModule R) : M₁ →lm M₂ := homomorphism.mk (const M₁ 0) !is_module_hom_constant structure isomorphism (M₁ M₂ : LeftModule R) := (to_hom : M₁ →lm M₂) (is_equiv_to_hom : is_equiv to_hom) infix ` ≃lm `:25 := isomorphism attribute isomorphism.to_hom [coercion] attribute isomorphism.is_equiv_to_hom [instance] attribute isomorphism._trans_of_to_hom [unfold 4] definition equiv_of_isomorphism [constructor] (φ : M₁ ≃lm M₂) : M₁ ≃ M₂ := equiv.mk φ !isomorphism.is_equiv_to_hom section local attribute pSet_of_LeftModule [coercion] definition pequiv_of_isomorphism [constructor] (φ : M₁ ≃lm M₂) : M₁ ≃* M₂ := pequiv_of_equiv (equiv_of_isomorphism φ) (to_respect_zero φ) end definition isomorphism_of_equiv [constructor] (φ : M₁ ≃ M₂) (p : Π(g₁ g₂ : M₁), φ (g₁ + g₂) = φ g₁ + φ g₂) (q : Πr x, φ (r • x) = r • φ x) : M₁ ≃lm M₂ := isomorphism.mk (homomorphism.mk φ (p, q)) !to_is_equiv definition isomorphism_of_eq [constructor] {M₁ M₂ : LeftModule R} (p : M₁ = M₂ :> LeftModule R) : M₁ ≃lm M₂ := isomorphism_of_equiv (equiv_of_eq (ap LeftModule.carrier p)) begin intros, induction p, reflexivity end begin intros, induction p, reflexivity end -- definition pequiv_of_isomorphism_of_eq {M₁ M₂ : LeftModule R} (p : M₁ = M₂ :> LeftModule R) : -- pequiv_of_isomorphism (isomorphism_of_eq p) = pequiv_of_eq (ap pType_of_LeftModule p) := -- begin -- induction p, -- apply pequiv_eq, -- fapply pmap_eq, -- { intro g, reflexivity}, -- { apply is_prop.elim} -- end definition to_lminv [constructor] (φ : M₁ ≃lm M₂) : M₂ →lm M₁ := homomorphism.mk φ⁻¹ abstract begin split, intro g₁ g₂, apply eq_of_fn_eq_fn' φ, rewrite [respect_add φ, +right_inv φ], intro r x, apply eq_of_fn_eq_fn' φ, rewrite [to_respect_smul φ, +right_inv φ], end end variable (M) definition isomorphism.refl [refl] [constructor] : M ≃lm M := isomorphism.mk lmid !is_equiv_id variable {M} definition isomorphism.rfl [refl] [constructor] : M ≃lm M := isomorphism.refl M definition isomorphism.symm [symm] [constructor] (φ : M₁ ≃lm M₂) : M₂ ≃lm M₁ := isomorphism.mk (to_lminv φ) !is_equiv_inv definition isomorphism.trans [trans] [constructor] (φ : M₁ ≃lm M₂) (ψ : M₂ ≃lm M₃) : M₁ ≃lm M₃ := isomorphism.mk (ψ ∘lm φ) !is_equiv_compose definition isomorphism.eq_trans [trans] [constructor] {M₁ M₂ : LeftModule R} {M₃ : LeftModule R} (φ : M₁ = M₂) (ψ : M₂ ≃lm M₃) : M₁ ≃lm M₃ := proof isomorphism.trans (isomorphism_of_eq φ) ψ qed definition isomorphism.trans_eq [trans] [constructor] {M₁ : LeftModule R} {M₂ M₃ : LeftModule R} (φ : M₁ ≃lm M₂) (ψ : M₂ = M₃) : M₁ ≃lm M₃ := isomorphism.trans φ (isomorphism_of_eq ψ) postfix `⁻¹ˡᵐ`:(max + 1) := isomorphism.symm infixl ` ⬝lm `:75 := isomorphism.trans infixl ` ⬝lmp `:75 := isomorphism.trans_eq infixl ` ⬝plm `:75 := isomorphism.eq_trans definition homomorphism_of_eq [constructor] {M₁ M₂ : LeftModule R} (p : M₁ = M₂ :> LeftModule R) : M₁ →lm M₂ := isomorphism_of_eq p definition group_homomorphism_of_lm_homomorphism [constructor] {M₁ M₂ : LeftModule R} (φ : M₁ →lm M₂) : M₁ →a M₂ := add_homomorphism.mk φ (to_respect_add φ) definition lm_homomorphism_of_group_homomorphism [constructor] {M₁ M₂ : LeftModule R} (φ : M₁ →a M₂) (h : Π(r : R) g, φ (r • g) = r • φ g) : M₁ →lm M₂ := homomorphism.mk' φ (group.to_respect_add φ) h section local attribute pSet_of_LeftModule [coercion] definition is_exact_mod (f : M₁ →lm M₂) (f' : M₂ →lm M₃) : Type := @is_exact M₁ M₂ M₃ (homomorphism_fn f) (homomorphism_fn f') definition is_exact_mod.mk {f : M₁ →lm M₂} {f' : M₂ →lm M₃} (h₁ : Πm, f' (f m) = 0) (h₂ : Πm, f' m = 0 → image f m) : is_exact_mod f f' := is_exact.mk h₁ h₂ structure short_exact_mod (A B C : LeftModule R) := (f : A →lm B) (g : B →lm C) (h : @is_short_exact A B C f g) local abbreviation g_of_lm := @group_homomorphism_of_lm_homomorphism definition short_exact_mod_of_is_exact {X A B C Y : LeftModule R} (k : X →lm A) (f : A →lm B) (g : B →lm C) (l : C →lm Y) (hX : is_contr X) (hY : is_contr Y) (kf : is_exact_mod k f) (fg : is_exact_mod f g) (gl : is_exact_mod g l) : short_exact_mod A B C := short_exact_mod.mk f g (is_short_exact_of_is_exact (g_of_lm k) (g_of_lm f) (g_of_lm g) (g_of_lm l) hX hY kf fg gl) definition short_exact_mod_isomorphism {A B A' B' C C' : LeftModule R} (eA : A ≃lm A') (eB : B ≃lm B') (eC : C ≃lm C') (H : short_exact_mod A' B' C') : short_exact_mod A B C := short_exact_mod.mk (eB⁻¹ˡᵐ ∘lm short_exact_mod.f H ∘lm eA) (eC⁻¹ˡᵐ ∘lm short_exact_mod.g H ∘lm eB) (is_short_exact_equiv _ _ (equiv_of_isomorphism eA) (equiv_of_isomorphism eB) (pequiv_of_isomorphism eC) (λa, to_right_inv (equiv_of_isomorphism eB) _) (λb, to_right_inv (equiv_of_isomorphism eC) _) (short_exact_mod.h H)) definition is_contr_middle_of_short_exact_mod {A B C : LeftModule R} (H : short_exact_mod A B C) (HA : is_contr A) (HC : is_contr C) : is_contr B := is_contr_middle_of_is_exact (is_exact_of_is_short_exact (short_exact_mod.h H)) end end end section int open int definition left_module_int_of_ab_group [constructor] (A : Type) [add_ab_group A] : left_module rℤ A := left_module_of_ab_group imul imul_add add_imul mul_imul one_imul definition LeftModule_int_of_AbGroup [constructor] (A : AddAbGroup) : LeftModule rℤ := LeftModule.mk A (left_module_int_of_ab_group A) definition lm_hom_int.mk [constructor] {A B : AbGroup} (φ : A →g B) : LeftModule_int_of_AbGroup A →lm LeftModule_int_of_AbGroup B := lm_homomorphism_of_group_homomorphism φ (to_respect_imul φ) definition lm_iso_int.mk [constructor] {A B : AbGroup} (φ : A ≃g B) : LeftModule_int_of_AbGroup A ≃lm LeftModule_int_of_AbGroup B := isomorphism.mk (lm_hom_int.mk φ) (group.isomorphism.is_equiv_to_hom φ) end int end left_module
3d825b314d3ec2302cba440999d5e550a84eac8d
0c1546a496eccfb56620165cad015f88d56190c5
/library/init/util.lean
20902ffe740983a45577f4155c2fbca5215a821e
[ "Apache-2.0" ]
permissive
Solertis/lean
491e0939957486f664498fbfb02546e042699958
84188c5aa1673fdf37a082b2de8562dddf53df3f
refs/heads/master
1,610,174,257,606
1,486,263,620,000
1,486,263,620,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,059
lean
/- Copyright (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude import init.data.string.basic universe variables u /- This function has a native implementation that tracks time. -/ def timeit {α : Type u} (s : string) (f : thunk α) : α := f () /- This function has a native implementation that displays the given string in the regular output stream. -/ def trace {α : Type u} (s : string) (f : thunk α) : α := f () /- This function has a native implementation that shows the VM call stack. -/ def trace_call_stack {α : Type u} (f : thunk α) : α := f () /- This function has a native implementation that displays in the given position all trace messages used in f. The arguments line and col are filled by the elaborator. -/ def scope_trace {α : Type u} {line col: nat} (f : thunk α) : α := f () meta constant undefined_core {α : Type u} (message : string) : α meta def undefined {α : Type u} : α := undefined_core "undefined"
3386d7761e8c818e7e24435839e540e02f1929ed
947b78d97130d56365ae2ec264df196ce769371a
/stage0/src/Lean/Meta/Tactic/Assumption.lean
21991f9bed205ab7450b79e8ca57b4843be9decf
[ "Apache-2.0" ]
permissive
shyamalschandra/lean4
27044812be8698f0c79147615b1d5090b9f4b037
6e7a883b21eaf62831e8111b251dc9b18f40e604
refs/heads/master
1,671,417,126,371
1,601,859,995,000
1,601,860,020,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
831
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Meta.ExprDefEq import Lean.Meta.Tactic.Util namespace Lean namespace Meta def assumptionAux (mvarId : MVarId) : MetaM Bool := withMVarContext mvarId $ do checkNotAssigned mvarId `assumption; mvarType ← getMVarType mvarId; lctx ← getLCtx; h? ← lctx.findDeclRevM? $ fun decl => if decl.isAuxDecl then pure none else condM (isDefEq mvarType decl.type) (pure (some decl.toExpr)) (pure none); match h? with | some h => do assignExprMVar mvarId h; pure true | none => pure false def assumption (mvarId : MVarId) : MetaM Unit := unlessM (assumptionAux mvarId) $ throwTacticEx `assumption mvarId "" end Meta end Lean
1921dbb5b2e9dd4cd23b27b11ed85065149fd3b9
30b012bb72d640ec30c8fdd4c45fdfa67beb012c
/group_theory/group_action.lean
3af46182245a13fc05e6ddf92f26e280483d5b59
[ "Apache-2.0" ]
permissive
kckennylau/mathlib
21fb810b701b10d6606d9002a4004f7672262e83
47b3477e20ffb5a06588dd3abb01fe0fe3205646
refs/heads/master
1,634,976,409,281
1,542,042,832,000
1,542,319,733,000
109,560,458
0
0
Apache-2.0
1,542,369,208,000
1,509,867,494,000
Lean
UTF-8
Lean
false
false
4,122
lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes -/ import data.set.finite group_theory.coset universes u v variables {α : Type u} {β : Type v} class is_monoid_action [monoid α] (f : α → β → β) : Prop := (one : ∀ a : β, f (1 : α) a = a) (mul : ∀ (x y : α) (a : β), f (x * y) a = f x (f y a)) namespace is_monoid_action variables [monoid α] (f : α → β → β) [is_monoid_action f] def orbit (a : β) := set.range (λ x : α, f x a) @[simp] lemma mem_orbit_iff {f : α → β → β} [is_monoid_action f] {a b : β} : b ∈ orbit f a ↔ ∃ x : α, f x a = b := iff.rfl @[simp] lemma mem_orbit (a : β) (x : α) : f x a ∈ orbit f a := ⟨x, rfl⟩ @[simp] lemma mem_orbit_self (a : β) : a ∈ orbit f a := ⟨1, show f 1 a = a, by simp [is_monoid_action.one f]⟩ instance orbit_fintype (a : β) [fintype α] [decidable_eq β] : fintype (orbit f a) := set.fintype_range _ def stabilizer (a : β) : set α := {x : α | f x a = a} @[simp] lemma mem_stabilizer_iff {f : α → β → β} [is_monoid_action f] {a : β} {x : α} : x ∈ stabilizer f a ↔ f x a = a := iff.rfl def fixed_points : set β := {a : β | ∀ x, x ∈ stabilizer f a} @[simp] lemma mem_fixed_points {f : α → β → β} [is_monoid_action f] {a : β} : a ∈ fixed_points f ↔ ∀ x : α, f x a = a := iff.rfl lemma mem_fixed_points' {f : α → β → β} [is_monoid_action f] {a : β} : a ∈ fixed_points f ↔ (∀ b, b ∈ orbit f a → b = a) := ⟨λ h b h₁, let ⟨x, hx⟩ := mem_orbit_iff.1 h₁ in hx ▸ h x, λ h b, mem_stabilizer_iff.2 (h _ (mem_orbit _ _ _))⟩ end is_monoid_action class is_group_action [group α] (f : α → β → β) extends is_monoid_action f namespace is_group_action variables [group α] (f : α → β → β) [is_group_action f] open is_monoid_action def to_perm (g : α) : equiv.perm β := { to_fun := f g, inv_fun := f g⁻¹, left_inv := λ a, by rw [← is_monoid_action.mul f, inv_mul_self, is_monoid_action.one f], right_inv := λ a, by rw [← is_monoid_action.mul f, mul_inv_self, is_monoid_action.one f] } instance : is_group_hom (to_perm f) := { mul := λ x y, equiv.ext _ _ (λ a, is_monoid_action.mul f x y a) } lemma bijective (g : α) : function.bijective (f g) := (to_perm f g).bijective lemma orbit_eq_iff {f : α → β → β} [is_monoid_action f] {a b : β} : orbit f a = orbit f b ↔ a ∈ orbit f b:= ⟨λ h, h ▸ mem_orbit_self _ _, λ ⟨x, (hx : f x b = a)⟩, set.ext (λ c, ⟨λ ⟨y, (hy : f y a = c)⟩, ⟨y * x, show f (y * x) b = c, by rwa [is_monoid_action.mul f, hx]⟩, λ ⟨y, (hy : f y b = c)⟩, ⟨y * x⁻¹, show f (y * x⁻¹) a = c, by conv {to_rhs, rw [← hy, ← mul_one y, ← inv_mul_self x, ← mul_assoc, is_monoid_action.mul f, hx]}⟩⟩)⟩ instance (a : β) : is_subgroup (stabilizer f a) := { one_mem := is_monoid_action.one _ _, mul_mem := λ x y (hx : f x a = a) (hy : f y a = a), show f (x * y) a = a, by rw is_monoid_action.mul f; simp *, inv_mem := λ x (hx : f x a = a), show f x⁻¹ a = a, by rw [← hx, ← is_monoid_action.mul f, inv_mul_self, is_monoid_action.one f, hx] } open quotient_group noncomputable def orbit_equiv_quotient_stabilizer (a : β) : orbit f a ≃ quotient (stabilizer f a) := equiv.symm (@equiv.of_bijective _ _ (λ x : quotient (stabilizer f a), quotient.lift_on' x (λ x, (⟨f x a, mem_orbit _ _ _⟩ : orbit f a)) (λ g h (H : _ = _), subtype.eq $ (is_group_action.bijective f (g⁻¹)).1 $ show f g⁻¹ (f g a) = f g⁻¹ (f h a), by rw [← is_monoid_action.mul f, ← is_monoid_action.mul f, H, inv_mul_self, is_monoid_action.one f])) ⟨λ g h, quotient.induction_on₂' g h (λ g h H, quotient.sound' $ have H : f g a = f h a := subtype.mk.inj H, show f (g⁻¹ * h) a = a, by rw [is_monoid_action.mul f, ← H, ← is_monoid_action.mul f, inv_mul_self, is_monoid_action.one f]), λ ⟨b, ⟨g, hgb⟩⟩, ⟨g, subtype.eq hgb⟩⟩) end is_group_action
e6f5b1da404f8485c0f941a15044b7b6454cfa4c
febba19712b2aefe4d6c7fb0230b8d7e272c98c4
/src/realizers.lean
ec150f2a3b21e760a49e9301ed5780f9f2318dfd
[]
no_license
hcheval/formalized-proof-mining
e6eb980feb644ae269f43d9af93ac584b7a47a17
216cc73fccd84900a1ba7eaae5f73732496d6afe
refs/heads/master
1,689,621,410,792
1,629,912,272,000
1,629,912,272,000
399,855,572
0
0
null
null
null
null
UTF-8
Lean
false
false
13,969
lean
import proof section realizers variables {ι : Type} {gri : ground_interpretation ι} local notation `𝔽` := formula ι gri local notation `𝕋` := type ι gri variables {greq : Π {i : ι}, ∥𝕏 i // gri ∥ → ∥𝕏 i // gri ∥ → 𝔽} local infixr `≅` : 35 := formula.eqext @greq namespace dia section logical_axioms open formula variables {σ τ : 𝕋} variables (A B C : 𝔽) (P : ∥σ∥ → 𝔽) variables (Γ : premises ι gri) def and_contr : realizer (A ⟹ A ⋀ A) := subtype.mk (⟨(λ x y, if A.dia x y.fst then y.2 else y.1), (λ x, (x, x))⟩) (begin rintros ⟨y₁, ⟨y₂₁, y₂₂⟩⟩ h, simp only [dia, dite_eq_ite, id.def] at *, by_cases h' : A.dia y₁ y₂₁, { simp only [*, if_true] at h, exact ⟨h', h⟩, }, { simp only [*, if_false] at h, contradiction, }, end) def or_contr : realizer (A ⋁ A ⟹ A) := subtype.mk ((λ x y, (y, y)), (λ x, match x with | (sum.inl x') := x' | (sum.inr x') := x' end)) (begin rintros ⟨y₁, y₂⟩ h, cases y₁; assumption, end) def and_weak : realizer (A ⋀ B ⟹ A) := subtype.mk (prod.mk (λ ⟨y1, y2⟩ y3, (y3, ℂ_inh B)) (λ ⟨y1, y2⟩, y1)) (begin rintros ⟨⟨y₁₁, y₁₂⟩ , y₂⟩ ⟨h₁, h₂⟩, assumption, end) def or_weak : realizer (A ⟹ A ⋁ B) := subtype.mk ((λ x y, y.fst), (λ x, sum.inl x)) (begin intros y h, assumption, end) def exfalso : realizer (prime false ⟹ A) := subtype.mk ⟨(λ _ _, punit.star), (λ _, 𝕎_inh A)⟩ (begin intros y h, cases h, end) def and_perm : realizer (A ⋀ B ⟹ B ⋀ A) := subtype.mk (((λ x y, (y.2, y.1)), λ x, (x.2, x.1))) (begin rintros ⟨⟨y₁₁, y₁₂⟩, ⟨y₂₁, y₂₂⟩⟩ h, dsimp only [dia] at *, exact and.comm.mp h, end) def or_perm : realizer (A ⋁ B ⟹ B ⋁ A) := subtype.mk (((λ x y, y.swap), (λ x, x.swap))) (begin rintros ⟨y₁, ⟨y₂₁, y₂₂⟩⟩ h, cases y₁; assumption, end) def univ_ax : Π a : ∥σ∥, realizer (universal' σ P ⟹ P a) := λ a, subtype.mk (((λ x y, ⟨_, y⟩), (λ x, x a))) (begin intros y h, exact h, end) def exist_ax : Π a : ∥σ∥, realizer (P a ⟹ existential' σ P) := λ a, subtype.mk (((λ x y, y a x), (λ x, ⟨a, x⟩))) (begin intros y h, exact h, end) end logical_axioms section logical_rules open formula local attribute [simp] dia variables {Γ : premises ι gri} variables {σ τ : 𝕋} variables {A B C : 𝔽} {P : ∥σ∥ → 𝔽} def of_prime_true {p : Prop} [decp : decidable p] (hp : p) : realizer (@prime _ gri p decp) := subtype.mk unit.star (λ _, hp) def mp : realizer A → realizer (A ⟹ B) → realizer B := λ hA hAB, subtype.mk ((hAB).1.2 (hA).1) (begin intros y, let h₁ := (hA).2, let h₂ := (hAB).2, dsimp only [dia, ℂ, mwc, dia, 𝕎] at h₂, simp only [prod.forall, subtype.val_eq_coe] at h₂, apply h₂, apply h₁, end) def syl : realizer (A ⟹ B) → realizer (B ⟹ C) → realizer (A ⟹ C) := λ hAB hBC, subtype.mk ((λ x y, (hAB).1.1 x ((hBC).1.1 ((hAB).1.2 x) y)), (λ x, (hBC).1.2 ((hAB).1.2 x))) (begin intros y h, let h₁ := (hAB).2, let h₂ := (hBC).2, dsimp only [ℂ, mwc, dia, 𝕎] at h₁ h₂, simp only [prod.forall, subtype.val_eq_coe] at h₁ h₂, apply h₂, apply h₁, apply h, end) def exportation : realizer (A ⋀ B ⟹ C) → realizer (A ⟹ (B ⟹ C)) := λ h, subtype.mk (((λ x y, ((h).1.1 (x, y.1) y.2).1), (λ x, ((λ y z, ((h).1.1 (x, y) z).2), (λ y, (h).1.2 (x, y)))))) (begin rintros ⟨y₁, ⟨y₂₁, y₂₂⟩⟩, let h' := (h).2, intros h₁ h₂, dsimp only [formula.ℂ, formula.𝕎, formula.dia, formula.mwc] at *, simp only [prod.forall] at *, exact h' _ _ _ ⟨h₁, h₂⟩, end) def importation : realizer (A ⟹ (B ⟹ C)) → realizer (A ⋀ B ⟹ C) := λ h, subtype.mk (((λ x y, ((h).1.1 x.1 (x.2, y), ((h).1.2 x.1).1 x.2 y)), (λ x, ((h).1.2 x.1).2 x.2))) (begin rintros ⟨⟨y₁₁, y₁₂⟩, y₂⟩, let h' := (h).2, rintros h₁, dsimp only [ℂ, mwc, dia, 𝕎] at h' h₁ ⊢, simp only [prod.forall, subtype.val_eq_coe] at h' h₁ ⊢, specialize h' y₁₁ ⟨y₁₂, y₂⟩, apply h', { apply h₁.1, }, { apply h₁.2, }, end) def univ_rule : (Π x : ∥σ∥, realizer (A ⟹ P x)) → realizer (A ⟹ universal' σ P) := λ h, subtype.mk ((λ x y, (h y.1).1.1 x y.2), (λ x y, (h y).1.2 x)) (begin rintros ⟨y1, ⟨z, y2⟩⟩, let ht := (h z).property, specialize ht ⟨y1, y2⟩, exact ht, end) def exist_rule : (Π x : ∥σ∥, realizer (P x ⟹ A)) → realizer (existential' σ P ⟹ A) := λ h, subtype.mk (((λ x y z v, (h z).1.1 v y), (λ x, (h x.1).1.2 x.2))) (begin rintros ⟨⟨y1, y2⟩, y3⟩, let ht := (h y1).property, specialize ht ⟨y2, y3⟩, exact ht, end) def expansion : realizer (A ⟹ B) → realizer ((C ⋁ A) ⟹ (C ⋁ B)) := λ h, subtype.mk (prod.mk (λ x y, match x with | (sum.inl x') := (y.1, ((h).1.1 (𝕎_inh _) y.2)) | (sum.inr x') := (y.1, (h).1.1 x' y.2) end ) (λ x, match x with | (sum.inl x') := sum.inl x' | (sum.inr x') := sum.inr ((h).1.2 x') end ) ) (begin rintros ⟨y₁, ⟨y₂₁, y₂₂⟩⟩, let h' := (h).property, dsimp only [ℂ, mwc, dia, 𝕎] at *, intros hA, cases y₁, case sum.inl { assumption, }, case sum.inr { dsimp only [mwc, realizer, dia] at *, simp only [prod.forall, subtype.val_eq_coe] at *, solve_by_elim, }, end) def qfer (admissible : admissible_greq @greq) (a b : ∥σ∥) : realizer (a ≅ b) → realizer (P a ⟹ P b) := λ h, subtype.mk ( have eqab : a = b := eq_of_eqext_realizer admissible _ _ h, have eqℂ : (P a).ℂ = (P b).ℂ := congr_arg ℂ (congr_arg P eqab), have eq𝕎 : (P a).𝕎 = (P b).𝕎 := congr_arg 𝕎 (congr_arg P eqab), prod.mk (λ u v, cast (eq.symm eqℂ) v) (λ u, cast eq𝕎 u)) (begin intros y h', have eqab : a = b := eq_of_eqext_realizer admissible _ _ h, subst eqab, exact h', end) end logical_rules section induction_rule open formula def ir {A : ∥𝕆 // gri∥ → 𝔽} (m : ∥𝕆 // gri∥) : realizer (A nat.zero) → (Π n : ∥𝕆 // gri∥, realizer (A n ⟹ A n.succ)) → realizer (A m) := λ h0 hi, subtype.mk (nat.rec_on m h0.val (λ n p, (hi n).val.snd p)) (begin intros y, induction m, case zero { exact h0.2 y, }, case succ: m ih{ have := λ n, (hi n).property, dsimp only [ℂ, mwc, 𝕎] at this, simp only [dia] at this, simp only, set u : (A m).𝕎 := nat.rec h0.val (λ (n : ℕ), (hi n).val.snd) m, specialize this m, specialize this ⟨u, y⟩, apply this, apply ih, } end) end induction_rule section other open formula def markov {σ : 𝕋} (A : ∥σ∥ → 𝔽) [uw : ∀ x : ∥σ∥, subsingleton (A x).𝕎] [uc : ∀ x : ∥σ∥, subsingleton (A x).ℂ] : realizer (∼(∀∀ (x : ∥σ∥) , ∼(A x)) ⟹ (∃∃ (x : ∥σ∥) , A x)) := subtype.mk (prod.mk (λ _ _, ℂ_inh _) (λ h, ⟨(h.1 (𝕎_inh _) (ℂ_inh _)).1, 𝕎_inh _⟩)) (begin dsimp only [negation, ℂ, mwc, dia] at *, simp only [ℂ, prod.forall, 𝕎] at *, intros y u v h, set φ := (((y, u), v).fst.fst (∀∀ (x : ∥σ∥), A x⟹(falsum ι gri)).𝕎_inh (falsum ι gri).ℂ_inh).fst, set ψ₁ := ((∀∀ (x : ∥σ∥), A x⟹(falsum ι gri))⟹(falsum ι gri)).ℂ_inh.fst with eq_ψ₁, rw ←eq_ψ₁ at *, set ψ₂ := ((∀∀ (x : ∥σ∥), A x⟹(falsum ι gri))⟹(falsum ι gri)).ℂ_inh.snd with eq_ψ₂, rw ←eq_ψ₂ at *, set χ := ((y, u), v) with eq_χ, rw ←eq_χ at *, dsimp only at h, have : φ = (y ψ₁ ψ₂).fst := rfl, rw this, clear this, rw [imp_false, imp_false, dia_not_not] at h, have : (χ.fst.fst ψ₁ ψ₂).snd.fst = (A (χ.fst.fst ψ₁ ψ₂).fst).𝕎_inh := subsingleton_iff.mp (uw (χ.fst.fst ψ₁ ψ₂).fst) _ _, rw ←this, clear this, have : (ψ₁ (χ.fst.fst ψ₁ ψ₂).fst).fst (χ.fst.fst ψ₁ ψ₂).snd.fst (χ.fst.fst ψ₁ ψ₂).snd.snd = v (χ.fst.fst ψ₁ ψ₂).fst (χ.fst.fst ψ₁ ψ₂).snd.fst := subsingleton_iff.mp (uc (χ.fst.fst ψ₁ ψ₂).fst) _ _, rw ←this, clear this, apply h, end) def ip {σ τ : 𝕋} (A : ∥σ∥ → 𝔽) (B : ∥τ∥ → 𝔽) [uwA : ∀ x : ∥σ∥, subsingleton (A x).𝕎] [ucB : ∀ y : ∥τ∥, subsingleton (B y).ℂ] : realizer $ ((∀∀ (x : ∥σ∥) , A x) ⟹ (∃∃ (y : ∥τ∥) , B y)) ⟹ ∃∃ (y : ∥τ∥) , ((∀∀ (x : ∥σ∥) , A x) ⟹ B y) := subtype.mk (let f := λ x : ∥σ∥, 𝕎_inh (A x) in let g := λ (y : ∥τ∥) (w : 𝕎 (B y)), ℂ_inh (B y) in prod.mk (λ x y, (f, g)) (λ a, ⟨(a.2 f).1, ((λ z _, a.1 f g), (λ z, (a.2 f).2))⟩) ) (begin dsimp only [ℂ, mwc, dia, 𝕎] at *, simp only [ℂ, prod.forall, 𝕎] at *, intros x y u h₁, unfreezingI { dsimp only at *}, set a := x (λ (x : σ.interpret), (A x).𝕎_inh) (λ (y : τ.interpret) (w : (B y).mwc.fst), (B y).ℂ_inh) with eq_a, rw ←eq_a at *, set b := y (λ (x : σ.interpret), (A x).𝕎_inh) with eq_b, rw ←eq_b at *, set c := λ (z : Π (x : σ.interpret), (A x).mwc.fst), b.snd with eq_c, rw ←eq_c at *, intros h₂, have : (u b.fst (λ (z : Π (x : σ.interpret), (A x).mwc.fst) (ᾰ : (B b.fst).mwc.snd), a, c)).snd = ℂ_inh (B b.fst) := subsingleton_iff.mp (ucB b.fst) _ _, rw this, clear this, have : (u b.fst (λ (z : Π (x : σ.interpret), (A x).mwc.fst) (ᾰ : (B b.fst).mwc.snd), a, c)).fst a.fst = 𝕎_inh (A a.fst) := subsingleton_iff.mp (uwA a.fst) _ _, rw this at h₂, clear this, apply h₁, exact h₂, end) def qfac {σ τ : 𝕋} (A : ∥σ∥ → ∥τ∥ → 𝔽) [uw : ∀ x y, subsingleton (A x y).𝕎] [uc : ∀ x y, subsingleton (A x y).ℂ] : realizer $ (∀∀ x : ∥σ∥, ∃∃ y : ∥τ∥, A x y ⟹ ∃∃ Y : ∥σ ↣ τ∥, ∀∀ x : ∥σ∥, A x (Y x)) := subtype.mk (by { dsimp at *, intros a, sorry, } ) (begin dsimp at *, intros, end) end other end dia end realizers section soundness namespace proof variables {ι : Type} {gri : ground_interpretation ι} local notation `𝔽` := formula ι gri variables {greq : Π {i : ι}, ∥𝕏 i // gri∥ → ∥𝕏 i // gri∥ → 𝔽} variables (admissible : admissible_greq @greq) include admissible def dia_realize {Γ : premises ι gri} (premise_realizer : (Π {γ : 𝔽}, γ ∈ Γ → dia.realizer γ)) : Π {A : 𝔽}, proof @greq {with_markov := tt, with_ip := tt} Γ A → dia.realizer A | A (@premise _ _ _ _ _ .(A) hmem) := premise_realizer hmem | _ (@of_prime_true _ _ _ _ _ p decp h) := @dia.of_prime_true _ _ p decp h | _ (and_contr _) := dia.and_contr _ | _ (or_contr _) := dia.or_contr _ | _ (and_weak _ _) := dia.and_weak _ _ | _ (or_weak _ _) := dia.or_weak _ _ | _ (and_perm _ _) := dia.and_perm _ _ | _ (or_perm _ _) := dia.or_perm _ _ | _ (univ_ax _ _) := dia.univ_ax _ _ | _ (exist_ax _ _) := dia.exist_ax _ _ | _ (exfalso _) := dia.exfalso _ | _ (mp prfA prfAB) := dia.mp prfA.dia_realize prfAB.dia_realize | _ (syl prfAB prfBC) := dia.syl prfAB.dia_realize prfBC.dia_realize | _ (importation prf) := dia.importation prf.dia_realize | _ (exportation prf) := dia.exportation prf.dia_realize | _ (expansion prf) := dia.expansion prf.dia_realize | _ (univ_rule prf) := dia.univ_rule $ λ x, (prf x).dia_realize | _ (exist_rule prf) := dia.exist_rule $ λ x, (prf x).dia_realize | _ (ir m prf_0 prf_succ) := dia.ir m prf_0.dia_realize $ λ n, (prf_succ n).dia_realize | _ (qfer σ x y A prf) := dia.qfer admissible x y prf.dia_realize | _ (@markov _ _ _ _ _ σ A uw uc _) := @dia.markov _ _ _ A uw uc | _ (@ip _ _ _ _ _ _ _ A B uwA ucB _) := @dia.ip _ _ _ _ A B uwA ucB end proof end soundness
f32a6126c19fc79f1f6e6a92eefcc135f1e52c94
69d4931b605e11ca61881fc4f66db50a0a875e39
/src/ring_theory/witt_vector/is_poly.lean
3c968c5d43c1ed35bd8f60caab2b4521c18c2378
[ "Apache-2.0" ]
permissive
abentkamp/mathlib
d9a75d291ec09f4637b0f30cc3880ffb07549ee5
5360e476391508e092b5a1e5210bd0ed22dc0755
refs/heads/master
1,682,382,954,948
1,622,106,077,000
1,622,106,077,000
149,285,665
0
0
null
null
null
null
UTF-8
Lean
false
false
23,405
lean
/- Copyright (c) 2020 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin, Robert Y. Lewis -/ import algebra.ring.ulift import ring_theory.witt_vector.basic import data.mv_polynomial.funext /-! # The `is_poly` predicate `witt_vector.is_poly` is a (type-valued) predicate on functions `f : Π R, 𝕎 R → 𝕎 R`. It asserts that there is a family of polynomials `φ : ℕ → mv_polynomial ℕ ℤ`, such that the `n`th coefficient of `f x` is equal to `φ n` evaluated on the coefficients of `x`. Many operations on Witt vectors satisfy this predicate (or an analogue for higher arity functions). We say that such a function `f` is a *polynomial function*. The power of satisfying this predicate comes from `is_poly.ext`. It shows that if `φ` and `ψ` witness that `f` and `g` are polynomial functions, then `f = g` not merely when `φ = ψ`, but in fact it suffices to prove ``` ∀ n, bind₁ φ (witt_polynomial p _ n) = bind₁ ψ (witt_polynomial p _ n) ``` (in other words, when evaluating the Witt polynomials on `φ` and `ψ`, we get the same values) which will then imply `φ = ψ` and hence `f = g`. Even though this sufficient condition looks somewhat intimidating, it is rather pleasant to check in practice; more so than direct checking of `φ = ψ`. In practice, we apply this technique to show that the composition of `witt_vector.frobenius` and `witt_vector.verschiebung` is equal to multiplication by `p`. ## Main declarations * `witt_vector.is_poly`, `witt_vector.is_poly₂`: two predicates that assert that a unary/binary function on Witt vectors is polynomial in the coefficients of the input values. * `witt_vector.is_poly.ext`, `witt_vector.is_poly₂.ext`: two polynomial functions are equal if their families of polynomials are equal after evaluating the Witt polynmials on them. * `witt_vector.is_poly.comp` (+ many variants) show that unary/binary compositions of polynomial functions are polynomial. * `witt_vector.id_is_poly`, `witt_vector.neg_is_poly`, `witt_vector.add_is_poly₂`, `witt_vector.mul_is_poly₂`: several well-known operations are polynomial functions (for Verschiebung, Frobenius, and multiplication by `p`, see their respective files). ## On higher arity analogues Ideally, there should be a predicate `is_polyₙ` for functions of higher arity, together with `is_polyₙ.comp` that shows how such functions compose. Since mathlib does not have a library on composition of higher arity functions, we have only implemented the unary and binary variants so far. Nullary functions (a.k.a. constants) are treated as constant functions and fall under the unary case. ## Tactics There are important metaprograms defined in this file: the tactics `ghost_simp` and `ghost_calc` and the attributes `@[is_poly]` and `@[ghost_simps]`. These are used in combination to discharge proofs of identities between polynomial functions. Any atomic proof of `is_poly` or `is_poly₂` (i.e. not taking additional `is_poly` arguments) should be tagged as `@[is_poly]`. Any lemma doing "ring equation rewriting" with polynomial functions should be tagged `@[ghost_simps]`, e.g. ```lean @[ghost_simps] lemma bind₁_frobenius_poly_witt_polynomial (n : ℕ) : bind₁ (frobenius_poly p) (witt_polynomial p ℤ n) = (witt_polynomial p ℤ (n+1)) ``` Proofs of identities between polynomial functions will often follow the pattern ```lean begin ghost_calc _, <minor preprocessing>, ghost_simp end ``` ## References * [Hazewinkel, *Witt Vectors*][Haze09] * [Commelin and Lewis, *Formalizing the Ring of Witt Vectors*][CL21] -/ /- ### Simplification tactics `ghost_simp` is used later in the development for certain simplifications. We define it here so it is a shared import. -/ mk_simp_attribute ghost_simps "Simplification rules for ghost equations" namespace tactic namespace interactive setup_tactic_parser /-- A macro for a common simplification when rewriting with ghost component equations. -/ meta def ghost_simp (lems : parse simp_arg_list) : tactic unit := do tactic.try tactic.intro1, simp none none tt (lems ++ [simp_arg_type.symm_expr ``(sub_eq_add_neg)]) [`ghost_simps] (loc.ns [none]) /-- `ghost_calc` is a tactic for proving identities between polynomial functions. Typically, when faced with a goal like ```lean ∀ (x y : 𝕎 R), verschiebung (x * frobenius y) = verschiebung x * y ``` you can 1. call `ghost_calc` 2. do a small amount of manual work -- maybe nothing, maybe `rintro`, etc 3. call `ghost_simp` and this will close the goal. `ghost_calc` cannot detect whether you are dealing with unary or binary polynomial functions. You must give it arguments to determine this. If you are proving a universally quantified goal like the above, call `ghost_calc _ _`. If the variables are introduced already, call `ghost_calc x y`. In the unary case, use `ghost_calc _` or `ghost_calc x`. `ghost_calc` is a light wrapper around type class inference. All it does is apply the appropriate extensionality lemma and try to infer the resulting goals. This is subtle and Lean's elaborator doesn't like it because of the HO unification involved, so it is easier (and prettier) to put it in a tactic script. -/ meta def ghost_calc (ids' : parse ident_*) : tactic unit := do ids ← ids'.mmap $ λ n, get_local n <|> tactic.intro n, `(@eq (witt_vector _ %%R) _ _) ← target, match ids with | [x] := refine ```(is_poly.ext _ _ _ _ %%x) | [x, y] := refine ```(is_poly₂.ext _ _ _ _ %%x %%y) | _ := fail "ghost_calc takes one or two arguments" end, nm ← match R with | expr.local_const _ nm _ _ := return nm | _ := get_unused_name `R end, iterate_exactly 2 apply_instance, unfreezingI (tactic.clear' tt [R]), introsI $ [nm, nm<.>"_inst"] ++ ids', skip end interactive end tactic namespace witt_vector universe variable u variables {p : ℕ} {R S : Type u} {σ idx : Type*} [hp : fact p.prime] [comm_ring R] [comm_ring S] local notation `𝕎` := witt_vector p -- type as `\bbW` open mv_polynomial open function (uncurry) include hp variables (p) noncomputable theory /-! ### The `is_poly` predicate -/ lemma poly_eq_of_witt_polynomial_bind_eq' (f g : ℕ → mv_polynomial (idx × ℕ) ℤ) (h : ∀ n, bind₁ f (witt_polynomial p _ n) = bind₁ g (witt_polynomial p _ n)) : f = g := begin ext1 n, apply mv_polynomial.map_injective (int.cast_ring_hom ℚ) int.cast_injective, rw ← function.funext_iff at h, replace h := congr_arg (λ fam, bind₁ (mv_polynomial.map (int.cast_ring_hom ℚ) ∘ fam) (X_in_terms_of_W p ℚ n)) h, simpa only [function.comp, map_bind₁, map_witt_polynomial, ← bind₁_bind₁, bind₁_witt_polynomial_X_in_terms_of_W, bind₁_X_right] using h end lemma poly_eq_of_witt_polynomial_bind_eq (f g : ℕ → mv_polynomial ℕ ℤ) (h : ∀ n, bind₁ f (witt_polynomial p _ n) = bind₁ g (witt_polynomial p _ n)) : f = g := begin ext1 n, apply mv_polynomial.map_injective (int.cast_ring_hom ℚ) int.cast_injective, rw ← function.funext_iff at h, replace h := congr_arg (λ fam, bind₁ (mv_polynomial.map (int.cast_ring_hom ℚ) ∘ fam) (X_in_terms_of_W p ℚ n)) h, simpa only [function.comp, map_bind₁, map_witt_polynomial, ← bind₁_bind₁, bind₁_witt_polynomial_X_in_terms_of_W, bind₁_X_right] using h end omit hp -- Ideally, we would generalise this to n-ary functions -- But we don't have a good theory of n-ary compositions in mathlib /-- A function `f : Π R, 𝕎 R → 𝕎 R` that maps Witt vectors to Witt vectors over arbitrary base rings is said to be *polynomial* if there is a family of polynomials `φₙ` over `ℤ` such that the `n`th coefficient of `f x` is given by evaluating `φₙ` at the coefficients of `x`. See also `witt_vector.is_poly₂` for the binary variant. The `ghost_calc` tactic treats `is_poly` as a type class, and the `@[is_poly]` attribute derives certain specialized composition instances for declarations of type `is_poly f`. For the most part, users are not expected to treat `is_poly` as a class. -/ class is_poly (f : Π ⦃R⦄ [comm_ring R], witt_vector p R → 𝕎 R) : Prop := mk' :: (poly : ∃ φ : ℕ → mv_polynomial ℕ ℤ, ∀ ⦃R⦄ [comm_ring R] (x : 𝕎 R), by exactI (f x).coeff = λ n, aeval x.coeff (φ n)) /-- The identity function on Witt vectors is a polynomial function. -/ instance id_is_poly : is_poly p (λ _ _, id) := ⟨⟨X, by { introsI, simp only [aeval_X, id] }⟩⟩ instance id_is_poly_i' : is_poly p (λ _ _ a, a) := witt_vector.id_is_poly _ namespace is_poly instance : inhabited (is_poly p (λ _ _, id)) := ⟨witt_vector.id_is_poly p⟩ variables {p} include hp lemma ext {f g} (hf : is_poly p f) (hg : is_poly p g) (h : ∀ (R : Type u) [_Rcr : comm_ring R] (x : 𝕎 R) (n : ℕ), by exactI ghost_component n (f x) = ghost_component n (g x)) : ∀ (R : Type u) [_Rcr : comm_ring R] (x : 𝕎 R), by exactI f x = g x := begin unfreezingI { obtain ⟨φ, hf⟩ := hf, obtain ⟨ψ, hg⟩ := hg }, intros, ext n, rw [hf, hg, poly_eq_of_witt_polynomial_bind_eq p φ ψ], intro k, apply mv_polynomial.funext, intro x, simp only [hom_bind₁], specialize h (ulift ℤ) (mk p $ λ i, ⟨x i⟩) k, simp only [ghost_component_apply, aeval_eq_eval₂_hom] at h, apply (ulift.ring_equiv.{0 u}).symm.injective, simp only [map_eval₂_hom], convert h, all_goals { funext i, rw [← ring_equiv.coe_to_ring_hom], simp only [hf, hg, mv_polynomial.eval, map_eval₂_hom], apply eval₂_hom_congr (ring_hom.ext_int _ _) _ rfl, ext1, apply eval₂_hom_congr (ring_hom.ext_int _ _) _ rfl, simp only [coeff_mk], refl } end omit hp /-- The composition of polynomial functions is polynomial. -/ lemma comp {g f} (hg : is_poly p g) (hf : is_poly p f) : is_poly p (λ R _Rcr, @g R _Rcr ∘ @f R _Rcr) := begin unfreezingI { obtain ⟨φ, hf⟩ := hf, obtain ⟨ψ, hg⟩ := hg }, use (λ n, bind₁ φ (ψ n)), intros, simp only [aeval_bind₁, function.comp, hg, hf] end end is_poly /-- A binary function `f : Π R, 𝕎 R → 𝕎 R → 𝕎 R` on Witt vectors is said to be *polynomial* if there is a family of polynomials `φₙ` over `ℤ` such that the `n`th coefficient of `f x y` is given by evaluating `φₙ` at the coefficients of `x` and `y`. See also `witt_vector.is_poly` for the unary variant. The `ghost_calc` tactic treats `is_poly₂` as a type class, and the `@[is_poly]` attribute derives certain specialized composition instances for declarations of type `is_poly₂ f`. For the most part, users are not expected to treat `is_poly₂` as a class. -/ class is_poly₂ (f : Π ⦃R⦄ [comm_ring R], witt_vector p R → 𝕎 R → 𝕎 R) : Prop := mk' :: (poly : ∃ φ : ℕ → mv_polynomial (fin 2 × ℕ) ℤ, ∀ ⦃R⦄ [comm_ring R] (x y : 𝕎 R), by exactI (f x y).coeff = λ n, peval (φ n) ![x.coeff, y.coeff]) variable {p} /-- The composition of polynomial functions is polynomial. -/ lemma is_poly₂.comp {h f g} (hh : is_poly₂ p h) (hf : is_poly p f) (hg : is_poly p g) : is_poly₂ p (λ R _Rcr x y, by exactI h (f x) (g y)) := begin unfreezingI { obtain ⟨φ, hf⟩ := hf, obtain ⟨ψ, hg⟩ := hg, obtain ⟨χ, hh⟩ := hh }, refine ⟨⟨(λ n, bind₁ (uncurry $ ![λ k, rename (prod.mk (0 : fin 2)) (φ k), λ k, rename (prod.mk (1 : fin 2)) (ψ k)]) (χ n)), _⟩⟩, intros, funext n, simp only [peval, aeval_bind₁, function.comp, hh, hf, hg, uncurry], apply eval₂_hom_congr rfl _ rfl, ext ⟨i, n⟩, fin_cases i; simp only [aeval_eq_eval₂_hom, eval₂_hom_rename, function.comp, matrix.cons_val_zero, matrix.head_cons, matrix.cons_val_one], end /-- The composition of a polynomial function with a binary polynomial function is polynomial. -/ lemma is_poly.comp₂ {g f} (hg : is_poly p g) (hf : is_poly₂ p f) : is_poly₂ p (λ R _Rcr x y, by exactI g (f x y)) := begin unfreezingI { obtain ⟨φ, hf⟩ := hf, obtain ⟨ψ, hg⟩ := hg }, use (λ n, bind₁ φ (ψ n)), intros, simp only [peval, aeval_bind₁, function.comp, hg, hf] end /-- The diagonal `λ x, f x x` of a polynomial function `f` is polynomial. -/ lemma is_poly₂.diag {f} (hf : is_poly₂ p f) : is_poly p (λ R _Rcr x, by exactI f x x) := begin unfreezingI {obtain ⟨φ, hf⟩ := hf}, refine ⟨⟨λ n, bind₁ (uncurry ![X, X]) (φ n), _⟩⟩, intros, funext n, simp only [hf, peval, uncurry, aeval_bind₁], apply eval₂_hom_congr rfl _ rfl, ext ⟨i, k⟩, fin_cases i; simp only [matrix.head_cons, aeval_X, matrix.cons_val_zero, matrix.cons_val_one], end namespace tactic open tactic /-! ### The `@[is_poly]` attribute This attribute is used to derive specialized composition instances for `is_poly` and `is_poly₂` declarations. -/ /-- If `n` is the name of a lemma with opened type `∀ vars, is_poly p _`, `mk_poly_comp_lemmas n vars p` adds composition instances to the environment `n.comp_i` and `n.comp₂_i`. -/ meta def mk_poly_comp_lemmas (n : name) (vars : list expr) (p : expr) : tactic unit := do c ← mk_const n, let appd := vars.foldl expr.app c, tgt_bod ← to_expr ``(λ f [hf : is_poly %%p f], is_poly.comp %%appd hf) >>= replace_univ_metas_with_univ_params, tgt_bod ← lambdas vars tgt_bod, tgt_tp ← infer_type tgt_bod, let nm := n <.> "comp_i", add_decl $ mk_definition nm tgt_tp.collect_univ_params tgt_tp tgt_bod, set_attribute `instance nm, tgt_bod ← to_expr ``(λ f [hf : is_poly₂ %%p f], is_poly.comp₂ %%appd hf) >>= replace_univ_metas_with_univ_params, tgt_bod ← lambdas vars tgt_bod, tgt_tp ← infer_type tgt_bod, let nm := n <.> "comp₂_i", add_decl $ mk_definition nm tgt_tp.collect_univ_params tgt_tp tgt_bod, set_attribute `instance nm /-- If `n` is the name of a lemma with opened type `∀ vars, is_poly₂ p _`, `mk_poly₂_comp_lemmas n vars p` adds composition instances to the environment `n.comp₂_i` and `n.comp_diag`. -/ meta def mk_poly₂_comp_lemmas (n : name) (vars : list expr) (p : expr) : tactic unit := do c ← mk_const n, let appd := vars.foldl expr.app c, tgt_bod ← to_expr ``(λ {f g} [hf : is_poly %%p f] [hg : is_poly %%p g], is_poly₂.comp %%appd hf hg) >>= replace_univ_metas_with_univ_params, tgt_bod ← lambdas vars tgt_bod, tgt_tp ← infer_type tgt_bod >>= simp_lemmas.mk.dsimplify, let nm := n <.> "comp₂_i", add_decl $ mk_definition nm tgt_tp.collect_univ_params tgt_tp tgt_bod, set_attribute `instance nm, tgt_bod ← to_expr ``(λ {f g} [hf : is_poly %%p f] [hg : is_poly %%p g], (is_poly₂.comp %%appd hf hg).diag) >>= replace_univ_metas_with_univ_params, tgt_bod ← lambdas vars tgt_bod, tgt_tp ← infer_type tgt_bod >>= simp_lemmas.mk.dsimplify, let nm := n <.> "comp_diag", add_decl $ mk_definition nm tgt_tp.collect_univ_params tgt_tp tgt_bod, set_attribute `instance nm /-- The `after_set` function for `@[is_poly]`. Calls `mk_poly(₂)_comp_lemmas`. -/ meta def mk_comp_lemmas (n : name) : tactic unit := do d ← get_decl n, (vars, tp) ← open_pis d.type, match tp with | `(is_poly %%p _) := mk_poly_comp_lemmas n vars p | `(is_poly₂ %%p _) := mk_poly₂_comp_lemmas n vars p | _ := fail "@[is_poly] should only be applied to terms of type `is_poly _ _` or `is_poly₂ _ _`" end /-- `@[is_poly]` is applied to lemmas of the form `is_poly f φ` or `is_poly₂ f φ`. These lemmas should *not* be tagged as instances, and only atomic `is_poly` defs should be tagged: composition lemmas should not. Roughly speaking, lemmas that take `is_poly` proofs as arguments should not be tagged. Type class inference struggles with function composition, and the higher order unification problems involved in inferring `is_poly` proofs are complex. The standard style writing these proofs by hand doesn't work very well. Instead, we construct the type class hierarchy "under the hood", with limited forms of composition. Applying `@[is_poly]` to a lemma creates a number of instances. Roughly, if the tagged lemma is a proof of `is_poly f φ`, the instances added have the form ```lean ∀ g ψ, [is_poly g ψ] → is_poly (f ∘ g) _ ``` Since `f` is fixed in this instance, it restricts the HO unification needed when the instance is applied. Composition lemmas relating `is_poly` with `is_poly₂` are also added. `id_is_poly` is an atomic instance. The user-written lemmas are not instances. Users should be able to assemble `is_poly` proofs by hand "as normal" if the tactic fails. -/ @[user_attribute] meta def is_poly_attr : user_attribute := { name := `is_poly, descr := "Lemmas with this attribute describe the polynomial structure of functions", after_set := some $ λ n _ _, mk_comp_lemmas n } end tactic include hp /-! ### `is_poly` instances These are not declared as instances at the top level, but the `@[is_poly]` attribute adds instances based on each one. Users are expected to use the non-instance versions manually. -/ /-- The additive negation is a polynomial function on Witt vectors. -/ @[is_poly] lemma neg_is_poly : is_poly p (λ R _, by exactI @has_neg.neg (𝕎 R) _) := ⟨⟨λ n, rename prod.snd (witt_neg p n), begin introsI, funext n, rw [neg_coeff, aeval_eq_eval₂_hom, eval₂_hom_rename], apply eval₂_hom_congr rfl _ rfl, ext ⟨i, k⟩, fin_cases i, refl, end⟩⟩ section zero_one /- To avoid a theory of 0-ary functions (a.k.a. constants) we model them as constant unary functions. -/ /-- The function that is constantly zero on Witt vectors is a polynomial function. -/ instance zero_is_poly : is_poly p (λ _ _ _, by exactI 0) := ⟨⟨0, by { introsI, funext n, simp only [pi.zero_apply, alg_hom.map_zero, zero_coeff] }⟩⟩ @[simp] lemma bind₁_zero_witt_polynomial (n : ℕ) : bind₁ (0 : ℕ → mv_polynomial ℕ R) (witt_polynomial p R n) = 0 := by rw [← aeval_eq_bind₁, aeval_zero, constant_coeff_witt_polynomial, ring_hom.map_zero] omit hp /-- The coefficients of `1 : 𝕎 R` as polynomials. -/ def one_poly (n : ℕ) : mv_polynomial ℕ ℤ := if n = 0 then 1 else 0 include hp @[simp] lemma bind₁_one_poly_witt_polynomial (n : ℕ) : bind₁ one_poly (witt_polynomial p ℤ n) = 1 := begin rw [witt_polynomial_eq_sum_C_mul_X_pow, alg_hom.map_sum, finset.sum_eq_single 0], { simp only [one_poly, one_pow, one_mul, alg_hom.map_pow, C_1, pow_zero, bind₁_X_right, if_true, eq_self_iff_true], }, { intros i hi hi0, simp only [one_poly, if_neg hi0, zero_pow (pow_pos hp.1.pos _), mul_zero, alg_hom.map_pow, bind₁_X_right, alg_hom.map_mul], }, { rw finset.mem_range, dec_trivial } end /-- The function that is constantly one on Witt vectors is a polynomial function. -/ instance one_is_poly : is_poly p (λ _ _ _, by exactI 1) := ⟨⟨one_poly, begin introsI, funext n, cases n, { simp only [one_poly, if_true, eq_self_iff_true, one_coeff_zero, alg_hom.map_one], }, { simp only [one_poly, nat.succ_pos', one_coeff_eq_of_pos, if_neg n.succ_ne_zero, alg_hom.map_zero] } end⟩⟩ end zero_one omit hp /-- Addition of Witt vectors is a polynomial function. -/ @[is_poly] lemma add_is_poly₂ [fact p.prime] : is_poly₂ p (λ _ _, by exactI (+)) := ⟨⟨witt_add p, by { introsI, dunfold witt_vector.has_add, simp [eval] }⟩⟩ /-- Multiplication of Witt vectors is a polynomial function. -/ @[is_poly] lemma mul_is_poly₂ [fact p.prime] : is_poly₂ p (λ _ _, by exactI (*)) := ⟨⟨witt_mul p, by { introsI, dunfold witt_vector.has_mul, simp [eval] }⟩⟩ include hp -- unfortunately this is not universe polymorphic, merely because `f` isn't lemma is_poly.map {f} (hf : is_poly p f) (g : R →+* S) (x : 𝕎 R) : map g (f x) = f (map g x) := begin -- this could be turned into a tactic “macro” (taking `hf` as parameter) -- so that applications do not have to worry about the universe issue -- see `is_poly₂.map` for a slightly more general proof strategy unfreezingI {obtain ⟨φ, hf⟩ := hf}, ext n, simp only [map_coeff, hf, map_aeval], apply eval₂_hom_congr (ring_hom.ext_int _ _) _ rfl, simp only [map_coeff] end namespace is_poly₂ omit hp instance [fact p.prime] : inhabited (is_poly₂ p _) := ⟨add_is_poly₂⟩ variables {p} /-- The composition of a binary polynomial function with a unary polynomial function in the first argument is polynomial. -/ lemma comp_left {g f} (hg : is_poly₂ p g) (hf : is_poly p f) : is_poly₂ p (λ R _Rcr x y, by exactI g (f x) y) := hg.comp hf (witt_vector.id_is_poly _) /-- The composition of a binary polynomial function with a unary polynomial function in the second argument is polynomial. -/ lemma comp_right {g f} (hg : is_poly₂ p g) (hf : is_poly p f) : is_poly₂ p (λ R _Rcr x y, by exactI g x (f y)) := hg.comp (witt_vector.id_is_poly p) hf include hp lemma ext {f g} (hf : is_poly₂ p f) (hg : is_poly₂ p g) (h : ∀ (R : Type u) [_Rcr : comm_ring R] (x y : 𝕎 R) (n : ℕ), by exactI ghost_component n (f x y) = ghost_component n (g x y)) : ∀ (R) [_Rcr : comm_ring R] (x y : 𝕎 R), by exactI f x y = g x y := begin unfreezingI { obtain ⟨φ, hf⟩ := hf, obtain ⟨ψ, hg⟩ := hg }, intros, ext n, rw [hf, hg, poly_eq_of_witt_polynomial_bind_eq' p φ ψ], clear x y, intro k, apply mv_polynomial.funext, intro x, simp only [hom_bind₁], specialize h (ulift ℤ) (mk p $ λ i, ⟨x (0, i)⟩) (mk p $ λ i, ⟨x (1, i)⟩) k, simp only [ghost_component_apply, aeval_eq_eval₂_hom] at h, apply (ulift.ring_equiv.{0 u}).symm.injective, simp only [map_eval₂_hom], convert h; clear h, all_goals { funext i, rw [← ring_equiv.coe_to_ring_hom], simp only [hf, hg, mv_polynomial.eval, map_eval₂_hom], apply eval₂_hom_congr (ring_hom.ext_int _ _) _ rfl, ext1, apply eval₂_hom_congr (ring_hom.ext_int _ _) _ rfl, ext ⟨b, _⟩, fin_cases b; simp only [coeff_mk, uncurry]; refl } end -- unfortunately this is not universe polymorphic, merely because `f` isn't lemma map {f} (hf : is_poly₂ p f) (g : R →+* S) (x y : 𝕎 R) : map g (f x y) = f (map g x) (map g y) := begin -- this could be turned into a tactic “macro” (taking `hf` as parameter) -- so that applications do not have to worry about the universe issue unfreezingI {obtain ⟨φ, hf⟩ := hf}, ext n, simp only [map_coeff, hf, map_aeval, peval, uncurry], apply eval₂_hom_congr (ring_hom.ext_int _ _) _ rfl, try { ext ⟨i, k⟩, fin_cases i }, all_goals { simp only [map_coeff, matrix.cons_val_zero, matrix.head_cons, matrix.cons_val_one] }, end end is_poly₂ attribute [ghost_simps] alg_hom.map_zero alg_hom.map_one alg_hom.map_add alg_hom.map_mul alg_hom.map_sub alg_hom.map_neg alg_hom.id_apply alg_hom.map_nat_cast ring_hom.map_zero ring_hom.map_one ring_hom.map_mul ring_hom.map_add ring_hom.map_sub ring_hom.map_neg ring_hom.id_apply ring_hom.map_nat_cast mul_add add_mul add_zero zero_add mul_one one_mul mul_zero zero_mul nat.succ_ne_zero nat.add_sub_cancel nat.succ_eq_add_one if_true eq_self_iff_true if_false forall_true_iff forall_2_true_iff forall_3_true_iff end witt_vector
fafdf322b9be9c1a00a10eba90323efbba188c9d
75c54c8946bb4203e0aaf196f918424a17b0de99
/src/aleph_one.lean
bc091441f546bcfced00222382c78484ad1e57eb
[ "Apache-2.0" ]
permissive
urkud/flypitch
261e2a45f1038130178575406df8aea78255ba77
2250f5eda14b6ef9fc3e4e1f4a9ac4005634de5c
refs/heads/master
1,653,266,469,246
1,577,819,679,000
1,577,819,679,000
259,862,235
1
0
Apache-2.0
1,588,147,244,000
1,588,147,244,000
null
UTF-8
Lean
false
false
46,135
lean
import .bvm_extras2 universes u v namespace pSet section open cardinal lemma regularity (x : pSet.{u}) (H_nonempty : ¬ equiv x (∅ : pSet.{u})) : ∃ (y : pSet) (Hy : y ∈ x), ∀ z ∈ x, ¬ (z ∈ y) := begin have := is_epsilon_well_founded x, cases exists_mem_of_nonempty H_nonempty with w Hw, have := this x (subset_self) ‹_›, { rcases this with ⟨y, Hy₁, Hy₂⟩, exact ⟨y,‹_›,‹_›⟩ } end noncomputable def aleph_one : pSet := card_ex (aleph 1) lemma aleph_one_Ord : Ord aleph_one := by apply Ord_mk def aleph_one_weak_Ord_spec (x : pSet.{u}) : Prop := Ord x ∧ (∀ y : pSet.{u}, Ord y ∧ ¬ injects_into y pSet.omega → x ⊆ y) def epsilon_trichotomy (x : pSet.{u}) : Prop := ∀ (y : pSet), y ∈ x → ∀ (z : pSet), z ∈ x → equiv y z ∨ y ∈ z ∨ z ∈ y lemma epsilon_trichotomy_of_Ord {x : pSet.{u}} (H_ord : Ord x) : epsilon_trichotomy x := H_ord.left.left lemma epsilon_trichotomy_of_Ord' {x : pSet.{u}} (H_ord : Ord x) : ∀ {y} (Hy : y ∈ x) {z} (Hz : z ∈ x), equiv y z ∨ y ∈ z ∨ z ∈ y := by { have := epsilon_trichotomy_of_Ord H_ord, intros, unfold epsilon_trichotomy at this, solve_by_elim } lemma is_transitive_of_mem_Ord {x : pSet.{u}} (H_ord : Ord x) : is_transitive x := H_ord.right lemma mem_of_mem_subset {x y z : pSet.{u}} (H_sub : y ⊆ z) (H_mem : x ∈ y) : x ∈ z := by { rw subset_iff_all_mem at H_sub, solve_by_elim } lemma mem_of_mem_Ord {x y z : pSet.{u}} (H_ord : Ord z) (H_mem₁ : x ∈ y) (H_mem₂ : y ∈ z) : x ∈ z := begin have := is_transitive_of_mem_Ord H_ord, refine mem_of_mem_subset _ H_mem₁, solve_by_elim end lemma subset_of_mem_Ord {x z : pSet.{u}} (H_ord : Ord z) (H_mem₁ : x ∈ z) : x ⊆ z := by {cases H_ord with H_ewo H_trans, solve_by_elim} lemma Ord_of_mem_Ord {x z : pSet.{u}} (H_mem : x ∈ z) (H : Ord z) : Ord x := begin refine ⟨_,_⟩, { refine ⟨_, by apply is_epsilon_well_founded⟩, intros y₁ Hy₁ y₂ Hy₂, apply (epsilon_trichotomy_of_Ord H); apply mem_of_mem_Ord; from ‹_› }, { apply transitive_of_mem_Ord, repeat { assumption } } end def compl (x y : pSet.{u}) : pSet.{u} := {z ∈ x | ¬ z ∈ y} lemma mem_compl_iff {x y z : pSet.{u}} : z ∈ compl x y ↔ z ∈ x ∧ ¬ z ∈ y := by {erw mem_sep_iff, simp} @[reducible]def non_empty (x : pSet.{u}) : Prop := ¬ (equiv x (∅ : pSet.{u})) lemma equiv_unfold' {x y : pSet.{u}} : equiv x y ↔ (∀ z, z ∈ x → z ∈ y) ∧ (∀ z, z ∈ y → z ∈ x ) := by simp [equiv.ext, subset_iff_all_mem] lemma nonempty_iff_exists_mem {x : pSet.{u}} : non_empty x ↔ ∃ y, y ∈ x := begin refine ⟨_,_⟩, { exact exists_mem_of_nonempty }, { intro H_ex_mem, intro H_eq, cases H_ex_mem with y Hy, apply pSet.mem_empty y, pSet_cc } end lemma nonempty_compl_of_ne {x y : pSet.{u}} (H_ne : ¬ equiv x y) : (non_empty $ compl x y) ∨ (non_empty $ compl y x) := begin rw equiv_unfold' at H_ne, push_neg at H_ne, cases H_ne, { rcases H_ne with ⟨z,Hz₁,Hz₂⟩, left, rw nonempty_iff_exists_mem, use z, simp[mem_compl_iff, *] }, { rcases H_ne with ⟨z,Hz₁,Hz₂⟩, right, rw nonempty_iff_exists_mem, use z, simp [mem_compl_iff, *] } end lemma compl_empty_of_subset {x y : pSet.{u}} (H_sub : x ⊆ y) : equiv (compl x y) (∅ : pSet.{u}) := begin classical, by_contra H_contra, change non_empty _ at H_contra, rw nonempty_iff_exists_mem at H_contra, cases H_contra with z Hz, rw mem_compl_iff at Hz, cases Hz, suffices : z ∈ y, by contradiction, from mem_of_mem_subset H_sub ‹_› end def binary_inter (x y : pSet.{u}) : pSet.{u} := {z ∈ x | z ∈ y} lemma mem_binary_inter_iff {x y z : pSet.{u}} : z ∈ binary_inter x y ↔ (z ∈ x ∧ z ∈ y) := by {erw mem_sep_iff, simp} lemma binary_inter_subset {x y : pSet.{u}} : ((binary_inter x y ⊆ x) ∧ (binary_inter x y ⊆ y)) := by {refine ⟨_,_⟩; rw subset_iff_all_mem; intros z Hz; rw mem_binary_inter_iff at Hz; simp*} lemma Ord_binary_inter {x y : pSet.{u}} (H₁ : Ord x) (H₂ : Ord y) : Ord (binary_inter x y) := begin refine ⟨⟨_,_⟩,_⟩, { intros w Hw_mem z Hz_mem, rw mem_binary_inter_iff at Hw_mem Hz_mem, have := epsilon_trichotomy_of_Ord H₁, tidy }, { apply is_epsilon_well_founded }, { intros z H_mem, rw mem_binary_inter_iff at H_mem, cases H_mem with H_mem₁ H_mem₂, rw subset_iff_all_mem, intros w Hw, rw mem_binary_inter_iff, refine ⟨_,_⟩, { exact mem_of_mem_Ord H₁ ‹_› ‹_› }, { exact mem_of_mem_Ord H₂ ‹_› ‹_› }} end lemma Ord.lt_of_ne_and_le {x y : pSet.{u}} (H₁ : Ord x) (H₂ : Ord y) (H_ne : ¬ (equiv x y)) (H_le : x ⊆ y) : x ∈ y := begin have H_compl_nonempty : non_empty (compl y x), by { have this₁ := nonempty_compl_of_ne ‹_›, have this₂ := compl_empty_of_subset ‹_›, cases this₁, { exfalso, contradiction }, { from ‹_› } }, have H_ex_min := regularity _ H_compl_nonempty, rcases H_ex_min with ⟨z,⟨Hz₁,Hz₂⟩⟩, cases mem_compl_iff.mp Hz₁ with Hz₁ Hz₁', suffices H_eq : equiv x z, by pSet_cc, apply mem.ext, intro a, refine ⟨_,_⟩; intro H_mem, { have this' := epsilon_trichotomy_of_Ord' H₂ (mem_of_mem_subset H_le ‹_›) Hz₁, cases this', { exfalso, pSet_cc }, { cases this', { from ‹_› }, { exfalso, suffices : z ∈ x, by pSet_cc, refine mem_of_mem_Ord _ _ _, from a, repeat { assumption }}},}, { classical, by_contra, have H_mem_y : a ∈ y, by {exact mem_of_mem_Ord ‹Ord y› H_mem ‹_› }, have : a ∈ y ∧ ¬(a ∈ x) := ⟨‹_›,‹_›⟩, rw ←mem_compl_iff at this, refine absurd H_mem _, solve_by_elim } end lemma Ord.le_or_le {x y : pSet.{u}} (H₁ : Ord x) (H₂ : Ord y) : x ⊆ y ∨ y ⊆ x := begin let w := binary_inter x y, have w_Ord : Ord w := Ord_binary_inter H₁ H₂, have : equiv w x ∨ equiv w y, by { classical, by_contra H_contra, push_neg at H_contra, suffices : w ∈ x ∧ w ∈ y, by { suffices : w ∈ w, from mem_self ‹_›, rwa mem_binary_inter_iff }, cases H_contra with H_contra₁ H_contra₂, refine ⟨_,_⟩, { exact Ord.lt_of_ne_and_le w_Ord ‹_› ‹_› binary_inter_subset.left }, { exact Ord.lt_of_ne_and_le w_Ord H₂ ‹_› binary_inter_subset.right }}, cases @binary_inter_subset x y with H_sub₁ H_sub₂, cases this, { left, dsimp[w] at this, pSet_cc }, { right, dsimp[w] at this, pSet_cc } end lemma equiv.comm {x y : pSet.{u}} : equiv x y ↔ equiv y x := by {have := @equiv.symm, tidy} -- why does {[smt] eblast_using [equiv.symm]} fail here? lemma Ord.trichotomy {x y : pSet.{u}} (H₁ : Ord x) (H₂ : Ord y) : equiv x y ∨ x ∈ y ∨ y ∈ x := begin classical, have := Ord.le_or_le H₁ H₂, cases this, { by_cases (equiv x y), { from or.inl ‹_› }, { refine or.inr (or.inl _), from Ord.lt_of_ne_and_le H₁ H₂ ‹_› ‹_› }}, { by_cases (equiv x y), { from or.inl ‹_› }, { refine or.inr (or.inr _), rw equiv.comm at h, have := @Ord.lt_of_ne_and_le, tactic.back_chaining_using_hs },}, end lemma Ord.lt_of_le_of_lt {x y z : pSet.{u}} (Hx : Ord x) (Hy : Ord y) (Hz : Ord z) (H_le : x ⊆ y) (H_lt : y ∈ z) : x ∈ z := begin have := Ord.trichotomy Hx Hy, have H_dichotomy : x ∈ y ∨ equiv x y, by {cases this, right, from ‹_›, cases this, left, from ‹_›, right, rw equiv.ext, refine ⟨‹_›,_⟩, apply Hx.right, from ‹_› }, cases H_dichotomy, { apply mem_trans_of_transitive, from ‹_›, from ‹_›, from Hz.right }, { rwa mem.congr_left (equiv.symm H_dichotomy) at H_lt } end lemma Ord.le_iff_lt_or_eq {x z : pSet.{u}} (H₁ : Ord x) (H₂ : Ord z) : x ⊆ z ↔ x ∈ z ∨ equiv x z := begin classical, refine ⟨_,_⟩; intro H, { by_cases H_eq : equiv x z, { right, from ‹_› }, { left, refine Ord.lt_of_ne_and_le H₁ _ _ _, repeat { from ‹_› }}}, { cases H, { from subset_of_mem_Ord H₂ ‹_› }, { have : x ⊆ x := subset_self, pSet_cc }}, end local prefix `#`:70 := cardinal.mk lemma mk_injects_into_of_mk_le_omega {η : ordinal.{u}} (H_le : #(ordinal.mk η).type ≤ #(pSet.omega : pSet.{u}).type) : injects_into (ordinal.mk η) pSet.omega := begin have H_ex_inj : ∃ f : (ordinal.mk η).type → (omega : pSet.{u}).type, function.injective f, by exact cardinal.injection_of_mk_le ‹_›, cases H_ex_inj with f Hf, let ψ : (ordinal.mk η).type → pSet.{u} := λ i, omega.func (f i), have H_congr : ∀ i j, pSet.equiv ((ordinal.mk η).func i) ((ordinal.mk η).func j) → pSet.equiv (ψ i) (ψ j), by { intros i₁ i₂ H_eqv, suffices : i₁ = i₂, by subst this, classical, by_contra, have := ordinal.mk_inj η i₁ i₂ ‹_›, contradiction }, have H_inj : ∀ i₁ i₂, equiv (ψ i₁) (ψ i₂) → equiv ((ordinal.mk η).func i₁) ((ordinal.mk η).func i₂), by {intros i₁ i₂ H_eqv, suffices : i₁ = i₂, by { subst this }, have := omega_inj H_eqv, finish }, use pSet.function.mk ψ H_congr, refine ⟨_,_⟩, { apply pSet.function.mk_is_func, simp* }, { apply pSet.function.mk_inj_of_inj, from ‹_› } end lemma injects_into_omega_of_mem_aleph_one {z : pSet} (H_mem : z ∈ aleph_one) : injects_into z omega := begin rcases equiv_mk_of_mem_mk z H_mem with ⟨w, Hw_lt, Hz_eq⟩, suffices : injects_into (ordinal.mk w) omega, by { apply P_ext_injects_into_left, from equiv.symm ‹_›, from ‹_› }, refine mk_injects_into_of_mk_le_omega _, rw [ordinal.mk_card, mk_omega_eq_mk_omega, ←cardinal.lt_succ], rwa [lt_ord, aleph_one_eq_succ_aleph_zero] at Hw_lt end lemma aleph_one_satisfies_spec : aleph_one_weak_Ord_spec aleph_one := begin refine ⟨aleph_one_Ord,_⟩, rintros z ⟨Hz₁, Hz₂⟩, rw Ord.le_iff_lt_or_eq (aleph_one_Ord) ‹_›, have := Ord.trichotomy aleph_one_Ord ‹_›, cases this with this₁ this, { from or.inr ‹_› }, { cases this with this₂ this₃, { from or.inl ‹_› }, { exfalso, from absurd (injects_into_omega_of_mem_aleph_one ‹_›) ‹_› }} end end end pSet open lattice bSet cardinal namespace bSet local notation `ℵ₁` := pSet.aleph_one local infix ` ⟹ `:65 := lattice.imp local infix ` ⇔ `:50 := lattice.biimp local infix `≺`:75 := (λ x y, -(larger_than x y)) local infix `≼`:75 := (λ x y, injects_into x y) section well_ordering variables {𝔹 : Type u} [nontrivial_complete_boolean_algebra 𝔹] @[reducible]def is_rel (r x : bSet 𝔹) : 𝔹 := r ⊆ᴮ prod x x def is_wo (r x : bSet 𝔹) : 𝔹 := is_rel r x ⊓ ((⨅y, pair y x ∈ᴮ r ⟹ (⨅z, pair z x ∈ᴮ r ⟹ (y =ᴮ z ⊔ pair y z ∈ᴮ r ⊔ pair z y ∈ᴮ r))) ⊓ (⨅u, u ⊆ᴮ x ⟹ (- (u =ᴮ ∅) ⟹ ⨆y, pair y u ∈ᴮ r ⊓ (⨅z', pair z' u ∈ᴮ r ⟹ (- (pair z' y ∈ᴮ r)))))) def mem_rel (x : bSet 𝔹) : bSet 𝔹 := subset.mk (λ pr : (prod x x).type, x.func pr.1 ∈ᴮ x.func pr.2) lemma mem_mem_rel_iff {x y z: bSet 𝔹} {Γ} : Γ ≤ pair y z ∈ᴮ mem_rel x ↔ (Γ ≤ y ∈ᴮ x ∧ Γ ≤ z ∈ᴮ x ∧ Γ ≤ y ∈ᴮ z) := begin erw mem_subset.mk_iff, refine ⟨_,_⟩; intro H, { simp at H, simp only [le_inf_iff.symm], bv_cases_at H pr Hpr, bv_split_at Hpr, rw pair_eq_pair_iff at Hpr_left, cases Hpr_left with H₁ H₂, simp only [le_inf_iff] at ⊢ Hpr_right, rcases Hpr_right with ⟨H'₁,H'₂,H'₃⟩, refine ⟨_,_,_⟩, { apply bv_rw' H₁, simp, simp* }, { apply bv_rw' H₂, simp, simp* }, { apply bv_rw' H₁, simp, apply bv_rw' H₂, simpa }}, { rcases H with ⟨H₁, H₂, H₃⟩, have H₄ := H₁, have H₅ := H₂, rw mem_unfold at H₄ H₅, bv_cases_at H₄ i Hi, bv_cases_at H₅ j Hj, bv_split_at Hi, bv_split_at Hj, apply bv_use (i,j), refine le_inf _ _, { dsimp, rw pair_eq_pair_iff, from ⟨‹_›, ‹_›⟩ }, { tidy, bv_cc } } end @[simp]lemma B_congr_mem_rel : B_congr (mem_rel : bSet 𝔹 → bSet 𝔹) := begin intros x y Γ H_eq, apply prod_ext, apply subset.mk_subset, { suffices : Γ ≤ prod x x =ᴮ prod y y, by {apply bv_rw' this, simp, apply subset.mk_subset }, exact prod_congr H_eq H_eq }, { bv_intro v, bv_imp_intro Hv_mem, bv_intro w, bv_imp_intro Hw_mem, refine le_inf _ _, { bv_imp_intro Hpr_mem, erw mem_mem_rel_iff at Hpr_mem ⊢, tidy; bv_cc }, { bv_imp_intro Hpr_mem, erw mem_mem_rel_iff at Hpr_mem ⊢, tidy; bv_cc },} end def prod.map (x y v w : bSet 𝔹) (f g : bSet 𝔹) : bSet 𝔹 := subset.mk (λ (pr : (prod (prod x v) (prod y w)).type), pair (x.func pr.1.1) (y.func pr.2.1) ∈ᴮ f ⊓ pair (v.func pr.1.2) (w.func pr.2.2) ∈ᴮ g) def prod.map_self (x y f : bSet 𝔹) : bSet 𝔹 := prod.map x y x y f f lemma B_congr_prod.map_self_left_aux {y f x x' : bSet 𝔹} {Γ : 𝔹} {H_eq : Γ ≤ x =ᴮ x'} : Γ ≤ ⨅ (z : bSet 𝔹), z ∈ᴮ (λ (x : bSet 𝔹), prod.map_self x y f) x ⟹ z ∈ᴮ (λ (x : bSet 𝔹), prod.map_self x y f) x' := begin bv_intro z, bv_imp_intro H_mem, erw mem_subset.mk_iff₂ at H_mem ⊢, bv_cases_at H_mem pr Hpr, cases pr with pr₁ pr₂, cases pr₁ with a₁ a₂, cases pr₂ with b₁ b₂, dsimp only at Hpr, bv_split_at Hpr, bv_split_at Hpr_right, bv_split_at Hpr_right_right, simp at Hpr_left, rcases Hpr_left with ⟨⟨Ha₁, Ha₂⟩, Hb₁, Hb₂⟩, have Ha₁_mem : Γ_2 ≤ (x.func a₁) ∈ᴮ x' := bv_rw'' H_eq (mem.mk'' ‹_›), have Ha₂_mem : Γ_2 ≤ (x.func a₂) ∈ᴮ x' := bv_rw'' H_eq (mem.mk'' ‹_›), rw mem_unfold at Ha₁_mem Ha₂_mem, bv_cases_at Ha₁_mem a₁' Ha₁', bv_cases_at Ha₂_mem a₂' Ha₂', apply bv_use ((a₁', a₂'), (b₁, b₂)), bv_split_at Ha₁', bv_split_at Ha₂', refine le_inf (le_inf (le_inf ‹_› ‹_›) (le_inf ‹_› ‹_›) ) (le_inf _ (le_inf _ _)), { apply bv_rw' Hpr_right_left, simp, erw pair_eq_pair_iff, refine ⟨_,_⟩, { erw pair_eq_pair_iff, from ⟨‹_›,‹_›⟩ }, { erw pair_eq_pair_iff, from ⟨bv_refl, bv_refl⟩ } }, { dsimp, change _ ≤ (λ w, pair w (func y b₁) ∈ᴮ f) _, apply bv_rw' (bv_symm Ha₁'_right), from B_ext_pair_mem_left, from ‹_› }, { dsimp, change _ ≤ (λ w, pair w (func y b₂) ∈ᴮ f) _, apply bv_rw' (bv_symm Ha₂'_right), from B_ext_pair_mem_left, from ‹_› } end @[simp]lemma B_congr_prod.map_self_left { y f : bSet 𝔹 } : B_congr (λ x : bSet 𝔹, prod.map_self x y f ) := begin intros x x' Γ H_eq, refine mem_ext _ _, { apply B_congr_prod.map_self_left_aux, from ‹_› }, { apply B_congr_prod.map_self_left_aux, from bv_symm ‹_› } end lemma mem_prod.map_self_iff { x y f a₁ a₂ b₁ b₂ : bSet 𝔹 } { Γ : 𝔹 } (H_func : Γ ≤ is_function x y f) : Γ ≤ pair (pair a₁ a₂) (pair b₁ b₂) ∈ᴮ prod.map_self x y f ↔ Γ ≤ a₁ ∈ᴮ x ∧ Γ ≤ a₂ ∈ᴮ x ∧ Γ ≤ b₁ ∈ᴮ y ∧ Γ ≤ b₂ ∈ᴮ y ∧ Γ ≤ pair a₁ b₁ ∈ᴮ f ∧ Γ ≤ pair a₂ b₂ ∈ᴮ f := begin refine ⟨_,_⟩; intro H, { erw mem_subset.mk_iff₂ at H, simp only [le_inf_iff.symm], bv_cases_at H pr Hpr, rcases pr with ⟨⟨i₁,i₂⟩, ⟨j₁,j₂⟩⟩, simp only [le_inf_iff] at Hpr, rcases Hpr with ⟨Hpr, Hpr', Hpr'', Hpr'''⟩, simp only [le_inf_iff], simp at Hpr, rcases Hpr with ⟨⟨Hi₁, Hi₂⟩, Hj₁, Hj₂⟩, have Ha₁_mem : Γ_1 ≤ (x.func i₁) ∈ᴮ x := (mem.mk'' ‹_›), have Ha₂_mem : Γ_1 ≤ (x.func i₂) ∈ᴮ x := (mem.mk'' ‹_›), have Hb₁_mem : Γ_1 ≤ (y.func j₁) ∈ᴮ y := (mem.mk'' ‹_›), have Hb₂_mem : Γ_1 ≤ (y.func j₂) ∈ᴮ y := (mem.mk'' ‹_›), repeat {erw pair_eq_pair_iff at Hpr'}, dsimp at Hpr', rcases Hpr' with ⟨⟨Heq₁, Heq₂⟩, Heq₃, Heq₄⟩, refine ⟨_,_,_,_,_,_⟩, { bv_cc }, { bv_cc }, { bv_cc }, { bv_cc }, { suffices : Γ_1 ≤ pair a₁ b₁ =ᴮ pair (func x i₁) (func y j₁), by { change _ ≤ (λ w, w ∈ᴮ f) _, apply bv_rw' (this), simp, from ‹_› }, rw pair_eq_pair_iff, exact ⟨‹_›,‹_›⟩ }, { suffices : Γ_1 ≤ pair a₂ b₂ =ᴮ pair (func x i₂) (func y j₂), by { change _ ≤ (λ w, w ∈ᴮ f) _, apply bv_rw' (this), simp, from ‹_› }, rw pair_eq_pair_iff, exact ⟨‹_›,‹_›⟩ }}, { rcases H with ⟨Ha₁_mem, Ha₂_mem, Hb₁_mem, Hb₂_mem, Hpr₁_mem, Hpr₂_mem⟩, erw mem_subset.mk_iff₂, rw mem_unfold at Ha₁_mem Ha₂_mem Hb₁_mem Hb₂_mem, bv_cases_at Ha₁_mem i₁ Hi₁, bv_split_at Hi₁, bv_cases_at Ha₂_mem i₂ Hi₂, bv_split_at Hi₂, bv_cases_at Hb₁_mem j₁ Hj₁, bv_split_at Hj₁, bv_cases_at Hb₂_mem j₂ Hj₂, bv_split_at Hj₂, apply bv_use ((i₁,i₂), (j₁,j₂)), refine le_inf (le_inf (le_inf ‹_› ‹_›) (le_inf ‹_› ‹_›)) (le_inf _ (le_inf _ _)), { repeat {erw pair_eq_pair_iff}, simp* }, { dsimp, suffices : Γ_4 ≤ pair (func x i₁) (func y j₁) =ᴮ pair a₁ b₁, by { change _ ≤ (λ w, w ∈ᴮ f) _, apply bv_rw' this, simp, from ‹_› }, rw pair_eq_pair_iff, refine ⟨bv_symm _, bv_symm _⟩; assumption }, { dsimp, suffices : Γ_4 ≤ pair (func x i₂) (func y j₂) =ᴮ pair a₂ b₂, by { change _ ≤ (λ w, w ∈ᴮ f) _, apply bv_rw' this, simp, from ‹_› }, rw pair_eq_pair_iff, refine ⟨bv_symm _, bv_symm _⟩; assumption } } end def induced_epsilon_rel (η : bSet 𝔹) (x : bSet 𝔹) (f : bSet 𝔹) : bSet 𝔹 := image (mem_rel η) (prod x x) (prod.map_self η x f) lemma eq_pair_of_mem_induced_epsilon_rel {η x f pr : bSet 𝔹} {Γ} (H_mem : Γ ≤ pr ∈ᴮ induced_epsilon_rel η x f) : ∃ a b : bSet 𝔹, Γ ≤ a ∈ᴮ x ∧ Γ ≤ b ∈ᴮ x ∧ Γ ≤ pr =ᴮ pair a b ∧ Γ ≤ pair a b ∈ᴮ induced_epsilon_rel η x f := begin have : Γ ≤ pr ∈ᴮ prod x x, by {refine mem_of_mem_subset _ H_mem, apply subset.mk_subset}, rw mem_prod_iff₂ at this, rcases this with ⟨v,Hv,w,Hw,H_eq⟩, use v, use w, refine ⟨‹_›,‹_›,‹_›, _⟩, change _ ≤ (λ z, z ∈ᴮ induced_epsilon_rel η x f) _, apply bv_rw' (bv_symm H_eq), simpa end lemma mem_induced_epsilon_rel_iff { η x f a b : bSet 𝔹 } { Γ } (H_func : Γ ≤ is_function η x f) : Γ ≤ pair a b ∈ᴮ (induced_epsilon_rel η x f) ↔ (Γ ≤ a ∈ᴮ x) ∧ (Γ ≤ b ∈ᴮ x) ∧ (Γ ≤ ⨆ a', a' ∈ᴮ η ⊓ ⨆ b', b' ∈ᴮ η ⊓ (pair a' a ∈ᴮ f ⊓ pair b' b ∈ᴮ f ⊓ a' ∈ᴮ b')) := begin refine ⟨_,_⟩; intro H, { erw mem_image_iff at H, cases H with H₁ H₂, simp at H₁, cases H₁ with H₁ H₁', refine ⟨‹_›,‹_›,_⟩, bv_cases_at H₂ z Hz, bv_split_at Hz, have : Γ_1 ≤ z ∈ᴮ prod η η, by {refine mem_of_mem_subset _ Hz_left, apply subset.mk_subset }, rw mem_prod_iff₂ at this, rcases this with ⟨v,Hv,w,Hw,H_eq⟩, apply bv_use v, refine le_inf ‹_› (bv_use w), refine le_inf ‹_› _, have : Γ_1 ≤ pair (pair v w) (pair a b) ∈ᴮ prod.map_self η x f, by { change _ ≤ (λ k, pair k (pair a b) ∈ᴮ prod.map_self η x f) _, apply bv_rw' (bv_symm H_eq), simp, from ‹_› }, rw mem_prod.map_self_iff at this, rcases this with ⟨_,_,_,_,_,_⟩, refine le_inf (le_inf ‹_› ‹_›) _, suffices : Γ_1 ≤ (pair v w ∈ᴮ mem_rel η), by { rw mem_mem_rel_iff at this, simp* }, change _ ≤ (λ s, s ∈ᴮ mem_rel η) _, apply bv_rw' (bv_symm H_eq), simp, from ‹_›, from ‹_› }, { rcases H with ⟨H₁,H₂,H₃⟩, bv_cases_at H₃ a' Ha', bv_split_at Ha', bv_cases_at Ha'_right b' Hb', bv_split_at Hb', erw mem_image_iff, refine ⟨_,_⟩, { rw mem_prod_iff, bv_split_at Hb'_right, bv_split_at Hb'_right_left, refine ⟨_,_⟩, { apply mem_codomain_of_is_function ‹_› ‹_› }, { apply mem_codomain_of_is_function ‹Γ_2 ≤ pair b' b ∈ᴮ f› ‹_› }}, { apply bv_use (pair a' b'), refine le_inf _ _, { rw mem_mem_rel_iff, exact ⟨‹_›,‹_›,bv_and.right ‹_›⟩ }, { rw mem_prod.map_self_iff, refine ⟨‹_›,‹_›, ‹_›, ‹_›, _⟩, bv_split_at Hb'_right, bv_split_at Hb'_right_left, from ⟨‹_›,‹_›⟩, from ‹_› }}} end lemma mem_induced_epsilon_rel_of_mem {η x f a b : bSet 𝔹} {Γ} (H_mem₁ : Γ ≤ a ∈ᴮ η) (H_mem₂ : Γ ≤ b ∈ᴮ η) (H_mem : Γ ≤ a ∈ᴮ b) (H_func : Γ ≤ is_function η x f) : Γ ≤ pair (function_eval H_func a H_mem₁) (function_eval H_func b H_mem₂) ∈ᴮ induced_epsilon_rel η x f := begin rw mem_induced_epsilon_rel_iff ‹_›, refine ⟨_,_,_⟩, { apply function_eval_mem_codomain }, { apply function_eval_mem_codomain }, { apply bv_use a, refine le_inf ‹_› (bv_use b), refine le_inf ‹_› (le_inf (le_inf _ _) ‹_›), { apply function_eval_pair_mem }, { apply function_eval_pair_mem }} end lemma mem_of_mem_induced_epsilon_rel {η x f a' b' a b : bSet 𝔹} {Γ} (H_inj : Γ ≤ is_injective_function η x f) (H_mem₁ : Γ ≤ pair a' a ∈ᴮ f) (H_mem₂ : Γ ≤ pair b' b ∈ᴮ f) (H_mem : Γ ≤ pair a b ∈ᴮ induced_epsilon_rel η x f) : Γ ≤ a' ∈ᴮ b' := begin rw (mem_induced_epsilon_rel_iff $ bv_and.left ‹_›) at H_mem, rcases H_mem with ⟨Ha_mem, Hb_mem, H⟩, bv_cases_at H a'' Ha'', bv_split_at Ha'', bv_cases_at Ha''_right b'' Hb'', simp only [le_inf_iff] at Hb'', rcases Hb'' with ⟨Hb''₁, ⟨Hb''₂, Hb''₃⟩, Hb''₄⟩, suffices : Γ_2 ≤ a' =ᴮ a'' ∧ Γ_2 ≤ b' =ᴮ b'', by {cases this, bv_cc}, have H_inj' := is_inj_of_is_injective_function H_inj, refine ⟨_,_⟩, { refine H_inj' a' a'' a a _, exact le_inf (le_inf ‹_› ‹_›) bv_refl }, { refine H_inj' b' b'' b b _, exact le_inf (le_inf ‹_› ‹_›) bv_refl } end lemma induced_epsilon_rel_sub_image_left { η x f a b : bSet 𝔹 } { Γ } (H_func : Γ ≤ is_function η x f) (H : Γ ≤ pair a b ∈ᴮ induced_epsilon_rel η x f ) : Γ ≤ a ∈ᴮ image η x f := begin rw mem_image_iff, rw mem_induced_epsilon_rel_iff at H, rcases H with ⟨H₁,H₂,H₃⟩, refine ⟨‹_›, _⟩, bv_cases_at H₃ a' Ha', bv_split_at Ha', bv_cases_at Ha'_right b' Hb', bv_split_at Hb', bv_split_at Hb'_right, bv_split_at Hb'_right_left, apply bv_use a', from le_inf ‹_› ‹_›, from ‹_› end lemma induced_epsilon_rel_sub_image_right { η x f a b : bSet 𝔹 } { Γ } (H_func : Γ ≤ is_function η x f) (H : Γ ≤ pair a b ∈ᴮ induced_epsilon_rel η x f ) : Γ ≤ b ∈ᴮ image η x f := begin rw mem_image_iff, rw mem_induced_epsilon_rel_iff at H, rcases H with ⟨H₁,H₂,H₃⟩, refine ⟨‹_›, _⟩, bv_cases_at H₃ a' Ha', bv_split_at Ha', bv_cases_at Ha'_right b' Hb', bv_split_at Hb', bv_split_at Hb'_right, bv_split_at Hb'_right_left, apply bv_use b', from le_inf ‹_› ‹_›, from ‹_› end lemma image_eq_of_eq_induced_epsilon_rel_aux { η ρ f g : bSet 𝔹 } { Γ } (Hη_inj : Γ ≤ is_injective_function η omega f) (Hρ_inj : Γ ≤ is_injective_function ρ omega g) (H_eq : Γ ≤ induced_epsilon_rel η omega f =ᴮ induced_epsilon_rel ρ omega g) (H_exists_two : Γ ≤ exists_two η) : Γ ≤ ⨅ (z : bSet 𝔹), z ∈ᴮ image η omega f ⟹ z ∈ᴮ image ρ omega g := begin bv_intro z, bv_imp_intro Hz_mem, rw mem_image_iff at Hz_mem, cases Hz_mem with Hz_mem₁ Hz_mem₂, bv_cases_at Hz_mem₂ z' Hz', bv_split_at Hz', unfold exists_two at H_exists_two, replace H_exists_two := H_exists_two z' ‹_›, bv_cases_at H_exists_two w' Hw', bv_split_at Hw', bv_or_elim_at' Hw'_right, { let w := function_eval (bv_and.left Hη_inj) w' ‹_›, apply induced_epsilon_rel_sub_image_left, show bSet 𝔹, from w, from bv_and.left ‹_›, apply bv_rw' (bv_symm H_eq), { simp }, rw mem_induced_epsilon_rel_iff, refine ⟨‹_›, by { apply function_eval_mem_codomain }, _⟩, apply bv_use z', refine le_inf ‹_› _, apply bv_use w', refine le_inf ‹_› _, refine le_inf (le_inf ‹_› (by apply function_eval_pair_mem)) ‹_›, from bv_and.left ‹_› }, { let w := function_eval (bv_and.left Hη_inj) w' ‹_›, apply induced_epsilon_rel_sub_image_right, show bSet 𝔹, from w, from bv_and.left ‹_›, apply bv_rw' (bv_symm H_eq), { simp }, rw mem_induced_epsilon_rel_iff, refine ⟨ by { apply function_eval_mem_codomain }, ‹_›, _⟩, apply bv_use w', refine le_inf ‹_› _, apply bv_use z', refine le_inf ‹_› _, refine le_inf (le_inf (by apply function_eval_pair_mem) ‹_›) ‹_›, from bv_and.left ‹_› } end lemma image_eq_of_eq_induced_epsilon_rel { η ρ f g : bSet 𝔹 } { Γ } (Hη_inj : Γ ≤ is_injective_function η omega f) (Hρ_inj : Γ ≤ is_injective_function ρ omega g) (H_eq : Γ ≤ induced_epsilon_rel η omega f =ᴮ induced_epsilon_rel ρ omega g) (H_exists_two : Γ ≤ exists_two η) (H_exists_two' : Γ ≤ exists_two ρ) : Γ ≤ image η omega f =ᴮ image ρ omega g := by { refine mem_ext _ _; apply image_eq_of_eq_induced_epsilon_rel_aux; repeat { assumption }, from bv_symm ‹_› } lemma eq_of_eq_induced_epsilon_rel {η ρ f g : bSet 𝔹} {Γ} (Hη_ord : Γ ≤ Ord η) (Hρ_ord : Γ ≤ Ord ρ) (Hη_inj : Γ ≤ is_injective_function η omega f) (Hρ_inj : Γ ≤ is_injective_function ρ omega g) (H_eq : Γ ≤ induced_epsilon_rel η omega f =ᴮ induced_epsilon_rel ρ omega g) (H_exists_two : Γ ≤ exists_two η) (H_exists_two' : Γ ≤ exists_two ρ) : Γ ≤ η =ᴮ ρ := begin suffices : Γ ≤ ⨆ h, eps_iso η ρ h, by { exact eq_of_Ord_eps_iso Hη_ord Hρ_ord ‹_› }, refine bv_use (injective_function_comp (factor_image_is_injective_function Hη_inj) _), from ρ, from injective_function_inverse Hρ_inj, { apply @bv_rw' _ _ _ _ _ (image_eq_of_eq_induced_epsilon_rel Hη_inj Hρ_inj ‹_› ‹_› ‹_›) (λ z, is_injective_function z ρ (injective_function_inverse Hρ_inj)), simp, from injective_function_inverse_is_injective_function }, refine le_inf (le_inf _ _) _, { apply injective_function_comp_is_function }, { rw strong_eps_hom_iff, intros, apply_all le_trans H_le, refine ⟨_,_⟩; intro H_mem, { erw mem_is_func'_comp_iff at Hpr₁_mem, rcases Hpr₁_mem with ⟨_,_,Hv₁_ex⟩, erw mem_is_func'_comp_iff at Hpr₂_mem, rcases Hpr₂_mem with ⟨_,_,Hv₂_ex⟩, bv_cases_at Hv₁_ex v₁ Hv₁, bv_cases_at Hv₂_ex v₂ Hv₂, have v₁_mem_v₂ : Γ_2 ≤ pair v₁ v₂ ∈ᴮ induced_epsilon_rel η omega f, by { rw mem_induced_epsilon_rel_iff, refine ⟨_,_,_⟩, { refine mem_of_mem_subset _ (bv_and.left Hv₁), apply image_subset }, { refine mem_of_mem_subset _ (bv_and.left Hv₂), apply image_subset }, { apply bv_use z₁, refine le_inf ‹_› (bv_use z₂), refine le_inf ‹_› (le_inf (le_inf _ _) _), { bv_split, bv_split, from ‹_› }, { bv_split, bv_split, from ‹_› }, { from ‹_› } }, from bv_and.left ‹_› }, have Hpr₁_mem : Γ_2 ≤ pair w₁ v₁ ∈ᴮ g, by { bv_split_at Hv₁, bv_split_at Hv₁_right, erw mem_inj_inverse_iff at Hv₁_right_right, simp* }, have Hpr₂_mem : Γ_2 ≤ pair w₂ v₂ ∈ᴮ g, by { bv_split_at Hv₂, bv_split_at Hv₂_right, erw mem_inj_inverse_iff at Hv₂_right_right, simp* }, refine mem_of_mem_induced_epsilon_rel Hρ_inj_1 Hpr₁_mem Hpr₂_mem _, apply bv_rw' (bv_symm H_eq_1), simp, from ‹_› }, { erw mem_is_func'_comp_iff at Hpr₁_mem, rcases Hpr₁_mem with ⟨_,_,Hv₁_ex⟩, erw mem_is_func'_comp_iff at Hpr₂_mem, rcases Hpr₂_mem with ⟨_,_,Hv₂_ex⟩, bv_cases_at Hv₁_ex v₁ Hv₁, bv_cases_at Hv₂_ex v₂ Hv₂, have v₁_mem_v₂ : Γ_2 ≤ pair v₁ v₂ ∈ᴮ induced_epsilon_rel ρ omega g, by { rw mem_induced_epsilon_rel_iff, refine ⟨_,_,_⟩, { refine mem_of_mem_subset _ (bv_and.left Hv₁), apply image_subset }, { refine mem_of_mem_subset _ (bv_and.left Hv₂), apply image_subset }, { apply bv_use w₁, refine le_inf ‹_› (bv_use w₂), refine le_inf ‹_› (le_inf (le_inf _ _) _), { bv_split_at Hv₁, bv_split_at Hv₁_right, erw mem_inj_inverse_iff at Hv₁_right_right, simp* }, { bv_split_at Hv₂, bv_split_at Hv₂_right, erw mem_inj_inverse_iff at Hv₂_right_right, simp* }, { from ‹_› } }, from bv_and.left ‹_› }, have Hpr₁_mem : Γ_2 ≤ pair z₁ v₁ ∈ᴮ f, by bv_split; bv_split; from ‹_›, have Hpr₂_mem : Γ_2 ≤ pair z₂ v₂ ∈ᴮ f, by bv_split; bv_split; from ‹_›, refine mem_of_mem_induced_epsilon_rel Hη_inj_1 Hpr₁_mem Hpr₂_mem _, apply bv_rw' H_eq_1, simp, from ‹_› }, }, {apply is_func'_comp_surj, { from bv_and.right ‹_› }, { apply injective_function_inverse_is_inj }, { exact surj_image (is_func'_of_is_injective_function Hη_inj) }, { change _ ≤ (λ z, is_surj z ρ (injective_function_inverse Hρ_inj)) _, apply bv_rw' (image_eq_of_eq_induced_epsilon_rel Hη_inj Hρ_inj ‹_› ‹_› ‹_›), simp, apply inj_inverse.is_surj }} end end well_ordering section a1 parameters {𝔹 : Type u} [nontrivial_complete_boolean_algebra 𝔹] def a1.ϕ : bSet 𝔹 → 𝔹 := λ x, (⨆η, Ord η ⊓ ⨆ f, is_injective_function η omega f ⊓ (image (mem_rel η) (prod omega omega) (prod.map_self η omega f) =ᴮ x) ⊓ (- (x =ᴮ ∅)) ) @[simp]lemma B_ext_a1.ϕ : B_ext a1.ϕ := by simp [a1.ϕ] def a1' : bSet 𝔹 := comprehend a1.ϕ (bv_powerset $ prod omega omega) def a1.type := a1'.type def a1.bval := a1'.bval def a1.ψ (v : bSet 𝔹) : bSet 𝔹 → 𝔹 := λ x, (Ord x ⊓ ⨆ f, is_injective_function x omega f ⊓ image (mem_rel x) (prod omega omega) (prod.map_self x omega f) =ᴮ v ⊓ (- (v =ᴮ ∅))) @[simp]lemma B_ext_a1.ψ {v : bSet 𝔹} : B_ext (a1.ψ v) := by { unfold a1.ψ, apply B_ext_inf, simp, apply B_ext_supr, intro i, apply B_ext_inf, swap, simp, apply B_ext_inf, simp, intros x y, tidy_context, refine bv_symm _, refine bv_trans (bv_symm a_right) _, have : Γ ≤ mem_rel x =ᴮ mem_rel y, by { exact B_congr_mem_rel ‹_› }, have := B_congr_image_left this, show bSet 𝔹, from prod omega omega, show bSet 𝔹, from (prod.map_self x omega i), dsimp at this, have : Γ ≤ (prod.map_self x omega i) =ᴮ (prod.map_self y omega i), by { exact B_congr_prod.map_self_left ‹_› }, have := B_congr_image_right this, show bSet 𝔹, from (mem_rel y), show bSet 𝔹, from (prod omega omega), dsimp at this, bv_cc } lemma a1'.AE {Γ : 𝔹} : Γ ≤ ⨅ z, z ∈ᴮ a1' ⟹ ⨆ η, Ord η ⊓ ⨆ f, is_injective_function η omega f ⊓ image (mem_rel η) (prod omega omega) (prod.map_self η omega f) =ᴮ z ⊓ (- (z =ᴮ ∅)) := begin bv_intro z, bv_imp_intro Hz_mem, erw mem_comprehend_iff at Hz_mem, bv_cases_at Hz_mem χ Hχ, bv_split_at Hχ, bv_split_at Hχ_right, apply bv_rw' Hχ_right_left, simp, convert Hχ_right_right, from (bv_powerset $ prod omega omega), simp end noncomputable def a1.func : a1.type → bSet 𝔹 := λ χ, classical.some (AE_convert' (a1.ψ) (λ z, B_ext_a1.ψ) a1' (a1'.func χ)) lemma a1.func_spec_aux {χ : a1.type} : ∀ {Γ : 𝔹}, (Γ ≤ ⨅ z, z ∈ᴮ a1' ⟹ ⨆ w, a1.ψ z w) → Γ ≤ (a1'.func χ) ∈ᴮ a1' → Γ ≤ a1.ψ (a1'.func χ) (a1.func χ) := by {intro Γ, exact classical.some_spec (a1.func._proof_1 χ)} lemma a1.func_spec {χ : a1.type} : ∀ {Γ : 𝔹}, Γ ≤ (a1'.func χ) ∈ᴮ a1' → Γ ≤ a1.ψ (a1'.func χ) (a1.func χ) := by { intros Γ H_mem, apply a1.func_spec_aux, exact a1'.AE, from ‹_› } -- equality of pushforward epsilon relation is not enough to guarantee 0 or 1 are in a1, -- since injectivity fails at 0 and 1 (both epsilon relations are empty) noncomputable def a1_aux : bSet 𝔹 := ⟨a1.type, a1.func, a1.bval⟩ lemma Ord_of_mem_a1_aux {Γ : 𝔹} {η : bSet 𝔹} (H_mem : Γ ≤ η ∈ᴮ a1_aux) : Γ ≤ Ord η := begin rw mem_unfold at H_mem, bv_cases_at H_mem χ Hχ, bv_split_at Hχ, have : Γ_1 ≤ a1'.func χ ∈ᴮ a1', by { convert mem.mk'' _, from ‹_› }, have := a1.func_spec this, bv_split_at this, apply bv_rw' Hχ_right, simp, from ‹_› end noncomputable def a1 : bSet 𝔹 := insert 0 (insert 1 a1_aux) lemma mem_a1_iff₀ { z : bSet 𝔹 } { Γ } : Γ ≤ z ∈ᴮ a1 ↔ Γ ≤ z =ᴮ 0 ⊔ z =ᴮ 1 ⊔ z ∈ᴮ a1_aux := by { simp [a1, sup_assoc] } lemma Ord_of_mem_a1 { Γ : 𝔹 } { η : bSet 𝔹 } (H_mem : Γ ≤ η ∈ᴮ a1) : Γ ≤ Ord η := begin rw mem_a1_iff₀ at H_mem, bv_or_elim_at H_mem, { bv_or_elim_at H_mem.left, { apply bv_rw' H_mem.left.left, simp, from Ord_zero }, { apply bv_rw' H_mem.left.right, simp, from Ord_one }}, { from Ord_of_mem_a1_aux ‹_› } end lemma eq_zero_iff_eq_empty {Γ : 𝔹} { u : bSet 𝔹 } : Γ ≤ u =ᴮ 0 ↔ Γ ≤ u =ᴮ ∅ := begin refine ⟨_,_⟩; intro H, { apply bv_rw' (bv_symm zero_eq_empty), simp, from ‹_› }, { apply bv_rw' zero_eq_empty, simp, from ‹_› } end lemma induced_rel_empty_of_eq_zero {η f : bSet 𝔹} {Γ : 𝔹} (H_func : Γ ≤ is_function η omega f) : Γ ≤ η =ᴮ 0 → Γ ≤ induced_epsilon_rel η omega f =ᴮ ∅ := begin intro H_eq_zero, apply bv_by_contra, bv_imp_intro H_contra, rw nonempty_iff_exists_mem at H_contra, bv_cases_at H_contra pr Hpr, rcases (eq_pair_of_mem_induced_epsilon_rel ‹_›) with ⟨a,b,Ha_mem,Hb_mem,H_eq,Hab⟩, replace Hab := induced_epsilon_rel_sub_image_left ‹_› Hab, rw mem_image_iff at Hab, cases Hab with _ H_im, bv_cases_at H_im z Hz, bv_split_at Hz, rw eq_zero_iff_eq_empty at H_eq_zero, rw empty_iff_forall_not_mem at H_eq_zero, replace H_eq_zero := H_eq_zero z, exact bv_absurd _ Hz_left ‹_› end lemma nonempty_of_induced_rel_nonempty {η f : bSet 𝔹} {Γ : 𝔹} (H_func : Γ ≤ is_function η omega f) : Γ ≤ -(induced_epsilon_rel η omega f =ᴮ ∅) → Γ ≤ -(η =ᴮ ∅) := begin intro H, rw ←imp_bot, bv_imp_intro H', rw ← eq_zero_iff_eq_empty at H', have := induced_rel_empty_of_eq_zero ‹_› ‹_›, bv_contradiction end lemma not_zero_of_induced_rel_nonempty {η f : bSet 𝔹} {Γ : 𝔹} (H_func : Γ ≤ is_function η omega f) : Γ ≤ -(induced_epsilon_rel η omega f =ᴮ ∅) → Γ ≤ -(η =ᴮ 0) := begin intro H', apply @bv_rw' _ _ _ _ _ (zero_eq_empty) (λ w, - (η =ᴮ w)), {simp}, exact nonempty_of_induced_rel_nonempty ‹_› ‹_› end lemma not_one_of_induced_rel_nonempty {η f : bSet 𝔹} {Γ : 𝔹} (H_func : Γ ≤ is_function η omega f) : Γ ≤ -(induced_epsilon_rel η omega f =ᴮ ∅) → Γ ≤ -(η =ᴮ 1) := begin intro H, rw nonempty_iff_exists_mem at H, bv_cases_at H pr Hpr, rcases eq_pair_of_mem_induced_epsilon_rel Hpr with ⟨a,b,Ha,Hb,H_eq,Hab⟩, rw mem_induced_epsilon_rel_iff at Hab, rcases Hab with ⟨Ha, Hb, Hab⟩, bv_cases_at' Hab a' Ha', bv_split_at Ha', bv_cases_at' Ha'_right b' Hb', bv_split_at Hb', bv_split_at Hb'_right, bv_split_at Hb'_right_left, rw ←imp_bot, bv_imp_intro' H_eq_one, suffices : Γ_4 ≤ 0 ∈ᴮ 0, by { exact bot_of_mem_self' ‹_› }, suffices : Γ_4 ≤ a' =ᴮ 0 ∧ Γ_4 ≤ b' =ᴮ 0, by { change _ ≤ (λ (w : bSet 𝔹), w ∈ᴮ 0) 0, apply bv_rw' (bv_symm this.left), simp, change _ ≤ (λ w, a' ∈ᴮ w) _, apply bv_rw' (bv_symm this.right), simpa }, refine ⟨_,_⟩, { apply eq_zero_of_mem_one, have := mem_domain_of_is_function ‹Γ_4 ≤ pair a' a ∈ᴮ f› ‹_›, bv_cc }, { apply eq_zero_of_mem_one, have := mem_domain_of_is_function ‹Γ_4 ≤ pair b' b ∈ᴮ f› ‹_›, bv_cc }, from ‹_› end lemma nonempty_induced_rel_iff_not_zero_and_not_one {η f : bSet 𝔹} {Γ : 𝔹} (H_ord : Γ ≤ Ord η) (H_inj : Γ ≤ is_function η omega f) : Γ ≤ -((induced_epsilon_rel η omega f) =ᴮ ∅) ↔ (Γ ≤ -(η =ᴮ 0) ∧ Γ ≤ -(η =ᴮ 1)) := begin refine ⟨_,_⟩; intro H, { refine ⟨_,_⟩, { exact not_zero_of_induced_rel_nonempty ‹_› ‹_› }, { exact not_one_of_induced_rel_nonempty ‹_› ‹_› }}, { cases H with H₁ H₂, rw nonempty_iff_exists_mem, have := one_mem_of_not_zero_and_not_one ‹_› H₁ H₂, have Hmem_one : Γ ≤ _ := zero_mem_one, have H_zero_mem : Γ ≤ 0 ∈ᴮ η, by { exact mem_of_mem_Ord ‹_› ‹_ ≤ 1 ∈ᴮ η› ‹_›}, refine bv_use _, swap, apply mem_induced_epsilon_rel_of_mem H_zero_mem this ‹_›, from ‹_› } end /-- a1 contains every ordinal η which injects into ω -/ lemma mem_a1_of_injects_into_omega_aux {Γ : 𝔹} {η : bSet 𝔹} (H_ord : Γ ≤ Ord η) (H_inj : Γ ≤ ⨆ f, is_injective_function η omega f) (H_not_zero : Γ ≤ - (η =ᴮ 0)) (H_not_one : Γ ≤ -(η =ᴮ 1)) : Γ ≤ η ∈ᴮ a1_aux := begin bv_cases_at H_inj f Hf, rw mem_unfold', let R := (induced_epsilon_rel η omega f), have : Γ_1 ≤ R ∈ᴮ a1', by { erw mem_comprehend_iff₂, apply bv_use R, refine le_inf _ (le_inf bv_refl _), { rw mem_powerset_iff, apply subset.mk_subset }, { apply bv_use η, refine le_inf ‹_› _, apply bv_use f, refine le_inf (le_inf ‹_› bv_refl) _, erw nonempty_induced_rel_iff_not_zero_and_not_one, simp*, from ‹_›, from bv_and.left ‹_› }, simp }, rw mem_unfold at this, bv_cases_at this χ Hχ, apply bv_use (a1.func χ), bv_split_at Hχ, refine le_inf _ _, convert mem.mk'' _, refl, from ‹_›, have H_mem : Γ_2 ≤ (a1'.func χ) ∈ᴮ a1', from mem.mk'' ‹_›, have := a1.func_spec H_mem, bv_split_at this, bv_cases_at this_right g Hg, bv_split_at Hg, bv_split_at Hg_left, apply eq_of_eq_induced_epsilon_rel, from ‹_›, {apply Ord_of_mem_a1_aux, convert mem.mk'' _, refl, from ‹_›}, from Hf, from Hg_left_left, { dsimp [R] at Hχ_right,change _ ≤ induced_epsilon_rel _ _ _ =ᴮ _ at Hg_left_right, bv_cc }, { rw exists_two_iff; from ‹_› }, rw exists_two_iff, suffices : Γ_3 ≤ -(image (mem_rel (a1.func χ)) (prod omega omega) (prod.map_self (a1.func χ) omega g) =ᴮ ∅), by { erw nonempty_induced_rel_iff_not_zero_and_not_one at this, cases this with this₁ this₂, from ‹_›, from ‹_›, from bv_and.left ‹_› }, apply @bv_rw' _ _ _ _ _ Hg_left_right (λ w, -(w =ᴮ ∅)), simp, from ‹_›, from ‹_› end lemma mem_a1_iff {Γ : 𝔹} {η : bSet 𝔹} (H_ord : Γ ≤ Ord η) : Γ ≤ η ∈ᴮ a1 ↔ Γ ≤ ⨆f, is_injective_function η omega f := begin refine ⟨_,_⟩, { intro H_mem, rw mem_a1_iff₀ at H_mem, bv_or_elim_at H_mem, bv_or_elim_at H_mem.left, { apply injection_into_of_injects_into, apply injects_into_of_subset, apply bv_rw' H_mem.left.left, simp, apply of_nat_subset_omega }, { apply injection_into_of_injects_into, apply injects_into_of_subset, apply bv_rw' H_mem.left.right, simp, apply of_nat_subset_omega }, { rw mem_unfold at H_mem.right, bv_cases_at H_mem.right χ Hχ, bv_split_at Hχ, have : Γ_2 ≤ a1'.func χ ∈ᴮ a1', by { from mem.mk'' ‹_› }, have := a1.func_spec this, apply bv_rw' Hχ_right, simp, bv_split_at this, bv_cases_at this_right f Hf, apply bv_use f, exact bv_and.left (bv_and.left ‹_›) }}, { intro H_ex, rw mem_a1_iff₀, bv_cases_on η =ᴮ 1, { exact bv_or_left (bv_or_right ‹_›) }, { bv_cases_on η =ᴮ 0, { exact bv_or_left (bv_or_left ‹_›) }, { refine bv_or_right _, apply mem_a1_of_injects_into_omega_aux, repeat { assumption }}}} end lemma a1_transitive {Γ} : Γ ≤ is_transitive a1 := begin bv_intro z, bv_imp_intro Hz_mem, rw subset_unfold', bv_intro w, bv_imp_intro Hw_mem, rw mem_a1_iff _, swap, { refine Ord_of_mem_Ord Hw_mem _, from Ord_of_mem_a1 ‹_› }, { have Hz_ord : Γ_2 ≤ Ord z := Ord_of_mem_a1 ‹_›, rw (mem_a1_iff ‹_›) at Hz_mem, cases (exists_convert Hz_mem) with f Hf, have Hw_sub : Γ_2 ≤ w ⊆ᴮ z, by {apply subset_of_mem_transitive, from bv_and.right ‹_›, from ‹_› }, have Hw_inj : Γ_2 ≤ injection_into w z := injection_into_of_subset Hw_sub, cases (exists_convert Hw_inj) with g Hg, apply bv_use (injective_function_comp Hg Hf), apply injective_function_comp_is_injective_function } end lemma a1_ewo {Γ} : Γ ≤ ewo a1 := begin refine le_inf _ _, { apply epsilon_trichotomy_of_sub_Ord, bv_intro x, bv_imp_intro H_mem, from Ord_of_mem_a1 ‹_› }, { apply epsilon_wf_of_sub_Ord } end lemma a1_Ord {Γ : 𝔹} : Γ ≤ Ord a1 := le_inf a1_ewo a1_transitive lemma a1_not_le_omega {Γ : 𝔹} : Γ ≤ -(a1 ≼ omega) := begin rw ←imp_bot, bv_imp_intro H_contra, rw injects_into_iff_injection_into at H_contra, erw ←mem_a1_iff (a1_Ord) at H_contra, from bot_of_mem_self' ‹_› end lemma a1_spec {Γ : 𝔹} : Γ ≤ aleph_one_Ord_spec a1 := begin refine le_inf (a1_not_le_omega) _, refine le_inf a1_Ord _, bv_intro η, bv_imp_intro Ord_η, bv_imp_intro H, classical, by_cases ⊥ < Γ_2, { rw (Ord.le_iff_lt_or_eq a1_Ord ‹_›), apply bv_by_contra, bv_imp_intro H_contra, simp only [le_inf_iff] with bv_push_neg at H_contra, cases H_contra with H_contra₁ H_contra₂, suffices : Γ_3 ≤ injects_into η omega, by exact bv_absurd _ this ‹_›, suffices : Γ_3 ≤ η ∈ᴮ a1, by {replace this := (mem_a1_iff ‹_›).mp this, bv_cases_at this f Hf, apply bv_use f, from le_inf (is_func'_of_is_injective_function ‹_›) (bv_and.right ‹_›) }, have : Γ_3 ≤ _ := Ord.trichotomy a1_Ord Ord_η, apply bv_by_contra, bv_imp_intro H_contra₃, bv_or_elim_at this, { bv_or_elim_at this.left, { bv_contradiction }, { bv_contradiction }}, { bv_contradiction } }, { have : Γ_2 ≤ ⊥ := le_bot_iff_not_bot_lt.mp h, from le_trans this bot_le } end lemma a1_le_of_omega_lt {Γ : 𝔹} : Γ ≤ le_of_omega_lt a1 := begin bv_intro x, bv_imp_intro H_Ord, bv_imp_intro H_no_surj, have H_no_inj : Γ_2 ≤ -(injects_into x omega), by { rw ←imp_bot, bv_imp_intro H_contra, refine bv_absurd _ _ H_no_surj, bv_cases_on x =ᴮ ∅, { apply bv_use (∅ : bSet 𝔹), apply bv_use (∅ : bSet 𝔹), refine le_inf _ _, refine le_inf empty_subset _, exact is_func'_empty, apply bv_rw' H.left, simp, apply is_surj_empty }, { apply larger_than_of_surjects_onto, refine surjects_onto_of_injects_into ‹_› _, rwa ←nonempty_iff_exists_mem } }, have H_not_mem_a1 : Γ_2 ≤ -(x ∈ᴮ a1), by { rw ←imp_bot, bv_imp_intro H_contra, rw mem_a1_iff ‹_›at H_contra, have := injects_into_of_injection_into H_contra, bv_contradiction }, refine injects_into_of_subset _, rw Ord.le_iff_lt_or_eq (a1_Ord) ‹_›, have := Ord.trichotomy (a1_Ord) ‹_›, bv_or_elim_at this, bv_or_elim_at this.left, { from bv_or_right ‹_› }, { from bv_or_left ‹_› }, { from bv_exfalso (by bv_contradiction) } end end a1 section variables {𝔹 : Type u} [nontrivial_complete_boolean_algebra 𝔹] lemma injects_into_omega_of_mem_aleph_one_check {Γ : 𝔹} {z : bSet 𝔹} (H_mem : Γ ≤ z ∈ᴮ (ℵ₁)̌ ): Γ ≤ injects_into z bSet.omega := begin rw mem_unfold at H_mem, bv_cases_at H_mem η Hη, simp at Hη, suffices : Γ_1 ≤ injects_into (ℵ₁̌.func η) bSet.omega, apply bv_rw' Hη, simp, from ‹_›, suffices : pSet.injects_into ((ℵ₁).func $ check_cast η) pSet.omega, by {rw check_func, apply check_injects_into, from ‹_› }, refine pSet.injects_into_omega_of_mem_aleph_one _, { simp } end lemma mem_aleph_one_of_injects_into_omega {x : bSet 𝔹} {Γ : 𝔹} (H_aleph_one : Γ ≤ aleph_one_Ord_spec x) {z : bSet 𝔹} (H_x_Ord : Γ ≤ Ord x) (H_z_Ord : Γ ≤ Ord z) (H_inj : Γ ≤ injects_into z bSet.omega) : Γ ≤ z ∈ᴮ x := begin apply bv_by_contra, bv_imp_intro H_contra, have := Ord.resolve_lt H_z_Ord H_x_Ord H_contra, rw ← Ord.le_iff_lt_or_eq H_x_Ord H_z_Ord at this, suffices H_inj_omega : Γ_1 ≤ injects_into x omega, by {refine bv_absurd _ H_inj_omega _, from bv_and.left ‹_› }, exact injects_into_trans (injects_into_of_subset this) (H_inj) end lemma aleph_one_check_sub_aleph_one_aux {x : bSet 𝔹} {Γ : 𝔹} (H_ord : Γ ≤ Ord x) (H_aleph_one : Γ ≤ aleph_one_Ord_spec x) : Γ ≤ ℵ₁̌ ⊆ᴮ x := begin rw subset_unfold', bv_intro w, bv_imp_intro H_mem_w, apply mem_aleph_one_of_injects_into_omega, from ‹_›, from ‹_›, exact Ord_of_mem_Ord H_mem_w (check_Ord (by {unfold pSet.aleph_one pSet.card_ex, simp })), exact injects_into_omega_of_mem_aleph_one_check ‹_› end end end bSet
00b91897932c0bee501265795e2caaa222f4b3f4
b73bd2854495d87ad5ce4f247cfcd6faa7e71c7e
/src/game/world2/level2.lean
ebb660199c43aaf91b2d8d246adb326e00e85faa
[]
no_license
agusakov/category-theory-game
20db0b26270e0c95a3d5605498570273d72f731d
652dd7e90ae706643b2a597e2c938403653e167d
refs/heads/master
1,669,201,216,310
1,595,740,057,000
1,595,740,057,000
280,895,295
12
0
null
null
null
null
UTF-8
Lean
false
false
948
lean
import category_theory.category.default import category_theory.isomorphism universes v u -- The order in this declaration matters: v often needs to be explicitly specified while u often can be omitted namespace category_theory variables (C : Type u) [category.{v} C] --rewrite this /- # Category world ## Level 1: Isomorphisms An isomorphism `f : X ⟶ Y` is a morphism for which there exists a morphism `g : Y ⟶ X`, such that `f ≫ g = 𝟙 X` and `g ≫ f = 𝟙 Y`. -/ /- Lemma If $$f : X ⟶ Y$$ and $$g : X ⟶ Y$$ are morphisms such that $$f = g$$, then $$f ≫ h = g ≫ h$$. -/ lemma cancel_right_iso' {X Y Z : C} (f : X ⟶ Y) [is_iso f] {g h : Y ⟶ Z} : (f ≫ g = f ≫ h) ↔ g = h := begin split, intro hyp, rw ← category.id_comp g, rw ← category.id_comp h, rw ← is_iso.inv_hom_id f, rw category.assoc, rw hyp, rw category.assoc, intro hyp, rw hyp, end end category_theory
2bf74b6f8bc4ebae864cd408cda7df08a1aa0304
957a80ea22c5abb4f4670b250d55534d9db99108
/tests/lean/interactive/my_tac_class.lean
c4c9a9bb3dfc576f212c1078104ad35739be3bdc
[ "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,779
lean
meta def mytac := state_t nat tactic meta instance : monad mytac := state_t.monad _ _ meta instance : monad.has_monad_lift tactic mytac := monad.monad_transformer_lift (state_t nat) tactic meta instance (α : Type) : has_coe (tactic α) (mytac α) := ⟨monad.monad_lift⟩ namespace mytac meta def step {α : Type} (t : mytac α) : mytac unit := t >> return () meta def istep {α : Type} (line0 col0 line col : nat) (t : mytac α) : mytac unit := λ v s, result.cases_on (@scope_trace _ line col (λ_, t 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 "value: " ++ to_fmt v ++ format.line ++ to_fmt "state:" ++ format.line ++ new_s^.to_format in interaction_monad.result.exception (some msg) (some ⟨line, col⟩) new_s | none := interaction_monad.silent_fail new_s end) meta def execute (tac : mytac unit) : tactic unit := tac 0 >> return () meta def save_info (p : pos) : mytac unit := do v ← state_t.read, s ← tactic.read, tactic.save_info_thunk p (λ _, to_fmt "Custom state: " ++ to_fmt v ++ format.line ++ tactic_state.to_format s) namespace interactive meta def intros : mytac unit := tactic.intros >> return () meta def constructor : mytac unit := tactic.constructor meta def trace (s : string) : mytac unit := tactic.trace s meta def assumption : mytac unit := tactic.assumption meta def inc : mytac unit := do v ← state_t.read, state_t.write (v+1) end interactive end mytac example (p q : Prop) : p → q → p ∧ q := begin [mytac] intros, inc, trace "test", constructor, inc, assumption, --^ "command": "info" assumption end
e8ec9d7861ea3c4b2d6bfda15bddc92afe45639e
2a70b774d16dbdf5a533432ee0ebab6838df0948
/_target/deps/mathlib/src/data/buffer/basic.lean
21ee942fc3d0f2a7dbf4ca45d8613cd174a0c5d5
[ "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
2,220
lean
/- Copyright (c) 2018 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Simon Hudon General utility functions for buffers. -/ import data.buffer import data.array.lemmas import control.traversable.instances namespace buffer open function variables {α : Type*} {xs : list α} instance : inhabited (buffer α) := ⟨nil⟩ @[ext] lemma ext : ∀ {b₁ b₂ : buffer α}, to_list b₁ = to_list b₂ → b₁ = b₂ | ⟨n₁, a₁⟩ ⟨n₂, a₂⟩ h := begin simp [to_list, to_array] at h, have e : n₁ = n₂ := by rw [←array.to_list_length a₁, ←array.to_list_length a₂, h], subst e, have h : a₁ == a₂.to_list.to_array := h ▸ a₁.to_list_to_array.symm, rw eq_of_heq (h.trans a₂.to_list_to_array) end instance (α) [decidable_eq α] : decidable_eq (buffer α) := by tactic.mk_dec_eq_instance @[simp] lemma to_list_append_list {b : buffer α} : to_list (append_list b xs) = to_list b ++ xs := by induction xs generalizing b; simp! [*]; cases b; simp! [to_list,to_array] @[simp] lemma append_list_mk_buffer : append_list mk_buffer xs = array.to_buffer (list.to_array xs) := by ext x : 1; simp [array.to_buffer,to_list,to_list_append_list]; induction xs; [refl,skip]; simp [to_array]; refl /-- The natural equivalence between lists and buffers, using `list.to_buffer` and `buffer.to_list`. -/ def list_equiv_buffer (α : Type*) : list α ≃ buffer α := begin refine { to_fun := list.to_buffer, inv_fun := buffer.to_list, .. }; simp [left_inverse,function.right_inverse], { intro x, induction x, refl, simp [list.to_buffer,append_list], rw ← x_ih, refl }, { intro x, cases x, simp [to_list,to_array,list.to_buffer], congr, simp, refl, apply array.to_list_to_array } end instance : traversable buffer := equiv.traversable list_equiv_buffer instance : is_lawful_traversable buffer := equiv.is_lawful_traversable list_equiv_buffer /-- A convenience wrapper around `read` that just fails if the index is out of bounds. -/ meta def read_t (b : buffer α) (i : ℕ) : tactic α := if h : i < b.size then return $ b.read (fin.mk i h) else tactic.fail "invalid buffer access" end buffer
93a3428abb263b415d3a3386a18de01e5068c1b0
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/autoPPExplicit.lean
7bbe4a9eb2f35ac605d6979d8757a65e70b5c258
[ "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
63
lean
def f {a b c : α} : a = c := Eq.trans (a := a) (b := b = c)
9d9588d10e7449c4dc0ae5d33146600e98a0ad5e
2a70b774d16dbdf5a533432ee0ebab6838df0948
/_target/deps/mathlib/src/data/int/parity.lean
4430f8e9541322db624d3c2533cbbb3ac088098a
[ "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
4,822
lean
/- Copyright (c) 2019 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Benjamin Davidson The `even` and `odd` predicates on the integers. -/ import data.int.modeq import data.nat.parity namespace int @[simp] theorem mod_two_ne_one {n : ℤ} : ¬ n % 2 = 1 ↔ n % 2 = 0 := by cases mod_two_eq_zero_or_one n with h h; simp [h] local attribute [simp] -- euclidean_domain.mod_eq_zero uses (2 ∣ n) as normal form theorem mod_two_ne_zero {n : ℤ} : ¬ n % 2 = 0 ↔ n % 2 = 1 := by cases mod_two_eq_zero_or_one n with h h; simp [h] @[simp] theorem even_coe_nat (n : nat) : even (n : ℤ) ↔ even n := have ∀ m, 2 * to_nat m = to_nat (2 * m), from λ m, by cases m; refl, ⟨λ ⟨m, hm⟩, ⟨to_nat m, by rw [this, ←to_nat_coe_nat n, hm]⟩, λ ⟨m, hm⟩, ⟨m, by simp [hm]⟩⟩ theorem even_iff {n : ℤ} : even n ↔ n % 2 = 0 := ⟨λ ⟨m, hm⟩, by simp [hm], λ h, ⟨n / 2, (mod_add_div n 2).symm.trans (by simp [h])⟩⟩ theorem odd_iff {n : ℤ} : odd n ↔ n % 2 = 1 := ⟨λ ⟨m, hm⟩, by { rw [hm, add_mod], norm_num }, λ h, ⟨n / 2, (mod_add_div n 2).symm.trans (by { rw h, abel })⟩⟩ lemma not_even_iff {n : ℤ} : ¬ even n ↔ n % 2 = 1 := by rw [even_iff, mod_two_ne_zero] lemma not_odd_iff {n : ℤ} : ¬ odd n ↔ n % 2 = 0 := by rw [odd_iff, mod_two_ne_one] lemma even_iff_not_odd {n : ℤ} : even n ↔ ¬ odd n := by rw [not_odd_iff, even_iff] @[simp] lemma odd_iff_not_even {n : ℤ} : odd n ↔ ¬ even n := by rw [not_even_iff, odd_iff] lemma even_or_odd (n : ℤ) : even n ∨ odd n := or.imp_right (odd_iff_not_even.2) (em (even n)) lemma even_or_odd' (n : ℤ) : ∃ k, n = 2 * k ∨ n = 2 * k + 1 := by simpa only [exists_or_distrib, ← odd, ← even] using even_or_odd n lemma even_xor_odd (n : ℤ) : xor (even n) (odd n) := begin cases (even_or_odd n) with h, { exact or.inl ⟨h, (even_iff_not_odd.mp h)⟩ }, { exact or.inr ⟨h, (odd_iff_not_even.mp h)⟩ }, end lemma even_xor_odd' (n : ℤ) : ∃ k, xor (n = 2 * k) (n = 2 * k + 1) := begin rcases (even_or_odd n) with ⟨k, h⟩ | ⟨k, h⟩; use k, { simpa only [xor, h, true_and, eq_self_iff_true, not_true, or_false, and_false] using (succ_ne_self (2*k)).symm }, { simp only [xor, h, add_right_eq_self, false_or, eq_self_iff_true, not_true, not_false_iff, one_ne_zero, and_self] }, end lemma ne_of_odd_sum {x y : ℤ} (h : odd (x + y)) : x ≠ y := by { rw odd_iff_not_even at h, intros contra, apply h, exact ⟨x, by rw [contra, two_mul]⟩, } @[simp] theorem two_dvd_ne_zero {n : ℤ} : ¬ 2 ∣ n ↔ n % 2 = 1 := not_even_iff instance : decidable_pred (even : ℤ → Prop) := λ n, decidable_of_decidable_of_iff (by apply_instance) even_iff.symm instance decidable_pred_odd : decidable_pred (odd : ℤ → Prop) := λ n, decidable_of_decidable_of_iff (by apply_instance) odd_iff_not_even.symm @[simp] theorem even_zero : even (0 : ℤ) := ⟨0, dec_trivial⟩ @[simp] theorem not_even_one : ¬ even (1 : ℤ) := by rw even_iff; apply one_ne_zero @[simp] theorem even_bit0 (n : ℤ) : even (bit0 n) := ⟨n, by rw [bit0, two_mul]⟩ @[parity_simps] theorem even_add {m n : ℤ} : even (m + n) ↔ (even m ↔ even n) := begin cases mod_two_eq_zero_or_one m with h₁ h₁; cases mod_two_eq_zero_or_one n with h₂ h₂; simp [even_iff, h₁, h₂, -euclidean_domain.mod_eq_zero], { exact @modeq.modeq_add _ _ 0 _ 0 h₁ h₂ }, { exact @modeq.modeq_add _ _ 0 _ 1 h₁ h₂ }, { exact @modeq.modeq_add _ _ 1 _ 0 h₁ h₂ }, exact @modeq.modeq_add _ _ 1 _ 1 h₁ h₂ end @[parity_simps] theorem even_neg {n : ℤ} : even (-n) ↔ even n := by simp [even_iff] @[simp] theorem not_even_bit1 (n : ℤ) : ¬ even (bit1 n) := by simp [bit1] with parity_simps @[parity_simps] theorem even_sub {m n : ℤ} : even (m - n) ↔ (even m ↔ even n) := by simp [sub_eq_add_neg] with parity_simps @[parity_simps] theorem even_mul {m n : ℤ} : even (m * n) ↔ even m ∨ even n := begin cases mod_two_eq_zero_or_one m with h₁ h₁; cases mod_two_eq_zero_or_one n with h₂ h₂; simp [even_iff, h₁, h₂, -euclidean_domain.mod_eq_zero], { exact @modeq.modeq_mul _ _ 0 _ 0 h₁ h₂ }, { exact @modeq.modeq_mul _ _ 0 _ 1 h₁ h₂ }, { exact @modeq.modeq_mul _ _ 1 _ 0 h₁ h₂ }, exact @modeq.modeq_mul _ _ 1 _ 1 h₁ h₂ end @[parity_simps] theorem even_pow {m : ℤ} {n : ℕ} : even (m^n) ↔ even m ∧ n ≠ 0 := by { induction n with n ih; simp [*, even_mul, pow_succ], tauto } -- Here are examples of how `parity_simps` can be used with `int`. example (m n : ℤ) (h : even m) : ¬ even (n + 3) ↔ even (m^2 + m + n) := by simp [*, (dec_trivial : ¬ 2 = 0)] with parity_simps example : ¬ even (25394535 : ℤ) := by simp end int
0bb5fcb56f8d7370e51efb9f4b89fb967a627afe
14d3c04048fcbea3818a26103a6e4f1c99fc6c62
/src/basic.lean
1666a6fcb565d5af8e25c81c366eff100c2dbb40
[]
no_license
gihanmarasingha/myint
866a880ae7ade3de7d1e8550e6d2c4be94f1b85f
eba85880a500a7977cc4e23c9fa51877dfc82b58
refs/heads/master
1,682,793,960,074
1,619,541,459,000
1,619,541,459,000
360,702,700
0
0
null
null
null
null
UTF-8
Lean
false
false
4,516
lean
import tactic @[derive decidable_rel] protected def myintrel : ℕ × ℕ → ℕ × ℕ → Prop := λ a b, a.1 + b.2 = b.1 + a.2 local infix `~` := myintrel protected theorem myintrel.refl : ∀ n : ℕ × ℕ, n ~ n := λ n, rfl protected theorem myintrel.symm : ∀ n m : ℕ × ℕ, n ~ m → m ~ n := λ n m h, by { dsimp [myintrel] at *, symmetry, rw h, } protected theorem myintrel.trans : ∀ n m k : ℕ × ℕ, n ~ m → m ~ k → n ~ k := by { dsimp [myintrel], intros n m k h₁ h₂, linarith, } protected theorem is_equivalence : equivalence myintrel := mk_equivalence myintrel myintrel.refl myintrel.symm myintrel.trans instance myint.setoid : setoid (ℕ × ℕ) := setoid.mk myintrel is_equivalence def myint := quotient myint.setoid namespace myint def mk (a₁ a₂ : ℕ) : myint := ⟦(a₁, a₂)⟧ notation `[[` a₁ `,` a₂ `]]` := mk a₁ a₂ example : [[1, 6]] = [[10, 15]] := dec_trivial @[derive decidable] private def is_nonneg' (n : ℕ × ℕ) : Prop := n.1 ≥ n.2 example : is_nonneg' (10,8) := dec_trivial def prod_nat_to_prod_nat (n : ℕ × ℕ) : ℕ × ℕ := if is_nonneg' n then (n.1-n.2, 0) else (0, n.2-n.1) example : prod_nat_to_prod_nat (5,7) = (0, 2) := rfl example : prod_nat_to_prod_nat (13, 4) = (9, 0) := rfl def prod_nat_to_string (n : ℕ × ℕ) : string := if is_nonneg' n then to_string (n.1-n.2) else "-" ++ to_string (n.2 - n.1) lemma prod_nat_of_is_nonneg {n : ℕ × ℕ} (h : is_nonneg' n) : prod_nat_to_prod_nat n = (n.1 - n.2, 0) := if_pos h lemma prod_nat_of_is_neg {n : ℕ × ℕ} (h : ¬(is_nonneg' n)) : prod_nat_to_prod_nat n = (0, n.2 - n.1) := if_neg h -- An auxiliary lemma needed only in the proof of `myint_to_prod_nat`. private lemma aux {x y u v : nat} (h : x + v = u + y) (k : x ≥ y) : x - y = u - v := begin have h₂ : u = x - y + v := (nat.add_sub_cancel u y) ▸ h ▸ (nat.sub_add_comm k), rw [h₂, nat.add_sub_cancel], end /- `myint_to_prod_nat` is our main workhorse. Given `n : myint`, it produces a canonical representative of type `ℕ × ℕ`. To do this, we use `quotient.lift` - a result that shows a function of type `α → β` can be lifted to a function of type `quotient s → β` as long as the function respects the equivalence relation that defines `quotient s`. -/ def myint_to_prod_nat (n : myint) : ℕ × ℕ := begin apply quotient.lift_on n prod_nat_to_prod_nat, dsimp [has_equiv.equiv, setoid.r, myintrel, prod_nat_to_prod_nat], intros a b h, split_ifs; unfold is_nonneg' at *, { ext, { dsimp, rwa aux h, }, refl, }, iterate 2 { ext; { dsimp, exfalso, linarith }, }, { ext; dsimp, { refl }, { apply aux; linarith }, }, end example : myint_to_prod_nat [[10, 4]] = (6,0) := rfl @[derive decidable] def is_nonneg : myint → Prop := is_nonneg' ∘ myint_to_prod_nat example : is_nonneg [[10, 3]] := dec_trivial def myint_to_string : myint → string := prod_nat_to_string ∘ myint_to_prod_nat instance myint_repr : has_repr myint := ⟨myint_to_string⟩ instance has_coe_to_myint : has_coe nat (quotient myint.setoid) := ⟨λ n, [[n,0]]⟩ instance has_one_myint : has_one myint := ⟨[[1, 0]]⟩ instance has_zero_myint : has_zero myint := ⟨[[0, 0]]⟩ protected def neg_pair (n : ℕ × ℕ) : myint := [[n.2, n.1]] /- The definition `neg` below uses `quotient.sound`. This result states that two elements `⟦a⟧` and `⟦b⟧` of a quotient type are equal if their representatives are equivalent. That is, `a ≈ b → ⟦a⟧ = ⟦b⟧`. -/ def neg (n : myint) : quotient myint.setoid := quotient.lift_on n myint.neg_pair ( λ a b h, quotient.sound (by {dsimp [has_equiv.equiv, setoid.r, myintrel] at h ⊢, simp only [add_comm, h], })) instance has_neg_myint : has_neg myint := ⟨neg⟩ example : - [[5, 9]] = [[9, 5]] := rfl def add_pair (n m : ℕ × ℕ) : myint := [[n.1 + m.1, n.2 + m.2]] def add : myint → myint → myint := quotient.lift₂ add_pair ( λ a₁ a₂ b₁ b₂ h₁ h₂, quot.sound (by {dsimp [has_equiv.equiv, setoid.r, myintrel] at *, linarith,})) instance has_add_myint : has_add myint := ⟨add⟩ instance has_add_myint' : has_add (quotient myint.setoid) := ⟨add⟩ instance has_sub_myint : has_sub myint := ⟨λ a b, a + -b⟩ example : is_nonneg (10 : myint) := dec_trivial example : ¬(is_nonneg (-10 : myint)) := dec_trivial example : [[6, 8]] + [[5, 1]] = [[2, 0]] := dec_trivial #eval [[6, 8]] + [[5, 36]] -- outputs `-33`. #eval ((5 - 78) : myint) -- outputs `-73`. end myint
66f383aeeb9e8fd2678efbcef00bc697fa5de16a
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/src/Init/System/ST.lean
15b120b2bfb8c3b3ce6882d0107d16d8b600b921
[ "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,558
lean
/- Copyright (c) 2020 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude import Init.Classical import Init.Control.EState import Init.Control.Reader def EST (ε : Type) (σ : Type) : Type → Type := EStateM ε σ abbrev ST (σ : Type) := EST Empty σ instance (ε σ : Type) : Monad (EST ε σ) := inferInstanceAs (Monad (EStateM _ _)) instance (ε σ : Type) : MonadExceptOf ε (EST ε σ) := inferInstanceAs (MonadExceptOf ε (EStateM _ _)) instance {ε σ : Type} {α : Type} [Inhabited ε] : Inhabited (EST ε σ α) := inferInstanceAs (Inhabited (EStateM _ _ _)) instance (σ : Type) : Monad (ST σ) := inferInstanceAs (Monad (EST _ _)) -- Auxiliary class for inferring the "state" of `EST` and `ST` monads class STWorld (σ : outParam Type) (m : Type → Type) instance {σ m n} [MonadLift m n] [STWorld σ m] : STWorld σ n := ⟨⟩ instance {ε σ} : STWorld σ (EST ε σ) := ⟨⟩ @[noinline, nospecialize] def runEST {ε α : Type} (x : (σ : Type) → EST ε σ α) : Except ε α := match x Unit () with | EStateM.Result.ok a _ => Except.ok a | EStateM.Result.error ex _ => Except.error ex @[noinline, nospecialize] def runST {α : Type} (x : (σ : Type) → ST σ α) : α := match x Unit () with | EStateM.Result.ok a _ => a | EStateM.Result.error ex _ => nomatch ex @[always_inline] instance {ε σ} : MonadLift (ST σ) (EST ε σ) := ⟨fun x s => match x s with | EStateM.Result.ok a s => EStateM.Result.ok a s | EStateM.Result.error ex _ => nomatch ex⟩ namespace ST /-- References -/ opaque RefPointed : NonemptyType.{0} structure Ref (σ : Type) (α : Type) : Type where ref : RefPointed.type h : Nonempty α instance {σ α} [s : Nonempty α] : Nonempty (Ref σ α) := Nonempty.intro { ref := Classical.choice RefPointed.property, h := s } namespace Prim /-- Auxiliary definition for showing that `ST σ α` is inhabited when we have a `Ref σ α` -/ private noncomputable def inhabitedFromRef {σ α} (r : Ref σ α) : ST σ α := let _ : Inhabited α := Classical.inhabited_of_nonempty r.h pure default @[extern "lean_st_mk_ref"] opaque mkRef {σ α} (a : α) : ST σ (Ref σ α) := pure { ref := Classical.choice RefPointed.property, h := Nonempty.intro a } @[extern "lean_st_ref_get"] opaque Ref.get {σ α} (r : @& Ref σ α) : ST σ α := inhabitedFromRef r @[extern "lean_st_ref_set"] opaque Ref.set {σ α} (r : @& Ref σ α) (a : α) : ST σ Unit @[extern "lean_st_ref_swap"] opaque Ref.swap {σ α} (r : @& Ref σ α) (a : α) : ST σ α := inhabitedFromRef r @[extern "lean_st_ref_take"] unsafe opaque Ref.take {σ α} (r : @& Ref σ α) : ST σ α := inhabitedFromRef r @[extern "lean_st_ref_ptr_eq"] opaque Ref.ptrEq {σ α} (r1 r2 : @& Ref σ α) : ST σ Bool @[inline] unsafe def Ref.modifyUnsafe {σ α : Type} (r : Ref σ α) (f : α → α) : ST σ Unit := do let v ← Ref.take r Ref.set r (f v) @[inline] unsafe def Ref.modifyGetUnsafe {σ α β : Type} (r : Ref σ α) (f : α → β × α) : ST σ β := do let v ← Ref.take r let (b, a) := f v Ref.set r a pure b @[implemented_by Ref.modifyUnsafe] def Ref.modify {σ α : Type} (r : Ref σ α) (f : α → α) : ST σ Unit := do let v ← Ref.get r Ref.set r (f v) @[implemented_by Ref.modifyGetUnsafe] def Ref.modifyGet {σ α β : Type} (r : Ref σ α) (f : α → β × α) : ST σ β := do let v ← Ref.get r let (b, a) := f v Ref.set r a pure b end Prim section variable {σ : Type} {m : Type → Type} [Monad m] [MonadLiftT (ST σ) m] @[inline] def mkRef {α : Type} (a : α) : m (Ref σ α) := liftM <| Prim.mkRef a @[inline] def Ref.get {α : Type} (r : Ref σ α) : m α := liftM <| Prim.Ref.get r @[inline] def Ref.set {α : Type} (r : Ref σ α) (a : α) : m Unit := liftM <| Prim.Ref.set r a @[inline] def Ref.swap {α : Type} (r : Ref σ α) (a : α) : m α := liftM <| Prim.Ref.swap r a @[inline] unsafe def Ref.take {α : Type} (r : Ref σ α) : m α := liftM <| Prim.Ref.take r @[inline] def Ref.ptrEq {α : Type} (r1 r2 : Ref σ α) : m Bool := liftM <| Prim.Ref.ptrEq r1 r2 @[inline] def Ref.modify {α : Type} (r : Ref σ α) (f : α → α) : m Unit := liftM <| Prim.Ref.modify r f @[inline] def Ref.modifyGet {α : Type} {β : Type} (r : Ref σ α) (f : α → β × α) : m β := liftM <| Prim.Ref.modifyGet r f def Ref.toMonadStateOf (r : Ref σ α) : MonadStateOf α m where get := r.get set := r.set modifyGet := r.modifyGet end end ST
c756ecd3effa3029ebf35804b7fad72598cb8f3c
9be442d9ec2fcf442516ed6e9e1660aa9071b7bd
/src/Lean/Util/ReplaceLevel.lean
119aedb690fdda3ad3d3341b3dc407afa28a96be
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
EdAyers/lean4
57ac632d6b0789cb91fab2170e8c9e40441221bd
37ba0df5841bde51dbc2329da81ac23d4f6a4de4
refs/heads/master
1,676,463,245,298
1,660,619,433,000
1,660,619,433,000
183,433,437
1
0
Apache-2.0
1,657,612,672,000
1,556,196,574,000
Lean
UTF-8
Lean
false
false
3,376
lean
/- Copyright (c) 2020 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Expr namespace Lean namespace Level partial def replace (f? : Level → Option Level) (u : Level) : Level := match f? u with | some v => v | none => match u with | max v₁ v₂ => mkLevelMax' (replace f? v₁) (replace f? v₂) | imax v₁ v₂ => mkLevelIMax' (replace f? v₁) (replace f? v₂) | succ v => mkLevelSucc (replace f? v) | _ => u end Level namespace Expr namespace ReplaceLevelImpl abbrev cacheSize : USize := 8192 structure State where keys : Array Expr -- Remark: our "unsafe" implementation relies on the fact that `()` is not a valid Expr results : Array Expr abbrev ReplaceM := StateM State unsafe def cache (i : USize) (key : Expr) (result : Expr) : ReplaceM Expr := do modify fun s => { keys := s.keys.uset i key lcProof, results := s.results.uset i result lcProof }; pure result unsafe def replaceUnsafeM (f? : Level → Option Level) (size : USize) (e : Expr) : ReplaceM Expr := do let rec visit (e : Expr) := do let c ← get let h := ptrAddrUnsafe e let i := h % size if ptrAddrUnsafe (c.keys.uget i lcProof) == h then pure <| c.results.uget i lcProof else match e with | Expr.forallE _ d b _ => cache i e <| e.updateForallE! (← visit d) (← visit b) | Expr.lam _ d b _ => cache i e <| e.updateLambdaE! (← visit d) (← visit b) | Expr.mdata _ b => cache i e <| e.updateMData! (← visit b) | Expr.letE _ t v b _ => cache i e <| e.updateLet! (← visit t) (← visit v) (← visit b) | Expr.app f a => cache i e <| e.updateApp! (← visit f) (← visit a) | Expr.proj _ _ b => cache i e <| e.updateProj! (← visit b) | Expr.sort u => cache i e <| e.updateSort! (u.replace f?) | Expr.const _ us => cache i e <| e.updateConst! (us.map (Level.replace f?)) | e => pure e visit e unsafe def initCache : State := { keys := mkArray cacheSize.toNat (cast lcProof ()), -- `()` is not a valid `Expr` results := mkArray cacheSize.toNat default } unsafe def replaceUnsafe (f? : Level → Option Level) (e : Expr) : Expr := (replaceUnsafeM f? cacheSize e).run' initCache end ReplaceLevelImpl @[implementedBy ReplaceLevelImpl.replaceUnsafe] partial def replaceLevel (f? : Level → Option Level) : Expr → Expr | e@(Expr.forallE _ d b _) => let d := replaceLevel f? d; let b := replaceLevel f? b; e.updateForallE! d b | e@(Expr.lam _ d b _) => let d := replaceLevel f? d; let b := replaceLevel f? b; e.updateLambdaE! d b | e@(Expr.mdata _ b) => let b := replaceLevel f? b; e.updateMData! b | e@(Expr.letE _ t v b _) => let t := replaceLevel f? t; let v := replaceLevel f? v; let b := replaceLevel f? b; e.updateLet! t v b | e@(Expr.app f a) => let f := replaceLevel f? f; let a := replaceLevel f? a; e.updateApp! f a | e@(Expr.proj _ _ b) => let b := replaceLevel f? b; e.updateProj! b | e@(Expr.sort u) => e.updateSort! (u.replace f?) | e@(Expr.const _ us) => e.updateConst! (us.map (Level.replace f?)) | e => e end Expr end Lean
62f87aa85e7f0127fe7a974336e3d8401a2eb652
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/ring_theory/dedekind_domain/adic_valuation.lean
5098e9e5faf7911f65835c85f1a0444f712192fd
[ "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
15,506
lean
/- Copyright (c) 2022 María Inés de Frutos-Fernández. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: María Inés de Frutos-Fernández -/ import ring_theory.dedekind_domain.ideal import ring_theory.valuation.extend_to_localization import ring_theory.valuation.valuation_subring import topology.algebra.valued_field /-! # Adic valuations on Dedekind domains Given a Dedekind domain `R` of Krull dimension 1 and a maximal ideal `v` of `R`, we define the `v`-adic valuation on `R` and its extension to the field of fractions `K` of `R`. We prove several properties of this valuation, including the existence of uniformizers. We define the completion of `K` with respect to the `v`-adic valuation, denoted `v.adic_completion`,and its ring of integers, denoted `v.adic_completion_integers`. ## Main definitions - `is_dedekind_domain.height_one_spectrum.int_valuation v` is the `v`-adic valuation on `R`. - `is_dedekind_domain.height_one_spectrum.valuation v` is the `v`-adic valuation on `K`. - `is_dedekind_domain.height_one_spectrum.adic_completion v` is the completion of `K` with respect to its `v`-adic valuation. - `is_dedekind_domain.height_one_spectrum.adic_completion_integers v` is the ring of integers of `v.adic_completion`. ## Main results - `is_dedekind_domain.height_one_spectrum.int_valuation_le_one` : The `v`-adic valuation on `R` is bounded above by 1. - `is_dedekind_domain.height_one_spectrum.int_valuation_lt_one_iff_dvd` : The `v`-adic valuation of `r ∈ R` is less than 1 if and only if `v` divides the ideal `(r)`. - `is_dedekind_domain.height_one_spectrum.int_valuation_le_pow_iff_dvd` : The `v`-adic valuation of `r ∈ R` is less than or equal to `multiplicative.of_add (-n)` if and only if `vⁿ` divides the ideal `(r)`. - `is_dedekind_domain.height_one_spectrum.int_valuation_exists_uniformizer` : There exists `π ∈ R` with `v`-adic valuation `multiplicative.of_add (-1)`. - `is_dedekind_domain.height_one_spectrum.valuation_of_mk'` : The `v`-adic valuation of `r/s ∈ K` is the valuation of `r` divided by the valuation of `s`. - `is_dedekind_domain.height_one_spectrum.valuation_of_algebra_map` : The `v`-adic valuation on `K` extends the `v`-adic valuation on `R`. - `is_dedekind_domain.height_one_spectrum.valuation_exists_uniformizer` : There exists `π ∈ K` with `v`-adic valuation `multiplicative.of_add (-1)`. ## Implementation notes We are only interested in Dedekind domains with Krull dimension 1. ## References * [G. J. Janusz, *Algebraic Number Fields*][janusz1996] * [J.W.S. Cassels, A. Frölich, *Algebraic Number Theory*][cassels1967algebraic] * [J. Neukirch, *Algebraic Number Theory*][Neukirch1992] ## Tags dedekind domain, dedekind ring, adic valuation -/ noncomputable theory open_locale classical discrete_valuation open multiplicative is_dedekind_domain variables {R : Type*} [comm_ring R] [is_domain R] [is_dedekind_domain R] {K : Type*} [field K] [algebra R K] [is_fraction_ring R K] (v : height_one_spectrum R) namespace is_dedekind_domain.height_one_spectrum /-! ### Adic valuations on the Dedekind domain R -/ /-- The additive `v`-adic valuation of `r ∈ R` is the exponent of `v` in the factorization of the ideal `(r)`, if `r` is nonzero, or infinity, if `r = 0`. `int_valuation_def` is the corresponding multiplicative valuation. -/ def int_valuation_def (r : R) : ℤₘ₀ := if r = 0 then 0 else multiplicative.of_add (-(associates.mk v.as_ideal).count (associates.mk (ideal.span {r} : ideal R)).factors : ℤ) lemma int_valuation_def_if_pos {r : R} (hr : r = 0) : v.int_valuation_def r = 0 := if_pos hr lemma int_valuation_def_if_neg {r : R} (hr : r ≠ 0) : v.int_valuation_def r = (multiplicative.of_add (-(associates.mk v.as_ideal).count (associates.mk (ideal.span {r} : ideal R)).factors : ℤ)) := if_neg hr /-- Nonzero elements have nonzero adic valuation. -/ lemma int_valuation_ne_zero (x : R) (hx : x ≠ 0) : v.int_valuation_def x ≠ 0 := begin rw [int_valuation_def, if_neg hx], exact with_zero.coe_ne_zero, end /-- Nonzero divisors have nonzero valuation. -/ lemma int_valuation_ne_zero' (x : non_zero_divisors R) : v.int_valuation_def x ≠ 0 := v.int_valuation_ne_zero x (non_zero_divisors.coe_ne_zero x) /-- Nonzero divisors have valuation greater than zero. -/ lemma int_valuation_zero_le (x : non_zero_divisors R) : 0 < v.int_valuation_def x := begin rw [v.int_valuation_def_if_neg (non_zero_divisors.coe_ne_zero x)], exact with_zero.zero_lt_coe _, end /-- The `v`-adic valuation on `R` is bounded above by 1. -/ lemma int_valuation_le_one (x : R) : v.int_valuation_def x ≤ 1 := begin rw int_valuation_def, by_cases hx : x = 0, { rw if_pos hx, exact with_zero.zero_le 1 }, { rw [if_neg hx, ← with_zero.coe_one, ← of_add_zero, with_zero.coe_le_coe, of_add_le, right.neg_nonpos_iff], exact int.coe_nat_nonneg _ } end /-- The `v`-adic valuation of `r ∈ R` is less than 1 if and only if `v` divides the ideal `(r)`. -/ lemma int_valuation_lt_one_iff_dvd (r : R) : v.int_valuation_def r < 1 ↔ v.as_ideal ∣ ideal.span {r} := begin rw int_valuation_def, split_ifs with hr, { simpa [hr] using (with_zero.zero_lt_coe _) }, { rw [← with_zero.coe_one, ← of_add_zero, with_zero.coe_lt_coe, of_add_lt, neg_lt_zero, ← int.coe_nat_zero, int.coe_nat_lt, zero_lt_iff], have h : (ideal.span {r} : ideal R) ≠ 0, { rw [ne.def, ideal.zero_eq_bot, ideal.span_singleton_eq_bot], exact hr }, apply associates.count_ne_zero_iff_dvd h (by apply v.irreducible) } end /-- The `v`-adic valuation of `r ∈ R` is less than `multiplicative.of_add (-n)` if and only if `vⁿ` divides the ideal `(r)`. -/ lemma int_valuation_le_pow_iff_dvd (r : R) (n : ℕ) : v.int_valuation_def r ≤ multiplicative.of_add (-(n : ℤ)) ↔ v.as_ideal^n ∣ ideal.span {r} := begin rw int_valuation_def, split_ifs with hr, { simp_rw [hr, ideal.dvd_span_singleton, zero_le', submodule.zero_mem], }, { rw [with_zero.coe_le_coe, of_add_le, neg_le_neg_iff, int.coe_nat_le, ideal.dvd_span_singleton, ← associates.le_singleton_iff, associates.prime_pow_dvd_iff_le (associates.mk_ne_zero'.mpr hr) (by apply v.associates_irreducible)] } end /-- The `v`-adic valuation of `0 : R` equals 0. -/ lemma int_valuation.map_zero' : v.int_valuation_def 0 = 0 := v.int_valuation_def_if_pos (eq.refl 0) /-- The `v`-adic valuation of `1 : R` equals 1. -/ lemma int_valuation.map_one' : v.int_valuation_def 1 = 1 := by rw [v.int_valuation_def_if_neg (zero_ne_one.symm : (1 : R) ≠ 0), ideal.span_singleton_one, ← ideal.one_eq_top, associates.mk_one, associates.factors_one, associates.count_zero (by apply v.associates_irreducible), int.coe_nat_zero, neg_zero, of_add_zero, with_zero.coe_one] /-- The `v`-adic valuation of a product equals the product of the valuations. -/ lemma int_valuation.map_mul' (x y : R) : v.int_valuation_def (x * y) = v.int_valuation_def x * v.int_valuation_def y := begin simp only [int_valuation_def], by_cases hx : x = 0, { rw [hx, zero_mul, if_pos (eq.refl _), zero_mul] }, { by_cases hy : y = 0, { rw [hy, mul_zero, if_pos (eq.refl _), mul_zero] }, { rw [if_neg hx, if_neg hy, if_neg (mul_ne_zero hx hy), ← with_zero.coe_mul, with_zero.coe_inj, ← of_add_add, ← ideal.span_singleton_mul_span_singleton, ← associates.mk_mul_mk, ← neg_add, associates.count_mul (by apply associates.mk_ne_zero'.mpr hx) (by apply associates.mk_ne_zero'.mpr hy) (by apply v.associates_irreducible)], refl }} end lemma int_valuation.le_max_iff_min_le {a b c : ℕ} : multiplicative.of_add(-c : ℤ) ≤ max (multiplicative.of_add(-a : ℤ)) (multiplicative.of_add(-b : ℤ)) ↔ min a b ≤ c := by rw [le_max_iff, of_add_le, of_add_le, neg_le_neg_iff, neg_le_neg_iff, int.coe_nat_le, int.coe_nat_le, ← min_le_iff] /-- The `v`-adic valuation of a sum is bounded above by the maximum of the valuations. -/ lemma int_valuation.map_add_le_max' (x y : R) : v.int_valuation_def (x + y) ≤ max (v.int_valuation_def x) (v.int_valuation_def y) := begin by_cases hx : x = 0, { rw [hx, zero_add], conv_rhs {rw [int_valuation_def, if_pos (eq.refl _)]}, rw max_eq_right (with_zero.zero_le (v.int_valuation_def y)), exact le_refl _, }, { by_cases hy : y = 0, { rw [hy, add_zero], conv_rhs {rw [max_comm, int_valuation_def, if_pos (eq.refl _)]}, rw max_eq_right (with_zero.zero_le (v.int_valuation_def x)), exact le_refl _ }, { by_cases hxy : x + y = 0, { rw [int_valuation_def, if_pos hxy], exact zero_le',}, { rw [v.int_valuation_def_if_neg hxy, v.int_valuation_def_if_neg hx, v.int_valuation_def_if_neg hy, with_zero.le_max_iff, int_valuation.le_max_iff_min_le], set nmin := min ((associates.mk v.as_ideal).count (associates.mk (ideal.span {x})).factors) ((associates.mk v.as_ideal).count (associates.mk (ideal.span {y})).factors), have h_dvd_x : x ∈ v.as_ideal ^ (nmin), { rw [← associates.le_singleton_iff x nmin _, associates.prime_pow_dvd_iff_le (associates.mk_ne_zero'.mpr hx) _], exact min_le_left _ _, apply v.associates_irreducible }, have h_dvd_y : y ∈ v.as_ideal ^ nmin, { rw [← associates.le_singleton_iff y nmin _, associates.prime_pow_dvd_iff_le (associates.mk_ne_zero'.mpr hy) _], exact min_le_right _ _, apply v.associates_irreducible }, have h_dvd_xy : associates.mk v.as_ideal^nmin ≤ associates.mk (ideal.span {x + y}), { rw associates.le_singleton_iff, exact ideal.add_mem (v.as_ideal^nmin) h_dvd_x h_dvd_y, }, rw (associates.prime_pow_dvd_iff_le (associates.mk_ne_zero'.mpr hxy) _) at h_dvd_xy, exact h_dvd_xy, apply v.associates_irreducible, }}} end /-- The `v`-adic valuation on `R`. -/ def int_valuation : valuation R ℤₘ₀ := { to_fun := v.int_valuation_def, map_zero' := int_valuation.map_zero' v, map_one' := int_valuation.map_one' v, map_mul' := int_valuation.map_mul' v, map_add_le_max' := int_valuation.map_add_le_max' v } /-- There exists `π ∈ R` with `v`-adic valuation `multiplicative.of_add (-1)`. -/ lemma int_valuation_exists_uniformizer : ∃ (π : R), v.int_valuation_def π = multiplicative.of_add (-1 : ℤ) := begin have hv : _root_.irreducible (associates.mk v.as_ideal) := v.associates_irreducible, have hlt : v.as_ideal^2 < v.as_ideal, { rw ← ideal.dvd_not_unit_iff_lt, exact ⟨v.ne_bot, v.as_ideal, (not_congr ideal.is_unit_iff).mpr (ideal.is_prime.ne_top v.is_prime), sq v.as_ideal⟩ } , obtain ⟨π, mem, nmem⟩ := set_like.exists_of_lt hlt, have hπ : associates.mk (ideal.span {π}) ≠ 0, { rw associates.mk_ne_zero', intro h, rw h at nmem, exact nmem (submodule.zero_mem (v.as_ideal^2)), }, use π, rw [int_valuation_def, if_neg (associates.mk_ne_zero'.mp hπ), with_zero.coe_inj], apply congr_arg, rw [neg_inj, ← int.coe_nat_one, int.coe_nat_inj'], rw [← ideal.dvd_span_singleton, ← associates.mk_le_mk_iff_dvd_iff] at mem nmem, rw [← pow_one (associates.mk v.as_ideal), associates.prime_pow_dvd_iff_le hπ hv] at mem, rw [associates.mk_pow, associates.prime_pow_dvd_iff_le hπ hv, not_le] at nmem, exact nat.eq_of_le_of_lt_succ mem nmem, end /-! ### Adic valuations on the field of fractions `K` -/ /-- The `v`-adic valuation of `x ∈ K` is the valuation of `r` divided by the valuation of `s`, where `r` and `s` are chosen so that `x = r/s`. -/ def valuation (v : height_one_spectrum R) : valuation K ℤₘ₀ := v.int_valuation.extend_to_localization (λ r hr, set.mem_compl $ v.int_valuation_ne_zero' ⟨r, hr⟩) K lemma valuation_def (x : K) : v.valuation x = v.int_valuation.extend_to_localization (λ r hr, set.mem_compl (v.int_valuation_ne_zero' ⟨r, hr⟩)) K x := rfl /-- The `v`-adic valuation of `r/s ∈ K` is the valuation of `r` divided by the valuation of `s`. -/ lemma valuation_of_mk' {r : R} {s : non_zero_divisors R} : v.valuation (is_localization.mk' K r s) = v.int_valuation r / v.int_valuation s := begin erw [valuation_def, (is_localization.to_localization_map (non_zero_divisors R) K).lift_mk', div_eq_mul_inv, mul_eq_mul_left_iff], left, rw [units.coe_inv, inv_inj], refl, end /-- The `v`-adic valuation on `K` extends the `v`-adic valuation on `R`. -/ lemma valuation_of_algebra_map (r : R) : v.valuation (algebra_map R K r) = v.int_valuation r := by rw [valuation_def, valuation.extend_to_localization_apply_map_apply] /-- The `v`-adic valuation on `R` is bounded above by 1. -/ lemma valuation_le_one (r : R) : v.valuation (algebra_map R K r) ≤ 1 := by { rw valuation_of_algebra_map, exact v.int_valuation_le_one r } /-- The `v`-adic valuation of `r ∈ R` is less than 1 if and only if `v` divides the ideal `(r)`. -/ lemma valuation_lt_one_iff_dvd (r : R) : v.valuation (algebra_map R K r) < 1 ↔ v.as_ideal ∣ ideal.span {r} := by { rw valuation_of_algebra_map, exact v.int_valuation_lt_one_iff_dvd r } variable (K) /-- There exists `π ∈ K` with `v`-adic valuation `multiplicative.of_add (-1)`. -/ lemma valuation_exists_uniformizer : ∃ (π : K), v.valuation π = multiplicative.of_add (-1 : ℤ) := begin obtain ⟨r, hr⟩ := v.int_valuation_exists_uniformizer, use algebra_map R K r, rw [valuation_def, valuation.extend_to_localization_apply_map_apply], exact hr, end /-- Uniformizers are nonzero. -/ lemma valuation_uniformizer_ne_zero : (classical.some (v.valuation_exists_uniformizer K)) ≠ 0 := begin have hu := classical.some_spec (v.valuation_exists_uniformizer K), exact (valuation.ne_zero_iff _).mp (ne_of_eq_of_ne hu with_zero.coe_ne_zero), end /-! ### Completions with respect to adic valuations Given a Dedekind domain `R` with field of fractions `K` and a maximal ideal `v` of `R`, we define the completion of `K` with respect to its `v`-adic valuation, denoted `v.adic_completion`, and its ring of integers, denoted `v.adic_completion_integers`. -/ variable {K} /-- `K` as a valued field with the `v`-adic valuation. -/ def adic_valued : valued K ℤₘ₀ := valued.mk' v.valuation lemma adic_valued_apply {x : K} : (v.adic_valued.v : _) x = v.valuation x := rfl variables (K) /-- The completion of `K` with respect to its `v`-adic valuation. -/ def adic_completion := @uniform_space.completion K v.adic_valued.to_uniform_space instance : field (v.adic_completion K) := @uniform_space.completion.field K _ v.adic_valued.to_uniform_space _ _ v.adic_valued.to_uniform_add_group instance : inhabited (v.adic_completion K) := ⟨0⟩ instance valued_adic_completion : valued (v.adic_completion K) ℤₘ₀ := @valued.valued_completion _ _ _ _ v.adic_valued lemma valued_adic_completion_def {x : v.adic_completion K} : valued.v x = @valued.extension K _ _ _ (adic_valued v) x := rfl instance adic_completion_complete_space : complete_space (v.adic_completion K) := @uniform_space.completion.complete_space K v.adic_valued.to_uniform_space instance adic_completion.has_lift_t : has_lift_t K (v.adic_completion K) := (infer_instance : has_lift_t K (@uniform_space.completion K v.adic_valued.to_uniform_space)) /-- The ring of integers of `adic_completion`. -/ def adic_completion_integers : valuation_subring (v.adic_completion K) := valued.v.valuation_subring end is_dedekind_domain.height_one_spectrum
27f86cb75d48706ae69b0b62ae04b09d7885e19e
63abd62053d479eae5abf4951554e1064a4c45b4
/src/analysis/normed_space/multilinear.lean
3edcd74ff1da00de5d5c58ce03400352bc529626
[ "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
57,146
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 analysis.normed_space.operator_norm import topology.algebra.multilinear /-! # Operator norm on the space of continuous multilinear maps When `f` is a continuous multilinear map in finitely many variables, we define its norm `∥f∥` as the smallest number such that `∥f m∥ ≤ ∥f∥ * ∏ i, ∥m i∥` for all `m`. We show that it is indeed a norm, and prove its basic properties. ## Main results Let `f` be a multilinear map in finitely many variables. * `exists_bound_of_continuous` asserts that, if `f` is continuous, then there exists `C > 0` with `∥f m∥ ≤ C * ∏ i, ∥m i∥` for all `m`. * `continuous_of_bound`, conversely, asserts that this bound implies continuity. * `mk_continuous` constructs the associated continuous multilinear map. Let `f` be a continuous multilinear map in finitely many variables. * `∥f∥` is its norm, i.e., the smallest number such that `∥f m∥ ≤ ∥f∥ * ∏ i, ∥m i∥` for all `m`. * `le_op_norm f m` asserts the fundamental inequality `∥f m∥ ≤ ∥f∥ * ∏ i, ∥m i∥`. * `norm_image_sub_le_of_bound f m₁ m₂` gives a control of the difference `f m₁ - f m₂` in terms of `∥f∥` and `∥m₁ - m₂∥`. We also register isomorphisms corresponding to currying or uncurrying variables, transforming a continuous multilinear function `f` in `n+1` variables into a continuous linear function taking values in continuous multilinear functions in `n` variables, and also into a continuous multilinear function in `n` variables taking values in continuous linear functions. These operations are called `f.curry_left` and `f.curry_right` respectively (with inverses `f.uncurry_left` and `f.uncurry_right`). They induce continuous linear equivalences between spaces of continuous multilinear functions in `n+1` variables and spaces of continuous linear functions into continuous multilinear functions in `n` variables (resp. continuous multilinear functions in `n` variables taking values in continuous linear functions), called respectively `continuous_multilinear_curry_left_equiv` and `continuous_multilinear_curry_right_equiv`. ## Implementation notes We mostly follow the API (and the proofs) of `operator_norm.lean`, with the additional complexity that we should deal with multilinear maps in several variables. The currying/uncurrying constructions are based on those in `multilinear.lean`. From the mathematical point of view, all the results follow from the results on operator norm in one variable, by applying them to one variable after the other through currying. However, this is only well defined when there is an order on the variables (for instance on `fin n`) although the final result is independent of the order. While everything could be done following this approach, it turns out that direct proofs are easier and more efficient. -/ noncomputable theory open_locale classical big_operators open finset local attribute [instance, priority 1001] add_comm_group.to_add_comm_monoid normed_group.to_add_comm_group normed_space.to_semimodule universes u v w w₁ w₂ wG variables {𝕜 : Type u} {ι : Type v} {n : ℕ} {G : Type wG} {E : fin n.succ → Type w} {E₁ : ι → Type w₁} {E₂ : Type w₂} [decidable_eq ι] [fintype ι] [nondiscrete_normed_field 𝕜] [normed_group G] [∀i, normed_group (E i)] [∀i, normed_group (E₁ i)] [normed_group E₂] [normed_space 𝕜 G] [∀i, normed_space 𝕜 (E i)] [∀i, normed_space 𝕜 (E₁ i)] [normed_space 𝕜 E₂] /-! ### Continuity properties of multilinear maps We relate continuity of multilinear maps to the inequality `∥f m∥ ≤ C * ∏ i, ∥m i∥`, in both directions. Along the way, we prove useful bounds on the difference `∥f m₁ - f m₂∥`. -/ namespace multilinear_map variable (f : multilinear_map 𝕜 E₁ E₂) /-- If a multilinear map in finitely many variables on normed spaces is continuous, then it satisfies the inequality `∥f m∥ ≤ C * ∏ i, ∥m i∥`, for some `C` which can be chosen to be positive. -/ theorem exists_bound_of_continuous (hf : continuous f) : ∃ (C : ℝ), 0 < C ∧ (∀ m, ∥f m∥ ≤ C * ∏ i, ∥m i∥) := begin /- The proof only uses the continuity at `0`. Then, given a general point `m`, rescale each of its coordinates to bring them to a shell of fixed width around `0`, on which one knows that `f` is bounded, and then use the multiplicativity of `f` along each coordinate to deduce the desired bound.-/ obtain ⟨ε, ε_pos, hε⟩ : ∃ ε > 0, ∀{m}, dist m 0 < ε → dist (f m) (f 0) < 1 := metric.tendsto_nhds_nhds.1 hf.continuous_at 1 zero_lt_one, let δ := ε/2, have δ_pos : δ > 0 := half_pos ε_pos, /- On points of size at most `δ`, `f` is bounded (by `1 + ∥f 0∥`). -/ have H : ∀{a}, ∥a∥ ≤ δ → ∥f a∥ ≤ 1 + ∥f 0∥, { assume a ha, have : dist (f a) (f 0) ≤ 1, { apply le_of_lt (hε _), rw [dist_eq_norm, sub_zero], exact lt_of_le_of_lt ha (half_lt_self ε_pos) }, calc ∥f a∥ = dist (f a) 0 : (dist_zero_right _).symm ... ≤ dist (f a) (f 0) + dist (f 0) 0 : dist_triangle _ _ _ ... ≤ 1 + ∥f 0∥ : by { rw dist_zero_right, exact add_le_add_right this _ } }, obtain ⟨c, hc⟩ : ∃c : 𝕜, 1 < ∥c∥ := normed_field.exists_one_lt_norm 𝕜, set C := (1 + ∥f 0∥) * ∏ i : ι, (δ⁻¹ * ∥c∥), have C_pos : 0 < C := mul_pos (lt_of_lt_of_le zero_lt_one (by simp)) (prod_pos (λi hi, mul_pos (inv_pos.2 δ_pos) (lt_of_le_of_lt zero_le_one hc))), refine ⟨C, C_pos, λm, _⟩, /- Given a general point `m`, rescale each coordinate to bring it to `[δ/∥c∥, δ]` by multiplication by a power of a scalar `c` with norm `∥c∥ > 1`.-/ by_cases h : ∃i, m i = 0, { rcases h with ⟨i, hi⟩, rw [f.map_coord_zero i hi, norm_zero], exact mul_nonneg (le_of_lt C_pos) (prod_nonneg (λi hi, norm_nonneg _)) }, { push_neg at h, have : ∀i, ∃d:𝕜, d ≠ 0 ∧ ∥d • m i∥ ≤ δ ∧ (δ/∥c∥ ≤ ∥d • m i∥) ∧ (∥d∥⁻¹ ≤ δ⁻¹ * ∥c∥ * ∥m i∥) := λi, rescale_to_shell hc δ_pos (h i), choose d hd using this, have A : 0 ≤ 1 + ∥f 0∥ := add_nonneg zero_le_one (norm_nonneg _), have B : ∀ (i : ι), i ∈ univ → 0 ≤ ∥d i∥⁻¹ := λi hi, by simp, -- use the bound on `f` on the ball of size `δ` to conclude. calc ∥f m∥ = ∥f (λi, (d i)⁻¹ • (d i • m i))∥ : by { unfold_coes, congr' with i, rw [← mul_smul, inv_mul_cancel (hd i).1, one_smul] } ... = ∥(∏ i, (d i)⁻¹) • f (λi, d i • m i)∥ : by rw f.map_smul_univ ... = (∏ i, ∥d i∥⁻¹) * ∥f (λi, d i • m i)∥ : by { rw [norm_smul, normed_field.norm_prod], congr' with i, rw normed_field.norm_inv } ... ≤ (∏ i, ∥d i∥⁻¹) * (1 + ∥f 0∥) : mul_le_mul_of_nonneg_left (H ((pi_norm_le_iff (le_of_lt δ_pos)).2 (λi, (hd i).2.1))) (prod_nonneg B) ... ≤ (∏ i, δ⁻¹ * ∥c∥ * ∥m i∥) * (1 + ∥f 0∥) : mul_le_mul_of_nonneg_right (prod_le_prod B (λi hi, (hd i).2.2.2)) A ... = (∏ i : ι, δ⁻¹ * ∥c∥) * (∏ i, ∥m i∥) * (1 + ∥f 0∥) : by rw prod_mul_distrib ... = C * (∏ i, ∥m i∥) : by rw [mul_comm, ← mul_assoc] } end /-- If `f` satisfies a boundedness property around `0`, one can deduce a bound on `f m₁ - f m₂` using the multilinearity. Here, we give a precise but hard to use version. See `norm_image_sub_le_of_bound` for a less precise but more usable version. The bound reads `∥f m - f m'∥ ≤ C * ∥m 1 - m' 1∥ * max ∥m 2∥ ∥m' 2∥ * max ∥m 3∥ ∥m' 3∥ * ... * max ∥m n∥ ∥m' n∥ + ...`, where the other terms in the sum are the same products where `1` is replaced by any `i`. -/ lemma norm_image_sub_le_of_bound' {C : ℝ} (hC : 0 ≤ C) (H : ∀ m, ∥f m∥ ≤ C * ∏ i, ∥m i∥) (m₁ m₂ : Πi, E₁ i) : ∥f m₁ - f m₂∥ ≤ C * ∑ i, ∏ j, if j = i then ∥m₁ i - m₂ i∥ else max ∥m₁ j∥ ∥m₂ j∥ := begin have A : ∀(s : finset ι), ∥f m₁ - f (s.piecewise m₂ m₁)∥ ≤ C * ∑ i in s, ∏ j, if j = i then ∥m₁ i - m₂ i∥ else max ∥m₁ j∥ ∥m₂ j∥, { refine finset.induction (by simp) _, assume i s his Hrec, have I : ∥f (s.piecewise m₂ m₁) - f ((insert i s).piecewise m₂ m₁)∥ ≤ C * ∏ j, if j = i then ∥m₁ i - m₂ i∥ else max ∥m₁ j∥ ∥m₂ j∥, { have A : ((insert i s).piecewise m₂ m₁) = function.update (s.piecewise m₂ m₁) i (m₂ i) := s.piecewise_insert _ _ _, have B : s.piecewise m₂ m₁ = function.update (s.piecewise m₂ m₁) i (m₁ i), { ext j, by_cases h : j = i, { rw h, simp [his] }, { simp [h] } }, rw [B, A, ← f.map_sub], apply le_trans (H _) (mul_le_mul_of_nonneg_left _ hC), refine prod_le_prod (λj hj, norm_nonneg _) (λj hj, _), by_cases h : j = i, { rw h, simp }, { by_cases h' : j ∈ s; simp [h', h, le_refl] } }, calc ∥f m₁ - f ((insert i s).piecewise m₂ m₁)∥ ≤ ∥f m₁ - f (s.piecewise m₂ m₁)∥ + ∥f (s.piecewise m₂ m₁) - f ((insert i s).piecewise m₂ m₁)∥ : by { rw [← dist_eq_norm, ← dist_eq_norm, ← dist_eq_norm], exact dist_triangle _ _ _ } ... ≤ (C * ∑ i in s, ∏ j, if j = i then ∥m₁ i - m₂ i∥ else max ∥m₁ j∥ ∥m₂ j∥) + C * ∏ j, if j = i then ∥m₁ i - m₂ i∥ else max ∥m₁ j∥ ∥m₂ j∥ : add_le_add Hrec I ... = C * ∑ i in insert i s, ∏ j, if j = i then ∥m₁ i - m₂ i∥ else max ∥m₁ j∥ ∥m₂ j∥ : by simp [his, add_comm, left_distrib] }, convert A univ, simp end /-- If `f` satisfies a boundedness property around `0`, one can deduce a bound on `f m₁ - f m₂` using the multilinearity. Here, we give a usable but not very precise version. See `norm_image_sub_le_of_bound'` for a more precise but less usable version. The bound is `∥f m - f m'∥ ≤ C * card ι * ∥m - m'∥ * (max ∥m∥ ∥m'∥) ^ (card ι - 1)`. -/ lemma norm_image_sub_le_of_bound {C : ℝ} (hC : 0 ≤ C) (H : ∀ m, ∥f m∥ ≤ C * ∏ i, ∥m i∥) (m₁ m₂ : Πi, E₁ i) : ∥f m₁ - f m₂∥ ≤ C * (fintype.card ι) * (max ∥m₁∥ ∥m₂∥) ^ (fintype.card ι - 1) * ∥m₁ - m₂∥ := begin have A : ∀ (i : ι), ∏ j, (if j = i then ∥m₁ i - m₂ i∥ else max ∥m₁ j∥ ∥m₂ j∥) ≤ ∥m₁ - m₂∥ * (max ∥m₁∥ ∥m₂∥) ^ (fintype.card ι - 1), { assume i, calc ∏ j, (if j = i then ∥m₁ i - m₂ i∥ else max ∥m₁ j∥ ∥m₂ j∥) ≤ ∏ j : ι, function.update (λ j, max ∥m₁∥ ∥m₂∥) i (∥m₁ - m₂∥) j : begin apply prod_le_prod, { assume j hj, by_cases h : j = i; simp [h, norm_nonneg] }, { assume j hj, by_cases h : j = i, { rw h, simp, exact norm_le_pi_norm (m₁ - m₂) i }, { simp [h, max_le_max, norm_le_pi_norm] } } end ... = ∥m₁ - m₂∥ * (max ∥m₁∥ ∥m₂∥) ^ (fintype.card ι - 1) : by { rw prod_update_of_mem (finset.mem_univ _), simp [card_univ_diff] } }, calc ∥f m₁ - f m₂∥ ≤ C * ∑ i, ∏ j, if j = i then ∥m₁ i - m₂ i∥ else max ∥m₁ j∥ ∥m₂ j∥ : f.norm_image_sub_le_of_bound' hC H m₁ m₂ ... ≤ C * ∑ i, ∥m₁ - m₂∥ * (max ∥m₁∥ ∥m₂∥) ^ (fintype.card ι - 1) : mul_le_mul_of_nonneg_left (sum_le_sum (λi hi, A i)) hC ... = C * (fintype.card ι) * (max ∥m₁∥ ∥m₂∥) ^ (fintype.card ι - 1) * ∥m₁ - m₂∥ : by { rw [sum_const, card_univ, nsmul_eq_mul], ring } end /-- If a multilinear map satisfies an inequality `∥f m∥ ≤ C * ∏ i, ∥m i∥`, then it is continuous. -/ theorem continuous_of_bound (C : ℝ) (H : ∀ m, ∥f m∥ ≤ C * ∏ i, ∥m i∥) : continuous f := begin let D := max C 1, have D_pos : 0 ≤ D := le_trans zero_le_one (le_max_right _ _), replace H : ∀ m, ∥f m∥ ≤ D * ∏ i, ∥m i∥, { assume m, apply le_trans (H m) (mul_le_mul_of_nonneg_right (le_max_left _ _) _), exact prod_nonneg (λ(i : ι) hi, norm_nonneg (m i)) }, refine continuous_iff_continuous_at.2 (λm, _), refine continuous_at_of_locally_lipschitz zero_lt_one (D * (fintype.card ι) * (∥m∥ + 1) ^ (fintype.card ι - 1)) (λm' h', _), rw [dist_eq_norm, dist_eq_norm], have : 0 ≤ (max ∥m'∥ ∥m∥), by simp, have : (max ∥m'∥ ∥m∥) ≤ ∥m∥ + 1, by simp [zero_le_one, norm_le_of_mem_closed_ball (le_of_lt h'), -add_comm], calc ∥f m' - f m∥ ≤ D * (fintype.card ι) * (max ∥m'∥ ∥m∥) ^ (fintype.card ι - 1) * ∥m' - m∥ : f.norm_image_sub_le_of_bound D_pos H m' m ... ≤ D * (fintype.card ι) * (∥m∥ + 1) ^ (fintype.card ι - 1) * ∥m' - m∥ : by apply_rules [mul_le_mul_of_nonneg_right, mul_le_mul_of_nonneg_left, mul_nonneg, norm_nonneg, nat.cast_nonneg, pow_le_pow_of_le_left] end /-- Constructing a continuous multilinear map from a multilinear map satisfying a boundedness condition. -/ def mk_continuous (C : ℝ) (H : ∀ m, ∥f m∥ ≤ C * ∏ i, ∥m i∥) : continuous_multilinear_map 𝕜 E₁ E₂ := { cont := f.continuous_of_bound C H, ..f } /-- Given a multilinear map in `n` variables, if one restricts it to `k` variables putting `z` on the other coordinates, then the resulting restricted function satisfies an inequality `∥f.restr v∥ ≤ C * ∥z∥^(n-k) * Π ∥v i∥` if the original function satisfies `∥f v∥ ≤ C * Π ∥v i∥`. -/ lemma restr_norm_le {k n : ℕ} (f : (multilinear_map 𝕜 (λ i : fin n, G) E₂ : _)) (s : finset (fin n)) (hk : s.card = k) (z : G) {C : ℝ} (H : ∀ m, ∥f m∥ ≤ C * ∏ i, ∥m i∥) (v : fin k → G) : ∥f.restr s hk z v∥ ≤ C * ∥z∥ ^ (n - k) * ∏ i, ∥v i∥ := begin rw mul_assoc, convert H _ using 2, simp only [apply_dite norm, fintype.prod_dite, prod_const (∥z∥), finset.card_univ, fintype.card_of_subtype sᶜ (λ x, mem_compl), card_compl, fintype.card_fin, hk, mk_coe, (s.mono_equiv_of_fin hk).symm.prod_comp (λ x, ∥v x∥)], apply mul_comm end end multilinear_map /-! ### Continuous multilinear maps We define the norm `∥f∥` of a continuous multilinear map `f` in finitely many variables as the smallest number such that `∥f m∥ ≤ ∥f∥ * ∏ i, ∥m i∥` for all `m`. We show that this defines a normed space structure on `continuous_multilinear_map 𝕜 E₁ E₂`. -/ namespace continuous_multilinear_map variables (c : 𝕜) (f g : continuous_multilinear_map 𝕜 E₁ E₂) (m : Πi, E₁ i) theorem bound : ∃ (C : ℝ), 0 < C ∧ (∀ m, ∥f m∥ ≤ C * ∏ i, ∥m i∥) := f.to_multilinear_map.exists_bound_of_continuous f.2 open real /-- The operator norm of a continuous multilinear map is the inf of all its bounds. -/ def op_norm := Inf {c | 0 ≤ (c : ℝ) ∧ ∀ m, ∥f m∥ ≤ c * ∏ i, ∥m i∥} instance has_op_norm : has_norm (continuous_multilinear_map 𝕜 E₁ E₂) := ⟨op_norm⟩ lemma norm_def : ∥f∥ = Inf {c | 0 ≤ (c : ℝ) ∧ ∀ m, ∥f m∥ ≤ c * ∏ i, ∥m i∥} := rfl -- So that invocations of `real.Inf_le` make sense: we show that the set of -- bounds is nonempty and bounded below. lemma bounds_nonempty {f : continuous_multilinear_map 𝕜 E₁ E₂} : ∃ c, c ∈ {c | 0 ≤ c ∧ ∀ m, ∥f m∥ ≤ c * ∏ i, ∥m i∥} := let ⟨M, hMp, hMb⟩ := f.bound in ⟨M, le_of_lt hMp, hMb⟩ lemma bounds_bdd_below {f : continuous_multilinear_map 𝕜 E₁ E₂} : bdd_below {c | 0 ≤ c ∧ ∀ m, ∥f m∥ ≤ c * ∏ i, ∥m i∥} := ⟨0, λ _ ⟨hn, _⟩, hn⟩ lemma op_norm_nonneg : 0 ≤ ∥f∥ := lb_le_Inf _ bounds_nonempty (λ _ ⟨hx, _⟩, hx) /-- The fundamental property of the operator norm of a continuous multilinear map: `∥f m∥` is bounded by `∥f∥` times the product of the `∥m i∥`. -/ theorem le_op_norm : ∥f m∥ ≤ ∥f∥ * ∏ i, ∥m i∥ := begin have A : 0 ≤ ∏ i, ∥m i∥ := prod_nonneg (λj hj, norm_nonneg _), by_cases h : ∏ i, ∥m i∥ = 0, { rcases prod_eq_zero_iff.1 h with ⟨i, _, hi⟩, rw norm_eq_zero at hi, have : f m = 0 := f.map_coord_zero i hi, rw [this, norm_zero], exact mul_nonneg (op_norm_nonneg f) A }, { have hlt : 0 < ∏ i, ∥m i∥ := lt_of_le_of_ne A (ne.symm h), rw [← div_le_iff hlt], apply (le_Inf _ bounds_nonempty bounds_bdd_below).2, rintro c ⟨_, hc⟩, rw [div_le_iff hlt], apply hc } end lemma ratio_le_op_norm : ∥f m∥ / ∏ i, ∥m i∥ ≤ ∥f∥ := begin have : 0 ≤ ∏ i, ∥m i∥ := prod_nonneg (λj hj, norm_nonneg _), cases eq_or_lt_of_le this with h h, { simp [h.symm, op_norm_nonneg f] }, { rw div_le_iff h, exact le_op_norm f m } end /-- The image of the unit ball under a continuous multilinear map is bounded. -/ lemma unit_le_op_norm (h : ∥m∥ ≤ 1) : ∥f m∥ ≤ ∥f∥ := calc ∥f m∥ ≤ ∥f∥ * ∏ i, ∥m i∥ : f.le_op_norm m ... ≤ ∥f∥ * ∏ i : ι, 1 : mul_le_mul_of_nonneg_left (prod_le_prod (λi hi, norm_nonneg _) (λi hi, le_trans (norm_le_pi_norm _ _) h)) (op_norm_nonneg f) ... = ∥f∥ : by simp /-- If one controls the norm of every `f x`, then one controls the norm of `f`. -/ lemma op_norm_le_bound {M : ℝ} (hMp: 0 ≤ M) (hM : ∀ m, ∥f m∥ ≤ M * ∏ i, ∥m i∥) : ∥f∥ ≤ M := Inf_le _ bounds_bdd_below ⟨hMp, hM⟩ /-- The operator norm satisfies the triangle inequality. -/ theorem op_norm_add_le : ∥f + g∥ ≤ ∥f∥ + ∥g∥ := Inf_le _ bounds_bdd_below ⟨add_nonneg (op_norm_nonneg _) (op_norm_nonneg _), λ x, by { rw add_mul, exact norm_add_le_of_le (le_op_norm _ _) (le_op_norm _ _) }⟩ /-- A continuous linear map is zero iff its norm vanishes. -/ theorem op_norm_zero_iff : ∥f∥ = 0 ↔ f = 0 := begin split, { assume h, ext m, simpa [h] using f.le_op_norm m }, { rintro rfl, apply le_antisymm (op_norm_le_bound 0 le_rfl (λm, _)) (op_norm_nonneg _), simp } end lemma op_norm_smul_le : ∥c • f∥ ≤ ∥c∥ * ∥f∥ := (Inf_le _ bounds_bdd_below ⟨mul_nonneg (norm_nonneg _) (op_norm_nonneg _), λ _, begin erw [norm_smul, mul_assoc], exact mul_le_mul_of_nonneg_left (le_op_norm _ _) (norm_nonneg _) end⟩) lemma op_norm_neg : ∥-f∥ = ∥f∥ := by { rw norm_def, apply congr_arg, ext, simp } /-- Continuous multilinear maps themselves form a normed space with respect to the operator norm. -/ instance to_normed_group : normed_group (continuous_multilinear_map 𝕜 E₁ E₂) := normed_group.of_core _ ⟨op_norm_zero_iff, op_norm_add_le, op_norm_neg⟩ instance to_normed_space : normed_space 𝕜 (continuous_multilinear_map 𝕜 E₁ E₂) := ⟨op_norm_smul_le⟩ /-- The difference `f m₁ - f m₂` is controlled in terms of `∥f∥` and `∥m₁ - m₂∥`, precise version. For a less precise but more usable version, see `norm_image_sub_le_of_bound`. The bound reads `∥f m - f m'∥ ≤ ∥f∥ * ∥m 1 - m' 1∥ * max ∥m 2∥ ∥m' 2∥ * max ∥m 3∥ ∥m' 3∥ * ... * max ∥m n∥ ∥m' n∥ + ...`, where the other terms in the sum are the same products where `1` is replaced by any `i`.-/ lemma norm_image_sub_le_of_bound' (m₁ m₂ : Πi, E₁ i) : ∥f m₁ - f m₂∥ ≤ ∥f∥ * ∑ i, ∏ j, if j = i then ∥m₁ i - m₂ i∥ else max ∥m₁ j∥ ∥m₂ j∥ := f.to_multilinear_map.norm_image_sub_le_of_bound' (norm_nonneg _) f.le_op_norm _ _ /-- The difference `f m₁ - f m₂` is controlled in terms of `∥f∥` and `∥m₁ - m₂∥`, less precise version. For a more precise but less usable version, see `norm_image_sub_le_of_bound'`. The bound is `∥f m - f m'∥ ≤ ∥f∥ * card ι * ∥m - m'∥ * (max ∥m∥ ∥m'∥) ^ (card ι - 1)`.-/ lemma norm_image_sub_le_of_bound (m₁ m₂ : Πi, E₁ i) : ∥f m₁ - f m₂∥ ≤ ∥f∥ * (fintype.card ι) * (max ∥m₁∥ ∥m₂∥) ^ (fintype.card ι - 1) * ∥m₁ - m₂∥ := f.to_multilinear_map.norm_image_sub_le_of_bound (norm_nonneg _) f.le_op_norm _ _ /-- Applying a multilinear map to a vector is continuous in both coordinates. -/ lemma continuous_eval : continuous (λ (p : (continuous_multilinear_map 𝕜 E₁ E₂ × (Πi, E₁ i))), p.1 p.2) := begin apply continuous_iff_continuous_at.2 (λp, _), apply continuous_at_of_locally_lipschitz zero_lt_one ((∥p∥ + 1) * (fintype.card ι) * (∥p∥ + 1) ^ (fintype.card ι - 1) + ∏ i, ∥p.2 i∥) (λq hq, _), have : 0 ≤ (max ∥q.2∥ ∥p.2∥), by simp, have : 0 ≤ ∥p∥ + 1, by simp [le_trans zero_le_one], have A : ∥q∥ ≤ ∥p∥ + 1 := norm_le_of_mem_closed_ball (le_of_lt hq), have : (max ∥q.2∥ ∥p.2∥) ≤ ∥p∥ + 1 := le_trans (max_le_max (norm_snd_le q) (norm_snd_le p)) (by simp [A, -add_comm, zero_le_one]), have : ∀ (i : ι), i ∈ univ → 0 ≤ ∥p.2 i∥ := λ i hi, norm_nonneg _, calc dist (q.1 q.2) (p.1 p.2) ≤ dist (q.1 q.2) (q.1 p.2) + dist (q.1 p.2) (p.1 p.2) : dist_triangle _ _ _ ... = ∥q.1 q.2 - q.1 p.2∥ + ∥q.1 p.2 - p.1 p.2∥ : by rw [dist_eq_norm, dist_eq_norm] ... ≤ ∥q.1∥ * (fintype.card ι) * (max ∥q.2∥ ∥p.2∥) ^ (fintype.card ι - 1) * ∥q.2 - p.2∥ + ∥q.1 - p.1∥ * ∏ i, ∥p.2 i∥ : add_le_add (norm_image_sub_le_of_bound _ _ _) ((q.1 - p.1).le_op_norm p.2) ... ≤ (∥p∥ + 1) * (fintype.card ι) * (∥p∥ + 1) ^ (fintype.card ι - 1) * ∥q - p∥ + ∥q - p∥ * ∏ i, ∥p.2 i∥ : by apply_rules [add_le_add, mul_le_mul, le_refl, le_trans (norm_fst_le q) A, nat.cast_nonneg, mul_nonneg, pow_le_pow_of_le_left, pow_nonneg, norm_snd_le (q - p), norm_nonneg, norm_fst_le (q - p), prod_nonneg] ... = ((∥p∥ + 1) * (fintype.card ι) * (∥p∥ + 1) ^ (fintype.card ι - 1) + (∏ i, ∥p.2 i∥)) * dist q p : by { rw dist_eq_norm, ring } end lemma continuous_eval_left (m : Π i, E₁ i) : continuous (λ (p : (continuous_multilinear_map 𝕜 E₁ E₂)), (p : (Π i, E₁ i) → E₂) m) := continuous_eval.comp (continuous.prod_mk continuous_id continuous_const) lemma has_sum_eval {α : Type*} {p : α → continuous_multilinear_map 𝕜 E₁ E₂} {q : continuous_multilinear_map 𝕜 E₁ E₂} (h : has_sum p q) (m : Π i, E₁ i) : has_sum (λ a, p a m) (q m) := begin dsimp [has_sum] at h ⊢, convert ((continuous_eval_left m).tendsto _).comp h, ext s, simp end open_locale topological_space open filter /-- If the target space is complete, the space of continuous multilinear maps with its norm is also complete. The proof is essentially the same as for the space of continuous linear maps (modulo the addition of `finset.prod` where needed. The duplication could be avoided by deducing the linear case from the multilinear case via a currying isomorphism. However, this would mess up imports, and it is more satisfactory to have the simplest case as a standalone proof. -/ instance [complete_space E₂] : complete_space (continuous_multilinear_map 𝕜 E₁ E₂) := begin have nonneg : ∀ (v : Π i, E₁ i), 0 ≤ ∏ i, ∥v i∥ := λ v, finset.prod_nonneg (λ i hi, norm_nonneg _), -- We show that every Cauchy sequence converges. refine metric.complete_of_cauchy_seq_tendsto (λ f hf, _), -- We now expand out the definition of a Cauchy sequence, rcases cauchy_seq_iff_le_tendsto_0.1 hf with ⟨b, b0, b_bound, b_lim⟩, -- and establish that the evaluation at any point `v : Π i, E₁ i` is Cauchy. have cau : ∀ v, cauchy_seq (λ n, f n v), { assume v, apply cauchy_seq_iff_le_tendsto_0.2 ⟨λ n, b n * ∏ i, ∥v i∥, λ n, _, _, _⟩, { exact mul_nonneg (b0 n) (nonneg v) }, { assume n m N hn hm, rw dist_eq_norm, apply le_trans ((f n - f m).le_op_norm v) _, exact mul_le_mul_of_nonneg_right (b_bound n m N hn hm) (nonneg v) }, { simpa using b_lim.mul tendsto_const_nhds } }, -- We assemble the limits points of those Cauchy sequences -- (which exist as `E₂` is complete) -- into a function which we call `F`. choose F hF using λv, cauchy_seq_tendsto_of_complete (cau v), -- Next, we show that this `F` is multilinear, let Fmult : multilinear_map 𝕜 E₁ E₂ := { to_fun := F, map_add' := λ v i x y, begin have A := hF (function.update v i (x + y)), have B := (hF (function.update v i x)).add (hF (function.update v i y)), simp at A B, exact tendsto_nhds_unique A B end, map_smul' := λ v i c x, begin have A := hF (function.update v i (c • x)), have B := filter.tendsto.smul (@tendsto_const_nhds _ ℕ _ c _) (hF (function.update v i x)), simp at A B, exact tendsto_nhds_unique A B end }, -- and that `F` has norm at most `(b 0 + ∥f 0∥)`. have Fnorm : ∀ v, ∥F v∥ ≤ (b 0 + ∥f 0∥) * ∏ i, ∥v i∥, { assume v, have A : ∀ n, ∥f n v∥ ≤ (b 0 + ∥f 0∥) * ∏ i, ∥v i∥, { assume n, apply le_trans ((f n).le_op_norm _) _, apply mul_le_mul_of_nonneg_right _ (nonneg v), calc ∥f n∥ = ∥(f n - f 0) + f 0∥ : by { congr' 1, abel } ... ≤ ∥f n - f 0∥ + ∥f 0∥ : norm_add_le _ _ ... ≤ b 0 + ∥f 0∥ : begin apply add_le_add_right, simpa [dist_eq_norm] using b_bound n 0 0 (zero_le _) (zero_le _) end }, exact le_of_tendsto (hF v).norm (eventually_of_forall A) }, -- Thus `F` is continuous, and we propose that as the limit point of our original Cauchy sequence. let Fcont := Fmult.mk_continuous _ Fnorm, use Fcont, -- Our last task is to establish convergence to `F` in norm. have : ∀ n, ∥f n - Fcont∥ ≤ b n, { assume n, apply op_norm_le_bound _ (b0 n) (λ v, _), have A : ∀ᶠ m in at_top, ∥(f n - f m) v∥ ≤ b n * ∏ i, ∥v i∥, { refine eventually_at_top.2 ⟨n, λ m hm, _⟩, apply le_trans ((f n - f m).le_op_norm _) _, exact mul_le_mul_of_nonneg_right (b_bound n m n (le_refl _) hm) (nonneg v) }, have B : tendsto (λ m, ∥(f n - f m) v∥) at_top (𝓝 (∥(f n - Fcont) v∥)) := tendsto.norm (tendsto_const_nhds.sub (hF v)), exact le_of_tendsto B A }, erw tendsto_iff_norm_tendsto_zero, exact squeeze_zero (λ n, norm_nonneg _) this b_lim, end end continuous_multilinear_map /-- If a continuous multilinear map is constructed from a multilinear map via the constructor `mk_continuous`, then its norm is bounded by the bound given to the constructor if it is nonnegative. -/ lemma multilinear_map.mk_continuous_norm_le (f : multilinear_map 𝕜 E₁ E₂) {C : ℝ} (hC : 0 ≤ C) (H : ∀ m, ∥f m∥ ≤ C * ∏ i, ∥m i∥) : ∥f.mk_continuous C H∥ ≤ C := continuous_multilinear_map.op_norm_le_bound _ hC (λm, H m) namespace continuous_multilinear_map /-- Given a continuous multilinear map `f` on `n` variables (parameterized by `fin n`) and a subset `s` of `k` of these variables, one gets a new continuous multilinear map on `fin k` by varying these variables, and fixing the other ones equal to a given value `z`. It is denoted by `f.restr s hk z`, where `hk` is a proof that the cardinality of `s` is `k`. The implicit identification between `fin k` and `s` that we use is the canonical (increasing) bijection. -/ def restr {k n : ℕ} (f : (G [×n]→L[𝕜] E₂ : _)) (s : finset (fin n)) (hk : s.card = k) (z : G) : G [×k]→L[𝕜] E₂ := (f.to_multilinear_map.restr s hk z).mk_continuous (∥f∥ * ∥z∥^(n-k)) $ λ v, multilinear_map.restr_norm_le _ _ _ _ f.le_op_norm _ lemma norm_restr {k n : ℕ} (f : G [×n]→L[𝕜] E₂) (s : finset (fin n)) (hk : s.card = k) (z : G) : ∥f.restr s hk z∥ ≤ ∥f∥ * ∥z∥ ^ (n - k) := begin apply multilinear_map.mk_continuous_norm_le, exact mul_nonneg (norm_nonneg _) (pow_nonneg (norm_nonneg _) _) end section variables (𝕜 ι) (A : Type*) [normed_comm_ring A] [normed_algebra 𝕜 A] /-- The continuous multilinear map on `A^ι`, where `A` is a normed commutative algebra over `𝕜`, associating to `m` the product of all the `m i`. See also `continuous_multilinear_map.mk_pi_algebra_fin`. -/ protected def mk_pi_algebra : continuous_multilinear_map 𝕜 (λ i : ι, A) A := @multilinear_map.mk_continuous 𝕜 ι (λ i : ι, A) A _ _ _ _ _ _ _ (multilinear_map.mk_pi_algebra 𝕜 ι A) (if nonempty ι then 1 else ∥(1 : A)∥) $ begin intro m, by_cases hι : nonempty ι, { resetI, simp [hι, norm_prod_le' univ univ_nonempty] }, { simp [eq_empty_of_not_nonempty hι univ, hι] } end variables {A 𝕜 ι} @[simp] lemma mk_pi_algebra_apply (m : ι → A) : continuous_multilinear_map.mk_pi_algebra 𝕜 ι A m = ∏ i, m i := rfl lemma norm_mk_pi_algebra_le [nonempty ι] : ∥continuous_multilinear_map.mk_pi_algebra 𝕜 ι A∥ ≤ 1 := calc ∥continuous_multilinear_map.mk_pi_algebra 𝕜 ι A∥ ≤ if nonempty ι then 1 else ∥(1 : A)∥ : multilinear_map.mk_continuous_norm_le _ (by split_ifs; simp [zero_le_one]) _ ... = _ : if_pos ‹_› lemma norm_mk_pi_algebra_of_empty (h : ¬nonempty ι) : ∥continuous_multilinear_map.mk_pi_algebra 𝕜 ι A∥ = ∥(1 : A)∥ := begin apply le_antisymm, calc ∥continuous_multilinear_map.mk_pi_algebra 𝕜 ι A∥ ≤ if nonempty ι then 1 else ∥(1 : A)∥ : multilinear_map.mk_continuous_norm_le _ (by split_ifs; simp [zero_le_one]) _ ... = ∥(1 : A)∥ : if_neg ‹_›, convert ratio_le_op_norm _ (λ _, 1); [skip, apply_instance], simp [eq_empty_of_not_nonempty h univ] end @[simp] lemma norm_mk_pi_algebra [norm_one_class A] : ∥continuous_multilinear_map.mk_pi_algebra 𝕜 ι A∥ = 1 := begin by_cases hι : nonempty ι, { resetI, refine le_antisymm norm_mk_pi_algebra_le _, convert ratio_le_op_norm _ (λ _, 1); [skip, apply_instance], simp }, { simp [norm_mk_pi_algebra_of_empty hι] } end end section variables (𝕜 n) (A : Type*) [normed_ring A] [normed_algebra 𝕜 A] /-- The continuous multilinear map on `A^n`, where `A` is a normed algebra over `𝕜`, associating to `m` the product of all the `m i`. See also: `multilinear_map.mk_pi_algebra`. -/ protected def mk_pi_algebra_fin : continuous_multilinear_map 𝕜 (λ i : fin n, A) A := @multilinear_map.mk_continuous 𝕜 (fin n) (λ i : fin n, A) A _ _ _ _ _ _ _ (multilinear_map.mk_pi_algebra_fin 𝕜 n A) (nat.cases_on n ∥(1 : A)∥ (λ _, 1)) $ begin intro m, cases n, { simp }, { have : @list.of_fn A n.succ m ≠ [] := by simp, simpa [← fin.prod_of_fn] using list.norm_prod_le' this } end variables {A 𝕜 n} @[simp] lemma mk_pi_algebra_fin_apply (m : fin n → A) : continuous_multilinear_map.mk_pi_algebra_fin 𝕜 n A m = (list.of_fn m).prod := rfl lemma norm_mk_pi_algebra_fin_succ_le : ∥continuous_multilinear_map.mk_pi_algebra_fin 𝕜 n.succ A∥ ≤ 1 := multilinear_map.mk_continuous_norm_le _ zero_le_one _ lemma norm_mk_pi_algebra_fin_le_of_pos (hn : 0 < n) : ∥continuous_multilinear_map.mk_pi_algebra_fin 𝕜 n A∥ ≤ 1 := by cases n; [exact hn.false.elim, exact norm_mk_pi_algebra_fin_succ_le] lemma norm_mk_pi_algebra_fin_zero : ∥continuous_multilinear_map.mk_pi_algebra_fin 𝕜 0 A∥ = ∥(1 : A)∥ := begin refine le_antisymm (multilinear_map.mk_continuous_norm_le _ (norm_nonneg _) _) _, convert ratio_le_op_norm _ (λ _, 1); [simp, apply_instance] end lemma norm_mk_pi_algebra_fin [norm_one_class A] : ∥continuous_multilinear_map.mk_pi_algebra_fin 𝕜 n A∥ = 1 := begin cases n, { simp [norm_mk_pi_algebra_fin_zero] }, { refine le_antisymm norm_mk_pi_algebra_fin_succ_le _, convert ratio_le_op_norm _ (λ _, 1); [skip, apply_instance], simp } end end variables (𝕜 ι) /-- The canonical continuous multilinear map on `𝕜^ι`, associating to `m` the product of all the `m i` (multiplied by a fixed reference element `z` in the target module) -/ protected def mk_pi_field (z : E₂) : continuous_multilinear_map 𝕜 (λ(i : ι), 𝕜) E₂ := @multilinear_map.mk_continuous 𝕜 ι (λ(i : ι), 𝕜) E₂ _ _ _ _ _ _ _ (multilinear_map.mk_pi_ring 𝕜 ι z) (∥z∥) (λ m, by simp only [multilinear_map.mk_pi_ring_apply, norm_smul, normed_field.norm_prod, mul_comm]) variables {𝕜 ι} @[simp] lemma mk_pi_field_apply (z : E₂) (m : ι → 𝕜) : (continuous_multilinear_map.mk_pi_field 𝕜 ι z : (ι → 𝕜) → E₂) m = (∏ i, m i) • z := rfl lemma mk_pi_field_apply_one_eq_self (f : continuous_multilinear_map 𝕜 (λ(i : ι), 𝕜) E₂) : continuous_multilinear_map.mk_pi_field 𝕜 ι (f (λi, 1)) = f := to_multilinear_map_inj f.to_multilinear_map.mk_pi_ring_apply_one_eq_self variables (𝕜 ι E₂) /-- Continuous multilinear maps on `𝕜^n` with values in `E₂` are in bijection with `E₂`, as such a continuous multilinear map is completely determined by its value on the constant vector made of ones. We register this bijection as a linear equivalence in `continuous_multilinear_map.pi_field_equiv_aux`. The continuous linear equivalence is `continuous_multilinear_map.pi_field_equiv`. -/ protected def pi_field_equiv_aux : E₂ ≃ₗ[𝕜] (continuous_multilinear_map 𝕜 (λ(i : ι), 𝕜) E₂) := { to_fun := λ z, continuous_multilinear_map.mk_pi_field 𝕜 ι z, inv_fun := λ f, f (λi, 1), map_add' := λ z z', by { ext m, simp [smul_add] }, map_smul' := λ c z, by { ext m, simp [smul_smul, mul_comm] }, left_inv := λ z, by simp, right_inv := λ f, f.mk_pi_field_apply_one_eq_self } /-- Continuous multilinear maps on `𝕜^n` with values in `E₂` are in bijection with `E₂`, as such a continuous multilinear map is completely determined by its value on the constant vector made of ones. We register this bijection as a continuous linear equivalence in `continuous_multilinear_map.pi_field_equiv`. -/ protected def pi_field_equiv : E₂ ≃L[𝕜] (continuous_multilinear_map 𝕜 (λ(i : ι), 𝕜) E₂) := { continuous_to_fun := begin refine (continuous_multilinear_map.pi_field_equiv_aux 𝕜 ι E₂).to_linear_map.continuous_of_bound (1 : ℝ) (λz, _), rw one_mul, change ∥continuous_multilinear_map.mk_pi_field 𝕜 ι z∥ ≤ ∥z∥, exact multilinear_map.mk_continuous_norm_le _ (norm_nonneg _) _ end, continuous_inv_fun := begin refine (continuous_multilinear_map.pi_field_equiv_aux 𝕜 ι E₂).symm.to_linear_map.continuous_of_bound (1 : ℝ) (λf, _), rw one_mul, change ∥f (λi, 1)∥ ≤ ∥f∥, apply @continuous_multilinear_map.unit_le_op_norm 𝕜 ι (λ (i : ι), 𝕜) E₂ _ _ _ _ _ _ _ f, simp [pi_norm_le_iff zero_le_one, le_refl] end, .. continuous_multilinear_map.pi_field_equiv_aux 𝕜 ι E₂ } end continuous_multilinear_map section currying /-! ### Currying We associate to a continuous multilinear map in `n+1` variables (i.e., based on `fin n.succ`) two curried functions, named `f.curry_left` (which is a continuous linear map on `E 0` taking values in continuous multilinear maps in `n` variables) and `f.curry_right` (which is a continuous multilinear map in `n` variables taking values in continuous linear maps on `E (last n)`). The inverse operations are called `uncurry_left` and `uncurry_right`. We also register continuous linear equiv versions of these correspondences, in `continuous_multilinear_curry_left_equiv` and `continuous_multilinear_curry_right_equiv`. -/ open fin function lemma continuous_linear_map.norm_map_tail_le (f : E 0 →L[𝕜] (continuous_multilinear_map 𝕜 (λ(i : fin n), E i.succ) E₂)) (m : Πi, E i) : ∥f (m 0) (tail m)∥ ≤ ∥f∥ * ∏ i, ∥m i∥ := calc ∥f (m 0) (tail m)∥ ≤ ∥f (m 0)∥ * ∏ i, ∥(tail m) i∥ : (f (m 0)).le_op_norm _ ... ≤ (∥f∥ * ∥m 0∥) * ∏ i, ∥(tail m) i∥ : mul_le_mul_of_nonneg_right (f.le_op_norm _) (prod_nonneg (λi hi, norm_nonneg _)) ... = ∥f∥ * (∥m 0∥ * ∏ i, ∥(tail m) i∥) : by ring ... = ∥f∥ * ∏ i, ∥m i∥ : by { rw prod_univ_succ, refl } lemma continuous_multilinear_map.norm_map_init_le (f : continuous_multilinear_map 𝕜 (λ(i : fin n), E i.cast_succ) (E (last n) →L[𝕜] E₂)) (m : Πi, E i) : ∥f (init m) (m (last n))∥ ≤ ∥f∥ * ∏ i, ∥m i∥ := calc ∥f (init m) (m (last n))∥ ≤ ∥f (init m)∥ * ∥m (last n)∥ : (f (init m)).le_op_norm _ ... ≤ (∥f∥ * (∏ i, ∥(init m) i∥)) * ∥m (last n)∥ : mul_le_mul_of_nonneg_right (f.le_op_norm _) (norm_nonneg _) ... = ∥f∥ * ((∏ i, ∥(init m) i∥) * ∥m (last n)∥) : mul_assoc _ _ _ ... = ∥f∥ * ∏ i, ∥m i∥ : by { rw prod_univ_cast_succ, refl } lemma continuous_multilinear_map.norm_map_cons_le (f : continuous_multilinear_map 𝕜 E E₂) (x : E 0) (m : Π(i : fin n), E i.succ) : ∥f (cons x m)∥ ≤ ∥f∥ * ∥x∥ * ∏ i, ∥m i∥ := calc ∥f (cons x m)∥ ≤ ∥f∥ * ∏ i, ∥cons x m i∥ : f.le_op_norm _ ... = (∥f∥ * ∥x∥) * ∏ i, ∥m i∥ : by { rw prod_univ_succ, simp [mul_assoc] } lemma continuous_multilinear_map.norm_map_snoc_le (f : continuous_multilinear_map 𝕜 E E₂) (m : Π(i : fin n), E i.cast_succ) (x : E (last n)) : ∥f (snoc m x)∥ ≤ ∥f∥ * (∏ i, ∥m i∥) * ∥x∥ := calc ∥f (snoc m x)∥ ≤ ∥f∥ * ∏ i, ∥snoc m x i∥ : f.le_op_norm _ ... = ∥f∥ * (∏ i, ∥m i∥) * ∥x∥ : by { rw prod_univ_cast_succ, simp [mul_assoc] } /-! #### Left currying -/ /-- Given a continuous linear map `f` from `E 0` to continuous multilinear maps on `n` variables, construct the corresponding continuous multilinear map on `n+1` variables obtained by concatenating the variables, given by `m ↦ f (m 0) (tail m)`-/ def continuous_linear_map.uncurry_left (f : E 0 →L[𝕜] (continuous_multilinear_map 𝕜 (λ(i : fin n), E i.succ) E₂)) : continuous_multilinear_map 𝕜 E E₂ := (@linear_map.uncurry_left 𝕜 n E E₂ _ _ _ _ _ (continuous_multilinear_map.to_multilinear_map_linear.comp f.to_linear_map)).mk_continuous (∥f∥) (λm, continuous_linear_map.norm_map_tail_le f m) @[simp] lemma continuous_linear_map.uncurry_left_apply (f : E 0 →L[𝕜] (continuous_multilinear_map 𝕜 (λ(i : fin n), E i.succ) E₂)) (m : Πi, E i) : f.uncurry_left m = f (m 0) (tail m) := rfl /-- Given a continuous multilinear map `f` in `n+1` variables, split the first variable to obtain a continuous linear map into continuous multilinear maps in `n` variables, given by `x ↦ (m ↦ f (cons x m))`. -/ def continuous_multilinear_map.curry_left (f : continuous_multilinear_map 𝕜 E E₂) : E 0 →L[𝕜] (continuous_multilinear_map 𝕜 (λ(i : fin n), E i.succ) E₂) := linear_map.mk_continuous { -- define a linear map into `n` continuous multilinear maps from an `n+1` continuous multilinear -- map to_fun := λx, (f.to_multilinear_map.curry_left x).mk_continuous (∥f∥ * ∥x∥) (f.norm_map_cons_le x), map_add' := λx y, by { ext m, exact f.cons_add m x y }, map_smul' := λc x, by { ext m, exact f.cons_smul m c x } } -- then register its continuity thanks to its boundedness properties. (∥f∥) (λx, multilinear_map.mk_continuous_norm_le _ (mul_nonneg (norm_nonneg _) (norm_nonneg _)) _) @[simp] lemma continuous_multilinear_map.curry_left_apply (f : continuous_multilinear_map 𝕜 E E₂) (x : E 0) (m : Π(i : fin n), E i.succ) : f.curry_left x m = f (cons x m) := rfl @[simp] lemma continuous_linear_map.curry_uncurry_left (f : E 0 →L[𝕜] (continuous_multilinear_map 𝕜 (λ(i : fin n), E i.succ) E₂)) : f.uncurry_left.curry_left = f := begin ext m x, simp only [tail_cons, continuous_linear_map.uncurry_left_apply, continuous_multilinear_map.curry_left_apply], rw cons_zero end @[simp] lemma continuous_multilinear_map.uncurry_curry_left (f : continuous_multilinear_map 𝕜 E E₂) : f.curry_left.uncurry_left = f := by { ext m, simp } @[simp] lemma continuous_multilinear_map.curry_left_norm (f : continuous_multilinear_map 𝕜 E E₂) : ∥f.curry_left∥ = ∥f∥ := begin apply le_antisymm (linear_map.mk_continuous_norm_le _ (norm_nonneg _) _), have : ∥f.curry_left.uncurry_left∥ ≤ ∥f.curry_left∥ := multilinear_map.mk_continuous_norm_le _ (norm_nonneg _) _, simpa end @[simp] lemma continuous_linear_map.uncurry_left_norm (f : E 0 →L[𝕜] (continuous_multilinear_map 𝕜 (λ(i : fin n), E i.succ) E₂)) : ∥f.uncurry_left∥ = ∥f∥ := begin apply le_antisymm (multilinear_map.mk_continuous_norm_le _ (norm_nonneg _) _), have : ∥f.uncurry_left.curry_left∥ ≤ ∥f.uncurry_left∥ := linear_map.mk_continuous_norm_le _ (norm_nonneg _) _, simpa end variables (𝕜 E E₂) /-- The space of continuous multilinear maps on `Π(i : fin (n+1)), E i` is canonically isomorphic to the space of continuous linear maps from `E 0` to the space of continuous multilinear maps on `Π(i : fin n), E i.succ `, by separating the first variable. We register this isomorphism as a linear isomorphism in `continuous_multilinear_curry_left_equiv_aux 𝕜 E E₂`. The algebraic version (without continuity assumption on the maps) is `multilinear_curry_left_equiv 𝕜 E E₂`, and the topological isomorphism (registering additionally that the isomorphism is continuous) is `continuous_multilinear_curry_left_equiv 𝕜 E E₂`. The direct and inverse maps are given by `f.uncurry_left` and `f.curry_left`. Use these unless you need the full framework of linear equivs. -/ def continuous_multilinear_curry_left_equiv_aux : (E 0 →L[𝕜] (continuous_multilinear_map 𝕜 (λ(i : fin n), E i.succ) E₂)) ≃ₗ[𝕜] (continuous_multilinear_map 𝕜 E E₂) := { to_fun := continuous_linear_map.uncurry_left, map_add' := λf₁ f₂, by { ext m, refl }, map_smul' := λc f, by { ext m, refl }, inv_fun := continuous_multilinear_map.curry_left, left_inv := continuous_linear_map.curry_uncurry_left, right_inv := continuous_multilinear_map.uncurry_curry_left } /-- The space of continuous multilinear maps on `Π(i : fin (n+1)), E i` is canonically isomorphic to the space of continuous linear maps from `E 0` to the space of continuous multilinear maps on `Π(i : fin n), E i.succ `, by separating the first variable. We register this isomorphism in `continuous_multilinear_curry_left_equiv 𝕜 E E₂`. The algebraic version (without topology) is given in `multilinear_curry_left_equiv 𝕜 E E₂`. The direct and inverse maps are given by `f.uncurry_left` and `f.curry_left`. Use these unless you need the full framework of continuous linear equivs. -/ def continuous_multilinear_curry_left_equiv : (E 0 →L[𝕜] (continuous_multilinear_map 𝕜 (λ(i : fin n), E i.succ) E₂)) ≃L[𝕜] (continuous_multilinear_map 𝕜 E E₂) := { continuous_to_fun := begin refine (continuous_multilinear_curry_left_equiv_aux 𝕜 E E₂).to_linear_map.continuous_of_bound (1 : ℝ) (λf, le_of_eq _), rw one_mul, exact f.uncurry_left_norm end, continuous_inv_fun := begin refine (continuous_multilinear_curry_left_equiv_aux 𝕜 E E₂).symm.to_linear_map.continuous_of_bound (1 : ℝ) (λf, le_of_eq _), rw one_mul, exact f.curry_left_norm end, .. continuous_multilinear_curry_left_equiv_aux 𝕜 E E₂ } variables {𝕜 E E₂} @[simp] lemma continuous_multilinear_curry_left_equiv_apply (f : E 0 →L[𝕜] (continuous_multilinear_map 𝕜 (λ(i : fin n), E i.succ) E₂)) (v : Π i, E i) : continuous_multilinear_curry_left_equiv 𝕜 E E₂ f v = f (v 0) (tail v) := rfl @[simp] lemma continuous_multilinear_curry_left_equiv_symm_apply (f : continuous_multilinear_map 𝕜 E E₂) (x : E 0) (v : Π (i : fin n), E i.succ) : (continuous_multilinear_curry_left_equiv 𝕜 E E₂).symm f x v = f (cons x v) := rfl /-! #### Right currying -/ /-- Given a continuous linear map `f` from continuous multilinear maps on `n` variables to continuous linear maps on `E 0`, construct the corresponding continuous multilinear map on `n+1` variables obtained by concatenating the variables, given by `m ↦ f (init m) (m (last n))`. -/ def continuous_multilinear_map.uncurry_right (f : continuous_multilinear_map 𝕜 (λ(i : fin n), E i.cast_succ) (E (last n) →L[𝕜] E₂)) : continuous_multilinear_map 𝕜 E E₂ := let f' : multilinear_map 𝕜 (λ(i : fin n), E i.cast_succ) (E (last n) →ₗ[𝕜] E₂) := { to_fun := λ m, (f m).to_linear_map, map_add' := λ m i x y, by { simp, refl }, map_smul' := λ m i c x, by { simp, refl } } in (@multilinear_map.uncurry_right 𝕜 n E E₂ _ _ _ _ _ f').mk_continuous (∥f∥) (λm, f.norm_map_init_le m) @[simp] lemma continuous_multilinear_map.uncurry_right_apply (f : continuous_multilinear_map 𝕜 (λ(i : fin n), E i.cast_succ) (E (last n) →L[𝕜] E₂)) (m : Πi, E i) : f.uncurry_right m = f (init m) (m (last n)) := rfl /-- Given a continuous multilinear map `f` in `n+1` variables, split the last variable to obtain a continuous multilinear map in `n` variables into continuous linear maps, given by `m ↦ (x ↦ f (snoc m x))`. -/ def continuous_multilinear_map.curry_right (f : continuous_multilinear_map 𝕜 E E₂) : continuous_multilinear_map 𝕜 (λ(i : fin n), E i.cast_succ) (E (last n) →L[𝕜] E₂) := let f' : multilinear_map 𝕜 (λ(i : fin n), E i.cast_succ) (E (last n) →L[𝕜] E₂) := { to_fun := λm, (f.to_multilinear_map.curry_right m).mk_continuous (∥f∥ * ∏ i, ∥m i∥) $ λx, f.norm_map_snoc_le m x, map_add' := λ m i x y, by { simp, refl }, map_smul' := λ m i c x, by { simp, refl } } in f'.mk_continuous (∥f∥) (λm, linear_map.mk_continuous_norm_le _ (mul_nonneg (norm_nonneg _) (prod_nonneg (λj hj, norm_nonneg _))) _) @[simp] lemma continuous_multilinear_map.curry_right_apply (f : continuous_multilinear_map 𝕜 E E₂) (m : Π(i : fin n), E i.cast_succ) (x : E (last n)) : f.curry_right m x = f (snoc m x) := rfl @[simp] lemma continuous_multilinear_map.curry_uncurry_right (f : continuous_multilinear_map 𝕜 (λ(i : fin n), E i.cast_succ) (E (last n) →L[𝕜] E₂)) : f.uncurry_right.curry_right = f := begin ext m x, simp only [snoc_last, continuous_multilinear_map.curry_right_apply, continuous_multilinear_map.uncurry_right_apply], rw init_snoc end @[simp] lemma continuous_multilinear_map.uncurry_curry_right (f : continuous_multilinear_map 𝕜 E E₂) : f.curry_right.uncurry_right = f := by { ext m, simp } @[simp] lemma continuous_multilinear_map.curry_right_norm (f : continuous_multilinear_map 𝕜 E E₂) : ∥f.curry_right∥ = ∥f∥ := begin refine le_antisymm (multilinear_map.mk_continuous_norm_le _ (norm_nonneg _) _) _, have : ∥f.curry_right.uncurry_right∥ ≤ ∥f.curry_right∥ := multilinear_map.mk_continuous_norm_le _ (norm_nonneg _) _, simpa end @[simp] lemma continuous_multilinear_map.uncurry_right_norm (f : continuous_multilinear_map 𝕜 (λ(i : fin n), E i.cast_succ) (E (last n) →L[𝕜] E₂)) : ∥f.uncurry_right∥ = ∥f∥ := begin refine le_antisymm (multilinear_map.mk_continuous_norm_le _ (norm_nonneg _) _) _, have : ∥f.uncurry_right.curry_right∥ ≤ ∥f.uncurry_right∥ := multilinear_map.mk_continuous_norm_le _ (norm_nonneg _) _, simpa end variables (𝕜 E E₂) /-- The space of continuous multilinear maps on `Π(i : fin (n+1)), E i` is canonically isomorphic to the space of continuous multilinear maps on `Π(i : fin n), E i.cast_succ` with values in the space of continuous linear maps on `E (last n)`, by separating the last variable. We register this isomorphism as a linear equiv in `continuous_multilinear_curry_right_equiv_aux 𝕜 E E₂`. The algebraic version (without continuity assumption on the maps) is `multilinear_curry_right_equiv 𝕜 E E₂`, and the topological isomorphism (registering additionally that the isomorphism is continuous) is `continuous_multilinear_curry_right_equiv 𝕜 E E₂`. The direct and inverse maps are given by `f.uncurry_right` and `f.curry_right`. Use these unless you need the full framework of linear equivs. -/ def continuous_multilinear_curry_right_equiv_aux : (continuous_multilinear_map 𝕜 (λ(i : fin n), E i.cast_succ) (E (last n) →L[𝕜] E₂)) ≃ₗ[𝕜] (continuous_multilinear_map 𝕜 E E₂) := { to_fun := continuous_multilinear_map.uncurry_right, map_add' := λf₁ f₂, by { ext m, refl }, map_smul' := λc f, by { ext m, refl }, inv_fun := continuous_multilinear_map.curry_right, left_inv := continuous_multilinear_map.curry_uncurry_right, right_inv := continuous_multilinear_map.uncurry_curry_right } /-- The space of continuous multilinear maps on `Π(i : fin (n+1)), E i` is canonically isomorphic to the space of continuous multilinear maps on `Π(i : fin n), E i.cast_succ` with values in the space of continuous linear maps on `E (last n)`, by separating the last variable. We register this isomorphism as a continuous linear equiv in `continuous_multilinear_curry_right_equiv 𝕜 E E₂`. The algebraic version (without topology) is given in `multilinear_curry_right_equiv 𝕜 E E₂`. The direct and inverse maps are given by `f.uncurry_right` and `f.curry_right`. Use these unless you need the full framework of continuous linear equivs. -/ def continuous_multilinear_curry_right_equiv : (continuous_multilinear_map 𝕜 (λ(i : fin n), E i.cast_succ) (E (last n) →L[𝕜] E₂)) ≃L[𝕜] (continuous_multilinear_map 𝕜 E E₂) := { continuous_to_fun := begin refine (continuous_multilinear_curry_right_equiv_aux 𝕜 E E₂).to_linear_map.continuous_of_bound (1 : ℝ) (λf, le_of_eq _), rw one_mul, exact f.uncurry_right_norm end, continuous_inv_fun := begin refine (continuous_multilinear_curry_right_equiv_aux 𝕜 E E₂).symm.to_linear_map.continuous_of_bound (1 : ℝ) (λf, le_of_eq _), rw one_mul, exact f.curry_right_norm end, .. continuous_multilinear_curry_right_equiv_aux 𝕜 E E₂ } variables {𝕜 G E E₂} @[simp] lemma continuous_multilinear_curry_right_equiv_apply (f : (continuous_multilinear_map 𝕜 (λ(i : fin n), E i.cast_succ) (E (last n) →L[𝕜] E₂))) (v : Π i, E i) : (continuous_multilinear_curry_right_equiv 𝕜 E E₂) f v = f (init v) (v (last n)) := rfl @[simp] lemma continuous_multilinear_curry_right_equiv_symm_apply (f : continuous_multilinear_map 𝕜 E E₂) (v : Π (i : fin n), E i.cast_succ) (x : E (last n)) : (continuous_multilinear_curry_right_equiv 𝕜 E E₂).symm f v x = f (snoc v x) := rfl /-! #### Currying with `0` variables The space of multilinear maps with `0` variables is trivial: such a multilinear map is just an arbitrary constant (note that multilinear maps in `0` variables need not map `0` to `0`!). Therefore, the space of continuous multilinear maps on `(fin 0) → G` with values in `E₂` is isomorphic (and even isometric) to `E₂`. As this is the zeroth step in the construction of iterated derivatives, we register this isomorphism. -/ variables {𝕜 G E₂} /-- Associating to a continuous multilinear map in `0` variables the unique value it takes. -/ def continuous_multilinear_map.uncurry0 (f : continuous_multilinear_map 𝕜 (λ (i : fin 0), G) E₂) : E₂ := f 0 variables (𝕜 G) /-- Associating to an element `x` of a vector space `E₂` the continuous multilinear map in `0` variables taking the (unique) value `x` -/ def continuous_multilinear_map.curry0 (x : E₂) : continuous_multilinear_map 𝕜 (λ (i : fin 0), G) E₂ := { to_fun := λm, x, map_add' := λ m i, fin.elim0 i, map_smul' := λ m i, fin.elim0 i, cont := continuous_const } variable {G} @[simp] lemma continuous_multilinear_map.curry0_apply (x : E₂) (m : (fin 0) → G) : (continuous_multilinear_map.curry0 𝕜 G x : ((fin 0) → G) → E₂) m = x := rfl variable {𝕜} @[simp] lemma continuous_multilinear_map.uncurry0_apply (f : continuous_multilinear_map 𝕜 (λ (i : fin 0), G) E₂) : f.uncurry0 = f 0 := rfl @[simp] lemma continuous_multilinear_map.apply_zero_curry0 (f : continuous_multilinear_map 𝕜 (λ (i : fin 0), G) E₂) {x : fin 0 → G} : continuous_multilinear_map.curry0 𝕜 G (f x) = f := by { ext m, simp [(subsingleton.elim _ _ : x = m)] } lemma continuous_multilinear_map.uncurry0_curry0 (f : continuous_multilinear_map 𝕜 (λ (i : fin 0), G) E₂) : continuous_multilinear_map.curry0 𝕜 G (f.uncurry0) = f := by simp variables (𝕜 G) @[simp] lemma continuous_multilinear_map.curry0_uncurry0 (x : E₂) : (continuous_multilinear_map.curry0 𝕜 G x).uncurry0 = x := rfl @[simp] lemma continuous_multilinear_map.uncurry0_norm (x : E₂) : ∥continuous_multilinear_map.curry0 𝕜 G x∥ = ∥x∥ := begin apply le_antisymm, { exact continuous_multilinear_map.op_norm_le_bound _ (norm_nonneg _) (λm, by simp) }, { simpa using (continuous_multilinear_map.curry0 𝕜 G x).le_op_norm 0 } end variables {𝕜 G} @[simp] lemma continuous_multilinear_map.fin0_apply_norm (f : continuous_multilinear_map 𝕜 (λ (i : fin 0), G) E₂) {x : fin 0 → G} : ∥f x∥ = ∥f∥ := begin have : x = 0 := subsingleton.elim _ _, subst this, refine le_antisymm (by simpa using f.le_op_norm 0) _, have : ∥continuous_multilinear_map.curry0 𝕜 G (f.uncurry0)∥ ≤ ∥f.uncurry0∥ := continuous_multilinear_map.op_norm_le_bound _ (norm_nonneg _) (λm, by simp [-continuous_multilinear_map.apply_zero_curry0]), simpa end lemma continuous_multilinear_map.curry0_norm (f : continuous_multilinear_map 𝕜 (λ (i : fin 0), G) E₂) : ∥f.uncurry0∥ = ∥f∥ := by simp variables (𝕜 G E₂) /-- The linear isomorphism between elements of a normed space, and continuous multilinear maps in `0` variables with values in this normed space. The continuous version is given in `continuous_multilinear_curry_fin0`. The direct and inverse maps are `uncurry0` and `curry0`. Use these unless you need the full framework of linear equivs. -/ def continuous_multilinear_curry_fin0_aux : (continuous_multilinear_map 𝕜 (λ (i : fin 0), G) E₂) ≃ₗ[𝕜] E₂ := { to_fun := λf, continuous_multilinear_map.uncurry0 f, inv_fun := λf, continuous_multilinear_map.curry0 𝕜 G f, map_add' := λf g, rfl, map_smul' := λc f, rfl, left_inv := continuous_multilinear_map.uncurry0_curry0, right_inv := continuous_multilinear_map.curry0_uncurry0 𝕜 G } /-- The continuous linear isomorphism between elements of a normed space, and continuous multilinear maps in `0` variables with values in this normed space. The direct and inverse maps are `uncurry0` and `curry0`. Use these unless you need the full framework of continuous linear equivs. -/ def continuous_multilinear_curry_fin0 : (continuous_multilinear_map 𝕜 (λ (i : fin 0), G) E₂) ≃L[𝕜] E₂ := { continuous_to_fun := begin change continuous (λ (f : continuous_multilinear_map 𝕜 (λ (i : fin 0), G) E₂), (f : ((fin 0) → G) → E₂) 0), exact continuous_multilinear_map.continuous_eval.comp (continuous_id.prod_mk continuous_const) end, continuous_inv_fun := begin refine (continuous_multilinear_curry_fin0_aux 𝕜 G E₂).symm.to_linear_map.continuous_of_bound (1 : ℝ) (λf, le_of_eq _), rw one_mul, exact continuous_multilinear_map.uncurry0_norm _ _ _ end, .. continuous_multilinear_curry_fin0_aux 𝕜 G E₂ } variables {𝕜 G E₂} @[simp] lemma continuous_multilinear_curry_fin0_apply (f : (continuous_multilinear_map 𝕜 (λ (i : fin 0), G) E₂)) : continuous_multilinear_curry_fin0 𝕜 G E₂ f = f 0 := rfl @[simp] lemma continuous_multilinear_curry_fin0_symm_apply (x : E₂) (v : (fin 0) → G) : (continuous_multilinear_curry_fin0 𝕜 G E₂).symm x v = x := rfl /-! #### With 1 variable -/ variables (𝕜 G E₂) /-- Continuous multilinear maps from `G^1` to `E₂` are isomorphic with continuous linear maps from `G` to `E₂`. -/ def continuous_multilinear_curry_fin1 : (continuous_multilinear_map 𝕜 (λ (i : fin 1), G) E₂) ≃L[𝕜] (G →L[𝕜] E₂) := (continuous_multilinear_curry_right_equiv 𝕜 (λ (i : fin 1), G) E₂).symm.trans (continuous_multilinear_curry_fin0 𝕜 G (G →L[𝕜] E₂)) variables {𝕜 G E₂} @[simp] lemma continuous_multilinear_curry_fin1_apply (f : (continuous_multilinear_map 𝕜 (λ (i : fin 1), G) E₂)) (x : G) : continuous_multilinear_curry_fin1 𝕜 G E₂ f x = f (fin.snoc 0 x) := rfl @[simp] lemma continuous_multilinear_curry_fin1_symm_apply (f : G →L[𝕜] E₂) (v : (fin 1) → G) : (continuous_multilinear_curry_fin1 𝕜 G E₂).symm f v = f (v 0) := rfl end currying
d258820cd47c61097d0893f370289c5affa931a9
3d2a7f1582fe5bae4d0bdc2fe86e997521239a65
/spatial-reasoning/spatial-reasoning-problem-08.lean
ca2f0c11c6360501b47caedb5989d4e16eb94be6
[]
no_license
own-pt/common-sense-lean
e4fa643ae010459de3d1bf673be7cbc7062563c9
f672210aecb4172f5bae265e43e6867397e13b1c
refs/heads/master
1,622,065,660,261
1,589,487,533,000
1,589,487,533,000
254,167,782
3
2
null
1,589,487,535,000
1,586,370,214,000
Lean
UTF-8
Lean
false
false
224
lean
/- Spatial Reasoning Problem 08 -/ /- It can be found at: SpatialQs.txt -/ /- (8) Bob and Jane are at the mouth of a tunnel. Bob travels through the tunnel. Can Bob be closer to Jane than the length of the tunnel? -/
7a25f28b9a5042f0fb6f5252ede79c263f6b344c
d1a52c3f208fa42c41df8278c3d280f075eb020c
/src/Init/Control/Option.lean
5a36ff70141924d3dacf4b44f44110f724ddb9c3
[ "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
2,308
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.Data.Option.Basic import Init.Control.Basic import Init.Control.Except universe u v instance {α} : ToBool (Option α) := ⟨Option.toBool⟩ def OptionT (m : Type u → Type v) (α : Type u) : Type v := m (Option α) @[inline] def OptionT.run {m : Type u → Type v} {α : Type u} (x : OptionT m α) : m (Option α) := x namespace OptionT variable {m : Type u → Type v} [Monad m] {α β : Type u} protected def mk (x : m (Option α)) : OptionT m α := x @[inline] protected def bind (x : OptionT m α) (f : α → OptionT m β) : OptionT m β := OptionT.mk do match (← x) with | some a => f a | none => pure none @[inline] protected def pure (a : α) : OptionT m α := OptionT.mk do pure (some a) instance : Monad (OptionT m) where pure := OptionT.pure bind := OptionT.bind @[inline] protected def orElse (x : OptionT m α) (y : Unit → OptionT m α) : OptionT m α := OptionT.mk do match (← x) with | some a => pure (some a) | _ => y () @[inline] protected def fail : OptionT m α := OptionT.mk do pure none instance : Alternative (OptionT m) where failure := OptionT.fail orElse := OptionT.orElse @[inline] protected def lift (x : m α) : OptionT m α := OptionT.mk do return some (← x) instance : MonadLift m (OptionT m) := ⟨OptionT.lift⟩ instance : MonadFunctor m (OptionT m) := ⟨fun f x => f x⟩ @[inline] protected def tryCatch (x : OptionT m α) (handle : Unit → OptionT m α) : OptionT m α := OptionT.mk do let some a ← x | handle () pure a instance : MonadExceptOf Unit (OptionT m) where throw := fun _ => OptionT.fail tryCatch := OptionT.tryCatch instance (ε : Type u) [Monad m] [MonadExceptOf ε m] : MonadExceptOf ε (OptionT m) where throw e := OptionT.mk <| throwThe ε e tryCatch x handle := OptionT.mk <| tryCatchThe ε x handle end OptionT abbrev OptionM (α : Type u) := OptionT Id α abbrev OptionM.run (x : OptionM α) : Option α := x instance [Monad m] : MonadControl m (OptionT m) where stM := Option liftWith f := liftM <| f fun x => x.run restoreM x := x
32e6f291a1f5612326c761b07f5685deee0ae8d6
c777c32c8e484e195053731103c5e52af26a25d1
/src/model_theory/satisfiability.lean
1c1a693e6e45b208c0b90eefa700b334678fbd2b
[ "Apache-2.0" ]
permissive
kbuzzard/mathlib
2ff9e85dfe2a46f4b291927f983afec17e946eb8
58537299e922f9c77df76cb613910914a479c1f7
refs/heads/master
1,685,313,702,744
1,683,974,212,000
1,683,974,212,000
128,185,277
1
0
null
1,522,920,600,000
1,522,920,600,000
null
UTF-8
Lean
false
false
28,055
lean
/- Copyright (c) 2021 Aaron Anderson. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Aaron Anderson -/ import model_theory.ultraproducts import model_theory.bundled import model_theory.skolem /-! # First-Order Satisfiability This file deals with the satisfiability of first-order theories, as well as equivalence over them. ## Main Definitions * `first_order.language.Theory.is_satisfiable`: `T.is_satisfiable` indicates that `T` has a nonempty model. * `first_order.language.Theory.is_finitely_satisfiable`: `T.is_finitely_satisfiable` indicates that every finite subset of `T` is satisfiable. * `first_order.language.Theory.is_complete`: `T.is_complete` indicates that `T` is satisfiable and models each sentence or its negation. * `first_order.language.Theory.semantically_equivalent`: `T.semantically_equivalent φ ψ` indicates that `φ` and `ψ` are equivalent formulas or sentences in models of `T`. * `cardinal.categorical`: A theory is `κ`-categorical if all models of size `κ` are isomorphic. ## Main Results * The Compactness Theorem, `first_order.language.Theory.is_satisfiable_iff_is_finitely_satisfiable`, shows that a theory is satisfiable iff it is finitely satisfiable. * `first_order.language.complete_theory.is_complete`: The complete theory of a structure is complete. * `first_order.language.Theory.exists_large_model_of_infinite_model` shows that any theory with an infinite model has arbitrarily large models. * `first_order.language.Theory.exists_elementary_embedding_card_eq`: The Upward Löwenheim–Skolem Theorem: If `κ` is a cardinal greater than the cardinalities of `L` and an infinite `L`-structure `M`, then `M` has an elementary extension of cardinality `κ`. ## Implementation Details * Satisfiability of an `L.Theory` `T` is defined in the minimal universe containing all the symbols of `L`. By Löwenheim-Skolem, this is equivalent to satisfiability in any universe. -/ universes u v w w' open cardinal category_theory open_locale cardinal first_order namespace first_order namespace language variables {L : language.{u v}} {T : L.Theory} {α : Type w} {n : ℕ} namespace Theory variable (T) /-- A theory is satisfiable if a structure models it. -/ def is_satisfiable : Prop := nonempty (Model.{u v (max u v)} T) /-- A theory is finitely satisfiable if all of its finite subtheories are satisfiable. -/ def is_finitely_satisfiable : Prop := ∀ (T0 : finset L.sentence), (T0 : L.Theory) ⊆ T → (T0 : L.Theory).is_satisfiable variables {T} {T' : L.Theory} lemma model.is_satisfiable (M : Type w) [n : nonempty M] [S : L.Structure M] [M ⊨ T] : T.is_satisfiable := ⟨((⊥ : substructure _ (Model.of T M)).elementary_skolem₁_reduct.to_Model T).shrink⟩ lemma is_satisfiable.mono (h : T'.is_satisfiable) (hs : T ⊆ T') : T.is_satisfiable := ⟨(Theory.model.mono (Model.is_model h.some) hs).bundled⟩ lemma is_satisfiable_empty (L : language.{u v}) : is_satisfiable (∅ : L.Theory) := ⟨default⟩ lemma is_satisfiable_of_is_satisfiable_on_Theory {L' : language.{w w'}} (φ : L →ᴸ L') (h : (φ.on_Theory T).is_satisfiable) : T.is_satisfiable := model.is_satisfiable (h.some.reduct φ) lemma is_satisfiable_on_Theory_iff {L' : language.{w w'}} {φ : L →ᴸ L'} (h : φ.injective) : (φ.on_Theory T).is_satisfiable ↔ T.is_satisfiable := begin classical, refine ⟨is_satisfiable_of_is_satisfiable_on_Theory φ, λ h', _⟩, haveI : inhabited (h'.some) := classical.inhabited_of_nonempty', exact model.is_satisfiable (h'.some.default_expansion h), end lemma is_satisfiable.is_finitely_satisfiable (h : T.is_satisfiable) : T.is_finitely_satisfiable := λ _, h.mono /-- The Compactness Theorem of first-order logic: A theory is satisfiable if and only if it is finitely satisfiable. -/ theorem is_satisfiable_iff_is_finitely_satisfiable {T : L.Theory} : T.is_satisfiable ↔ T.is_finitely_satisfiable := ⟨Theory.is_satisfiable.is_finitely_satisfiable, λ h, begin classical, set M : Π (T0 : finset T), Type (max u v) := λ T0, (h (T0.map (function.embedding.subtype (λ x, x ∈ T))) T0.map_subtype_subset).some with hM, let M' := filter.product ↑(ultrafilter.of (filter.at_top : filter (finset T))) M, haveI h' : M' ⊨ T, { refine ⟨λ φ hφ, _⟩, rw ultraproduct.sentence_realize, refine filter.eventually.filter_mono (ultrafilter.of_le _) (filter.eventually_at_top.2 ⟨{⟨φ, hφ⟩}, λ s h', Theory.realize_sentence_of_mem (s.map (function.embedding.subtype (λ x, x ∈ T))) _⟩), simp only [finset.coe_map, function.embedding.coe_subtype, set.mem_image, finset.mem_coe, subtype.exists, subtype.coe_mk, exists_and_distrib_right, exists_eq_right], exact ⟨hφ, h' (finset.mem_singleton_self _)⟩ }, exact ⟨Model.of T M'⟩, end⟩ theorem is_satisfiable_directed_union_iff {ι : Type*} [nonempty ι] {T : ι → L.Theory} (h : directed (⊆) T) : Theory.is_satisfiable (⋃ i, T i) ↔ ∀ i, (T i).is_satisfiable := begin refine ⟨λ h' i, h'.mono (set.subset_Union _ _), λ h', _⟩, rw [is_satisfiable_iff_is_finitely_satisfiable, is_finitely_satisfiable], intros T0 hT0, obtain ⟨i, hi⟩ := h.exists_mem_subset_of_finset_subset_bUnion hT0, exact (h' i).mono hi, end theorem is_satisfiable_union_distinct_constants_theory_of_card_le (T : L.Theory) (s : set α) (M : Type w') [nonempty M] [L.Structure M] [M ⊨ T] (h : cardinal.lift.{w'} (# s) ≤ cardinal.lift.{w} (# M)) : ((L.Lhom_with_constants α).on_Theory T ∪ L.distinct_constants_theory s).is_satisfiable := begin haveI : inhabited M := classical.inhabited_of_nonempty infer_instance, rw [cardinal.lift_mk_le'] at h, letI : (constants_on α).Structure M := constants_on.Structure (function.extend coe h.some default), haveI : M ⊨ (L.Lhom_with_constants α).on_Theory T ∪ L.distinct_constants_theory s, { refine ((Lhom.on_Theory_model _ _).2 infer_instance).union _, rw [model_distinct_constants_theory], refine λ a as b bs ab, _, rw [← subtype.coe_mk a as, ← subtype.coe_mk b bs, ← subtype.ext_iff], exact h.some.injective ((subtype.coe_injective.extend_apply h.some default ⟨a, as⟩).symm.trans (ab.trans (subtype.coe_injective.extend_apply h.some default ⟨b, bs⟩))), }, exact model.is_satisfiable M, end theorem is_satisfiable_union_distinct_constants_theory_of_infinite (T : L.Theory) (s : set α) (M : Type w') [L.Structure M] [M ⊨ T] [infinite M] : ((L.Lhom_with_constants α).on_Theory T ∪ L.distinct_constants_theory s).is_satisfiable := begin classical, rw [distinct_constants_theory_eq_Union, set.union_Union, is_satisfiable_directed_union_iff], { exact λ t, is_satisfiable_union_distinct_constants_theory_of_card_le T _ M ((lift_le_aleph_0.2 ((finset_card_lt_aleph_0 _).le)).trans (aleph_0_le_lift.2 (aleph_0_le_mk M))) }, { refine (monotone_const.union (monotone_distinct_constants_theory.comp _)).directed_le, simp only [finset.coe_map, function.embedding.coe_subtype], exact set.monotone_image.comp (λ _ _, finset.coe_subset.2) } end /-- Any theory with an infinite model has arbitrarily large models. -/ lemma exists_large_model_of_infinite_model (T : L.Theory) (κ : cardinal.{w}) (M : Type w') [L.Structure M] [M ⊨ T] [infinite M] : ∃ (N : Model.{_ _ (max u v w)} T), cardinal.lift.{max u v w} κ ≤ # N := begin obtain ⟨N⟩ := is_satisfiable_union_distinct_constants_theory_of_infinite T (set.univ : set κ.out) M, refine ⟨(N.is_model.mono (set.subset_union_left _ _)).bundled.reduct _, _⟩, haveI : N ⊨ distinct_constants_theory _ _ := N.is_model.mono (set.subset_union_right _ _), simp only [Model.reduct_carrier, coe_of, Model.carrier_eq_coe], refine trans (lift_le.2 (le_of_eq (cardinal.mk_out κ).symm)) _, rw [← mk_univ], refine (card_le_of_model_distinct_constants_theory L set.univ N).trans (lift_le.1 _), rw lift_lift, end lemma is_satisfiable_Union_iff_is_satisfiable_Union_finset {ι : Type*} (T : ι → L.Theory) : is_satisfiable (⋃ i, T i) ↔ ∀ (s : finset ι), is_satisfiable (⋃ (i ∈ s), T i) := begin classical, refine ⟨λ h s, h.mono (set.Union_mono (λ _, set.Union_subset_iff.2 (λ _, refl _))), λ h, _⟩, rw is_satisfiable_iff_is_finitely_satisfiable, intros s hs, rw set.Union_eq_Union_finset at hs, obtain ⟨t, ht⟩ := directed.exists_mem_subset_of_finset_subset_bUnion _ hs, { exact (h t).mono ht }, { exact (monotone.directed_le (λ t1 t2 h, set.Union_mono (λ _, set.Union_mono' (λ h1, ⟨h h1, refl _⟩)))) }, end end Theory variables (L) /-- A version of The Downward Löwenheim–Skolem theorem where the structure `N` elementarily embeds into `M`, but is not by type a substructure of `M`, and thus can be chosen to belong to the universe of the cardinal `κ`. -/ lemma exists_elementary_embedding_card_eq_of_le (M : Type w') [L.Structure M] [nonempty M] (κ : cardinal.{w}) (h1 : ℵ₀ ≤ κ) (h2 : lift.{w} L.card ≤ cardinal.lift.{max u v} κ) (h3 : lift.{w'} κ ≤ cardinal.lift.{w} (# M)) : ∃ (N : bundled L.Structure), nonempty (N ↪ₑ[L] M) ∧ # N = κ := begin obtain ⟨S, _, hS⟩ := exists_elementary_substructure_card_eq L ∅ κ h1 (by simp) h2 h3, haveI : small.{w} S, { rw [← lift_inj.{_ (w + 1)}, lift_lift, lift_lift] at hS, exact small_iff_lift_mk_lt_univ.2 (lt_of_eq_of_lt hS κ.lift_lt_univ') }, refine ⟨(equiv_shrink S).bundled_induced L, ⟨S.subtype.comp (equiv.bundled_induced_equiv L _).symm.to_elementary_embedding⟩, lift_inj.1 (trans _ hS)⟩, simp only [equiv.bundled_induced_α, lift_mk_shrink'], end /-- The Upward Löwenheim–Skolem Theorem: If `κ` is a cardinal greater than the cardinalities of `L` and an infinite `L`-structure `M`, then `M` has an elementary extension of cardinality `κ`. -/ theorem exists_elementary_embedding_card_eq_of_ge (M : Type w') [L.Structure M] [iM : infinite M] (κ : cardinal.{w}) (h1 : cardinal.lift.{w} L.card ≤ cardinal.lift.{max u v} κ) (h2 : cardinal.lift.{w} (# M) ≤ cardinal.lift.{w'} κ) : ∃ (N : bundled L.Structure), nonempty (M ↪ₑ[L] N) ∧ # N = κ := begin obtain ⟨N0, hN0⟩ := (L.elementary_diagram M).exists_large_model_of_infinite_model κ M, let f0 := elementary_embedding.of_models_elementary_diagram L M N0, rw [← lift_le.{(max w w') (max u v)}, lift_lift, lift_lift] at h2, obtain ⟨N, ⟨NN0⟩, hN⟩ := exists_elementary_embedding_card_eq_of_le (L[[M]]) N0 κ (aleph_0_le_lift.1 ((aleph_0_le_lift.2 (aleph_0_le_mk M)).trans h2)) _ (hN0.trans _), { letI := (Lhom_with_constants L M).reduct N, haveI h : N ⊨ L.elementary_diagram M := (NN0.Theory_model_iff (L.elementary_diagram M)).2 infer_instance, refine ⟨bundled.of N, ⟨_⟩, hN⟩, apply elementary_embedding.of_models_elementary_diagram L M N, }, { simp only [card_with_constants, lift_add, lift_lift], rw [add_comm, add_eq_max (aleph_0_le_lift.2 (infinite_iff.1 iM)), max_le_iff], rw [← lift_le.{_ w'}, lift_lift, lift_lift] at h1, exact ⟨h2, h1⟩, }, { rw [← lift_umax', lift_id] }, end /-- The Löwenheim–Skolem Theorem: If `κ` is a cardinal greater than the cardinalities of `L` and an infinite `L`-structure `M`, then there is an elementary embedding in the appropriate direction between then `M` and a structure of cardinality `κ`. -/ theorem exists_elementary_embedding_card_eq (M : Type w') [L.Structure M] [iM : infinite M] (κ : cardinal.{w}) (h1 : ℵ₀ ≤ κ) (h2 : lift.{w} L.card ≤ cardinal.lift.{max u v} κ) : ∃ (N : bundled L.Structure), (nonempty (N ↪ₑ[L] M) ∨ nonempty (M ↪ₑ[L] N)) ∧ # N = κ := begin cases le_or_gt (lift.{w'} κ) (cardinal.lift.{w} (# M)), { obtain ⟨N, hN1, hN2⟩ := exists_elementary_embedding_card_eq_of_le L M κ h1 h2 h, exact ⟨N, or.inl hN1, hN2⟩ }, { obtain ⟨N, hN1, hN2⟩ := exists_elementary_embedding_card_eq_of_ge L M κ h2 (le_of_lt h), exact ⟨N, or.inr hN1, hN2⟩ } end /-- A consequence of the Löwenheim–Skolem Theorem: If `κ` is a cardinal greater than the cardinalities of `L` and an infinite `L`-structure `M`, then there is a structure of cardinality `κ` elementarily equivalent to `M`. -/ lemma exists_elementarily_equivalent_card_eq (M : Type w') [L.Structure M] [infinite M] (κ : cardinal.{w}) (h1 : ℵ₀ ≤ κ) (h2 : lift.{w} L.card ≤ cardinal.lift.{max u v} κ) : ∃ (N : category_theory.bundled L.Structure), M ≅[L] N ∧ # N = κ := begin obtain ⟨N, (NM | MN), hNκ⟩ := exists_elementary_embedding_card_eq L M κ h1 h2, { exact ⟨N, NM.some.elementarily_equivalent.symm, hNκ⟩ }, { exact ⟨N, MN.some.elementarily_equivalent, hNκ⟩ } end variable {L} namespace Theory theorem exists_model_card_eq (h : ∃ (M : Model.{u v (max u v)} T), infinite M) (κ : cardinal.{w}) (h1 : ℵ₀ ≤ κ) (h2 : cardinal.lift.{w} L.card ≤ cardinal.lift.{max u v} κ) : ∃ (N : Model.{u v w} T), # N = κ := begin casesI h with M MI, obtain ⟨N, hN, rfl⟩ := exists_elementarily_equivalent_card_eq L M κ h1 h2, haveI : nonempty N := hN.nonempty, exact ⟨hN.Theory_model.bundled, rfl⟩, end variable (T) /-- A theory models a (bounded) formula when any of its nonempty models realizes that formula on all inputs.-/ def models_bounded_formula (φ : L.bounded_formula α n) : Prop := ∀ (M : Model.{u v (max u v)} T) (v : α → M) (xs : fin n → M), φ.realize v xs -- input using \|= or \vDash, but not using \models infix (name := models_bounded_formula) ` ⊨ `:51 := models_bounded_formula variable {T} lemma models_formula_iff {φ : L.formula α} : T ⊨ φ ↔ ∀ (M : Model.{u v (max u v)} T) (v : α → M), φ.realize v := forall_congr (λ M, forall_congr (λ v, unique.forall_iff)) lemma models_sentence_iff {φ : L.sentence} : T ⊨ φ ↔ ∀ (M : Model.{u v (max u v)} T), M ⊨ φ := models_formula_iff.trans (forall_congr (λ M, unique.forall_iff)) lemma models_sentence_of_mem {φ : L.sentence} (h : φ ∈ T) : T ⊨ φ := models_sentence_iff.2 (λ _, realize_sentence_of_mem T h) lemma models_iff_not_satisfiable (φ : L.sentence) : T ⊨ φ ↔ ¬ is_satisfiable (T ∪ {φ.not}) := begin rw [models_sentence_iff, is_satisfiable], refine ⟨λ h1 h2, (sentence.realize_not _).1 (realize_sentence_of_mem (T ∪ {formula.not φ}) (set.subset_union_right _ _ (set.mem_singleton _))) (h1 (h2.some.subtheory_Model (set.subset_union_left _ _))), λ h M, _⟩, contrapose! h, rw ← sentence.realize_not at h, refine ⟨{ carrier := M, is_model := ⟨λ ψ hψ, hψ.elim (realize_sentence_of_mem _) (λ h', _)⟩, }⟩, rw set.mem_singleton_iff.1 h', exact h, end lemma models_bounded_formula.realize_sentence {φ : L.sentence} (h : T ⊨ φ) (M : Type*) [L.Structure M] [M ⊨ T] [nonempty M] : M ⊨ φ := begin rw models_iff_not_satisfiable at h, contrapose! h, haveI : M ⊨ (T ∪ {formula.not φ}), { simp only [set.union_singleton, model_iff, set.mem_insert_iff, forall_eq_or_imp, sentence.realize_not], rw ← model_iff, exact ⟨h, infer_instance⟩ }, exact model.is_satisfiable M, end /-- A theory is complete when it is satisfiable and models each sentence or its negation. -/ def is_complete (T : L.Theory) : Prop := T.is_satisfiable ∧ ∀ (φ : L.sentence), (T ⊨ φ) ∨ (T ⊨ φ.not) namespace is_complete lemma models_not_iff (h : T.is_complete) (φ : L.sentence) : T ⊨ φ.not ↔ ¬ T ⊨ φ := begin cases h.2 φ with hφ hφn, { simp only [hφ, not_true, iff_false], rw [models_sentence_iff, not_forall], refine ⟨h.1.some, _⟩, simp only [sentence.realize_not, not_not], exact models_sentence_iff.1 hφ _ }, { simp only [hφn, true_iff], intro hφ, rw models_sentence_iff at *, exact hφn h.1.some (hφ _) } end lemma realize_sentence_iff (h : T.is_complete) (φ : L.sentence) (M : Type*) [L.Structure M] [M ⊨ T] [nonempty M] : M ⊨ φ ↔ T ⊨ φ := begin cases h.2 φ with hφ hφn, { exact iff_of_true (hφ.realize_sentence M) hφ }, { exact iff_of_false ((sentence.realize_not M).1 (hφn.realize_sentence M)) ((h.models_not_iff φ).1 hφn), } end end is_complete /-- A theory is maximal when it is satisfiable and contains each sentence or its negation. Maximal theories are complete. -/ def is_maximal (T : L.Theory) : Prop := T.is_satisfiable ∧ ∀ (φ : L.sentence), φ ∈ T ∨ φ.not ∈ T lemma is_maximal.is_complete (h : T.is_maximal) : T.is_complete := h.imp_right (forall_imp (λ _, or.imp models_sentence_of_mem models_sentence_of_mem)) lemma is_maximal.mem_or_not_mem (h : T.is_maximal) (φ : L.sentence) : φ ∈ T ∨ φ.not ∈ T := h.2 φ lemma is_maximal.mem_of_models (h : T.is_maximal) {φ : L.sentence} (hφ : T ⊨ φ) : φ ∈ T := begin refine (h.mem_or_not_mem φ).resolve_right (λ con, _), rw [models_iff_not_satisfiable, set.union_singleton, set.insert_eq_of_mem con] at hφ, exact hφ h.1, end lemma is_maximal.mem_iff_models (h : T.is_maximal) (φ : L.sentence) : φ ∈ T ↔ T ⊨ φ := ⟨models_sentence_of_mem, h.mem_of_models⟩ /-- Two (bounded) formulas are semantically equivalent over a theory `T` when they have the same interpretation in every model of `T`. (This is also known as logical equivalence, which also has a proof-theoretic definition.) -/ def semantically_equivalent (T : L.Theory) (φ ψ : L.bounded_formula α n) : Prop := T ⊨ φ.iff ψ @[refl] lemma semantically_equivalent.refl (φ : L.bounded_formula α n) : T.semantically_equivalent φ φ := λ M v xs, by rw bounded_formula.realize_iff instance : is_refl (L.bounded_formula α n) T.semantically_equivalent := ⟨semantically_equivalent.refl⟩ @[symm] lemma semantically_equivalent.symm {φ ψ : L.bounded_formula α n} (h : T.semantically_equivalent φ ψ) : T.semantically_equivalent ψ φ := λ M v xs, begin rw [bounded_formula.realize_iff, iff.comm, ← bounded_formula.realize_iff], exact h M v xs, end @[trans] lemma semantically_equivalent.trans {φ ψ θ : L.bounded_formula α n} (h1 : T.semantically_equivalent φ ψ) (h2 : T.semantically_equivalent ψ θ) : T.semantically_equivalent φ θ := λ M v xs, begin have h1' := h1 M v xs, have h2' := h2 M v xs, rw [bounded_formula.realize_iff] at *, exact ⟨h2'.1 ∘ h1'.1, h1'.2 ∘ h2'.2⟩, end lemma semantically_equivalent.realize_bd_iff {φ ψ : L.bounded_formula α n} {M : Type (max u v)} [ne : nonempty M] [str : L.Structure M] [hM : T.model M] (h : T.semantically_equivalent φ ψ) {v : α → M} {xs : (fin n → M)} : φ.realize v xs ↔ ψ.realize v xs := bounded_formula.realize_iff.1 (h (Model.of T M) v xs) lemma semantically_equivalent.realize_iff {φ ψ : L.formula α} {M : Type (max u v)} [ne : nonempty M] [str : L.Structure M] (hM : T.model M) (h : T.semantically_equivalent φ ψ) {v : α → M} : φ.realize v ↔ ψ.realize v := h.realize_bd_iff /-- Semantic equivalence forms an equivalence relation on formulas. -/ def semantically_equivalent_setoid (T : L.Theory) : setoid (L.bounded_formula α n) := { r := semantically_equivalent T, iseqv := ⟨λ _, refl _, λ a b h, h.symm, λ _ _ _ h1 h2, h1.trans h2⟩ } protected lemma semantically_equivalent.all {φ ψ : L.bounded_formula α (n + 1)} (h : T.semantically_equivalent φ ψ) : T.semantically_equivalent φ.all ψ.all := begin simp_rw [semantically_equivalent, models_bounded_formula, bounded_formula.realize_iff, bounded_formula.realize_all], exact λ M v xs, forall_congr (λ a, h.realize_bd_iff), end protected lemma semantically_equivalent.ex {φ ψ : L.bounded_formula α (n + 1)} (h : T.semantically_equivalent φ ψ) : T.semantically_equivalent φ.ex ψ.ex := begin simp_rw [semantically_equivalent, models_bounded_formula, bounded_formula.realize_iff, bounded_formula.realize_ex], exact λ M v xs, exists_congr (λ a, h.realize_bd_iff), end protected lemma semantically_equivalent.not {φ ψ : L.bounded_formula α n} (h : T.semantically_equivalent φ ψ) : T.semantically_equivalent φ.not ψ.not := begin simp_rw [semantically_equivalent, models_bounded_formula, bounded_formula.realize_iff, bounded_formula.realize_not], exact λ M v xs, not_congr h.realize_bd_iff, end protected lemma semantically_equivalent.imp {φ ψ φ' ψ' : L.bounded_formula α n} (h : T.semantically_equivalent φ ψ) (h' : T.semantically_equivalent φ' ψ') : T.semantically_equivalent (φ.imp φ') (ψ.imp ψ') := begin simp_rw [semantically_equivalent, models_bounded_formula, bounded_formula.realize_iff, bounded_formula.realize_imp], exact λ M v xs, imp_congr h.realize_bd_iff h'.realize_bd_iff, end end Theory namespace complete_theory variables (L) (M : Type w) [L.Structure M] lemma is_satisfiable [nonempty M] : (L.complete_theory M).is_satisfiable := Theory.model.is_satisfiable M lemma mem_or_not_mem (φ : L.sentence) : φ ∈ L.complete_theory M ∨ φ.not ∈ L.complete_theory M := by simp_rw [complete_theory, set.mem_set_of_eq, sentence.realize, formula.realize_not, or_not] lemma is_maximal [nonempty M] : (L.complete_theory M).is_maximal := ⟨is_satisfiable L M, mem_or_not_mem L M⟩ lemma is_complete [nonempty M] : (L.complete_theory M).is_complete := (complete_theory.is_maximal L M).is_complete end complete_theory namespace bounded_formula variables (φ ψ : L.bounded_formula α n) lemma semantically_equivalent_not_not : T.semantically_equivalent φ φ.not.not := λ M v xs, by simp lemma imp_semantically_equivalent_not_sup : T.semantically_equivalent (φ.imp ψ) (φ.not ⊔ ψ) := λ M v xs, by simp [imp_iff_not_or] lemma sup_semantically_equivalent_not_inf_not : T.semantically_equivalent (φ ⊔ ψ) (φ.not ⊓ ψ.not).not := λ M v xs, by simp [imp_iff_not_or] lemma inf_semantically_equivalent_not_sup_not : T.semantically_equivalent (φ ⊓ ψ) (φ.not ⊔ ψ.not).not := λ M v xs, by simp [and_iff_not_or_not] lemma all_semantically_equivalent_not_ex_not (φ : L.bounded_formula α (n + 1)) : T.semantically_equivalent φ.all φ.not.ex.not := λ M v xs, by simp lemma ex_semantically_equivalent_not_all_not (φ : L.bounded_formula α (n + 1)) : T.semantically_equivalent φ.ex φ.not.all.not := λ M v xs, by simp lemma semantically_equivalent_all_lift_at : T.semantically_equivalent φ (φ.lift_at 1 n).all := λ M v xs, by { resetI, rw [realize_iff, realize_all_lift_at_one_self] } end bounded_formula namespace formula variables (φ ψ : L.formula α) lemma semantically_equivalent_not_not : T.semantically_equivalent φ φ.not.not := φ.semantically_equivalent_not_not lemma imp_semantically_equivalent_not_sup : T.semantically_equivalent (φ.imp ψ) (φ.not ⊔ ψ) := φ.imp_semantically_equivalent_not_sup ψ lemma sup_semantically_equivalent_not_inf_not : T.semantically_equivalent (φ ⊔ ψ) (φ.not ⊓ ψ.not).not := φ.sup_semantically_equivalent_not_inf_not ψ lemma inf_semantically_equivalent_not_sup_not : T.semantically_equivalent (φ ⊓ ψ) (φ.not ⊔ ψ.not).not := φ.inf_semantically_equivalent_not_sup_not ψ end formula namespace bounded_formula lemma is_qf.induction_on_sup_not {P : L.bounded_formula α n → Prop} {φ : L.bounded_formula α n} (h : is_qf φ) (hf : P (⊥ : L.bounded_formula α n)) (ha : ∀ (ψ : L.bounded_formula α n), is_atomic ψ → P ψ) (hsup : ∀ {φ₁ φ₂} (h₁ : P φ₁) (h₂ : P φ₂), P (φ₁ ⊔ φ₂)) (hnot : ∀ {φ} (h : P φ), P φ.not) (hse : ∀ {φ₁ φ₂ : L.bounded_formula α n} (h : Theory.semantically_equivalent ∅ φ₁ φ₂), P φ₁ ↔ P φ₂) : P φ := is_qf.rec_on h hf ha (λ φ₁ φ₂ _ _ h1 h2, (hse (φ₁.imp_semantically_equivalent_not_sup φ₂)).2 (hsup (hnot h1) h2)) lemma is_qf.induction_on_inf_not {P : L.bounded_formula α n → Prop} {φ : L.bounded_formula α n} (h : is_qf φ) (hf : P (⊥ : L.bounded_formula α n)) (ha : ∀ (ψ : L.bounded_formula α n), is_atomic ψ → P ψ) (hinf : ∀ {φ₁ φ₂} (h₁ : P φ₁) (h₂ : P φ₂), P (φ₁ ⊓ φ₂)) (hnot : ∀ {φ} (h : P φ), P φ.not) (hse : ∀ {φ₁ φ₂ : L.bounded_formula α n} (h : Theory.semantically_equivalent ∅ φ₁ φ₂), P φ₁ ↔ P φ₂) : P φ := h.induction_on_sup_not hf ha (λ φ₁ φ₂ h1 h2, ((hse (φ₁.sup_semantically_equivalent_not_inf_not φ₂)).2 (hnot (hinf (hnot h1) (hnot h2))))) (λ _, hnot) (λ _ _, hse) lemma semantically_equivalent_to_prenex (φ : L.bounded_formula α n) : (∅ : L.Theory).semantically_equivalent φ φ.to_prenex := λ M v xs, by rw [realize_iff, realize_to_prenex] lemma induction_on_all_ex {P : Π {m}, L.bounded_formula α m → Prop} (φ : L.bounded_formula α n) (hqf : ∀ {m} {ψ : L.bounded_formula α m}, is_qf ψ → P ψ) (hall : ∀ {m} {ψ : L.bounded_formula α (m + 1)} (h : P ψ), P ψ.all) (hex : ∀ {m} {φ : L.bounded_formula α (m + 1)} (h : P φ), P φ.ex) (hse : ∀ {m} {φ₁ φ₂ : L.bounded_formula α m} (h : Theory.semantically_equivalent ∅ φ₁ φ₂), P φ₁ ↔ P φ₂) : P φ := begin suffices h' : ∀ {m} {φ : L.bounded_formula α m}, φ.is_prenex → P φ, { exact (hse φ.semantically_equivalent_to_prenex).2 (h' φ.to_prenex_is_prenex) }, intros m φ hφ, induction hφ with _ _ hφ _ _ _ hφ _ _ _ hφ, { exact hqf hφ }, { exact hall hφ, }, { exact hex hφ, }, end lemma induction_on_exists_not {P : Π {m}, L.bounded_formula α m → Prop} (φ : L.bounded_formula α n) (hqf : ∀ {m} {ψ : L.bounded_formula α m}, is_qf ψ → P ψ) (hnot : ∀ {m} {φ : L.bounded_formula α m} (h : P φ), P φ.not) (hex : ∀ {m} {φ : L.bounded_formula α (m + 1)} (h : P φ), P φ.ex) (hse : ∀ {m} {φ₁ φ₂ : L.bounded_formula α m} (h : Theory.semantically_equivalent ∅ φ₁ φ₂), P φ₁ ↔ P φ₂) : P φ := φ.induction_on_all_ex (λ _ _, hqf) (λ _ φ hφ, (hse φ.all_semantically_equivalent_not_ex_not).2 (hnot (hex (hnot hφ)))) (λ _ _, hex) (λ _ _ _, hse) end bounded_formula end language end first_order namespace cardinal open first_order first_order.language variables {L : language.{u v}} (κ : cardinal.{w}) (T : L.Theory) /-- A theory is `κ`-categorical if all models of size `κ` are isomorphic. -/ def categorical : Prop := ∀ (M N : T.Model), # M = κ → # N = κ → nonempty (M ≃[L] N) /-- The Łoś–Vaught Test : a criterion for categorical theories to be complete. -/ lemma categorical.is_complete (h : κ.categorical T) (h1 : ℵ₀ ≤ κ) (h2 : cardinal.lift.{w} L.card ≤ cardinal.lift.{max u v} κ) (hS : T.is_satisfiable) (hT : ∀ (M : Theory.Model.{u v max u v} T), infinite M) : T.is_complete := ⟨hS, λ φ, begin obtain ⟨N, hN⟩ := Theory.exists_model_card_eq ⟨hS.some, hT hS.some⟩ κ h1 h2, rw [Theory.models_sentence_iff, Theory.models_sentence_iff], by_contra con, push_neg at con, obtain ⟨⟨MF, hMF⟩, MT, hMT⟩ := con, rw [sentence.realize_not, not_not] at hMT, refine hMF _, haveI := hT MT, haveI := hT MF, obtain ⟨NT, MNT, hNT⟩ := exists_elementarily_equivalent_card_eq L MT κ h1 h2, obtain ⟨NF, MNF, hNF⟩ := exists_elementarily_equivalent_card_eq L MF κ h1 h2, obtain ⟨TF⟩ := h (MNT.to_Model T) (MNF.to_Model T) hNT hNF, exact ((MNT.realize_sentence φ).trans ((TF.realize_sentence φ).trans (MNF.realize_sentence φ).symm)).1 hMT, end⟩ theorem empty_Theory_categorical (T : language.empty.Theory) : κ.categorical T := λ M N hM hN, by rw [empty.nonempty_equiv_iff, hM, hN] theorem empty_infinite_Theory_is_complete : language.empty.infinite_theory.is_complete := (empty_Theory_categorical ℵ₀ _).is_complete ℵ₀ _ le_rfl (by simp) ⟨Theory.model.bundled ((model_infinite_theory_iff language.empty).2 nat.infinite)⟩ (λ M, (model_infinite_theory_iff language.empty).1 M.is_model) end cardinal
7ec86497bf16454b8b29a765fbaf075f4d102e4a
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/run/genindices.lean
da00729e34d9e7071ec96a3fd3df301adeecf410
[ "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
739
lean
import Lean universe u inductive Pred : ∀ (α : Type u), List α → Type (u+1) | foo {α : Type u} (l1 : List α) (l2 : List (Option α)) : Pred (Option α) l2 → Pred α l1 axiom goal : forall (α : Type u) (xs : List (List α)) (h : Pred (List α) xs), xs ≠ [] → xs = xs open Lean open Lean.Meta def tst1 : MetaM Unit := do let cinfo ← getConstInfo `goal; let type := cinfo.type; let mvar ← mkFreshExprMVar type; trace[Elab] (MessageData.ofGoal mvar.mvarId!); let (_, mvarId) ← introN mvar.mvarId! 2; let (fvarId, mvarId) ← intro1 mvarId; trace[Elab] (MessageData.ofGoal mvarId); let s ← generalizeIndices mvarId fvarId; trace[Elab] (MessageData.ofGoal s.mvarId); pure () set_option trace.Elab true #eval tst1
f8adf28d6b8b7a4c5de90d84aab33703ea8c8cb5
49bd2218ae088932d847f9030c8dbff1c5607bb7
/src/topology/bounded_continuous_function.lean
b2f783f5183e766778169ec9d198bb03d039b04b
[ "Apache-2.0" ]
permissive
FredericLeRoux/mathlib
e8f696421dd3e4edc8c7edb3369421c8463d7bac
3645bf8fb426757e0a20af110d1fdded281d286e
refs/heads/master
1,607,062,870,732
1,578,513,186,000
1,578,513,186,000
231,653,181
0
0
Apache-2.0
1,578,080,327,000
1,578,080,326,000
null
UTF-8
Lean
false
false
23,631
lean
/- Copyright (c) 2018 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sébastien Gouëzel, Mario Carneiro Type of bounded continuous functions taking values in a metric space, with the uniform distance. -/ import analysis.normed_space.basic topology.metric_space.lipschitz noncomputable theory local attribute [instance] classical.decidable_inhabited classical.prop_decidable open_locale topological_space open set lattice filter metric universes u v w variables {α : Type u} {β : Type v} {γ : Type w} /-- A locally uniform limit of continuous functions is continuous -/ lemma continuous_of_locally_uniform_limit_of_continuous [topological_space α] [metric_space β] {F : ℕ → α → β} {f : α → β} (L : ∀x:α, ∃s ∈ 𝓝 x, ∀ε>(0:ℝ), ∃n, ∀y∈s, dist (F n y) (f y) ≤ ε) (C : ∀ n, continuous (F n)) : continuous f := continuous_iff'.2 $ λ x ε ε0, begin rcases L x with ⟨r, rx, hr⟩, rcases hr (ε/2/2) (half_pos $ half_pos ε0) with ⟨n, hn⟩, rcases continuous_iff'.1 (C n) x (ε/2) (half_pos ε0) with ⟨s, sx, hs⟩, refine ⟨_, (𝓝 x).inter_sets rx sx, _⟩, rintro y ⟨yr, ys⟩, calc dist (f y) (f x) ≤ dist (F n y) (F n x) + (dist (F n y) (f y) + dist (F n x) (f x)) : dist_triangle4_left _ _ _ _ ... < ε/2 + (ε/2/2 + ε/2/2) : add_lt_add_of_lt_of_le (hs _ ys) (add_le_add (hn _ yr) (hn _ (mem_of_nhds rx))) ... = ε : by rw [add_halves, add_halves] end /-- A uniform limit of continuous functions is continuous -/ lemma continuous_of_uniform_limit_of_continuous [topological_space α] {β : Type v} [metric_space β] {F : ℕ → α → β} {f : α → β} (L : ∀ε>(0:ℝ), ∃N, ∀y, dist (F N y) (f y) ≤ ε) : (∀ n, continuous (F n)) → continuous f := continuous_of_locally_uniform_limit_of_continuous $ λx, ⟨univ, by simpa [filter.univ_mem_sets] using L⟩ /-- The type of bounded continuous functions from a topological space to a metric space -/ def bounded_continuous_function (α : Type u) (β : Type v) [topological_space α] [metric_space β] : Type (max u v) := {f : α → β // continuous f ∧ ∃C, ∀x y:α, dist (f x) (f y) ≤ C} local infixr ` →ᵇ `:25 := bounded_continuous_function namespace bounded_continuous_function section basics variables [topological_space α] [metric_space β] [metric_space γ] variables {f g : α →ᵇ β} {x : α} {C : ℝ} instance : has_coe_to_fun (α →ᵇ β) := ⟨_, subtype.val⟩ lemma bounded_range : bounded (range f) := bounded_range_iff.2 f.2.2 /-- If a function is continuous on a compact space, it is automatically bounded, and therefore gives rise to an element of the type of bounded continuous functions -/ def mk_of_compact [compact_space α] (f : α → β) (hf : continuous f) : α →ᵇ β := ⟨f, hf, bounded_range_iff.1 $ bounded_of_compact $ compact_range hf⟩ /-- If a function is bounded on a discrete space, it is automatically continuous, and therefore gives rise to an element of the type of bounded continuous functions -/ def mk_of_discrete [discrete_topology α] (f : α → β) (hf : ∃C, ∀x y, dist (f x) (f y) ≤ C) : α →ᵇ β := ⟨f, continuous_of_discrete_topology, hf⟩ /-- The uniform distance between two bounded continuous functions -/ instance : has_dist (α →ᵇ β) := ⟨λf g, Inf {C | C ≥ 0 ∧ ∀ x : α, dist (f x) (g x) ≤ C}⟩ lemma dist_eq : dist f g = Inf {C | C ≥ 0 ∧ ∀ x : α, dist (f x) (g x) ≤ C} := rfl lemma dist_set_exists : ∃ C, C ≥ 0 ∧ ∀ x : α, dist (f x) (g x) ≤ C := begin refine if h : nonempty α then _ else ⟨0, le_refl _, λ x, h.elim ⟨x⟩⟩, cases h with x, rcases f.2 with ⟨_, Cf, hCf⟩, /- hCf : ∀ (x y : α), dist (f.val x) (f.val y) ≤ Cf -/ rcases g.2 with ⟨_, Cg, hCg⟩, /- hCg : ∀ (x y : α), dist (g.val x) (g.val y) ≤ Cg -/ let C := max 0 (dist (f x) (g x) + (Cf + Cg)), exact ⟨C, le_max_left _ _, λ y, calc dist (f y) (g y) ≤ dist (f x) (g x) + (dist (f x) (f y) + dist (g x) (g y)) : dist_triangle4_left _ _ _ _ ... ≤ dist (f x) (g x) + (Cf + Cg) : add_le_add_left (add_le_add (hCf _ _) (hCg _ _)) _ ... ≤ C : le_max_right _ _⟩ end /-- The pointwise distance is controlled by the distance between functions, by definition -/ lemma dist_coe_le_dist (x : α) : dist (f x) (g x) ≤ dist f g := le_cInf (ne_empty_iff_exists_mem.2 dist_set_exists) $ λb hb, hb.2 x @[ext] lemma ext (H : ∀x, f x = g x) : f = g := subtype.eq $ by ext; apply H /- This lemma will be needed in the proof of the metric space instance, but it will become useless afterwards as it will be superceded by the general result that the distance is nonnegative is metric spaces. -/ private lemma dist_nonneg' : 0 ≤ dist f g := le_cInf (ne_empty_iff_exists_mem.2 dist_set_exists) (λ C, and.left) /-- The distance between two functions is controlled by the supremum of the pointwise distances -/ lemma dist_le (C0 : (0 : ℝ) ≤ C) : dist f g ≤ C ↔ ∀x:α, dist (f x) (g x) ≤ C := ⟨λ h x, le_trans (dist_coe_le_dist x) h, λ H, cInf_le ⟨0, λ C, and.left⟩ ⟨C0, H⟩⟩ /-- On an empty space, bounded continuous functions are at distance 0 -/ lemma dist_zero_of_empty (e : ¬ nonempty α) : dist f g = 0 := le_antisymm ((dist_le (le_refl _)).2 $ λ x, e.elim ⟨x⟩) dist_nonneg' /-- The type of bounded continuous functions, with the uniform distance, is a metric space. -/ instance : metric_space (α →ᵇ β) := { dist_self := λ f, le_antisymm ((dist_le (le_refl _)).2 $ λ x, by simp) dist_nonneg', eq_of_dist_eq_zero := λ f g hfg, by ext x; exact eq_of_dist_eq_zero (le_antisymm (hfg ▸ dist_coe_le_dist _) dist_nonneg), dist_comm := λ f g, by simp [dist_eq, dist_comm], dist_triangle := λ f g h, (dist_le (add_nonneg dist_nonneg' dist_nonneg')).2 $ λ x, le_trans (dist_triangle _ _ _) (add_le_add (dist_coe_le_dist _) (dist_coe_le_dist _)) } def const (b : β) : α →ᵇ β := ⟨λx, b, continuous_const, 0, by simp [le_refl]⟩ /-- If the target space is inhabited, so is the space of bounded continuous functions -/ instance [inhabited β] : inhabited (α →ᵇ β) := ⟨const (default β)⟩ /-- The evaluation map is continuous, as a joint function of `u` and `x` -/ theorem continuous_eval : continuous (λ p : (α →ᵇ β) × α, p.1 p.2) := continuous_iff'.2 $ λ ⟨f, x⟩ ε ε0, /- use the continuity of `f` to find a neighborhood of `x` where it varies at most by ε/2 -/ let ⟨s, sx, Hs⟩ := continuous_iff'.1 f.2.1 x (ε/2) (half_pos ε0) in /- s : set α, sx : s ∈ 𝓝 x, Hs : ∀ (b : α), b ∈ s → dist (f.val b) (f.val x) < ε / 2 -/ ⟨set.prod (ball f (ε/2)) s, prod_mem_nhds_sets (ball_mem_nhds _ (half_pos ε0)) sx, λ ⟨g, y⟩ ⟨hg, hy⟩, calc dist (g y) (f x) ≤ dist (g y) (f y) + dist (f y) (f x) : dist_triangle _ _ _ ... < ε/2 + ε/2 : add_lt_add (lt_of_le_of_lt (dist_coe_le_dist _) hg) (Hs _ hy) ... = ε : add_halves _⟩ /-- In particular, when `x` is fixed, `f → f x` is continuous -/ theorem continuous_evalx {x : α} : continuous (λ f : α →ᵇ β, f x) := continuous_eval.comp (continuous_id.prod_mk continuous_const) /-- When `f` is fixed, `x → f x` is also continuous, by definition -/ theorem continuous_evalf {f : α →ᵇ β} : continuous f := f.2.1 /-- Bounded continuous functions taking values in a complete space form a complete space. -/ instance [complete_space β] : complete_space (α →ᵇ β) := complete_of_cauchy_seq_tendsto $ λ (f : ℕ → α →ᵇ β) (hf : cauchy_seq f), begin /- We have to show that `f n` converges to a bounded continuous function. For this, we prove pointwise convergence to define the limit, then check it is a continuous bounded function, and then check the norm convergence. -/ rcases cauchy_seq_iff_le_tendsto_0.1 hf with ⟨b, b0, b_bound, b_lim⟩, have f_bdd := λx n m N hn hm, le_trans (dist_coe_le_dist x) (b_bound n m N hn hm), have fx_cau : ∀x, cauchy_seq (λn, f n x) := λx, cauchy_seq_iff_le_tendsto_0.2 ⟨b, b0, f_bdd x, b_lim⟩, choose F hF using λx, cauchy_seq_tendsto_of_complete (fx_cau x), /- F : α → β, hF : ∀ (x : α), tendsto (λ (n : ℕ), f n x) at_top (𝓝 (F x)) `F` is the desired limit function. Check that it is uniformly approximated by `f N` -/ have fF_bdd : ∀x N, dist (f N x) (F x) ≤ b N := λ x N, le_of_tendsto (by simp) (tendsto_dist tendsto_const_nhds (hF x)) (filter.mem_at_top_sets.2 ⟨N, λn hn, f_bdd x N n N (le_refl N) hn⟩), refine ⟨⟨F, _, _⟩, _⟩, { /- Check that `F` is continuous -/ refine continuous_of_uniform_limit_of_continuous (λ ε ε0, _) (λN, (f N).2.1), rcases metric.tendsto_at_top.1 b_lim ε ε0 with ⟨N, hN⟩, exact ⟨N, λy, calc dist (f N y) (F y) ≤ b N : fF_bdd y N ... ≤ dist (b N) 0 : begin simp, show b N ≤ abs(b N), from le_abs_self _ end ... ≤ ε : le_of_lt (hN N (le_refl N))⟩ }, { /- Check that `F` is bounded -/ rcases (f 0).2.2 with ⟨C, hC⟩, exact ⟨C + (b 0 + b 0), λ x y, calc dist (F x) (F y) ≤ dist (f 0 x) (f 0 y) + (dist (f 0 x) (F x) + dist (f 0 y) (F y)) : dist_triangle4_left _ _ _ _ ... ≤ C + (b 0 + b 0) : add_le_add (hC x y) (add_le_add (fF_bdd x 0) (fF_bdd y 0))⟩ }, { /- Check that `F` is close to `f N` in distance terms -/ refine tendsto_iff_dist_tendsto_zero.2 (squeeze_zero (λ _, dist_nonneg) _ b_lim), exact λ N, (dist_le (b0 _)).2 (λx, fF_bdd x N) } end /-- Composition (in the target) of a bounded continuous function with a Lipschitz map again gives a bounded continuous function -/ def comp (G : β → γ) {C : nnreal} (H : lipschitz_with C G) (f : α →ᵇ β) : α →ᵇ γ := ⟨λx, G (f x), H.to_continuous.comp f.2.1, let ⟨D, hD⟩ := f.2.2 in ⟨max C 0 * D, λ x y, calc dist (G (f x)) (G (f y)) ≤ C * dist (f x) (f y) : H _ _ ... ≤ max C 0 * dist (f x) (f y) : mul_le_mul_of_nonneg_right (le_max_left C 0) dist_nonneg ... ≤ max C 0 * D : mul_le_mul_of_nonneg_left (hD _ _) (le_max_right C 0)⟩⟩ /-- The composition operator (in the target) with a Lipschitz map is Lipschitz -/ lemma lipschitz_comp {G : β → γ} {C : nnreal} (H : lipschitz_with C G) : lipschitz_with C (comp G H : (α →ᵇ β) → α →ᵇ γ) := λ f g, (dist_le (mul_nonneg C.2 dist_nonneg)).2 $ λ x, calc dist (G (f x)) (G (g x)) ≤ C * dist (f x) (g x) : H _ _ ... ≤ C * dist f g : mul_le_mul_of_nonneg_left (dist_coe_le_dist _) C.2 /-- The composition operator (in the target) with a Lipschitz map is uniformly continuous -/ lemma uniform_continuous_comp {G : β → γ} {C : nnreal} (H : lipschitz_with C G) : uniform_continuous (comp G H : (α →ᵇ β) → α →ᵇ γ) := (lipschitz_comp H).to_uniform_continuous /-- The composition operator (in the target) with a Lipschitz map is continuous -/ lemma continuous_comp {G : β → γ} {C : nnreal} (H : lipschitz_with C G) : continuous (comp G H : (α →ᵇ β) → α →ᵇ γ) := (lipschitz_comp H).to_continuous /-- Restriction (in the target) of a bounded continuous function taking values in a subset -/ def cod_restrict (s : set β) (f : α →ᵇ β) (H : ∀x, f x ∈ s) : α →ᵇ s := ⟨λx, ⟨f x, H x⟩, continuous_subtype_mk _ f.2.1, f.2.2⟩ end basics section arzela_ascoli variables [topological_space α] [compact_space α] [metric_space β] variables {f g : α →ᵇ β} {x : α} {C : ℝ} /- Arzela-Ascoli theorem asserts that, on a compact space, a set of functions sharing a common modulus of continuity and taking values in a compact set forms a compact subset for the topology of uniform convergence. In this section, we prove this theorem and several useful variations around it. -/ /-- First version, with pointwise equicontinuity and range in a compact space -/ theorem arzela_ascoli₁ [compact_space β] (A : set (α →ᵇ β)) (closed : is_closed A) (H : ∀ (x:α) (ε > 0), ∃U ∈ 𝓝 x, ∀ (y z ∈ U) (f : α →ᵇ β), f ∈ A → dist (f y) (f z) < ε) : compact A := begin refine compact_of_totally_bounded_is_closed _ closed, refine totally_bounded_of_finite_discretization (λ ε ε0, _), rcases dense ε0 with ⟨ε₁, ε₁0, εε₁⟩, let ε₂ := ε₁/2/2, /- We have to find a finite discretization of `u`, i.e., finite information that is sufficient to reconstruct `u` up to ε. This information will be provided by the values of `u` on a sufficiently dense set tα, slightly translated to fit in a finite ε₂-dense set tβ in the image. Such sets exist by compactness of the source and range. Then, to check that these data determine the function up to ε, one uses the control on the modulus of continuity to extend the closeness on tα to closeness everywhere. -/ have ε₂0 : ε₂ > 0 := half_pos (half_pos ε₁0), have : ∀x:α, ∃U, x ∈ U ∧ is_open U ∧ ∀ (y z ∈ U) {f : α →ᵇ β}, f ∈ A → dist (f y) (f z) < ε₂ := λ x, let ⟨U, nhdsU, hU⟩ := H x _ ε₂0, ⟨V, VU, openV, xV⟩ := mem_nhds_sets_iff.1 nhdsU in ⟨V, xV, openV, λy z hy hz f hf, hU y z (VU hy) (VU hz) f hf⟩, choose U hU using this, /- For all x, the set hU x is an open set containing x on which the elements of A fluctuate by at most ε₂. We extract finitely many of these sets that cover the whole space, by compactness -/ rcases compact_univ.elim_finite_subcover_image (λx _, (hU x).2.1) (λx hx, mem_bUnion (mem_univ _) (hU x).1) with ⟨tα, _, ⟨_⟩, htα⟩, /- tα : set α, htα : univ ⊆ ⋃x ∈ tα, U x -/ rcases @finite_cover_balls_of_compact β _ _ compact_univ _ ε₂0 with ⟨tβ, _, ⟨_⟩, htβ⟩, resetI, /- tβ : set β, htβ : univ ⊆ ⋃y ∈ tβ, ball y ε₂ -/ /- Associate to every point `y` in the space a nearby point `F y` in tβ -/ choose F hF using λy, show ∃z∈tβ, dist y z < ε₂, by simpa using htβ (mem_univ y), /- F : β → β, hF : ∀ (y : β), F y ∈ tβ ∧ dist y (F y) < ε₂ -/ /- Associate to every function a discrete approximation, mapping each point in `tα` to a point in `tβ` close to its true image by the function. -/ refine ⟨tα → tβ, by apply_instance, λ f a, ⟨F (f a), (hF (f a)).1⟩, _⟩, rintro ⟨f, hf⟩ ⟨g, hg⟩ f_eq_g, /- If two functions have the same approximation, then they are within distance ε -/ refine lt_of_le_of_lt ((dist_le $ le_of_lt ε₁0).2 (λ x, _)) εε₁, have : ∃x', x' ∈ tα ∧ x ∈ U x' := mem_bUnion_iff.1 (htα (mem_univ x)), rcases this with ⟨x', x'tα, hx'⟩, refine calc dist (f x) (g x) ≤ dist (f x) (f x') + dist (g x) (g x') + dist (f x') (g x') : dist_triangle4_right _ _ _ _ ... ≤ ε₂ + ε₂ + ε₁/2 : le_of_lt (add_lt_add (add_lt_add _ _) _) ... = ε₁ : by rw [add_halves, add_halves], { exact (hU x').2.2 _ _ hx' ((hU x').1) hf }, { exact (hU x').2.2 _ _ hx' ((hU x').1) hg }, { have F_f_g : F (f x') = F (g x') := (congr_arg (λ f:tα → tβ, (f ⟨x', x'tα⟩ : β)) f_eq_g : _), calc dist (f x') (g x') ≤ dist (f x') (F (f x')) + dist (g x') (F (f x')) : dist_triangle_right _ _ _ ... = dist (f x') (F (f x')) + dist (g x') (F (g x')) : by rw F_f_g ... < ε₂ + ε₂ : add_lt_add (hF (f x')).2 (hF (g x')).2 ... = ε₁/2 : add_halves _ } end /-- Second version, with pointwise equicontinuity and range in a compact subset -/ theorem arzela_ascoli₂ (s : set β) (hs : compact s) (A : set (α →ᵇ β)) (closed : is_closed A) (in_s : ∀(f : α →ᵇ β) (x : α), f ∈ A → f x ∈ s) (H : ∀(x:α) (ε > 0), ∃U ∈ 𝓝 x, ∀ (y z ∈ U) (f : α →ᵇ β), f ∈ A → dist (f y) (f z) < ε) : compact A := /- This version is deduced from the previous one by restricting to the compact type in the target, using compactness there and then lifting everything to the original space. -/ begin have M : lipschitz_with 1 coe := lipschitz_with.subtype_coe s, let F : (α →ᵇ s) → α →ᵇ β := comp coe M, refine compact_of_is_closed_subset ((_ : compact (F ⁻¹' A)).image (continuous_comp M)) closed (λ f hf, _), { haveI : compact_space s := compact_iff_compact_space.1 hs, refine arzela_ascoli₁ _ (continuous_iff_is_closed.1 (continuous_comp M) _ closed) (λ x ε ε0, bex.imp_right (λ U U_nhds hU y z hy hz f hf, _) (H x ε ε0)), calc dist (f y) (f z) = dist (F f y) (F f z) : rfl ... < ε : hU y z hy hz (F f) hf }, { let g := cod_restrict s f (λx, in_s f x hf), rw [show f = F g, by ext; refl] at hf ⊢, exact ⟨g, hf, rfl⟩ } end /-- Third (main) version, with pointwise equicontinuity and range in a compact subset, but without closedness. The closure is then compact -/ theorem arzela_ascoli (s : set β) (hs : compact s) (A : set (α →ᵇ β)) (in_s : ∀(f : α →ᵇ β) (x : α), f ∈ A → f x ∈ s) (H : ∀(x:α) (ε > 0), ∃U ∈ 𝓝 x, ∀ (y z ∈ U) (f : α →ᵇ β), f ∈ A → dist (f y) (f z) < ε) : compact (closure A) := /- This version is deduced from the previous one by checking that the closure of A, in addition to being closed, still satisfies the properties of compact range and equicontinuity -/ arzela_ascoli₂ s hs (closure A) is_closed_closure (λ f x hf, (mem_of_closed' (closed_of_compact _ hs)).2 $ λ ε ε0, let ⟨g, gA, dist_fg⟩ := mem_closure_iff'.1 hf ε ε0 in ⟨g x, in_s g x gA, lt_of_le_of_lt (dist_coe_le_dist _) dist_fg⟩) (λ x ε ε0, show ∃ U ∈ 𝓝 x, ∀ y z ∈ U, ∀ (f : α →ᵇ β), f ∈ closure A → dist (f y) (f z) < ε, begin refine bex.imp_right (λ U U_set hU y z hy hz f hf, _) (H x (ε/2) (half_pos ε0)), rcases mem_closure_iff'.1 hf (ε/2/2) (half_pos (half_pos ε0)) with ⟨g, gA, dist_fg⟩, replace dist_fg := λ x, lt_of_le_of_lt (dist_coe_le_dist x) dist_fg, calc dist (f y) (f z) ≤ dist (f y) (g y) + dist (f z) (g z) + dist (g y) (g z) : dist_triangle4_right _ _ _ _ ... < ε/2/2 + ε/2/2 + ε/2 : add_lt_add (add_lt_add (dist_fg y) (dist_fg z)) (hU y z hy hz g gA) ... = ε : by rw [add_halves, add_halves] end) /- To apply the previous theorems, one needs to check the equicontinuity. An important instance is when the source space is a metric space, and there is a fixed modulus of continuity for all the functions in the set A -/ lemma equicontinuous_of_continuity_modulus {α : Type u} [metric_space α] (b : ℝ → ℝ) (b_lim : tendsto b (𝓝 0) (𝓝 0)) (A : set (α →ᵇ β)) (H : ∀(x y:α) (f : α →ᵇ β), f ∈ A → dist (f x) (f y) ≤ b (dist x y)) (x:α) (ε : ℝ) (ε0 : ε > 0) : ∃U ∈ 𝓝 x, ∀ (y z ∈ U) (f : α →ᵇ β), f ∈ A → dist (f y) (f z) < ε := begin rcases tendsto_nhds_nhds.1 b_lim ε ε0 with ⟨δ, δ0, hδ⟩, refine ⟨ball x (δ/2), ball_mem_nhds x (half_pos δ0), λ y z hy hz f hf, _⟩, have : dist y z < δ := calc dist y z ≤ dist y x + dist z x : dist_triangle_right _ _ _ ... < δ/2 + δ/2 : add_lt_add hy hz ... = δ : add_halves _, calc dist (f y) (f z) ≤ b (dist y z) : H y z f hf ... ≤ abs (b (dist y z)) : le_abs_self _ ... = dist (b (dist y z)) 0 : by simp [real.dist_eq] ... < ε : hδ (by simpa [real.dist_eq] using this), end end arzela_ascoli section normed_group /- In this section, if β is a normed group, then we show that the space of bounded continuous functions from α to β inherits a normed group structure, by using pointwise operations and checking that they are compatible with the uniform distance. -/ variables [topological_space α] [normed_group β] variables {f g : α →ᵇ β} {x : α} {C : ℝ} instance : has_zero (α →ᵇ β) := ⟨const 0⟩ @[simp] lemma coe_zero : (0 : α →ᵇ β) x = 0 := rfl instance : has_norm (α →ᵇ β) := ⟨λu, dist u 0⟩ lemma norm_def : ∥f∥ = dist f 0 := rfl lemma norm_coe_le_norm (x : α) : ∥f x∥ ≤ ∥f∥ := calc ∥f x∥ = dist (f x) ((0 : α →ᵇ β) x) : by simp [dist_zero_right] ... ≤ ∥f∥ : dist_coe_le_dist _ /-- Distance between the images of any two points is at most twice the norm of the function. -/ lemma dist_le_two_norm (x y : α) : dist (f x) (f y) ≤ 2 * ∥f∥ := calc dist (f x) (f y) ≤ ∥f x∥ + ∥f y∥ : dist_le_norm_add_norm _ _ ... ≤ ∥f∥ + ∥f∥ : add_le_add (norm_coe_le_norm x) (norm_coe_le_norm y) ... = 2 * ∥f∥ : (two_mul _).symm /-- The norm of a function is controlled by the supremum of the pointwise norms -/ lemma norm_le (C0 : (0 : ℝ) ≤ C) : ∥f∥ ≤ C ↔ ∀x:α, ∥f x∥ ≤ C := by simpa only [coe_zero, dist_zero_right] using @dist_le _ _ _ _ f 0 _ C0 /-- The pointwise sum of two bounded continuous functions is again bounded continuous. -/ instance : has_add (α →ᵇ β) := ⟨λf g, ⟨λx, f x + g x, f.2.1.add g.2.1, let ⟨_, fM, hf⟩ := f.2 in let ⟨_, gM, hg⟩ := g.2 in ⟨fM + gM, λ x y, dist_add_add_le_of_le (hf _ _) (hg _ _)⟩⟩⟩ /-- The pointwise opposite of a bounded continuous function is again bounded continuous. -/ instance : has_neg (α →ᵇ β) := ⟨λf, ⟨λx, -f x, f.2.1.neg, by simpa only [dist_neg_neg] using f.2.2⟩⟩ @[simp] lemma coe_add : (f + g) x = f x + g x := rfl @[simp] lemma coe_neg : (-f) x = - (f x) := rfl lemma forall_coe_zero_iff_zero : (∀x, f x = 0) ↔ f = 0 := ⟨@ext _ _ _ _ f 0, by rintro rfl _; refl⟩ instance : add_comm_group (α →ᵇ β) := { add_assoc := assume f g h, by ext; simp, zero_add := assume f, by ext; simp, add_zero := assume f, by ext; simp, add_left_neg := assume f, by ext; simp, add_comm := assume f g, by ext; simp, ..bounded_continuous_function.has_add, ..bounded_continuous_function.has_neg, ..bounded_continuous_function.has_zero } @[simp] lemma coe_diff : (f - g) x = f x - g x := rfl instance : normed_group (α →ᵇ β) := normed_group.of_add_dist (λ _, rfl) $ λ f g h, (dist_le dist_nonneg).2 $ λ x, le_trans (by rw [dist_eq_norm, dist_eq_norm, coe_add, coe_add, add_sub_add_right_eq_sub]) (dist_coe_le_dist x) lemma abs_diff_coe_le_dist : norm (f x - g x) ≤ dist f g := by rw normed_group.dist_eq; exact @norm_coe_le_norm _ _ _ _ (f-g) x lemma coe_le_coe_add_dist {f g : α →ᵇ ℝ} : f x ≤ g x + dist f g := sub_le_iff_le_add'.1 $ (abs_le.1 $ @dist_coe_le_dist _ _ _ _ f g x).2 /-- Constructing a bounded continuous function from a uniformly bounded continuous function taking values in a normed group. -/ def of_normed_group {α : Type u} {β : Type v} [topological_space α] [normed_group β] (f : α → β) (C : ℝ) (H : ∀x, norm (f x) ≤ C) (Hf : continuous f) : α →ᵇ β := ⟨λn, f n, ⟨Hf, ⟨C + C, λ m n, calc dist (f m) (f n) ≤ dist (f m) 0 + dist (f n) 0 : dist_triangle_right _ _ _ ... = norm (f m) + norm (f n) : by simp ... ≤ C + C : add_le_add (H m) (H n)⟩⟩⟩ /-- Constructing a bounded continuous function from a uniformly bounded function on a discrete space, taking values in a normed group -/ def of_normed_group_discrete {α : Type u} {β : Type v} [topological_space α] [discrete_topology α] [normed_group β] (f : α → β) (C : ℝ) (H : ∀x, norm (f x) ≤ C) : α →ᵇ β := of_normed_group f C H continuous_of_discrete_topology end normed_group end bounded_continuous_function
d29fd7bb74261968835306415188370c750f74fa
d9d511f37a523cd7659d6f573f990e2a0af93c6f
/src/analysis/calculus/inverse.lean
548f4d24a7f14f28ebad2721f1bb85d1e10f0463
[ "Apache-2.0" ]
permissive
hikari0108/mathlib
b7ea2b7350497ab1a0b87a09d093ecc025a50dfa
a9e7d333b0cfd45f13a20f7b96b7d52e19fa2901
refs/heads/master
1,690,483,608,260
1,631,541,580,000
1,631,541,580,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
32,270
lean
/- Copyright (c) 2020 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudryashov, Heather Macbeth, Sébastien Gouëzel -/ import analysis.calculus.times_cont_diff import analysis.normed_space.banach import topology.local_homeomorph import topology.metric_space.contracting /-! # Inverse function theorem In this file we prove the inverse function theorem. It says that if a map `f : E → F` has an invertible strict derivative `f'` at `a`, then it is locally invertible, and the inverse function has derivative `f' ⁻¹`. We define `has_strict_deriv_at.to_local_homeomorph` that repacks a function `f` with a `hf : has_strict_fderiv_at f f' a`, `f' : E ≃L[𝕜] F`, into a `local_homeomorph`. The `to_fun` of this `local_homeomorph` is `defeq` to `f`, so one can apply theorems about `local_homeomorph` to `hf.to_local_homeomorph f`, and get statements about `f`. Then we define `has_strict_fderiv_at.local_inverse` to be the `inv_fun` of this `local_homeomorph`, and prove two versions of the inverse function theorem: * `has_strict_fderiv_at.to_local_inverse`: if `f` has an invertible derivative `f'` at `a` in the strict sense (`hf`), then `hf.local_inverse f f' a` has derivative `f'.symm` at `f a` in the strict sense; * `has_strict_fderiv_at.to_local_left_inverse`: if `f` has an invertible derivative `f'` at `a` in the strict sense and `g` is locally left inverse to `f` near `a`, then `g` has derivative `f'.symm` at `f a` in the strict sense. In the one-dimensional case we reformulate these theorems in terms of `has_strict_deriv_at` and `f'⁻¹`. We also reformulate the theorems in terms of `times_cont_diff`, to give that `C^k` (respectively, smooth) inputs give `C^k` (smooth) inverses. These versions require that continuous differentiability implies strict differentiability; this is false over a general field, true over `ℝ` or `ℂ` and implemented here assuming `is_R_or_C 𝕂`. Some related theorems, providing the derivative and higher regularity assuming that we already know the inverse function, are formulated in `fderiv.lean`, `deriv.lean`, and `times_cont_diff.lean`. ## Notations In the section about `approximates_linear_on` we introduce some `local notation` to make formulas shorter: * by `N` we denote `∥f'⁻¹∥`; * by `g` we denote the auxiliary contracting map `x ↦ x + f'.symm (y - f x)` used to prove that `{x | f x = y}` is nonempty. ## Tags derivative, strictly differentiable, continuously differentiable, smooth, inverse function -/ open function set filter metric open_locale topological_space classical nnreal noncomputable theory variables {𝕜 : Type*} [nondiscrete_normed_field 𝕜] variables {E : Type*} [normed_group E] [normed_space 𝕜 E] variables {F : Type*} [normed_group F] [normed_space 𝕜 F] variables {G : Type*} [normed_group G] [normed_space 𝕜 G] variables {G' : Type*} [normed_group G'] [normed_space 𝕜 G'] variables {ε : ℝ} open asymptotics filter metric set open continuous_linear_map (id) /-! ### Non-linear maps close to affine maps In this section we study a map `f` such that `∥f x - f y - f' (x - y)∥ ≤ c * ∥x - y∥` on an open set `s`, where `f' : E →L[𝕜] F` is a continuous linear map and `c` is suitably small. Maps of this type behave like `f a + f' (x - a)` near each `a ∈ s`. When `f'` is onto, we show that `f` is locally onto. When `f'` is a continuous linear equiv, we show that `f` is a homeomorphism between `s` and `f '' s`. More precisely, we define `approximates_linear_on.to_local_homeomorph` to be a `local_homeomorph` with `to_fun = f`, `source = s`, and `target = f '' s`. Maps of this type naturally appear in the proof of the inverse function theorem (see next section), and `approximates_linear_on.to_local_homeomorph` will imply that the locally inverse function exists. We define this auxiliary notion to split the proof of the inverse function theorem into small lemmas. This approach makes it possible - to prove a lower estimate on the size of the domain of the inverse function; - to reuse parts of the proofs in the case if a function is not strictly differentiable. E.g., for a function `f : E × F → G` with estimates on `f x y₁ - f x y₂` but not on `f x₁ y - f x₂ y`. -/ /-- We say that `f` approximates a continuous linear map `f'` on `s` with constant `c`, if `∥f x - f y - f' (x - y)∥ ≤ c * ∥x - y∥` whenever `x, y ∈ s`. This predicate is defined to facilitate the splitting of the inverse function theorem into small lemmas. Some of these lemmas can be useful, e.g., to prove that the inverse function is defined on a specific set. -/ def approximates_linear_on (f : E → F) (f' : E →L[𝕜] F) (s : set E) (c : ℝ≥0) : Prop := ∀ (x ∈ s) (y ∈ s), ∥f x - f y - f' (x - y)∥ ≤ c * ∥x - y∥ namespace approximates_linear_on variables [cs : complete_space E] {f : E → F} /-! First we prove some properties of a function that `approximates_linear_on` a (not necessarily invertible) continuous linear map. -/ section variables {f' : E →L[𝕜] F} {s t : set E} {c c' : ℝ≥0} theorem mono_num (hc : c ≤ c') (hf : approximates_linear_on f f' s c) : approximates_linear_on f f' s c' := λ x hx y hy, le_trans (hf x hx y hy) (mul_le_mul_of_nonneg_right hc $ norm_nonneg _) theorem mono_set (hst : s ⊆ t) (hf : approximates_linear_on f f' t c) : approximates_linear_on f f' s c := λ x hx y hy, hf x (hst hx) y (hst hy) lemma lipschitz_sub (hf : approximates_linear_on f f' s c) : lipschitz_with c (λ x : s, f x - f' x) := begin refine lipschitz_with.of_dist_le_mul (λ x y, _), rw [dist_eq_norm, subtype.dist_eq, dist_eq_norm], convert hf x x.2 y y.2 using 2, rw [f'.map_sub], abel end protected lemma lipschitz (hf : approximates_linear_on f f' s c) : lipschitz_with (nnnorm f' + c) (s.restrict f) := by simpa only [restrict_apply, add_sub_cancel'_right] using (f'.lipschitz.restrict s).add hf.lipschitz_sub protected lemma continuous (hf : approximates_linear_on f f' s c) : continuous (s.restrict f) := hf.lipschitz.continuous protected lemma continuous_on (hf : approximates_linear_on f f' s c) : continuous_on f s := continuous_on_iff_continuous_restrict.2 hf.continuous end section locally_onto /-! We prove that a function which is linearly approximated by a continuous linear map with a nonlinear right inverse is locally onto. This will apply to the case where the approximating map is a linear equivalence, for the local inverse theorem, but also whenever the approximating map is onto, by Banach's open mapping theorem. -/ include cs variables {s : set E} {c : ℝ≥0} {f' : E →L[𝕜] F} /-- If a function is linearly approximated by a continuous linear map with a (possibly nonlinear) right inverse, then it is locally onto: a ball of an explicit radius is included in the image of the map. -/ theorem surj_on_closed_ball_of_nonlinear_right_inverse (hf : approximates_linear_on f f' s c) (f'symm : f'.nonlinear_right_inverse) {ε : ℝ} {b : E} (ε0 : 0 ≤ ε) (hε : closed_ball b ε ⊆ s) : surj_on f (closed_ball b ε) (closed_ball (f b) (((f'symm.nnnorm : ℝ)⁻¹ - c) * ε)) := begin assume y hy, cases le_or_lt (f'symm.nnnorm : ℝ) ⁻¹ c with hc hc, { refine ⟨b, by simp [ε0], _⟩, have : dist y (f b) ≤ 0 := (mem_closed_ball.1 hy).trans (mul_nonpos_of_nonpos_of_nonneg (by linarith) ε0), simp only [dist_le_zero] at this, rw this }, have If' : (0 : ℝ) < f'symm.nnnorm, by { rw [← inv_pos], exact (nnreal.coe_nonneg _).trans_lt hc }, have Icf' : (c : ℝ) * f'symm.nnnorm < 1, by rwa [inv_eq_one_div, lt_div_iff If'] at hc, have Jf' : (f'symm.nnnorm : ℝ) ≠ 0 := ne_of_gt If', have Jcf' : (1 : ℝ) - c * f'symm.nnnorm ≠ 0, by { apply ne_of_gt, linarith }, /- We have to show that `y` can be written as `f x` for some `x ∈ closed_ball b ε`. The idea of the proof is to apply the Banach contraction principle to the map `g : x ↦ x + f'symm (y - f x)`, as a fixed point of this map satisfies `f x = y`. When `f'symm` is a genuine linear inverse, `g` is a contracting map. In our case, since `f'symm` is nonlinear, this map is not contracting (it is not even continuous), but still the proof of the contraction theorem holds: `uₙ = gⁿ b` is a Cauchy sequence, converging exponentially fast to the desired point `x`. Instead of appealing to general results, we check this by hand. The main point is that `f (u n)` becomes exponentially close to `y`, and therefore `dist (u (n+1)) (u n)` becomes exponentally small, making it possible to get an inductive bound on `dist (u n) b`, from which one checks that `u n` stays in the ball on which one has a control. Therefore, the bound can be checked at the next step, and so on inductively. -/ set g := λ x, x + f'symm (y - f x) with hg, set u := λ (n : ℕ), g ^[n] b with hu, have usucc : ∀ n, u (n + 1) = g (u n), by simp [hu, ← iterate_succ_apply' g _ b], -- First bound: if `f z` is close to `y`, then `g z` is close to `z` (i.e., almost a fixed point). have A : ∀ z, dist (g z) z ≤ f'symm.nnnorm * dist (f z) y, { assume z, rw [dist_eq_norm, hg, add_sub_cancel', dist_eq_norm'], exact f'symm.bound _ }, -- Second bound: if `z` and `g z` are in the set with good control, then `f (g z)` becomes closer -- to `y` than `f z` was (this uses the linear approximation property, and is the reason for the -- choice of the formula for `g`). have B : ∀ z ∈ closed_ball b ε, g z ∈ closed_ball b ε → dist (f (g z)) y ≤ c * f'symm.nnnorm * dist (f z) y, { assume z hz hgz, set v := f'symm (y - f z) with hv, calc dist (f (g z)) y = ∥f (z + v) - y∥ : by rw [dist_eq_norm] ... = ∥f (z + v) - f z - f' v + f' v - (y - f z)∥ : by { congr' 1, abel } ... = ∥f (z + v) - f z - f' ((z + v) - z)∥ : by simp only [continuous_linear_map.nonlinear_right_inverse.right_inv, add_sub_cancel', sub_add_cancel] ... ≤ c * ∥(z + v) - z∥ : hf _ (hε hgz) _ (hε hz) ... ≤ c * (f'symm.nnnorm * dist (f z) y) : begin apply mul_le_mul_of_nonneg_left _ (nnreal.coe_nonneg c), simpa [hv, dist_eq_norm'] using f'symm.bound (y - f z), end ... = c * f'symm.nnnorm * dist (f z) y : by ring }, -- Third bound: a complicated bound on `dist w b` (that will show up in the induction) is enough -- to check that `w` is in the ball on which one has controls. Will be used to check that `u n` -- belongs to this ball for all `n`. have C : ∀ (n : ℕ) (w : E), dist w b ≤ f'symm.nnnorm * (1 - (c * f'symm.nnnorm)^n) / (1 - c * f'symm.nnnorm) * dist (f b) y → w ∈ closed_ball b ε, { assume n w hw, apply hw.trans, rw [div_mul_eq_mul_div, div_le_iff], swap, { linarith }, calc (f'symm.nnnorm : ℝ) * (1 - (c * f'symm.nnnorm) ^ n) * dist (f b) y = f'symm.nnnorm * dist (f b) y * (1 - (c * f'symm.nnnorm) ^ n) : by ring ... ≤ f'symm.nnnorm * dist (f b) y * 1 : begin apply mul_le_mul_of_nonneg_left _ (mul_nonneg (nnreal.coe_nonneg _) dist_nonneg), rw [sub_le_self_iff], exact pow_nonneg (mul_nonneg (nnreal.coe_nonneg _) (nnreal.coe_nonneg _)) _, end ... ≤ f'symm.nnnorm * (((f'symm.nnnorm : ℝ)⁻¹ - c) * ε) : by { rw [mul_one], exact mul_le_mul_of_nonneg_left (mem_closed_ball'.1 hy) (nnreal.coe_nonneg _) } ... = ε * (1 - c * f'symm.nnnorm) : by { field_simp, ring } }, /- Main inductive control: `f (u n)` becomes exponentially close to `y`, and therefore `dist (u (n+1)) (u n)` becomes exponentally small, making it possible to get an inductive bound on `dist (u n) b`, from which one checks that `u n` remains in the ball on which we have estimates. -/ have D : ∀ (n : ℕ), dist (f (u n)) y ≤ (c * f'symm.nnnorm)^n * dist (f b) y ∧ dist (u n) b ≤ f'symm.nnnorm * (1 - (c * f'symm.nnnorm)^n) / (1 - c * f'symm.nnnorm) * dist (f b) y, { assume n, induction n with n IH, { simp [hu, le_refl] }, rw usucc, have Ign : dist (g (u n)) b ≤ f'symm.nnnorm * (1 - (c * f'symm.nnnorm)^n.succ) / (1 - c * f'symm.nnnorm) * dist (f b) y := calc dist (g (u n)) b ≤ dist (g (u n)) (u n) + dist (u n) b : dist_triangle _ _ _ ... ≤ f'symm.nnnorm * dist (f (u n)) y + dist (u n) b : add_le_add (A _) (le_refl _) ... ≤ f'symm.nnnorm * ((c * f'symm.nnnorm)^n * dist (f b) y) + f'symm.nnnorm * (1 - (c * f'symm.nnnorm)^n) / (1 - c * f'symm.nnnorm) * dist (f b) y : add_le_add (mul_le_mul_of_nonneg_left IH.1 (nnreal.coe_nonneg _)) IH.2 ... = f'symm.nnnorm * (1 - (c * f'symm.nnnorm)^n.succ) / (1 - c * f'symm.nnnorm) * dist (f b) y : by { field_simp [Jcf'], ring_exp }, refine ⟨_, Ign⟩, calc dist (f (g (u n))) y ≤ c * f'symm.nnnorm * dist (f (u n)) y : B _ (C n _ IH.2) (C n.succ _ Ign) ... ≤ (c * f'symm.nnnorm) * ((c * f'symm.nnnorm)^n * dist (f b) y) : mul_le_mul_of_nonneg_left IH.1 (mul_nonneg (nnreal.coe_nonneg _) (nnreal.coe_nonneg _)) ... = (c * f'symm.nnnorm) ^ n.succ * dist (f b) y : by ring_exp }, -- Deduce from the inductive bound that `uₙ` is a Cauchy sequence, therefore converging. have : cauchy_seq u, { have : ∀ (n : ℕ), dist (u n) (u (n+1)) ≤ f'symm.nnnorm * dist (f b) y * (c * f'symm.nnnorm)^n, { assume n, calc dist (u n) (u (n+1)) = dist (g (u n)) (u n) : by rw [usucc, dist_comm] ... ≤ f'symm.nnnorm * dist (f (u n)) y : A _ ... ≤ f'symm.nnnorm * ((c * f'symm.nnnorm)^n * dist (f b) y) : mul_le_mul_of_nonneg_left (D n).1 (nnreal.coe_nonneg _) ... = f'symm.nnnorm * dist (f b) y * (c * f'symm.nnnorm)^n : by ring }, exact cauchy_seq_of_le_geometric _ _ Icf' this }, obtain ⟨x, hx⟩ : ∃ x, tendsto u at_top (𝓝 x) := cauchy_seq_tendsto_of_complete this, -- As all the `uₙ` belong to the ball `closed_ball b ε`, so does their limit `x`. have xmem : x ∈ closed_ball b ε := is_closed_ball.mem_of_tendsto hx (eventually_of_forall (λ n, C n _ (D n).2)), refine ⟨x, xmem, _⟩, -- It remains to check that `f x = y`. This follows from continuity of `f` on `closed_ball b ε` -- and from the fact that `f uₙ` is converging to `y` by construction. have hx' : tendsto u at_top (𝓝[closed_ball b ε] x), { simp only [nhds_within, tendsto_inf, hx, true_and, ge_iff_le, tendsto_principal], exact eventually_of_forall (λ n, C n _ (D n).2) }, have T1 : tendsto (λ n, f (u n)) at_top (𝓝 (f x)) := (hf.continuous_on.mono hε x xmem).tendsto.comp hx', have T2 : tendsto (λ n, f (u n)) at_top (𝓝 y), { rw tendsto_iff_dist_tendsto_zero, refine squeeze_zero (λ n, dist_nonneg) (λ n, (D n).1) _, simpa using (tendsto_pow_at_top_nhds_0_of_lt_1 (mul_nonneg (nnreal.coe_nonneg _) (nnreal.coe_nonneg _)) Icf').mul tendsto_const_nhds }, exact tendsto_nhds_unique T1 T2, end lemma open_image (hf : approximates_linear_on f f' s c) (f'symm : f'.nonlinear_right_inverse) (hs : is_open s) (hc : subsingleton F ∨ c < f'symm.nnnorm⁻¹) : is_open (f '' s) := begin cases hc with hE hc, { resetI, apply is_open_discrete }, simp only [is_open_iff_mem_nhds, nhds_basis_closed_ball.mem_iff, ball_image_iff] at hs ⊢, intros x hx, rcases hs x hx with ⟨ε, ε0, hε⟩, refine ⟨(f'symm.nnnorm⁻¹ - c) * ε, mul_pos (sub_pos.2 hc) ε0, _⟩, exact (hf.surj_on_closed_ball_of_nonlinear_right_inverse f'symm (le_of_lt ε0) hε).mono hε (subset.refl _) end lemma image_mem_nhds (hf : approximates_linear_on f f' s c) (f'symm : f'.nonlinear_right_inverse) {x : E} (hs : s ∈ 𝓝 x) (hc : subsingleton F ∨ c < f'symm.nnnorm⁻¹) : f '' s ∈ 𝓝 (f x) := begin obtain ⟨t, hts, ht, xt⟩ : ∃ t ⊆ s, is_open t ∧ x ∈ t := _root_.mem_nhds_iff.1 hs, have := is_open.mem_nhds ((hf.mono_set hts).open_image f'symm ht hc) (mem_image_of_mem _ xt), exact mem_of_superset this (image_subset _ hts), end lemma map_nhds_eq (hf : approximates_linear_on f f' s c) (f'symm : f'.nonlinear_right_inverse) {x : E} (hs : s ∈ 𝓝 x) (hc : subsingleton F ∨ c < f'symm.nnnorm⁻¹) : map f (𝓝 x) = 𝓝 (f x) := begin refine le_antisymm ((hf.continuous_on x (mem_of_mem_nhds hs)).continuous_at hs) (le_map (λ t ht, _)), have : f '' (s ∩ t) ∈ 𝓝 (f x) := (hf.mono_set (inter_subset_left s t)).image_mem_nhds f'symm (inter_mem hs ht) hc, exact mem_of_superset this (image_subset _ (inter_subset_right _ _)), end end locally_onto /-! From now on we assume that `f` approximates an invertible continuous linear map `f : E ≃L[𝕜] F`. We also assume that either `E = {0}`, or `c < ∥f'⁻¹∥⁻¹`. We use `N` as an abbreviation for `∥f'⁻¹∥`. -/ variables {f' : E ≃L[𝕜] F} {s : set E} {c : ℝ≥0} local notation `N` := nnnorm (f'.symm : F →L[𝕜] E) protected lemma antilipschitz (hf : approximates_linear_on f (f' : E →L[𝕜] F) s c) (hc : subsingleton E ∨ c < N⁻¹) : antilipschitz_with (N⁻¹ - c)⁻¹ (s.restrict f) := begin cases hc with hE hc, { haveI : subsingleton s := ⟨λ x y, subtype.eq $ @subsingleton.elim _ hE _ _⟩, exact antilipschitz_with.of_subsingleton }, convert (f'.antilipschitz.restrict s).add_lipschitz_with hf.lipschitz_sub hc, simp [restrict] end protected lemma injective (hf : approximates_linear_on f (f' : E →L[𝕜] F) s c) (hc : subsingleton E ∨ c < N⁻¹) : injective (s.restrict f) := (hf.antilipschitz hc).injective protected lemma inj_on (hf : approximates_linear_on f (f' : E →L[𝕜] F) s c) (hc : subsingleton E ∨ c < N⁻¹) : inj_on f s := inj_on_iff_injective.2 $ hf.injective hc /-- A map approximating a linear equivalence on a set defines a local equivalence on this set. Should not be used outside of this file, because it is superseded by `to_local_homeomorph` below. This is a first step towards the inverse function. -/ def to_local_equiv (hf : approximates_linear_on f (f' : E →L[𝕜] F) s c) (hc : subsingleton E ∨ c < N⁻¹) : local_equiv E F := (hf.inj_on hc).to_local_equiv _ _ /-- The inverse function is continuous on `f '' s`. Use properties of `local_homeomorph` instead. -/ lemma inverse_continuous_on (hf : approximates_linear_on f (f' : E →L[𝕜] F) s c) (hc : subsingleton E ∨ c < N⁻¹) : continuous_on (hf.to_local_equiv hc).symm (f '' s) := begin apply continuous_on_iff_continuous_restrict.2, refine ((hf.antilipschitz hc).to_right_inv_on' _ (hf.to_local_equiv hc).right_inv').continuous, exact (λ x hx, (hf.to_local_equiv hc).map_target hx) end include cs section variables (f s) /-- Given a function `f` that approximates a linear equivalence on an open set `s`, returns a local homeomorph with `to_fun = f` and `source = s`. -/ def to_local_homeomorph (hf : approximates_linear_on f (f' : E →L[𝕜] F) s c) (hc : subsingleton E ∨ c < N⁻¹) (hs : is_open s) : local_homeomorph E F := { to_local_equiv := hf.to_local_equiv hc, open_source := hs, open_target := hf.open_image f'.to_nonlinear_right_inverse hs (by rwa f'.to_linear_equiv.to_equiv.subsingleton_congr at hc), continuous_to_fun := hf.continuous_on, continuous_inv_fun := hf.inverse_continuous_on hc } end @[simp] lemma to_local_homeomorph_coe (hf : approximates_linear_on f (f' : E →L[𝕜] F) s c) (hc : subsingleton E ∨ c < N⁻¹) (hs : is_open s) : (hf.to_local_homeomorph f s hc hs : E → F) = f := rfl @[simp] lemma to_local_homeomorph_source (hf : approximates_linear_on f (f' : E →L[𝕜] F) s c) (hc : subsingleton E ∨ c < N⁻¹) (hs : is_open s) : (hf.to_local_homeomorph f s hc hs).source = s := rfl @[simp] lemma to_local_homeomorph_target (hf : approximates_linear_on f (f' : E →L[𝕜] F) s c) (hc : subsingleton E ∨ c < N⁻¹) (hs : is_open s) : (hf.to_local_homeomorph f s hc hs).target = f '' s := rfl lemma closed_ball_subset_target (hf : approximates_linear_on f (f' : E →L[𝕜] F) s c) (hc : subsingleton E ∨ c < N⁻¹) (hs : is_open s) {b : E} (ε0 : 0 ≤ ε) (hε : closed_ball b ε ⊆ s) : closed_ball (f b) ((N⁻¹ - c) * ε) ⊆ (hf.to_local_homeomorph f s hc hs).target := (hf.surj_on_closed_ball_of_nonlinear_right_inverse f'.to_nonlinear_right_inverse ε0 hε).mono hε (subset.refl _) end approximates_linear_on /-! ### Inverse function theorem Now we prove the inverse function theorem. Let `f : E → F` be a map defined on a complete vector space `E`. Assume that `f` has an invertible derivative `f' : E ≃L[𝕜] F` at `a : E` in the strict sense. Then `f` approximates `f'` in the sense of `approximates_linear_on` on an open neighborhood of `a`, and we can apply `approximates_linear_on.to_local_homeomorph` to construct the inverse function. -/ namespace has_strict_fderiv_at /-- If `f` has derivative `f'` at `a` in the strict sense and `c > 0`, then `f` approximates `f'` with constant `c` on some neighborhood of `a`. -/ lemma approximates_deriv_on_nhds {f : E → F} {f' : E →L[𝕜] F} {a : E} (hf : has_strict_fderiv_at f f' a) {c : ℝ≥0} (hc : subsingleton E ∨ 0 < c) : ∃ s ∈ 𝓝 a, approximates_linear_on f f' s c := begin cases hc with hE hc, { refine ⟨univ, is_open.mem_nhds is_open_univ trivial, λ x hx y hy, _⟩, simp [@subsingleton.elim E hE x y] }, have := hf.def hc, rw [nhds_prod_eq, filter.eventually, mem_prod_same_iff] at this, rcases this with ⟨s, has, hs⟩, exact ⟨s, has, λ x hx y hy, hs (mk_mem_prod hx hy)⟩ end lemma map_nhds_eq_of_surj [complete_space E] [complete_space F] {f : E → F} {f' : E →L[𝕜] F} {a : E} (hf : has_strict_fderiv_at f (f' : E →L[𝕜] F) a) (h : f'.range = ⊤) : map f (𝓝 a) = 𝓝 (f a) := begin let f'symm := f'.nonlinear_right_inverse_of_surjective h, set c : ℝ≥0 := f'symm.nnnorm⁻¹ / 2 with hc, have f'symm_pos : 0 < f'symm.nnnorm := f'.nonlinear_right_inverse_of_surjective_nnnorm_pos h, have cpos : 0 < c, by simp [hc, nnreal.half_pos, nnreal.inv_pos, f'symm_pos], obtain ⟨s, s_nhds, hs⟩ : ∃ s ∈ 𝓝 a, approximates_linear_on f f' s c := hf.approximates_deriv_on_nhds (or.inr cpos), apply hs.map_nhds_eq f'symm s_nhds (or.inr (nnreal.half_lt_self _)), simp [ne_of_gt f'symm_pos], end variables [cs : complete_space E] {f : E → F} {f' : E ≃L[𝕜] F} {a : E} lemma approximates_deriv_on_open_nhds (hf : has_strict_fderiv_at f (f' : E →L[𝕜] F) a) : ∃ (s : set E) (hs : a ∈ s ∧ is_open s), approximates_linear_on f (f' : E →L[𝕜] F) s ((nnnorm (f'.symm : F →L[𝕜] E))⁻¹ / 2) := begin refine ((nhds_basis_opens a).exists_iff _).1 _, exact (λ s t, approximates_linear_on.mono_set), exact (hf.approximates_deriv_on_nhds $ f'.subsingleton_or_nnnorm_symm_pos.imp id $ λ hf', nnreal.half_pos $ nnreal.inv_pos.2 $ hf') end include cs variable (f) /-- Given a function with an invertible strict derivative at `a`, returns a `local_homeomorph` with `to_fun = f` and `a ∈ source`. This is a part of the inverse function theorem. The other part `has_strict_fderiv_at.to_local_inverse` states that the inverse function of this `local_homeomorph` has derivative `f'.symm`. -/ def to_local_homeomorph (hf : has_strict_fderiv_at f (f' : E →L[𝕜] F) a) : local_homeomorph E F := approximates_linear_on.to_local_homeomorph f (classical.some hf.approximates_deriv_on_open_nhds) (classical.some_spec hf.approximates_deriv_on_open_nhds).snd (f'.subsingleton_or_nnnorm_symm_pos.imp id $ λ hf', nnreal.half_lt_self $ ne_of_gt $ nnreal.inv_pos.2 $ hf') (classical.some_spec hf.approximates_deriv_on_open_nhds).fst.2 variable {f} @[simp] lemma to_local_homeomorph_coe (hf : has_strict_fderiv_at f (f' : E →L[𝕜] F) a) : (hf.to_local_homeomorph f : E → F) = f := rfl lemma mem_to_local_homeomorph_source (hf : has_strict_fderiv_at f (f' : E →L[𝕜] F) a) : a ∈ (hf.to_local_homeomorph f).source := (classical.some_spec hf.approximates_deriv_on_open_nhds).fst.1 lemma image_mem_to_local_homeomorph_target (hf : has_strict_fderiv_at f (f' : E →L[𝕜] F) a) : f a ∈ (hf.to_local_homeomorph f).target := (hf.to_local_homeomorph f).map_source hf.mem_to_local_homeomorph_source lemma map_nhds_eq_of_equiv (hf : has_strict_fderiv_at f (f' : E →L[𝕜] F) a) : map f (𝓝 a) = 𝓝 (f a) := (hf.to_local_homeomorph f).map_nhds_eq hf.mem_to_local_homeomorph_source variables (f f' a) /-- Given a function `f` with an invertible derivative, returns a function that is locally inverse to `f`. -/ def local_inverse (hf : has_strict_fderiv_at f (f' : E →L[𝕜] F) a) : F → E := (hf.to_local_homeomorph f).symm variables {f f' a} lemma local_inverse_def (hf : has_strict_fderiv_at f (f' : E →L[𝕜] F) a) : hf.local_inverse f _ _ = (hf.to_local_homeomorph f).symm := rfl lemma eventually_left_inverse (hf : has_strict_fderiv_at f (f' : E →L[𝕜] F) a) : ∀ᶠ x in 𝓝 a, hf.local_inverse f f' a (f x) = x := (hf.to_local_homeomorph f).eventually_left_inverse hf.mem_to_local_homeomorph_source @[simp] lemma local_inverse_apply_image (hf : has_strict_fderiv_at f (f' : E →L[𝕜] F) a) : hf.local_inverse f f' a (f a) = a := hf.eventually_left_inverse.self_of_nhds lemma eventually_right_inverse (hf : has_strict_fderiv_at f (f' : E →L[𝕜] F) a) : ∀ᶠ y in 𝓝 (f a), f (hf.local_inverse f f' a y) = y := (hf.to_local_homeomorph f).eventually_right_inverse' hf.mem_to_local_homeomorph_source lemma local_inverse_continuous_at (hf : has_strict_fderiv_at f (f' : E →L[𝕜] F) a) : continuous_at (hf.local_inverse f f' a) (f a) := (hf.to_local_homeomorph f).continuous_at_symm hf.image_mem_to_local_homeomorph_target lemma local_inverse_tendsto (hf : has_strict_fderiv_at f (f' : E →L[𝕜] F) a) : tendsto (hf.local_inverse f f' a) (𝓝 $ f a) (𝓝 a) := (hf.to_local_homeomorph f).tendsto_symm hf.mem_to_local_homeomorph_source lemma local_inverse_unique (hf : has_strict_fderiv_at f (f' : E →L[𝕜] F) a) {g : F → E} (hg : ∀ᶠ x in 𝓝 a, g (f x) = x) : ∀ᶠ y in 𝓝 (f a), g y = local_inverse f f' a hf y := eventually_eq_of_left_inv_of_right_inv hg hf.eventually_right_inverse $ (hf.to_local_homeomorph f).tendsto_symm hf.mem_to_local_homeomorph_source /-- If `f` has an invertible derivative `f'` at `a` in the sense of strict differentiability `(hf)`, then the inverse function `hf.local_inverse f` has derivative `f'.symm` at `f a`. -/ theorem to_local_inverse (hf : has_strict_fderiv_at f (f' : E →L[𝕜] F) a) : has_strict_fderiv_at (hf.local_inverse f f' a) (f'.symm : F →L[𝕜] E) (f a) := (hf.to_local_homeomorph f).has_strict_fderiv_at_symm hf.image_mem_to_local_homeomorph_target $ by simpa [← local_inverse_def] using hf /-- If `f : E → F` has an invertible derivative `f'` at `a` in the sense of strict differentiability and `g (f x) = x` in a neighborhood of `a`, then `g` has derivative `f'.symm` at `f a`. For a version assuming `f (g y) = y` and continuity of `g` at `f a` but not `[complete_space E]` see `of_local_left_inverse`. -/ theorem to_local_left_inverse (hf : has_strict_fderiv_at f (f' : E →L[𝕜] F) a) {g : F → E} (hg : ∀ᶠ x in 𝓝 a, g (f x) = x) : has_strict_fderiv_at g (f'.symm : F →L[𝕜] E) (f a) := hf.to_local_inverse.congr_of_eventually_eq $ (hf.local_inverse_unique hg).mono $ λ _, eq.symm end has_strict_fderiv_at /-- If a function has an invertible strict derivative at all points, then it is an open map. -/ lemma open_map_of_strict_fderiv_equiv [complete_space E] {f : E → F} {f' : E → E ≃L[𝕜] F} (hf : ∀ x, has_strict_fderiv_at f (f' x : E →L[𝕜] F) x) : is_open_map f := is_open_map_iff_nhds_le.2 $ λ x, (hf x).map_nhds_eq_of_equiv.ge /-! ### Inverse function theorem, 1D case In this case we prove a version of the inverse function theorem for maps `f : 𝕜 → 𝕜`. We use `continuous_linear_equiv.units_equiv_aut` to translate `has_strict_deriv_at f f' a` and `f' ≠ 0` into `has_strict_fderiv_at f (_ : 𝕜 ≃L[𝕜] 𝕜) a`. -/ namespace has_strict_deriv_at variables [cs : complete_space 𝕜] {f : 𝕜 → 𝕜} {f' a : 𝕜} (hf : has_strict_deriv_at f f' a) (hf' : f' ≠ 0) include cs variables (f f' a) /-- A function that is inverse to `f` near `a`. -/ @[reducible] def local_inverse : 𝕜 → 𝕜 := (hf.has_strict_fderiv_at_equiv hf').local_inverse _ _ _ variables {f f' a} lemma map_nhds_eq : map f (𝓝 a) = 𝓝 (f a) := (hf.has_strict_fderiv_at_equiv hf').map_nhds_eq_of_equiv theorem to_local_inverse : has_strict_deriv_at (hf.local_inverse f f' a hf') f'⁻¹ (f a) := (hf.has_strict_fderiv_at_equiv hf').to_local_inverse theorem to_local_left_inverse {g : 𝕜 → 𝕜} (hg : ∀ᶠ x in 𝓝 a, g (f x) = x) : has_strict_deriv_at g f'⁻¹ (f a) := (hf.has_strict_fderiv_at_equiv hf').to_local_left_inverse hg end has_strict_deriv_at /-- If a function has a non-zero strict derivative at all points, then it is an open map. -/ lemma open_map_of_strict_deriv [complete_space 𝕜] {f f' : 𝕜 → 𝕜} (hf : ∀ x, has_strict_deriv_at f (f' x) x) (h0 : ∀ x, f' x ≠ 0) : is_open_map f := is_open_map_iff_nhds_le.2 $ λ x, ((hf x).map_nhds_eq (h0 x)).ge /-! ### Inverse function theorem, smooth case -/ namespace times_cont_diff_at variables {𝕂 : Type*} [is_R_or_C 𝕂] variables {E' : Type*} [normed_group E'] [normed_space 𝕂 E'] variables {F' : Type*} [normed_group F'] [normed_space 𝕂 F'] variables [complete_space E'] (f : E' → F') {f' : E' ≃L[𝕂] F'} {a : E'} /-- Given a `times_cont_diff` function over `𝕂` (which is `ℝ` or `ℂ`) with an invertible derivative at `a`, returns a `local_homeomorph` with `to_fun = f` and `a ∈ source`. -/ def to_local_homeomorph {n : with_top ℕ} (hf : times_cont_diff_at 𝕂 n f a) (hf' : has_fderiv_at f (f' : E' →L[𝕂] F') a) (hn : 1 ≤ n) : local_homeomorph E' F' := (hf.has_strict_fderiv_at' hf' hn).to_local_homeomorph f variable {f} @[simp] lemma to_local_homeomorph_coe {n : with_top ℕ} (hf : times_cont_diff_at 𝕂 n f a) (hf' : has_fderiv_at f (f' : E' →L[𝕂] F') a) (hn : 1 ≤ n) : (hf.to_local_homeomorph f hf' hn : E' → F') = f := rfl lemma mem_to_local_homeomorph_source {n : with_top ℕ} (hf : times_cont_diff_at 𝕂 n f a) (hf' : has_fderiv_at f (f' : E' →L[𝕂] F') a) (hn : 1 ≤ n) : a ∈ (hf.to_local_homeomorph f hf' hn).source := (hf.has_strict_fderiv_at' hf' hn).mem_to_local_homeomorph_source lemma image_mem_to_local_homeomorph_target {n : with_top ℕ} (hf : times_cont_diff_at 𝕂 n f a) (hf' : has_fderiv_at f (f' : E' →L[𝕂] F') a) (hn : 1 ≤ n) : f a ∈ (hf.to_local_homeomorph f hf' hn).target := (hf.has_strict_fderiv_at' hf' hn).image_mem_to_local_homeomorph_target /-- Given a `times_cont_diff` function over `𝕂` (which is `ℝ` or `ℂ`) with an invertible derivative at `a`, returns a function that is locally inverse to `f`. -/ def local_inverse {n : with_top ℕ} (hf : times_cont_diff_at 𝕂 n f a) (hf' : has_fderiv_at f (f' : E' →L[𝕂] F') a) (hn : 1 ≤ n) : F' → E' := (hf.has_strict_fderiv_at' hf' hn).local_inverse f f' a lemma local_inverse_apply_image {n : with_top ℕ} (hf : times_cont_diff_at 𝕂 n f a) (hf' : has_fderiv_at f (f' : E' →L[𝕂] F') a) (hn : 1 ≤ n) : hf.local_inverse hf' hn (f a) = a := (hf.has_strict_fderiv_at' hf' hn).local_inverse_apply_image /-- Given a `times_cont_diff` function over `𝕂` (which is `ℝ` or `ℂ`) with an invertible derivative at `a`, the inverse function (produced by `times_cont_diff.to_local_homeomorph`) is also `times_cont_diff`. -/ lemma to_local_inverse {n : with_top ℕ} (hf : times_cont_diff_at 𝕂 n f a) (hf' : has_fderiv_at f (f' : E' →L[𝕂] F') a) (hn : 1 ≤ n) : times_cont_diff_at 𝕂 n (hf.local_inverse hf' hn) (f a) := begin have := hf.local_inverse_apply_image hf' hn, apply (hf.to_local_homeomorph f hf' hn).times_cont_diff_at_symm (image_mem_to_local_homeomorph_target hf hf' hn), { convert hf' }, { convert hf } end end times_cont_diff_at
7ce58f8c1fa8154df99fcf9964c048c3062ee82a
77c5b91fae1b966ddd1db969ba37b6f0e4901e88
/src/topology/metric_space/hausdorff_distance.lean
4bd05cd29febb02555172d3e2d834127c7030667
[ "Apache-2.0" ]
permissive
dexmagic/mathlib
ff48eefc56e2412429b31d4fddd41a976eb287ce
7a5d15a955a92a90e1d398b2281916b9c41270b2
refs/heads/master
1,693,481,322,046
1,633,360,193,000
1,633,360,193,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
32,515
lean
/- Copyright (c) 2019 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sébastien Gouëzel -/ import topology.metric_space.isometry import topology.instances.ennreal import analysis.specific_limits /-! # Hausdorff distance The Hausdorff distance on subsets of a metric (or emetric) space. Given two subsets `s` and `t` of a metric space, their Hausdorff distance is the smallest `d` such that any point `s` is within `d` of a point in `t`, and conversely. This quantity is often infinite (think of `s` bounded and `t` unbounded), and therefore better expressed in the setting of emetric spaces. ## Main definitions This files introduces: * `inf_edist x s`, the infimum edistance of a point `x` to a set `s` in an emetric space * `Hausdorff_edist s t`, the Hausdorff edistance of two sets in an emetric space * Versions of these notions on metric spaces, called respectively `inf_dist` and `Hausdorff_dist`. -/ noncomputable theory open_locale classical nnreal ennreal topological_space universes u v w open classical set function topological_space filter namespace emetric section inf_edist variables {α : Type u} {β : Type v} [pseudo_emetric_space α] [pseudo_emetric_space β] {x y : α} {s t : set α} {Φ : α → β} /-! ### Distance of a point to a set as a function into `ℝ≥0∞`. -/ /-- The minimal edistance of a point to a set -/ def inf_edist (x : α) (s : set α) : ℝ≥0∞ := ⨅ y ∈ s, edist x y @[simp] lemma inf_edist_empty : inf_edist x ∅ = ∞ := infi_emptyset lemma le_inf_edist {d} : d ≤ inf_edist x s ↔ ∀ y ∈ s, d ≤ edist x y := by simp only [inf_edist, le_infi_iff] /-- The edist to a union is the minimum of the edists -/ @[simp] lemma inf_edist_union : inf_edist x (s ∪ t) = inf_edist x s ⊓ inf_edist x t := infi_union /-- The edist to a singleton is the edistance to the single point of this singleton -/ @[simp] lemma inf_edist_singleton : inf_edist x {y} = edist x y := infi_singleton /-- The edist to a set is bounded above by the edist to any of its points -/ lemma inf_edist_le_edist_of_mem (h : y ∈ s) : inf_edist x s ≤ edist x y := binfi_le _ h /-- If a point `x` belongs to `s`, then its edist to `s` vanishes -/ lemma inf_edist_zero_of_mem (h : x ∈ s) : inf_edist x s = 0 := nonpos_iff_eq_zero.1 $ @edist_self _ _ x ▸ inf_edist_le_edist_of_mem h /-- The edist is monotonous with respect to inclusion -/ lemma inf_edist_le_inf_edist_of_subset (h : s ⊆ t) : inf_edist x t ≤ inf_edist x s := infi_le_infi_of_subset h /-- If the edist to a set is `< r`, there exists a point in the set at edistance `< r` -/ lemma exists_edist_lt_of_inf_edist_lt {r : ℝ≥0∞} (h : inf_edist x s < r) : ∃y∈s, edist x y < r := by simpa only [inf_edist, infi_lt_iff] using h /-- The edist of `x` to `s` is bounded by the sum of the edist of `y` to `s` and the edist from `x` to `y` -/ lemma inf_edist_le_inf_edist_add_edist : inf_edist x s ≤ inf_edist y s + edist x y := calc (⨅ z ∈ s, edist x z) ≤ ⨅ z ∈ s, edist y z + edist x y : binfi_le_binfi $ λ z hz, (edist_triangle _ _ _).trans_eq (add_comm _ _) ... = (⨅ z ∈ s, edist y z) + edist x y : by simp only [ennreal.infi_add] /-- The edist to a set depends continuously on the point -/ @[continuity] lemma continuous_inf_edist : continuous (λx, inf_edist x s) := continuous_of_le_add_edist 1 (by simp) $ by simp only [one_mul, inf_edist_le_inf_edist_add_edist, forall_2_true_iff] /-- The edist to a set and to its closure coincide -/ lemma inf_edist_closure : inf_edist x (closure s) = inf_edist x s := begin refine le_antisymm (inf_edist_le_inf_edist_of_subset subset_closure) _, refine ennreal.le_of_forall_pos_le_add (λε εpos h, _), have ε0 : 0 < (ε / 2 : ℝ≥0∞) := by simpa [pos_iff_ne_zero] using εpos, have : inf_edist x (closure s) < inf_edist x (closure s) + ε/2, from ennreal.lt_add_right h.ne ε0.ne', rcases exists_edist_lt_of_inf_edist_lt this with ⟨y, ycs, hy⟩, -- y : α, ycs : y ∈ closure s, hy : edist x y < inf_edist x (closure s) + ↑ε / 2 rcases emetric.mem_closure_iff.1 ycs (ε/2) ε0 with ⟨z, zs, dyz⟩, -- z : α, zs : z ∈ s, dyz : edist y z < ↑ε / 2 calc inf_edist x s ≤ edist x z : inf_edist_le_edist_of_mem zs ... ≤ edist x y + edist y z : edist_triangle _ _ _ ... ≤ (inf_edist x (closure s) + ε / 2) + (ε/2) : add_le_add (le_of_lt hy) (le_of_lt dyz) ... = inf_edist x (closure s) + ↑ε : by rw [add_assoc, ennreal.add_halves] end /-- A point belongs to the closure of `s` iff its infimum edistance to this set vanishes -/ lemma mem_closure_iff_inf_edist_zero : x ∈ closure s ↔ inf_edist x s = 0 := ⟨λh, by rw ← inf_edist_closure; exact inf_edist_zero_of_mem h, λh, emetric.mem_closure_iff.2 $ λε εpos, exists_edist_lt_of_inf_edist_lt (by rwa h)⟩ /-- Given a closed set `s`, a point belongs to `s` iff its infimum edistance to this set vanishes -/ lemma mem_iff_inf_edist_zero_of_closed (h : is_closed s) : x ∈ s ↔ inf_edist x s = 0 := begin convert ← mem_closure_iff_inf_edist_zero, exact h.closure_eq end /-- The infimum edistance is invariant under isometries -/ lemma inf_edist_image (hΦ : isometry Φ) : inf_edist (Φ x) (Φ '' t) = inf_edist x t := by simp only [inf_edist, infi_image, hΦ.edist_eq] lemma _root_.is_open.exists_Union_is_closed {U : set α} (hU : is_open U) : ∃ F : ℕ → set α, (∀ n, is_closed (F n)) ∧ (∀ n, F n ⊆ U) ∧ ((⋃ n, F n) = U) ∧ (monotone F) := begin obtain ⟨a, a_pos, a_lt_one⟩ : ∃ (a : ℝ≥0∞), 0 < a ∧ a < 1 := exists_between (ennreal.zero_lt_one), let F := λ (n : ℕ), (λ x, inf_edist x Uᶜ) ⁻¹' (Ici (a^n)), have F_subset : ∀ n, F n ⊆ U, { assume n x hx, by_contra h, rw [← mem_compl_iff, mem_iff_inf_edist_zero_of_closed (is_open.is_closed_compl hU)] at h, have : 0 < inf_edist x Uᶜ := lt_of_lt_of_le (ennreal.pow_pos a_pos _) hx, rw h at this, exact lt_irrefl _ this }, refine ⟨F, λ n, is_closed.preimage continuous_inf_edist is_closed_Ici, F_subset, _, _⟩, show monotone F, { assume m n hmn x hx, simp only [mem_Ici, mem_preimage] at hx ⊢, apply le_trans (ennreal.pow_le_pow_of_le_one a_lt_one.le hmn) hx }, show (⋃ n, F n) = U, { refine subset.antisymm (by simp only [Union_subset_iff, F_subset, forall_const]) (λ x hx, _), have : ¬(x ∈ Uᶜ), by simpa using hx, rw mem_iff_inf_edist_zero_of_closed (is_open.is_closed_compl hU) at this, have B : 0 < inf_edist x Uᶜ, by simpa [pos_iff_ne_zero] using this, have : filter.tendsto (λ n, a^n) at_top (𝓝 0) := ennreal.tendsto_pow_at_top_nhds_0_of_lt_1 a_lt_one, rcases ((tendsto_order.1 this).2 _ B).exists with ⟨n, hn⟩, simp only [mem_Union, mem_Ici, mem_preimage], exact ⟨n, hn.le⟩ }, end end inf_edist --section /-! ### The Hausdorff distance as a function into `ℝ≥0∞`. -/ /-- The Hausdorff edistance between two sets is the smallest `r` such that each set is contained in the `r`-neighborhood of the other one -/ @[irreducible] def Hausdorff_edist {α : Type u} [pseudo_emetric_space α] (s t : set α) : ℝ≥0∞ := (⨆ x ∈ s, inf_edist x t) ⊔ (⨆ y ∈ t, inf_edist y s) lemma Hausdorff_edist_def {α : Type u} [pseudo_emetric_space α] (s t : set α) : Hausdorff_edist s t = (⨆ x ∈ s, inf_edist x t) ⊔ (⨆ y ∈ t, inf_edist y s) := by rw Hausdorff_edist section Hausdorff_edist variables {α : Type u} {β : Type v} [pseudo_emetric_space α] [pseudo_emetric_space β] {x y : α} {s t u : set α} {Φ : α → β} /-- The Hausdorff edistance of a set to itself vanishes -/ @[simp] lemma Hausdorff_edist_self : Hausdorff_edist s s = 0 := begin simp only [Hausdorff_edist_def, sup_idem, ennreal.supr_eq_zero], exact λ x hx, inf_edist_zero_of_mem hx end /-- The Haudorff edistances of `s` to `t` and of `t` to `s` coincide -/ lemma Hausdorff_edist_comm : Hausdorff_edist s t = Hausdorff_edist t s := by unfold Hausdorff_edist; apply sup_comm /-- Bounding the Hausdorff edistance by bounding the edistance of any point in each set to the other set -/ lemma Hausdorff_edist_le_of_inf_edist {r : ℝ≥0∞} (H1 : ∀x ∈ s, inf_edist x t ≤ r) (H2 : ∀x ∈ t, inf_edist x s ≤ r) : Hausdorff_edist s t ≤ r := begin simp only [Hausdorff_edist, sup_le_iff, supr_le_iff], exact ⟨H1, H2⟩ end /-- Bounding the Hausdorff edistance by exhibiting, for any point in each set, another point in the other set at controlled distance -/ lemma Hausdorff_edist_le_of_mem_edist {r : ℝ≥0∞} (H1 : ∀x ∈ s, ∃y ∈ t, edist x y ≤ r) (H2 : ∀x ∈ t, ∃y ∈ s, edist x y ≤ r) : Hausdorff_edist s t ≤ r := begin refine Hausdorff_edist_le_of_inf_edist _ _, { assume x xs, rcases H1 x xs with ⟨y, yt, hy⟩, exact le_trans (inf_edist_le_edist_of_mem yt) hy }, { assume x xt, rcases H2 x xt with ⟨y, ys, hy⟩, exact le_trans (inf_edist_le_edist_of_mem ys) hy } end /-- The distance to a set is controlled by the Hausdorff distance -/ lemma inf_edist_le_Hausdorff_edist_of_mem (h : x ∈ s) : inf_edist x t ≤ Hausdorff_edist s t := begin rw Hausdorff_edist_def, refine le_trans _ le_sup_left, exact le_bsupr x h end /-- If the Hausdorff distance is `<r`, then any point in one of the sets has a corresponding point at distance `<r` in the other set -/ lemma exists_edist_lt_of_Hausdorff_edist_lt {r : ℝ≥0∞} (h : x ∈ s) (H : Hausdorff_edist s t < r) : ∃y∈t, edist x y < r := exists_edist_lt_of_inf_edist_lt $ calc inf_edist x t ≤ Hausdorff_edist s t : inf_edist_le_Hausdorff_edist_of_mem h ... < r : H /-- The distance from `x` to `s` or `t` is controlled in terms of the Hausdorff distance between `s` and `t` -/ lemma inf_edist_le_inf_edist_add_Hausdorff_edist : inf_edist x t ≤ inf_edist x s + Hausdorff_edist s t := ennreal.le_of_forall_pos_le_add $ λε εpos h, begin have ε0 : (ε / 2 : ℝ≥0∞) ≠ 0 := by simpa [pos_iff_ne_zero] using εpos, have : inf_edist x s < inf_edist x s + ε/2 := ennreal.lt_add_right (ennreal.add_lt_top.1 h).1.ne ε0, rcases exists_edist_lt_of_inf_edist_lt this with ⟨y, ys, dxy⟩, -- y : α, ys : y ∈ s, dxy : edist x y < inf_edist x s + ↑ε / 2 have : Hausdorff_edist s t < Hausdorff_edist s t + ε/2 := ennreal.lt_add_right (ennreal.add_lt_top.1 h).2.ne ε0, rcases exists_edist_lt_of_Hausdorff_edist_lt ys this with ⟨z, zt, dyz⟩, -- z : α, zt : z ∈ t, dyz : edist y z < Hausdorff_edist s t + ↑ε / 2 calc inf_edist x t ≤ edist x z : inf_edist_le_edist_of_mem zt ... ≤ edist x y + edist y z : edist_triangle _ _ _ ... ≤ (inf_edist x s + ε/2) + (Hausdorff_edist s t + ε/2) : add_le_add dxy.le dyz.le ... = inf_edist x s + Hausdorff_edist s t + ε : by simp [ennreal.add_halves, add_comm, add_left_comm] end /-- The Hausdorff edistance is invariant under eisometries -/ lemma Hausdorff_edist_image (h : isometry Φ) : Hausdorff_edist (Φ '' s) (Φ '' t) = Hausdorff_edist s t := by simp only [Hausdorff_edist_def, supr_image, inf_edist_image h] /-- The Hausdorff distance is controlled by the diameter of the union -/ lemma Hausdorff_edist_le_ediam (hs : s.nonempty) (ht : t.nonempty) : Hausdorff_edist s t ≤ diam (s ∪ t) := begin rcases hs with ⟨x, xs⟩, rcases ht with ⟨y, yt⟩, refine Hausdorff_edist_le_of_mem_edist _ _, { intros z hz, exact ⟨y, yt, edist_le_diam_of_mem (subset_union_left _ _ hz) (subset_union_right _ _ yt)⟩ }, { intros z hz, exact ⟨x, xs, edist_le_diam_of_mem (subset_union_right _ _ hz) (subset_union_left _ _ xs)⟩ } end /-- The Hausdorff distance satisfies the triangular inequality -/ lemma Hausdorff_edist_triangle : Hausdorff_edist s u ≤ Hausdorff_edist s t + Hausdorff_edist t u := begin rw Hausdorff_edist_def, simp only [sup_le_iff, supr_le_iff], split, show ∀x ∈ s, inf_edist x u ≤ Hausdorff_edist s t + Hausdorff_edist t u, from λx xs, calc inf_edist x u ≤ inf_edist x t + Hausdorff_edist t u : inf_edist_le_inf_edist_add_Hausdorff_edist ... ≤ Hausdorff_edist s t + Hausdorff_edist t u : add_le_add_right (inf_edist_le_Hausdorff_edist_of_mem xs) _, show ∀x ∈ u, inf_edist x s ≤ Hausdorff_edist s t + Hausdorff_edist t u, from λx xu, calc inf_edist x s ≤ inf_edist x t + Hausdorff_edist t s : inf_edist_le_inf_edist_add_Hausdorff_edist ... ≤ Hausdorff_edist u t + Hausdorff_edist t s : add_le_add_right (inf_edist_le_Hausdorff_edist_of_mem xu) _ ... = Hausdorff_edist s t + Hausdorff_edist t u : by simp [Hausdorff_edist_comm, add_comm] end /-- Two sets are at zero Hausdorff edistance if and only if they have the same closure -/ lemma Hausdorff_edist_zero_iff_closure_eq_closure : Hausdorff_edist s t = 0 ↔ closure s = closure t := calc Hausdorff_edist s t = 0 ↔ s ⊆ closure t ∧ t ⊆ closure s : by simp only [Hausdorff_edist_def, ennreal.sup_eq_zero, ennreal.supr_eq_zero, ← mem_closure_iff_inf_edist_zero, subset_def] ... ↔ closure s = closure t : ⟨λ h, subset.antisymm (closure_minimal h.1 is_closed_closure) (closure_minimal h.2 is_closed_closure), λ h, ⟨h ▸ subset_closure, h.symm ▸ subset_closure⟩⟩ /-- The Hausdorff edistance between a set and its closure vanishes -/ @[simp, priority 1100] lemma Hausdorff_edist_self_closure : Hausdorff_edist s (closure s) = 0 := by rw [Hausdorff_edist_zero_iff_closure_eq_closure, closure_closure] /-- Replacing a set by its closure does not change the Hausdorff edistance. -/ @[simp] lemma Hausdorff_edist_closure₁ : Hausdorff_edist (closure s) t = Hausdorff_edist s t := begin refine le_antisymm _ _, { calc _ ≤ Hausdorff_edist (closure s) s + Hausdorff_edist s t : Hausdorff_edist_triangle ... = Hausdorff_edist s t : by simp [Hausdorff_edist_comm] }, { calc _ ≤ Hausdorff_edist s (closure s) + Hausdorff_edist (closure s) t : Hausdorff_edist_triangle ... = Hausdorff_edist (closure s) t : by simp } end /-- Replacing a set by its closure does not change the Hausdorff edistance. -/ @[simp] lemma Hausdorff_edist_closure₂ : Hausdorff_edist s (closure t) = Hausdorff_edist s t := by simp [@Hausdorff_edist_comm _ _ s _] /-- The Hausdorff edistance between sets or their closures is the same -/ @[simp] lemma Hausdorff_edist_closure : Hausdorff_edist (closure s) (closure t) = Hausdorff_edist s t := by simp /-- Two closed sets are at zero Hausdorff edistance if and only if they coincide -/ lemma Hausdorff_edist_zero_iff_eq_of_closed (hs : is_closed s) (ht : is_closed t) : Hausdorff_edist s t = 0 ↔ s = t := by rw [Hausdorff_edist_zero_iff_closure_eq_closure, hs.closure_eq, ht.closure_eq] /-- The Haudorff edistance to the empty set is infinite -/ lemma Hausdorff_edist_empty (ne : s.nonempty) : Hausdorff_edist s ∅ = ∞ := begin rcases ne with ⟨x, xs⟩, have : inf_edist x ∅ ≤ Hausdorff_edist s ∅ := inf_edist_le_Hausdorff_edist_of_mem xs, simpa using this, end /-- If a set is at finite Hausdorff edistance of a nonempty set, it is nonempty -/ lemma nonempty_of_Hausdorff_edist_ne_top (hs : s.nonempty) (fin : Hausdorff_edist s t ≠ ⊤) : t.nonempty := t.eq_empty_or_nonempty.elim (λ ht, (fin $ ht.symm ▸ Hausdorff_edist_empty hs).elim) id lemma empty_or_nonempty_of_Hausdorff_edist_ne_top (fin : Hausdorff_edist s t ≠ ⊤) : s = ∅ ∧ t = ∅ ∨ s.nonempty ∧ t.nonempty := begin cases s.eq_empty_or_nonempty with hs hs, { cases t.eq_empty_or_nonempty with ht ht, { exact or.inl ⟨hs, ht⟩ }, { rw Hausdorff_edist_comm at fin, exact or.inr ⟨nonempty_of_Hausdorff_edist_ne_top ht fin, ht⟩ } }, { exact or.inr ⟨hs, nonempty_of_Hausdorff_edist_ne_top hs fin⟩ } end end Hausdorff_edist -- section end emetric --namespace /-! Now, we turn to the same notions in metric spaces. To avoid the difficulties related to `Inf` and `Sup` on `ℝ` (which is only conditionally complete), we use the notions in `ℝ≥0∞` formulated in terms of the edistance, and coerce them to `ℝ`. Then their properties follow readily from the corresponding properties in `ℝ≥0∞`, modulo some tedious rewriting of inequalities from one to the other. -/ namespace metric section variables {α : Type u} {β : Type v} [pseudo_metric_space α] [pseudo_metric_space β] {s t u : set α} {x y : α} {Φ : α → β} open emetric /-! ### Distance of a point to a set as a function into `ℝ`. -/ /-- The minimal distance of a point to a set -/ def inf_dist (x : α) (s : set α) : ℝ := ennreal.to_real (inf_edist x s) /-- the minimal distance is always nonnegative -/ lemma inf_dist_nonneg : 0 ≤ inf_dist x s := by simp [inf_dist] /-- the minimal distance to the empty set is 0 (if you want to have the more reasonable value ∞ instead, use `inf_edist`, which takes values in ℝ≥0∞) -/ @[simp] lemma inf_dist_empty : inf_dist x ∅ = 0 := by simp [inf_dist] /-- In a metric space, the minimal edistance to a nonempty set is finite -/ lemma inf_edist_ne_top (h : s.nonempty) : inf_edist x s ≠ ⊤ := begin rcases h with ⟨y, hy⟩, apply lt_top_iff_ne_top.1, calc inf_edist x s ≤ edist x y : inf_edist_le_edist_of_mem hy ... < ⊤ : lt_top_iff_ne_top.2 (edist_ne_top _ _) end /-- The minimal distance of a point to a set containing it vanishes -/ lemma inf_dist_zero_of_mem (h : x ∈ s) : inf_dist x s = 0 := by simp [inf_edist_zero_of_mem h, inf_dist] /-- The minimal distance to a singleton is the distance to the unique point in this singleton -/ @[simp] lemma inf_dist_singleton : inf_dist x {y} = dist x y := by simp [inf_dist, inf_edist, dist_edist] /-- The minimal distance to a set is bounded by the distance to any point in this set -/ lemma inf_dist_le_dist_of_mem (h : y ∈ s) : inf_dist x s ≤ dist x y := begin rw [dist_edist, inf_dist, ennreal.to_real_le_to_real (inf_edist_ne_top ⟨_, h⟩) (edist_ne_top _ _)], exact inf_edist_le_edist_of_mem h end /-- The minimal distance is monotonous with respect to inclusion -/ lemma inf_dist_le_inf_dist_of_subset (h : s ⊆ t) (hs : s.nonempty) : inf_dist x t ≤ inf_dist x s := begin have ht : t.nonempty := hs.mono h, rw [inf_dist, inf_dist, ennreal.to_real_le_to_real (inf_edist_ne_top ht) (inf_edist_ne_top hs)], exact inf_edist_le_inf_edist_of_subset h end /-- If the minimal distance to a set is `<r`, there exists a point in this set at distance `<r` -/ lemma exists_dist_lt_of_inf_dist_lt {r : real} (h : inf_dist x s < r) (hs : s.nonempty) : ∃y∈s, dist x y < r := begin have rpos : 0 < r := lt_of_le_of_lt inf_dist_nonneg h, have : inf_edist x s < ennreal.of_real r, { rwa [inf_dist, ← ennreal.to_real_of_real (le_of_lt rpos), ennreal.to_real_lt_to_real (inf_edist_ne_top hs)] at h, simp }, rcases exists_edist_lt_of_inf_edist_lt this with ⟨y, ys, hy⟩, rw [edist_dist, ennreal.of_real_lt_of_real_iff rpos] at hy, exact ⟨y, ys, hy⟩, end /-- The minimal distance from `x` to `s` is bounded by the distance from `y` to `s`, modulo the distance between `x` and `y` -/ lemma inf_dist_le_inf_dist_add_dist : inf_dist x s ≤ inf_dist y s + dist x y := begin cases s.eq_empty_or_nonempty with hs hs, { by simp [hs, dist_nonneg] }, { rw [inf_dist, inf_dist, dist_edist, ← ennreal.to_real_add (inf_edist_ne_top hs) (edist_ne_top _ _), ennreal.to_real_le_to_real (inf_edist_ne_top hs)], { apply inf_edist_le_inf_edist_add_edist }, { simp [ennreal.add_eq_top, inf_edist_ne_top hs, edist_ne_top] }} end variable (s) /-- The minimal distance to a set is Lipschitz in point with constant 1 -/ lemma lipschitz_inf_dist_pt : lipschitz_with 1 (λx, inf_dist x s) := lipschitz_with.of_le_add $ λ x y, inf_dist_le_inf_dist_add_dist /-- The minimal distance to a set is uniformly continuous in point -/ lemma uniform_continuous_inf_dist_pt : uniform_continuous (λx, inf_dist x s) := (lipschitz_inf_dist_pt s).uniform_continuous /-- The minimal distance to a set is continuous in point -/ @[continuity] lemma continuous_inf_dist_pt : continuous (λx, inf_dist x s) := (uniform_continuous_inf_dist_pt s).continuous variable {s} /-- The minimal distance to a set and its closure coincide -/ lemma inf_dist_eq_closure : inf_dist x (closure s) = inf_dist x s := by simp [inf_dist, inf_edist_closure] /-- A point belongs to the closure of `s` iff its infimum distance to this set vanishes -/ lemma mem_closure_iff_inf_dist_zero (h : s.nonempty) : x ∈ closure s ↔ inf_dist x s = 0 := by simp [mem_closure_iff_inf_edist_zero, inf_dist, ennreal.to_real_eq_zero_iff, inf_edist_ne_top h] /-- Given a closed set `s`, a point belongs to `s` iff its infimum distance to this set vanishes -/ lemma mem_iff_inf_dist_zero_of_closed (h : is_closed s) (hs : s.nonempty) : x ∈ s ↔ inf_dist x s = 0 := begin have := @mem_closure_iff_inf_dist_zero _ _ s x hs, rwa h.closure_eq at this end /-- The infimum distance is invariant under isometries -/ lemma inf_dist_image (hΦ : isometry Φ) : inf_dist (Φ x) (Φ '' t) = inf_dist x t := by simp [inf_dist, inf_edist_image hΦ] /-! ### Distance of a point to a set as a function into `ℝ≥0`. -/ /-- The minimal distance of a point to a set as a `ℝ≥0` -/ def inf_nndist (x : α) (s : set α) : ℝ≥0 := ennreal.to_nnreal (inf_edist x s) @[simp] lemma coe_inf_nndist : (inf_nndist x s : ℝ) = inf_dist x s := rfl /-- The minimal distance to a set (as `ℝ≥0`) is Lipschitz in point with constant 1 -/ lemma lipschitz_inf_nndist_pt (s : set α) : lipschitz_with 1 (λx, inf_nndist x s) := lipschitz_with.of_le_add $ λ x y, inf_dist_le_inf_dist_add_dist /-- The minimal distance to a set (as `ℝ≥0`) is uniformly continuous in point -/ lemma uniform_continuous_inf_nndist_pt (s : set α) : uniform_continuous (λx, inf_nndist x s) := (lipschitz_inf_nndist_pt s).uniform_continuous /-- The minimal distance to a set (as `ℝ≥0`) is continuous in point -/ lemma continuous_inf_nndist_pt (s : set α) : continuous (λx, inf_nndist x s) := (uniform_continuous_inf_nndist_pt s).continuous /-! ### The Hausdorff distance as a function into `ℝ`. -/ /-- The Hausdorff distance between two sets is the smallest nonnegative `r` such that each set is included in the `r`-neighborhood of the other. If there is no such `r`, it is defined to be `0`, arbitrarily -/ def Hausdorff_dist (s t : set α) : ℝ := ennreal.to_real (Hausdorff_edist s t) /-- The Hausdorff distance is nonnegative -/ lemma Hausdorff_dist_nonneg : 0 ≤ Hausdorff_dist s t := by simp [Hausdorff_dist] /-- If two sets are nonempty and bounded in a metric space, they are at finite Hausdorff edistance. -/ lemma Hausdorff_edist_ne_top_of_nonempty_of_bounded (hs : s.nonempty) (ht : t.nonempty) (bs : bounded s) (bt : bounded t) : Hausdorff_edist s t ≠ ⊤ := begin rcases hs with ⟨cs, hcs⟩, rcases ht with ⟨ct, hct⟩, rcases (bounded_iff_subset_ball ct).1 bs with ⟨rs, hrs⟩, rcases (bounded_iff_subset_ball cs).1 bt with ⟨rt, hrt⟩, have : Hausdorff_edist s t ≤ ennreal.of_real (max rs rt), { apply Hausdorff_edist_le_of_mem_edist, { assume x xs, existsi [ct, hct], have : dist x ct ≤ max rs rt := le_trans (hrs xs) (le_max_left _ _), rwa [edist_dist, ennreal.of_real_le_of_real_iff], exact le_trans dist_nonneg this }, { assume x xt, existsi [cs, hcs], have : dist x cs ≤ max rs rt := le_trans (hrt xt) (le_max_right _ _), rwa [edist_dist, ennreal.of_real_le_of_real_iff], exact le_trans dist_nonneg this }}, exact ne_top_of_le_ne_top ennreal.of_real_ne_top this end /-- The Hausdorff distance between a set and itself is zero -/ @[simp] lemma Hausdorff_dist_self_zero : Hausdorff_dist s s = 0 := by simp [Hausdorff_dist] /-- The Hausdorff distance from `s` to `t` and from `t` to `s` coincide -/ lemma Hausdorff_dist_comm : Hausdorff_dist s t = Hausdorff_dist t s := by simp [Hausdorff_dist, Hausdorff_edist_comm] /-- The Hausdorff distance to the empty set vanishes (if you want to have the more reasonable value ∞ instead, use `Hausdorff_edist`, which takes values in ℝ≥0∞) -/ @[simp] lemma Hausdorff_dist_empty : Hausdorff_dist s ∅ = 0 := begin cases s.eq_empty_or_nonempty with h h, { simp [h] }, { simp [Hausdorff_dist, Hausdorff_edist_empty h] } end /-- The Hausdorff distance to the empty set vanishes (if you want to have the more reasonable value ∞ instead, use `Hausdorff_edist`, which takes values in ℝ≥0∞) -/ @[simp] lemma Hausdorff_dist_empty' : Hausdorff_dist ∅ s = 0 := by simp [Hausdorff_dist_comm] /-- Bounding the Hausdorff distance by bounding the distance of any point in each set to the other set -/ lemma Hausdorff_dist_le_of_inf_dist {r : ℝ} (hr : 0 ≤ r) (H1 : ∀x ∈ s, inf_dist x t ≤ r) (H2 : ∀x ∈ t, inf_dist x s ≤ r) : Hausdorff_dist s t ≤ r := begin by_cases h1 : Hausdorff_edist s t = ⊤, by rwa [Hausdorff_dist, h1, ennreal.top_to_real], cases s.eq_empty_or_nonempty with hs hs, by rwa [hs, Hausdorff_dist_empty'], cases t.eq_empty_or_nonempty with ht ht, by rwa [ht, Hausdorff_dist_empty], have : Hausdorff_edist s t ≤ ennreal.of_real r, { apply Hausdorff_edist_le_of_inf_edist _ _, { assume x hx, have I := H1 x hx, rwa [inf_dist, ← ennreal.to_real_of_real hr, ennreal.to_real_le_to_real (inf_edist_ne_top ht) ennreal.of_real_ne_top] at I }, { assume x hx, have I := H2 x hx, rwa [inf_dist, ← ennreal.to_real_of_real hr, ennreal.to_real_le_to_real (inf_edist_ne_top hs) ennreal.of_real_ne_top] at I }}, rwa [Hausdorff_dist, ← ennreal.to_real_of_real hr, ennreal.to_real_le_to_real h1 ennreal.of_real_ne_top] end /-- Bounding the Hausdorff distance by exhibiting, for any point in each set, another point in the other set at controlled distance -/ lemma Hausdorff_dist_le_of_mem_dist {r : ℝ} (hr : 0 ≤ r) (H1 : ∀x ∈ s, ∃y ∈ t, dist x y ≤ r) (H2 : ∀x ∈ t, ∃y ∈ s, dist x y ≤ r) : Hausdorff_dist s t ≤ r := begin apply Hausdorff_dist_le_of_inf_dist hr, { assume x xs, rcases H1 x xs with ⟨y, yt, hy⟩, exact le_trans (inf_dist_le_dist_of_mem yt) hy }, { assume x xt, rcases H2 x xt with ⟨y, ys, hy⟩, exact le_trans (inf_dist_le_dist_of_mem ys) hy } end /-- The Hausdorff distance is controlled by the diameter of the union -/ lemma Hausdorff_dist_le_diam (hs : s.nonempty) (bs : bounded s) (ht : t.nonempty) (bt : bounded t) : Hausdorff_dist s t ≤ diam (s ∪ t) := begin rcases hs with ⟨x, xs⟩, rcases ht with ⟨y, yt⟩, refine Hausdorff_dist_le_of_mem_dist diam_nonneg _ _, { exact λz hz, ⟨y, yt, dist_le_diam_of_mem (bounded_union.2 ⟨bs, bt⟩) (subset_union_left _ _ hz) (subset_union_right _ _ yt)⟩ }, { exact λz hz, ⟨x, xs, dist_le_diam_of_mem (bounded_union.2 ⟨bs, bt⟩) (subset_union_right _ _ hz) (subset_union_left _ _ xs)⟩ } end /-- The distance to a set is controlled by the Hausdorff distance -/ lemma inf_dist_le_Hausdorff_dist_of_mem (hx : x ∈ s) (fin : Hausdorff_edist s t ≠ ⊤) : inf_dist x t ≤ Hausdorff_dist s t := begin have ht : t.nonempty := nonempty_of_Hausdorff_edist_ne_top ⟨x, hx⟩ fin, rw [Hausdorff_dist, inf_dist, ennreal.to_real_le_to_real (inf_edist_ne_top ht) fin], exact inf_edist_le_Hausdorff_edist_of_mem hx end /-- If the Hausdorff distance is `<r`, then any point in one of the sets is at distance `<r` of a point in the other set -/ lemma exists_dist_lt_of_Hausdorff_dist_lt {r : ℝ} (h : x ∈ s) (H : Hausdorff_dist s t < r) (fin : Hausdorff_edist s t ≠ ⊤) : ∃y∈t, dist x y < r := begin have r0 : 0 < r := lt_of_le_of_lt (Hausdorff_dist_nonneg) H, have : Hausdorff_edist s t < ennreal.of_real r, by rwa [Hausdorff_dist, ← ennreal.to_real_of_real (le_of_lt r0), ennreal.to_real_lt_to_real fin (ennreal.of_real_ne_top)] at H, rcases exists_edist_lt_of_Hausdorff_edist_lt h this with ⟨y, hy, yr⟩, rw [edist_dist, ennreal.of_real_lt_of_real_iff r0] at yr, exact ⟨y, hy, yr⟩ end /-- If the Hausdorff distance is `<r`, then any point in one of the sets is at distance `<r` of a point in the other set -/ lemma exists_dist_lt_of_Hausdorff_dist_lt' {r : ℝ} (h : y ∈ t) (H : Hausdorff_dist s t < r) (fin : Hausdorff_edist s t ≠ ⊤) : ∃x∈s, dist x y < r := begin rw Hausdorff_dist_comm at H, rw Hausdorff_edist_comm at fin, simpa [dist_comm] using exists_dist_lt_of_Hausdorff_dist_lt h H fin end /-- The infimum distance to `s` and `t` are the same, up to the Hausdorff distance between `s` and `t` -/ lemma inf_dist_le_inf_dist_add_Hausdorff_dist (fin : Hausdorff_edist s t ≠ ⊤) : inf_dist x t ≤ inf_dist x s + Hausdorff_dist s t := begin rcases empty_or_nonempty_of_Hausdorff_edist_ne_top fin with ⟨hs,ht⟩|⟨hs,ht⟩, { simp only [hs, ht, Hausdorff_dist_empty, inf_dist_empty, zero_add] }, rw [inf_dist, inf_dist, Hausdorff_dist, ← ennreal.to_real_add (inf_edist_ne_top hs) fin, ennreal.to_real_le_to_real (inf_edist_ne_top ht)], { exact inf_edist_le_inf_edist_add_Hausdorff_edist }, { exact ennreal.add_ne_top.2 ⟨inf_edist_ne_top hs, fin⟩ } end /-- The Hausdorff distance is invariant under isometries -/ lemma Hausdorff_dist_image (h : isometry Φ) : Hausdorff_dist (Φ '' s) (Φ '' t) = Hausdorff_dist s t := by simp [Hausdorff_dist, Hausdorff_edist_image h] /-- The Hausdorff distance satisfies the triangular inequality -/ lemma Hausdorff_dist_triangle (fin : Hausdorff_edist s t ≠ ⊤) : Hausdorff_dist s u ≤ Hausdorff_dist s t + Hausdorff_dist t u := begin by_cases Hausdorff_edist s u = ⊤, { calc Hausdorff_dist s u = 0 + 0 : by simp [Hausdorff_dist, h] ... ≤ Hausdorff_dist s t + Hausdorff_dist t u : add_le_add (Hausdorff_dist_nonneg) (Hausdorff_dist_nonneg) }, { have Dtu : Hausdorff_edist t u < ⊤ := calc Hausdorff_edist t u ≤ Hausdorff_edist t s + Hausdorff_edist s u : Hausdorff_edist_triangle ... = Hausdorff_edist s t + Hausdorff_edist s u : by simp [Hausdorff_edist_comm] ... < ⊤ : by simp [lt_top_iff_ne_top, *], rw [Hausdorff_dist, Hausdorff_dist, Hausdorff_dist, ← ennreal.to_real_add fin Dtu.ne, ennreal.to_real_le_to_real h], { exact Hausdorff_edist_triangle }, { simp [ennreal.add_eq_top, lt_top_iff_ne_top.1 Dtu, fin] }} end /-- The Hausdorff distance satisfies the triangular inequality -/ lemma Hausdorff_dist_triangle' (fin : Hausdorff_edist t u ≠ ⊤) : Hausdorff_dist s u ≤ Hausdorff_dist s t + Hausdorff_dist t u := begin rw Hausdorff_edist_comm at fin, have I : Hausdorff_dist u s ≤ Hausdorff_dist u t + Hausdorff_dist t s := Hausdorff_dist_triangle fin, simpa [add_comm, Hausdorff_dist_comm] using I end /-- The Hausdorff distance between a set and its closure vanish -/ @[simp, priority 1100] lemma Hausdorff_dist_self_closure : Hausdorff_dist s (closure s) = 0 := by simp [Hausdorff_dist] /-- Replacing a set by its closure does not change the Hausdorff distance. -/ @[simp] lemma Hausdorff_dist_closure₁ : Hausdorff_dist (closure s) t = Hausdorff_dist s t := by simp [Hausdorff_dist] /-- Replacing a set by its closure does not change the Hausdorff distance. -/ @[simp] lemma Hausdorff_dist_closure₂ : Hausdorff_dist s (closure t) = Hausdorff_dist s t := by simp [Hausdorff_dist] /-- The Hausdorff distance between two sets and their closures coincide -/ @[simp] lemma Hausdorff_dist_closure : Hausdorff_dist (closure s) (closure t) = Hausdorff_dist s t := by simp [Hausdorff_dist] /-- Two sets are at zero Hausdorff distance if and only if they have the same closures -/ lemma Hausdorff_dist_zero_iff_closure_eq_closure (fin : Hausdorff_edist s t ≠ ⊤) : Hausdorff_dist s t = 0 ↔ closure s = closure t := by simp [Hausdorff_edist_zero_iff_closure_eq_closure.symm, Hausdorff_dist, ennreal.to_real_eq_zero_iff, fin] /-- Two closed sets are at zero Hausdorff distance if and only if they coincide -/ lemma Hausdorff_dist_zero_iff_eq_of_closed (hs : is_closed s) (ht : is_closed t) (fin : Hausdorff_edist s t ≠ ⊤) : Hausdorff_dist s t = 0 ↔ s = t := by simp [(Hausdorff_edist_zero_iff_eq_of_closed hs ht).symm, Hausdorff_dist, ennreal.to_real_eq_zero_iff, fin] end --section end metric --namespace
9c7fefe317ecf5ed05ac4cc1c1202ed18ddc3f1d
42610cc2e5db9c90269470365e6056df0122eaa0
/library/data/real/basic.lean
13f3bdf55c4a441571f799fe482b3bfba72ec7de
[ "Apache-2.0" ]
permissive
tomsib2001/lean
2ab59bfaebd24a62109f800dcf4a7139ebd73858
eb639a7d53fb40175bea5c8da86b51d14bb91f76
refs/heads/master
1,586,128,387,740
1,468,968,950,000
1,468,968,950,000
61,027,234
0
0
null
1,465,813,585,000
1,465,813,585,000
null
UTF-8
Lean
false
false
42,450
lean
/- Copyright (c) 2015 Robert Y. Lewis. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Robert Y. Lewis The real numbers, constructed as equivalence classes of Cauchy sequences of rationals. This construction follows Bishop and Bridges (1985). The construction of the reals is arranged in four files. - basic.lean proves properties about regular sequences of rationals in the namespace rat_seq, defines ℝ to be the quotient type of regular sequences mod equivalence, and shows ℝ is a ring in namespace real. No classical axioms are used. - order.lean defines an order on regular sequences and lifts the order to ℝ. In the namespace real, ℝ is shown to be an ordered ring. No classical axioms are used. - division.lean defines the inverse of a regular sequence and lifts this to ℝ. If a sequence is equivalent to the 0 sequence, its inverse is the zero sequence. In the namespace real, ℝ is shown to be an ordered field. This construction is classical. - complete.lean -/ import data.nat data.rat.order data.pnat open nat eq pnat open - [coercion] rat local postfix `⁻¹` := pnat.inv -- small helper lemmas private theorem s_mul_assoc_lemma_3 (a b n : ℕ+) (p : ℚ) : p * ((a * n)⁻¹ + (b * n)⁻¹) = p * (a⁻¹ + b⁻¹) * n⁻¹ := by rewrite [rat.mul_assoc, right_distrib, *pnat.inv_mul_eq_mul_inv] private theorem s_mul_assoc_lemma_4 {n : ℕ+} {ε q : ℚ} (Hε : ε > 0) (Hq : q > 0) (H : n ≥ pceil (q / ε)) : q * n⁻¹ ≤ ε := begin note H2 := pceil_helper H (div_pos_of_pos_of_pos Hq Hε), note H3 := mul_le_of_le_div (div_pos_of_pos_of_pos Hq Hε) H2, rewrite -(one_mul ε), apply mul_le_mul_of_mul_div_le, repeat assumption end private theorem find_thirds (a b : ℚ) (H : b > 0) : ∃ n : ℕ+, a + n⁻¹ + n⁻¹ + n⁻¹ < a + b := let n := pceil (of_nat 4 / b) in have of_nat 3 * n⁻¹ < b, from calc of_nat 3 * n⁻¹ < of_nat 4 * n⁻¹ : mul_lt_mul_of_pos_right dec_trivial !pnat.inv_pos ... ≤ of_nat 4 * (b / of_nat 4) : mul_le_mul_of_nonneg_left (!inv_pceil_div dec_trivial H) !of_nat_nonneg ... = b / of_nat 4 * of_nat 4 : mul.comm ... = b : !div_mul_cancel dec_trivial, exists.intro n (calc a + n⁻¹ + n⁻¹ + n⁻¹ = a + (1 + 1 + 1) * n⁻¹ : by rewrite [+right_distrib, +rat.one_mul, -+add.assoc] ... = a + of_nat 3 * n⁻¹ : {show 1+1+1=of_nat 3, from dec_trivial} ... < a + b : rat.add_lt_add_left this a) private theorem squeeze {a b : ℚ} (H : ∀ j : ℕ+, a ≤ b + j⁻¹ + j⁻¹ + j⁻¹) : a ≤ b := begin apply le_of_not_gt, intro Hb, cases exists_add_lt_and_pos_of_lt Hb with [c, Hc], cases find_thirds b c (and.right Hc) with [j, Hbj], have Ha : a > b + j⁻¹ + j⁻¹ + j⁻¹, from lt.trans Hbj (and.left Hc), apply (not_le_of_gt Ha) !H end private theorem rewrite_helper (a b c d : ℚ) : a * b - c * d = a * (b - d) + (a - c) * d := by rewrite [mul_sub_left_distrib, mul_sub_right_distrib, add_sub, sub_add_cancel] private theorem rewrite_helper3 (a b c d e f g: ℚ) : a * (b + c) - (d * e + f * g) = (a * b - d * e) + (a * c - f * g) := by rewrite [left_distrib, add_sub_comm] private theorem rewrite_helper4 (a b c d : ℚ) : a * b - c * d = (a * b - a * d) + (a * d - c * d) := by rewrite[add_sub, sub_add_cancel] private theorem rewrite_helper5 (a b x y : ℚ) : a - b = (a - x) + (x - y) + (y - b) := by rewrite[*add_sub, *sub_add_cancel] private theorem rewrite_helper7 (a b c d x : ℚ) : a * b * c - d = (b * c) * (a - x) + (x * b * c - d) := begin have ∀ (a b c : ℚ), a * b * c = b * c * a, begin intros a b c, rewrite (mul.right_comm b c a), rewrite (mul.comm b a) end, rewrite [mul_sub_left_distrib, add_sub], calc a * b * c - d = a * b * c - x * b * c + x * b * c - d : sub_add_cancel ... = b * c * a - b * c * x + x * b * c - d : begin rewrite [this a b c, this x b c] end end private theorem ineq_helper (a b : ℚ) (k m n : ℕ+) (H : a ≤ (k * 2 * m)⁻¹ + (k * 2 * n)⁻¹) (H2 : b ≤ (k * 2 * m)⁻¹ + (k * 2 * n)⁻¹) : (rat_of_pnat k) * a + b * (rat_of_pnat k) ≤ m⁻¹ + n⁻¹ := have H3 : (k * 2 * m)⁻¹ + (k * 2 * n)⁻¹ = (2 * k)⁻¹ * (m⁻¹ + n⁻¹), begin rewrite [left_distrib, *pnat.inv_mul_eq_mul_inv], rewrite (mul.comm k⁻¹) end, have H' : a ≤ (2 * k)⁻¹ * (m⁻¹ + n⁻¹), begin rewrite H3 at H, exact H end, have H2' : b ≤ (2 * k)⁻¹ * (m⁻¹ + n⁻¹), begin rewrite H3 at H2, exact H2 end, have a + b ≤ k⁻¹ * (m⁻¹ + n⁻¹), from calc a + b ≤ (2 * k)⁻¹ * (m⁻¹ + n⁻¹) + (2 * k)⁻¹ * (m⁻¹ + n⁻¹) : add_le_add H' H2' ... = ((2 * k)⁻¹ + (2 * k)⁻¹) * (m⁻¹ + n⁻¹) : by rewrite right_distrib ... = k⁻¹ * (m⁻¹ + n⁻¹) : by rewrite (pnat.add_halves k), calc (rat_of_pnat k) * a + b * (rat_of_pnat k) = (rat_of_pnat k) * a + (rat_of_pnat k) * b : by rewrite (mul.comm b) ... = (rat_of_pnat k) * (a + b) : left_distrib ... ≤ (rat_of_pnat k) * (k⁻¹ * (m⁻¹ + n⁻¹)) : iff.mp (!le_iff_mul_le_mul_left !rat_of_pnat_is_pos) this ... = m⁻¹ + n⁻¹ : by rewrite[-mul.assoc, pnat.inv_cancel_left, one_mul] private theorem factor_lemma (a b c d e : ℚ) : abs (a + b + c - (d + (b + e))) = abs ((a - d) + (c - e)) := !congr_arg (calc a + b + c - (d + (b + e)) = a + b + c - (d + b + e) : rat.add_assoc ... = a + b - (d + b) + (c - e) : add_sub_comm ... = a + b - b - d + (c - e) : sub_add_eq_sub_sub_swap ... = a - d + (c - e) : add_sub_cancel) private theorem factor_lemma_2 (a b c d : ℚ) : (a + b) + (c + d) = (a + c) + (d + b) := begin note H := (binary.comm4 add.comm add.assoc a b c d), rewrite [add.comm b d at H], exact H end -------------------------------------- -- define cauchy sequences and equivalence. show equivalence actually is one namespace rat_seq notation `seq` := ℕ+ → ℚ definition regular (s : seq) := ∀ m n : ℕ+, abs (s m - s n) ≤ m⁻¹ + n⁻¹ definition equiv (s t : seq) := ∀ n : ℕ+, abs (s n - t n) ≤ n⁻¹ + n⁻¹ infix `≡` := equiv theorem equiv.refl (s : seq) : s ≡ s := begin intros, rewrite [sub_self, abs_zero], apply add_invs_nonneg end theorem equiv.symm (s t : seq) (H : s ≡ t) : t ≡ s := begin intros, rewrite [-abs_neg, neg_sub], exact H n end theorem bdd_of_eq {s t : seq} (H : s ≡ t) : ∀ j : ℕ+, ∀ n : ℕ+, n ≥ 2 * j → abs (s n - t n) ≤ j⁻¹ := begin intros [j, n, Hn], apply le.trans, apply H, rewrite -(pnat.add_halves j), apply add_le_add, apply inv_ge_of_le Hn, apply inv_ge_of_le Hn end theorem eq_of_bdd {s t : seq} (Hs : regular s) (Ht : regular t) (H : ∀ j : ℕ+, ∃ Nj : ℕ+, ∀ n : ℕ+, Nj ≤ n → abs (s n - t n) ≤ j⁻¹) : s ≡ t := begin intros, have Hj : (∀ j : ℕ+, abs (s n - t n) ≤ n⁻¹ + n⁻¹ + j⁻¹ + j⁻¹ + j⁻¹), begin intros, cases H j with [Nj, HNj], rewrite [-(sub_add_cancel (s n) (s (max j Nj))), +sub_eq_add_neg, add.assoc (s n + -s (max j Nj)), ↑regular at *], apply rat.le_trans, apply abs_add_le_abs_add_abs, apply rat.le_trans, apply add_le_add, apply Hs, rewrite [-(sub_add_cancel (s (max j Nj)) (t (max j Nj))), add.assoc], apply abs_add_le_abs_add_abs, apply rat.le_trans, apply rat.add_le_add_left, apply add_le_add, apply HNj (max j Nj) (pnat.max_right j Nj), apply Ht, have hsimp : ∀ m : ℕ+, n⁻¹ + m⁻¹ + (j⁻¹ + (m⁻¹ + n⁻¹)) = n⁻¹ + n⁻¹ + j⁻¹ + (m⁻¹ + m⁻¹), from λm, calc n⁻¹ + m⁻¹ + (j⁻¹ + (m⁻¹ + n⁻¹)) = n⁻¹ + (j⁻¹ + (m⁻¹ + n⁻¹)) + m⁻¹ : add.right_comm ... = n⁻¹ + (j⁻¹ + m⁻¹ + n⁻¹) + m⁻¹ : add.assoc ... = n⁻¹ + (n⁻¹ + (j⁻¹ + m⁻¹)) + m⁻¹ : add.comm ... = n⁻¹ + n⁻¹ + j⁻¹ + (m⁻¹ + m⁻¹) : by rewrite[-*add.assoc], rewrite hsimp, have Hms : (max j Nj)⁻¹ + (max j Nj)⁻¹ ≤ j⁻¹ + j⁻¹, begin apply add_le_add, apply inv_ge_of_le (pnat.max_left j Nj), apply inv_ge_of_le (pnat.max_left j Nj), end, apply (calc n⁻¹ + n⁻¹ + j⁻¹ + ((max j Nj)⁻¹ + (max j Nj)⁻¹) ≤ n⁻¹ + n⁻¹ + j⁻¹ + (j⁻¹ + j⁻¹) : rat.add_le_add_left Hms ... = n⁻¹ + n⁻¹ + j⁻¹ + j⁻¹ + j⁻¹ : by rewrite *rat.add_assoc) end, apply squeeze Hj end theorem eq_of_bdd_var {s t : seq} (Hs : regular s) (Ht : regular t) (H : ∀ ε : ℚ, ε > 0 → ∃ Nj : ℕ+, ∀ n : ℕ+, Nj ≤ n → abs (s n - t n) ≤ ε) : s ≡ t := begin apply eq_of_bdd, repeat assumption, intros, apply H, apply pnat.inv_pos end theorem bdd_of_eq_var {s t : seq} (Hs : regular s) (Ht : regular t) (Heq : s ≡ t) : ∀ ε : ℚ, ε > 0 → ∃ Nj : ℕ+, ∀ n : ℕ+, Nj ≤ n → abs (s n - t n) ≤ ε := begin intro ε Hε, cases pnat_bound Hε with [N, HN], existsi 2 * N, intro n Hn, apply rat.le_trans, apply bdd_of_eq Heq N n Hn, exact HN -- assumption -- TODO: something funny here; what is 11.source.to_has_le_2? end theorem equiv.trans (s t u : seq) (Hs : regular s) (Ht : regular t) (Hu : regular u) (H : s ≡ t) (H2 : t ≡ u) : s ≡ u := begin apply eq_of_bdd Hs Hu, intros, existsi 2 * (2 * j), intro n Hn, rewrite [-sub_add_cancel (s n) (t n), *sub_eq_add_neg, add.assoc], apply rat.le_trans, apply abs_add_le_abs_add_abs, have Hst : abs (s n - t n) ≤ (2 * j)⁻¹, from bdd_of_eq H _ _ Hn, have Htu : abs (t n - u n) ≤ (2 * j)⁻¹, from bdd_of_eq H2 _ _ Hn, rewrite -(pnat.add_halves j), apply add_le_add, exact Hst, exact Htu end ----------------------------------- -- define operations on cauchy sequences. show operations preserve regularity private definition K (s : seq) : ℕ+ := pnat.pos (ubound (abs (s pone)) + 1 + 1) dec_trivial private theorem canon_bound {s : seq} (Hs : regular s) (n : ℕ+) : abs (s n) ≤ rat_of_pnat (K s) := calc abs (s n) = abs (s n - s pone + s pone) : by rewrite sub_add_cancel ... ≤ abs (s n - s pone) + abs (s pone) : abs_add_le_abs_add_abs ... ≤ n⁻¹ + pone⁻¹ + abs (s pone) : add_le_add_right !Hs ... = n⁻¹ + (1 + abs (s pone)) : by rewrite [pone_inv, rat.add_assoc] ... ≤ 1 + (1 + abs (s pone)) : add_le_add_right (inv_le_one n) ... = abs (s pone) + (1 + 1) : by rewrite [add.comm 1 (abs (s pone)), add.comm 1, rat.add_assoc] ... ≤ of_nat (ubound (abs (s pone))) + (1 + 1) : add_le_add_right (!ubound_ge) ... = of_nat (ubound (abs (s pone)) + (1 + 1)) : of_nat_add ... = of_nat (ubound (abs (s pone)) + 1 + 1) : add.assoc ... = rat_of_pnat (K s) : by esimp theorem bdd_of_regular {s : seq} (H : regular s) : ∃ b : ℚ, ∀ n : ℕ+, s n ≤ b := begin existsi rat_of_pnat (K s), intros, apply rat.le_trans, apply le_abs_self, apply canon_bound H end theorem bdd_of_regular_strict {s : seq} (H : regular s) : ∃ b : ℚ, ∀ n : ℕ+, s n < b := begin cases bdd_of_regular H with [b, Hb], existsi b + 1, intro n, apply rat.lt_of_le_of_lt, apply Hb, apply lt_add_of_pos_right, apply zero_lt_one end definition K₂ (s t : seq) := max (K s) (K t) private theorem K₂_symm (s t : seq) : K₂ s t = K₂ t s := if H : K s < K t then (have H1 : K₂ s t = K t, from pnat.max_eq_right H, have H2 : K₂ t s = K t, from pnat.max_eq_left (pnat.not_lt_of_ge (pnat.le_of_lt H)), by rewrite [H1, -H2]) else (have H1 : K₂ s t = K s, from pnat.max_eq_left H, if J : K t < K s then (have H2 : K₂ t s = K s, from pnat.max_eq_right J, by rewrite [H1, -H2]) else (have Heq : K t = K s, from pnat.eq_of_le_of_ge (pnat.le_of_not_gt H) (pnat.le_of_not_gt J), by rewrite [↑K₂, Heq])) theorem canon_2_bound_left (s t : seq) (Hs : regular s) (n : ℕ+) : abs (s n) ≤ rat_of_pnat (K₂ s t) := calc abs (s n) ≤ rat_of_pnat (K s) : canon_bound Hs n ... ≤ rat_of_pnat (K₂ s t) : rat_of_pnat_le_of_pnat_le (!pnat.max_left) theorem canon_2_bound_right (s t : seq) (Ht : regular t) (n : ℕ+) : abs (t n) ≤ rat_of_pnat (K₂ s t) := calc abs (t n) ≤ rat_of_pnat (K t) : canon_bound Ht n ... ≤ rat_of_pnat (K₂ s t) : rat_of_pnat_le_of_pnat_le (!pnat.max_right) definition sadd (s t : seq) : seq := λ n, (s (2 * n)) + (t (2 * n)) theorem reg_add_reg {s t : seq} (Hs : regular s) (Ht : regular t) : regular (sadd s t) := begin rewrite [↑regular at *, ↑sadd], intros, rewrite add_sub_comm, apply rat.le_trans, apply abs_add_le_abs_add_abs, rewrite add_halves_double, apply add_le_add, apply Hs, apply Ht end definition smul (s t : seq) : seq := λ n : ℕ+, (s ((K₂ s t) * 2 * n)) * (t ((K₂ s t) * 2 * n)) theorem reg_mul_reg {s t : seq} (Hs : regular s) (Ht : regular t) : regular (smul s t) := begin rewrite [↑regular at *, ↑smul], intros, rewrite rewrite_helper, apply rat.le_trans, apply abs_add_le_abs_add_abs, apply rat.le_trans, apply add_le_add, rewrite abs_mul, apply mul_le_mul_of_nonneg_right, apply canon_2_bound_left s t Hs, apply abs_nonneg, rewrite abs_mul, apply mul_le_mul_of_nonneg_left, apply canon_2_bound_right s t Ht, apply abs_nonneg, apply ineq_helper, apply Ht, apply Hs end definition sneg (s : seq) : seq := λ n : ℕ+, - (s n) theorem reg_neg_reg {s : seq} (Hs : regular s) : regular (sneg s) := begin rewrite [↑regular at *, ↑sneg], intros, rewrite [-abs_neg, neg_sub, sub_neg_eq_add, add.comm], apply Hs end ----------------------------------- -- show properties of +, *, - definition zero : seq := λ n, 0 definition one : seq := λ n, 1 theorem s_add_comm (s t : seq) : sadd s t ≡ sadd t s := begin esimp [sadd], intro n, rewrite [sub_add_eq_sub_sub, add_sub_cancel, sub_self, abs_zero], apply add_invs_nonneg end theorem s_add_assoc (s t u : seq) (Hs : regular s) (Hu : regular u) : sadd (sadd s t) u ≡ sadd s (sadd t u) := begin rewrite [↑sadd, ↑equiv, ↑regular at *], intros, rewrite factor_lemma, apply rat.le_trans, apply abs_add_le_abs_add_abs, apply rat.le_trans, rotate 1, apply add_le_add_right, apply inv_two_mul_le_inv, rewrite [-(pnat.add_halves (2 * n)), -(pnat.add_halves n), factor_lemma_2], apply add_le_add, apply Hs, apply Hu end theorem s_mul_comm (s t : seq) : smul s t ≡ smul t s := begin rewrite ↑smul, intros n, rewrite [*(K₂_symm s t), rat.mul_comm, sub_self, abs_zero], apply add_invs_nonneg end private definition DK (s t : seq) := (K₂ s t) * 2 private theorem DK_rewrite (s t : seq) : (K₂ s t) * 2 = DK s t := rfl private definition TK (s t u : seq) := (DK (λ (n : ℕ+), s (mul (DK s t) n) * t (mul (DK s t) n)) u) private theorem TK_rewrite (s t u : seq) : (DK (λ (n : ℕ+), s (mul (DK s t) n) * t (mul (DK s t) n)) u) = TK s t u := rfl private theorem s_mul_assoc_lemma (s t u : seq) (a b c d : ℕ+) : abs (s a * t a * u b - s c * t d * u d) ≤ abs (t a) * abs (u b) * abs (s a - s c) + abs (s c) * abs (t a) * abs (u b - u d) + abs (s c) * abs (u d) * abs (t a - t d) := begin rewrite (rewrite_helper7 _ _ _ _ (s c)), apply rat.le_trans, apply abs_add_le_abs_add_abs, rewrite rat.add_assoc, apply add_le_add, rewrite 2 abs_mul, apply le.refl, rewrite [*rat.mul_assoc, -mul_sub_left_distrib, -left_distrib, abs_mul], apply mul_le_mul_of_nonneg_left, rewrite rewrite_helper, apply le.trans, apply abs_add_le_abs_add_abs, apply add_le_add, rewrite abs_mul, apply rat.le_refl, rewrite [abs_mul, rat.mul_comm], apply rat.le_refl, apply abs_nonneg end private definition Kq (s : seq) := rat_of_pnat (K s) + 1 private theorem Kq_bound {s : seq} (H : regular s) : ∀ n, abs (s n) ≤ Kq s := begin intros, apply le_of_lt, apply lt_of_le_of_lt, apply canon_bound H, apply lt_add_of_pos_right, apply zero_lt_one end private theorem Kq_bound_nonneg {s : seq} (H : regular s) : 0 ≤ Kq s := le.trans !abs_nonneg (Kq_bound H 2) private theorem Kq_bound_pos {s : seq} (H : regular s) : 0 < Kq s := have H1 : 0 ≤ rat_of_pnat (K s), from rat.le_trans (!abs_nonneg) (canon_bound H 2), add_pos_of_nonneg_of_pos H1 rat.zero_lt_one private theorem s_mul_assoc_lemma_5 {s t u : seq} (Hs : regular s) (Ht : regular t) (Hu : regular u) (a b c : ℕ+) : abs (t a) * abs (u b) * abs (s a - s c) ≤ (Kq t) * (Kq u) * (a⁻¹ + c⁻¹) := begin repeat apply mul_le_mul, apply Kq_bound Ht, apply Kq_bound Hu, apply abs_nonneg, apply Kq_bound_nonneg Ht, apply Hs, apply abs_nonneg, apply rat.mul_nonneg, apply Kq_bound_nonneg Ht, apply Kq_bound_nonneg Hu, end private theorem s_mul_assoc_lemma_2 {s t u : seq} (Hs : regular s) (Ht : regular t) (Hu : regular u) (a b c d : ℕ+) : abs (t a) * abs (u b) * abs (s a - s c) + abs (s c) * abs (t a) * abs (u b - u d) + abs (s c) * abs (u d) * abs (t a - t d) ≤ (Kq t) * (Kq u) * (a⁻¹ + c⁻¹) + (Kq s) * (Kq t) * (b⁻¹ + d⁻¹) + (Kq s) * (Kq u) * (a⁻¹ + d⁻¹) := begin apply add_le_add_three, repeat (assumption | apply mul_le_mul | apply Kq_bound | apply Kq_bound_nonneg | apply abs_nonneg), apply Hs, apply abs_nonneg, apply rat.mul_nonneg, repeat (assumption | apply mul_le_mul | apply Kq_bound | apply Kq_bound_nonneg | apply abs_nonneg), apply Hu, apply abs_nonneg, apply rat.mul_nonneg, repeat (assumption | apply mul_le_mul | apply Kq_bound | apply Kq_bound_nonneg | apply abs_nonneg), apply Ht, apply abs_nonneg, apply rat.mul_nonneg, repeat (apply Kq_bound_nonneg; assumption) end theorem s_mul_assoc {s t u : seq} (Hs : regular s) (Ht : regular t) (Hu : regular u) : smul (smul s t) u ≡ smul s (smul t u) := begin apply eq_of_bdd_var, repeat apply reg_mul_reg, apply Hs, apply Ht, apply Hu, apply reg_mul_reg Hs, apply reg_mul_reg Ht Hu, intros, apply exists.intro, intros, rewrite [↑smul, *DK_rewrite, *TK_rewrite, -*pnat.mul_assoc, -*mul.assoc], apply rat.le_trans, apply s_mul_assoc_lemma, apply rat.le_trans, apply s_mul_assoc_lemma_2, apply Hs, apply Ht, apply Hu, rewrite [*s_mul_assoc_lemma_3, -distrib_three_right], apply s_mul_assoc_lemma_4, apply a, repeat apply add_pos, repeat apply mul_pos, apply Kq_bound_pos Ht, apply Kq_bound_pos Hu, apply add_pos, repeat apply pnat.inv_pos, repeat apply rat.mul_pos, apply Kq_bound_pos Hs, apply Kq_bound_pos Ht, apply add_pos, repeat apply pnat.inv_pos, repeat apply rat.mul_pos, apply Kq_bound_pos Hs, apply Kq_bound_pos Hu, apply add_pos, repeat apply pnat.inv_pos, apply a_1 end theorem zero_is_reg : regular zero := begin rewrite [↑regular, ↑zero], intros, rewrite [sub_zero, abs_zero], apply add_invs_nonneg end theorem s_zero_add (s : seq) (H : regular s) : sadd zero s ≡ s := begin rewrite [↑sadd, ↑zero, ↑equiv, ↑regular at H], intros, rewrite [rat.zero_add], apply rat.le_trans, apply H, apply add_le_add, apply inv_two_mul_le_inv, apply rat.le_refl end theorem s_add_zero (s : seq) (H : regular s) : sadd s zero ≡ s := begin rewrite [↑sadd, ↑zero, ↑equiv, ↑regular at H], intros, rewrite [rat.add_zero], apply rat.le_trans, apply H, apply add_le_add, apply inv_two_mul_le_inv, apply rat.le_refl end theorem s_neg_cancel (s : seq) (H : regular s) : sadd (sneg s) s ≡ zero := begin rewrite [↑sadd, ↑sneg, ↑regular at H, ↑zero, ↑equiv], intros, rewrite [neg_add_eq_sub, sub_self, sub_zero, abs_zero], apply add_invs_nonneg end theorem neg_s_cancel (s : seq) (H : regular s) : sadd s (sneg s) ≡ zero := begin apply equiv.trans, rotate 3, apply s_add_comm, apply s_neg_cancel s H, repeat (apply reg_add_reg | apply reg_neg_reg | assumption), apply zero_is_reg end theorem add_well_defined {s t u v : seq} (Hs : regular s) (Ht : regular t) (Hu : regular u) (Hv : regular v) (Esu : s ≡ u) (Etv : t ≡ v) : sadd s t ≡ sadd u v := begin rewrite [↑sadd, ↑equiv at *], intros, rewrite [add_sub_comm, add_halves_double], apply rat.le_trans, apply abs_add_le_abs_add_abs, apply add_le_add, apply Esu, apply Etv end set_option tactic.goal_names false private theorem mul_bound_helper {s t : seq} (Hs : regular s) (Ht : regular t) (a b c : ℕ+) (j : ℕ+) : ∃ N : ℕ+, ∀ n : ℕ+, n ≥ N → abs (s (a * n) * t (b * n) - s (c * n) * t (c * n)) ≤ j⁻¹ := begin existsi pceil (((rat_of_pnat (K s)) * (b⁻¹ + c⁻¹) + (a⁻¹ + c⁻¹) * (rat_of_pnat (K t))) * (rat_of_pnat j)), intros n Hn, rewrite rewrite_helper4, apply rat.le_trans, apply abs_add_le_abs_add_abs, apply rat.le_trans, rotate 1, show n⁻¹ * ((rat_of_pnat (K s)) * (b⁻¹ + c⁻¹)) + n⁻¹ * ((a⁻¹ + c⁻¹) * (rat_of_pnat (K t))) ≤ j⁻¹, begin rewrite -left_distrib, apply rat.le_trans, apply mul_le_mul_of_nonneg_right, apply pceil_helper Hn, { repeat (apply mul_pos | apply add_pos | apply rat_of_pnat_is_pos | apply pnat.inv_pos) }, apply rat.le_of_lt, apply add_pos, apply rat.mul_pos, apply rat_of_pnat_is_pos, apply add_pos, apply pnat.inv_pos, apply pnat.inv_pos, apply rat.mul_pos, apply add_pos, apply pnat.inv_pos, apply pnat.inv_pos, apply rat_of_pnat_is_pos, have H : (rat_of_pnat (K s) * (b⁻¹ + c⁻¹) + (a⁻¹ + c⁻¹) * rat_of_pnat (K t)) ≠ 0, begin apply ne_of_gt, repeat (apply mul_pos | apply add_pos | apply rat_of_pnat_is_pos | apply pnat.inv_pos), end, rewrite (!div_helper H), apply rat.le_refl end, apply add_le_add, rewrite [-mul_sub_left_distrib, abs_mul], apply rat.le_trans, apply mul_le_mul, apply canon_bound, apply Hs, apply Ht, apply abs_nonneg, apply rat.le_of_lt, apply rat_of_pnat_is_pos, rewrite [*pnat.inv_mul_eq_mul_inv, -right_distrib, -rat.mul_assoc, rat.mul_comm], apply mul_le_mul_of_nonneg_left, apply rat.le_refl, apply rat.le_of_lt, apply pnat.inv_pos, rewrite [-mul_sub_right_distrib, abs_mul], apply rat.le_trans, apply mul_le_mul, apply Hs, apply canon_bound, apply Ht, apply abs_nonneg, apply add_invs_nonneg, rewrite [*pnat.inv_mul_eq_mul_inv, -right_distrib, mul.comm _ n⁻¹, rat.mul_assoc], apply mul_le_mul, repeat apply rat.le_refl, apply rat.le_of_lt, apply rat.mul_pos, apply add_pos, repeat apply pnat.inv_pos, apply rat_of_pnat_is_pos, apply rat.le_of_lt, apply pnat.inv_pos end theorem s_distrib {s t u : seq} (Hs : regular s) (Ht : regular t) (Hu : regular u) : smul s (sadd t u) ≡ sadd (smul s t) (smul s u) := begin apply eq_of_bdd, repeat (assumption | apply reg_add_reg | apply reg_mul_reg), intros, let exh1 := λ a b c, mul_bound_helper Hs Ht a b c (2 * j), apply exists.elim, apply exh1, rotate 3, intros N1 HN1, let exh2 := λ d e f, mul_bound_helper Hs Hu d e f (2 * j), apply exists.elim, apply exh2, rotate 3, intros N2 HN2, existsi max N1 N2, intros n Hn, rewrite [↑sadd at *, ↑smul, rewrite_helper3, -pnat.add_halves j, -*pnat.mul_assoc at *], apply rat.le_trans, apply abs_add_le_abs_add_abs, apply add_le_add, apply HN1, apply pnat.le_trans, apply pnat.max_left N1 N2, apply Hn, apply HN2, apply pnat.le_trans, apply pnat.max_right N1 N2, apply Hn end theorem mul_zero_equiv_zero {s t : seq} (Hs : regular s) (Ht : regular t) (Htz : t ≡ zero) : smul s t ≡ zero := begin apply eq_of_bdd_var, apply reg_mul_reg Hs Ht, apply zero_is_reg, intro ε Hε, let Bd := bdd_of_eq_var Ht zero_is_reg Htz (ε / (Kq s)) (div_pos_of_pos_of_pos Hε (Kq_bound_pos Hs)), cases Bd with [N, HN], existsi N, intro n Hn, rewrite [↑equiv at Htz, ↑zero at *, sub_zero, ↑smul, abs_mul], apply le.trans, apply mul_le_mul, apply Kq_bound Hs, have HN' : ∀ (n : ℕ+), N ≤ n → abs (t n) ≤ ε / Kq s, from λ n, (eq.subst (sub_zero (t n)) (HN n)), apply HN', apply pnat.le_trans Hn, apply pnat.mul_le_mul_left, apply abs_nonneg, apply le_of_lt (Kq_bound_pos Hs), rewrite (mul_div_cancel' (ne.symm (ne_of_lt (Kq_bound_pos Hs)))), apply le.refl end private theorem neg_bound_eq_bound (s : seq) : K (sneg s) = K s := by rewrite [↑K, ↑sneg, abs_neg] private theorem neg_bound2_eq_bound2 (s t : seq) : K₂ s (sneg t) = K₂ s t := by rewrite [↑K₂, neg_bound_eq_bound] private theorem sneg_def (s : seq) : (λ (n : ℕ+), -(s n)) = sneg s := rfl theorem mul_neg_equiv_neg_mul {s t : seq} : smul s (sneg t) ≡ sneg (smul s t) := begin rewrite [↑equiv, ↑smul], intros, rewrite [↑sneg, *sub_neg_eq_add, -neg_mul_eq_mul_neg, add.comm], rewrite [*sneg_def t, *neg_bound2_eq_bound2, add.right_inv, abs_zero], apply add_invs_nonneg end theorem equiv_of_diff_equiv_zero {s t : seq} (Hs : regular s) (Ht : regular t) (H : sadd s (sneg t) ≡ zero) : s ≡ t := begin have hsimp : ∀ a b c d e : ℚ, a + b + c + (d + e) = b + d + a + e + c, from λ a b c d e, calc a + b + c + (d + e) = a + b + (d + e) + c : add.right_comm ... = a + (b + d) + e + c : by rewrite[-*add.assoc] ... = b + d + a + e + c : add.comm, apply eq_of_bdd Hs Ht, intros, note He := bdd_of_eq H, existsi 2 * (2 * (2 * j)), intros n Hn, rewrite (rewrite_helper5 _ _ (s (2 * n)) (t (2 * n))), apply rat.le_trans, apply abs_add_three, apply rat.le_trans, apply add_le_add_three, apply Hs, rewrite [↑sadd at He, ↑sneg at He, ↑zero at He], let He' := λ a b c, eq.subst !sub_zero (He a b c), apply (He' _ _ Hn), apply Ht, rewrite [hsimp, pnat.add_halves, -(pnat.add_halves j), -(pnat.add_halves (2 * j)), -*rat.add_assoc], apply add_le_add_right, apply add_le_add_three, repeat (apply rat.le_trans; apply inv_ge_of_le Hn; apply inv_two_mul_le_inv) end theorem s_sub_cancel (s : seq) : sadd s (sneg s) ≡ zero := begin rewrite [↑equiv, ↑sadd, ↑sneg, ↑zero], intros, rewrite [sub_zero, add.right_inv, abs_zero], apply add_invs_nonneg end theorem diff_equiv_zero_of_equiv {s t : seq} (Hs : regular s) (Ht : regular t) (H : s ≡ t) : sadd s (sneg t) ≡ zero := begin apply equiv.trans, rotate 4, apply s_sub_cancel t, rotate 2, apply zero_is_reg, apply add_well_defined, repeat (assumption | apply reg_neg_reg), apply equiv.refl, repeat (assumption | apply reg_add_reg | apply reg_neg_reg) end private theorem mul_well_defined_half1 {s t u : seq} (Hs : regular s) (Ht : regular t) (Hu : regular u) (Etu : t ≡ u) : smul s t ≡ smul s u := begin apply equiv_of_diff_equiv_zero, rotate 2, apply equiv.trans, rotate 3, apply equiv.symm, apply add_well_defined, rotate 4, apply equiv.refl, apply mul_neg_equiv_neg_mul, apply equiv.trans, rotate 3, apply equiv.symm, apply s_distrib, rotate 3, apply mul_zero_equiv_zero, rotate 2, apply diff_equiv_zero_of_equiv, repeat (assumption | apply reg_mul_reg | apply reg_neg_reg | apply reg_add_reg | apply zero_is_reg) end private theorem mul_well_defined_half2 {s t u : seq} (Hs : regular s) (Ht : regular t) (Hu : regular u) (Est : s ≡ t) : smul s u ≡ smul t u := begin apply equiv.trans, rotate 3, apply s_mul_comm, apply equiv.trans, rotate 3, apply mul_well_defined_half1, rotate 2, apply Ht, rotate 1, apply s_mul_comm, repeat (assumption | apply reg_mul_reg) end theorem mul_well_defined {s t u v : seq} (Hs : regular s) (Ht : regular t) (Hu : regular u) (Hv : regular v) (Esu : s ≡ u) (Etv : t ≡ v) : smul s t ≡ smul u v := begin apply equiv.trans, exact reg_mul_reg Hs Ht, exact reg_mul_reg Hs Hv, exact reg_mul_reg Hu Hv, apply mul_well_defined_half1, repeat assumption, apply mul_well_defined_half2, repeat assumption end theorem neg_well_defined {s t : seq} (Est : s ≡ t) : sneg s ≡ sneg t := begin rewrite [↑sneg, ↑equiv at *], intros, rewrite [-abs_neg, neg_sub, sub_neg_eq_add, add.comm], apply Est end theorem one_is_reg : regular one := begin rewrite [↑regular, ↑one], intros, rewrite [sub_self, abs_zero], apply add_invs_nonneg end theorem s_one_mul {s : seq} (H : regular s) : smul one s ≡ s := begin intros, rewrite [↑smul, ↑one, rat.one_mul], apply rat.le_trans, apply H, apply add_le_add_right, apply pnat.inv_mul_le_inv end theorem s_mul_one {s : seq} (H : regular s) : smul s one ≡ s := begin apply equiv.trans, apply reg_mul_reg H one_is_reg, rotate 2, apply s_mul_comm, apply s_one_mul H, apply reg_mul_reg one_is_reg H, apply H end theorem zero_nequiv_one : ¬ zero ≡ one := begin intro Hz, rewrite [↑equiv at Hz, ↑zero at Hz, ↑one at Hz], note H := Hz (2 * 2), rewrite [zero_sub at H, abs_neg at H, pnat.add_halves at H], have H' : pone⁻¹ ≤ 2⁻¹, from calc pone⁻¹ = 1 : by rewrite -pone_inv ... = abs 1 : abs_of_pos zero_lt_one ... ≤ 2⁻¹ : H, let H'' := ge_of_inv_le H', apply absurd (one_lt_two) (pnat.not_lt_of_ge H'') end --------------------------------------------- -- constant sequences definition const (a : ℚ) : seq := λ n, a theorem const_reg (a : ℚ) : regular (const a) := begin intros, rewrite [↑const, sub_self, abs_zero], apply add_invs_nonneg end theorem add_consts (a b : ℚ) : sadd (const a) (const b) ≡ const (a + b) := by apply equiv.refl theorem mul_consts (a b : ℚ) : smul (const a) (const b) ≡ const (a * b) := by apply equiv.refl theorem neg_const (a : ℚ) : sneg (const a) ≡ const (-a) := by apply equiv.refl section open rat lemma eq_of_const_equiv {a b : ℚ} (H : const a ≡ const b) : a = b := have H₁ : ∀ n : ℕ+, abs (a - b) ≤ n⁻¹ + n⁻¹, from H, eq_of_forall_abs_sub_le (take ε, suppose ε > 0, have ε / 2 > 0, begin exact div_pos_of_pos_of_pos this two_pos end, obtain n (Hn : n⁻¹ ≤ ε / 2), from pnat_bound this, show abs (a - b) ≤ ε, from calc abs (a - b) ≤ n⁻¹ + n⁻¹ : H₁ n ... ≤ ε / 2 + ε / 2 : add_le_add Hn Hn ... = ε : add_halves) end --------------------------------------------- -- create the type of regular sequences and lift theorems record reg_seq : Type := (sq : seq) (is_reg : regular sq) definition requiv (s t : reg_seq) := (reg_seq.sq s) ≡ (reg_seq.sq t) definition requiv.refl (s : reg_seq) : requiv s s := equiv.refl (reg_seq.sq s) definition requiv.symm (s t : reg_seq) (H : requiv s t) : requiv t s := equiv.symm (reg_seq.sq s) (reg_seq.sq t) H definition requiv.trans (s t u : reg_seq) (H : requiv s t) (H2 : requiv t u) : requiv s u := equiv.trans _ _ _ (reg_seq.is_reg s) (reg_seq.is_reg t) (reg_seq.is_reg u) H H2 definition radd (s t : reg_seq) : reg_seq := reg_seq.mk (sadd (reg_seq.sq s) (reg_seq.sq t)) (reg_add_reg (reg_seq.is_reg s) (reg_seq.is_reg t)) infix + := radd definition rmul (s t : reg_seq) : reg_seq := reg_seq.mk (smul (reg_seq.sq s) (reg_seq.sq t)) (reg_mul_reg (reg_seq.is_reg s) (reg_seq.is_reg t)) infix * := rmul definition rneg (s : reg_seq) : reg_seq := reg_seq.mk (sneg (reg_seq.sq s)) (reg_neg_reg (reg_seq.is_reg s)) prefix - := rneg definition radd_well_defined {s t u v : reg_seq} (H : requiv s u) (H2 : requiv t v) : requiv (s + t) (u + v) := add_well_defined (reg_seq.is_reg s) (reg_seq.is_reg t) (reg_seq.is_reg u) (reg_seq.is_reg v) H H2 definition rmul_well_defined {s t u v : reg_seq} (H : requiv s u) (H2 : requiv t v) : requiv (s * t) (u * v) := mul_well_defined (reg_seq.is_reg s) (reg_seq.is_reg t) (reg_seq.is_reg u) (reg_seq.is_reg v) H H2 definition rneg_well_defined {s t : reg_seq} (H : requiv s t) : requiv (-s) (-t) := neg_well_defined H theorem requiv_is_equiv : equivalence requiv := mk_equivalence requiv requiv.refl requiv.symm requiv.trans definition reg_seq.to_setoid [instance] : setoid reg_seq := ⦃setoid, r := requiv, iseqv := requiv_is_equiv⦄ definition r_zero : reg_seq := reg_seq.mk (zero) (zero_is_reg) definition r_one : reg_seq := reg_seq.mk (one) (one_is_reg) theorem r_add_comm (s t : reg_seq) : requiv (s + t) (t + s) := s_add_comm (reg_seq.sq s) (reg_seq.sq t) theorem r_add_assoc (s t u : reg_seq) : requiv (s + t + u) (s + (t + u)) := s_add_assoc (reg_seq.sq s) (reg_seq.sq t) (reg_seq.sq u) (reg_seq.is_reg s) (reg_seq.is_reg u) theorem r_zero_add (s : reg_seq) : requiv (r_zero + s) s := s_zero_add (reg_seq.sq s) (reg_seq.is_reg s) theorem r_add_zero (s : reg_seq) : requiv (s + r_zero) s := s_add_zero (reg_seq.sq s) (reg_seq.is_reg s) theorem r_neg_cancel (s : reg_seq) : requiv (-s + s) r_zero := s_neg_cancel (reg_seq.sq s) (reg_seq.is_reg s) theorem r_mul_comm (s t : reg_seq) : requiv (s * t) (t * s) := s_mul_comm (reg_seq.sq s) (reg_seq.sq t) theorem r_mul_assoc (s t u : reg_seq) : requiv (s * t * u) (s * (t * u)) := s_mul_assoc (reg_seq.is_reg s) (reg_seq.is_reg t) (reg_seq.is_reg u) theorem r_mul_one (s : reg_seq) : requiv (s * r_one) s := s_mul_one (reg_seq.is_reg s) theorem r_one_mul (s : reg_seq) : requiv (r_one * s) s := s_one_mul (reg_seq.is_reg s) theorem r_distrib (s t u : reg_seq) : requiv (s * (t + u)) (s * t + s * u) := s_distrib (reg_seq.is_reg s) (reg_seq.is_reg t) (reg_seq.is_reg u) theorem r_zero_nequiv_one : ¬ requiv r_zero r_one := zero_nequiv_one definition r_const (a : ℚ) : reg_seq := reg_seq.mk (const a) (const_reg a) theorem r_add_consts (a b : ℚ) : requiv (r_const a + r_const b) (r_const (a + b)) := add_consts a b theorem r_mul_consts (a b : ℚ) : requiv (r_const a * r_const b) (r_const (a * b)) := mul_consts a b theorem r_neg_const (a : ℚ) : requiv (-r_const a) (r_const (-a)) := neg_const a end rat_seq ---------------------------------------------- -- take quotients to get ℝ and show it's a comm ring open rat_seq definition real := quot reg_seq.to_setoid namespace real notation `ℝ` := real protected definition prio := num.pred rat.prio protected definition add (x y : ℝ) : ℝ := (quot.lift_on₂ x y (λ a b, quot.mk (a + b)) (take a b c d : reg_seq, take Hab : requiv a c, take Hcd : requiv b d, quot.sound (radd_well_defined Hab Hcd))) --infix [priority real.prio] + := add protected definition mul (x y : ℝ) : ℝ := (quot.lift_on₂ x y (λ a b, quot.mk (a * b)) (take a b c d : reg_seq, take Hab : requiv a c, take Hcd : requiv b d, quot.sound (rmul_well_defined Hab Hcd))) --infix [priority real.prio] * := mul protected definition neg (x : ℝ) : ℝ := (quot.lift_on x (λ a, quot.mk (-a)) (take a b : reg_seq, take Hab : requiv a b, quot.sound (rneg_well_defined Hab))) --prefix [priority real.prio] `-` := neg definition real_has_add [instance] [priority real.prio] : has_add real := has_add.mk real.add definition real_has_mul [instance] [priority real.prio] : has_mul real := has_mul.mk real.mul definition real_has_neg [instance] [priority real.prio] : has_neg real := has_neg.mk real.neg protected definition sub [reducible] (a b : ℝ) : real := a + (-b) definition real_has_sub [instance] [priority real.prio] : has_sub real := has_sub.mk real.sub open rat -- no coercions before definition of_rat [coercion] (a : ℚ) : ℝ := quot.mk (r_const a) definition of_int [coercion] (i : ℤ) : ℝ := i definition of_nat [coercion] (n : ℕ) : ℝ := n definition of_num [coercion] [reducible] (n : num) : ℝ := of_rat (rat.of_num n) definition real_has_zero [reducible] : has_zero real := has_zero.mk (of_rat 0) local attribute real_has_zero [instance] [priority real.prio] definition real_has_one [reducible] : has_one real := has_one.mk (of_rat 1) local attribute real_has_one [instance] [priority real.prio] theorem real_zero_eq_rat_zero : (0:real) = of_rat (0:rat) := rfl theorem real_one_eq_rat_one : (1:real) = of_rat (1:rat) := rfl protected theorem add_comm (x y : ℝ) : x + y = y + x := quot.induction_on₂ x y (λ s t, quot.sound (r_add_comm s t)) protected theorem add_assoc (x y z : ℝ) : x + y + z = x + (y + z) := quot.induction_on₃ x y z (λ s t u, quot.sound (r_add_assoc s t u)) protected theorem zero_add (x : ℝ) : 0 + x = x := quot.induction_on x (λ s, quot.sound (r_zero_add s)) protected theorem add_zero (x : ℝ) : x + 0 = x := quot.induction_on x (λ s, quot.sound (r_add_zero s)) protected theorem neg_cancel (x : ℝ) : -x + x = 0 := quot.induction_on x (λ s, quot.sound (r_neg_cancel s)) protected theorem mul_assoc (x y z : ℝ) : x * y * z = x * (y * z) := quot.induction_on₃ x y z (λ s t u, quot.sound (r_mul_assoc s t u)) protected theorem mul_comm (x y : ℝ) : x * y = y * x := quot.induction_on₂ x y (λ s t, quot.sound (r_mul_comm s t)) protected theorem one_mul (x : ℝ) : 1 * x = x := quot.induction_on x (λ s, quot.sound (r_one_mul s)) protected theorem mul_one (x : ℝ) : x * 1 = x := quot.induction_on x (λ s, quot.sound (r_mul_one s)) protected theorem left_distrib (x y z : ℝ) : x * (y + z) = x * y + x * z := quot.induction_on₃ x y z (λ s t u, quot.sound (r_distrib s t u)) protected theorem right_distrib (x y z : ℝ) : (x + y) * z = x * z + y * z := by rewrite [real.mul_comm, real.left_distrib, {x * _}real.mul_comm, {y * _}real.mul_comm] protected theorem zero_ne_one : ¬ (0 : ℝ) = 1 := take H : 0 = 1, absurd (quot.exact H) (r_zero_nequiv_one) protected definition comm_ring [reducible] : comm_ring ℝ := begin fapply comm_ring.mk, exact real.add, exact real.add_assoc, exact 0, exact real.zero_add, exact real.add_zero, exact real.neg, exact real.neg_cancel, exact real.add_comm, exact real.mul, exact real.mul_assoc, apply 1, apply real.one_mul, apply real.mul_one, apply real.left_distrib, apply real.right_distrib, apply real.mul_comm end theorem of_int_eq (a : ℤ) : of_int a = of_rat (rat.of_int a) := rfl theorem of_nat_eq (a : ℕ) : of_nat a = of_rat (rat.of_nat a) := rfl theorem of_rat.inj {x y : ℚ} (H : of_rat x = of_rat y) : x = y := eq_of_const_equiv (quot.exact H) theorem eq_of_of_rat_eq_of_rat {x y : ℚ} (H : of_rat x = of_rat y) : x = y := of_rat.inj H theorem of_rat_eq_of_rat_iff (x y : ℚ) : of_rat x = of_rat y ↔ x = y := iff.intro eq_of_of_rat_eq_of_rat !congr_arg theorem of_int.inj {a b : ℤ} (H : of_int a = of_int b) : a = b := rat.of_int.inj (of_rat.inj 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 of_int.inj !congr_arg 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 theorem of_rat_add (a b : ℚ) : of_rat (a + b) = of_rat a + of_rat b := quot.sound (r_add_consts a b) theorem of_rat_neg (a : ℚ) : of_rat (-a) = -of_rat a := eq.symm (quot.sound (r_neg_const a)) theorem of_rat_mul (a b : ℚ) : of_rat (a * b) = of_rat a * of_rat b := quot.sound (r_mul_consts a b) theorem of_rat_zero : of_rat 0 = 0 := rfl theorem of_rat_one : of_rat 1 = 1 := rfl open int theorem of_int_add (a b : ℤ) : of_int (a + b) = of_int a + of_int b := by rewrite [of_int_eq, rat.of_int_add, of_rat_add] theorem of_int_neg (a : ℤ) : of_int (-a) = -of_int a := by rewrite [of_int_eq, rat.of_int_neg, of_rat_neg] theorem of_int_mul (a b : ℤ) : of_int (a * b) = of_int a * of_int b := by rewrite [of_int_eq, rat.of_int_mul, of_rat_mul] theorem of_nat_add (a b : ℕ) : of_nat (a + b) = of_nat a + of_nat b := by rewrite [of_nat_eq, rat.of_nat_add, of_rat_add] theorem of_nat_mul (a b : ℕ) : of_nat (a * b) = of_nat a * of_nat b := by rewrite [of_nat_eq, rat.of_nat_mul, of_rat_mul] theorem add_half_of_rat (n : ℕ+) : of_rat (2 * n)⁻¹ + of_rat (2 * n)⁻¹ = of_rat (n⁻¹) := by rewrite [-of_rat_add, pnat.add_halves] theorem one_add_one : 1 + 1 = (2 : ℝ) := rfl end real
9ef51e58bd66ac0ce443c35445d3391dfd547f60
c777c32c8e484e195053731103c5e52af26a25d1
/src/algebra/lie/normalizer.lean
e5a30f89fef4d07a4c8153a5ad4310e385652bf7
[ "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
6,494
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 algebra.lie.abelian import algebra.lie.ideal_operations import algebra.lie.quotient /-! # The normalizer of a Lie submodules and subalgebras. Given a Lie module `M` over a Lie subalgebra `L`, the normalizer of a Lie submodule `N ⊆ M` is the Lie submodule with underlying set `{ m | ∀ (x : L), ⁅x, m⁆ ∈ N }`. The lattice of Lie submodules thus has two natural operations, the normalizer: `N ↦ N.normalizer` and the ideal operation: `N ↦ ⁅⊤, N⁆`; these are adjoint, i.e., they form a Galois connection. This adjointness is the reason that we may define nilpotency in terms of either the upper or lower central series. Given a Lie subalgebra `H ⊆ L`, we may regard `H` as a Lie submodule of `L` over `H`, and thus consider the normalizer. This turns out to be a Lie subalgebra. ## Main definitions * `lie_submodule.normalizer` * `lie_subalgebra.normalizer` * `lie_submodule.gc_top_lie_normalizer` ## Tags lie algebra, normalizer -/ variables {R L M M' : Type*} variables [comm_ring R] [lie_ring L] [lie_algebra R L] variables [add_comm_group M] [module R M] [lie_ring_module L M] [lie_module R L M] variables [add_comm_group M'] [module R M'] [lie_ring_module L M'] [lie_module R L M'] namespace lie_submodule variables (N : lie_submodule R L M) {N₁ N₂ : lie_submodule R L M} /-- The normalizer of a Lie submodule. -/ def normalizer : lie_submodule R L M := { carrier := { m | ∀ (x : L), ⁅x, m⁆ ∈ N }, add_mem' := λ m₁ m₂ hm₁ hm₂ x, by { rw lie_add, exact N.add_mem' (hm₁ x) (hm₂ x), }, zero_mem' := λ x, by simp, smul_mem' := λ t m hm x, by { rw lie_smul, exact N.smul_mem' t (hm x), }, lie_mem := λ x m hm y, by { rw leibniz_lie, exact N.add_mem' (hm ⁅y, x⁆) (N.lie_mem (hm y)), } } @[simp] lemma mem_normalizer (m : M) : m ∈ N.normalizer ↔ ∀ (x : L), ⁅x, m⁆ ∈ N := iff.rfl lemma le_normalizer : N ≤ N.normalizer := begin intros m hm, rw mem_normalizer, exact λ x, N.lie_mem hm, end lemma normalizer_inf : (N₁ ⊓ N₂).normalizer = N₁.normalizer ⊓ N₂.normalizer := by { ext, simp [← forall_and_distrib], } @[mono] lemma monotone_normalizer : monotone (normalizer : lie_submodule R L M → lie_submodule R L M) := begin intros N₁ N₂ h m hm, rw mem_normalizer at hm ⊢, exact λ x, h (hm x), end @[simp] lemma comap_normalizer (f : M' →ₗ⁅R,L⁆ M) : N.normalizer.comap f = (N.comap f).normalizer := by { ext, simp, } lemma top_lie_le_iff_le_normalizer (N' : lie_submodule R L M) : ⁅(⊤ : lie_ideal R L), N⁆ ≤ N' ↔ N ≤ N'.normalizer := by { rw lie_le_iff, tauto, } lemma gc_top_lie_normalizer : galois_connection (λ N : lie_submodule R L M, ⁅(⊤ : lie_ideal R L), N⁆) normalizer := top_lie_le_iff_le_normalizer variables (R L M) lemma normalizer_bot_eq_max_triv_submodule : (⊥ : lie_submodule R L M).normalizer = lie_module.max_triv_submodule R L M := rfl end lie_submodule namespace lie_subalgebra variables (H : lie_subalgebra R L) /-- Regarding a Lie subalgebra `H ⊆ L` as a module over itself, its normalizer is in fact a Lie subalgebra. -/ def normalizer : lie_subalgebra R L := { lie_mem' := λ y z hy hz x, begin rw [coe_bracket_of_module, mem_to_lie_submodule, leibniz_lie, ← lie_skew y, ← sub_eq_add_neg], exact H.sub_mem (hz ⟨_, hy x⟩) (hy ⟨_, hz x⟩), end, .. H.to_lie_submodule.normalizer } lemma mem_normalizer_iff' (x : L) : x ∈ H.normalizer ↔ ∀ (y : L), (y ∈ H) → ⁅y, x⁆ ∈ H := by { rw subtype.forall', refl, } lemma mem_normalizer_iff (x : L) : x ∈ H.normalizer ↔ ∀ (y : L), (y ∈ H) → ⁅x, y⁆ ∈ H := begin rw mem_normalizer_iff', refine forall₂_congr (λ y hy, _), rw [← lie_skew, neg_mem_iff], end lemma le_normalizer : H ≤ H.normalizer := H.to_lie_submodule.le_normalizer lemma coe_normalizer_eq_normalizer : (H.to_lie_submodule.normalizer : submodule R L) = H.normalizer := rfl variables {H} lemma lie_mem_sup_of_mem_normalizer {x y z : L} (hx : x ∈ H.normalizer) (hy : y ∈ (R ∙ x) ⊔ ↑H) (hz : z ∈ (R ∙ x) ⊔ ↑H) : ⁅y, z⁆ ∈ (R ∙ x) ⊔ ↑H := begin rw submodule.mem_sup at hy hz, obtain ⟨u₁, hu₁, v, hv : v ∈ H, rfl⟩ := hy, obtain ⟨u₂, hu₂, w, hw : w ∈ H, rfl⟩ := hz, obtain ⟨t, rfl⟩ := submodule.mem_span_singleton.mp hu₁, obtain ⟨s, rfl⟩ := submodule.mem_span_singleton.mp hu₂, apply submodule.mem_sup_right, simp only [lie_subalgebra.mem_coe_submodule, smul_lie, add_lie, zero_add, lie_add, smul_zero, lie_smul, lie_self], refine H.add_mem (H.smul_mem s _) (H.add_mem (H.smul_mem t _) (H.lie_mem hv hw)), exacts [(H.mem_normalizer_iff' x).mp hx v hv, (H.mem_normalizer_iff x).mp hx w hw], end /-- A Lie subalgebra is an ideal of its normalizer. -/ lemma ideal_in_normalizer {x y : L} (hx : x ∈ H.normalizer) (hy : y ∈ H) : ⁅x,y⁆ ∈ H := begin rw [← lie_skew, neg_mem_iff], exact hx ⟨y, hy⟩, end /-- A Lie subalgebra `H` is an ideal of any Lie subalgebra `K` containing `H` and contained in the normalizer of `H`. -/ lemma exists_nested_lie_ideal_of_le_normalizer {K : lie_subalgebra R L} (h₁ : H ≤ K) (h₂ : K ≤ H.normalizer) : ∃ (I : lie_ideal R K), (I : lie_subalgebra R K) = of_le h₁ := begin rw exists_nested_lie_ideal_coe_eq_iff, exact λ x y hx hy, ideal_in_normalizer (h₂ hx) hy, end variables (H) lemma normalizer_eq_self_iff : H.normalizer = H ↔ (lie_module.max_triv_submodule R H $ L ⧸ H.to_lie_submodule) = ⊥ := begin rw lie_submodule.eq_bot_iff, refine ⟨λ h, _, λ h, le_antisymm (λ x hx, _) H.le_normalizer⟩, { rintros ⟨x⟩ hx, suffices : x ∈ H, by simpa, rw [← h, H.mem_normalizer_iff'], intros y hy, replace hx : ⁅_, lie_submodule.quotient.mk' _ x⁆ = 0 := hx ⟨y, hy⟩, rwa [← lie_module_hom.map_lie, lie_submodule.quotient.mk_eq_zero] at hx, }, { let y := lie_submodule.quotient.mk' H.to_lie_submodule x, have hy : y ∈ lie_module.max_triv_submodule R H (L ⧸ H.to_lie_submodule), { rintros ⟨z, hz⟩, rw [← lie_module_hom.map_lie, lie_submodule.quotient.mk_eq_zero, coe_bracket_of_module, submodule.coe_mk, mem_to_lie_submodule], exact (H.mem_normalizer_iff' x).mp hx z hz, }, simpa using h y hy, }, end end lie_subalgebra
cc9393947b4503f8949957e66cacb2e4c40d9021
42610cc2e5db9c90269470365e6056df0122eaa0
/hott/hit/set_quotient.hlean
5b0574174fbcf37f44c7ab5d228fdf2d1288a561
[ "Apache-2.0" ]
permissive
tomsib2001/lean
2ab59bfaebd24a62109f800dcf4a7139ebd73858
eb639a7d53fb40175bea5c8da86b51d14bb91f76
refs/heads/master
1,586,128,387,740
1,468,968,950,000
1,468,968,950,000
61,027,234
0
0
null
1,465,813,585,000
1,465,813,585,000
null
UTF-8
Lean
false
false
5,761
hlean
/- Copyright (c) 2015 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn Declaration of set-quotients, i.e. quotient of a mere relation which is then set-truncated. -/ import function algebra.relation types.trunc types.eq hit.quotient open eq is_trunc trunc quotient equiv namespace set_quotient section parameters {A : Type} (R : A → A → Prop) -- set-quotients are just set-truncations of (type) quotients definition set_quotient : Type := trunc 0 (quotient R) parameter {R} definition class_of (a : A) : set_quotient := tr (class_of _ a) definition eq_of_rel {a a' : A} (H : R a a') : class_of a = class_of a' := ap tr (eq_of_rel _ H) theorem is_set_set_quotient [instance] : is_set set_quotient := begin unfold set_quotient, exact _ end protected definition rec {P : set_quotient → Type} [Pt : Πaa, is_set (P aa)] (Pc : Π(a : A), P (class_of a)) (Pp : Π⦃a a' : A⦄ (H : R a a'), Pc a =[eq_of_rel H] Pc a') (x : set_quotient) : P x := begin apply (@trunc.rec_on _ _ P x), { intro x', apply Pt}, { intro y, induction y, { apply Pc}, { exact pathover_of_pathover_ap P tr (Pp H)}} end protected definition rec_on [reducible] {P : set_quotient → Type} (x : set_quotient) [Pt : Πaa, is_set (P aa)] (Pc : Π(a : A), P (class_of a)) (Pp : Π⦃a a' : A⦄ (H : R a a'), Pc a =[eq_of_rel H] Pc a') : P x := rec Pc Pp x theorem rec_eq_of_rel {P : set_quotient → Type} [Pt : Πaa, is_set (P aa)] (Pc : Π(a : A), P (class_of a)) (Pp : Π⦃a a' : A⦄ (H : R a a'), Pc a =[eq_of_rel H] Pc a') {a a' : A} (H : R a a') : apd (rec Pc Pp) (eq_of_rel H) = Pp H := !is_set.elimo protected definition elim {P : Type} [Pt : is_set P] (Pc : A → P) (Pp : Π⦃a a' : A⦄ (H : R a a'), Pc a = Pc a') (x : set_quotient) : P := rec Pc (λa a' H, pathover_of_eq (Pp H)) x protected definition elim_on [reducible] {P : Type} (x : set_quotient) [Pt : is_set P] (Pc : A → P) (Pp : Π⦃a a' : A⦄ (H : R a a'), Pc a = Pc a') : P := elim Pc Pp x theorem elim_eq_of_rel {P : Type} [Pt : is_set P] (Pc : A → P) (Pp : Π⦃a a' : A⦄ (H : R a a'), Pc a = Pc a') {a a' : A} (H : R a a') : ap (elim Pc Pp) (eq_of_rel H) = Pp H := begin apply eq_of_fn_eq_fn_inv !(pathover_constant (eq_of_rel H)), rewrite [▸*,-apd_eq_pathover_of_eq_ap,↑elim,rec_eq_of_rel], end protected definition rec_prop {P : set_quotient → Type} [Pt : Πaa, is_prop (P aa)] (Pc : Π(a : A), P (class_of a)) (x : set_quotient) : P x := rec Pc (λa a' H, !is_prop.elimo) x protected definition elim_prop {P : Type} [Pt : is_prop P] (Pc : A → P) (x : set_quotient) : P := elim Pc (λa a' H, !is_prop.elim) x end end set_quotient attribute set_quotient.class_of [constructor] attribute set_quotient.rec set_quotient.elim [unfold 7] [recursor 7] attribute set_quotient.rec_on set_quotient.elim_on [unfold 4] open sigma relation function namespace set_quotient variables {A B C : Type} (R : A → A → Prop) (S : B → B → Prop) (T : C → C → Prop) definition is_surjective_class_of : is_surjective (class_of : A → set_quotient R) := λx, set_quotient.rec_on x (λa, tr (fiber.mk a idp)) (λa a' r, !is_prop.elimo) /- non-dependent universal property -/ definition set_quotient_arrow_equiv (B : Type) [H : is_set B] : (set_quotient R → B) ≃ (Σ(f : A → B), Π(a a' : A), R a a' → f a = f a') := begin fapply equiv.MK, { intro f, exact ⟨λa, f (class_of a), λa a' r, ap f (eq_of_rel r)⟩}, { intro v x, induction v with f p, exact set_quotient.elim_on x f p}, { intro v, induction v with f p, esimp, apply ap (sigma.mk f), apply eq_of_homotopy3, intro a a' r, apply elim_eq_of_rel}, { intro f, apply eq_of_homotopy, intro x, refine set_quotient.rec_on x _ _: esimp, intro a, reflexivity, intro a a' r, apply eq_pathover, apply hdeg_square, apply elim_eq_of_rel} end protected definition code [unfold 4] (a : A) (x : set_quotient R) [H : is_equivalence R] : Prop := set_quotient.elim_on x (R a) begin intros a' a'' H1, refine to_inv !trunctype_eq_equiv _, esimp, apply ua, apply equiv_of_is_prop, { intro H2, exact is_transitive.trans R H2 H1}, { intro H2, apply is_transitive.trans R H2, exact is_symmetric.symm R H1} end protected definition encode {a : A} {x : set_quotient R} (p : class_of a = x) [H : is_equivalence R] : set_quotient.code R a x := begin induction p, esimp, apply is_reflexive.refl R end definition rel_of_eq {a a' : A} (p : class_of a = class_of a' :> set_quotient R) [H : is_equivalence R] : R a a' := set_quotient.encode R p variables {R S T} definition quotient_unary_map [unfold 7] (f : A → B) (H : Π{a a'} (r : R a a'), S (f a) (f a')) : set_quotient R → set_quotient S := set_quotient.elim (class_of ∘ f) (λa a' r, eq_of_rel (H r)) definition quotient_binary_map [unfold 10 11] (f : A → B → C) (H : Π{a a'} (r : R a a') {b b'} (s : S b b'), T (f a b) (f a' b')) [HR : is_reflexive R] [HS : is_reflexive S] : set_quotient R → set_quotient S → set_quotient T := begin refine set_quotient.elim _ _, { intro a, refine set_quotient.elim _ _, { intro b, exact class_of (f a b)}, { intro b b' s, apply eq_of_rel, apply H, apply is_reflexive.refl R, exact s}}, { intro a a' r, apply eq_of_homotopy, refine set_quotient.rec _ _, { intro b, esimp, apply eq_of_rel, apply H, exact r, apply is_reflexive.refl S}, { intro b b' s, apply eq_pathover, esimp, apply is_set.elims}} end end set_quotient
150532815bc026a03065ec5f27424b0b9fb36802
b7f22e51856f4989b970961f794f1c435f9b8f78
/tests/lean/run/vector2.lean
f1d86856542d56990a472d3475e2c7d7f12d9d20
[ "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
389
lean
import logic data.nat.basic open nat inductive vector (A : Type) : nat → Type := | vnil : vector A zero | vcons : Π {n : nat}, A → vector A n → vector A (succ n) namespace vector theorem vcons.inj₁ {A : Type} {n : nat} (a₁ a₂ : A) (v₁ v₂ : vector A n) : vcons a₁ v₁ = vcons a₂ v₂ → a₁ = a₂ := assume h, vector.no_confusion h (λ n h t, h) end vector
611fc4d8fc843b999ce21b0f5fd6e36db57fdcc6
efa51dd2edbbbbd6c34bd0ce436415eb405832e7
/20161026_ICTAC_Tutorial/ex39.lean
71426d1d50244f9183a84b7404583290984219c6
[ "Apache-2.0" ]
permissive
leanprover/presentations
dd031a05bcb12c8855676c77e52ed84246bd889a
3ce2d132d299409f1de269fa8e95afa1333d644e
refs/heads/master
1,688,703,388,796
1,686,838,383,000
1,687,465,742,000
29,750,158
12
9
Apache-2.0
1,540,211,670,000
1,422,042,683,000
Lean
UTF-8
Lean
false
false
606
lean
open classical variables p q : Prop check em p theorem dne {p : Prop} (h : ¬¬p) : p := or.elim (em p) (assume hp : p, hp) (assume hnp : ¬p, absurd hnp h) /- For a constructivist ¬¬p means "p is non-contradictory" -/ example (h : ¬¬p) : p := by_cases (assume h1 : p, h1) (assume h1 : ¬p, absurd h1 h) example (h : ¬¬p) : p := by_contradiction (assume h1 : ¬p, show false, from h h1) example (h : ¬ (p ∧ q)) : ¬ p ∨ ¬ q := or.elim (em p) (assume hp : p, have hnq : ¬q, from assume hq : q, h ⟨hp, hq⟩, or.inr hnq) (assume hp : ¬p, or.inl hp)
6e9f0b29bf1ce65a44bcd56f313707ea12f121bf
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/algebra/category/fgModule/basic.lean
6ea72337a70247bd5690874cd0fefdbce0ebd664
[ "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,032
lean
/- Copyright (c) 2021 Jakob von Raumer. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jakob von Raumer -/ import category_theory.monoidal.rigid.basic import category_theory.monoidal.subcategory import linear_algebra.coevaluation import algebra.category.Module.monoidal /-! # The category of finitely generated modules over a ring This introduces `fgModule R`, the category of finitely generated modules over a ring `R`. It is implemented as a full subcategory on a subtype of `Module R`. When `K` is a field, `fgModule K` is the category of finite dimensional vector spaces over `K`. We first create the instance as a preadditive category. When `R` is commutative we then give the structure as an `R`-linear monoidal category. When `R` is a field we give it the structure of a closed monoidal category and then as a right-rigid monoidal category. ## Future work * Show that `fgModule R` is abelian when `R` is (left)-noetherian. -/ noncomputable theory open category_theory Module.monoidal_category open_locale classical big_operators universes u section ring variables (R : Type u) [ring R] /-- Define `fgModule` as the subtype of `Module.{u} R` of finitely generated modules. -/ @[derive [large_category, concrete_category, preadditive]] def fgModule := full_subcategory (λ (V : Module.{u} R), module.finite R V) end ring namespace fgModule section ring variables (R : Type u) [ring R] instance finite (V : fgModule R) : module.finite R V.obj := V.property instance : inhabited (fgModule R) := ⟨⟨Module.of R R, module.finite.self R⟩⟩ /-- Lift an unbundled finitely generated module to `fgModule R`. -/ def of (V : Type u) [add_comm_group V] [module R V] [module.finite R V] : fgModule R := ⟨Module.of R V, by { change module.finite R V, apply_instance }⟩ instance (V : fgModule R) : module.finite R V.obj := V.property instance : has_forget₂ (fgModule.{u} R) (Module.{u} R) := by { dsimp [fgModule], apply_instance, } instance : full (forget₂ (fgModule R) (Module.{u} R)) := { preimage := λ X Y f, f, } variables {R} /-- Converts and isomorphism in the category `fgModule R` to a `linear_equiv` between the underlying modules. -/ def iso_to_linear_equiv {V W : fgModule R} (i : V ≅ W) : V.obj ≃ₗ[R] W.obj := ((forget₂ (fgModule.{u} R) (Module.{u} R)).map_iso i).to_linear_equiv /-- Converts a `linear_equiv` to an isomorphism in the category `fgModule R`. -/ @[simps] def _root_.linear_equiv.to_fgModule_iso {V W : Type u} [add_comm_group V] [module R V] [module.finite R V] [add_comm_group W] [module R W] [module.finite R W] (e : V ≃ₗ[R] W) : fgModule.of R V ≅ fgModule.of R W := { hom := e.to_linear_map, inv := e.symm.to_linear_map, hom_inv_id' := by {ext, exact e.left_inv x}, inv_hom_id' := by {ext, exact e.right_inv x} } end ring section comm_ring variables (R : Type u) [comm_ring R] instance : linear R (fgModule R) := by dsimp_result { dsimp [fgModule], apply_instance, } instance monoidal_predicate_module_finite : monoidal_category.monoidal_predicate (λ V : Module.{u} R, module.finite R V) := { prop_id' := module.finite.self R, prop_tensor' := λ X Y hX hY, by exactI module.finite.tensor_product R X Y } instance : monoidal_category (fgModule R) := by dsimp_result { dsimp [fgModule], apply_instance, } instance : symmetric_category (fgModule R) := by dsimp_result { dsimp [fgModule], apply_instance, } instance : monoidal_preadditive (fgModule R) := by dsimp_result { dsimp [fgModule], apply_instance, } instance : monoidal_linear R (fgModule R) := by dsimp_result { dsimp [fgModule], apply_instance, } /-- The forgetful functor `fgModule R ⥤ Module R` as a monoidal functor. -/ def forget₂_monoidal : monoidal_functor (fgModule R) (Module.{u} R) := monoidal_category.full_monoidal_subcategory_inclusion _ instance forget₂_monoidal_faithful : faithful (forget₂_monoidal R).to_functor := by { dsimp [forget₂_monoidal], apply_instance, } instance forget₂_monoidal_additive : (forget₂_monoidal R).to_functor.additive := by { dsimp [forget₂_monoidal], apply_instance, } instance forget₂_monoidal_linear : (forget₂_monoidal R).to_functor.linear R := by { dsimp [forget₂_monoidal], apply_instance, } lemma iso.conj_eq_conj {V W : fgModule R} (i : V ≅ W) (f : End V) : iso.conj i f = linear_equiv.conj (iso_to_linear_equiv i) f := rfl end comm_ring section field variables (K : Type u) [field K] instance (V W : fgModule K) : module.finite K (V ⟶ W) := (by apply_instance : module.finite K (V.obj →ₗ[K] W.obj)) instance closed_predicate_module_finite : monoidal_category.closed_predicate (λ V : Module.{u} K, module.finite K V) := { prop_ihom' := λ X Y hX hY, by exactI @linear_map.finite_dimensional K _ X _ _ hX Y _ _ hY } instance : monoidal_closed (fgModule K) := by dsimp_result { dsimp [fgModule], apply_instance, } variables (V W : fgModule K) @[simp] lemma ihom_obj : (ihom V).obj W = fgModule.of K (V.obj →ₗ[K] W.obj) := rfl /-- The dual module is the dual in the rigid monoidal category `fgModule K`. -/ def fgModule_dual : fgModule K := ⟨Module.of K (module.dual K V.obj), subspace.module.dual.finite_dimensional⟩ open category_theory.monoidal_category /-- The coevaluation map is defined in `linear_algebra.coevaluation`. -/ def fgModule_coevaluation : 𝟙_ (fgModule K) ⟶ V ⊗ (fgModule_dual K V) := by apply coevaluation K V.obj lemma fgModule_coevaluation_apply_one : fgModule_coevaluation K V (1 : K) = ∑ (i : basis.of_vector_space_index K V.obj), (basis.of_vector_space K V.obj) i ⊗ₜ[K] (basis.of_vector_space K V.obj).coord i := by apply coevaluation_apply_one K V.obj /-- The evaluation morphism is given by the contraction map. -/ def fgModule_evaluation : (fgModule_dual K V) ⊗ V ⟶ 𝟙_ (fgModule K) := by apply contract_left K V.obj @[simp] lemma fgModule_evaluation_apply (f : (fgModule_dual K V).obj) (x : V.obj) : (fgModule_evaluation K V) (f ⊗ₜ x) = f.to_fun x := by apply contract_left_apply f x private theorem coevaluation_evaluation : let V' : fgModule K := fgModule_dual K V in (𝟙 V' ⊗ (fgModule_coevaluation K V)) ≫ (α_ V' V V').inv ≫ (fgModule_evaluation K V ⊗ 𝟙 V') = (ρ_ V').hom ≫ (λ_ V').inv := by apply contract_left_assoc_coevaluation K V.obj private theorem evaluation_coevaluation : (fgModule_coevaluation K V ⊗ 𝟙 V) ≫ (α_ V (fgModule_dual K V) V).hom ≫ (𝟙 V ⊗ fgModule_evaluation K V) = (λ_ V).hom ≫ (ρ_ V).inv := by apply contract_left_assoc_coevaluation' K V.obj instance exact_pairing : exact_pairing V (fgModule_dual K V) := { coevaluation := fgModule_coevaluation K V, evaluation := fgModule_evaluation K V, coevaluation_evaluation' := coevaluation_evaluation K V, evaluation_coevaluation' := evaluation_coevaluation K V } instance right_dual : has_right_dual V := ⟨fgModule_dual K V⟩ instance right_rigid_category : right_rigid_category (fgModule K) := { } end field end fgModule
4444a825e2b0dfe283f86d5a4d9b7a17ee7f623d
618003631150032a5676f229d13a079ac875ff77
/test/library_search/basic.lean
f778d10e347b93e29658f078fcee63863d849ccc
[ "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
6,527
lean
/- Copyright (c) 2018 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import data.nat.basic /- Turn off trace messages so they don't pollute the test build: -/ set_option trace.silence_library_search true /- For debugging purposes, we can display the list of lemmas: -/ -- set_option trace.suggest true namespace test.library_search -- Check that `library_search` fails if there are no goals. example : true := begin trivial, success_if_fail { library_search }, end -- Verify that `library_search` solves goals via `solve_by_elim` when the library isn't -- even needed. example (P : Prop) (p : P) : P := by library_search example (P : Prop) (p : P) (np : ¬P) : false := by library_search example (X : Type) (P : Prop) (x : X) (h : Π x : X, x = x → P) : P := by library_search def lt_one (n : ℕ) := n < 1 lemma zero_lt_one (n : ℕ) (h : n = 0) : lt_one n := by subst h; dsimp [lt_one]; simp -- Verify that calls to solve_by_elim to discharge subgoals use `rfl` example : lt_one 0 := by library_search example (α : Prop) : α → α := by library_search -- says: `exact id` example (p : Prop) [decidable p] : (¬¬p) → p := by library_search -- says: `exact not_not.mp` example (a b : Prop) (h : a ∧ b) : a := by library_search -- says: `exact h.left` example (P Q : Prop) [decidable P] [decidable Q]: (¬ Q → ¬ P) → (P → Q) := by library_search -- says: `exact not_imp_not.mp` example (a b : ℕ) : a + b = b + a := by library_search -- says: `exact add_comm a b` example {a b : ℕ} : a ≤ a + b := by library_search -- says: `exact nat.le.intro rfl` example (n m k : ℕ) : n * (m - k) = n * m - n * k := by library_search -- says: `exact nat.mul_sub_left_distrib n m k` example (n m k : ℕ) : n * m - n * k = n * (m - k) := by library_search -- says: `exact eq.symm (nat.mul_sub_left_distrib n m k)` example {n m : ℕ} (h : m < n) : m ≤ n - 1 := by library_search -- says: `exact nat.le_pred_of_lt h` example {α : Type} (x y : α) : x = y ↔ y = x := by library_search -- says: `exact eq_comm` example (a b : ℕ) (ha : 0 < a) (hb : 0 < b) : 0 < a + b := by library_search -- says: `exact add_pos ha hb` example (a b : ℕ) : 0 < a → 0 < b → 0 < a + b := by library_search -- says: `exact add_pos` section synonym -- Synonym `>` for `<` in the goal example (a b : ℕ) : 0 < a → 0 < b → a + b > 0 := by library_search -- says: `exact add_pos` -- Synonym `>` for `<` in another part of the goal example (a b : ℕ) : a > 0 → 0 < b → 0 < a + b := by library_search -- says: `exact add_pos` -- Synonym `>` for `<` in another part of the goal example (a b : ℕ) (ha : a > 0) (hb : 0 < b) : 0 < a + b := by library_search -- says: `exact add_pos ha hb` example (a b : ℕ) (h : a ∣ b) (w : b > 0) : a ≤ b := by library_search -- says: `exact nat.le_of_dvd w h` example (a b : ℕ) (h : a ∣ b) (w : b > 0) : b ≥ a := by library_search -- says: `exact nat.le_of_dvd w h` -- A lemma with head symbol `¬` can be used to prove `¬ p` or `⊥` example (a : ℕ) : ¬ (a < 0) := by library_search -- says `exact not_lt_bot` example (a : ℕ) (h : a < 0) : false := by library_search -- says `exact not_lt_bot h` -- An inductive type hides the constructor's arguments enough -- so that `library_search` doesn't accidentally close the goal. inductive P : ℕ → Prop | gt_in_head {n : ℕ} : n < 0 → P n -- This lemma with `>` as its head symbol should also be found for goals with head symbol `<`. lemma lemma_with_gt_in_head (a : ℕ) (h : P a) : 0 > a := by { cases h, assumption } -- This lemma with `false` as its head symbols should also be found for goals with head symbol `¬`. lemma lemma_with_false_in_head (a b : ℕ) (h1 : a < b) (h2 : P a) : false := by { apply nat.not_lt_zero, cases h2, assumption } example (a : ℕ) (h : P a) : 0 > a := by library_search -- says `exact lemma_with_gt_in_head a h` example (a : ℕ) (h : P a) : a < 0 := by library_search -- says `exact lemma_with_gt_in_head a h` example (a b : ℕ) (h1 : a < b) (h2 : P a) : false := by library_search -- says `exact lemma_with_false_in_head a b h1 h2` example (a b : ℕ) (h1 : a < b) : ¬ (P a) := by library_search -- says `exact lemma_with_false_in_head a b h1` end synonym -- We even find `iff` results: example : ∀ P : Prop, ¬(P ↔ ¬P) := by library_search -- says: `λ (a : Prop), (iff_not_self a).mp` example {a b c : ℕ} (ha : a > 0) (w : b ∣ c) : a * b ∣ a * c := by library_search -- exact mul_dvd_mul_left a w example {a b c : ℕ} (h₁ : a ∣ c) (h₂ : a ∣ b + c) : a ∣ b := by library_search -- says `exact (nat.dvd_add_left h₁).mp h₂` -- We have control of how `library_search` uses `solve_by_elim`. -- In particular, we can add extra lemmas to the `solve_by_elim` step -- (i.e. for `library_search` to use to attempt to discharge subgoals -- after successfully applying a lemma from the library.) example {a b c d: nat} (h₁ : a < c) (h₂ : b < d) : max (c + d) (a + b) = (c + d) := begin library_search [add_lt_add], -- Says: `exact max_eq_left_of_lt (add_lt_add h₁ h₂)` end -- We can also use attributes: meta def ex_attr : user_attribute := { name := `ex, descr := "A lemma that should be applied by `library_search` when discharging subgoals." } run_cmd attribute.register ``ex_attr attribute [ex] add_lt_add example {a b c d: nat} (h₁ : a < c) (h₂ : b < d) : max (c + d) (a + b) = (c + d) := begin suggest with ex, library_search with ex, -- Says: `exact max_eq_left_of_lt (add_lt_add h₁ h₂)` end example (a b : ℕ) (h : 0 < b) : (a * b) / b = a := by library_search -- Says: `exact nat.mul_div_left a h` example (a b : ℕ) (h : b ≠ 0) : (a * b) / b = a := begin success_if_fail { library_search }, library_search [nat.pos_iff_ne_zero.mpr], end -- Checking examples from issue #2220 example {α : Sort*} (h : empty) : α := by library_search example {α : Type*} (h : empty) : α := by library_search def map_from_sum {A B C : Type} (f : A → C) (g : B → C) : (A ⊕ B) → C := by library_search -- Test that we can provide custom `apply` tactics, -- e.g. to change how aggressively we unfold definitions in trying to apply lemmas. lemma bind_singleton {α β} (x : α) (f : α → list β) : list.bind [x] f = f x := begin success_if_fail { library_search { apply := λ e, tactic.apply e { md := tactic.transparency.reducible } }, }, library_search, end end test.library_search
62873cdec79ba13e8060b948b1f3e8140fb76143
05f637fa14ac28031cb1ea92086a0f4eb23ff2b1
/src/builtin/num.lean
646dfc65077a2b858bd5070c229b7525d488f475
[ "Apache-2.0" ]
permissive
codyroux/lean0.1
1ce92751d664aacff0529e139083304a7bbc8a71
0dc6fb974aa85ed6f305a2f4b10a53a44ee5f0ef
refs/heads/master
1,610,830,535,062
1,402,150,480,000
1,402,150,480,000
19,588,851
2
0
null
null
null
null
UTF-8
Lean
false
false
27,637
lean
-- Copyright (c) 2014 Microsoft Corporation. All rights reserved. -- Released under Apache 2.0 license as described in the file LICENSE. -- Author: Leonardo de Moura import macros subtype tactic using subtype namespace num theorem inhabited_ind : inhabited ind -- We use as the witness for non-emptiness, the value w in ind that is not convered by f. := obtain f His, from infinity, obtain w Hw, from and_elimr His, inhabited_intro w definition S := ε (inhabited_ex_intro infinity) (λ f, injective f ∧ non_surjective f) definition Z := ε inhabited_ind (λ y, ∀ x, ¬ S x = y) theorem injective_S : injective S := and_eliml (exists_to_eps infinity) theorem non_surjective_S : non_surjective S := and_elimr (exists_to_eps infinity) theorem S_ne_Z (i : ind) : S i ≠ Z := obtain w Hw, from non_surjective_S, eps_ax inhabited_ind w Hw i definition N (i : ind) : Bool := ∀ P, P Z → (∀ x, P x → P (S x)) → P i theorem N_Z : N Z := λ P Hz Hi, Hz theorem N_S {i : ind} (H : N i) : N (S i) := λ P Hz Hi, Hi i (H P Hz Hi) theorem N_smallest : ∀ P : ind → Bool, P Z → (∀ x, P x → P (S x)) → (∀ i, N i → P i) := λ P Hz Hi i Hni, Hni P Hz Hi definition num := subtype ind N theorem inhab : inhabited num := subtype_inhabited (exists_intro Z N_Z) definition zero : num := abst Z inhab theorem zero_pred : N Z := N_Z definition succ (n : num) : num := abst (S (rep n)) inhab theorem succ_pred (n : num) : N (S (rep n)) := have N_n : N (rep n), from P_rep n, show N (S (rep n)), from N_S N_n theorem succ_inj {a b : num} : succ a = succ b → a = b := assume Heq1 : succ a = succ b, have Heq2 : S (rep a) = S (rep b), from abst_inj inhab (succ_pred a) (succ_pred b) Heq1, have rep_eq : (rep a) = (rep b), from injective_S (rep a) (rep b) Heq2, show a = b, from rep_inj rep_eq theorem succ_inj_rw {a b : num} : succ a = succ b ↔ a = b := iff_intro (assume Hl, succ_inj Hl) (assume Hr, congr2 succ Hr) add_rewrite succ_inj_rw theorem succ_nz (a : num) : ¬ (succ a = zero) := not_intro (assume R : succ a = zero, have Heq1 : S (rep a) = Z, from abst_inj inhab (succ_pred a) zero_pred R, show false, from absurd Heq1 (S_ne_Z (rep a))) add_rewrite succ_nz theorem induction {P : num → Bool} (H1 : P zero) (H2 : ∀ n, P n → P (succ n)) : ∀ a, P a := take a, let Q := λ x, N x ∧ P (abst x inhab) in have QZ : Q Z, from and_intro zero_pred H1, have QS : ∀ x, Q x → Q (S x), from take x, assume Qx, have Hp1 : P (succ (abst x inhab)), from H2 (abst x inhab) (and_elimr Qx), have Hp2 : P (abst (S (rep (abst x inhab))) inhab), from Hp1, have Nx : N x, from and_eliml Qx, have rep_eq : rep (abst x inhab) = x, from rep_abst inhab x Nx, show Q (S x), from and_intro (N_S Nx) (subst Hp2 rep_eq), have Qa : P (abst (rep a) inhab), from and_elimr (N_smallest Q QZ QS (rep a) (P_rep a)), have abst_eq : abst (rep a) inhab = a, from abst_rep inhab a, show P a, from subst Qa abst_eq theorem induction_on {P : num → Bool} (a : num) (H1 : P zero) (H2 : ∀ n, P n → P (succ n)) : P a := induction H1 H2 a theorem dichotomy (m : num) : m = zero ∨ (∃ n, m = succ n) := induction_on m (by simp) (λ n iH, or_intror _ (@exists_intro _ (λ x, succ n = succ x) n (refl (succ n)))) theorem sn_ne_n (n : num) : succ n ≠ n := induction_on n (succ_nz zero) (λ (n : num) (iH : succ n ≠ n), not_intro (assume R : succ (succ n) = succ n, absurd (succ_inj R) iH)) add_rewrite sn_ne_n set_opaque num true set_opaque Z true set_opaque S true set_opaque zero true set_opaque succ true definition lt (m n : num) := ∃ P, (∀ i, P (succ i) → P i) ∧ P m ∧ ¬ P n infix 50 < : lt theorem lt_elim {m n : num} {B : Bool} (H1 : m < n) (H2 : ∀ (P : num → Bool), (∀ i, P (succ i) → P i) → P m → ¬ P n → B) : B := obtain P Pdef, from H1, H2 P (and_eliml Pdef) (and_eliml (and_elimr Pdef)) (and_elimr (and_elimr Pdef)) theorem lt_intro {m n : num} {P : num → Bool} (H1 : ∀ i, P (succ i) → P i) (H2 : P m) (H3 : ¬ P n) : m < n := exists_intro P (and_intro H1 (and_intro H2 H3)) set_opaque lt true theorem lt_nrefl (n : num) : ¬ (n < n) := not_intro (assume N : n < n, lt_elim N (λ P Pred Pn nPn, absurd Pn nPn)) add_rewrite lt_nrefl theorem lt_succ {m n : num} : succ m < n → m < n := assume H : succ m < n, lt_elim H (λ (P : num → Bool) (Pred : ∀ i, P (succ i) → P i) (Psm : P (succ m)) (nPn : ¬ P n), have Pm : P m, from Pred m Psm, show m < n, from lt_intro Pred Pm nPn) theorem not_lt_zero (n : num) : ¬ (n < zero) := induction_on n (show ¬ (zero < zero), from lt_nrefl zero) (λ (n : num) (iH : ¬ (n < zero)), show ¬ (succ n < zero), from not_intro (assume N : succ n < zero, have nLTzero : n < zero, from lt_succ N, show false, from absurd nLTzero iH)) add_rewrite not_lt_zero definition one := succ zero theorem one_eq_succ_zero : one = succ zero := refl one theorem zero_lt_one : zero < one := let P : num → Bool := λ x, x = zero in have Ppred : ∀ i, P (succ i) → P i, from take i, assume Ps : P (succ i), have si_eq_z : succ i = zero, from Ps, have si_ne_z : succ i ≠ zero, from succ_nz i, show P i, from absurd_elim (P i) si_eq_z (succ_nz i), have Pz : P zero, from (refl zero), have nPs : ¬ P (succ zero), from succ_nz zero, show zero < succ zero, from lt_intro Ppred Pz nPs theorem succ_mono_lt {m n : num} : m < n → succ m < succ n := assume H : m < n, lt_elim H (λ (P : num → Bool) (Ppred : ∀ i, P (succ i) → P i) (Pm : P m) (nPn : ¬ P n), let Q : num → Bool := λ x, x = succ m ∨ P x in have Qpred : ∀ i, Q (succ i) → Q i, from take i, assume Qsi : Q (succ i), or_elim Qsi (assume Hl : succ i = succ m, have Him : i = m, from succ_inj Hl, have Pi : P i, from subst Pm (symm Him), or_intror _ Pi) (assume Hr : P (succ i), have Pi : P i, from Ppred i Hr, or_intror _ Pi), have Qsm : Q (succ m), from or_introl (refl (succ m)) _, have nQsn : ¬ Q (succ n), from not_intro (assume R : Q (succ n), or_elim R (assume Hl : succ n = succ m, absurd Pm (subst nPn (succ_inj Hl))) (assume Hr : P (succ n), absurd (Ppred n Hr) nPn)), show succ m < succ n, from lt_intro Qpred Qsm nQsn) theorem lt_to_lt_succ {m n : num} : m < n → m < succ n := assume H : m < n, lt_elim H (λ (P : num → Bool) (Ppred : ∀ i, P (succ i) → P i) (Pm : P m) (nPn : ¬ P n), have nPsn : ¬ P (succ n), from not_intro (assume R : P (succ n), absurd (Ppred n R) nPn), show m < succ n, from lt_intro Ppred Pm nPsn) theorem n_lt_succ_n (n : num) : n < succ n := induction_on n (show zero < succ zero, from zero_lt_one) (λ (n : num) (iH : n < succ n), succ_mono_lt iH) add_rewrite n_lt_succ_n theorem lt_to_neq {m n : num} : m < n → m ≠ n := assume H : m < n, lt_elim H (λ (P : num → Bool) (Ppred : ∀ i, P (succ i) → P i) (Pm : P m) (nPn : ¬ P n), not_intro (assume R : m = n, absurd Pm (subst nPn (symm R)))) theorem eq_to_not_lt {m n : num} : m = n → ¬ (m < n) := assume Heq : m = n, not_intro (assume R : m < n, absurd (subst R Heq) (lt_nrefl n)) theorem zero_lt_succ_n {n : num} : zero < succ n := induction_on n (show zero < succ zero, from zero_lt_one) (λ (n : num) (iH : zero < succ n), lt_to_lt_succ iH) add_rewrite zero_lt_succ_n theorem lt_succ_to_disj {m n : num} : m < succ n → m = n ∨ m < n := assume H : m < succ n, lt_elim H (λ (P : num → Bool) (Ppred : ∀ i, P (succ i) → P i) (Pm : P m) (nPsn : ¬ P (succ n)), or_elim (em (m = n)) (assume Heq : m = n, or_introl Heq _) (assume Hne : m ≠ n, let Q : num → Bool := λ x, x ≠ n ∧ P x in have Qpred : ∀ i, Q (succ i) → Q i, from take i, assume Hsi : Q (succ i), have H1 : succ i ≠ n, from and_eliml Hsi, have Psi : P (succ i), from and_elimr Hsi, have Pi : P i, from Ppred i Psi, have neq : i ≠ n, from not_intro (assume N : i = n, absurd (subst Psi N) nPsn), and_intro neq Pi, have Qm : Q m, from and_intro Hne Pm, have nQn : ¬ Q n, from not_intro (assume N : n ≠ n ∧ P n, absurd (refl n) (and_eliml N)), show m = n ∨ m < n, from or_intror _ (lt_intro Qpred Qm nQn))) theorem disj_to_lt_succ {m n : num} : m = n ∨ m < n → m < succ n := assume H : m = n ∨ m < n, or_elim H (λ Hl : m = n, have H1 : n < succ n, from n_lt_succ_n n, show m < succ n, from subst H1 (symm Hl)) (λ Hr : m < n, lt_to_lt_succ Hr) theorem lt_succ_ne_to_lt {m n : num} : m < succ n → m ≠ n → m < n := assume (H1 : m < succ n) (H2 : m ≠ n), resolve1 (lt_succ_to_disj H1) H2 definition simp_rec_rel {A : (Type U)} (fn : num → A) (x : A) (f : A → A) (n : num) := fn zero = x ∧ (∀ m, m < n → fn (succ m) = f (fn m)) definition simp_rec_fun {A : (Type U)} (x : A) (f : A → A) (n : num) : num → A := ε (inhabited_fun num (inhabited_intro x)) (λ fn : num → A, simp_rec_rel fn x f n) -- The basic idea is: -- (simp_rec_fun x f n) returns a function that 'works' for all m < n -- We have that n < succ n, then we can define (simp_rec x f n) as: definition simp_rec {A : (Type U)} (x : A) (f : A → A) (n : num) : A := simp_rec_fun x f (succ n) n theorem simp_rec_def {A : (Type U)} (x : A) (f : A → A) (n : num) : (∃ fn, simp_rec_rel fn x f n) ↔ (simp_rec_fun x f n zero = x ∧ ∀ m, m < n → simp_rec_fun x f n (succ m) = f (simp_rec_fun x f n m)) := iff_intro (assume Hl : (∃ fn, simp_rec_rel fn x f n), obtain (fn : num → A) (Hfn : simp_rec_rel fn x f n), from Hl, have inhab : inhabited (num → A), from (inhabited_fun num (inhabited_intro x)), show simp_rec_rel (simp_rec_fun x f n) x f n, from @eps_ax (num → A) inhab (λ fn, simp_rec_rel fn x f n) fn Hfn) (assume Hr, have H1 : simp_rec_rel (simp_rec_fun x f n) x f n, from Hr, show (∃ fn, simp_rec_rel fn x f n), from exists_intro (simp_rec_fun x f n) H1) theorem simp_rec_ex {A : (Type U)} (x : A) (f : A → A) (n : num) : ∃ fn, simp_rec_rel fn x f n := induction_on n (let fn : num → A := λ n, x in have fz : fn zero = x, by simp, have fs : ∀ m, m < zero → fn (succ m) = f (fn m), from take m, assume Hmn : m < zero, absurd_elim (fn (succ m) = f (fn m)) Hmn (not_lt_zero m), show ∃ fn, simp_rec_rel fn x f zero, from exists_intro fn (and_intro fz fs)) (λ (n : num) (iH : ∃ fn, simp_rec_rel fn x f n), obtain (fn : num → A) (Hfn : simp_rec_rel fn x f n), from iH, let fn1 : num → A := λ m, if succ n = m then f (fn n) else fn m in have fnz : fn zero = x, from and_eliml Hfn, have f1z : fn1 zero = x, by simp, have f1s : ∀ m, m < succ n → fn1 (succ m) = f (fn1 m), from take m, assume Hlt : m < succ n, or_elim (lt_succ_to_disj Hlt) (assume Hl : m = n, by simp) (assume Hr : m < n, have Haux1 : fn (succ m) = f (fn m), from (and_elimr Hfn m Hr), have Hrw1 : (succ n = succ m) ↔ false, from eqf_intro (not_intro (assume N : succ n = succ m, have nLt : ¬ m < n, from eq_to_not_lt (symm (succ_inj N)), absurd Hr nLt)), have Haux2 : m < succ n, from lt_to_lt_succ Hr, have Haux3 : ¬ (succ n = m), from ne_symm (lt_to_neq Haux2), have Hrw2 : fn m = fn1 m, by simp, calc fn1 (succ m) = if succ n = succ m then f (fn n) else fn (succ m) : refl (fn1 (succ m)) ... = if false then f (fn n) else fn (succ m) : { Hrw1 } ... = fn (succ m) : if_false _ _ ... = f (fn m) : Haux1 ... = f (fn1 m) : { Hrw2 }), show ∃ fn, simp_rec_rel fn x f (succ n), from exists_intro fn1 (and_intro f1z f1s)) theorem simp_rec_lemma1 {A : (Type U)} (x : A) (f : A → A) (n : num) : simp_rec_fun x f n zero = x ∧ ∀ m, m < n → simp_rec_fun x f n (succ m) = f (simp_rec_fun x f n m) := (simp_rec_def x f n) ◂ (simp_rec_ex x f n) theorem simp_rec_lemma2 {A : (Type U)} (x : A) (f : A → A) (n m1 m2 : num) : n < m1 → n < m2 → simp_rec_fun x f m1 n = simp_rec_fun x f m2 n := induction_on n (assume H1 H2, calc simp_rec_fun x f m1 zero = x : and_eliml (simp_rec_lemma1 x f m1) ... = simp_rec_fun x f m2 zero : symm (and_eliml (simp_rec_lemma1 x f m2))) (λ (n : num) (iH : n < m1 → n < m2 → simp_rec_fun x f m1 n = simp_rec_fun x f m2 n), assume (Hs1 : succ n < m1) (Hs2 : succ n < m2), have H1 : n < m1, from lt_succ Hs1, have H2 : n < m2, from lt_succ Hs2, have Heq1 : simp_rec_fun x f m1 (succ n) = f (simp_rec_fun x f m1 n), from and_elimr (simp_rec_lemma1 x f m1) n H1, have Heq2 : simp_rec_fun x f m1 n = simp_rec_fun x f m2 n, from iH H1 H2, have Heq3 : simp_rec_fun x f m2 (succ n) = f (simp_rec_fun x f m2 n), from and_elimr (simp_rec_lemma1 x f m2) n H2, show simp_rec_fun x f m1 (succ n) = simp_rec_fun x f m2 (succ n), by simp) theorem simp_rec_thm {A : (Type U)} (x : A) (f : A → A) : simp_rec x f zero = x ∧ ∀ m, simp_rec x f (succ m) = f (simp_rec x f m) := have Heqz : simp_rec_fun x f (succ zero) zero = x, from and_eliml (simp_rec_lemma1 x f (succ zero)), have Hz : simp_rec x f zero = x, from calc simp_rec x f zero = simp_rec_fun x f (succ zero) zero : refl _ ... = x : Heqz, have Hs : ∀ m, simp_rec x f (succ m) = f (simp_rec x f m), from take m, have Hlt1 : m < succ (succ m), from lt_to_lt_succ (n_lt_succ_n m), have Hlt2 : m < succ m, from n_lt_succ_n m, have Heq1 : simp_rec_fun x f (succ (succ m)) (succ m) = f (simp_rec_fun x f (succ (succ m)) m), from and_elimr (simp_rec_lemma1 x f (succ (succ m))) m Hlt1, have Heq2 : simp_rec_fun x f (succ (succ m)) m = simp_rec_fun x f (succ m) m, from simp_rec_lemma2 x f m (succ (succ m)) (succ m) Hlt1 Hlt2, calc simp_rec x f (succ m) = simp_rec_fun x f (succ (succ m)) (succ m) : refl _ ... = f (simp_rec_fun x f (succ (succ m)) m) : Heq1 ... = f (simp_rec_fun x f (succ m) m) : { Heq2 } ... = f (simp_rec x f m) : refl _, show simp_rec x f zero = x ∧ ∀ m, simp_rec x f (succ m) = f (simp_rec x f m), from and_intro Hz Hs definition pre (m : num) := if m = zero then zero else ε inhab (λ n, succ n = m) theorem pre_zero : pre zero = zero := by (Then (unfold num::pre) simp) theorem pre_succ (m : num) : pre (succ m) = m := have Heq : (λ n, succ n = succ m) = (λ n, n = m), from funext (λ n, iff_intro (assume Hl, succ_inj Hl) (assume Hr, congr2 succ Hr)), calc pre (succ m) = ε inhab (λ n, succ n = succ m) : by (Then (unfold num::pre) simp) ... = ε inhab (λ n, n = m) : { Heq } ... = m : eps_singleton inhab m add_rewrite pre_zero pre_succ theorem succ_pre (m : num) : m ≠ zero → succ (pre m) = m := assume H : m ≠ zero, have H1 : ∃ n, m = succ n, from resolve1 (dichotomy m) H, obtain (w : num) (H2 : m = succ w), from H1, have H3 : (λ n, succ n = m) = (λ n, n = w), from funext (λ n, by simp), calc succ (pre m) = succ (if m = zero then zero else ε inhab (λ n, succ n = m)) : refl _ ... = succ (ε inhab (λ n, n = w)) : by simp ... = succ w : { eps_singleton inhab w } ... = m : symm H2 definition prim_rec_fun {A : (Type U)} (x : A) (f : A → num → A) := simp_rec (λ n : num, x) (λ fn n, f (fn (pre n)) n) definition prim_rec {A : (Type U)} (x : A) (f : A → num → A) (m : num) := prim_rec_fun x f m (pre m) theorem prim_rec_thm {A : (Type U)} (x : A) (f : A → num → A) : prim_rec x f zero = x ∧ ∀ m, prim_rec x f (succ m) = f (prim_rec x f m) m := let faux := λ fn n, f (fn (pre n)) n in have Hz : prim_rec x f zero = x, from have Heq1 : simp_rec (λ n, x) faux zero = (λ n : num, x), from and_eliml (simp_rec_thm (λ n, x) faux), calc prim_rec x f zero = prim_rec_fun x f zero (pre zero) : refl _ ... = prim_rec_fun x f zero zero : { pre_zero } ... = simp_rec (λ n, x) faux zero zero : refl _ ... = x : congr1 Heq1 zero, have Hs : ∀ m, prim_rec x f (succ m) = f (prim_rec x f m) m, from take m, have Heq1 : pre (succ m) = m, from pre_succ m, have Heq2 : simp_rec (λ n, x) faux (succ m) = faux (simp_rec (λ n, x) faux m), from and_elimr (simp_rec_thm (λ n, x) faux) m, calc prim_rec x f (succ m) = prim_rec_fun x f (succ m) (pre (succ m)) : refl _ ... = prim_rec_fun x f (succ m) m : { Heq1 } ... = simp_rec (λ n, x) faux (succ m) m : refl _ ... = faux (simp_rec (λ n, x) faux m) m : congr1 Heq2 m ... = f (prim_rec x f m) m : refl _, show prim_rec x f zero = x ∧ ∀ m, prim_rec x f (succ m) = f (prim_rec x f m) m, from and_intro Hz Hs theorem prim_rec_zero {A : (Type U)} (x : A) (f : A → num → A) : prim_rec x f zero = x := and_eliml (prim_rec_thm x f) theorem prim_rec_succ {A : (Type U)} (x : A) (f : A → num → A) (m : num) : prim_rec x f (succ m) = f (prim_rec x f m) m := and_elimr (prim_rec_thm x f) m set_opaque simp_rec_rel true set_opaque simp_rec_fun true set_opaque simp_rec true set_opaque prim_rec_fun true set_opaque prim_rec true definition add (a b : num) : num := prim_rec a (λ x n, succ x) b infixl 65 + : add theorem add_zeror (a : num) : a + zero = a := prim_rec_zero a (λ x n, succ x) theorem add_succr (a b : num) : a + succ b = succ (a + b) := prim_rec_succ a (λ x n, succ x) b definition mul (a b : num) : num := prim_rec zero (λ x n, x + a) b infixl 70 * : mul theorem mul_zeror (a : num) : a * zero = zero := prim_rec_zero zero (λ x n, x + a) theorem mul_succr (a b : num) : a * (succ b) = a * b + a := prim_rec_succ zero (λ x n, x + a) b add_rewrite add_zeror add_succr mul_zeror mul_succr set_opaque add true set_opaque mul true theorem add_zerol (a : num) : zero + a = a := induction_on a (by simp) (by simp) theorem add_succl (a b : num) : (succ a) + b = succ (a + b) := induction_on b (by simp) (by simp) add_rewrite add_zerol add_succl theorem add_comm (a b : num) : a + b = b + a := induction_on b (by simp) (by simp) theorem add_assoc (a b c : num) : (a + b) + c = a + (b + c) := induction_on a (by simp) (by simp) theorem add_left_comm (a b c : num) : a + (b + c) = b + (a + c) := left_comm add_comm add_assoc a b c add_rewrite add_assoc add_comm add_left_comm theorem mul_zerol (a : num) : zero * a = zero := induction_on a (by simp) (by simp) theorem mul_succl (a b : num) : (succ a) * b = a * b + b := induction_on b (by simp) (by simp) add_rewrite mul_zerol mul_succl theorem mul_onel (a : num) : (succ zero) * a = a := induction_on a (by simp) (by simp) theorem mul_oner (a : num) : a * (succ zero) = a := induction_on a (by simp) (by simp) add_rewrite mul_onel mul_oner theorem mul_comm (a b : num) : a * b = b * a := induction_on b (by simp) (by simp) theorem distributer (a b c : num) : a * (b + c) = a * b + a * c := induction_on a (by simp) (by simp) add_rewrite mul_comm distributer theorem distributel (a b c : num) : (a + b) * c = a * c + b * c := induction_on a (by simp) (by simp) add_rewrite distributel theorem mul_assoc (a b c : num) : (a * b) * c = a * (b * c) := induction_on b (by simp) (by simp) theorem mul_left_comm (a b c : num) : a * (b * c) = b * (a * c) := left_comm mul_comm mul_assoc a b c add_rewrite mul_assoc mul_left_comm theorem lt_addr {a b : num} (c : num) : a < b → a + c < b + c := assume H : a < b, induction_on c (by simp) (λ (c : num) (iH : a + c < b + c), have H1 : succ (a + c) < succ (b + c), from succ_mono_lt iH, show a + succ c < b + succ c, from subst (subst H1 (symm (add_succr a c))) (symm (add_succr b c))) theorem addl_lt {a b c : num} : a + c < b → a < b := induction_on c (assume H : a + zero < b, subst H (add_zeror a)) (λ (c : num) (iH : a + c < b → a < b), assume H : a + (succ c) < b, have H1 : succ (a + c) < b, from subst H (add_succr a c), have H2 : a + c < b, from lt_succ H1, show a < b, from iH H2) theorem lt_to_nez {a b : num} (H : a < b) : b ≠ zero := not_intro (assume N : b = zero, absurd (subst H N) (not_lt_zero a)) theorem lt_ex1 {a b : num} : a < b → ∃ c, a + (succ c) = b := induction_on a (assume H : zero < b, have H1 : b ≠ zero, from lt_to_nez H, have H2 : succ (pre b) = b, from succ_pre b H1, show ∃ c, zero + (succ c) = b, from exists_intro (pre b) (by simp)) (λ (a : num) (iH : a < b → ∃ c, a + (succ c) = b), assume H : succ a < b, have H1 : a < b, from lt_succ H, obtain (c : num) (Hc : a + (succ c) = b), from iH H1, have Hcnz : c ≠ zero, from not_intro (assume L1 : c = zero, have Hb : b = a + (succ c), from symm Hc, have L2 : succ a = b, by simp, show false, from absurd L2 (lt_to_neq H)), have Hspc : succ (pre c) = c, from succ_pre c Hcnz, show ∃ c, (succ a) + (succ c) = b, from exists_intro (pre c) (calc (succ a) + (succ (pre c)) = succ (a + c) : by simp ... = a + (succ c) : symm (add_succr _ _) ... = b : Hc )) theorem lt_ex2 {a b : num} : (∃ c, a + (succ c) = b) → a < b := assume Hex : ∃ c, a + (succ c) = b, obtain (c : num) (Hc : a + (succ c) = b), from Hex, have H1 : succ (a + c) = b, from subst Hc (add_succr a c), have H2 : a + c < b, from subst (n_lt_succ_n (a + c)) H1, show a < b, from addl_lt H2 theorem lt_ex (a b : num) : a < b ↔ ∃ c, a + (succ c) = b := iff_intro (assume Hl, lt_ex1 Hl) (assume Hr, lt_ex2 Hr) theorem lt_to_ex {a b : num} (H : a < b) : ∃ c, a + (succ c) = b := lt_ex1 H theorem ex_to_lt {a b c : num} (H : a + succ c = b) : a < b := lt_ex2 (exists_intro c H) theorem lt_trans {a b c : num} : a < b → b < c → a < c := assume H1 H2, obtain (w1 : num) (Hw1 : a + succ w1 = b), from lt_to_ex H1, obtain (w2 : num) (Hw2 : b + succ w2 = c), from lt_to_ex H2, have Hac : a + succ (succ (w1 + w2)) = c, from calc a + succ (succ (w1 + w2)) = (a + succ w1) + succ w2 : by simp_no_assump ... = b + succ w2 : { Hw1 } ... = c : { Hw2 }, ex_to_lt Hac theorem strong_induction {P : num → Bool} (H : ∀ n, (∀ m, m < n → P m) → P n) : ∀ a, P a := take a : num, have stronger : P a ∧ ∀ m, m < a → P m, from induction_on a -- we prove a stronger result by regular induction on a (have c2 : ∀ m, m < zero → P m, from λ (m : num) (Hlt : m < zero), absurd_elim (P m) Hlt (not_lt_zero m), have c1 : P zero, from H zero c2, show P zero ∧ ∀ m, m < zero → P m, from and_intro c1 c2) (λ (n : num) (iH : P n ∧ ∀ m, m < n → P m), have iH1 : P n, from and_eliml iH, have iH2 : ∀ m, m < n → P m, from and_elimr iH, have c2 : ∀ m, m < succ n → P m, from take m : num, assume Hlt : m < succ n, or_elim (em (m = n)) (assume Heq : m = n, subst iH1 (symm Heq)) (assume Hne : m ≠ n, iH2 m (lt_succ_ne_to_lt Hlt Hne)), have c1 : P (succ n), from H (succ n) c2, and_intro c1 c2), show P a, from and_eliml stronger definition fact (a : num) : num := prim_rec one (λ x n, succ n * x) a theorem fact_zero : fact zero = one := prim_rec_zero one (λ x n : num, succ n * x) theorem fact_succ (n : num) : fact (succ n) = succ n * fact n := prim_rec_succ one (λ x n : num, succ n * x) n definition exp (a b : num) : num := prim_rec one (λ x n, a * x) b theorem exp_zero (a : num) : exp a zero = one := prim_rec_zero one (λ x n, a * x) theorem exp_succ (a b : num) : exp a (succ b) = a * (exp a b) := prim_rec_succ one (λ x n, a * x) b set_opaque fact true set_opaque exp true end definition num := num::num
468dc32214b81eada1b2dc3543060f1effa0d365
491068d2ad28831e7dade8d6dff871c3e49d9431
/tests/lean/run/vector.lean
a02d78c6dbbc0c19a31c9498aed61523e0b0e7b2
[ "Apache-2.0" ]
permissive
davidmueller13/lean
65a3ed141b4088cd0a268e4de80eb6778b21a0e9
c626e2e3c6f3771e07c32e82ee5b9e030de5b050
refs/heads/master
1,611,278,313,401
1,444,021,177,000
1,444,021,177,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
4,886
lean
import logic data.nat.basic data.prod data.unit open nat prod inductive vector (A : Type) : nat → Type := | vnil {} : vector A zero | vcons : Π {n : nat}, A → vector A n → vector A (succ n) namespace vector -- print definition no_confusion infixr `::` := vcons local abbreviation no_confusion := @vector.no_confusion local abbreviation below := @vector.below theorem vcons.inj₁ {A : Type} {n : nat} (a₁ a₂ : A) (v₁ v₂ : vector A n) : vcons a₁ v₁ = vcons a₂ v₂ → a₁ = a₂ := begin intro h, apply (no_confusion h), intros, assumption end theorem vcons.inj₂ {A : Type} {n : nat} (a₁ a₂ : A) (v₁ v₂ : vector A n) : vcons a₁ v₁ = vcons a₂ v₂ → v₁ = v₂ := begin intro h, apply heq.to_eq, apply (no_confusion h), intros, eassumption, end set_option pp.universes true check @below namespace manual section universe variables l₁ l₂ variable {A : Type.{l₁}} variable {C : Π (n : nat), vector A n → Type.{l₂}} definition brec_on {n : nat} (v : vector A n) (H : Π (n : nat) (v : vector A n), @vector.below A C n v → C n v) : C n v := have general : C n v × @vector.below A C n v, from vector.rec_on v (pair (H zero vnil poly_unit.star) poly_unit.star) (λ (n₁ : nat) (a₁ : A) (v₁ : vector A n₁) (r₁ : C n₁ v₁ × @vector.below A C n₁ v₁), have b : @vector.below A C _ (vcons a₁ v₁), from r₁, have c : C (succ n₁) (vcons a₁ v₁), from H (succ n₁) (vcons a₁ v₁) b, pair c b), pr₁ general end end manual -- check vector.brec_on definition bw := @below definition sum {n : nat} (v : vector nat n) : nat := vector.brec_on v (λ (n : nat) (v : vector nat n), vector.cases_on v (λ (B : bw vnil), zero) (λ (n₁ : nat) (a : nat) (v₁ : vector nat n₁) (B : bw (vcons a v₁)), a + pr₁ B)) example : sum (10 :: 20 :: vnil) = 30 := rfl definition addk {n : nat} (v : vector nat n) (k : nat) : vector nat n := vector.brec_on v (λ (n : nat) (v : vector nat n), vector.cases_on v (λ (B : bw vnil), vnil) (λ (n₁ : nat) (a₁ : nat) (v₁ : vector nat n₁) (B : bw (vcons a₁ v₁)), vcons (a₁+k) (pr₁ B))) example : addk (1 :: 2 :: vnil) 3 = 4 :: 5 :: vnil := rfl definition append.{l} {A : Type.{l+1}} {n m : nat} (w : vector A m) (v : vector A n) : vector A (n + m) := vector.brec_on w (λ (n : nat) (w : vector A n), vector.cases_on w (λ (B : bw vnil), v) (λ (n₁ : nat) (a₁ : A) (v₁ : vector A n₁) (B : bw (vcons a₁ v₁)), vcons a₁ (pr₁ B))) example : append (1 :: 2 :: vnil) (3 :: vnil) = 1 :: 2 :: 3 :: vnil := rfl definition head {A : Type} {n : nat} (v : vector A (succ n)) : A := vector.cases_on v (λ H : succ n = 0, nat.no_confusion H) (λn' h t (H : succ n = succ n'), h) rfl definition tail {A : Type} {n : nat} (v : vector A (succ n)) : vector A n := @vector.cases_on A (λn' v, succ n = n' → vector A (pred n')) (succ n) v (λ H : succ n = 0, nat.no_confusion H) (λ (n' : nat) (h : A) (t : vector A n') (H : succ n = succ n'), t) rfl definition add {n : nat} (w v : vector nat n) : vector nat n := @vector.brec_on nat (λ (n : nat) (v : vector nat n), vector nat n → vector nat n) n w (λ (n : nat) (w : vector nat n), vector.cases_on w (λ (B : bw vnil) (w : vector nat zero), vnil) (λ (n₁ : nat) (a₁ : nat) (v₁ : vector nat n₁) (B : bw (vcons a₁ v₁)) (v : vector nat (succ n₁)), vcons (a₁ + head v) (pr₁ B (tail v)))) v example : add (1 :: 2 :: vnil) (3 :: 5 :: vnil) = 4 :: 7 :: vnil := rfl definition map {A B C : Type} {n : nat} (f : A → B → C) (w : vector A n) (v : vector B n) : vector C n := let P := λ (n : nat) (v : vector A n), vector B n → vector C n in @vector.brec_on A P n w (λ (n : nat) (w : vector A n), begin cases w with [n', h₁, t₁], show @below A P zero vnil → vector B zero → vector C zero, from λ b v, vnil, show @below A P (succ n') (h₁ :: t₁) → vector B (succ n') → vector C (succ n'), from λ b v, begin cases v with [n', h₂, t₂], have r : vector B n' → vector C n', from pr₁ b, exact ((f h₁ h₂) :: r t₂), end end) v theorem map_nil_nil {A B C : Type} (f : A → B → C) : map f vnil vnil = vnil := rfl theorem map_cons_cons {A B C : Type} (f : A → B → C) (a : A) (b : B) {n : nat} (va : vector A n) (vb : vector B n) : map f (a :: va) (b :: vb) = f a b :: map f va vb := rfl example : map nat.add (1 :: 2 :: vnil) (3 :: 5 :: vnil) = 4 :: 7 :: vnil := rfl print definition map end vector
64b3c3adfb184a3818627cf8104eb7ee2587f937
9be442d9ec2fcf442516ed6e9e1660aa9071b7bd
/stage0/src/Lean/Server/Rpc/RequestHandling.lean
1f11482aaffcfadc4f38b755a1584c2fec95e50f
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
EdAyers/lean4
57ac632d6b0789cb91fab2170e8c9e40441221bd
37ba0df5841bde51dbc2329da81ac23d4f6a4de4
refs/heads/master
1,676,463,245,298
1,660,619,433,000
1,660,619,433,000
183,433,437
1
0
Apache-2.0
1,657,612,672,000
1,556,196,574,000
Lean
UTF-8
Lean
false
false
5,511
lean
/- Copyright (c) 2021 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Wojciech Nawrocki -/ import Lean.Data.Lsp.Extra import Lean.Server.Requests import Lean.Server.Rpc.Basic namespace Lean.Server private structure RpcProcedure where wrapper : (sessionId : UInt64) → Json → RequestM (RequestTask Json) deriving Inhabited /- We store the builtin RPC handlers in a Ref and users' handlers in an extension. This ensures that users don't need to import core Lean modules to make builtin handlers work, but also that they *can* easily create custom handlers and use them in the same file. -/ builtin_initialize builtinRpcProcedures : IO.Ref (Std.PHashMap Name RpcProcedure) ← IO.mkRef {} builtin_initialize userRpcProcedures : MapDeclarationExtension Name ← mkMapDeclarationExtension `userRpcProcedures open RequestM in private unsafe def handleRpcCallUnsafe (p : Lsp.RpcCallParams) : RequestM (RequestTask Json) := do let doc ← readDoc let text := doc.meta.text let callPos := text.lspPosToUtf8Pos p.position bindWaitFindSnap doc (fun s => s.endPos >= callPos) (notFoundX := throwThe RequestError { code := JsonRpc.ErrorCode.invalidParams message := s!"Incorrect position '{p.toTextDocumentPositionParams}' in RPC call" }) fun snap => do if let some proc := (← builtinRpcProcedures.get).find? p.method then proc.wrapper p.sessionId p.params else if let some procName := userRpcProcedures.find? snap.env p.method then let options := snap.cmdState.scopes.head!.opts let proc : Except _ _ := Lean.Environment.evalConstCheck RpcProcedure snap.env options ``RpcProcedure procName match proc with | Except.ok x => x.wrapper p.sessionId p.params | Except.error e => throwThe RequestError { code := JsonRpc.ErrorCode.internalError message := s!"Failed to evaluate RPC constant '{procName}': {e}" } else throwThe RequestError { code := JsonRpc.ErrorCode.methodNotFound message := s!"No RPC method '{p.method}' bound" } @[implementedBy handleRpcCallUnsafe] private opaque handleRpcCall (p : Lsp.RpcCallParams) : RequestM (RequestTask Json) builtin_initialize registerLspRequestHandler "$/lean/rpc/call" Lsp.RpcCallParams Json handleRpcCall def wrapRpcProcedure (method : Name) paramType respType [RpcEncodable paramType] [RpcEncodable respType] (handler : paramType → RequestM (RequestTask respType)) : RpcProcedure := ⟨fun seshId j => do let rc ← read let some seshRef := rc.rpcSessions.find? seshId | throwThe RequestError { code := JsonRpc.ErrorCode.rpcNeedsReconnect message := s!"Outdated RPC session" } let t ← RequestM.asTask do match rpcDecode j (← seshRef.get).objects with | Except.ok v => return v | Except.error e => throwThe RequestError { code := JsonRpc.ErrorCode.invalidParams message := s!"Cannot decode params in RPC call '{method}({j.compress})'\n{e}" } let t ← RequestM.bindTask t fun | Except.error e => throw e | Except.ok ps => handler ps RequestM.mapTask t fun | Except.error e => throw e | Except.ok ret => seshRef.modifyGet fun st => rpcEncode ret st.objects |>.map id ({st with objects := ·})⟩ def registerBuiltinRpcProcedure (method : Name) paramType respType [RpcEncodable paramType] [RpcEncodable respType] (handler : paramType → RequestM (RequestTask respType)) : IO Unit := do let errMsg := s!"Failed to register builtin RPC call handler for '{method}'" unless (← IO.initializing) do throw <| IO.userError s!"{errMsg}: only possible during initialization" if (←builtinRpcProcedures.get).contains method then throw <| IO.userError s!"{errMsg}: already registered" let proc := wrapRpcProcedure method paramType respType handler builtinRpcProcedures.modify fun ps => ps.insert method proc open Lean Elab Command Term Meta in def registerRpcProcedure (method : Name) : CoreM Unit := do let env ← getEnv let errMsg := "Failed to register RPC call handler for '{method}'" if (←builtinRpcProcedures.get).contains method then throwError s!"{errMsg}: already registered (builtin)" if userRpcProcedures.contains env method then throwError s!"{errMsg}: already registered" let wrappedName := method ++ `_rpc_wrapped let procT := mkConst ``RpcProcedure let proc ← MetaM.run' <| TermElabM.run' <| withoutErrToSorry do let stx ← ``(wrapRpcProcedure $(quote method) _ _ $(mkIdent method)) let c ← Lean.Elab.Term.elabTerm stx procT instantiateMVars c addAndCompile <| Declaration.defnDecl { name := wrappedName type := procT value := proc safety := DefinitionSafety.safe levelParams := [] hints := ReducibilityHints.opaque } setEnv <| userRpcProcedures.insert (← getEnv) method wrappedName builtin_initialize registerBuiltinAttribute { name := `serverRpcMethod descr := "Marks a function as a Lean server RPC method. Shorthand for `registerRpcProcedure`. The function must have type `α → RequestM (RequestTask β)` with `[RpcEncodable α]` and `[RpcEncodable β]`." applicationTime := AttributeApplicationTime.afterCompilation add := fun decl _ _ => registerRpcProcedure decl } end Lean.Server
4bf3710df293752cd471dd3eb2e5d004e15b2769
94e33a31faa76775069b071adea97e86e218a8ee
/src/topology/constructions.lean
c7f021430b5497321812008d4296e213485306c7
[ "Apache-2.0" ]
permissive
urkud/mathlib
eab80095e1b9f1513bfb7f25b4fa82fa4fd02989
6379d39e6b5b279df9715f8011369a301b634e41
refs/heads/master
1,658,425,342,662
1,658,078,703,000
1,658,078,703,000
186,910,338
0
0
Apache-2.0
1,568,512,083,000
1,557,958,709,000
Lean
UTF-8
Lean
false
false
54,680
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Mario Carneiro, Patrick Massot -/ import topology.maps import order.filter.pi import data.fin.tuple /-! # Constructions of new topological spaces from old ones This file constructs products, sums, subtypes and quotients of topological spaces and sets up their basic theory, such as criteria for maps into or out of these constructions to be continuous; descriptions of the open sets, neighborhood filters, and generators of these constructions; and their behavior with respect to embeddings and other specific classes of maps. ## Implementation note The constructed topologies are defined using induced and coinduced topologies along with the complete lattice structure on topologies. Their universal properties (for example, a map `X → Y × Z` is continuous if and only if both projections `X → Y`, `X → Z` are) follow easily using order-theoretic descriptions of continuity. With more work we can also extract descriptions of the open sets, neighborhood filters and so on. ## Tags product, sum, disjoint union, subspace, quotient space -/ noncomputable theory open topological_space set filter open_locale classical topological_space filter universes u v variables {α : Type u} {β : Type v} {γ δ ε ζ : Type*} section constructions instance {p : α → Prop} [t : topological_space α] : topological_space (subtype p) := induced coe t instance {r : α → α → Prop} [t : topological_space α] : topological_space (quot r) := coinduced (quot.mk r) t instance {s : setoid α} [t : topological_space α] : topological_space (quotient s) := coinduced quotient.mk t instance [t₁ : topological_space α] [t₂ : topological_space β] : topological_space (α × β) := induced prod.fst t₁ ⊓ induced prod.snd t₂ instance [t₁ : topological_space α] [t₂ : topological_space β] : topological_space (α ⊕ β) := coinduced sum.inl t₁ ⊔ coinduced sum.inr t₂ instance {β : α → Type v} [t₂ : Πa, topological_space (β a)] : topological_space (sigma β) := ⨆a, coinduced (sigma.mk a) (t₂ a) instance Pi.topological_space {β : α → Type v} [t₂ : Πa, topological_space (β a)] : topological_space (Πa, β a) := ⨅a, induced (λf, f a) (t₂ a) instance ulift.topological_space [t : topological_space α] : topological_space (ulift.{v u} α) := t.induced ulift.down lemma quotient.preimage_mem_nhds [topological_space α] [s : setoid α] {V : set $ quotient s} {a : α} (hs : V ∈ 𝓝 (quotient.mk a)) : quotient.mk ⁻¹' V ∈ 𝓝 a := preimage_nhds_coinduced hs /-- The image of a dense set under `quotient.mk` is a dense set. -/ lemma dense.quotient [setoid α] [topological_space α] {s : set α} (H : dense s) : dense (quotient.mk '' s) := (surjective_quotient_mk α).dense_range.dense_image continuous_coinduced_rng H /-- The composition of `quotient.mk` and a function with dense range has dense range. -/ lemma dense_range.quotient [setoid α] [topological_space α] {f : β → α} (hf : dense_range f) : dense_range (quotient.mk ∘ f) := (surjective_quotient_mk α).dense_range.comp hf continuous_coinduced_rng instance {p : α → Prop} [topological_space α] [discrete_topology α] : discrete_topology (subtype p) := ⟨bot_unique $ assume s hs, ⟨coe '' s, is_open_discrete _, (set.preimage_image_eq _ subtype.coe_injective)⟩⟩ instance sum.discrete_topology [topological_space α] [topological_space β] [hα : discrete_topology α] [hβ : discrete_topology β] : discrete_topology (α ⊕ β) := ⟨by unfold sum.topological_space; simp [hα.eq_bot, hβ.eq_bot]⟩ instance sigma.discrete_topology {β : α → Type v} [Πa, topological_space (β a)] [h : Πa, discrete_topology (β a)] : discrete_topology (sigma β) := ⟨by { unfold sigma.topological_space, simp [λ a, (h a).eq_bot] }⟩ section topα variable [topological_space α] /- The 𝓝 filter and the subspace topology. -/ theorem mem_nhds_subtype (s : set α) (a : {x // x ∈ s}) (t : set {x // x ∈ s}) : t ∈ 𝓝 a ↔ ∃ u ∈ 𝓝 (a : α), coe ⁻¹' u ⊆ t := mem_nhds_induced coe a t theorem nhds_subtype (s : set α) (a : {x // x ∈ s}) : 𝓝 a = comap coe (𝓝 (a : α)) := nhds_induced coe a end topα /-- A type synonym equiped with the topology whose open sets are the empty set and the sets with finite complements. -/ def cofinite_topology (α : Type*) := α namespace cofinite_topology /-- The identity equivalence between `α` and `cofinite_topology α`. -/ def of : α ≃ cofinite_topology α := equiv.refl α instance [inhabited α] : inhabited (cofinite_topology α) := { default := of default } instance : topological_space (cofinite_topology α) := { is_open := λ s, s.nonempty → set.finite sᶜ, is_open_univ := by simp, is_open_inter := λ s t, begin rintros hs ht ⟨x, hxs, hxt⟩, rw compl_inter, exact (hs ⟨x, hxs⟩).union (ht ⟨x, hxt⟩), end, is_open_sUnion := begin rintros s h ⟨x, t, hts, hzt⟩, rw set.compl_sUnion, exact set.finite.sInter (mem_image_of_mem _ hts) (h t hts ⟨x, hzt⟩), end } lemma is_open_iff {s : set (cofinite_topology α)} : is_open s ↔ (s.nonempty → (sᶜ).finite) := iff.rfl lemma is_open_iff' {s : set (cofinite_topology α)} : is_open s ↔ (s = ∅ ∨ (sᶜ).finite) := by simp only [is_open_iff, ← ne_empty_iff_nonempty, or_iff_not_imp_left] lemma is_closed_iff {s : set (cofinite_topology α)} : is_closed s ↔ s = univ ∨ s.finite := by simp [← is_open_compl_iff, is_open_iff'] lemma nhds_eq (a : cofinite_topology α) : 𝓝 a = pure a ⊔ cofinite := begin ext U, rw mem_nhds_iff, split, { rintro ⟨V, hVU, V_op, haV⟩, exact mem_sup.mpr ⟨hVU haV, mem_of_superset (V_op ⟨_, haV⟩) hVU⟩ }, { rintros ⟨hU : a ∈ U, hU' : (Uᶜ).finite⟩, exact ⟨U, subset.rfl, λ h, hU', hU⟩ } end lemma mem_nhds_iff {a : cofinite_topology α} {s : set (cofinite_topology α)} : s ∈ 𝓝 a ↔ a ∈ s ∧ sᶜ.finite := by simp [nhds_eq] end cofinite_topology end constructions section prod variables [topological_space α] [topological_space β] [topological_space γ] [topological_space δ] [topological_space ε] [topological_space ζ] @[continuity] lemma continuous_fst : continuous (@prod.fst α β) := continuous_inf_dom_left continuous_induced_dom /-- Postcomposing `f` with `prod.fst` is continuous -/ lemma continuous.fst {f : α → β × γ} (hf : continuous f) : continuous (λ a : α, (f a).1) := continuous_fst.comp hf /-- Precomposing `f` with `prod.fst` is continuous -/ lemma continuous.fst' {f : α → γ} (hf : continuous f) : continuous (λ x : α × β, f x.fst) := hf.comp continuous_fst lemma continuous_at_fst {p : α × β} : continuous_at prod.fst p := continuous_fst.continuous_at /-- Postcomposing `f` with `prod.fst` is continuous at `x` -/ lemma continuous_at.fst {f : α → β × γ} {x : α} (hf : continuous_at f x) : continuous_at (λ a : α, (f a).1) x := continuous_at_fst.comp hf /-- Precomposing `f` with `prod.fst` is continuous at `(x, y)` -/ lemma continuous_at.fst' {f : α → γ} {x : α} {y : β} (hf : continuous_at f x) : continuous_at (λ x : α × β, f x.fst) (x, y) := continuous_at.comp hf continuous_at_fst /-- Precomposing `f` with `prod.fst` is continuous at `x : α × β` -/ lemma continuous_at.fst'' {f : α → γ} {x : α × β} (hf : continuous_at f x.fst) : continuous_at (λ x : α × β, f x.fst) x := hf.comp continuous_at_fst @[continuity] lemma continuous_snd : continuous (@prod.snd α β) := continuous_inf_dom_right continuous_induced_dom /-- Postcomposing `f` with `prod.snd` is continuous -/ lemma continuous.snd {f : α → β × γ} (hf : continuous f) : continuous (λ a : α, (f a).2) := continuous_snd.comp hf /-- Precomposing `f` with `prod.snd` is continuous -/ lemma continuous.snd' {f : β → γ} (hf : continuous f) : continuous (λ x : α × β, f x.snd) := hf.comp continuous_snd lemma continuous_at_snd {p : α × β} : continuous_at prod.snd p := continuous_snd.continuous_at /-- Postcomposing `f` with `prod.snd` is continuous at `x` -/ lemma continuous_at.snd {f : α → β × γ} {x : α} (hf : continuous_at f x) : continuous_at (λ a : α, (f a).2) x := continuous_at_snd.comp hf /-- Precomposing `f` with `prod.snd` is continuous at `(x, y)` -/ lemma continuous_at.snd' {f : β → γ} {x : α} {y : β} (hf : continuous_at f y) : continuous_at (λ x : α × β, f x.snd) (x, y) := continuous_at.comp hf continuous_at_snd /-- Precomposing `f` with `prod.snd` is continuous at `x : α × β` -/ lemma continuous_at.snd'' {f : β → γ} {x : α × β} (hf : continuous_at f x.snd) : continuous_at (λ x : α × β, f x.snd) x := hf.comp continuous_at_snd @[continuity] lemma continuous.prod_mk {f : γ → α} {g : γ → β} (hf : continuous f) (hg : continuous g) : continuous (λx, (f x, g x)) := continuous_inf_rng (continuous_induced_rng hf) (continuous_induced_rng hg) @[continuity] lemma continuous.prod.mk (a : α) : continuous (λ b : β, (a, b)) := continuous_const.prod_mk continuous_id' @[continuity] lemma continuous.prod.mk_left (b : β) : continuous (λ a : α, (a, b)) := continuous_id'.prod_mk continuous_const lemma continuous.comp₂ {g : α × β → γ} (hg : continuous g) {e : δ → α} (he : continuous e) {f : δ → β} (hf : continuous f) : continuous (λ x, g (e x, f x)) := hg.comp $ he.prod_mk hf lemma continuous.comp₃ {g : α × β × γ → ε} (hg : continuous g) {e : δ → α} (he : continuous e) {f : δ → β} (hf : continuous f) {k : δ → γ} (hk : continuous k) : continuous (λ x, g (e x, f x, k x)) := hg.comp₂ he $ hf.prod_mk hk lemma continuous.comp₄ {g : α × β × γ × ζ → ε} (hg : continuous g) {e : δ → α} (he : continuous e) {f : δ → β} (hf : continuous f) {k : δ → γ} (hk : continuous k) {l : δ → ζ} (hl : continuous l) : continuous (λ x, g (e x, f x, k x, l x)) := hg.comp₃ he hf $ hk.prod_mk hl lemma continuous.prod_map {f : γ → α} {g : δ → β} (hf : continuous f) (hg : continuous g) : continuous (λ x : γ × δ, (f x.1, g x.2)) := hf.fst'.prod_mk hg.snd' /-- A version of `continuous_inf_dom_left` for binary functions -/ lemma continuous_inf_dom_left₂ {α β γ} {f : α → β → γ} {ta1 ta2 : topological_space α} {tb1 tb2 : topological_space β} {tc1 : topological_space γ} (h : by haveI := ta1; haveI := tb1; exact continuous (λ p : α × β, f p.1 p.2)) : by haveI := ta1 ⊓ ta2; haveI := tb1 ⊓ tb2; exact continuous (λ p : α × β, f p.1 p.2) := begin have ha := @continuous_inf_dom_left _ _ id ta1 ta2 ta1 (@continuous_id _ (id _)), have hb := @continuous_inf_dom_left _ _ id tb1 tb2 tb1 (@continuous_id _ (id _)), have h_continuous_id := @continuous.prod_map _ _ _ _ ta1 tb1 (ta1 ⊓ ta2) (tb1 ⊓ tb2) _ _ ha hb, exact @continuous.comp _ _ _ (id _) (id _) _ _ _ h h_continuous_id, end /-- A version of `continuous_inf_dom_right` for binary functions -/ lemma continuous_inf_dom_right₂ {α β γ} {f : α → β → γ} {ta1 ta2 : topological_space α} {tb1 tb2 : topological_space β} {tc1 : topological_space γ} (h : by haveI := ta2; haveI := tb2; exact continuous (λ p : α × β, f p.1 p.2)) : by haveI := ta1 ⊓ ta2; haveI := tb1 ⊓ tb2; exact continuous (λ p : α × β, f p.1 p.2) := begin have ha := @continuous_inf_dom_right _ _ id ta1 ta2 ta2 (@continuous_id _ (id _)), have hb := @continuous_inf_dom_right _ _ id tb1 tb2 tb2 (@continuous_id _ (id _)), have h_continuous_id := @continuous.prod_map _ _ _ _ ta2 tb2 (ta1 ⊓ ta2) (tb1 ⊓ tb2) _ _ ha hb, exact @continuous.comp _ _ _ (id _) (id _) _ _ _ h h_continuous_id, end /-- A version of `continuous_Inf_dom` for binary functions -/ lemma continuous_Inf_dom₂ {α β γ} {f : α → β → γ} {tas : set (topological_space α)} {tbs : set (topological_space β)} {ta : topological_space α} {tb : topological_space β} {tc : topological_space γ} (ha : ta ∈ tas) (hb : tb ∈ tbs) (hf : continuous (λ p : α × β, f p.1 p.2)): by haveI := Inf tas; haveI := Inf tbs; exact @continuous _ _ _ tc (λ p : α × β, f p.1 p.2) := begin let t : topological_space (α × β) := prod.topological_space, have ha := continuous_Inf_dom ha continuous_id, have hb := continuous_Inf_dom hb continuous_id, have h_continuous_id := @continuous.prod_map _ _ _ _ ta tb (Inf tas) (Inf tbs) _ _ ha hb, exact @continuous.comp _ _ _ (id _) (id _) _ _ _ hf h_continuous_id, end lemma filter.eventually.prod_inl_nhds {p : α → Prop} {a : α} (h : ∀ᶠ x in 𝓝 a, p x) (b : β) : ∀ᶠ x in 𝓝 (a, b), p (x : α × β).1 := continuous_at_fst h lemma filter.eventually.prod_inr_nhds {p : β → Prop} {b : β} (h : ∀ᶠ x in 𝓝 b, p x) (a : α) : ∀ᶠ x in 𝓝 (a, b), p (x : α × β).2 := continuous_at_snd h lemma filter.eventually.prod_mk_nhds {pa : α → Prop} {a} (ha : ∀ᶠ x in 𝓝 a, pa x) {pb : β → Prop} {b} (hb : ∀ᶠ y in 𝓝 b, pb y) : ∀ᶠ p in 𝓝 (a, b), pa (p : α × β).1 ∧ pb p.2 := (ha.prod_inl_nhds b).and (hb.prod_inr_nhds a) lemma continuous_swap : continuous (prod.swap : α × β → β × α) := continuous_snd.prod_mk continuous_fst lemma continuous_uncurry_left {f : α → β → γ} (a : α) (h : continuous (function.uncurry f)) : continuous (f a) := show continuous (function.uncurry f ∘ (λ b, (a, b))), from h.comp (by continuity) lemma continuous_uncurry_right {f : α → β → γ} (b : β) (h : continuous (function.uncurry f)) : continuous (λ a, f a b) := show continuous (function.uncurry f ∘ (λ a, (a, b))), from h.comp (by continuity) lemma continuous_curry {g : α × β → γ} (a : α) (h : continuous g) : continuous (function.curry g a) := show continuous (g ∘ (λ b, (a, b))), from h.comp (by continuity) lemma is_open.prod {s : set α} {t : set β} (hs : is_open s) (ht : is_open t) : is_open (s ×ˢ t) := (hs.preimage continuous_fst).inter (ht.preimage continuous_snd) lemma nhds_prod_eq {a : α} {b : β} : 𝓝 (a, b) = 𝓝 a ×ᶠ 𝓝 b := by rw [filter.prod, prod.topological_space, nhds_inf, nhds_induced, nhds_induced] /-- If a function `f x y` is such that `y ↦ f x y` is continuous for all `x`, and `x` lives in a discrete space, then `f` is continuous. -/ lemma continuous_uncurry_of_discrete_topology [discrete_topology α] {f : α → β → γ} (hf : ∀ a, continuous (f a)) : continuous (function.uncurry f) := begin apply continuous_iff_continuous_at.2, rintros ⟨a, x⟩, change map _ _ ≤ _, rw [nhds_prod_eq, nhds_discrete, filter.map_pure_prod], exact (hf a).continuous_at end lemma mem_nhds_prod_iff {a : α} {b : β} {s : set (α × β)} : s ∈ 𝓝 (a, b) ↔ ∃ (u ∈ 𝓝 a) (v ∈ 𝓝 b), u ×ˢ v ⊆ s := by rw [nhds_prod_eq, mem_prod_iff] lemma mem_nhds_prod_iff' {a : α} {b : β} {s : set (α × β)} : s ∈ 𝓝 (a, b) ↔ ∃ (u : set α) (v : set β), is_open u ∧ a ∈ u ∧ is_open v ∧ b ∈ v ∧ u ×ˢ v ⊆ s := begin rw mem_nhds_prod_iff, split, { rintros ⟨u, Hu, v, Hv, h⟩, rcases mem_nhds_iff.1 Hu with ⟨u', u'u, u'_open, Hu'⟩, rcases mem_nhds_iff.1 Hv with ⟨v', v'v, v'_open, Hv'⟩, exact ⟨u', v', u'_open, Hu', v'_open, Hv', (set.prod_mono u'u v'v).trans h⟩ }, { rintros ⟨u, v, u_open, au, v_open, bv, huv⟩, exact ⟨u, u_open.mem_nhds au, v, v_open.mem_nhds bv, huv⟩ } end lemma _root_.prod.tendsto_iff {α} (seq : α → β × γ) {f : filter α} (x : β × γ) : tendsto seq f (𝓝 x) ↔ tendsto (λ n, (seq n).fst) f (𝓝 x.fst) ∧ tendsto (λ n, (seq n).snd) f (𝓝 x.snd) := by { cases x, rw [nhds_prod_eq, filter.tendsto_prod_iff'], } lemma filter.has_basis.prod_nhds {ιa ιb : Type*} {pa : ιa → Prop} {pb : ιb → Prop} {sa : ιa → set α} {sb : ιb → set β} {a : α} {b : β} (ha : (𝓝 a).has_basis pa sa) (hb : (𝓝 b).has_basis pb sb) : (𝓝 (a, b)).has_basis (λ i : ιa × ιb, pa i.1 ∧ pb i.2) (λ i, sa i.1 ×ˢ sb i.2) := by { rw nhds_prod_eq, exact ha.prod hb } lemma filter.has_basis.prod_nhds' {ιa ιb : Type*} {pa : ιa → Prop} {pb : ιb → Prop} {sa : ιa → set α} {sb : ιb → set β} {ab : α × β} (ha : (𝓝 ab.1).has_basis pa sa) (hb : (𝓝 ab.2).has_basis pb sb) : (𝓝 ab).has_basis (λ i : ιa × ιb, pa i.1 ∧ pb i.2) (λ i, sa i.1 ×ˢ sb i.2) := by { cases ab, exact ha.prod_nhds hb } instance [discrete_topology α] [discrete_topology β] : discrete_topology (α × β) := ⟨eq_of_nhds_eq_nhds $ assume ⟨a, b⟩, by rw [nhds_prod_eq, nhds_discrete α, nhds_discrete β, nhds_bot, filter.prod_pure_pure]⟩ lemma prod_mem_nhds_iff {s : set α} {t : set β} {a : α} {b : β} : s ×ˢ t ∈ 𝓝 (a, b) ↔ s ∈ 𝓝 a ∧ t ∈ 𝓝 b := by rw [nhds_prod_eq, prod_mem_prod_iff] lemma prod_mem_nhds {s : set α} {t : set β} {a : α} {b : β} (ha : s ∈ 𝓝 a) (hb : t ∈ 𝓝 b) : s ×ˢ t ∈ 𝓝 (a, b) := prod_mem_nhds_iff.2 ⟨ha, hb⟩ lemma filter.eventually.prod_nhds {p : α → Prop} {q : β → Prop} {a : α} {b : β} (ha : ∀ᶠ x in 𝓝 a, p x) (hb : ∀ᶠ y in 𝓝 b, q y) : ∀ᶠ z : α × β in 𝓝 (a, b), p z.1 ∧ q z.2 := prod_mem_nhds ha hb lemma nhds_swap (a : α) (b : β) : 𝓝 (a, b) = (𝓝 (b, a)).map prod.swap := by rw [nhds_prod_eq, filter.prod_comm, nhds_prod_eq]; refl lemma filter.tendsto.prod_mk_nhds {γ} {a : α} {b : β} {f : filter γ} {ma : γ → α} {mb : γ → β} (ha : tendsto ma f (𝓝 a)) (hb : tendsto mb f (𝓝 b)) : tendsto (λc, (ma c, mb c)) f (𝓝 (a, b)) := by rw [nhds_prod_eq]; exact filter.tendsto.prod_mk ha hb lemma filter.eventually.curry_nhds {p : α × β → Prop} {x : α} {y : β} (h : ∀ᶠ x in 𝓝 (x, y), p x) : ∀ᶠ x' in 𝓝 x, ∀ᶠ y' in 𝓝 y, p (x', y') := by { rw [nhds_prod_eq] at h, exact h.curry } lemma continuous_at.prod {f : α → β} {g : α → γ} {x : α} (hf : continuous_at f x) (hg : continuous_at g x) : continuous_at (λx, (f x, g x)) x := hf.prod_mk_nhds hg lemma continuous_at.prod_map {f : α → γ} {g : β → δ} {p : α × β} (hf : continuous_at f p.fst) (hg : continuous_at g p.snd) : continuous_at (λ p : α × β, (f p.1, g p.2)) p := hf.fst''.prod hg.snd'' lemma continuous_at.prod_map' {f : α → γ} {g : β → δ} {x : α} {y : β} (hf : continuous_at f x) (hg : continuous_at g y) : continuous_at (λ p : α × β, (f p.1, g p.2)) (x, y) := hf.fst'.prod hg.snd' lemma prod_generate_from_generate_from_eq {α β : Type*} {s : set (set α)} {t : set (set β)} (hs : ⋃₀ s = univ) (ht : ⋃₀ t = univ) : @prod.topological_space α β (generate_from s) (generate_from t) = generate_from {g | ∃ u ∈ s, ∃ v ∈ t, g = u ×ˢ v} := let G := generate_from {g | ∃ u ∈ s, ∃ v ∈ t, g = u ×ˢ v} in le_antisymm (le_generate_from $ λ g ⟨u, hu, v, hv, g_eq⟩, g_eq.symm ▸ @is_open.prod _ _ (generate_from s) (generate_from t) _ _ (generate_open.basic _ hu) (generate_open.basic _ hv)) (le_inf (coinduced_le_iff_le_induced.mp $ le_generate_from $ λ u hu, have (⋃ v ∈ t, u ×ˢ v) = prod.fst ⁻¹' u, by simp_rw [← prod_Union, ← sUnion_eq_bUnion, ht, prod_univ], show G.is_open (prod.fst ⁻¹' u), by { rw [← this], exactI is_open_Union (λ v, is_open_Union $ λ hv, generate_open.basic _ ⟨_, hu, _, hv, rfl⟩) }) (coinduced_le_iff_le_induced.mp $ le_generate_from $ λ v hv, have (⋃ u ∈ s, u ×ˢ v) = prod.snd ⁻¹' v, by simp_rw [← Union_prod_const, ← sUnion_eq_bUnion, hs, univ_prod], show G.is_open (prod.snd ⁻¹' v), by { rw [← this], exactI is_open_Union (λ u, is_open_Union $ λ hu, generate_open.basic _ ⟨_, hu, _, hv, rfl⟩) })) lemma prod_eq_generate_from : prod.topological_space = generate_from {g | ∃(s:set α) (t:set β), is_open s ∧ is_open t ∧ g = s ×ˢ t} := le_antisymm (le_generate_from $ λ g ⟨s, t, hs, ht, g_eq⟩, g_eq.symm ▸ hs.prod ht) (le_inf (ball_image_of_ball $ λt ht, generate_open.basic _ ⟨t, univ, by simpa [set.prod_eq] using ht⟩) (ball_image_of_ball $ λt ht, generate_open.basic _ ⟨univ, t, by simpa [set.prod_eq] using ht⟩)) lemma is_open_prod_iff {s : set (α × β)} : is_open s ↔ (∀a b, (a, b) ∈ s → ∃ (u : set α) (v : set β), is_open u ∧ is_open v ∧ a ∈ u ∧ b ∈ v ∧ u ×ˢ v ⊆ s) := begin rw [is_open_iff_nhds], simp_rw [le_principal_iff, prod.forall, ((nhds_basis_opens _).prod_nhds (nhds_basis_opens _)).mem_iff, prod.exists, exists_prop], simp only [and_assoc, and.left_comm] end /-- A product of induced topologies is induced by the product map -/ lemma prod_induced_induced {α γ : Type*} (f : α → β) (g : γ → δ) : @prod.topological_space α γ (induced f ‹_›) (induced g ‹_›) = induced (λ p, (f p.1, g p.2)) prod.topological_space := by simp_rw [prod.topological_space, induced_inf, induced_compose] lemma continuous_uncurry_of_discrete_topology_left [discrete_topology α] {f : α → β → γ} (h : ∀ a, continuous (f a)) : continuous (function.uncurry f) := continuous_iff_continuous_at.2 $ λ ⟨a, b⟩, by simp only [continuous_at, nhds_prod_eq, nhds_discrete α, pure_prod, tendsto_map'_iff, (∘), function.uncurry, (h a).tendsto] /-- Given a neighborhood `s` of `(x, x)`, then `(x, x)` has a square open neighborhood that is a subset of `s`. -/ lemma exists_nhds_square {s : set (α × α)} {x : α} (hx : s ∈ 𝓝 (x, x)) : ∃ U : set α, is_open U ∧ x ∈ U ∧ U ×ˢ U ⊆ s := by simpa [nhds_prod_eq, (nhds_basis_opens x).prod_self.mem_iff, and.assoc, and.left_comm] using hx /-- `prod.fst` maps neighborhood of `x : α × β` within the section `prod.snd ⁻¹' {x.2}` to `𝓝 x.1`. -/ lemma map_fst_nhds_within (x : α × β) : map prod.fst (𝓝[prod.snd ⁻¹' {x.2}] x) = 𝓝 x.1 := begin refine le_antisymm (continuous_at_fst.mono_left inf_le_left) (λ s hs, _), rcases x with ⟨x, y⟩, rw [mem_map, nhds_within, mem_inf_principal, mem_nhds_prod_iff] at hs, rcases hs with ⟨u, hu, v, hv, H⟩, simp only [prod_subset_iff, mem_singleton_iff, mem_set_of_eq, mem_preimage] at H, exact mem_of_superset hu (λ z hz, H _ hz _ (mem_of_mem_nhds hv) rfl) end @[simp] lemma map_fst_nhds (x : α × β) : map prod.fst (𝓝 x) = 𝓝 x.1 := le_antisymm continuous_at_fst $ (map_fst_nhds_within x).symm.trans_le (map_mono inf_le_left) /-- The first projection in a product of topological spaces sends open sets to open sets. -/ lemma is_open_map_fst : is_open_map (@prod.fst α β) := is_open_map_iff_nhds_le.2 $ λ x, (map_fst_nhds x).ge /-- `prod.snd` maps neighborhood of `x : α × β` within the section `prod.fst ⁻¹' {x.1}` to `𝓝 x.2`. -/ lemma map_snd_nhds_within (x : α × β) : map prod.snd (𝓝[prod.fst ⁻¹' {x.1}] x) = 𝓝 x.2 := begin refine le_antisymm (continuous_at_snd.mono_left inf_le_left) (λ s hs, _), rcases x with ⟨x, y⟩, rw [mem_map, nhds_within, mem_inf_principal, mem_nhds_prod_iff] at hs, rcases hs with ⟨u, hu, v, hv, H⟩, simp only [prod_subset_iff, mem_singleton_iff, mem_set_of_eq, mem_preimage] at H, exact mem_of_superset hv (λ z hz, H _ (mem_of_mem_nhds hu) _ hz rfl) end @[simp] lemma map_snd_nhds (x : α × β) : map prod.snd (𝓝 x) = 𝓝 x.2 := le_antisymm continuous_at_snd $ (map_snd_nhds_within x).symm.trans_le (map_mono inf_le_left) /-- The second projection in a product of topological spaces sends open sets to open sets. -/ lemma is_open_map_snd : is_open_map (@prod.snd α β) := is_open_map_iff_nhds_le.2 $ λ x, (map_snd_nhds x).ge /-- A product set is open in a product space if and only if each factor is open, or one of them is empty -/ lemma is_open_prod_iff' {s : set α} {t : set β} : is_open (s ×ˢ t) ↔ (is_open s ∧ is_open t) ∨ (s = ∅) ∨ (t = ∅) := begin cases (s ×ˢ t : set _).eq_empty_or_nonempty with h h, { simp [h, prod_eq_empty_iff.1 h] }, { have st : s.nonempty ∧ t.nonempty, from prod_nonempty_iff.1 h, split, { assume H : is_open (s ×ˢ t), refine or.inl ⟨_, _⟩, show is_open s, { rw ← fst_image_prod s st.2, exact is_open_map_fst _ H }, show is_open t, { rw ← snd_image_prod st.1 t, exact is_open_map_snd _ H } }, { assume H, simp only [st.1.ne_empty, st.2.ne_empty, not_false_iff, or_false] at H, exact H.1.prod H.2 } } end lemma closure_prod_eq {s : set α} {t : set β} : closure (s ×ˢ t) = closure s ×ˢ closure t := set.ext $ assume ⟨a, b⟩, have (𝓝 a ×ᶠ 𝓝 b) ⊓ 𝓟 (s ×ˢ t) = (𝓝 a ⊓ 𝓟 s) ×ᶠ (𝓝 b ⊓ 𝓟 t), by rw [←prod_inf_prod, prod_principal_principal], by simp [closure_eq_cluster_pts, cluster_pt, nhds_prod_eq, this]; exact prod_ne_bot lemma interior_prod_eq (s : set α) (t : set β) : interior (s ×ˢ t) = interior s ×ˢ interior t := set.ext $ λ ⟨a, b⟩, by simp only [mem_interior_iff_mem_nhds, mem_prod, prod_mem_nhds_iff] lemma frontier_prod_eq (s : set α) (t : set β) : frontier (s ×ˢ t) = closure s ×ˢ frontier t ∪ frontier s ×ˢ closure t := by simp only [frontier, closure_prod_eq, interior_prod_eq, prod_diff_prod] @[simp] lemma frontier_prod_univ_eq (s : set α) : frontier (s ×ˢ (univ : set β)) = frontier s ×ˢ (univ : set β) := by simp [frontier_prod_eq] @[simp] lemma frontier_univ_prod_eq (s : set β) : frontier ((univ : set α) ×ˢ s) = (univ : set α) ×ˢ (frontier s) := by simp [frontier_prod_eq] lemma map_mem_closure2 {s : set α} {t : set β} {u : set γ} {f : α → β → γ} {a : α} {b : β} (hf : continuous (λp:α×β, f p.1 p.2)) (ha : a ∈ closure s) (hb : b ∈ closure t) (hu : ∀a b, a ∈ s → b ∈ t → f a b ∈ u) : f a b ∈ closure u := have (a, b) ∈ closure (s ×ˢ t), by rw [closure_prod_eq]; from ⟨ha, hb⟩, show (λp:α×β, f p.1 p.2) (a, b) ∈ closure u, from map_mem_closure hf this $ assume ⟨a, b⟩ ⟨ha, hb⟩, hu a b ha hb lemma is_closed.prod {s₁ : set α} {s₂ : set β} (h₁ : is_closed s₁) (h₂ : is_closed s₂) : is_closed (s₁ ×ˢ s₂) := closure_eq_iff_is_closed.mp $ by simp only [h₁.closure_eq, h₂.closure_eq, closure_prod_eq] /-- The product of two dense sets is a dense set. -/ lemma dense.prod {s : set α} {t : set β} (hs : dense s) (ht : dense t) : dense (s ×ˢ t) := λ x, by { rw closure_prod_eq, exact ⟨hs x.1, ht x.2⟩ } /-- If `f` and `g` are maps with dense range, then `prod.map f g` has dense range. -/ lemma dense_range.prod_map {ι : Type*} {κ : Type*} {f : ι → β} {g : κ → γ} (hf : dense_range f) (hg : dense_range g) : dense_range (prod.map f g) := by simpa only [dense_range, prod_range_range_eq] using hf.prod hg lemma inducing.prod_mk {f : α → β} {g : γ → δ} (hf : inducing f) (hg : inducing g) : inducing (λx:α×γ, (f x.1, g x.2)) := ⟨by rw [prod.topological_space, prod.topological_space, hf.induced, hg.induced, induced_compose, induced_compose, induced_inf, induced_compose, induced_compose]⟩ lemma embedding.prod_mk {f : α → β} {g : γ → δ} (hf : embedding f) (hg : embedding g) : embedding (λx:α×γ, (f x.1, g x.2)) := { inj := assume ⟨x₁, x₂⟩ ⟨y₁, y₂⟩, by simp; exact assume h₁ h₂, ⟨hf.inj h₁, hg.inj h₂⟩, ..hf.to_inducing.prod_mk hg.to_inducing } protected lemma is_open_map.prod {f : α → β} {g : γ → δ} (hf : is_open_map f) (hg : is_open_map g) : is_open_map (λ p : α × γ, (f p.1, g p.2)) := begin rw [is_open_map_iff_nhds_le], rintros ⟨a, b⟩, rw [nhds_prod_eq, nhds_prod_eq, ← filter.prod_map_map_eq], exact filter.prod_mono (is_open_map_iff_nhds_le.1 hf a) (is_open_map_iff_nhds_le.1 hg b) end protected lemma open_embedding.prod {f : α → β} {g : γ → δ} (hf : open_embedding f) (hg : open_embedding g) : open_embedding (λ x : α × γ, (f x.1, g x.2)) := open_embedding_of_embedding_open (hf.1.prod_mk hg.1) (hf.is_open_map.prod hg.is_open_map) lemma embedding_graph {f : α → β} (hf : continuous f) : embedding (λ x, (x, f x)) := embedding_of_embedding_compose (continuous_id.prod_mk hf) continuous_fst embedding_id end prod section sum open sum variables [topological_space α] [topological_space β] [topological_space γ] [topological_space δ] @[continuity] lemma continuous_inl : continuous (@inl α β) := continuous_sup_rng_left continuous_coinduced_rng @[continuity] lemma continuous_inr : continuous (@inr α β) := continuous_sup_rng_right continuous_coinduced_rng @[continuity] lemma continuous.sum_elim {f : α → γ} {g : β → γ} (hf : continuous f) (hg : continuous g) : continuous (sum.elim f g) := begin apply continuous_sup_dom; rw continuous_def at hf hg ⊢; assumption end @[continuity] lemma continuous.sum_map {f : α → β} {g : γ → δ} (hf : continuous f) (hg : continuous g) : continuous (sum.map f g) := (continuous_inl.comp hf).sum_elim (continuous_inr.comp hg) lemma is_open_sum_iff {s : set (α ⊕ β)} : is_open s ↔ is_open (inl ⁻¹' s) ∧ is_open (inr ⁻¹' s) := iff.rfl lemma is_open_map_sum {f : α ⊕ β → γ} (h₁ : is_open_map (λ a, f (inl a))) (h₂ : is_open_map (λ b, f (inr b))) : is_open_map f := begin intros u hu, rw is_open_sum_iff at hu, cases hu with hu₁ hu₂, have : u = inl '' (inl ⁻¹' u) ∪ inr '' (inr ⁻¹' u), { ext (_|_); simp }, rw [this, set.image_union, set.image_image, set.image_image], exact is_open.union (h₁ _ hu₁) (h₂ _ hu₂) end lemma embedding_inl : embedding (@inl α β) := { induced := begin unfold sum.topological_space, apply le_antisymm, { rw ← coinduced_le_iff_le_induced, exact le_sup_left }, { intros u hu, existsi (inl '' u), change (is_open (inl ⁻¹' (@inl α β '' u)) ∧ is_open (inr ⁻¹' (@inl α β '' u))) ∧ inl ⁻¹' (inl '' u) = u, rw [preimage_image_eq u sum.inl_injective, preimage_inr_image_inl], exact ⟨⟨hu, is_open_empty⟩, rfl⟩ } end, inj := λ _ _, inl.inj_iff.mp } lemma embedding_inr : embedding (@inr α β) := { induced := begin unfold sum.topological_space, apply le_antisymm, { rw ← coinduced_le_iff_le_induced, exact le_sup_right }, { intros u hu, existsi (inr '' u), change (is_open (inl ⁻¹' (@inr α β '' u)) ∧ is_open (inr ⁻¹' (@inr α β '' u))) ∧ inr ⁻¹' (inr '' u) = u, rw [preimage_inl_image_inr, preimage_image_eq u sum.inr_injective], exact ⟨⟨is_open_empty, hu⟩, rfl⟩ } end, inj := λ _ _, inr.inj_iff.mp } lemma is_open_range_inl : is_open (range (inl : α → α ⊕ β)) := is_open_sum_iff.2 $ by simp lemma is_open_range_inr : is_open (range (inr : β → α ⊕ β)) := is_open_sum_iff.2 $ by simp lemma is_closed_range_inl : is_closed (range (inl : α → α ⊕ β)) := by { rw [← is_open_compl_iff, compl_range_inl], exact is_open_range_inr } lemma is_closed_range_inr : is_closed (range (inr : β → α ⊕ β)) := by { rw [← is_open_compl_iff, compl_range_inr], exact is_open_range_inl } lemma open_embedding_inl : open_embedding (inl : α → α ⊕ β) := { open_range := is_open_range_inl, .. embedding_inl } lemma open_embedding_inr : open_embedding (inr : β → α ⊕ β) := { open_range := is_open_range_inr, .. embedding_inr } lemma closed_embedding_inl : closed_embedding (inl : α → α ⊕ β) := { closed_range := is_closed_range_inl, .. embedding_inl } lemma closed_embedding_inr : closed_embedding (inr : β → α ⊕ β) := { closed_range := is_closed_range_inr, .. embedding_inr } end sum section subtype variables [topological_space α] [topological_space β] [topological_space γ] {p : α → Prop} lemma inducing_coe {b : set β} : inducing (coe : b → β) := ⟨rfl⟩ lemma inducing.of_cod_restrict {f : α → β} {b : set β} (hb : ∀ a, f a ∈ b) (h : inducing (b.cod_restrict f hb)) : inducing f := inducing_coe.comp h lemma embedding_subtype_coe : embedding (coe : subtype p → α) := ⟨⟨rfl⟩, subtype.coe_injective⟩ lemma closed_embedding_subtype_coe (h : is_closed {a | p a}) : closed_embedding (coe : subtype p → α) := ⟨embedding_subtype_coe, by rwa [subtype.range_coe_subtype]⟩ @[continuity] lemma continuous_subtype_val : continuous (@subtype.val α p) := continuous_induced_dom lemma continuous_subtype_coe : continuous (coe : subtype p → α) := continuous_subtype_val lemma continuous.subtype_coe {f : β → subtype p} (hf : continuous f) : continuous (λ x, (f x : α)) := continuous_subtype_coe.comp hf lemma is_open.open_embedding_subtype_coe {s : set α} (hs : is_open s) : open_embedding (coe : s → α) := { induced := rfl, inj := subtype.coe_injective, open_range := (subtype.range_coe : range coe = s).symm ▸ hs } lemma is_open.is_open_map_subtype_coe {s : set α} (hs : is_open s) : is_open_map (coe : s → α) := hs.open_embedding_subtype_coe.is_open_map lemma is_open_map.restrict {f : α → β} (hf : is_open_map f) {s : set α} (hs : is_open s) : is_open_map (s.restrict f) := hf.comp hs.is_open_map_subtype_coe lemma is_closed.closed_embedding_subtype_coe {s : set α} (hs : is_closed s) : closed_embedding (coe : {x // x ∈ s} → α) := { induced := rfl, inj := subtype.coe_injective, closed_range := (subtype.range_coe : range coe = s).symm ▸ hs } @[continuity] lemma continuous_subtype_mk {f : β → α} (hp : ∀x, p (f x)) (h : continuous f) : continuous (λx, (⟨f x, hp x⟩ : subtype p)) := continuous_induced_rng h lemma continuous_inclusion {s t : set α} (h : s ⊆ t) : continuous (inclusion h) := continuous_subtype_mk _ continuous_subtype_coe lemma continuous_at_subtype_coe {p : α → Prop} {a : subtype p} : continuous_at (coe : subtype p → α) a := continuous_iff_continuous_at.mp continuous_subtype_coe _ lemma subtype.dense_iff {s : set α} {t : set s} : dense t ↔ s ⊆ closure (coe '' t) := by { rw [inducing_coe.dense_iff, set_coe.forall], refl } lemma map_nhds_subtype_coe_eq {a : α} (ha : p a) (h : {a | p a} ∈ 𝓝 a) : map (coe : subtype p → α) (𝓝 ⟨a, ha⟩) = 𝓝 a := map_nhds_induced_of_mem $ by simpa only [subtype.coe_mk, subtype.range_coe] using h lemma nhds_subtype_eq_comap {a : α} {h : p a} : 𝓝 (⟨a, h⟩ : subtype p) = comap coe (𝓝 a) := nhds_induced _ _ lemma tendsto_subtype_rng {β : Type*} {p : α → Prop} {b : filter β} {f : β → subtype p} : ∀{a:subtype p}, tendsto f b (𝓝 a) ↔ tendsto (λx, (f x : α)) b (𝓝 (a : α)) | ⟨a, ha⟩ := by rw [nhds_subtype_eq_comap, tendsto_comap_iff, subtype.coe_mk] lemma continuous_subtype_nhds_cover {ι : Sort*} {f : α → β} {c : ι → α → Prop} (c_cover : ∀x:α, ∃i, {x | c i x} ∈ 𝓝 x) (f_cont : ∀i, continuous (λ(x : subtype (c i)), f x)) : continuous f := continuous_iff_continuous_at.mpr $ assume x, let ⟨i, (c_sets : {x | c i x} ∈ 𝓝 x)⟩ := c_cover x in let x' : subtype (c i) := ⟨x, mem_of_mem_nhds c_sets⟩ in calc map f (𝓝 x) = map f (map coe (𝓝 x')) : congr_arg (map f) (map_nhds_subtype_coe_eq _ $ c_sets).symm ... = map (λx:subtype (c i), f x) (𝓝 x') : rfl ... ≤ 𝓝 (f x) : continuous_iff_continuous_at.mp (f_cont i) x' lemma continuous_subtype_is_closed_cover {ι : Sort*} {f : α → β} (c : ι → α → Prop) (h_lf : locally_finite (λi, {x | c i x})) (h_is_closed : ∀i, is_closed {x | c i x}) (h_cover : ∀x, ∃i, c i x) (f_cont : ∀i, continuous (λ(x : subtype (c i)), f x)) : continuous f := continuous_iff_is_closed.mpr $ assume s hs, have ∀i, is_closed ((coe : {x | c i x} → α) '' (f ∘ coe ⁻¹' s)), from assume i, (closed_embedding_subtype_coe (h_is_closed _)).is_closed_map _ (hs.preimage (f_cont i)), have is_closed (⋃i, (coe : {x | c i x} → α) '' (f ∘ coe ⁻¹' s)), from locally_finite.is_closed_Union (h_lf.subset $ assume i x ⟨⟨x', hx'⟩, _, heq⟩, heq ▸ hx') this, have f ⁻¹' s = (⋃i, (coe : {x | c i x} → α) '' (f ∘ coe ⁻¹' s)), begin apply set.ext, have : ∀ (x : α), f x ∈ s ↔ ∃ (i : ι), c i x ∧ f x ∈ s := λ x, ⟨λ hx, let ⟨i, hi⟩ := h_cover x in ⟨i, hi, hx⟩, λ ⟨i, hi, hx⟩, hx⟩, simpa [and.comm, @and.left_comm (c _ _), ← exists_and_distrib_right], end, by rwa [this] lemma closure_subtype {x : {a // p a}} {s : set {a // p a}}: x ∈ closure s ↔ (x : α) ∈ closure ((coe : _ → α) '' s) := closure_induced @[continuity] lemma continuous.cod_restrict {f : α → β} {s : set β} (hf : continuous f) (hs : ∀ a, f a ∈ s) : continuous (s.cod_restrict f hs) := continuous_subtype_mk hs hf lemma inducing.cod_restrict {e : α → β} (he : inducing e) {s : set β} (hs : ∀ x, e x ∈ s) : inducing (cod_restrict e s hs) := inducing_of_inducing_compose (he.continuous.cod_restrict hs) continuous_subtype_coe he lemma embedding.cod_restrict {e : α → β} (he : embedding e) (s : set β) (hs : ∀ x, e x ∈ s) : embedding (cod_restrict e s hs) := embedding_of_embedding_compose (he.continuous.cod_restrict hs) continuous_subtype_coe he end subtype section quotient variables [topological_space α] [topological_space β] [topological_space γ] variables {r : α → α → Prop} {s : setoid α} lemma quotient_map_quot_mk : quotient_map (@quot.mk α r) := ⟨quot.exists_rep, rfl⟩ @[continuity] lemma continuous_quot_mk : continuous (@quot.mk α r) := continuous_coinduced_rng @[continuity] lemma continuous_quot_lift {f : α → β} (hr : ∀ a b, r a b → f a = f b) (h : continuous f) : continuous (quot.lift f hr : quot r → β) := continuous_coinduced_dom h lemma quotient_map_quotient_mk : quotient_map (@quotient.mk α s) := quotient_map_quot_mk lemma continuous_quotient_mk : continuous (@quotient.mk α s) := continuous_coinduced_rng lemma continuous_quotient_lift {f : α → β} (hs : ∀ a b, a ≈ b → f a = f b) (h : continuous f) : continuous (quotient.lift f hs : quotient s → β) := continuous_coinduced_dom h lemma continuous_quotient_lift_on' {f : α → β} (hs : ∀ a b, a ≈ b → f a = f b) (h : continuous f) : continuous (λ x, quotient.lift_on' x f hs : quotient s → β) := continuous_coinduced_dom h end quotient section pi variables {ι : Type*} {π : ι → Type*} @[continuity] lemma continuous_pi [topological_space α] [∀i, topological_space (π i)] {f : α → Πi:ι, π i} (h : ∀i, continuous (λa, f a i)) : continuous f := continuous_infi_rng $ assume i, continuous_induced_rng $ h i @[continuity] lemma continuous_apply [∀i, topological_space (π i)] (i : ι) : continuous (λp:Πi, π i, p i) := continuous_infi_dom continuous_induced_dom @[continuity] lemma continuous_apply_apply {κ : Type*} {ρ : κ → ι → Type*} [∀ j i, topological_space (ρ j i)] (j : κ) (i : ι) : continuous (λ p : (Π j, Π i, ρ j i), p j i) := (continuous_apply i).comp (continuous_apply j) lemma continuous_at_apply [∀i, topological_space (π i)] (i : ι) (x : Π i, π i) : continuous_at (λ p : Π i, π i, p i) x := (continuous_apply i).continuous_at lemma filter.tendsto.apply [∀i, topological_space (π i)] {l : filter α} {f : α → Π i, π i} {x : Π i, π i} (h : tendsto f l (𝓝 x)) (i : ι) : tendsto (λ a, f a i) l (𝓝 $ x i) := (continuous_at_apply i _).tendsto.comp h lemma continuous_pi_iff [topological_space α] [∀ i, topological_space (π i)] {f : α → Π i, π i} : continuous f ↔ ∀ i, continuous (λ y, f y i) := iff.intro (λ h i, (continuous_apply i).comp h) continuous_pi lemma nhds_pi [t : ∀i, topological_space (π i)] {a : Πi, π i} : 𝓝 a = pi (λ i, 𝓝 (a i)) := calc 𝓝 a = (⨅i, @nhds _ (@topological_space.induced _ _ (λx:Πi, π i, x i) (t i)) a) : nhds_infi ... = (⨅i, comap (λx, x i) (𝓝 (a i))) : by simp [nhds_induced] lemma tendsto_pi_nhds [t : ∀i, topological_space (π i)] {f : α → Πi, π i} {g : Πi, π i} {u : filter α} : tendsto f u (𝓝 g) ↔ ∀ x, tendsto (λ i, f i x) u (𝓝 (g x)) := by rw [nhds_pi, filter.tendsto_pi] lemma continuous_at_pi [∀ i, topological_space (π i)] [topological_space α] {f : α → Π i, π i} {x : α} : continuous_at f x ↔ ∀ i, continuous_at (λ y, f y i) x := tendsto_pi_nhds lemma filter.tendsto.update [∀i, topological_space (π i)] [decidable_eq ι] {l : filter α} {f : α → Π i, π i} {x : Π i, π i} (hf : tendsto f l (𝓝 x)) (i : ι) {g : α → π i} {xi : π i} (hg : tendsto g l (𝓝 xi)) : tendsto (λ a, function.update (f a) i (g a)) l (𝓝 $ function.update x i xi) := tendsto_pi_nhds.2 $ λ j, by { rcases em (j = i) with rfl|hj; simp [*, hf.apply] } lemma continuous_at.update [∀i, topological_space (π i)] [topological_space α] [decidable_eq ι] {f : α → Π i, π i} {a : α} (hf : continuous_at f a) (i : ι) {g : α → π i} (hg : continuous_at g a) : continuous_at (λ a, function.update (f a) i (g a)) a := hf.update i hg lemma continuous.update [∀i, topological_space (π i)] [topological_space α] [decidable_eq ι] {f : α → Π i, π i} (hf : continuous f) (i : ι) {g : α → π i} (hg : continuous g) : continuous (λ a, function.update (f a) i (g a)) := continuous_iff_continuous_at.2 $ λ x, hf.continuous_at.update i hg.continuous_at /-- `function.update f i x` is continuous in `(f, x)`. -/ @[continuity] lemma continuous_update [∀i, topological_space (π i)] [decidable_eq ι] (i : ι) : continuous (λ f : (Π j, π j) × π i, function.update f.1 i f.2) := continuous_fst.update i continuous_snd lemma filter.tendsto.fin_insert_nth {n} {π : fin (n + 1) → Type*} [Π i, topological_space (π i)] (i : fin (n + 1)) {f : α → π i} {l : filter α} {x : π i} (hf : tendsto f l (𝓝 x)) {g : α → Π j : fin n, π (i.succ_above j)} {y : Π j, π (i.succ_above j)} (hg : tendsto g l (𝓝 y)) : tendsto (λ a, i.insert_nth (f a) (g a)) l (𝓝 $ i.insert_nth x y) := tendsto_pi_nhds.2 (λ j, fin.succ_above_cases i (by simpa) (by simpa using tendsto_pi_nhds.1 hg) j) lemma continuous_at.fin_insert_nth {n} {π : fin (n + 1) → Type*} [Π i, topological_space (π i)] [topological_space α] (i : fin (n + 1)) {f : α → π i} {a : α} (hf : continuous_at f a) {g : α → Π j : fin n, π (i.succ_above j)} (hg : continuous_at g a) : continuous_at (λ a, i.insert_nth (f a) (g a)) a := hf.fin_insert_nth i hg lemma continuous.fin_insert_nth {n} {π : fin (n + 1) → Type*} [Π i, topological_space (π i)] [topological_space α] (i : fin (n + 1)) {f : α → π i} (hf : continuous f) {g : α → Π j : fin n, π (i.succ_above j)} (hg : continuous g) : continuous (λ a, i.insert_nth (f a) (g a)) := continuous_iff_continuous_at.2 $ λ a, hf.continuous_at.fin_insert_nth i hg.continuous_at lemma is_open_set_pi [∀a, topological_space (π a)] {i : set ι} {s : Πa, set (π a)} (hi : i.finite) (hs : ∀a∈i, is_open (s a)) : is_open (pi i s) := by rw [pi_def]; exact (is_open_bInter hi $ assume a ha, (hs _ ha).preimage (continuous_apply _)) lemma is_closed_set_pi [∀a, topological_space (π a)] {i : set ι} {s : Πa, set (π a)} (hs : ∀a∈i, is_closed (s a)) : is_closed (pi i s) := by rw [pi_def]; exact (is_closed_Inter $ λ a, is_closed_Inter $ λ ha, (hs _ ha).preimage (continuous_apply _)) lemma mem_nhds_of_pi_mem_nhds {ι : Type*} {α : ι → Type*} [Π (i : ι), topological_space (α i)] {I : set ι} {s : Π i, set (α i)} (a : Π i, α i) (hs : I.pi s ∈ 𝓝 a) {i : ι} (hi : i ∈ I) : s i ∈ 𝓝 (a i) := by { rw nhds_pi at hs, exact mem_of_pi_mem_pi hs hi } lemma set_pi_mem_nhds [Π a, topological_space (π a)] {i : set ι} {s : Π a, set (π a)} {x : Π a, π a} (hi : i.finite) (hs : ∀ a ∈ i, s a ∈ 𝓝 (x a)) : pi i s ∈ 𝓝 x := by { rw [pi_def, bInter_mem hi], exact λ a ha, (continuous_apply a).continuous_at (hs a ha) } lemma set_pi_mem_nhds_iff {α : ι → Type*} [Π (i : ι), topological_space (α i)] {I : set ι} (hI : I.finite) {s : Π i, set (α i)} (a : Π i, α i) : I.pi s ∈ 𝓝 a ↔ ∀ (i : ι), i ∈ I → s i ∈ 𝓝 (a i) := by { rw [nhds_pi, pi_mem_pi_iff hI], apply_instance } lemma interior_pi_set {α : ι → Type*} [Π i, topological_space (α i)] {I : set ι} (hI : I.finite) {s : Π i, set (α i)} : interior (pi I s) = I.pi (λ i, interior (s i)) := by { ext a, simp only [set.mem_pi, mem_interior_iff_mem_nhds, set_pi_mem_nhds_iff hI] } lemma exists_finset_piecewise_mem_of_mem_nhds [decidable_eq ι] [Π i, topological_space (π i)] {s : set (Π a, π a)} {x : Π a, π a} (hs : s ∈ 𝓝 x) (y : Π a, π a) : ∃ I : finset ι, I.piecewise x y ∈ s := begin simp only [nhds_pi, filter.mem_pi'] at hs, rcases hs with ⟨I, t, htx, hts⟩, refine ⟨I, hts $ λ i hi, _⟩, simpa [finset.mem_coe.1 hi] using mem_of_mem_nhds (htx i) end lemma pi_eq_generate_from [∀a, topological_space (π a)] : Pi.topological_space = generate_from {g | ∃(s:Πa, set (π a)) (i : finset ι), (∀a∈i, is_open (s a)) ∧ g = pi ↑i s} := le_antisymm (le_generate_from $ assume g ⟨s, i, hi, eq⟩, eq.symm ▸ is_open_set_pi (finset.finite_to_set _) hi) (le_infi $ assume a s ⟨t, ht, s_eq⟩, generate_open.basic _ $ ⟨function.update (λa, univ) a t, {a}, by simpa using ht, s_eq ▸ by ext f; simp [set.pi]⟩) lemma pi_generate_from_eq {g : Πa, set (set (π a))} : @Pi.topological_space ι π (λa, generate_from (g a)) = generate_from {t | ∃(s:Πa, set (π a)) (i : finset ι), (∀a∈i, s a ∈ g a) ∧ t = pi ↑i s} := let G := {t | ∃(s:Πa, set (π a)) (i : finset ι), (∀a∈i, s a ∈ g a) ∧ t = pi ↑i s} in begin rw [pi_eq_generate_from], refine le_antisymm (generate_from_mono _) (le_generate_from _), exact assume s ⟨t, i, ht, eq⟩, ⟨t, i, assume a ha, generate_open.basic _ (ht a ha), eq⟩, { rintros s ⟨t, i, hi, rfl⟩, rw [pi_def], apply is_open_bInter (finset.finite_to_set _), assume a ha, show ((generate_from G).coinduced (λf:Πa, π a, f a)).is_open (t a), refine le_generate_from _ _ (hi a ha), exact assume s hs, generate_open.basic _ ⟨function.update (λa, univ) a s, {a}, by simp [hs]⟩ } end lemma pi_generate_from_eq_fintype {g : Πa, set (set (π a))} [fintype ι] (hg : ∀a, ⋃₀ g a = univ) : @Pi.topological_space ι π (λa, generate_from (g a)) = generate_from {t | ∃(s:Πa, set (π a)), (∀a, s a ∈ g a) ∧ t = pi univ s} := begin rw [pi_generate_from_eq], refine le_antisymm (generate_from_mono _) (le_generate_from _), exact assume s ⟨t, ht, eq⟩, ⟨t, finset.univ, by simp [ht, eq]⟩, { rintros s ⟨t, i, ht, rfl⟩, apply is_open_iff_forall_mem_open.2 _, assume f hf, choose c hc using show ∀a, ∃s, s ∈ g a ∧ f a ∈ s, { assume a, have : f a ∈ ⋃₀ g a, { rw [hg], apply mem_univ }, simpa }, refine ⟨pi univ (λa, if a ∈ i then t a else (c : Πa, set (π a)) a), _, _, _⟩, { simp [pi_if] }, { refine generate_open.basic _ ⟨_, assume a, _, rfl⟩, by_cases a ∈ i; simp [*, set.pi] at * }, { have : f ∈ pi {a | a ∉ i} c, { simp [*, set.pi] at * }, simpa [pi_if, hf] } } end /-- Suppose `π i` is a family of topological spaces indexed by `i : ι`, and `X` is a type endowed with a family of maps `f i : X → π i` for every `i : ι`, hence inducing a map `g : X → Π i, π i`. This lemma shows that infimum of the topologies on `X` induced by the `f i` as `i : ι` varies is simply the topology on `X` induced by `g : X → Π i, π i` where `Π i, π i` is endowed with the usual product topology. -/ lemma inducing_infi_to_pi {X : Type*} [∀ i, topological_space (π i)] (f : Π i, X → π i) : @inducing X (Π i, π i) (⨅ i, induced (f i) infer_instance) _ (λ x i, f i x) := begin constructor, erw induced_infi, congr' 1, funext, erw induced_compose, end variables [fintype ι] [∀ i, topological_space (π i)] [∀ i, discrete_topology (π i)] /-- A finite product of discrete spaces is discrete. -/ instance Pi.discrete_topology : discrete_topology (Π i, π i) := singletons_open_iff_discrete.mp (λ x, begin rw show {x} = ⋂ i, {y : Π i, π i | y i = x i}, { ext, simp only [function.funext_iff, set.mem_singleton_iff, set.mem_Inter, set.mem_set_of_eq] }, exact is_open_Inter (λ i, (continuous_apply i).is_open_preimage {x i} (is_open_discrete {x i})) end) end pi section sigma variables {ι : Type*} {σ : ι → Type*} [Π i, topological_space (σ i)] @[continuity] lemma continuous_sigma_mk {i : ι} : continuous (@sigma.mk ι σ i) := continuous_supr_rng continuous_coinduced_rng lemma is_open_sigma_iff {s : set (sigma σ)} : is_open s ↔ ∀ i, is_open (sigma.mk i ⁻¹' s) := by simp only [is_open_supr_iff, is_open_coinduced] lemma is_closed_sigma_iff {s : set (sigma σ)} : is_closed s ↔ ∀ i, is_closed (sigma.mk i ⁻¹' s) := by simp only [← is_open_compl_iff, is_open_sigma_iff, preimage_compl] lemma is_open_map_sigma_mk {i : ι} : is_open_map (@sigma.mk ι σ i) := begin intros s hs, rw is_open_sigma_iff, intro j, rcases eq_or_ne i j with (rfl|hne), { rwa set.preimage_image_eq _ sigma_mk_injective }, { convert is_open_empty, apply set.eq_empty_of_subset_empty, rintro x ⟨y, _, hy⟩, have : i = j, by cc, contradiction } end lemma is_open_range_sigma_mk {i : ι} : is_open (set.range (@sigma.mk ι σ i)) := is_open_map_sigma_mk.is_open_range lemma is_closed_map_sigma_mk {i : ι} : is_closed_map (@sigma.mk ι σ i) := begin intros s hs, rw is_closed_sigma_iff, intro j, rcases eq_or_ne i j with (rfl|hne), { rwa set.preimage_image_eq _ sigma_mk_injective }, { convert is_closed_empty, apply set.eq_empty_of_subset_empty, rintro x ⟨y, _, hy⟩, have : i = j, by cc, contradiction } end lemma is_closed_sigma_mk {i : ι} : is_closed (set.range (@sigma.mk ι σ i)) := by { rw ←set.image_univ, exact is_closed_map_sigma_mk _ is_closed_univ } lemma open_embedding_sigma_mk {i : ι} : open_embedding (@sigma.mk ι σ i) := open_embedding_of_continuous_injective_open continuous_sigma_mk sigma_mk_injective is_open_map_sigma_mk lemma closed_embedding_sigma_mk {i : ι} : closed_embedding (@sigma.mk ι σ i) := closed_embedding_of_continuous_injective_closed continuous_sigma_mk sigma_mk_injective is_closed_map_sigma_mk lemma embedding_sigma_mk {i : ι} : embedding (@sigma.mk ι σ i) := closed_embedding_sigma_mk.1 lemma is_open_sigma_fst_preimage (s : set ι) : is_open (sigma.fst ⁻¹' s : set (Σ a, σ a)) := begin rw [← bUnion_of_singleton s, preimage_Union₂], simp only [← range_sigma_mk], exact is_open_bUnion (λ _ _, is_open_range_sigma_mk) end /-- A map out of a sum type is continuous if its restriction to each summand is. -/ @[continuity] lemma continuous_sigma [topological_space β] {f : sigma σ → β} (h : ∀ i, continuous (λ a, f ⟨i, a⟩)) : continuous f := continuous_supr_dom (λ i, continuous_coinduced_dom (h i)) @[continuity] lemma continuous_sigma_map {κ : Type*} {τ : κ → Type*} [Π k, topological_space (τ k)] {f₁ : ι → κ} {f₂ : Π i, σ i → τ (f₁ i)} (hf : ∀ i, continuous (f₂ i)) : continuous (sigma.map f₁ f₂) := continuous_sigma $ λ i, show continuous (λ a, sigma.mk (f₁ i) (f₂ i a)), from continuous_sigma_mk.comp (hf i) lemma is_open_map_sigma [topological_space β] {f : sigma σ → β} (h : ∀ i, is_open_map (λ a, f ⟨i, a⟩)) : is_open_map f := begin intros s hs, rw is_open_sigma_iff at hs, rw [← Union_image_preimage_sigma_mk_eq_self s, image_Union], apply is_open_Union, intro i, rw [image_image], exact h i _ (hs i) end /-- The sum of embeddings is an embedding. -/ lemma embedding_sigma_map {τ : ι → Type*} [Π i, topological_space (τ i)] {f : Π i, σ i → τ i} (hf : ∀ i, embedding (f i)) : embedding (sigma.map id f) := begin refine ⟨⟨_⟩, function.injective_id.sigma_map (λ i, (hf i).inj)⟩, refine le_antisymm (continuous_iff_le_induced.mp (continuous_sigma_map (λ i, (hf i).continuous))) _, intros s hs, replace hs := is_open_sigma_iff.mp hs, have : ∀ i, ∃ t, is_open t ∧ f i ⁻¹' t = sigma.mk i ⁻¹' s, { intro i, apply is_open_induced_iff.mp, convert hs i, exact (hf i).induced.symm }, choose t ht using this, apply is_open_induced_iff.mpr, refine ⟨⋃ i, sigma.mk i '' t i, is_open_Union (λ i, is_open_map_sigma_mk _ (ht i).1), _⟩, ext ⟨i, x⟩, change (sigma.mk i (f i x) ∈ ⋃ (i : ι), sigma.mk i '' t i) ↔ x ∈ sigma.mk i ⁻¹' s, rw [←(ht i).2, mem_Union], split, { rintro ⟨j, hj⟩, rw mem_image at hj, rcases hj with ⟨y, hy₁, hy₂⟩, rcases sigma.mk.inj_iff.mp hy₂ with ⟨rfl, hy⟩, replace hy := eq_of_heq hy, subst y, exact hy₁ }, { intro hx, use i, rw mem_image, exact ⟨f i x, hx, rfl⟩ } end end sigma section ulift @[continuity] lemma continuous_ulift_down [topological_space α] : continuous (ulift.down : ulift.{v u} α → α) := continuous_induced_dom @[continuity] lemma continuous_ulift_up [topological_space α] : continuous (ulift.up : α → ulift.{v u} α) := continuous_induced_rng continuous_id end ulift lemma mem_closure_of_continuous [topological_space α] [topological_space β] {f : α → β} {a : α} {s : set α} {t : set β} (hf : continuous f) (ha : a ∈ closure s) (h : maps_to f s (closure t)) : f a ∈ closure t := calc f a ∈ f '' closure s : mem_image_of_mem _ ha ... ⊆ closure (f '' s) : image_closure_subset_closure_image hf ... ⊆ closure t : closure_minimal h.image_subset is_closed_closure lemma mem_closure_of_continuous2 [topological_space α] [topological_space β] [topological_space γ] {f : α → β → γ} {a : α} {b : β} {s : set α} {t : set β} {u : set γ} (hf : continuous (λp:α×β, f p.1 p.2)) (ha : a ∈ closure s) (hb : b ∈ closure t) (h : ∀a∈s, ∀b∈t, f a b ∈ closure u) : f a b ∈ closure u := have (a,b) ∈ closure (s ×ˢ t), by simp [closure_prod_eq, ha, hb], show f (a, b).1 (a, b).2 ∈ closure u, from @mem_closure_of_continuous (α×β) _ _ _ (λp:α×β, f p.1 p.2) (a,b) _ u hf this $ assume ⟨p₁, p₂⟩ ⟨h₁, h₂⟩, h p₁ h₁ p₂ h₂
fb896d43530acf8a35f8b7d75b8cb9af43d7eb8d
4727251e0cd73359b15b664c3170e5d754078599
/src/category_theory/limits/shapes/normal_mono/basic.lean
8d9883af5c44bdd07bd94682f3e6732171ce6115
[ "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
10,606
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.regular_mono import category_theory.limits.shapes.kernels import category_theory.limits.preserves.basic /-! # Definitions and basic properties of normal monomorphisms and epimorphisms. A normal monomorphism is a morphism that is the kernel of some other morphism. We give the construction `normal_mono → regular_mono` (`category_theory.normal_mono.regular_mono`) as well as the dual construction for normal epimorphisms. We show equivalences reflect normal monomorphisms (`category_theory.equivalence_reflects_normal_mono`), and that the pullback of a normal monomorphism is normal (`category_theory.normal_of_is_pullback_snd_of_normal`). We also define classes `normal_mono_category` and `normal_epi_category` for classes in which every monomorphism or epimorphism is normal, and deduce that these categories are `regular_mono_category`s resp. `regular_epi_category`s. -/ noncomputable theory namespace category_theory open category_theory.limits universes v₁ u₁ u₂ variables {C : Type u₁} [category.{v₁} C] variables {X Y : C} section variables [has_zero_morphisms C] /-- A normal monomorphism is a morphism which is the kernel of some morphism. -/ class normal_mono (f : X ⟶ Y) := (Z : C) (g : Y ⟶ Z) (w : f ≫ g = 0) (is_limit : is_limit (kernel_fork.of_ι f w)) section local attribute [instance] fully_faithful_reflects_limits local attribute [instance] equivalence.ess_surj_of_equivalence /-- If `F` is an equivalence and `F.map f` is a normal mono, then `f` is a normal mono. -/ def equivalence_reflects_normal_mono {D : Type u₂} [category.{v₁} D] [has_zero_morphisms D] (F : C ⥤ D) [is_equivalence F] {X Y : C} {f : X ⟶ Y} (hf : normal_mono (F.map f)) : normal_mono f := { Z := F.obj_preimage hf.Z, g := full.preimage (hf.g ≫ (F.obj_obj_preimage_iso hf.Z).inv), w := faithful.map_injective F $ by simp [reassoc_of hf.w], is_limit := reflects_limit.reflects $ is_limit.of_cone_equiv (cones.postcompose_equivalence (comp_nat_iso F : _)) $ is_limit.of_iso_limit (by exact is_limit.of_iso_limit (is_kernel.of_comp_iso _ _ (F.obj_obj_preimage_iso hf.Z) (by simp) hf.is_limit) (of_ι_congr (category.comp_id _).symm)) (iso_of_ι _).symm } end /-- Every normal monomorphism is a regular monomorphism. -/ @[priority 100] instance normal_mono.regular_mono (f : X ⟶ Y) [I : normal_mono f] : regular_mono f := { left := I.g, right := 0, w := (by simpa using I.w), ..I } /-- If `f` is a normal mono, then any map `k : W ⟶ Y` such that `k ≫ normal_mono.g = 0` induces a morphism `l : W ⟶ X` such that `l ≫ f = k`. -/ def normal_mono.lift' {W : C} (f : X ⟶ Y) [normal_mono f] (k : W ⟶ Y) (h : k ≫ normal_mono.g = 0) : {l : W ⟶ X // l ≫ f = k} := kernel_fork.is_limit.lift' normal_mono.is_limit _ h /-- The second leg of a pullback cone is a normal monomorphism if the right component is too. See also `pullback.snd_of_mono` for the basic monomorphism version, and `normal_of_is_pullback_fst_of_normal` for the flipped version. -/ def normal_of_is_pullback_snd_of_normal {P Q R S : C} {f : P ⟶ Q} {g : P ⟶ R} {h : Q ⟶ S} {k : R ⟶ S} [hn : normal_mono h] (comm : f ≫ h = g ≫ k) (t : is_limit (pullback_cone.mk _ _ comm)) : normal_mono g := { Z := hn.Z, g := k ≫ hn.g, w := by rw [← reassoc_of comm, hn.w, has_zero_morphisms.comp_zero], is_limit := begin letI gr := regular_of_is_pullback_snd_of_regular comm t, have q := (has_zero_morphisms.comp_zero k hn.Z).symm, convert gr.is_limit, dunfold kernel_fork.of_ι fork.of_ι, congr, exact q, exact q, exact q, apply proof_irrel_heq, end } /-- The first leg of a pullback cone is a normal monomorphism if the left component is too. See also `pullback.fst_of_mono` for the basic monomorphism version, and `normal_of_is_pullback_snd_of_normal` for the flipped version. -/ def normal_of_is_pullback_fst_of_normal {P Q R S : C} {f : P ⟶ Q} {g : P ⟶ R} {h : Q ⟶ S} {k : R ⟶ S} [hn : normal_mono k] (comm : f ≫ h = g ≫ k) (t : is_limit (pullback_cone.mk _ _ comm)) : normal_mono f := normal_of_is_pullback_snd_of_normal comm.symm (pullback_cone.flip_is_limit t) section variables (C) /-- A normal mono category is a category in which every monomorphism is normal. -/ class normal_mono_category := (normal_mono_of_mono : ∀ {X Y : C} (f : X ⟶ Y) [mono f], normal_mono f) end /-- In a category in which every monomorphism is normal, we can express every monomorphism as a kernel. This is not an instance because it would create an instance loop. -/ def normal_mono_of_mono [normal_mono_category C] (f : X ⟶ Y) [mono f] : normal_mono f := normal_mono_category.normal_mono_of_mono _ @[priority 100] instance regular_mono_category_of_normal_mono_category [normal_mono_category C] : regular_mono_category C := { regular_mono_of_mono := λ _ _ f _, by { haveI := by exactI normal_mono_of_mono f, apply_instance } } end section variables [has_zero_morphisms C] /-- A normal epimorphism is a morphism which is the cokernel of some morphism. -/ class normal_epi (f : X ⟶ Y) := (W : C) (g : W ⟶ X) (w : g ≫ f = 0) (is_colimit : is_colimit (cokernel_cofork.of_π f w)) section local attribute [instance] fully_faithful_reflects_colimits local attribute [instance] equivalence.ess_surj_of_equivalence /-- If `F` is an equivalence and `F.map f` is a normal epi, then `f` is a normal epi. -/ def equivalence_reflects_normal_epi {D : Type u₂} [category.{v₁} D] [has_zero_morphisms D] (F : C ⥤ D) [is_equivalence F] {X Y : C} {f : X ⟶ Y} (hf : normal_epi (F.map f)) : normal_epi f := { W := F.obj_preimage hf.W, g := full.preimage ((F.obj_obj_preimage_iso hf.W).hom ≫ hf.g), w := faithful.map_injective F $ by simp [hf.w], is_colimit := reflects_colimit.reflects $ is_colimit.of_cocone_equiv (cocones.precompose_equivalence (comp_nat_iso F).symm) $ is_colimit.of_iso_colimit (by exact is_colimit.of_iso_colimit (is_cokernel.of_iso_comp _ _ (F.obj_obj_preimage_iso hf.W).symm (by simp) hf.is_colimit) (of_π_congr (category.id_comp _).symm)) (iso_of_π _).symm } end /-- Every normal epimorphism is a regular epimorphism. -/ @[priority 100] instance normal_epi.regular_epi (f : X ⟶ Y) [I : normal_epi f] : regular_epi f := { left := I.g, right := 0, w := (by simpa using I.w), ..I } /-- If `f` is a normal epi, then every morphism `k : X ⟶ W` satisfying `normal_epi.g ≫ k = 0` induces `l : Y ⟶ W` such that `f ≫ l = k`. -/ def normal_epi.desc' {W : C} (f : X ⟶ Y) [normal_epi f] (k : X ⟶ W) (h : normal_epi.g ≫ k = 0) : {l : Y ⟶ W // f ≫ l = k} := cokernel_cofork.is_colimit.desc' (normal_epi.is_colimit) _ h /-- The second leg of a pushout cocone is a normal epimorphism if the right component is too. See also `pushout.snd_of_epi` for the basic epimorphism version, and `normal_of_is_pushout_fst_of_normal` for the flipped version. -/ def normal_of_is_pushout_snd_of_normal {P Q R S : C} {f : P ⟶ Q} {g : P ⟶ R} {h : Q ⟶ S} {k : R ⟶ S} [gn : normal_epi g] (comm : f ≫ h = g ≫ k) (t : is_colimit (pushout_cocone.mk _ _ comm)) : normal_epi h := { W := gn.W, g := gn.g ≫ f, w := by rw [category.assoc, comm, reassoc_of gn.w, zero_comp], is_colimit := begin letI hn := regular_of_is_pushout_snd_of_regular comm t, have q := (@zero_comp _ _ _ gn.W _ _ f).symm, convert hn.is_colimit, dunfold cokernel_cofork.of_π cofork.of_π, congr, exact q, exact q, exact q, apply proof_irrel_heq, end } /-- The first leg of a pushout cocone is a normal epimorphism if the left component is too. See also `pushout.fst_of_epi` for the basic epimorphism version, and `normal_of_is_pushout_snd_of_normal` for the flipped version. -/ def normal_of_is_pushout_fst_of_normal {P Q R S : C} {f : P ⟶ Q} {g : P ⟶ R} {h : Q ⟶ S} {k : R ⟶ S} [hn : normal_epi f] (comm : f ≫ h = g ≫ k) (t : is_colimit (pushout_cocone.mk _ _ comm)) : normal_epi k := normal_of_is_pushout_snd_of_normal comm.symm (pushout_cocone.flip_is_colimit t) end open opposite variables [has_zero_morphisms C] /-- A normal mono becomes a normal epi in the opposite category. -/ def normal_epi_of_normal_mono_unop {X Y : Cᵒᵖ} (f : X ⟶ Y) (m : normal_mono f.unop) : normal_epi f := { W := op m.Z, g := m.g.op, w := congr_arg quiver.hom.op m.w, is_colimit := is_colimit.of_π _ _ (λ Z' g' w', (kernel_fork.is_limit.lift' m.is_limit g'.unop (congr_arg quiver.hom.unop w')).1.op) (λ Z' g' w', congr_arg quiver.hom.op (kernel_fork.is_limit.lift' m.is_limit g'.unop (congr_arg quiver.hom.unop w')).2) begin rintros Z' g' w' m' rfl, apply quiver.hom.unop_inj, apply m.is_limit.uniq (kernel_fork.of_ι (m'.unop ≫ f.unop) _) m'.unop, rintro (⟨⟩|⟨⟩); simp, end, } /-- A normal epi becomes a normal mono in the opposite category. -/ def normal_mono_of_normal_epi_unop {X Y : Cᵒᵖ} (f : X ⟶ Y) (m : normal_epi f.unop) : normal_mono f := { Z := op m.W, g := m.g.op, w := congr_arg quiver.hom.op m.w, is_limit := is_limit.of_ι _ _ (λ Z' g' w', (cokernel_cofork.is_colimit.desc' m.is_colimit g'.unop (congr_arg quiver.hom.unop w')).1.op) (λ Z' g' w', congr_arg quiver.hom.op (cokernel_cofork.is_colimit.desc' m.is_colimit g'.unop (congr_arg quiver.hom.unop w')).2) begin rintros Z' g' w' m' rfl, apply quiver.hom.unop_inj, apply m.is_colimit.uniq (cokernel_cofork.of_π (f.unop ≫ m'.unop) _) m'.unop, rintro (⟨⟩|⟨⟩); simp, end, } section variables (C) /-- A normal epi category is a category in which every epimorphism is normal. -/ class normal_epi_category := (normal_epi_of_epi : ∀ {X Y : C} (f : X ⟶ Y) [epi f], normal_epi f) end /-- In a category in which every epimorphism is normal, we can express every epimorphism as a kernel. This is not an instance because it would create an instance loop. -/ def normal_epi_of_epi [normal_epi_category C] (f : X ⟶ Y) [epi f] : normal_epi f := normal_epi_category.normal_epi_of_epi _ @[priority 100] instance regular_epi_category_of_normal_epi_category [normal_epi_category C] : regular_epi_category C := { regular_epi_of_epi := λ _ _ f _, by { haveI := by exactI normal_epi_of_epi f, apply_instance } } end category_theory
ed7bffd3d5a07b955ffed36a8b0351d5b0cf2df6
e00ea76a720126cf9f6d732ad6216b5b824d20a7
/src/algebra/archimedean.lean
3f202592b34d388a34dba91b15b1b80234d03731
[ "Apache-2.0" ]
permissive
vaibhavkarve/mathlib
a574aaf68c0a431a47fa82ce0637f0f769826bfe
17f8340912468f49bdc30acdb9a9fa02eeb0473a
refs/heads/master
1,621,263,802,637
1,585,399,588,000
1,585,399,588,000
250,833,447
0
0
Apache-2.0
1,585,410,341,000
1,585,410,341,000
null
UTF-8
Lean
false
false
10,109
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.group_power algebra.field_power algebra.floor import data.rat tactic.linarith variables {α : Type*} open_locale add_monoid class archimedean (α) [ordered_comm_monoid α] : Prop := (arch : ∀ (x : α) {y}, 0 < y → ∃ n : ℕ, x ≤ n • y) 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 ← add_monoid.smul_one) (nat.cast_lt.2 (nat.lt_succ_self _))⟩ section linear_ordered_ring variables [linear_ordered_ring α] [archimedean α] lemma pow_unbounded_of_one_lt (x : α) {y : α} (hy1 : 1 < y) : ∃ n : ℕ, x < y ^ n := have hy0 : 0 < y - 1 := sub_pos_of_lt hy1, -- TODO `by linarith` fails to prove hy1' have hy1' : (-1:α) ≤ y, from le_trans (neg_le_self zero_le_one) (le_of_lt hy1), let ⟨n, h⟩ := archimedean.arch x hy0 in ⟨n, calc x ≤ n • (y - 1) : h ... < 1 + n • (y - 1) : lt_one_add _ ... ≤ y ^ n : one_add_sub_mul_le_pow hy1' n⟩ /-- Every x greater than 1 is between two successive natural-number powers of another 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_lt_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 [discrete_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)), one_div_eq_inv]; 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' [discrete_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 (discrete_linear_ordered_field.zero_lt_one α) hy, ⟨-(m+1), by rwa [fpow_neg, one_div_eq_inv, inv_lt (fpow_pos_of_pos hyp _) hx], by rwa [neg_add, neg_add_cancel_right, fpow_neg, one_div_eq_inv, 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.smul_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 [add_monoid.smul_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)⟩⟩ 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, ← add_monoid.smul_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_eq_inv], { 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 archimedean_iff_nat_lt.1 (by apply_instance) (1/ε) with n hn, existsi n, apply div_lt_of_mul_lt_of_pos, { simp, apply add_pos_of_nonneg_of_pos, apply nat.cast_nonneg, apply zero_lt_one }, { apply (div_lt_iff' hε).1, transitivity, { exact hn }, { simp [zero_lt_one] }} 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 [discrete_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
ac9af2775fdbf7897b5aac4f662522ba1fd2f9fd
bbecf0f1968d1fba4124103e4f6b55251d08e9c4
/src/number_theory/padics/padic_integers.lean
bc01f1cb73a1a5d0884b2b37c56dbe457e037a8c
[ "Apache-2.0" ]
permissive
waynemunro/mathlib
e3fd4ff49f4cb43d4a8ded59d17be407bc5ee552
065a70810b5480d584033f7bbf8e0409480c2118
refs/heads/master
1,693,417,182,397
1,634,644,781,000
1,634,644,781,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
20,816
lean
/- Copyright (c) 2018 Robert Y. Lewis. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Robert Y. Lewis, Mario Carneiro, Johan Commelin -/ import data.int.modeq import data.zmod.basic import number_theory.padics.padic_numbers import ring_theory.discrete_valuation_ring import topology.metric_space.cau_seq_filter /-! # p-adic integers This file defines the p-adic integers `ℤ_p` as the subtype of `ℚ_p` with norm `≤ 1`. We show that `ℤ_p` * is complete * is nonarchimedean * is a normed ring * is a local ring * is a discrete valuation ring The relation between `ℤ_[p]` and `zmod p` is established in another file. ## Important definitions * `padic_int` : the type of p-adic numbers ## Notation We introduce the notation `ℤ_[p]` for the p-adic integers. ## Implementation notes Much, but not all, of this file assumes that `p` is prime. This assumption is inferred automatically by taking `[fact (nat.prime p)] as a type class argument. Coercions into `ℤ_p` are set up to work with the `norm_cast` tactic. ## References * [F. Q. Gouêva, *p-adic numbers*][gouvea1997] * [R. Y. Lewis, *A formal proof of Hensel's lemma over the p-adic integers*][lewis2019] * <https://en.wikipedia.org/wiki/P-adic_number> ## Tags p-adic, p adic, padic, p-adic integer -/ open padic metric local_ring noncomputable theory open_locale classical /-- The p-adic integers ℤ_p are the p-adic numbers with norm ≤ 1. -/ def padic_int (p : ℕ) [fact p.prime] := {x : ℚ_[p] // ∥x∥ ≤ 1} notation `ℤ_[`p`]` := padic_int p namespace padic_int /-! ### Ring structure and coercion to `ℚ_[p]` -/ variables {p : ℕ} [fact p.prime] instance : has_coe ℤ_[p] ℚ_[p] := ⟨subtype.val⟩ lemma ext {x y : ℤ_[p]} : (x : ℚ_[p]) = y → x = y := subtype.ext_iff_val.2 /-- Addition on ℤ_p is inherited from ℚ_p. -/ instance : has_add ℤ_[p] := ⟨λ ⟨x, hx⟩ ⟨y, hy⟩, ⟨x+y, le_trans (padic_norm_e.nonarchimedean _ _) (max_le_iff.2 ⟨hx,hy⟩)⟩⟩ /-- Multiplication on ℤ_p is inherited from ℚ_p. -/ instance : has_mul ℤ_[p] := ⟨λ ⟨x, hx⟩ ⟨y, hy⟩, ⟨x*y, begin rw padic_norm_e.mul, apply mul_le_one; {assumption <|> apply norm_nonneg} end⟩⟩ /-- Negation on ℤ_p is inherited from ℚ_p. -/ instance : has_neg ℤ_[p] := ⟨λ ⟨x, hx⟩, ⟨-x, by simpa⟩⟩ /-- Subtraction on ℤ_p is inherited from ℚ_p. -/ instance : has_sub ℤ_[p] := ⟨λ ⟨x, hx⟩ ⟨y, hy⟩, ⟨x - y, by { rw sub_eq_add_neg, rw ← norm_neg at hy, exact le_trans (padic_norm_e.nonarchimedean _ _) (max_le_iff.2 ⟨hx, hy⟩) }⟩⟩ /-- Zero on ℤ_p is inherited from ℚ_p. -/ instance : has_zero ℤ_[p] := ⟨⟨0, by norm_num⟩⟩ instance : inhabited ℤ_[p] := ⟨0⟩ /-- One on ℤ_p is inherited from ℚ_p. -/ instance : has_one ℤ_[p] := ⟨⟨1, by norm_num⟩⟩ @[simp] lemma mk_zero {h} : (⟨0, h⟩ : ℤ_[p]) = (0 : ℤ_[p]) := rfl @[simp] lemma val_eq_coe (z : ℤ_[p]) : z.val = z := rfl @[simp, norm_cast] lemma coe_add : ∀ (z1 z2 : ℤ_[p]), ((z1 + z2 : ℤ_[p]) : ℚ_[p]) = z1 + z2 | ⟨_, _⟩ ⟨_, _⟩ := rfl @[simp, norm_cast] lemma coe_mul : ∀ (z1 z2 : ℤ_[p]), ((z1 * z2 : ℤ_[p]) : ℚ_[p]) = z1 * z2 | ⟨_, _⟩ ⟨_, _⟩ := rfl @[simp, norm_cast] lemma coe_neg : ∀ (z1 : ℤ_[p]), ((-z1 : ℤ_[p]) : ℚ_[p]) = -z1 | ⟨_, _⟩ := rfl @[simp, norm_cast] lemma coe_sub : ∀ (z1 z2 : ℤ_[p]), ((z1 - z2 : ℤ_[p]) : ℚ_[p]) = z1 - z2 | ⟨_, _⟩ ⟨_, _⟩ := rfl @[simp, norm_cast] lemma coe_one : ((1 : ℤ_[p]) : ℚ_[p]) = 1 := rfl @[simp, norm_cast] lemma coe_coe : ∀ n : ℕ, ((n : ℤ_[p]) : ℚ_[p]) = n | 0 := rfl | (k+1) := by simp [coe_coe] @[simp, norm_cast] lemma coe_coe_int : ∀ (z : ℤ), ((z : ℤ_[p]) : ℚ_[p]) = z | (int.of_nat n) := by simp | -[1+n] := by simp @[simp, norm_cast] lemma coe_zero : ((0 : ℤ_[p]) : ℚ_[p]) = 0 := rfl instance : ring ℤ_[p] := by refine_struct { add := (+), mul := (*), neg := has_neg.neg, zero := (0 : ℤ_[p]), one := 1, sub := has_sub.sub, npow := @npow_rec _ ⟨1⟩ ⟨(*)⟩, nsmul := @nsmul_rec _ ⟨0⟩ ⟨(+)⟩, gsmul := @gsmul_rec _ ⟨0⟩ ⟨(+)⟩ ⟨has_neg.neg⟩ }; intros; try { refl }; ext; simp; ring /-- The coercion from ℤ[p] to ℚ[p] as a ring homomorphism. -/ def coe.ring_hom : ℤ_[p] →+* ℚ_[p] := { to_fun := (coe : ℤ_[p] → ℚ_[p]), map_zero' := rfl, map_one' := rfl, map_mul' := coe_mul, map_add' := coe_add } @[simp, norm_cast] lemma coe_pow (x : ℤ_[p]) (n : ℕ) : (↑(x^n) : ℚ_[p]) = (↑x : ℚ_[p])^n := coe.ring_hom.map_pow x n @[simp] lemma mk_coe : ∀ (k : ℤ_[p]), (⟨k, k.2⟩ : ℤ_[p]) = k | ⟨_, _⟩ := rfl /-- The inverse of a p-adic integer with norm equal to 1 is also a p-adic integer. Otherwise, the inverse is defined to be 0. -/ def inv : ℤ_[p] → ℤ_[p] | ⟨k, _⟩ := if h : ∥k∥ = 1 then ⟨1/k, by simp [h]⟩ else 0 instance : char_zero ℤ_[p] := { cast_injective := λ m n h, nat.cast_injective $ show (m:ℚ_[p]) = n, by { rw subtype.ext_iff at h, norm_cast at h, exact h } } @[simp, norm_cast] lemma coe_int_eq (z1 z2 : ℤ) : (z1 : ℤ_[p]) = z2 ↔ z1 = z2 := suffices (z1 : ℚ_[p]) = z2 ↔ z1 = z2, from iff.trans (by norm_cast) this, by norm_cast /-- A sequence of integers that is Cauchy with respect to the `p`-adic norm converges to a `p`-adic integer. -/ def of_int_seq (seq : ℕ → ℤ) (h : is_cau_seq (padic_norm p) (λ n, seq n)) : ℤ_[p] := ⟨⟦⟨_, h⟩⟧, show ↑(padic_seq.norm _) ≤ (1 : ℝ), begin rw padic_seq.norm, split_ifs with hne; norm_cast, { exact zero_le_one }, { apply padic_norm.of_int } end ⟩ end padic_int namespace padic_int /-! ### Instances We now show that `ℤ_[p]` is a * complete metric space * normed ring * integral domain -/ variables (p : ℕ) [fact p.prime] instance : metric_space ℤ_[p] := subtype.metric_space instance complete_space : complete_space ℤ_[p] := have is_closed {x : ℚ_[p] | ∥x∥ ≤ 1}, from is_closed_le continuous_norm continuous_const, this.complete_space_coe instance : has_norm ℤ_[p] := ⟨λ z, ∥(z : ℚ_[p])∥⟩ variables {p} protected lemma mul_comm : ∀ z1 z2 : ℤ_[p], z1*z2 = z2*z1 | ⟨q1, h1⟩ ⟨q2, h2⟩ := show (⟨q1*q2, _⟩ : ℤ_[p]) = ⟨q2*q1, _⟩, by simp [_root_.mul_comm] protected lemma zero_ne_one : (0 : ℤ_[p]) ≠ 1 := show (⟨(0 : ℚ_[p]), _⟩ : ℤ_[p]) ≠ ⟨(1 : ℚ_[p]), _⟩, from mt subtype.ext_iff_val.1 zero_ne_one protected lemma eq_zero_or_eq_zero_of_mul_eq_zero : ∀ (a b : ℤ_[p]), a * b = 0 → a = 0 ∨ b = 0 | ⟨a, ha⟩ ⟨b, hb⟩ := λ h : (⟨a * b, _⟩ : ℤ_[p]) = ⟨0, _⟩, have a * b = 0, from subtype.ext_iff_val.1 h, (mul_eq_zero.1 this).elim (λ h1, or.inl (by simp [h1]; refl)) (λ h2, or.inr (by simp [h2]; refl)) lemma norm_def {z : ℤ_[p]} : ∥z∥ = ∥(z : ℚ_[p])∥ := rfl variables (p) instance : normed_comm_ring ℤ_[p] := { dist_eq := λ ⟨_, _⟩ ⟨_, _⟩, rfl, norm_mul := λ ⟨_, _⟩ ⟨_, _⟩, norm_mul_le _ _, mul_comm := padic_int.mul_comm } instance : norm_one_class ℤ_[p] := ⟨norm_def.trans norm_one⟩ instance is_absolute_value : is_absolute_value (λ z : ℤ_[p], ∥z∥) := { abv_nonneg := norm_nonneg, abv_eq_zero := λ ⟨_, _⟩, by simp [norm_eq_zero], abv_add := λ ⟨_,_⟩ ⟨_, _⟩, norm_add_le _ _, abv_mul := λ _ _, by simp only [norm_def, padic_norm_e.mul, padic_int.coe_mul]} variables {p} instance : integral_domain ℤ_[p] := { eq_zero_or_eq_zero_of_mul_eq_zero := λ x y, padic_int.eq_zero_or_eq_zero_of_mul_eq_zero x y, exists_pair_ne := ⟨0, 1, padic_int.zero_ne_one⟩, .. padic_int.normed_comm_ring p } end padic_int namespace padic_int /-! ### Norm -/ variables {p : ℕ} [fact p.prime] lemma norm_le_one : ∀ z : ℤ_[p], ∥z∥ ≤ 1 | ⟨_, h⟩ := h @[simp] lemma norm_mul (z1 z2 : ℤ_[p]) : ∥z1 * z2∥ = ∥z1∥ * ∥z2∥ := by simp [norm_def] @[simp] lemma norm_pow (z : ℤ_[p]) : ∀ n : ℕ, ∥z^n∥ = ∥z∥^n | 0 := by simp | (k+1) := by { rw [pow_succ, pow_succ, norm_mul], congr, apply norm_pow } theorem nonarchimedean : ∀ (q r : ℤ_[p]), ∥q + r∥ ≤ max (∥q∥) (∥r∥) | ⟨_, _⟩ ⟨_, _⟩ := padic_norm_e.nonarchimedean _ _ theorem norm_add_eq_max_of_ne : ∀ {q r : ℤ_[p]}, ∥q∥ ≠ ∥r∥ → ∥q+r∥ = max (∥q∥) (∥r∥) | ⟨_, _⟩ ⟨_, _⟩ := padic_norm_e.add_eq_max_of_ne lemma norm_eq_of_norm_add_lt_right {z1 z2 : ℤ_[p]} (h : ∥z1 + z2∥ < ∥z2∥) : ∥z1∥ = ∥z2∥ := by_contradiction $ λ hne, not_lt_of_ge (by rw norm_add_eq_max_of_ne hne; apply le_max_right) h lemma norm_eq_of_norm_add_lt_left {z1 z2 : ℤ_[p]} (h : ∥z1 + z2∥ < ∥z1∥) : ∥z1∥ = ∥z2∥ := by_contradiction $ λ hne, not_lt_of_ge (by rw norm_add_eq_max_of_ne hne; apply le_max_left) h @[simp] lemma padic_norm_e_of_padic_int (z : ℤ_[p]) : ∥(↑z : ℚ_[p])∥ = ∥z∥ := by simp [norm_def] lemma norm_int_cast_eq_padic_norm (z : ℤ) : ∥(z : ℤ_[p])∥ = ∥(z : ℚ_[p])∥ := by simp [norm_def] @[simp] lemma norm_eq_padic_norm {q : ℚ_[p]} (hq : ∥q∥ ≤ 1) : @norm ℤ_[p] _ ⟨q, hq⟩ = ∥q∥ := rfl @[simp] lemma norm_p : ∥(p : ℤ_[p])∥ = p⁻¹ := show ∥((p : ℤ_[p]) : ℚ_[p])∥ = p⁻¹, by exact_mod_cast padic_norm_e.norm_p @[simp] lemma norm_p_pow (n : ℕ) : ∥(p : ℤ_[p])^n∥ = p^(-n:ℤ) := show ∥((p^n : ℤ_[p]) : ℚ_[p])∥ = p^(-n:ℤ), by { convert padic_norm_e.norm_p_pow n, simp, } private def cau_seq_to_rat_cau_seq (f : cau_seq ℤ_[p] norm) : cau_seq ℚ_[p] (λ a, ∥a∥) := ⟨ λ n, f n, λ _ hε, by simpa [norm, norm_def] using f.cauchy hε ⟩ variables (p) instance complete : cau_seq.is_complete ℤ_[p] norm := ⟨ λ f, have hqn : ∥cau_seq.lim (cau_seq_to_rat_cau_seq f)∥ ≤ 1, from padic_norm_e_lim_le zero_lt_one (λ _, norm_le_one _), ⟨ ⟨_, hqn⟩, λ ε, by simpa [norm, norm_def] using cau_seq.equiv_lim (cau_seq_to_rat_cau_seq f) ε⟩⟩ end padic_int namespace padic_int variables (p : ℕ) [hp_prime : fact p.prime] include hp_prime lemma exists_pow_neg_lt {ε : ℝ} (hε : 0 < ε) : ∃ (k : ℕ), ↑p ^ -((k : ℕ) : ℤ) < ε := begin obtain ⟨k, hk⟩ := exists_nat_gt ε⁻¹, use k, rw ← inv_lt_inv hε (_root_.fpow_pos_of_pos _ _), { rw [fpow_neg, inv_inv₀, gpow_coe_nat], apply lt_of_lt_of_le hk, norm_cast, apply le_of_lt, convert nat.lt_pow_self _ _ using 1, exact hp_prime.1.one_lt }, { exact_mod_cast hp_prime.1.pos } end lemma exists_pow_neg_lt_rat {ε : ℚ} (hε : 0 < ε) : ∃ (k : ℕ), ↑p ^ -((k : ℕ) : ℤ) < ε := begin obtain ⟨k, hk⟩ := @exists_pow_neg_lt p _ ε (by exact_mod_cast hε), use k, rw (show (p : ℝ) = (p : ℚ), by simp) at hk, exact_mod_cast hk end variable {p} lemma norm_int_lt_one_iff_dvd (k : ℤ) : ∥(k : ℤ_[p])∥ < 1 ↔ ↑p ∣ k := suffices ∥(k : ℚ_[p])∥ < 1 ↔ ↑p ∣ k, by rwa norm_int_cast_eq_padic_norm, padic_norm_e.norm_int_lt_one_iff_dvd k lemma norm_int_le_pow_iff_dvd {k : ℤ} {n : ℕ} : ∥(k : ℤ_[p])∥ ≤ ((↑p)^(-n : ℤ)) ↔ ↑p^n ∣ k := suffices ∥(k : ℚ_[p])∥ ≤ ((↑p)^(-n : ℤ)) ↔ ↑(p^n) ∣ k, by simpa [norm_int_cast_eq_padic_norm], padic_norm_e.norm_int_le_pow_iff_dvd _ _ /-! ### Valuation on `ℤ_[p]` -/ /-- `padic_int.valuation` lifts the p-adic valuation on `ℚ` to `ℤ_[p]`. -/ def valuation (x : ℤ_[p]) := padic.valuation (x : ℚ_[p]) lemma norm_eq_pow_val {x : ℤ_[p]} (hx : x ≠ 0) : ∥x∥ = p^(-x.valuation) := begin convert padic.norm_eq_pow_val _, contrapose! hx, exact subtype.val_injective hx end @[simp] lemma valuation_zero : valuation (0 : ℤ_[p]) = 0 := padic.valuation_zero @[simp] lemma valuation_one : valuation (1 : ℤ_[p]) = 0 := padic.valuation_one @[simp] lemma valuation_p : valuation (p : ℤ_[p]) = 1 := by simp [valuation, -cast_eq_of_rat_of_nat] lemma valuation_nonneg (x : ℤ_[p]) : 0 ≤ x.valuation := begin by_cases hx : x = 0, { simp [hx] }, have h : (1 : ℝ) < p := by exact_mod_cast hp_prime.1.one_lt, rw [← neg_nonpos, ← (fpow_strict_mono h).le_iff_le], show (p : ℝ) ^ -valuation x ≤ p ^ 0, rw [← norm_eq_pow_val hx], simpa using x.property, end @[simp] lemma valuation_p_pow_mul (n : ℕ) (c : ℤ_[p]) (hc : c ≠ 0) : (↑p ^ n * c).valuation = n + c.valuation := begin have : ∥↑p ^ n * c∥ = ∥(p ^ n : ℤ_[p])∥ * ∥c∥, { exact norm_mul _ _ }, have aux : ↑p ^ n * c ≠ 0, { contrapose! hc, rw mul_eq_zero at hc, cases hc, { refine (hp_prime.1.ne_zero _).elim, exact_mod_cast (pow_eq_zero hc) }, { exact hc } }, rwa [norm_eq_pow_val aux, norm_p_pow, norm_eq_pow_val hc, ← fpow_add, ← neg_add, fpow_inj, neg_inj] at this, { exact_mod_cast hp_prime.1.pos }, { exact_mod_cast hp_prime.1.ne_one }, { exact_mod_cast hp_prime.1.ne_zero }, end section units /-! ### Units of `ℤ_[p]` -/ local attribute [reducible] padic_int lemma mul_inv : ∀ {z : ℤ_[p]}, ∥z∥ = 1 → z * z.inv = 1 | ⟨k, _⟩ h := begin have hk : k ≠ 0, from λ h', @zero_ne_one ℚ_[p] _ _ (by simpa [h'] using h), unfold padic_int.inv, split_ifs, { change (⟨k * (1/k), _⟩ : ℤ_[p]) = 1, simp [hk], refl }, { apply subtype.ext_iff_val.2, simp [mul_inv_cancel hk] } end lemma inv_mul {z : ℤ_[p]} (hz : ∥z∥ = 1) : z.inv * z = 1 := by rw [mul_comm, mul_inv hz] lemma is_unit_iff {z : ℤ_[p]} : is_unit z ↔ ∥z∥ = 1 := ⟨λ h, begin rcases is_unit_iff_dvd_one.1 h with ⟨w, eq⟩, refine le_antisymm (norm_le_one _) _, have := mul_le_mul_of_nonneg_left (norm_le_one w) (norm_nonneg z), rwa [mul_one, ← norm_mul, ← eq, norm_one] at this end, λ h, ⟨⟨z, z.inv, mul_inv h, inv_mul h⟩, rfl⟩⟩ lemma norm_lt_one_add {z1 z2 : ℤ_[p]} (hz1 : ∥z1∥ < 1) (hz2 : ∥z2∥ < 1) : ∥z1 + z2∥ < 1 := lt_of_le_of_lt (nonarchimedean _ _) (max_lt hz1 hz2) lemma norm_lt_one_mul {z1 z2 : ℤ_[p]} (hz2 : ∥z2∥ < 1) : ∥z1 * z2∥ < 1 := calc ∥z1 * z2∥ = ∥z1∥ * ∥z2∥ : by simp ... < 1 : mul_lt_one_of_nonneg_of_lt_one_right (norm_le_one _) (norm_nonneg _) hz2 @[simp] lemma mem_nonunits {z : ℤ_[p]} : z ∈ nonunits ℤ_[p] ↔ ∥z∥ < 1 := by rw lt_iff_le_and_ne; simp [norm_le_one z, nonunits, is_unit_iff] /-- A `p`-adic number `u` with `∥u∥ = 1` is a unit of `ℤ_[p]`. -/ def mk_units {u : ℚ_[p]} (h : ∥u∥ = 1) : units ℤ_[p] := let z : ℤ_[p] := ⟨u, le_of_eq h⟩ in ⟨z, z.inv, mul_inv h, inv_mul h⟩ @[simp] lemma mk_units_eq {u : ℚ_[p]} (h : ∥u∥ = 1) : ((mk_units h : ℤ_[p]) : ℚ_[p]) = u := rfl @[simp] lemma norm_units (u : units ℤ_[p]) : ∥(u : ℤ_[p])∥ = 1 := is_unit_iff.mp $ by simp /-- `unit_coeff hx` is the unit `u` in the unique representation `x = u * p ^ n`. See `unit_coeff_spec`. -/ def unit_coeff {x : ℤ_[p]} (hx : x ≠ 0) : units ℤ_[p] := let u : ℚ_[p] := x*p^(-x.valuation) in have hu : ∥u∥ = 1, by simp [hx, nat.fpow_ne_zero_of_pos (by exact_mod_cast hp_prime.1.pos) x.valuation, norm_eq_pow_val, fpow_neg, inv_mul_cancel, -cast_eq_of_rat_of_nat], mk_units hu @[simp] lemma unit_coeff_coe {x : ℤ_[p]} (hx : x ≠ 0) : (unit_coeff hx : ℚ_[p]) = x * p ^ (-x.valuation) := rfl lemma unit_coeff_spec {x : ℤ_[p]} (hx : x ≠ 0) : x = (unit_coeff hx : ℤ_[p]) * p ^ int.nat_abs (valuation x) := begin apply subtype.coe_injective, push_cast, have repr : (x : ℚ_[p]) = (unit_coeff hx) * p ^ x.valuation, { rw [unit_coeff_coe, mul_assoc, ← fpow_add], { simp }, { exact_mod_cast hp_prime.1.ne_zero } }, convert repr using 2, rw [← gpow_coe_nat, int.nat_abs_of_nonneg (valuation_nonneg x)], end end units section norm_le_iff /-! ### Various characterizations of open unit balls -/ lemma norm_le_pow_iff_le_valuation (x : ℤ_[p]) (hx : x ≠ 0) (n : ℕ) : ∥x∥ ≤ p ^ (-n : ℤ) ↔ ↑n ≤ x.valuation := begin rw norm_eq_pow_val hx, lift x.valuation to ℕ using x.valuation_nonneg with k hk, simp only [int.coe_nat_le, fpow_neg, gpow_coe_nat], have aux : ∀ n : ℕ, 0 < (p ^ n : ℝ), { apply pow_pos, exact_mod_cast hp_prime.1.pos }, rw [inv_le_inv (aux _) (aux _)], have : p ^ n ≤ p ^ k ↔ n ≤ k := (strict_mono_pow hp_prime.1.one_lt).le_iff_le, rw [← this], norm_cast, end lemma mem_span_pow_iff_le_valuation (x : ℤ_[p]) (hx : x ≠ 0) (n : ℕ) : x ∈ (ideal.span {p ^ n} : ideal ℤ_[p]) ↔ ↑n ≤ x.valuation := begin rw [ideal.mem_span_singleton], split, { rintro ⟨c, rfl⟩, suffices : c ≠ 0, { rw [valuation_p_pow_mul _ _ this, le_add_iff_nonneg_right], apply valuation_nonneg, }, contrapose! hx, rw [hx, mul_zero], }, { rw [unit_coeff_spec hx] { occs := occurrences.pos [2] }, lift x.valuation to ℕ using x.valuation_nonneg with k hk, simp only [int.nat_abs_of_nat, units.is_unit, is_unit.dvd_mul_left, int.coe_nat_le], intro H, obtain ⟨k, rfl⟩ := nat.exists_eq_add_of_le H, simp only [pow_add, dvd_mul_right], } end lemma norm_le_pow_iff_mem_span_pow (x : ℤ_[p]) (n : ℕ) : ∥x∥ ≤ p ^ (-n : ℤ) ↔ x ∈ (ideal.span {p ^ n} : ideal ℤ_[p]) := begin by_cases hx : x = 0, { subst hx, simp only [norm_zero, fpow_neg, gpow_coe_nat, inv_nonneg, iff_true, submodule.zero_mem], exact_mod_cast nat.zero_le _ }, rw [norm_le_pow_iff_le_valuation x hx, mem_span_pow_iff_le_valuation x hx], end lemma norm_le_pow_iff_norm_lt_pow_add_one (x : ℤ_[p]) (n : ℤ) : ∥x∥ ≤ p ^ n ↔ ∥x∥ < p ^ (n + 1) := begin rw norm_def, exact padic.norm_le_pow_iff_norm_lt_pow_add_one _ _, end lemma norm_lt_pow_iff_norm_le_pow_sub_one (x : ℤ_[p]) (n : ℤ) : ∥x∥ < p ^ n ↔ ∥x∥ ≤ p ^ (n - 1) := by rw [norm_le_pow_iff_norm_lt_pow_add_one, sub_add_cancel] lemma norm_lt_one_iff_dvd (x : ℤ_[p]) : ∥x∥ < 1 ↔ ↑p ∣ x := begin have := norm_le_pow_iff_mem_span_pow x 1, rw [ideal.mem_span_singleton, pow_one] at this, rw [← this, norm_le_pow_iff_norm_lt_pow_add_one], simp only [gpow_zero, int.coe_nat_zero, int.coe_nat_succ, add_left_neg, zero_add], end @[simp] lemma pow_p_dvd_int_iff (n : ℕ) (a : ℤ) : (p ^ n : ℤ_[p]) ∣ a ↔ ↑p ^ n ∣ a := by rw [← norm_int_le_pow_iff_dvd, norm_le_pow_iff_mem_span_pow, ideal.mem_span_singleton] end norm_le_iff section dvr /-! ### Discrete valuation ring -/ instance : local_ring ℤ_[p] := local_of_nonunits_ideal zero_ne_one $ λ x y, by simp; exact norm_lt_one_add lemma p_nonnunit : (p : ℤ_[p]) ∈ nonunits ℤ_[p] := have (p : ℝ)⁻¹ < 1, from inv_lt_one $ by exact_mod_cast hp_prime.1.one_lt, by simp [this] lemma maximal_ideal_eq_span_p : maximal_ideal ℤ_[p] = ideal.span {p} := begin apply le_antisymm, { intros x hx, rw ideal.mem_span_singleton, simp only [local_ring.mem_maximal_ideal, mem_nonunits] at hx, rwa ← norm_lt_one_iff_dvd, }, { rw [ideal.span_le, set.singleton_subset_iff], exact p_nonnunit } end lemma prime_p : prime (p : ℤ_[p]) := begin rw [← ideal.span_singleton_prime, ← maximal_ideal_eq_span_p], { apply_instance }, { exact_mod_cast hp_prime.1.ne_zero } end lemma irreducible_p : irreducible (p : ℤ_[p]) := prime.irreducible prime_p instance : discrete_valuation_ring ℤ_[p] := discrete_valuation_ring.of_has_unit_mul_pow_irreducible_factorization ⟨p, irreducible_p, λ x hx, ⟨x.valuation.nat_abs, unit_coeff hx, by rw [mul_comm, ← unit_coeff_spec hx]⟩⟩ lemma ideal_eq_span_pow_p {s : ideal ℤ_[p]} (hs : s ≠ ⊥) : ∃ n : ℕ, s = ideal.span {p ^ n} := discrete_valuation_ring.ideal_eq_span_pow_irreducible hs irreducible_p open cau_seq instance : is_adic_complete (maximal_ideal ℤ_[p]) ℤ_[p] := { prec' := λ x hx, begin simp only [← ideal.one_eq_top, smul_eq_mul, mul_one, smodeq.sub_mem, maximal_ideal_eq_span_p, ideal.span_singleton_pow, ← norm_le_pow_iff_mem_span_pow] at hx ⊢, let x' : cau_seq ℤ_[p] norm := ⟨x, _⟩, swap, { intros ε hε, obtain ⟨m, hm⟩ := exists_pow_neg_lt p hε, refine ⟨m, λ n hn, lt_of_le_of_lt _ hm⟩, rw [← neg_sub, norm_neg], exact hx hn }, { refine ⟨x'.lim, λ n, _⟩, have : (0:ℝ) < p ^ (-n : ℤ), { apply fpow_pos_of_pos, exact_mod_cast hp_prime.1.pos }, obtain ⟨i, hi⟩ := equiv_def₃ (equiv_lim x') this, by_cases hin : i ≤ n, { exact (hi i le_rfl n hin).le, }, { push_neg at hin, specialize hi i le_rfl i le_rfl, specialize hx hin.le, have := nonarchimedean (x n - x i) (x i - x'.lim), rw [sub_add_sub_cancel] at this, refine this.trans (max_le_iff.mpr ⟨hx, hi.le⟩), } }, end } end dvr end padic_int
65a20119ce70a9f880e75100ce94590c4094bd4d
439bc6c3e74a118aa51df633b8e1f24415804d86
/category.lean
6aecc608170934037308f619a3e696bdc32a89d9
[]
no_license
jcommelin/lt2019_slides
4ca498db02b5187c5778c21b985126d52d260696
3234cd92920d3d4321cc2cef78b48e5fa55be413
refs/heads/master
1,586,718,101,957
1,546,930,855,000
1,546,930,855,000
162,697,592
1
0
null
null
null
null
UTF-8
Lean
false
false
541
lean
class category (obj : Type u) : Type (max u (v+1)) := (hom : obj → obj → Type v) (infixr ` ⟶ `:10 := hom) (id : Π X : obj, X ⟶ X) (notation `𝟙` := id) (comp : Π {X Y Z : obj}, (X ⟶ Y) → (Y ⟶ Z) → (X ⟶ Z)) (infixr ` ≫ `:80 := comp) (id_comp' : ∀ {X Y : obj} (f : X ⟶ Y), 𝟙 X ≫ f = f . obviously) (comp_id' : ∀ {X Y : obj} (f : X ⟶ Y), f ≫ 𝟙 Y = f . obviously) (assoc' : ∀ {W X Y Z : obj} (f : W ⟶ X) (g : X ⟶ Y) (h : Y ⟶ Z), (f ≫ g) ≫ h = f ≫ (g ≫ h) . obviously)
a030050fe62cfa681a488e536cca4495f9fe9fea
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/run/inaccessibleAnnotDefEqIssue.lean
8ce021305f5beb0086472210f8ee723831336a99
[ "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
283
lean
example : Int → Nat | (_ : Nat) => 0 | Int.negSucc n => 0 protected theorem Int.add_comm : ∀ a b : Int, a + b = b + a | (n : Nat), (m : Nat) => sorry | (_ : Nat), Int.negSucc _ => rfl | Int.negSucc _, (_ : Nat) => rfl | Int.negSucc _, Int.negSucc _ => sorry
00d2ab0895c56ee0ec9bb234daed2a3cacf9b146
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/traceStateBactracking.lean
921bf8da8008990c2296b30c8d5265411d5233bf
[ "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
166
lean
example (h : 0 = 1) : False := by first | trace_state; fail | contradiction example (h : 0 = 1) : False := by first | trace "first branch"; fail | contradiction
2497de90aea37270921cfb9256bd4e0d5a74b122
24cea0681d40a3d3a2fd112c35ce26dfe9e2dd1c
/src/relax/disintegration.lean
50b2dbcb5cd82171e220f977ea8fdd0e4679f86c
[ "Apache-2.0" ]
permissive
jtristan/FormalML
4119809fd728bd0e6ffe2e4961e1a2dfdc1b7864
b9f54593c7f2badde15953de876ee214e23b34a0
refs/heads/master
1,668,672,921,807
1,594,691,391,000
1,594,691,391,000
279,452,890
4
0
null
null
null
null
UTF-8
Lean
false
false
12,964
lean
/- Copyright © 2020, Oracle and/or its affiliates. All rights reserved. -/ import .relax local attribute [instance] classical.prop_decidable open set namespace relax variables (μ: probability_measure ℍ) noncomputable def maj_code (u: ℍ × ℍ): (ℍ × ℕ) := let u1 := u.fst in let u2 := u.snd in let theta := generate_uniform_variate_simple(0,1,u1) in let X := generate_binomial_variate_simple(theta,u2) in (theta,X) @[simp] lemma measurable_maj_code:measurable ( λ (u: ℍ × ℍ),maj_code u) := begin unfold maj_code, simp, apply measurable.prod; simp, { apply measurable.comp, apply uniform_measurable, apply measurable.prod; simp, apply measurable_const, apply measurable.prod; simp, apply measurable_const, apply measurable_fst, apply measurable_id, }, { apply measurable.comp, apply binomial_measurable, apply measurable.prod; simp, apply measurable.comp, apply uniform_measurable, apply measurable.prod; simp, apply measurable_const, apply measurable.prod; simp, apply measurable_const, apply measurable_fst, apply measurable_id, apply measurable_snd, apply measurable_id, } end axiom τ(t: ℍ): probability_measure ℍ axiom dd: ∀ t: ℍ, τ(t) {x: ℍ | generate_uniform_variate_simple(0,1,x) = t} = 1 noncomputable def γ(t: ℍ): probability_measure (ℍ × ℕ) := map maj_code (prod.prob_measure (τ(t)) μ) def male_selected_(t: ℍ) := {v: (ℍ × ℕ) | v.snd = 1 ∧ v.fst = t} @[simp] lemma is_measurable_1: is_measurable {v: (ℍ × ℕ) | v.snd = 1} := begin have prod: {v: (ℍ × ℕ) | v.snd = 1} = set.prod {x: ℍ | true} {n: ℕ | n = 1}, { rw ext_iff, intro, rw mem_prod_eq, split, intro, split, rw mem_set_of_eq at *, trivial, rw mem_set_of_eq at *, exact a, intro, cases a, rw mem_set_of_eq at *, exact a_right, }, rw prod, clear prod, apply is_measurable_set_prod, apply is_measurable.univ, trivial, end @[simp] lemma is_measurable_2: ∀ t, is_measurable {v: (ℍ × ℕ) | v.fst = t} := begin intro, have prod: {v: (ℍ × ℕ) | v.fst = t} = set.prod {t} univ, { rw ext_iff, intro, rw mem_prod_eq, split, intro, split, rw mem_set_of_eq at *, rw a, simp, rw mem_set_of_eq at *, trivial, intro, cases a, rw mem_set_of_eq at *, simp at a_left, exact a_left, }, rw prod, clear prod, apply is_measurable_set_prod, swap, apply is_measurable.univ, apply measure_theory.is_measurable_singleton, end lemma test: ∀ t, (γ μ t) {a: ℍ × ℕ | a.fst = t} = 1 := begin intro, dunfold γ, rw map_apply, simp, unfold maj_code, simp, have foo: {a: ℍ × ℍ | generate_uniform_variate_simple(0,1,a.fst) = t} = set.prod {a: ℍ | generate_uniform_variate_simple(0,1,a) = t} univ, { rw ext_iff, intros, repeat {rw mem_set_of_eq}, simp, }, rw foo, rw prod.prob_measure_apply, rw dd, simp, simp, apply is_measurable.univ, simp, simp, end @[simp] lemma is_measurable_3: ∀ t, is_measurable {v: (ℍ × ℕ) | v.snd = 1 ∧ v.fst = t} := begin intros, apply is_measurable.inter, apply is_measurable_1, apply is_measurable_2, end lemma rw_gamma_2: ∀ t: ℍ, (γ μ)(t) {a: ℍ × ℕ | a.snd = 1 ∧ a.fst = t} = t := begin intros, dunfold γ, rw map_apply; simp, have set_rw: {a: ℍ × ℍ | (maj_code a).snd = 1 ∧ (maj_code a).fst = t} = set.prod {a: ℍ | generate_uniform_variate_simple(0,1,a) = t} {a: ℍ | generate_binomial_variate_simple(t,a) = 1}, { rw ext_iff, intros, repeat {rw mem_set_of_eq}, simp, cases x, unfold maj_code, simp, split; intros, { cases a, rw a_right at *, simp at *, assumption, }, { cases a, rw a_left at *, simp at *, assumption, }, }, rw set_rw, clear set_rw, rw prod.prob_measure_apply, have bin_rw:= generate_binomial_variate_simple_prop μ t, unfold E_bin at bin_rw, rw bin_rw at *, rw dd, simp, simp, simp, end lemma maj_: ∀ t: ℍ, (γ μ)(t) (male_selected_ t) = t := begin intros, unfold male_selected_, rw rw_gamma_2, end noncomputable def code (u: (ℍ × ℕ) × ℍ × ℍ): (ℍ × ℕ) × (ℍ × ℕ) := let theta := u.fst.fst in let X := u.fst.snd in let u3 := u.snd.fst in let u4 := u.snd.snd in let phi := generate_uniform_variate_simple(0.8 * theta,1,u3) in let Y := generate_binomial_variate_simple(phi,u4) in ((theta,X),(phi,Y)) lemma measurable_coe : measurable (coe : nnreal → real) := begin apply measure_theory.measurable_of_continuous, apply nnreal.continuous_coe, end @[simp] lemma measurable_code:measurable ( λ (u: (ℍ × ℕ) × ℍ × ℍ),code u) := begin unfold code, apply measurable.prod, { apply measurable.prod; simp, { apply measurable.comp, apply measurable_fst, apply measurable_id, apply measurable.comp, apply measurable_fst, apply measurable_id, apply measurable_id, }, { apply measurable.comp, apply measurable_snd, apply measurable_id, apply measurable.comp, apply measurable_fst, apply measurable_id, apply measurable_id, }, }, { apply measurable.prod; simp, { apply measurable.comp, apply uniform_measurable, apply measurable.prod; simp, { apply measure_theory.measurable_mul, apply measurable_const, apply measurable.comp, apply measurable_coe, apply measurable_fst, apply measurable_fst, apply measurable_id, }, apply measurable.prod; simp, apply measurable_const, apply measurable_fst, apply measurable_snd, apply measurable_id, }, { apply measurable.comp, apply binomial_measurable, apply measurable.prod; simp, apply measurable.comp, apply uniform_measurable, apply measurable.prod; simp, { apply measure_theory.measurable_mul, apply measurable_const, apply measurable.comp, apply measurable_coe, apply measurable_fst, apply measurable_fst, apply measurable_id, }, apply measurable.prod; simp, apply measurable_const, apply measurable_fst, apply measurable_snd, apply measurable_id, apply measurable_snd, apply measurable_snd, apply measurable_id, }, } end noncomputable def δ(t: ℍ): probability_measure ((ℍ × ℕ) × (ℍ × ℕ)) := map code (prod.prob_measure ((γ μ)(t)) (prod.prob_measure μ μ)) @[simp] lemma is_measurable_4: ∀ t, is_measurable {v: (ℍ × ℕ) × (ℍ × ℕ) | v.fst.fst = t} := begin intro, have prod: {v: (ℍ × ℕ) × (ℍ × ℕ) | v.fst.fst = t} = set.prod (set.prod {t} univ) (set.prod univ univ), { rw ext_iff, intro, rw mem_prod_eq, rw mem_prod_eq, split, { intro, split, split, rw mem_set_of_eq at *, rw a, simp, rw mem_set_of_eq at *, trivial, rw mem_set_of_eq at *, simp, }, intro, cases a, rw mem_set_of_eq at *, simp at a_left, exact a_left, }, rw prod, clear prod, apply is_measurable_set_prod, apply is_measurable_set_prod, apply measure_theory.is_measurable_singleton, apply is_measurable.univ, apply is_measurable_set_prod, apply is_measurable.univ, apply is_measurable.univ, end @[simp] lemma is_measurable_5: is_measurable {v: (ℍ × ℕ) × (ℍ × ℕ) | v.fst.snd = 1} := begin have prod: {v: (ℍ × ℕ) × (ℍ × ℕ) | v.fst.snd = 1} = set.prod (set.prod univ {n: ℕ | n = 1}) (set.prod univ univ), { rw ext_iff, intro, rw mem_prod_eq, rw mem_prod_eq, split, intro, split, split, rw mem_set_of_eq at *, trivial, rw mem_set_of_eq at *, exact a, split, rw mem_set_of_eq at *, trivial, rw mem_set_of_eq at *, trivial, intro, cases a, cases a_left, rw mem_set_of_eq at *, exact a_left_right, }, rw prod, clear prod, apply is_measurable_set_prod, apply is_measurable_set_prod, apply is_measurable.univ, trivial, apply is_measurable_set_prod, apply is_measurable.univ, apply is_measurable.univ, end @[simp] lemma is_measurable_6: is_measurable {v: (ℍ × ℕ) × (ℍ × ℕ) | v.snd.snd = 1} := begin have prod: {v: (ℍ × ℕ) × (ℍ × ℕ) | v.snd.snd = 1} = set.prod (set.prod univ univ) (set.prod univ {n: ℕ | n = 1}), { rw ext_iff, intro, rw mem_prod_eq, rw mem_prod_eq, split, intro, split, split, rw mem_set_of_eq at *, trivial, rw mem_set_of_eq at *, trivial, split, rw mem_set_of_eq at *, trivial, rw mem_set_of_eq at *, exact a, intro, cases a, cases a_right, rw mem_set_of_eq at *, exact a_right_right, }, rw prod, clear prod, apply is_measurable_set_prod, apply is_measurable_set_prod, apply is_measurable.univ, apply is_measurable.univ, apply is_measurable_set_prod, apply is_measurable.univ, trivial, end def male_selected(t: ℍ) := {v: (ℍ × ℕ) × (ℍ × ℕ) | v.fst.snd = 1 ∧ v.fst.fst = t} @[simp] lemma male_selected_is_measurable: ∀ t, is_measurable {v: (ℍ × ℕ) × (ℍ × ℕ) | v.fst.snd = 1 ∧ v.fst.fst = t} := begin intros, apply is_measurable.inter, apply is_measurable_5, apply is_measurable_4, end def female_selected(t: ℍ) := {v: (ℍ × ℕ) × (ℍ × ℕ) | v.snd.snd = 1 ∧ v.fst.fst = t} @[simp] lemma female_selected_is_measurable: ∀ t, is_measurable {v: (ℍ × ℕ) × (ℍ × ℕ) | v.snd.snd = 1 ∧ v.fst.fst = t} := begin intros, apply is_measurable.inter, apply is_measurable_6, apply is_measurable_4, end lemma rw_dive: ∀ t: ℍ, ∀ P: ℍ × ℕ → Prop, is_measurable (set_of P) → (δ μ) t {v: (ℍ × ℕ) × (ℍ × ℕ) | P v.fst} = (γ μ) t {v: ℍ × ℕ | P v} := begin intros, dunfold δ, dunfold γ, rw map_apply, simp, rw map_apply, simp, unfold code, simp, have set_rw: {a: (ℍ × ℕ) × ℍ × ℍ | P a.fst} = set.prod {a: ℍ × ℕ | P a} (set.prod univ univ), { rw ext_iff, intros, repeat {rw mem_set_of_eq}, simp, }, rw set_rw, simp, clear set_rw, rw prod.prob_measure_apply, simp, rw map_apply, simp, /- Mundane measurability -/ simp, apply a, apply a, apply is_measurable.univ, simp, apply a, simp, /- Interesting example -/ have prod: {v: (ℍ × ℕ) × (ℍ × ℕ) | P (v.fst)} = set.prod {v: (ℍ × ℕ) | P(v)} univ, { rw ext_iff, intro, rw mem_prod_eq, split, intro, split, rw mem_set_of_eq at *, exact a_1, rw mem_set_of_eq at *, trivial, intro, cases a_1, rw mem_set_of_eq at *, exact a_1_left, }, rw prod, clear prod, apply is_measurable_set_prod, exact a, apply is_measurable.univ, end lemma set_rw_1: ∀ t: ℍ, set.prod {a: ℍ × ℕ | a.fst = t} (set.prod univ {a: ℍ | generate_binomial_variate_simple(4/5 * t,a) = 1}) ⊆ {a: (ℍ × ℕ) × ℍ × ℍ | (code a).snd.snd = 1 ∧ (code a).fst.fst = t} := begin intros, unfold set.prod, rw set_of_subset_set_of, repeat {rw mem_set_of_eq}, simp, intros, unfold code, simp, rw a_1 at *, simp, apply generate_binomial_variate_simple_prop_2 b_1.snd (4/5 *t), have uni_in:= generate_uniform_variate_simple_in b_1.fst (4/5 * t) 1, cases uni_in, assumption, assumption, end lemma principal: ∀ t, 4/5 * t ≤ (δ μ)(t) (female_selected t) := begin intros, unfold female_selected, have foo:= set_rw_1 t, have bar:= probability_measure.prob_mono (prod.prob_measure ((γ μ) t) (prod.prob_measure μ μ)) foo, clear foo, rw prod.prob_measure_apply at bar, rw prod.prob_measure_apply at bar, have bin_rw:= generate_binomial_variate_simple_prop μ (4/5 * t), unfold E_bin at bin_rw, rw bin_rw at *, clear bin_rw, dunfold δ, rw map_apply, simp, rw test at bar, simp at bar, exact bar, /- Mundane measurability -/ simp, simp, apply is_measurable.univ, simp, simp, apply is_measurable_set_prod, apply is_measurable.univ, simp, end lemma maj: ∀ t: ℍ, (δ μ)(t) (male_selected t) = t := begin intros, unfold male_selected, have rw_1 := rw_dive μ t (λ (v: ℍ × ℕ), v.snd = 1 ∧ v.fst = t), rw rw_1, clear rw_1, have prop:= maj_ μ t, unfold male_selected_ at prop, assumption, simp, end theorem final: ∀ t: ℍ, (0.8:nnreal) * (δ μ)(t) (male_selected t) ≤ (δ μ)(t) (female_selected t) := begin intros, rw maj, apply principal, end end relax
824e371ecbbc70bcd6972e0cef8d72711cbdd676
1abd1ed12aa68b375cdef28959f39531c6e95b84
/src/order/filter/basic.lean
dc28ffccfcfe1d50e51b439090026ec32b692a42
[ "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
117,407
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, Jeremy Avigad -/ import data.set.finite import order.copy import order.zorn import tactic.monotonicity /-! # Theory of filters on sets ## Main definitions * `filter` : filters on a set; * `at_top`, `at_bot`, `cofinite`, `principal` : specific filters; * `map`, `comap`, `prod` : operations on filters; * `tendsto` : limit with respect to filters; * `eventually` : `f.eventually p` means `{x | p x} ∈ f`; * `frequently` : `f.frequently p` means `{x | ¬p x} ∉ f`; * `filter_upwards [h₁, ..., hₙ]` : takes a list of proofs `hᵢ : sᵢ ∈ f`, and replaces a goal `s ∈ f` with `∀ x, x ∈ s₁ → ... → x ∈ sₙ → x ∈ s`; * `ne_bot f` : an utility class stating that `f` is a non-trivial filter. Filters on a type `X` are sets of sets of `X` satisfying three conditions. They are mostly used to abstract two related kinds of ideas: * *limits*, including finite or infinite limits of sequences, finite or infinite limits of functions at a point or at infinity, etc... * *things happening eventually*, including things happening for large enough `n : ℕ`, or near enough a point `x`, or for close enough pairs of points, or things happening almost everywhere in the sense of measure theory. Dually, filters can also express the idea of *things happening often*: for arbitrarily large `n`, or at a point in any neighborhood of given a point etc... In this file, we define the type `filter X` of filters on `X`, and endow it with a complete lattice structure. This structure is lifted from the lattice structure on `set (set X)` using the Galois insertion which maps a filter to its elements in one direction, and an arbitrary set of sets to the smallest filter containing it in the other direction. We also prove `filter` is a monadic functor, with a push-forward operation `filter.map` and a pull-back operation `filter.comap` that form a Galois connections for the order on filters. Finally we describe a product operation `filter X → filter Y → filter (X × Y)`. The examples of filters appearing in the description of the two motivating ideas are: * `(at_top : filter ℕ)` : made of sets of `ℕ` containing `{n | n ≥ N}` for some `N` * `𝓝 x` : made of neighborhoods of `x` in a topological space (defined in topology.basic) * `𝓤 X` : made of entourages of a uniform space (those space are generalizations of metric spaces defined in topology.uniform_space.basic) * `μ.ae` : made of sets whose complement has zero measure with respect to `μ` (defined in `measure_theory.measure_space`) The general notion of limit of a map with respect to filters on the source and target types is `filter.tendsto`. It is defined in terms of the order and the push-forward operation. The predicate "happening eventually" is `filter.eventually`, and "happening often" is `filter.frequently`, whose definitions are immediate after `filter` is defined (but they come rather late in this file in order to immediately relate them to the lattice structure). For instance, anticipating on topology.basic, the statement: "if a sequence `u` converges to some `x` and `u n` belongs to a set `M` for `n` large enough then `x` is in the closure of `M`" is formalized as: `tendsto u at_top (𝓝 x) → (∀ᶠ n in at_top, u n ∈ M) → x ∈ closure M`, which is a special case of `mem_closure_of_tendsto` from topology.basic. ## Notations * `∀ᶠ x in f, p x` : `f.eventually p`; * `∃ᶠ x in f, p x` : `f.frequently p`; * `f =ᶠ[l] g` : `∀ᶠ x in l, f x = g x`; * `f ≤ᶠ[l] g` : `∀ᶠ x in l, f x ≤ g x`; * `f ×ᶠ g` : `filter.prod f g`, localized in `filter`; * `𝓟 s` : `principal s`, localized in `filter`. ## References * [N. Bourbaki, *General Topology*][bourbaki1966] Important note: Bourbaki requires that a filter on `X` cannot contain all sets of `X`, which we do *not* require. This gives `filter X` better formal properties, in particular a bottom element `⊥` for its lattice structure, at the cost of including the assumption `[ne_bot f]` in a number of lemmas and definitions. -/ open set function universes u v w x y open_locale classical /-- A filter `F` on a type `α` is a collection of sets of `α` which contains the whole `α`, is upwards-closed, and is stable under intersection. We do not forbid this collection to be all sets of `α`. -/ structure filter (α : Type*) := (sets : set (set α)) (univ_sets : set.univ ∈ sets) (sets_of_superset {x y} : x ∈ sets → x ⊆ y → y ∈ sets) (inter_sets {x y} : x ∈ sets → y ∈ sets → x ∩ y ∈ sets) /-- If `F` is a filter on `α`, and `U` a subset of `α` then we can write `U ∈ F` as on paper. -/ instance {α : Type*}: has_mem (set α) (filter α) := ⟨λ U F, U ∈ F.sets⟩ namespace filter variables {α : Type u} {f g : filter α} {s t : set α} @[simp] protected lemma mem_mk {t : set (set α)} {h₁ h₂ h₃} : s ∈ mk t h₁ h₂ h₃ ↔ s ∈ t := iff.rfl @[simp] protected lemma mem_sets : s ∈ f.sets ↔ s ∈ f := iff.rfl instance inhabited_mem : inhabited {s : set α // s ∈ f} := ⟨⟨univ, f.univ_sets⟩⟩ lemma filter_eq : ∀ {f g : filter α}, f.sets = g.sets → f = g | ⟨a, _, _, _⟩ ⟨._, _, _, _⟩ rfl := rfl lemma filter_eq_iff : f = g ↔ f.sets = g.sets := ⟨congr_arg _, filter_eq⟩ protected lemma ext_iff : f = g ↔ ∀ s, s ∈ f ↔ s ∈ g := by simp only [filter_eq_iff, ext_iff, filter.mem_sets] @[ext] protected lemma ext : (∀ s, s ∈ f ↔ s ∈ g) → f = g := filter.ext_iff.2 @[simp] lemma univ_mem : univ ∈ f := f.univ_sets lemma mem_of_superset : ∀ {x y : set α}, x ∈ f → x ⊆ y → y ∈ f := f.sets_of_superset lemma inter_mem : ∀ {s t}, s ∈ f → t ∈ f → s ∩ t ∈ f := f.inter_sets @[simp] lemma inter_mem_iff {s t} : s ∩ t ∈ f ↔ s ∈ f ∧ t ∈ f := ⟨λ h, ⟨mem_of_superset h (inter_subset_left s t), mem_of_superset h (inter_subset_right s t)⟩, and_imp.2 inter_mem⟩ lemma univ_mem' (h : ∀ a, a ∈ s) : s ∈ f := mem_of_superset univ_mem (λ x _, h x) lemma mp_mem (hs : s ∈ f) (h : {x | x ∈ s → x ∈ t} ∈ f) : t ∈ f := mem_of_superset (inter_mem hs h) $ λ x ⟨h₁, h₂⟩, h₂ h₁ lemma congr_sets (h : {x | x ∈ s ↔ x ∈ t} ∈ f) : s ∈ f ↔ t ∈ f := ⟨λ hs, mp_mem hs (mem_of_superset h (λ x, iff.mp)), λ hs, mp_mem hs (mem_of_superset h (λ x, iff.mpr))⟩ @[simp] lemma bInter_mem {β : Type v} {s : β → set α} {is : set β} (hf : finite is) : (⋂ i ∈ is, s i) ∈ f ↔ ∀ i ∈ is, s i ∈ f := finite.induction_on hf (by simp) (λ i s hi _ hs, by simp [hs]) @[simp] lemma bInter_finset_mem {β : Type v} {s : β → set α} (is : finset β) : (⋂ i ∈ is, s i) ∈ f ↔ ∀ i ∈ is, s i ∈ f := bInter_mem is.finite_to_set alias bInter_finset_mem ← finset.Inter_mem_sets attribute [protected] finset.Inter_mem_sets @[simp] lemma sInter_mem {s : set (set α)} (hfin : finite s) : ⋂₀ s ∈ f ↔ ∀ U ∈ s, U ∈ f := by rw [sInter_eq_bInter, bInter_mem hfin] @[simp] lemma Inter_mem {β : Type v} {s : β → set α} [fintype β] : (⋂ i, s i) ∈ f ↔ ∀ i, s i ∈ f := by simpa using bInter_mem finite_univ lemma exists_mem_subset_iff : (∃ t ∈ f, t ⊆ s) ↔ s ∈ f := ⟨λ ⟨t, ht, ts⟩, mem_of_superset ht ts, λ hs, ⟨s, hs, subset.rfl⟩⟩ lemma monotone_mem {f : filter α} : monotone (λ s, s ∈ f) := λ s t hst h, mem_of_superset h hst end filter namespace tactic.interactive open tactic interactive /-- `filter_upwards [h1, ⋯, hn]` replaces a goal of the form `s ∈ f` and terms `h1 : t1 ∈ f, ⋯, hn : tn ∈ f` with `∀ x, x ∈ t1 → ⋯ → x ∈ tn → x ∈ s`. `filter_upwards [h1, ⋯, hn] e` is a short form for `{ filter_upwards [h1, ⋯, hn], exact e }`. -/ meta def filter_upwards (s : parse types.pexpr_list) (e' : parse $ optional types.texpr) : tactic unit := do s.reverse.mmap (λ e, eapplyc `filter.mp_mem >> eapply e), eapplyc `filter.univ_mem', `[dsimp only [set.mem_set_of_eq]], match e' with | some e := interactive.exact e | none := skip end add_tactic_doc { name := "filter_upwards", category := doc_category.tactic, decl_names := [`tactic.interactive.filter_upwards], tags := ["goal management", "lemma application"] } end tactic.interactive namespace filter variables {α : Type u} {β : Type v} {γ : Type w} {ι : Sort x} section principal /-- The principal filter of `s` is the collection of all supersets of `s`. -/ def principal (s : set α) : filter α := { sets := {t | s ⊆ t}, univ_sets := subset_univ s, sets_of_superset := λ x y hx, subset.trans hx, inter_sets := λ x y, subset_inter } localized "notation `𝓟` := filter.principal" in filter instance : inhabited (filter α) := ⟨𝓟 ∅⟩ @[simp] lemma mem_principal {s t : set α} : s ∈ 𝓟 t ↔ t ⊆ s := iff.rfl lemma mem_principal_self (s : set α) : s ∈ 𝓟 s := subset.rfl end principal open_locale filter section join /-- The join of a filter of filters is defined by the relation `s ∈ join f ↔ {t | s ∈ t} ∈ f`. -/ def join (f : filter (filter α)) : filter α := { sets := {s | {t : filter α | s ∈ t} ∈ f}, univ_sets := by simp only [mem_set_of_eq, univ_sets, ← filter.mem_sets, set_of_true], sets_of_superset := λ x y hx xy, mem_of_superset hx $ λ f h, mem_of_superset h xy, inter_sets := λ x y hx hy, mem_of_superset (inter_mem hx hy) $ λ f ⟨h₁, h₂⟩, inter_mem h₁ h₂ } @[simp] lemma mem_join {s : set α} {f : filter (filter α)} : s ∈ join f ↔ {t | s ∈ t} ∈ f := iff.rfl end join section lattice instance : partial_order (filter α) := { le := λ f g, ∀ ⦃U : set α⦄, U ∈ g → U ∈ f, le_antisymm := λ a b h₁ h₂, filter_eq $ subset.antisymm h₂ h₁, le_refl := λ a, subset.rfl, le_trans := λ a b c h₁ h₂, subset.trans h₂ h₁ } theorem le_def {f g : filter α} : f ≤ g ↔ ∀ x ∈ g, x ∈ f := iff.rfl /-- `generate_sets g s`: `s` is in the filter closure of `g`. -/ inductive generate_sets (g : set (set α)) : set α → Prop | basic {s : set α} : s ∈ g → generate_sets s | univ : generate_sets univ | superset {s t : set α} : generate_sets s → s ⊆ t → generate_sets t | inter {s t : set α} : generate_sets s → generate_sets t → generate_sets (s ∩ t) /-- `generate g` is the smallest filter containing the sets `g`. -/ def generate (g : set (set α)) : filter α := { sets := generate_sets g, univ_sets := generate_sets.univ, sets_of_superset := λ x y, generate_sets.superset, inter_sets := λ s t, generate_sets.inter } lemma sets_iff_generate {s : set (set α)} {f : filter α} : f ≤ filter.generate s ↔ s ⊆ f.sets := iff.intro (λ h u hu, h $ generate_sets.basic $ hu) (λ h u hu, hu.rec_on h univ_mem (λ x y _ hxy hx, mem_of_superset hx hxy) (λ x y _ _ hx hy, inter_mem hx hy)) lemma mem_generate_iff {s : set $ set α} {U : set α} : U ∈ generate s ↔ ∃ t ⊆ s, finite t ∧ ⋂₀ t ⊆ U := begin split ; intro h, { induction h with V V_in V W V_in hVW hV V W V_in W_in hV hW, { use {V}, simp [V_in] }, { use ∅, simp [subset.refl, univ] }, { rcases hV with ⟨t, hts, htfin, hinter⟩, exact ⟨t, hts, htfin, hinter.trans hVW⟩ }, { rcases hV with ⟨t, hts, htfin, htinter⟩, rcases hW with ⟨z, hzs, hzfin, hzinter⟩, refine ⟨t ∪ z, union_subset hts hzs, htfin.union hzfin, _⟩, rw sInter_union, exact inter_subset_inter htinter hzinter } }, { rcases h with ⟨t, ts, tfin, h⟩, apply generate_sets.superset _ h, revert ts, apply finite.induction_on tfin, { intro h, rw sInter_empty, exact generate_sets.univ }, { intros V r hV rfin hinter h, cases insert_subset.mp h with V_in r_sub, rw [insert_eq V r, sInter_union], apply generate_sets.inter _ (hinter r_sub), rw sInter_singleton, exact generate_sets.basic V_in } }, end /-- `mk_of_closure s hs` constructs a filter on `α` whose elements set is exactly `s : set (set α)`, provided one gives the assumption `hs : (generate s).sets = s`. -/ protected def mk_of_closure (s : set (set α)) (hs : (generate s).sets = s) : filter α := { sets := s, univ_sets := hs ▸ (univ_mem : univ ∈ generate s), sets_of_superset := λ x y, hs ▸ (mem_of_superset : x ∈ generate s → x ⊆ y → y ∈ generate s), inter_sets := λ x y, hs ▸ (inter_mem : x ∈ generate s → y ∈ generate s → x ∩ y ∈ generate s) } lemma mk_of_closure_sets {s : set (set α)} {hs : (generate s).sets = s} : filter.mk_of_closure s hs = generate s := filter.ext $ λ u, show u ∈ (filter.mk_of_closure s hs).sets ↔ u ∈ (generate s).sets, from hs.symm ▸ iff.rfl /-- Galois insertion from sets of sets into filters. -/ def gi_generate (α : Type*) : @galois_insertion (set (set α)) (order_dual (filter α)) _ _ filter.generate filter.sets := { gc := λ s f, sets_iff_generate, le_l_u := λ f u h, generate_sets.basic h, choice := λ s hs, filter.mk_of_closure s (le_antisymm hs $ sets_iff_generate.1 $ le_rfl), choice_eq := λ s hs, mk_of_closure_sets } /-- The infimum of filters is the filter generated by intersections of elements of the two filters. -/ instance : has_inf (filter α) := ⟨λf g : filter α, { sets := {s | ∃ (a ∈ f) (b ∈ g), s = a ∩ b }, univ_sets := ⟨_, univ_mem, _, univ_mem, by simp⟩, sets_of_superset := begin rintro x y ⟨a, ha, b, hb, rfl⟩ xy, refine ⟨a ∪ y, mem_of_superset ha (subset_union_left a y), b ∪ y, mem_of_superset hb (subset_union_left b y), _⟩, rw [← inter_union_distrib_right, union_eq_self_of_subset_left xy] end, inter_sets := begin rintro x y ⟨a, ha, b, hb, rfl⟩ ⟨c, hc, d, hd, rfl⟩, refine ⟨a ∩ c, inter_mem ha hc, b ∩ d, inter_mem hb hd, _⟩, ac_refl end }⟩ lemma mem_inf_iff {f g : filter α} {s : set α} : s ∈ f ⊓ g ↔ ∃ t₁ ∈ f, ∃ t₂ ∈ g, s = t₁ ∩ t₂ := iff.rfl lemma mem_inf_of_left {f g : filter α} {s : set α} (h : s ∈ f) : s ∈ f ⊓ g := ⟨s, h, univ, univ_mem, (inter_univ s).symm⟩ lemma mem_inf_of_right {f g : filter α} {s : set α} (h : s ∈ g) : s ∈ f ⊓ g := ⟨univ, univ_mem, s, h, (univ_inter s).symm⟩ lemma inter_mem_inf {α : Type u} {f g : filter α} {s t : set α} (hs : s ∈ f) (ht : t ∈ g) : s ∩ t ∈ f ⊓ g := ⟨s, hs, t, ht, rfl⟩ lemma mem_inf_of_inter {f g : filter α} {s t u : set α} (hs : s ∈ f) (ht : t ∈ g) (h : s ∩ t ⊆ u) : u ∈ f ⊓ g := mem_of_superset (inter_mem_inf hs ht) h lemma mem_inf_iff_superset {f g : filter α} {s : set α} : s ∈ f ⊓ g ↔ ∃ t₁ ∈ f, ∃ t₂ ∈ g, t₁ ∩ t₂ ⊆ s := ⟨λ ⟨t₁, h₁, t₂, h₂, eq⟩, ⟨t₁, h₁, t₂, h₂, eq ▸ subset.rfl⟩, λ ⟨t₁, h₁, t₂, h₂, sub⟩, mem_inf_of_inter h₁ h₂ sub⟩ instance : has_top (filter α) := ⟨{ sets := {s | ∀ x, x ∈ s}, univ_sets := λ x, mem_univ x, sets_of_superset := λ x y hx hxy a, hxy (hx a), inter_sets := λ x y hx hy a, mem_inter (hx _) (hy _) }⟩ lemma mem_top_iff_forall {s : set α} : s ∈ (⊤ : filter α) ↔ (∀ x, x ∈ s) := iff.rfl @[simp] lemma mem_top {s : set α} : s ∈ (⊤ : filter α) ↔ s = univ := by rw [mem_top_iff_forall, eq_univ_iff_forall] section complete_lattice /- We lift the complete lattice along the Galois connection `generate` / `sets`. Unfortunately, we want to have different definitional equalities for the lattice operations. So we define them upfront and change the lattice operations for the complete lattice instance. -/ private def original_complete_lattice : complete_lattice (filter α) := @order_dual.complete_lattice _ (gi_generate α).lift_complete_lattice local attribute [instance] original_complete_lattice instance : complete_lattice (filter α) := original_complete_lattice.copy /- le -/ filter.partial_order.le rfl /- top -/ (filter.has_top).1 (top_unique $ λ s hs, by simp [mem_top.1 hs]) /- bot -/ _ rfl /- sup -/ _ rfl /- inf -/ (filter.has_inf).1 begin ext f g : 2, exact le_antisymm (le_inf (λ s, mem_inf_of_left) (λ s, mem_inf_of_right)) (begin rintro s ⟨a, ha, b, hb, rfl⟩, exact inter_sets _ (@inf_le_left (filter α) _ _ _ _ ha) (@inf_le_right (filter α) _ _ _ _ hb) end) end /- Sup -/ (join ∘ 𝓟) (by { ext s x, exact (@mem_bInter_iff _ _ s filter.sets x).symm.trans (set.ext_iff.1 (sInter_image _ _) x).symm}) /- Inf -/ _ rfl end complete_lattice /-- A filter is `ne_bot` if it is not equal to `⊥`, or equivalently the empty set does not belong to the filter. Bourbaki include this assumption in the definition of a filter but we prefer to have a `complete_lattice` structure on filter, so we use a typeclass argument in lemmas instead. -/ class ne_bot (f : filter α) : Prop := (ne' : f ≠ ⊥) lemma ne_bot_iff {f : filter α} : ne_bot f ↔ f ≠ ⊥ := ⟨λ h, h.1, λ h, ⟨h⟩⟩ lemma ne_bot.ne {f : filter α} (hf : ne_bot f) : f ≠ ⊥ := ne_bot.ne' @[simp] lemma not_ne_bot {α : Type*} {f : filter α} : ¬ f.ne_bot ↔ f = ⊥ := not_iff_comm.1 ne_bot_iff.symm lemma ne_bot.mono {f g : filter α} (hf : ne_bot f) (hg : f ≤ g) : ne_bot g := ⟨ne_bot_of_le_ne_bot hf.1 hg⟩ lemma ne_bot_of_le {f g : filter α} [hf : ne_bot f] (hg : f ≤ g) : ne_bot g := hf.mono hg @[simp] lemma sup_ne_bot {f g : filter α} : ne_bot (f ⊔ g) ↔ ne_bot f ∨ ne_bot g := by simp [ne_bot_iff, not_and_distrib] lemma bot_sets_eq : (⊥ : filter α).sets = univ := rfl lemma sup_sets_eq {f g : filter α} : (f ⊔ g).sets = f.sets ∩ g.sets := (gi_generate α).gc.u_inf lemma Sup_sets_eq {s : set (filter α)} : (Sup s).sets = (⋂ f ∈ s, (f : filter α).sets) := (gi_generate α).gc.u_Inf lemma supr_sets_eq {f : ι → filter α} : (supr f).sets = (⋂ i, (f i).sets) := (gi_generate α).gc.u_infi lemma generate_empty : filter.generate ∅ = (⊤ : filter α) := (gi_generate α).gc.l_bot lemma generate_univ : filter.generate univ = (⊥ : filter α) := mk_of_closure_sets.symm lemma generate_union {s t : set (set α)} : filter.generate (s ∪ t) = filter.generate s ⊓ filter.generate t := (gi_generate α).gc.l_sup lemma generate_Union {s : ι → set (set α)} : filter.generate (⋃ i, s i) = (⨅ i, filter.generate (s i)) := (gi_generate α).gc.l_supr @[simp] lemma mem_bot {s : set α} : s ∈ (⊥ : filter α) := trivial @[simp] lemma mem_sup {f g : filter α} {s : set α} : s ∈ f ⊔ g ↔ s ∈ f ∧ s ∈ g := iff.rfl lemma union_mem_sup {f g : filter α} {s t : set α} (hs : s ∈ f) (ht : t ∈ g) : s ∪ t ∈ f ⊔ g := ⟨mem_of_superset hs (subset_union_left s t), mem_of_superset ht (subset_union_right s t)⟩ @[simp] lemma mem_Sup {x : set α} {s : set (filter α)} : x ∈ Sup s ↔ (∀ f ∈ s, x ∈ (f : filter α)) := iff.rfl @[simp] lemma mem_supr {x : set α} {f : ι → filter α} : x ∈ supr f ↔ (∀ i, x ∈ f i) := by simp only [← filter.mem_sets, supr_sets_eq, iff_self, mem_Inter] @[simp] lemma supr_ne_bot {f : ι → filter α} : (⨆ i, f i).ne_bot ↔ ∃ i, (f i).ne_bot := by simp [ne_bot_iff] lemma infi_eq_generate (s : ι → filter α) : infi s = generate (⋃ i, (s i).sets) := show generate _ = generate _, from congr_arg _ $ congr_arg Sup $ (range_comp _ _).symm lemma mem_infi_of_mem {f : ι → filter α} (i : ι) : ∀ {s}, s ∈ f i → s ∈ ⨅ i, f i := show (⨅ i, f i) ≤ f i, from infi_le _ _ lemma mem_infi_of_Inter {ι} {s : ι → filter α} {U : set α} {I : set ι} (I_fin : finite I) {V : I → set α} (hV : ∀ i, V i ∈ s i) (hU : (⋂ i, V i) ⊆ U) : U ∈ ⨅ i, s i := begin haveI := I_fin.fintype, refine mem_of_superset (Inter_mem.2 $ λ i, _) hU, exact mem_infi_of_mem i (hV _) end lemma mem_infi {ι} {s : ι → filter α} {U : set α} : (U ∈ ⨅ i, s i) ↔ ∃ I : set ι, finite I ∧ ∃ V : I → set α, (∀ i, V i ∈ s i) ∧ U = ⋂ i, V i := begin split, { rw [infi_eq_generate, mem_generate_iff], rintro ⟨t, tsub, tfin, tinter⟩, rcases eq_finite_Union_of_finite_subset_Union tfin tsub with ⟨I, Ifin, σ, σfin, σsub, rfl⟩, rw sInter_Union at tinter, set V := λ i, U ∪ ⋂₀ σ i with hV, have V_in : ∀ i, V i ∈ s i, { rintro i, have : (⋂₀ σ i) ∈ s i, { rw sInter_mem (σfin _), apply σsub }, exact mem_of_superset this (subset_union_right _ _) }, refine ⟨I, Ifin, V, V_in, _⟩, rwa [hV, ← union_Inter, union_eq_self_of_subset_right] }, { rintro ⟨I, Ifin, V, V_in, rfl⟩, exact mem_infi_of_Inter Ifin V_in subset.rfl } end lemma mem_infi' {ι} {s : ι → filter α} {U : set α} : (U ∈ ⨅ i, s i) ↔ ∃ I : set ι, finite I ∧ ∃ V : ι → set α, (∀ i, V i ∈ s i) ∧ (∀ i ∉ I, V i = univ) ∧ (U = ⋂ i ∈ I, V i) ∧ U = ⋂ i, V i := begin simp only [mem_infi, set_coe.forall', bInter_eq_Inter], refine ⟨_, λ ⟨I, If, V, hVs, _, hVU, _⟩, ⟨I, If, λ i, V i, λ i, hVs i, hVU⟩⟩, rintro ⟨I, If, V, hV, rfl⟩, refine ⟨I, If, λ i, if hi : i ∈ I then V ⟨i, hi⟩ else univ, λ i, _, λ i hi, _, _⟩, { split_ifs, exacts [hV _, univ_mem] }, { exact dif_neg hi }, { simp [Inter_dite, bInter_eq_Inter] } end lemma exists_Inter_of_mem_infi {ι : Type*} {α : Type*} {f : ι → filter α} {s} (hs : s ∈ ⨅ i, f i) : ∃ t : ι → set α, (∀ i, t i ∈ f i) ∧ s = ⋂ i, t i := let ⟨I, If, V, hVs, hV', hVU, hVU'⟩ := mem_infi'.1 hs in ⟨V, hVs, hVU'⟩ lemma mem_infi_of_fintype {ι : Type*} [fintype ι] {α : Type*} {f : ι → filter α} (s) : s ∈ (⨅ i, f i) ↔ ∃ t : ι → set α, (∀ i, t i ∈ f i) ∧ s = ⋂ i, t i := begin refine ⟨exists_Inter_of_mem_infi, _⟩, rintro ⟨t, ht, rfl⟩, exact Inter_mem.2 (λ i, mem_infi_of_mem i (ht i)) end @[simp] lemma le_principal_iff {s : set α} {f : filter α} : f ≤ 𝓟 s ↔ s ∈ f := show (∀ {t}, s ⊆ t → t ∈ f) ↔ s ∈ f, from ⟨λ h, h (subset.refl s), λ hs t ht, mem_of_superset hs ht⟩ lemma principal_mono {s t : set α} : 𝓟 s ≤ 𝓟 t ↔ s ⊆ t := by simp only [le_principal_iff, iff_self, mem_principal] @[mono] lemma monotone_principal : monotone (𝓟 : set α → filter α) := λ _ _, principal_mono.2 @[simp] lemma principal_eq_iff_eq {s t : set α} : 𝓟 s = 𝓟 t ↔ s = t := by simp only [le_antisymm_iff, le_principal_iff, mem_principal]; refl @[simp] lemma join_principal_eq_Sup {s : set (filter α)} : join (𝓟 s) = Sup s := rfl @[simp] lemma principal_univ : 𝓟 (univ : set α) = ⊤ := top_unique $ by simp only [le_principal_iff, mem_top, eq_self_iff_true] @[simp] lemma principal_empty : 𝓟 (∅ : set α) = ⊥ := bot_unique $ λ s _, empty_subset _ lemma generate_eq_binfi (S : set (set α)) : generate S = ⨅ s ∈ S, 𝓟 s := eq_of_forall_le_iff $ λ f, by simp [sets_iff_generate, le_principal_iff, subset_def] /-! ### Lattice equations -/ lemma empty_mem_iff_bot {f : filter α} : ∅ ∈ f ↔ f = ⊥ := ⟨λ h, bot_unique $ λ s _, mem_of_superset h (empty_subset s), λ h, h.symm ▸ mem_bot⟩ lemma nonempty_of_mem {f : filter α} [hf : ne_bot f] {s : set α} (hs : s ∈ f) : s.nonempty := s.eq_empty_or_nonempty.elim (λ h, absurd hs (h.symm ▸ mt empty_mem_iff_bot.mp hf.1)) id lemma ne_bot.nonempty_of_mem {f : filter α} (hf : ne_bot f) {s : set α} (hs : s ∈ f) : s.nonempty := @nonempty_of_mem α f hf s hs @[simp] lemma empty_not_mem (f : filter α) [ne_bot f] : ¬(∅ ∈ f) := λ h, (nonempty_of_mem h).ne_empty rfl lemma nonempty_of_ne_bot (f : filter α) [ne_bot f] : nonempty α := nonempty_of_exists $ nonempty_of_mem (univ_mem : univ ∈ f) lemma compl_not_mem {f : filter α} {s : set α} [ne_bot f] (h : s ∈ f) : sᶜ ∉ f := λ hsc, (nonempty_of_mem (inter_mem h hsc)).ne_empty $ inter_compl_self s lemma filter_eq_bot_of_is_empty [is_empty α] (f : filter α) : f = ⊥ := empty_mem_iff_bot.mp $ univ_mem' is_empty_elim lemma disjoint_of_disjoint_of_mem {f g : filter α} {s t : set α} (h : disjoint s t) (hs : s ∈ f) (ht : t ∈ g) : disjoint f g := begin refine le_of_eq (empty_mem_iff_bot.1 _), rw [← set.disjoint_iff_inter_eq_empty.1 h], exact inter_mem_inf hs ht end /-- There is exactly one filter on an empty type. --/ -- TODO[gh-6025]: make this globally an instance once safe to do so local attribute [instance] protected def unique [is_empty α] : unique (filter α) := { default := ⊥, uniq := filter_eq_bot_of_is_empty } lemma forall_mem_nonempty_iff_ne_bot {f : filter α} : (∀ (s : set α), s ∈ f → s.nonempty) ↔ ne_bot f := ⟨λ h, ⟨λ hf, empty_not_nonempty (h ∅ $ hf.symm ▸ mem_bot)⟩, @nonempty_of_mem _ _⟩ lemma nontrivial_iff_nonempty : nontrivial (filter α) ↔ nonempty α := ⟨λ ⟨⟨f, g, hfg⟩⟩, by_contra $ λ h, hfg $ by haveI : is_empty α := not_nonempty_iff.1 h; exact subsingleton.elim _ _, λ ⟨x⟩, ⟨⟨⊤, ⊥, ne_bot.ne $ forall_mem_nonempty_iff_ne_bot.1 $ λ s hs, by rwa [mem_top.1 hs, ← nonempty_iff_univ_nonempty]⟩⟩⟩ lemma eq_Inf_of_mem_iff_exists_mem {S : set (filter α)} {l : filter α} (h : ∀ {s}, s ∈ l ↔ ∃ f ∈ S, s ∈ f) : l = Inf S := le_antisymm (le_Inf $ λ f hf s hs, h.2 ⟨f, hf, hs⟩) (λ s hs, let ⟨f, hf, hs⟩ := h.1 hs in (Inf_le hf : Inf S ≤ f) hs) lemma eq_infi_of_mem_iff_exists_mem {f : ι → filter α} {l : filter α} (h : ∀ {s}, s ∈ l ↔ ∃ i, s ∈ f i) : l = infi f := eq_Inf_of_mem_iff_exists_mem $ λ s, h.trans exists_range_iff.symm lemma eq_binfi_of_mem_iff_exists_mem {f : ι → filter α} {p : ι → Prop} {l : filter α} (h : ∀ {s}, s ∈ l ↔ ∃ i (_ : p i), s ∈ f i) : l = ⨅ i (_ : p i), f i := begin rw [infi_subtype'], apply eq_infi_of_mem_iff_exists_mem, intro s, exact h.trans ⟨λ ⟨i, pi, si⟩, ⟨⟨i, pi⟩, si⟩, λ ⟨⟨i, pi⟩, si⟩, ⟨i, pi, si⟩⟩ end lemma infi_sets_eq {f : ι → filter α} (h : directed (≥) f) [ne : nonempty ι] : (infi f).sets = (⋃ i, (f i).sets) := let ⟨i⟩ := ne, u := { filter . sets := (⋃ i, (f i).sets), univ_sets := by simp only [mem_Union]; exact ⟨i, univ_mem⟩, sets_of_superset := by simp only [mem_Union, exists_imp_distrib]; intros x y i hx hxy; exact ⟨i, mem_of_superset hx hxy⟩, inter_sets := begin simp only [mem_Union, exists_imp_distrib], intros x y a hx b hy, rcases h a b with ⟨c, ha, hb⟩, exact ⟨c, inter_mem (ha hx) (hb hy)⟩ end } in have u = infi f, from eq_infi_of_mem_iff_exists_mem (λ s, by simp only [filter.mem_mk, mem_Union, filter.mem_sets]), congr_arg filter.sets this.symm lemma mem_infi_of_directed {f : ι → filter α} (h : directed (≥) f) [nonempty ι] (s) : s ∈ infi f ↔ ∃ i, s ∈ f i := by simp only [← filter.mem_sets, infi_sets_eq h, mem_Union] lemma mem_binfi_of_directed {f : β → filter α} {s : set β} (h : directed_on (f ⁻¹'o (≥)) s) (ne : s.nonempty) {t : set α} : t ∈ (⨅ i ∈ s, f i) ↔ ∃ i ∈ s, t ∈ f i := by haveI : nonempty {x // x ∈ s} := ne.to_subtype; erw [infi_subtype', mem_infi_of_directed h.directed_coe, subtype.exists]; refl lemma binfi_sets_eq {f : β → filter α} {s : set β} (h : directed_on (f ⁻¹'o (≥)) s) (ne : s.nonempty) : (⨅ i ∈ s, f i).sets = ⋃ i ∈ s, (f i).sets := ext $ λ t, by simp [mem_binfi_of_directed h ne] lemma infi_sets_eq_finite {ι : Type*} (f : ι → filter α) : (⨅ i, f i).sets = (⋃ t : finset ι, (⨅ i ∈ t, f i).sets) := begin rw [infi_eq_infi_finset, infi_sets_eq], exact (directed_of_sup $ λ s₁ s₂ hs, infi_le_infi $ λ i, infi_le_infi_const $ λ h, hs h), end lemma infi_sets_eq_finite' (f : ι → filter α) : (⨅ i, f i).sets = (⋃ t : finset (plift ι), (⨅ i ∈ t, f (plift.down i)).sets) := by { rw [← infi_sets_eq_finite, ← equiv.plift.surjective.infi_comp], refl } lemma mem_infi_finite {ι : Type*} {f : ι → filter α} (s) : s ∈ infi f ↔ ∃ t : finset ι, s ∈ ⨅ i ∈ t, f i := (set.ext_iff.1 (infi_sets_eq_finite f) s).trans mem_Union lemma mem_infi_finite' {f : ι → filter α} (s) : s ∈ infi f ↔ ∃ t : finset (plift ι), s ∈ ⨅ i ∈ t, f (plift.down i) := (set.ext_iff.1 (infi_sets_eq_finite' f) s).trans mem_Union @[simp] lemma sup_join {f₁ f₂ : filter (filter α)} : (join f₁ ⊔ join f₂) = join (f₁ ⊔ f₂) := filter.ext $ λ x, by simp only [mem_sup, mem_join] @[simp] lemma supr_join {ι : Sort w} {f : ι → filter (filter α)} : (⨆ x, join (f x)) = join (⨆ x, f x) := filter.ext $ λ x, by simp only [mem_supr, mem_join] instance : bounded_distrib_lattice (filter α) := { le_sup_inf := begin intros x y z s, simp only [and_assoc, mem_inf_iff, mem_sup, exists_prop, exists_imp_distrib, and_imp], rintro hs t₁ ht₁ t₂ ht₂ rfl, exact ⟨t₁, x.sets_of_superset hs (inter_subset_left t₁ t₂), ht₁, t₂, x.sets_of_superset hs (inter_subset_right t₁ t₂), ht₂, rfl⟩ end, ..filter.complete_lattice } /- the complementary version with ⨆ i, f ⊓ g i does not hold! -/ lemma infi_sup_left {f : filter α} {g : ι → filter α} : (⨅ x, f ⊔ g x) = f ⊔ infi g := begin refine le_antisymm _ (le_infi $ λ i, sup_le_sup_left (infi_le _ _) _), rintro t ⟨h₁, h₂⟩, rw [infi_sets_eq_finite'] at h₂, simp only [mem_Union, (finset.inf_eq_infi _ _).symm] at h₂, rcases h₂ with ⟨s, hs⟩, suffices : (⨅ i, f ⊔ g i) ≤ f ⊔ s.inf (λ i, g i.down), { exact this ⟨h₁, hs⟩ }, refine finset.induction_on s _ _, { exact le_sup_of_le_right le_top }, { rintro ⟨i⟩ s his ih, rw [finset.inf_insert, sup_inf_left], exact le_inf (infi_le _ _) ih } end lemma infi_sup_right {f : filter α} {g : ι → filter α} : (⨅ x, g x ⊔ f) = infi g ⊔ f := by simp [sup_comm, ← infi_sup_left] lemma binfi_sup_right (p : ι → Prop) (f : ι → filter α) (g : filter α) : (⨅ i (h : p i), (f i ⊔ g)) = (⨅ i (h : p i), f i) ⊔ g := by rw [infi_subtype', infi_sup_right, infi_subtype'] lemma binfi_sup_left (p : ι → Prop) (f : ι → filter α) (g : filter α) : (⨅ i (h : p i), (g ⊔ f i)) = g ⊔ (⨅ i (h : p i), f i) := by rw [infi_subtype', infi_sup_left, infi_subtype'] lemma mem_infi_finset {s : finset α} {f : α → filter β} {t : set β} : t ∈ (⨅ a ∈ s, f a) ↔ (∃ p : α → set β, (∀ a ∈ s, p a ∈ f a) ∧ t = ⋂ a ∈ s, p a) := begin simp only [← finset.set_bInter_coe, bInter_eq_Inter, infi_subtype'], refine ⟨λ h, _, _⟩, { rcases (mem_infi_of_fintype _).1 h with ⟨p, hp, rfl⟩, refine ⟨λ a, if h : a ∈ s then p ⟨a, h⟩ else univ, λ a ha, by simpa [ha] using hp ⟨a, ha⟩, _⟩, refine Inter_congr id surjective_id _, rintro ⟨a, ha⟩, simp [ha] }, { rintro ⟨p, hpf, rfl⟩, exact Inter_mem.2 (λ a, mem_infi_of_mem a (hpf a a.2)) } end /-- If `f : ι → filter α` is directed, `ι` is not empty, and `∀ i, f i ≠ ⊥`, then `infi f ≠ ⊥`. See also `infi_ne_bot_of_directed` for a version assuming `nonempty α` instead of `nonempty ι`. -/ lemma infi_ne_bot_of_directed' {f : ι → filter α} [nonempty ι] (hd : directed (≥) f) (hb : ∀ i, ne_bot (f i)) : ne_bot (infi f) := ⟨begin intro h, have he : ∅ ∈ (infi f), from h.symm ▸ (mem_bot : ∅ ∈ (⊥ : filter α)), obtain ⟨i, hi⟩ : ∃ i, ∅ ∈ f i, from (mem_infi_of_directed hd ∅).1 he, exact (hb i).ne (empty_mem_iff_bot.1 hi) end⟩ /-- If `f : ι → filter α` is directed, `α` is not empty, and `∀ i, f i ≠ ⊥`, then `infi f ≠ ⊥`. See also `infi_ne_bot_of_directed'` for a version assuming `nonempty ι` instead of `nonempty α`. -/ lemma infi_ne_bot_of_directed {f : ι → filter α} [hn : nonempty α] (hd : directed (≥) f) (hb : ∀ i, ne_bot (f i)) : ne_bot (infi f) := if hι : nonempty ι then @infi_ne_bot_of_directed' _ _ _ hι hd hb else ⟨λ h : infi f = ⊥, have univ ⊆ (∅ : set α), begin rw [←principal_mono, principal_univ, principal_empty, ←h], exact (le_infi $ λ i, false.elim $ hι ⟨i⟩) end, let ⟨x⟩ := hn in this (mem_univ x)⟩ lemma infi_ne_bot_iff_of_directed' {f : ι → filter α} [nonempty ι] (hd : directed (≥) f) : ne_bot (infi f) ↔ ∀ i, ne_bot (f i) := ⟨λ H i, H.mono (infi_le _ i), infi_ne_bot_of_directed' hd⟩ lemma infi_ne_bot_iff_of_directed {f : ι → filter α} [nonempty α] (hd : directed (≥) f) : ne_bot (infi f) ↔ (∀ i, ne_bot (f i)) := ⟨λ H i, H.mono (infi_le _ i), infi_ne_bot_of_directed hd⟩ @[elab_as_eliminator] lemma infi_sets_induct {f : ι → filter α} {s : set α} (hs : s ∈ infi f) {p : set α → Prop} (uni : p univ) (ins : ∀ {i s₁ s₂}, s₁ ∈ f i → p s₂ → p (s₁ ∩ s₂)) : p s := begin rw [mem_infi_finite'] at hs, simp only [← finset.inf_eq_infi] at hs, rcases hs with ⟨is, his⟩, revert s, refine finset.induction_on is _ _, { intros s hs, rwa [mem_top.1 hs] }, { rintro ⟨i⟩ js his ih s hs, rw [finset.inf_insert, mem_inf_iff] at hs, rcases hs with ⟨s₁, hs₁, s₂, hs₂, rfl⟩, exact ins hs₁ (ih hs₂) } end /-! #### `principal` equations -/ @[simp] lemma inf_principal {s t : set α} : 𝓟 s ⊓ 𝓟 t = 𝓟 (s ∩ t) := le_antisymm (by simp only [le_principal_iff, mem_inf_iff]; exact ⟨s, subset.rfl, t, subset.rfl, rfl⟩) (by simp [le_inf_iff, inter_subset_left, inter_subset_right]) @[simp] lemma sup_principal {s t : set α} : 𝓟 s ⊔ 𝓟 t = 𝓟 (s ∪ t) := filter.ext $ λ u, by simp only [union_subset_iff, mem_sup, mem_principal] @[simp] lemma supr_principal {ι : Sort w} {s : ι → set α} : (⨆ x, 𝓟 (s x)) = 𝓟 (⋃ i, s i) := filter.ext $ λ x, by simp only [mem_supr, mem_principal, Union_subset_iff] @[simp] lemma principal_eq_bot_iff {s : set α} : 𝓟 s = ⊥ ↔ s = ∅ := empty_mem_iff_bot.symm.trans $ mem_principal.trans subset_empty_iff @[simp] lemma principal_ne_bot_iff {s : set α} : ne_bot (𝓟 s) ↔ s.nonempty := ne_bot_iff.trans $ (not_congr principal_eq_bot_iff).trans ne_empty_iff_nonempty lemma is_compl_principal (s : set α) : is_compl (𝓟 s) (𝓟 sᶜ) := ⟨by simp only [inf_principal, inter_compl_self, principal_empty, le_refl], by simp only [sup_principal, union_compl_self, principal_univ, le_refl]⟩ theorem mem_inf_principal {f : filter α} {s t : set α} : s ∈ f ⊓ 𝓟 t ↔ {x | x ∈ t → x ∈ s} ∈ f := begin simp only [← le_principal_iff, (is_compl_principal s).le_left_iff, disjoint, inf_assoc, inf_principal, imp_iff_not_or], rw [← disjoint, ← (is_compl_principal (t ∩ sᶜ)).le_right_iff, compl_inter, compl_compl], refl end lemma supr_inf_principal (f : ι → filter α) (s : set α) : (⨆ i, f i ⊓ 𝓟 s) = (⨆ i, f i) ⊓ 𝓟 s := by { ext, simp only [mem_supr, mem_inf_principal] } lemma inf_principal_eq_bot {f : filter α} {s : set α} : f ⊓ 𝓟 s = ⊥ ↔ sᶜ ∈ f := by { rw [← empty_mem_iff_bot, mem_inf_principal], refl } lemma mem_of_eq_bot {f : filter α} {s : set α} (h : f ⊓ 𝓟 sᶜ = ⊥) : s ∈ f := by rwa [inf_principal_eq_bot, compl_compl] at h lemma diff_mem_inf_principal_compl {f : filter α} {s : set α} (hs : s ∈ f) (t : set α) : s \ t ∈ f ⊓ 𝓟 tᶜ := begin rw mem_inf_principal, filter_upwards [hs], intros a has hat, exact ⟨has, hat⟩ end lemma principal_le_iff {s : set α} {f : filter α} : 𝓟 s ≤ f ↔ ∀ V ∈ f, s ⊆ V := begin change (∀ V, V ∈ f → V ∈ _) ↔ _, simp_rw mem_principal, end @[simp] lemma infi_principal_finset {ι : Type w} (s : finset ι) (f : ι → set α) : (⨅ i ∈ s, 𝓟 (f i)) = 𝓟 (⋂ i ∈ s, f i) := begin induction s using finset.induction_on with i s hi hs, { simp }, { rw [finset.infi_insert, finset.set_bInter_insert, hs, inf_principal] }, end @[simp] lemma infi_principal_fintype {ι : Type w} [fintype ι] (f : ι → set α) : (⨅ i, 𝓟 (f i)) = 𝓟 (⋂ i, f i) := by simpa using infi_principal_finset finset.univ f lemma infi_principal_finite {ι : Type w} {s : set ι} (hs : finite s) (f : ι → set α) : (⨅ i ∈ s, 𝓟 (f i)) = 𝓟 (⋂ i ∈ s, f i) := begin lift s to finset ι using hs, exact_mod_cast infi_principal_finset s f end end lattice @[mono] lemma join_mono {f₁ f₂ : filter (filter α)} (h : f₁ ≤ f₂) : join f₁ ≤ join f₂ := λ s hs, h hs /-! ### Eventually -/ /-- `f.eventually p` or `∀ᶠ x in f, p x` mean that `{x | p x} ∈ f`. E.g., `∀ᶠ x in at_top, p x` means that `p` holds true for sufficiently large `x`. -/ protected def eventually (p : α → Prop) (f : filter α) : Prop := {x | p x} ∈ f notation `∀ᶠ` binders ` in ` f `, ` r:(scoped p, filter.eventually p f) := r lemma eventually_iff {f : filter α} {P : α → Prop} : (∀ᶠ x in f, P x) ↔ {x | P x} ∈ f := iff.rfl protected lemma ext' {f₁ f₂ : filter α} (h : ∀ p : α → Prop, (∀ᶠ x in f₁, p x) ↔ (∀ᶠ x in f₂, p x)) : f₁ = f₂ := filter.ext h lemma eventually.filter_mono {f₁ f₂ : filter α} (h : f₁ ≤ f₂) {p : α → Prop} (hp : ∀ᶠ x in f₂, p x) : ∀ᶠ x in f₁, p x := h hp lemma eventually_of_mem {f : filter α} {P : α → Prop} {U : set α} (hU : U ∈ f) (h : ∀ x ∈ U, P x) : ∀ᶠ x in f, P x := mem_of_superset hU h protected lemma eventually.and {p q : α → Prop} {f : filter α} : f.eventually p → f.eventually q → ∀ᶠ x in f, p x ∧ q x := inter_mem @[simp] lemma eventually_true (f : filter α) : ∀ᶠ x in f, true := univ_mem lemma eventually_of_forall {p : α → Prop} {f : filter α} (hp : ∀ x, p x) : ∀ᶠ x in f, p x := univ_mem' hp @[simp] lemma eventually_false_iff_eq_bot {f : filter α} : (∀ᶠ x in f, false) ↔ f = ⊥ := empty_mem_iff_bot @[simp] lemma eventually_const {f : filter α} [t : ne_bot f] {p : Prop} : (∀ᶠ x in f, p) ↔ p := classical.by_cases (λ h : p, by simp [h]) (λ h, by simpa [h] using t.ne) lemma eventually_iff_exists_mem {p : α → Prop} {f : filter α} : (∀ᶠ x in f, p x) ↔ ∃ v ∈ f, ∀ y ∈ v, p y := exists_mem_subset_iff.symm lemma eventually.exists_mem {p : α → Prop} {f : filter α} (hp : ∀ᶠ x in f, p x) : ∃ v ∈ f, ∀ y ∈ v, p y := eventually_iff_exists_mem.1 hp lemma eventually.mp {p q : α → Prop} {f : filter α} (hp : ∀ᶠ x in f, p x) (hq : ∀ᶠ x in f, p x → q x) : ∀ᶠ x in f, q x := mp_mem hp hq lemma eventually.mono {p q : α → Prop} {f : filter α} (hp : ∀ᶠ x in f, p x) (hq : ∀ x, p x → q x) : ∀ᶠ x in f, q x := hp.mp (eventually_of_forall hq) @[simp] lemma eventually_and {p q : α → Prop} {f : filter α} : (∀ᶠ x in f, p x ∧ q x) ↔ (∀ᶠ x in f, p x) ∧ (∀ᶠ x in f, q x) := inter_mem_iff lemma eventually.congr {f : filter α} {p q : α → Prop} (h' : ∀ᶠ x in f, p x) (h : ∀ᶠ x in f, p x ↔ q x) : ∀ᶠ x in f, q x := h'.mp (h.mono $ λ x hx, hx.mp) lemma eventually_congr {f : filter α} {p q : α → Prop} (h : ∀ᶠ x in f, p x ↔ q x) : (∀ᶠ x in f, p x) ↔ (∀ᶠ x in f, q x) := ⟨λ hp, hp.congr h, λ hq, hq.congr $ by simpa only [iff.comm] using h⟩ @[simp] lemma eventually_all {ι} [fintype ι] {l} {p : ι → α → Prop} : (∀ᶠ x in l, ∀ i, p i x) ↔ ∀ i, ∀ᶠ x in l, p i x := by simpa only [filter.eventually, set_of_forall] using Inter_mem @[simp] lemma eventually_all_finite {ι} {I : set ι} (hI : I.finite) {l} {p : ι → α → Prop} : (∀ᶠ x in l, ∀ i ∈ I, p i x) ↔ (∀ i ∈ I, ∀ᶠ x in l, p i x) := by simpa only [filter.eventually, set_of_forall] using bInter_mem hI alias eventually_all_finite ← set.finite.eventually_all attribute [protected] set.finite.eventually_all @[simp] lemma eventually_all_finset {ι} (I : finset ι) {l} {p : ι → α → Prop} : (∀ᶠ x in l, ∀ i ∈ I, p i x) ↔ ∀ i ∈ I, ∀ᶠ x in l, p i x := I.finite_to_set.eventually_all alias eventually_all_finset ← finset.eventually_all attribute [protected] finset.eventually_all @[simp] lemma eventually_or_distrib_left {f : filter α} {p : Prop} {q : α → Prop} : (∀ᶠ x in f, p ∨ q x) ↔ (p ∨ ∀ᶠ x in f, q x) := classical.by_cases (λ h : p, by simp [h]) (λ h, by simp [h]) @[simp] lemma eventually_or_distrib_right {f : filter α} {p : α → Prop} {q : Prop} : (∀ᶠ x in f, p x ∨ q) ↔ ((∀ᶠ x in f, p x) ∨ q) := by simp only [or_comm _ q, eventually_or_distrib_left] @[simp] lemma eventually_imp_distrib_left {f : filter α} {p : Prop} {q : α → Prop} : (∀ᶠ x in f, p → q x) ↔ (p → ∀ᶠ x in f, q x) := by simp only [imp_iff_not_or, eventually_or_distrib_left] @[simp] lemma eventually_bot {p : α → Prop} : ∀ᶠ x in ⊥, p x := ⟨⟩ @[simp] lemma eventually_top {p : α → Prop} : (∀ᶠ x in ⊤, p x) ↔ (∀ x, p x) := iff.rfl @[simp] lemma eventually_sup {p : α → Prop} {f g : filter α} : (∀ᶠ x in f ⊔ g, p x) ↔ (∀ᶠ x in f, p x) ∧ (∀ᶠ x in g, p x) := iff.rfl @[simp] lemma eventually_Sup {p : α → Prop} {fs : set (filter α)} : (∀ᶠ x in Sup fs, p x) ↔ (∀ f ∈ fs, ∀ᶠ x in f, p x) := iff.rfl @[simp] lemma eventually_supr {p : α → Prop} {fs : β → filter α} : (∀ᶠ x in (⨆ b, fs b), p x) ↔ (∀ b, ∀ᶠ x in fs b, p x) := mem_supr @[simp] lemma eventually_principal {a : set α} {p : α → Prop} : (∀ᶠ x in 𝓟 a, p x) ↔ (∀ x ∈ a, p x) := iff.rfl lemma eventually_inf {f g : filter α} {p : α → Prop} : (∀ᶠ x in f ⊓ g, p x) ↔ ∃ (s ∈ f) (t ∈ g), ∀ x ∈ s ∩ t, p x := mem_inf_iff_superset theorem eventually_inf_principal {f : filter α} {p : α → Prop} {s : set α} : (∀ᶠ x in f ⊓ 𝓟 s, p x) ↔ ∀ᶠ x in f, x ∈ s → p x := mem_inf_principal /-! ### Frequently -/ /-- `f.frequently p` or `∃ᶠ x in f, p x` mean that `{x | ¬p x} ∉ f`. E.g., `∃ᶠ x in at_top, p x` means that there exist arbitrarily large `x` for which `p` holds true. -/ protected def frequently (p : α → Prop) (f : filter α) : Prop := ¬∀ᶠ x in f, ¬p x notation `∃ᶠ` binders ` in ` f `, ` r:(scoped p, filter.frequently p f) := r lemma eventually.frequently {f : filter α} [ne_bot f] {p : α → Prop} (h : ∀ᶠ x in f, p x) : ∃ᶠ x in f, p x := compl_not_mem h lemma frequently_of_forall {f : filter α} [ne_bot f] {p : α → Prop} (h : ∀ x, p x) : ∃ᶠ x in f, p x := eventually.frequently (eventually_of_forall h) lemma frequently.mp {p q : α → Prop} {f : filter α} (h : ∃ᶠ x in f, p x) (hpq : ∀ᶠ x in f, p x → q x) : ∃ᶠ x in f, q x := mt (λ hq, hq.mp $ hpq.mono $ λ x, mt) h lemma frequently.filter_mono {p : α → Prop} {f g : filter α} (h : ∃ᶠ x in f, p x) (hle : f ≤ g) : ∃ᶠ x in g, p x := mt (λ h', h'.filter_mono hle) h lemma frequently.mono {p q : α → Prop} {f : filter α} (h : ∃ᶠ x in f, p x) (hpq : ∀ x, p x → q x) : ∃ᶠ x in f, q x := h.mp (eventually_of_forall hpq) lemma frequently.and_eventually {p q : α → Prop} {f : filter α} (hp : ∃ᶠ x in f, p x) (hq : ∀ᶠ x in f, q x) : ∃ᶠ x in f, p x ∧ q x := begin refine mt (λ h, hq.mp $ h.mono _) hp, exact λ x hpq hq hp, hpq ⟨hp, hq⟩ end lemma eventually.and_frequently {p q : α → Prop} {f : filter α} (hp : ∀ᶠ x in f, p x) (hq : ∃ᶠ x in f, q x) : ∃ᶠ x in f, p x ∧ q x := by simpa only [and.comm] using hq.and_eventually hp lemma frequently.exists {p : α → Prop} {f : filter α} (hp : ∃ᶠ x in f, p x) : ∃ x, p x := begin by_contradiction H, replace H : ∀ᶠ x in f, ¬ p x, from eventually_of_forall (not_exists.1 H), exact hp H end lemma eventually.exists {p : α → Prop} {f : filter α} [ne_bot f] (hp : ∀ᶠ x in f, p x) : ∃ x, p x := hp.frequently.exists lemma frequently_iff_forall_eventually_exists_and {p : α → Prop} {f : filter α} : (∃ᶠ x in f, p x) ↔ ∀ {q : α → Prop}, (∀ᶠ x in f, q x) → ∃ x, p x ∧ q x := ⟨λ hp q hq, (hp.and_eventually hq).exists, λ H hp, by simpa only [and_not_self, exists_false] using H hp⟩ lemma frequently_iff {f : filter α} {P : α → Prop} : (∃ᶠ x in f, P x) ↔ ∀ {U}, U ∈ f → ∃ x ∈ U, P x := begin rw frequently_iff_forall_eventually_exists_and, split ; intro h, { intros U U_in, simpa [exists_prop, and_comm] using h U_in }, { intros H H', simpa [and_comm] using h H' }, end @[simp] lemma not_eventually {p : α → Prop} {f : filter α} : (¬ ∀ᶠ x in f, p x) ↔ (∃ᶠ x in f, ¬ p x) := by simp [filter.frequently] @[simp] lemma not_frequently {p : α → Prop} {f : filter α} : (¬ ∃ᶠ x in f, p x) ↔ (∀ᶠ x in f, ¬ p x) := by simp only [filter.frequently, not_not] @[simp] lemma frequently_true_iff_ne_bot (f : filter α) : (∃ᶠ x in f, true) ↔ ne_bot f := by simp [filter.frequently, -not_eventually, eventually_false_iff_eq_bot, ne_bot_iff] @[simp] lemma frequently_false (f : filter α) : ¬ ∃ᶠ x in f, false := by simp @[simp] lemma frequently_const {f : filter α} [ne_bot f] {p : Prop} : (∃ᶠ x in f, p) ↔ p := classical.by_cases (λ h : p, by simpa [h]) (λ h, by simp [h]) @[simp] lemma frequently_or_distrib {f : filter α} {p q : α → Prop} : (∃ᶠ x in f, p x ∨ q x) ↔ (∃ᶠ x in f, p x) ∨ (∃ᶠ x in f, q x) := by simp only [filter.frequently, ← not_and_distrib, not_or_distrib, eventually_and] lemma frequently_or_distrib_left {f : filter α} [ne_bot f] {p : Prop} {q : α → Prop} : (∃ᶠ x in f, p ∨ q x) ↔ (p ∨ ∃ᶠ x in f, q x) := by simp lemma frequently_or_distrib_right {f : filter α} [ne_bot f] {p : α → Prop} {q : Prop} : (∃ᶠ x in f, p x ∨ q) ↔ (∃ᶠ x in f, p x) ∨ q := by simp @[simp] lemma frequently_imp_distrib {f : filter α} {p q : α → Prop} : (∃ᶠ x in f, p x → q x) ↔ ((∀ᶠ x in f, p x) → ∃ᶠ x in f, q x) := by simp [imp_iff_not_or, not_eventually, frequently_or_distrib] lemma frequently_imp_distrib_left {f : filter α} [ne_bot f] {p : Prop} {q : α → Prop} : (∃ᶠ x in f, p → q x) ↔ (p → ∃ᶠ x in f, q x) := by simp lemma frequently_imp_distrib_right {f : filter α} [ne_bot f] {p : α → Prop} {q : Prop} : (∃ᶠ x in f, p x → q) ↔ ((∀ᶠ x in f, p x) → q) := by simp @[simp] lemma eventually_imp_distrib_right {f : filter α} {p : α → Prop} {q : Prop} : (∀ᶠ x in f, p x → q) ↔ ((∃ᶠ x in f, p x) → q) := by simp only [imp_iff_not_or, eventually_or_distrib_right, not_frequently] @[simp] lemma frequently_and_distrib_left {f : filter α} {p : Prop} {q : α → Prop} : (∃ᶠ x in f, p ∧ q x) ↔ (p ∧ ∃ᶠ x in f, q x) := by simp only [filter.frequently, not_and, eventually_imp_distrib_left, not_imp] @[simp] lemma frequently_and_distrib_right {f : filter α} {p : α → Prop} {q : Prop} : (∃ᶠ x in f, p x ∧ q) ↔ ((∃ᶠ x in f, p x) ∧ q) := by simp only [and_comm _ q, frequently_and_distrib_left] @[simp] lemma frequently_bot {p : α → Prop} : ¬ ∃ᶠ x in ⊥, p x := by simp @[simp] lemma frequently_top {p : α → Prop} : (∃ᶠ x in ⊤, p x) ↔ (∃ x, p x) := by simp [filter.frequently] @[simp] lemma frequently_principal {a : set α} {p : α → Prop} : (∃ᶠ x in 𝓟 a, p x) ↔ (∃ x ∈ a, p x) := by simp [filter.frequently, not_forall] lemma frequently_sup {p : α → Prop} {f g : filter α} : (∃ᶠ x in f ⊔ g, p x) ↔ (∃ᶠ x in f, p x) ∨ (∃ᶠ x in g, p x) := by simp only [filter.frequently, eventually_sup, not_and_distrib] @[simp] lemma frequently_Sup {p : α → Prop} {fs : set (filter α)} : (∃ᶠ x in Sup fs, p x) ↔ (∃ f ∈ fs, ∃ᶠ x in f, p x) := by simp [filter.frequently, -not_eventually, not_forall] @[simp] lemma frequently_supr {p : α → Prop} {fs : β → filter α} : (∃ᶠ x in (⨆ b, fs b), p x) ↔ (∃ b, ∃ᶠ x in fs b, p x) := by simp [filter.frequently, -not_eventually, not_forall] /-! ### Relation “eventually equal” -/ /-- Two functions `f` and `g` are *eventually equal* along a filter `l` if the set of `x` such that `f x = g x` belongs to `l`. -/ def eventually_eq (l : filter α) (f g : α → β) : Prop := ∀ᶠ x in l, f x = g x notation f ` =ᶠ[`:50 l:50 `] `:0 g:50 := eventually_eq l f g lemma eventually_eq.eventually {l : filter α} {f g : α → β} (h : f =ᶠ[l] g) : ∀ᶠ x in l, f x = g x := h lemma eventually_eq.rw {l : filter α} {f g : α → β} (h : f =ᶠ[l] g) (p : α → β → Prop) (hf : ∀ᶠ x in l, p x (f x)) : ∀ᶠ x in l, p x (g x) := hf.congr $ h.mono $ λ x hx, hx ▸ iff.rfl lemma eventually_eq_set {s t : set α} {l : filter α} : s =ᶠ[l] t ↔ ∀ᶠ x in l, x ∈ s ↔ x ∈ t := eventually_congr $ eventually_of_forall $ λ x, ⟨eq.to_iff, iff.to_eq⟩ alias eventually_eq_set ↔ filter.eventually_eq.mem_iff filter.eventually.set_eq lemma eventually_eq.exists_mem {l : filter α} {f g : α → β} (h : f =ᶠ[l] g) : ∃ s ∈ l, eq_on f g s := h.exists_mem lemma eventually_eq_of_mem {l : filter α} {f g : α → β} {s : set α} (hs : s ∈ l) (h : eq_on f g s) : f =ᶠ[l] g := eventually_of_mem hs h lemma eventually_eq_iff_exists_mem {l : filter α} {f g : α → β} : (f =ᶠ[l] g) ↔ ∃ s ∈ l, eq_on f g s := eventually_iff_exists_mem lemma eventually_eq.filter_mono {l l' : filter α} {f g : α → β} (h₁ : f =ᶠ[l] g) (h₂ : l' ≤ l) : f =ᶠ[l'] g := h₂ h₁ @[refl] lemma eventually_eq.refl (l : filter α) (f : α → β) : f =ᶠ[l] f := eventually_of_forall $ λ x, rfl lemma eventually_eq.rfl {l : filter α} {f : α → β} : f =ᶠ[l] f := eventually_eq.refl l f @[symm] lemma eventually_eq.symm {f g : α → β} {l : filter α} (H : f =ᶠ[l] g) : g =ᶠ[l] f := H.mono $ λ _, eq.symm @[trans] lemma eventually_eq.trans {f g h : α → β} {l : filter α} (H₁ : f =ᶠ[l] g) (H₂ : g =ᶠ[l] h) : f =ᶠ[l] h := H₂.rw (λ x y, f x = y) H₁ lemma eventually_eq.prod_mk {l} {f f' : α → β} (hf : f =ᶠ[l] f') {g g' : α → γ} (hg : g =ᶠ[l] g') : (λ x, (f x, g x)) =ᶠ[l] (λ x, (f' x, g' x)) := hf.mp $ hg.mono $ by { intros, simp only * } lemma eventually_eq.fun_comp {f g : α → β} {l : filter α} (H : f =ᶠ[l] g) (h : β → γ) : (h ∘ f) =ᶠ[l] (h ∘ g) := H.mono $ λ x hx, congr_arg h hx lemma eventually_eq.comp₂ {δ} {f f' : α → β} {g g' : α → γ} {l} (Hf : f =ᶠ[l] f') (h : β → γ → δ) (Hg : g =ᶠ[l] g') : (λ x, h (f x) (g x)) =ᶠ[l] (λ x, h (f' x) (g' x)) := (Hf.prod_mk Hg).fun_comp (uncurry h) @[to_additive] lemma eventually_eq.mul [has_mul β] {f f' g g' : α → β} {l : filter α} (h : f =ᶠ[l] g) (h' : f' =ᶠ[l] g') : ((λ x, f x * f' x) =ᶠ[l] (λ x, g x * g' x)) := h.comp₂ (*) h' @[to_additive] lemma eventually_eq.inv [has_inv β] {f g : α → β} {l : filter α} (h : f =ᶠ[l] g) : ((λ x, (f x)⁻¹) =ᶠ[l] (λ x, (g x)⁻¹)) := h.fun_comp has_inv.inv lemma eventually_eq.div [group_with_zero β] {f f' g g' : α → β} {l : filter α} (h : f =ᶠ[l] g) (h' : f' =ᶠ[l] g') : ((λ x, f x / f' x) =ᶠ[l] (λ x, g x / g' x)) := by simpa only [div_eq_mul_inv] using h.mul h'.inv lemma eventually_eq.div' [group β] {f f' g g' : α → β} {l : filter α} (h : f =ᶠ[l] g) (h' : f' =ᶠ[l] g') : ((λ x, f x / f' x) =ᶠ[l] (λ x, g x / g' x)) := by simpa only [div_eq_mul_inv] using h.mul h'.inv lemma eventually_eq.sub [add_group β] {f f' g g' : α → β} {l : filter α} (h : f =ᶠ[l] g) (h' : f' =ᶠ[l] g') : ((λ x, f x - f' x) =ᶠ[l] (λ x, g x - g' x)) := by simpa only [sub_eq_add_neg] using h.add h'.neg lemma eventually_eq.inter {s t s' t' : set α} {l : filter α} (h : s =ᶠ[l] t) (h' : s' =ᶠ[l] t') : (s ∩ s' : set α) =ᶠ[l] (t ∩ t' : set α) := h.comp₂ (∧) h' lemma eventually_eq.union {s t s' t' : set α} {l : filter α} (h : s =ᶠ[l] t) (h' : s' =ᶠ[l] t') : (s ∪ s' : set α) =ᶠ[l] (t ∪ t' : set α) := h.comp₂ (∨) h' lemma eventually_eq.compl {s t : set α} {l : filter α} (h : s =ᶠ[l] t) : (sᶜ : set α) =ᶠ[l] (tᶜ : set α) := h.fun_comp not lemma eventually_eq.diff {s t s' t' : set α} {l : filter α} (h : s =ᶠ[l] t) (h' : s' =ᶠ[l] t') : (s \ s' : set α) =ᶠ[l] (t \ t' : set α) := h.inter h'.compl lemma eventually_eq_empty {s : set α} {l : filter α} : s =ᶠ[l] (∅ : set α) ↔ ∀ᶠ x in l, x ∉ s := eventually_eq_set.trans $ by simp lemma inter_eventually_eq_left {s t : set α} {l : filter α} : (s ∩ t : set α) =ᶠ[l] s ↔ ∀ᶠ x in l, x ∈ s → x ∈ t := by simp only [eventually_eq_set, mem_inter_eq, and_iff_left_iff_imp] lemma inter_eventually_eq_right {s t : set α} {l : filter α} : (s ∩ t : set α) =ᶠ[l] t ↔ ∀ᶠ x in l, x ∈ t → x ∈ s := by rw [inter_comm, inter_eventually_eq_left] @[simp] lemma eventually_eq_principal {s : set α} {f g : α → β} : f =ᶠ[𝓟 s] g ↔ eq_on f g s := iff.rfl lemma eventually_eq_inf_principal_iff {F : filter α} {s : set α} {f g : α → β} : (f =ᶠ[F ⊓ 𝓟 s] g) ↔ ∀ᶠ x in F, x ∈ s → f x = g x := eventually_inf_principal lemma eventually_eq.sub_eq [add_group β] {f g : α → β} {l : filter α} (h : f =ᶠ[l] g) : f - g =ᶠ[l] 0 := by simpa using (eventually_eq.sub (eventually_eq.refl l f) h).symm lemma eventually_eq_iff_sub [add_group β] {f g : α → β} {l : filter α} : f =ᶠ[l] g ↔ f - g =ᶠ[l] 0 := ⟨λ h, h.sub_eq, λ h, by simpa using h.add (eventually_eq.refl l g)⟩ section has_le variables [has_le β] {l : filter α} /-- A function `f` is eventually less than or equal to a function `g` at a filter `l`. -/ def eventually_le (l : filter α) (f g : α → β) : Prop := ∀ᶠ x in l, f x ≤ g x notation f ` ≤ᶠ[`:50 l:50 `] `:0 g:50 := eventually_le l f g lemma eventually_le.congr {f f' g g' : α → β} (H : f ≤ᶠ[l] g) (hf : f =ᶠ[l] f') (hg : g =ᶠ[l] g') : f' ≤ᶠ[l] g' := H.mp $ hg.mp $ hf.mono $ λ x hf hg H, by rwa [hf, hg] at H lemma eventually_le_congr {f f' g g' : α → β} (hf : f =ᶠ[l] f') (hg : g =ᶠ[l] g') : f ≤ᶠ[l] g ↔ f' ≤ᶠ[l] g' := ⟨λ H, H.congr hf hg, λ H, H.congr hf.symm hg.symm⟩ end has_le section preorder variables [preorder β] {l : filter α} {f g h : α → β} lemma eventually_eq.le (h : f =ᶠ[l] g) : f ≤ᶠ[l] g := h.mono $ λ x, le_of_eq @[refl] lemma eventually_le.refl (l : filter α) (f : α → β) : f ≤ᶠ[l] f := eventually_eq.rfl.le lemma eventually_le.rfl : f ≤ᶠ[l] f := eventually_le.refl l f @[trans] lemma eventually_le.trans (H₁ : f ≤ᶠ[l] g) (H₂ : g ≤ᶠ[l] h) : f ≤ᶠ[l] h := H₂.mp $ H₁.mono $ λ x, le_trans @[trans] lemma eventually_eq.trans_le (H₁ : f =ᶠ[l] g) (H₂ : g ≤ᶠ[l] h) : f ≤ᶠ[l] h := H₁.le.trans H₂ @[trans] lemma eventually_le.trans_eq (H₁ : f ≤ᶠ[l] g) (H₂ : g =ᶠ[l] h) : f ≤ᶠ[l] h := H₁.trans H₂.le end preorder lemma eventually_le.antisymm [partial_order β] {l : filter α} {f g : α → β} (h₁ : f ≤ᶠ[l] g) (h₂ : g ≤ᶠ[l] f) : f =ᶠ[l] g := h₂.mp $ h₁.mono $ λ x, le_antisymm lemma eventually_le_antisymm_iff [partial_order β] {l : filter α} {f g : α → β} : f =ᶠ[l] g ↔ f ≤ᶠ[l] g ∧ g ≤ᶠ[l] f := by simp only [eventually_eq, eventually_le, le_antisymm_iff, eventually_and] lemma eventually_le.le_iff_eq [partial_order β] {l : filter α} {f g : α → β} (h : f ≤ᶠ[l] g) : g ≤ᶠ[l] f ↔ g =ᶠ[l] f := ⟨λ h', h'.antisymm h, eventually_eq.le⟩ lemma eventually.ne_of_lt [preorder β] {l : filter α} {f g : α → β} (h : ∀ᶠ x in l, f x < g x) : ∀ᶠ x in l, f x ≠ g x := h.mono (λ x hx, hx.ne) lemma eventually.ne_top_of_lt [order_top β] {l : filter α} {f g : α → β} (h : ∀ᶠ x in l, f x < g x) : ∀ᶠ x in l, f x ≠ ⊤ := h.mono (λ x hx, hx.ne_top) lemma eventually.lt_top_of_ne [order_top β] {l : filter α} {f : α → β} (h : ∀ᶠ x in l, f x ≠ ⊤) : ∀ᶠ x in l, f x < ⊤ := h.mono (λ x hx, hx.lt_top) lemma eventually.lt_top_iff_ne_top [order_top β] {l : filter α} {f : α → β} : (∀ᶠ x in l, f x < ⊤) ↔ ∀ᶠ x in l, f x ≠ ⊤ := ⟨eventually.ne_of_lt, eventually.lt_top_of_ne⟩ @[mono] lemma eventually_le.inter {s t s' t' : set α} {l : filter α} (h : s ≤ᶠ[l] t) (h' : s' ≤ᶠ[l] t') : (s ∩ s' : set α) ≤ᶠ[l] (t ∩ t' : set α) := h'.mp $ h.mono $ λ x, and.imp @[mono] lemma eventually_le.union {s t s' t' : set α} {l : filter α} (h : s ≤ᶠ[l] t) (h' : s' ≤ᶠ[l] t') : (s ∪ s' : set α) ≤ᶠ[l] (t ∪ t' : set α) := h'.mp $ h.mono $ λ x, or.imp @[mono] lemma eventually_le.compl {s t : set α} {l : filter α} (h : s ≤ᶠ[l] t) : (tᶜ : set α) ≤ᶠ[l] (sᶜ : set α) := h.mono $ λ x, mt @[mono] lemma eventually_le.diff {s t s' t' : set α} {l : filter α} (h : s ≤ᶠ[l] t) (h' : t' ≤ᶠ[l] s') : (s \ s' : set α) ≤ᶠ[l] (t \ t' : set α) := h.inter h'.compl lemma join_le {f : filter (filter α)} {l : filter α} (h : ∀ᶠ m in f, m ≤ l) : join f ≤ l := λ s hs, h.mono $ λ m hm, hm hs /-! ### Push-forwards, pull-backs, and the monad structure -/ section map /-- The forward map of a filter -/ def map (m : α → β) (f : filter α) : filter β := { sets := preimage m ⁻¹' f.sets, univ_sets := univ_mem, sets_of_superset := λ s t hs st, mem_of_superset hs $ preimage_mono st, inter_sets := λ s t hs ht, inter_mem hs ht } @[simp] lemma map_principal {s : set α} {f : α → β} : map f (𝓟 s) = 𝓟 (set.image f s) := filter.ext $ λ a, image_subset_iff.symm variables {f : filter α} {m : α → β} {m' : β → γ} {s : set α} {t : set β} @[simp] lemma eventually_map {P : β → Prop} : (∀ᶠ b in map m f, P b) ↔ ∀ᶠ a in f, P (m a) := iff.rfl @[simp] lemma frequently_map {P : β → Prop} : (∃ᶠ b in map m f, P b) ↔ ∃ᶠ a in f, P (m a) := iff.rfl @[simp] lemma mem_map : t ∈ map m f ↔ m ⁻¹' t ∈ f := iff.rfl lemma mem_map' : t ∈ map m f ↔ {x | m x ∈ t} ∈ f := iff.rfl lemma image_mem_map (hs : s ∈ f) : m '' s ∈ map m f := f.sets_of_superset hs $ subset_preimage_image m s lemma image_mem_map_iff (hf : injective m) : m '' s ∈ map m f ↔ s ∈ f := ⟨λ h, by rwa [← preimage_image_eq s hf], image_mem_map⟩ lemma range_mem_map : range m ∈ map m f := by { rw ←image_univ, exact image_mem_map univ_mem } lemma mem_map_iff_exists_image : t ∈ map m f ↔ (∃ s ∈ f, m '' s ⊆ t) := ⟨λ ht, ⟨m ⁻¹' t, ht, image_preimage_subset _ _⟩, λ ⟨s, hs, ht⟩, mem_of_superset (image_mem_map hs) ht⟩ @[simp] lemma map_id : filter.map id f = f := filter_eq $ rfl @[simp] lemma map_id' : filter.map (λ x, x) f = f := map_id @[simp] lemma map_compose : filter.map m' ∘ filter.map m = filter.map (m' ∘ m) := funext $ λ _, filter_eq $ rfl @[simp] lemma map_map : filter.map m' (filter.map m f) = filter.map (m' ∘ m) f := congr_fun (@@filter.map_compose m m') f /-- If functions `m₁` and `m₂` are eventually equal at a filter `f`, then they map this filter to the same filter. -/ lemma map_congr {m₁ m₂ : α → β} {f : filter α} (h : m₁ =ᶠ[f] m₂) : map m₁ f = map m₂ f := filter.ext' $ λ p, by { simp only [eventually_map], exact eventually_congr (h.mono $ λ x hx, hx ▸ iff.rfl) } end map section comap /-- The inverse map of a filter -/ def comap (m : α → β) (f : filter β) : filter α := { sets := { s | ∃ t ∈ f, m ⁻¹' t ⊆ s }, univ_sets := ⟨univ, univ_mem, by simp only [subset_univ, preimage_univ]⟩, sets_of_superset := λ a b ⟨a', ha', ma'a⟩ ab, ⟨a', ha', ma'a.trans ab⟩, inter_sets := λ a b ⟨a', ha₁, ha₂⟩ ⟨b', hb₁, hb₂⟩, ⟨a' ∩ b', inter_mem ha₁ hb₁, inter_subset_inter ha₂ hb₂⟩ } lemma eventually_comap' {f : filter β} {φ : α → β} {p : β → Prop} (hf : ∀ᶠ b in f, p b) : ∀ᶠ a in comap φ f, p (φ a) := ⟨_, hf, (λ a h, h)⟩ @[simp] lemma eventually_comap {f : filter β} {φ : α → β} {P : α → Prop} : (∀ᶠ a in comap φ f, P a) ↔ ∀ᶠ b in f, ∀ a, φ a = b → P a := begin split ; intro h, { rcases h with ⟨t, t_in, ht⟩, apply mem_of_superset t_in, rintro y y_in _ rfl, apply ht y_in }, { exact ⟨_, h, λ _ x_in, x_in _ rfl⟩ } end @[simp] lemma frequently_comap {f : filter β} {φ : α → β} {P : α → Prop} : (∃ᶠ a in comap φ f, P a) ↔ ∃ᶠ b in f, ∃ a, φ a = b ∧ P a := by simp only [filter.frequently, eventually_comap, not_exists, not_and] end comap /-- The monadic bind operation on filter is defined the usual way in terms of `map` and `join`. Unfortunately, this `bind` does not result in the expected applicative. See `filter.seq` for the applicative instance. -/ def bind (f : filter α) (m : α → filter β) : filter β := join (map m f) /-- The applicative sequentiation operation. This is not induced by the bind operation. -/ def seq (f : filter (α → β)) (g : filter α) : filter β := ⟨{ s | ∃ u ∈ f, ∃ t ∈ g, (∀ m ∈ u, ∀ x ∈ t, (m : α → β) x ∈ s) }, ⟨univ, univ_mem, univ, univ_mem, by simp only [forall_prop_of_true, mem_univ, forall_true_iff]⟩, λ s₀ s₁ ⟨t₀, t₁, h₀, h₁, h⟩ hst, ⟨t₀, t₁, h₀, h₁, λ x hx y hy, hst $ h _ hx _ hy⟩, λ s₀ s₁ ⟨t₀, ht₀, t₁, ht₁, ht⟩ ⟨u₀, hu₀, u₁, hu₁, hu⟩, ⟨t₀ ∩ u₀, inter_mem ht₀ hu₀, t₁ ∩ u₁, inter_mem ht₁ hu₁, λ x ⟨hx₀, hx₁⟩ x ⟨hy₀, hy₁⟩, ⟨ht _ hx₀ _ hy₀, hu _ hx₁ _ hy₁⟩⟩⟩ /-- `pure x` is the set of sets that contain `x`. It is equal to `𝓟 {x}` but with this definition we have `s ∈ pure a` defeq `a ∈ s`. -/ instance : has_pure filter := ⟨λ (α : Type u) x, { sets := {s | x ∈ s}, inter_sets := λ s t, and.intro, sets_of_superset := λ s t hs hst, hst hs, univ_sets := trivial }⟩ instance : has_bind filter := ⟨@filter.bind⟩ instance : has_seq filter := ⟨@filter.seq⟩ instance : functor filter := { map := @filter.map } lemma pure_sets (a : α) : (pure a : filter α).sets = {s | a ∈ s} := rfl @[simp] lemma mem_pure {a : α} {s : set α} : s ∈ (pure a : filter α) ↔ a ∈ s := iff.rfl @[simp] lemma eventually_pure {a : α} {p : α → Prop} : (∀ᶠ x in pure a, p x) ↔ p a := iff.rfl @[simp] lemma principal_singleton (a : α) : 𝓟 {a} = pure a := filter.ext $ λ s, by simp only [mem_pure, mem_principal, singleton_subset_iff] @[simp] lemma map_pure (f : α → β) (a : α) : map f (pure a) = pure (f a) := rfl @[simp] lemma join_pure (f : filter α) : join (pure f) = f := filter.ext $ λ s, iff.rfl @[simp] lemma pure_bind (a : α) (m : α → filter β) : bind (pure a) m = m a := by simp only [has_bind.bind, bind, map_pure, join_pure] section -- this section needs to be before applicative, otherwise the wrong instance will be chosen /-- The monad structure on filters. -/ protected def monad : monad filter := { map := @filter.map } local attribute [instance] filter.monad protected lemma is_lawful_monad : is_lawful_monad filter := { id_map := λ α f, filter_eq rfl, pure_bind := λ α β, pure_bind, bind_assoc := λ α β γ f m₁ m₂, filter_eq rfl, bind_pure_comp_eq_map := λ α β f x, filter.ext $ λ s, by simp only [has_bind.bind, bind, functor.map, mem_map', mem_join, mem_set_of_eq, comp, mem_pure] } end instance : applicative filter := { map := @filter.map, seq := @filter.seq } instance : alternative filter := { failure := λ α, ⊥, orelse := λ α x y, x ⊔ y } @[simp] lemma map_def {α β} (m : α → β) (f : filter α) : m <$> f = map m f := rfl @[simp] lemma bind_def {α β} (f : filter α) (m : α → filter β) : f >>= m = bind f m := rfl /-! #### `map` and `comap` equations -/ section map variables {f f₁ f₂ : filter α} {g g₁ g₂ : filter β} {m : α → β} {m' : β → γ} {s : set α} {t : set β} @[simp] theorem mem_comap : s ∈ comap m g ↔ ∃ t ∈ g, m ⁻¹' t ⊆ s := iff.rfl theorem preimage_mem_comap (ht : t ∈ g) : m ⁻¹' t ∈ comap m g := ⟨t, ht, subset.rfl⟩ lemma comap_id : comap id f = f := le_antisymm (λ s, preimage_mem_comap) (λ s ⟨t, ht, hst⟩, mem_of_superset ht hst) lemma comap_const_of_not_mem {x : α} {f : filter α} {V : set α} (hV : V ∈ f) (hx : x ∉ V) : comap (λ y : α, x) f = ⊥ := begin ext W, suffices : ∃ t ∈ f, (λ (y : α), x) ⁻¹' t ⊆ W, by simpa, use [V, hV], simp [preimage_const_of_not_mem hx], end lemma comap_const_of_mem {x : α} {f : filter α} (h : ∀ V ∈ f, x ∈ V) : comap (λ y : α, x) f = ⊤ := begin ext W, suffices : (∃ (t : set α), t ∈ f ∧ (λ (y : α), x) ⁻¹' t ⊆ W) ↔ W = univ, by simpa, split, { rintro ⟨V, V_in, hW⟩, simpa [preimage_const_of_mem (h V V_in), univ_subset_iff] using hW }, { rintro rfl, use univ, simp [univ_mem] }, end lemma comap_comap {m : γ → β} {n : β → α} : comap m (comap n f) = comap (n ∘ m) f := le_antisymm (λ c ⟨b, hb, (h : preimage (n ∘ m) b ⊆ c)⟩, ⟨preimage n b, preimage_mem_comap hb, h⟩) (λ c ⟨b, ⟨a, ha, (h₁ : preimage n a ⊆ b)⟩, (h₂ : preimage m b ⊆ c)⟩, ⟨a, ha, show preimage m (preimage n a) ⊆ c, from (preimage_mono h₁).trans h₂⟩) section comm variables {δ : Type*} /-! The variables in the following lemmas are used as in this diagram: ``` φ α → β θ ↓ ↓ ψ γ → δ ρ ``` -/ variables {φ : α → β} {θ : α → γ} {ψ : β → δ} {ρ : γ → δ} (H : ψ ∘ φ = ρ ∘ θ) include H lemma map_comm (F : filter α) : map ψ (map φ F) = map ρ (map θ F) := by rw [filter.map_map, H, ← filter.map_map] lemma comap_comm (G : filter δ) : comap φ (comap ψ G) = comap θ (comap ρ G) := by rw [filter.comap_comap, H, ← filter.comap_comap] end comm @[simp] theorem comap_principal {t : set β} : comap m (𝓟 t) = 𝓟 (m ⁻¹' t) := filter.ext $ λ s, ⟨λ ⟨u, (hu : t ⊆ u), (b : preimage m u ⊆ s)⟩, (preimage_mono hu).trans b, λ h, ⟨t, subset.refl t, h⟩⟩ @[simp] theorem comap_pure {b : β} : comap m (pure b) = 𝓟 (m ⁻¹' {b}) := by rw [← principal_singleton, comap_principal] lemma map_le_iff_le_comap : map m f ≤ g ↔ f ≤ comap m g := ⟨λ h s ⟨t, ht, hts⟩, mem_of_superset (h ht) hts, λ h s ht, h ⟨_, ht, subset.rfl⟩⟩ lemma gc_map_comap (m : α → β) : galois_connection (map m) (comap m) := λ f g, map_le_iff_le_comap @[mono] lemma map_mono : monotone (map m) := (gc_map_comap m).monotone_l @[mono] lemma comap_mono : monotone (comap m) := (gc_map_comap m).monotone_u @[simp] lemma map_bot : map m ⊥ = ⊥ := (gc_map_comap m).l_bot @[simp] lemma map_sup : map m (f₁ ⊔ f₂) = map m f₁ ⊔ map m f₂ := (gc_map_comap m).l_sup @[simp] lemma map_supr {f : ι → filter α} : map m (⨆ i, f i) = (⨆ i, map m (f i)) := (gc_map_comap m).l_supr @[simp] lemma comap_top : comap m ⊤ = ⊤ := (gc_map_comap m).u_top @[simp] lemma comap_inf : comap m (g₁ ⊓ g₂) = comap m g₁ ⊓ comap m g₂ := (gc_map_comap m).u_inf @[simp] lemma comap_infi {f : ι → filter β} : comap m (⨅ i, f i) = (⨅ i, comap m (f i)) := (gc_map_comap m).u_infi lemma le_comap_top (f : α → β) (l : filter α) : l ≤ comap f ⊤ := by { rw [comap_top], exact le_top } lemma map_comap_le : map m (comap m g) ≤ g := (gc_map_comap m).l_u_le _ lemma le_comap_map : f ≤ comap m (map m f) := (gc_map_comap m).le_u_l _ @[simp] lemma comap_bot : comap m ⊥ = ⊥ := bot_unique $ λ s _, ⟨∅, by simp only [mem_bot], by simp only [empty_subset, preimage_empty]⟩ lemma comap_supr {ι} {f : ι → filter β} {m : α → β} : comap m (supr f) = (⨆ i, comap m (f i)) := le_antisymm (λ s hs, have ∀ i, ∃ t, t ∈ f i ∧ m ⁻¹' t ⊆ s, by simpa only [mem_comap, exists_prop, mem_supr] using mem_supr.1 hs, let ⟨t, ht⟩ := classical.axiom_of_choice this in ⟨⋃ i, t i, mem_supr.2 $ λ i, (f i).sets_of_superset (ht i).1 (subset_Union _ _), begin rw [preimage_Union, Union_subset_iff], exact λ i, (ht i).2 end⟩) (supr_le $ λ i, comap_mono $ le_supr _ _) lemma comap_Sup {s : set (filter β)} {m : α → β} : comap m (Sup s) = (⨆ f ∈ s, comap m f) := by simp only [Sup_eq_supr, comap_supr, eq_self_iff_true] lemma comap_sup : comap m (g₁ ⊔ g₂) = comap m g₁ ⊔ comap m g₂ := by rw [sup_eq_supr, comap_supr, supr_bool_eq, bool.cond_tt, bool.cond_ff] lemma map_comap (f : filter β) (m : α → β) : (f.comap m).map m = f ⊓ 𝓟 (range m) := begin refine le_antisymm (le_inf map_comap_le $ le_principal_iff.2 range_mem_map) _, rintro t' ⟨t, ht, sub⟩, refine mem_inf_principal.2 (mem_of_superset ht _), rintro _ hxt ⟨x, rfl⟩, exact sub hxt end lemma map_comap_of_mem {f : filter β} {m : α → β} (hf : range m ∈ f) : (f.comap m).map m = f := by rw [map_comap, inf_eq_left.2 (le_principal_iff.2 hf)] lemma comap_le_comap_iff {f g : filter β} {m : α → β} (hf : range m ∈ f) : comap m f ≤ comap m g ↔ f ≤ g := ⟨λ h, map_comap_of_mem hf ▸ (map_mono h).trans map_comap_le, λ h, comap_mono h⟩ theorem map_comap_of_surjective {f : α → β} (hf : surjective f) (l : filter β) : map f (comap f l) = l := map_comap_of_mem $ by simp only [hf.range_eq, univ_mem] lemma _root_.function.surjective.filter_map_top {f : α → β} (hf : surjective f) : map f ⊤ = ⊤ := (congr_arg _ comap_top).symm.trans $ map_comap_of_surjective hf ⊤ lemma subtype_coe_map_comap (s : set α) (f : filter α) : map (coe : s → α) (comap (coe : s → α) f) = f ⊓ 𝓟 s := by rw [map_comap, subtype.range_coe] lemma subtype_coe_map_comap_prod (s : set α) (f : filter (α × α)) : map (coe : s × s → α × α) (comap (coe : s × s → α × α) f) = f ⊓ 𝓟 (s.prod s) := have (coe : s × s → α × α) = (λ x, (x.1, x.2)), by ext ⟨x, y⟩; refl, by simp [this, map_comap, ← prod_range_range_eq] lemma image_mem_of_mem_comap {f : filter α} {c : β → α} (h : range c ∈ f) {W : set β} (W_in : W ∈ comap c f) : c '' W ∈ f := begin rw ← map_comap_of_mem h, exact image_mem_map W_in end lemma image_coe_mem_of_mem_comap {f : filter α} {U : set α} (h : U ∈ f) {W : set U} (W_in : W ∈ comap (coe : U → α) f) : coe '' W ∈ f := image_mem_of_mem_comap (by simp [h]) W_in lemma comap_map {f : filter α} {m : α → β} (h : injective m) : comap m (map m f) = f := le_antisymm (λ s hs, mem_of_superset (preimage_mem_comap $ image_mem_map hs) $ by simp only [preimage_image_eq s h]) le_comap_map lemma mem_comap_iff {f : filter β} {m : α → β} (inj : injective m) (large : set.range m ∈ f) {S : set α} : S ∈ comap m f ↔ m '' S ∈ f := by rw [← image_mem_map_iff inj, map_comap_of_mem large] lemma le_of_map_le_map_inj' {f g : filter α} {m : α → β} {s : set α} (hsf : s ∈ f) (hsg : s ∈ g) (hm : ∀ x ∈ s, ∀ y ∈ s, m x = m y → x = y) (h : map m f ≤ map m g) : f ≤ g := λ t ht, by filter_upwards [hsf, h $ image_mem_map (inter_mem hsg ht)] λ a has ⟨b, ⟨hbs, hb⟩, h⟩, hm _ hbs _ has h ▸ hb lemma le_of_map_le_map_inj_iff {f g : filter α} {m : α → β} {s : set α} (hsf : s ∈ f) (hsg : s ∈ g) (hm : ∀ x ∈ s, ∀ y ∈ s, m x = m y → x = y) : map m f ≤ map m g ↔ f ≤ g := iff.intro (le_of_map_le_map_inj' hsf hsg hm) (λ h, map_mono h) lemma eq_of_map_eq_map_inj' {f g : filter α} {m : α → β} {s : set α} (hsf : s ∈ f) (hsg : s ∈ g) (hm : ∀ x ∈ s, ∀ y ∈ s, m x = m y → x = y) (h : map m f = map m g) : f = g := le_antisymm (le_of_map_le_map_inj' hsf hsg hm $ le_of_eq h) (le_of_map_le_map_inj' hsg hsf hm $ le_of_eq h.symm) lemma map_inj {f g : filter α} {m : α → β} (hm : injective m) (h : map m f = map m g) : f = g := have comap m (map m f) = comap m (map m g), by rw h, by rwa [comap_map hm, comap_map hm] at this lemma comap_ne_bot_iff {f : filter β} {m : α → β} : ne_bot (comap m f) ↔ ∀ t ∈ f, ∃ a, m a ∈ t := begin rw ← forall_mem_nonempty_iff_ne_bot, exact ⟨λ h t t_in, h (m ⁻¹' t) ⟨t, t_in, subset.rfl⟩, λ h s ⟨u, u_in, hu⟩, let ⟨x, hx⟩ := h u u_in in ⟨x, hu hx⟩⟩, end lemma comap_ne_bot {f : filter β} {m : α → β} (hm : ∀ t ∈ f, ∃ a, m a ∈ t) : ne_bot (comap m f) := comap_ne_bot_iff.mpr hm lemma comap_ne_bot_iff_frequently {f : filter β} {m : α → β} : ne_bot (comap m f) ↔ ∃ᶠ y in f, y ∈ range m := by simp [comap_ne_bot_iff, frequently_iff, ← exists_and_distrib_left, and.comm] lemma comap_ne_bot_iff_compl_range {f : filter β} {m : α → β} : ne_bot (comap m f) ↔ (range m)ᶜ ∉ f := comap_ne_bot_iff_frequently lemma ne_bot.comap_of_range_mem {f : filter β} {m : α → β} (hf : ne_bot f) (hm : range m ∈ f) : ne_bot (comap m f) := comap_ne_bot_iff_frequently.2 $ eventually.frequently hm @[simp] lemma comap_fst_ne_bot_iff {f : filter α} : (f.comap (prod.fst : α × β → α)).ne_bot ↔ f.ne_bot ∧ nonempty β := begin casesI is_empty_or_nonempty β, { rw [filter_eq_bot_of_is_empty (f.comap _), ← not_iff_not]; [simp *, apply_instance] }, { simp [comap_ne_bot_iff_frequently, h] } end @[instance] lemma comap_fst_ne_bot [nonempty β] {f : filter α} [ne_bot f] : (f.comap (prod.fst : α × β → α)).ne_bot := comap_fst_ne_bot_iff.2 ⟨‹_›, ‹_›⟩ @[simp] lemma comap_snd_ne_bot_iff {f : filter β} : (f.comap (prod.snd : α × β → β)).ne_bot ↔ nonempty α ∧ f.ne_bot := begin casesI is_empty_or_nonempty α with hα hα, { rw [filter_eq_bot_of_is_empty (f.comap _), ← not_iff_not]; [simpa using hα.elim, apply_instance] }, { simp [comap_ne_bot_iff_frequently, hα] } end @[instance] lemma comap_snd_ne_bot [nonempty α] {f : filter β} [ne_bot f] : (f.comap (prod.snd : α × β → β)).ne_bot := comap_snd_ne_bot_iff.2 ⟨‹_›, ‹_›⟩ lemma comap_eval_ne_bot_iff' {ι : Type*} {α : ι → Type*} {i : ι} {f : filter (α i)} : (comap (eval i) f).ne_bot ↔ (∀ j, nonempty (α j)) ∧ ne_bot f := begin casesI is_empty_or_nonempty (Π j, α j) with H H, { rw [filter_eq_bot_of_is_empty (f.comap _), ← not_iff_not]; [skip, assumption], simpa [← classical.nonempty_pi] using H.elim }, { haveI : ∀ j, nonempty (α j), from classical.nonempty_pi.1 H, simp [comap_ne_bot_iff_frequently, *] } end @[simp] lemma comap_eval_ne_bot_iff {ι : Type*} {α : ι → Type*} [∀ j, nonempty (α j)] {i : ι} {f : filter (α i)} : (comap (eval i) f).ne_bot ↔ ne_bot f := by simp [comap_eval_ne_bot_iff', *] @[instance] lemma comap_eval_ne_bot {ι : Type*} {α : ι → Type*} [∀ j, nonempty (α j)] (i : ι) (f : filter (α i)) [ne_bot f] : (comap (eval i) f).ne_bot := comap_eval_ne_bot_iff.2 ‹_› lemma comap_inf_principal_ne_bot_of_image_mem {f : filter β} {m : α → β} (hf : ne_bot f) {s : set α} (hs : m '' s ∈ f) : ne_bot (comap m f ⊓ 𝓟 s) := begin refine ⟨compl_compl s ▸ mt mem_of_eq_bot _⟩, rintro ⟨t, ht, hts⟩, rcases hf.nonempty_of_mem (inter_mem hs ht) with ⟨_, ⟨x, hxs, rfl⟩, hxt⟩, exact absurd hxs (hts hxt) end lemma comap_coe_ne_bot_of_le_principal {s : set γ} {l : filter γ} [h : ne_bot l] (h' : l ≤ 𝓟 s) : ne_bot (comap (coe : s → γ) l) := h.comap_of_range_mem $ (@subtype.range_coe γ s).symm ▸ h' (mem_principal_self s) lemma ne_bot.comap_of_surj {f : filter β} {m : α → β} (hf : ne_bot f) (hm : surjective m) : ne_bot (comap m f) := hf.comap_of_range_mem $ univ_mem' hm lemma ne_bot.comap_of_image_mem {f : filter β} {m : α → β} (hf : ne_bot f) {s : set α} (hs : m '' s ∈ f) : ne_bot (comap m f) := hf.comap_of_range_mem $ mem_of_superset hs (image_subset_range _ _) @[simp] lemma map_eq_bot_iff : map m f = ⊥ ↔ f = ⊥ := ⟨by { rw [←empty_mem_iff_bot, ←empty_mem_iff_bot], exact id }, λ h, by simp only [h, eq_self_iff_true, map_bot]⟩ lemma map_ne_bot_iff (f : α → β) {F : filter α} : ne_bot (map f F) ↔ ne_bot F := by simp only [ne_bot_iff, ne, map_eq_bot_iff] lemma ne_bot.map (hf : ne_bot f) (m : α → β) : ne_bot (map m f) := (map_ne_bot_iff m).2 hf instance map_ne_bot [hf : ne_bot f] : ne_bot (f.map m) := hf.map m lemma sInter_comap_sets (f : α → β) (F : filter β) : ⋂₀ (comap f F).sets = ⋂ U ∈ F, f ⁻¹' U := begin ext x, suffices : (∀ (A : set α) (B : set β), B ∈ F → f ⁻¹' B ⊆ A → x ∈ A) ↔ ∀ (B : set β), B ∈ F → f x ∈ B, by simp only [mem_sInter, mem_Inter, filter.mem_sets, mem_comap, this, and_imp, exists_prop, mem_preimage, exists_imp_distrib], split, { intros h U U_in, simpa only [subset.refl, forall_prop_of_true, mem_preimage] using h (f ⁻¹' U) U U_in }, { intros h V U U_in f_U_V, exact f_U_V (h U U_in) }, end end map -- this is a generic rule for monotone functions: lemma map_infi_le {f : ι → filter α} {m : α → β} : map m (infi f) ≤ (⨅ i, map m (f i)) := le_infi $ λ i, map_mono $ infi_le _ _ lemma map_infi_eq {f : ι → filter α} {m : α → β} (hf : directed (≥) f) [nonempty ι] : map m (infi f) = (⨅ i, map m (f i)) := map_infi_le.antisymm (λ s (hs : preimage m s ∈ infi f), let ⟨i, hi⟩ := (mem_infi_of_directed hf _).1 hs in have (⨅ i, map m (f i)) ≤ 𝓟 s, from infi_le_of_le i $ by { simp only [le_principal_iff, mem_map], assumption }, filter.le_principal_iff.1 this) lemma map_binfi_eq {ι : Type w} {f : ι → filter α} {m : α → β} {p : ι → Prop} (h : directed_on (f ⁻¹'o (≥)) {x | p x}) (ne : ∃ i, p i) : map m (⨅ i (h : p i), f i) = (⨅ i (h : p i), map m (f i)) := begin haveI := nonempty_subtype.2 ne, simp only [infi_subtype'], exact map_infi_eq h.directed_coe end lemma map_inf_le {f g : filter α} {m : α → β} : map m (f ⊓ g) ≤ map m f ⊓ map m g := (@map_mono _ _ m).map_inf_le f g lemma map_inf' {f g : filter α} {m : α → β} {t : set α} (htf : t ∈ f) (htg : t ∈ g) (h : ∀ x ∈ t, ∀ y ∈ t, m x = m y → x = y) : map m (f ⊓ g) = map m f ⊓ map m g := begin refine le_antisymm map_inf_le (λ s hs, _), simp only [mem_inf_iff, exists_prop, mem_map, mem_preimage, mem_inf_iff] at hs, rcases hs with ⟨t₁, h₁, t₂, h₂, hs : m ⁻¹' s = t₁ ∩ t₂⟩, have : m '' (t₁ ∩ t) ∩ m '' (t₂ ∩ t) ∈ map m f ⊓ map m g, { apply inter_mem_inf ; apply image_mem_map, exacts [inter_mem h₁ htf, inter_mem h₂ htg] }, apply mem_of_superset this, { rw [image_inter_on], { refine image_subset_iff.2 _, rw hs, exact λ x ⟨⟨h₁, _⟩, h₂, _⟩, ⟨h₁, h₂⟩ }, { exact λ x ⟨_, hx⟩ y ⟨_, hy⟩, h x hx y hy } } end lemma map_inf {f g : filter α} {m : α → β} (h : injective m) : map m (f ⊓ g) = map m f ⊓ map m g := map_inf' univ_mem univ_mem (λ x _ y _ hxy, h hxy) lemma map_eq_comap_of_inverse {f : filter α} {m : α → β} {n : β → α} (h₁ : m ∘ n = id) (h₂ : n ∘ m = id) : map m f = comap n f := le_antisymm (λ b ⟨a, ha, (h : preimage n a ⊆ b)⟩, f.sets_of_superset ha $ calc a = preimage (n ∘ m) a : by simp only [h₂, preimage_id, eq_self_iff_true] ... ⊆ preimage m b : preimage_mono h) (λ b (hb : preimage m b ∈ f), ⟨preimage m b, hb, show preimage (m ∘ n) b ⊆ b, by simp only [h₁]; apply subset.refl⟩) lemma map_swap_eq_comap_swap {f : filter (α × β)} : prod.swap <$> f = comap prod.swap f := map_eq_comap_of_inverse prod.swap_swap_eq prod.swap_swap_eq lemma le_map {f : filter α} {m : α → β} {g : filter β} (h : ∀ s ∈ f, m '' s ∈ g) : g ≤ f.map m := λ s hs, mem_of_superset (h _ hs) $ image_preimage_subset _ _ protected lemma push_pull (f : α → β) (F : filter α) (G : filter β) : map f (F ⊓ comap f G) = map f F ⊓ G := begin apply le_antisymm, { calc map f (F ⊓ comap f G) ≤ map f F ⊓ (map f $ comap f G) : map_inf_le ... ≤ map f F ⊓ G : inf_le_inf_left (map f F) map_comap_le }, { rintro U ⟨V, V_in, W, ⟨Z, Z_in, hZ⟩, h⟩, apply mem_inf_of_inter (image_mem_map V_in) Z_in, calc f '' V ∩ Z = f '' (V ∩ f ⁻¹' Z) : by rw image_inter_preimage ... ⊆ f '' (V ∩ W) : image_subset _ (inter_subset_inter_right _ ‹_›) ... = f '' (f ⁻¹' U) : by rw h ... ⊆ U : image_preimage_subset f U } end protected lemma push_pull' (f : α → β) (F : filter α) (G : filter β) : map f (comap f G ⊓ F) = G ⊓ map f F := by simp only [filter.push_pull, inf_comm] section applicative lemma singleton_mem_pure {a : α} : {a} ∈ (pure a : filter α) := mem_singleton a lemma pure_injective : injective (pure : α → filter α) := λ a b hab, (filter.ext_iff.1 hab {x | a = x}).1 rfl instance pure_ne_bot {α : Type u} {a : α} : ne_bot (pure a) := ⟨mt empty_mem_iff_bot.2 $ not_mem_empty a⟩ @[simp] lemma le_pure_iff {f : filter α} {a : α} : f ≤ pure a ↔ {a} ∈ f := ⟨λ h, h singleton_mem_pure, λ h s hs, mem_of_superset h $ singleton_subset_iff.2 hs⟩ lemma mem_seq_def {f : filter (α → β)} {g : filter α} {s : set β} : s ∈ f.seq g ↔ (∃ u ∈ f, ∃ t ∈ g, ∀ x ∈ u, ∀ y ∈ t, (x : α → β) y ∈ s) := iff.rfl lemma mem_seq_iff {f : filter (α → β)} {g : filter α} {s : set β} : s ∈ f.seq g ↔ (∃ u ∈ f, ∃ t ∈ g, set.seq u t ⊆ s) := by simp only [mem_seq_def, seq_subset, exists_prop, iff_self] lemma mem_map_seq_iff {f : filter α} {g : filter β} {m : α → β → γ} {s : set γ} : s ∈ (f.map m).seq g ↔ (∃ t u, t ∈ g ∧ u ∈ f ∧ ∀ x ∈ u, ∀ y ∈ t, m x y ∈ s) := iff.intro (λ ⟨t, ht, s, hs, hts⟩, ⟨s, m ⁻¹' t, hs, ht, λ a, hts _⟩) (λ ⟨t, s, ht, hs, hts⟩, ⟨m '' s, image_mem_map hs, t, ht, λ f ⟨a, has, eq⟩, eq ▸ hts _ has⟩) lemma seq_mem_seq {f : filter (α → β)} {g : filter α} {s : set (α → β)} {t : set α} (hs : s ∈ f) (ht : t ∈ g) : s.seq t ∈ f.seq g := ⟨s, hs, t, ht, λ f hf a ha, ⟨f, hf, a, ha, rfl⟩⟩ lemma le_seq {f : filter (α → β)} {g : filter α} {h : filter β} (hh : ∀ t ∈ f, ∀ u ∈ g, set.seq t u ∈ h) : h ≤ seq f g := λ s ⟨t, ht, u, hu, hs⟩, mem_of_superset (hh _ ht _ hu) $ λ b ⟨m, hm, a, ha, eq⟩, eq ▸ hs _ hm _ ha @[mono] lemma seq_mono {f₁ f₂ : filter (α → β)} {g₁ g₂ : filter α} (hf : f₁ ≤ f₂) (hg : g₁ ≤ g₂) : f₁.seq g₁ ≤ f₂.seq g₂ := le_seq $ λ s hs t ht, seq_mem_seq (hf hs) (hg ht) @[simp] lemma pure_seq_eq_map (g : α → β) (f : filter α) : seq (pure g) f = f.map g := begin refine le_antisymm (le_map $ λ s hs, _) (le_seq $ λ s hs t ht, _), { rw ← singleton_seq, apply seq_mem_seq _ hs, exact singleton_mem_pure }, { refine sets_of_superset (map g f) (image_mem_map ht) _, rintro b ⟨a, ha, rfl⟩, exact ⟨g, hs, a, ha, rfl⟩ } end @[simp] lemma seq_pure (f : filter (α → β)) (a : α) : seq f (pure a) = map (λ g : α → β, g a) f := begin refine le_antisymm (le_map $ λ s hs, _) (le_seq $ λ s hs t ht, _), { rw ← seq_singleton, exact seq_mem_seq hs singleton_mem_pure }, { refine sets_of_superset (map (λg:α→β, g a) f) (image_mem_map hs) _, rintro b ⟨g, hg, rfl⟩, exact ⟨g, hg, a, ht, rfl⟩ } end @[simp] lemma seq_assoc (x : filter α) (g : filter (α → β)) (h : filter (β → γ)) : seq h (seq g x) = seq (seq (map (∘) h) g) x := begin refine le_antisymm (le_seq $ λ s hs t ht, _) (le_seq $ λ s hs t ht, _), { rcases mem_seq_iff.1 hs with ⟨u, hu, v, hv, hs⟩, rcases mem_map_iff_exists_image.1 hu with ⟨w, hw, hu⟩, refine mem_of_superset _ (set.seq_mono ((set.seq_mono hu subset.rfl).trans hs) subset.rfl), rw ← set.seq_seq, exact seq_mem_seq hw (seq_mem_seq hv ht) }, { rcases mem_seq_iff.1 ht with ⟨u, hu, v, hv, ht⟩, refine mem_of_superset _ (set.seq_mono subset.rfl ht), rw set.seq_seq, exact seq_mem_seq (seq_mem_seq (image_mem_map hs) hu) hv } end lemma prod_map_seq_comm (f : filter α) (g : filter β) : (map prod.mk f).seq g = seq (map (λ b a, (a, b)) g) f := begin refine le_antisymm (le_seq $ λ s hs t ht, _) (le_seq $ λ s hs t ht, _), { rcases mem_map_iff_exists_image.1 hs with ⟨u, hu, hs⟩, refine mem_of_superset _ (set.seq_mono hs subset.rfl), rw ← set.prod_image_seq_comm, exact seq_mem_seq (image_mem_map ht) hu }, { rcases mem_map_iff_exists_image.1 hs with ⟨u, hu, hs⟩, refine mem_of_superset _ (set.seq_mono hs subset.rfl), rw set.prod_image_seq_comm, exact seq_mem_seq (image_mem_map ht) hu } end instance : is_lawful_functor (filter : Type u → Type u) := { id_map := λ α f, map_id, comp_map := λ α β γ f g a, map_map.symm } instance : is_lawful_applicative (filter : Type u → Type u) := { pure_seq_eq_map := λ α β, pure_seq_eq_map, map_pure := λ α β, map_pure, seq_pure := λ α β, seq_pure, seq_assoc := λ α β γ, seq_assoc } instance : is_comm_applicative (filter : Type u → Type u) := ⟨λ α β f g, prod_map_seq_comm f g⟩ lemma {l} seq_eq_filter_seq {α β : Type l} (f : filter (α → β)) (g : filter α) : f <*> g = seq f g := rfl end applicative /-! #### `bind` equations -/ section bind @[simp] lemma eventually_bind {f : filter α} {m : α → filter β} {p : β → Prop} : (∀ᶠ y in bind f m, p y) ↔ ∀ᶠ x in f, ∀ᶠ y in m x, p y := iff.rfl @[simp] lemma eventually_eq_bind {f : filter α} {m : α → filter β} {g₁ g₂ : β → γ} : (g₁ =ᶠ[bind f m] g₂) ↔ ∀ᶠ x in f, g₁ =ᶠ[m x] g₂ := iff.rfl @[simp] lemma eventually_le_bind [has_le γ] {f : filter α} {m : α → filter β} {g₁ g₂ : β → γ} : (g₁ ≤ᶠ[bind f m] g₂) ↔ ∀ᶠ x in f, g₁ ≤ᶠ[m x] g₂ := iff.rfl lemma mem_bind' {s : set β} {f : filter α} {m : α → filter β} : s ∈ bind f m ↔ {a | s ∈ m a} ∈ f := iff.rfl @[simp] lemma mem_bind {s : set β} {f : filter α} {m : α → filter β} : s ∈ bind f m ↔ ∃ t ∈ f, ∀ x ∈ t, s ∈ m x := calc s ∈ bind f m ↔ {a | s ∈ m a} ∈ f : iff.rfl ... ↔ (∃ t ∈ f, t ⊆ {a | s ∈ m a}) : exists_mem_subset_iff.symm ... ↔ (∃ t ∈ f, ∀ x ∈ t, s ∈ m x) : iff.rfl lemma bind_le {f : filter α} {g : α → filter β} {l : filter β} (h : ∀ᶠ x in f, g x ≤ l) : f.bind g ≤ l := join_le $ eventually_map.2 h @[mono] lemma bind_mono {f₁ f₂ : filter α} {g₁ g₂ : α → filter β} (hf : f₁ ≤ f₂) (hg : g₁ ≤ᶠ[f₁] g₂) : bind f₁ g₁ ≤ bind f₂ g₂ := begin refine le_trans (λ s hs, _) (join_mono $ map_mono hf), simp only [mem_join, mem_bind', mem_map] at hs ⊢, filter_upwards [hg, hs], exact λ x hx hs, hx hs end lemma bind_inf_principal {f : filter α} {g : α → filter β} {s : set β} : f.bind (λ x, g x ⊓ 𝓟 s) = (f.bind g) ⊓ 𝓟 s := filter.ext $ λ s, by simp only [mem_bind, mem_inf_principal] lemma sup_bind {f g : filter α} {h : α → filter β} : bind (f ⊔ g) h = bind f h ⊔ bind g h := by simp only [bind, sup_join, map_sup, eq_self_iff_true] lemma principal_bind {s : set α} {f : α → filter β} : (bind (𝓟 s) f) = (⨆ x ∈ s, f x) := show join (map f (𝓟 s)) = (⨆ x ∈ s, f x), by simp only [Sup_image, join_principal_eq_Sup, map_principal, eq_self_iff_true] end bind section list_traverse /- This is a separate section in order to open `list`, but mostly because of universe equality requirements in `traverse` -/ open list lemma sequence_mono : ∀ (as bs : list (filter α)), forall₂ (≤) as bs → sequence as ≤ sequence bs | [] [] forall₂.nil := le_rfl | (a :: as) (b :: bs) (forall₂.cons h hs) := seq_mono (map_mono h) (sequence_mono as bs hs) variables {α' β' γ' : Type u} {f : β' → filter α'} {s : γ' → set α'} lemma mem_traverse : ∀ (fs : list β') (us : list γ'), forall₂ (λ b c, s c ∈ f b) fs us → traverse s us ∈ traverse f fs | [] [] forall₂.nil := mem_pure.2 $ mem_singleton _ | (f :: fs) (u :: us) (forall₂.cons h hs) := seq_mem_seq (image_mem_map h) (mem_traverse fs us hs) lemma mem_traverse_iff (fs : list β') (t : set (list α')) : t ∈ traverse f fs ↔ (∃ us : list (set α'), forall₂ (λ b (s : set α'), s ∈ f b) fs us ∧ sequence us ⊆ t) := begin split, { induction fs generalizing t, case nil { simp only [sequence, mem_pure, imp_self, forall₂_nil_left_iff, exists_eq_left, set.pure_def, singleton_subset_iff, traverse_nil] }, case cons : b fs ih t { intro ht, rcases mem_seq_iff.1 ht with ⟨u, hu, v, hv, ht⟩, rcases mem_map_iff_exists_image.1 hu with ⟨w, hw, hwu⟩, rcases ih v hv with ⟨us, hus, hu⟩, exact ⟨w :: us, forall₂.cons hw hus, (set.seq_mono hwu hu).trans ht⟩ } }, { rintro ⟨us, hus, hs⟩, exact mem_of_superset (mem_traverse _ _ hus) hs } end end list_traverse /-! ### Limits -/ /-- `tendsto` is the generic "limit of a function" predicate. `tendsto f l₁ l₂` asserts that for every `l₂` neighborhood `a`, the `f`-preimage of `a` is an `l₁` neighborhood. -/ def tendsto (f : α → β) (l₁ : filter α) (l₂ : filter β) := l₁.map f ≤ l₂ lemma tendsto_def {f : α → β} {l₁ : filter α} {l₂ : filter β} : tendsto f l₁ l₂ ↔ ∀ s ∈ l₂, f ⁻¹' s ∈ l₁ := iff.rfl lemma tendsto_iff_eventually {f : α → β} {l₁ : filter α} {l₂ : filter β} : tendsto f l₁ l₂ ↔ ∀ ⦃p : β → Prop⦄, (∀ᶠ y in l₂, p y) → ∀ᶠ x in l₁, p (f x) := iff.rfl lemma tendsto.eventually {f : α → β} {l₁ : filter α} {l₂ : filter β} {p : β → Prop} (hf : tendsto f l₁ l₂) (h : ∀ᶠ y in l₂, p y) : ∀ᶠ x in l₁, p (f x) := hf h lemma tendsto.frequently {f : α → β} {l₁ : filter α} {l₂ : filter β} {p : β → Prop} (hf : tendsto f l₁ l₂) (h : ∃ᶠ x in l₁, p (f x)) : ∃ᶠ y in l₂, p y := mt hf.eventually h lemma tendsto.frequently_map {l₁ : filter α} {l₂ : filter β} {p : α → Prop} {q : β → Prop} (f : α → β) (c : filter.tendsto f l₁ l₂) (w : ∀ x, p x → q (f x)) (h : ∃ᶠ x in l₁, p x) : ∃ᶠ y in l₂, q y := c.frequently (h.mono w) @[simp] lemma tendsto_bot {f : α → β} {l : filter β} : tendsto f ⊥ l := by simp [tendsto] @[simp] lemma tendsto_top {f : α → β} {l : filter α} : tendsto f l ⊤ := le_top lemma le_map_of_right_inverse {mab : α → β} {mba : β → α} {f : filter α} {g : filter β} (h₁ : mab ∘ mba =ᶠ[g] id) (h₂ : tendsto mba g f) : g ≤ map mab f := by { rw [← @map_id _ g, ← map_congr h₁, ← map_map], exact map_mono h₂ } lemma tendsto_of_is_empty [is_empty α] {f : α → β} {la : filter α} {lb : filter β} : tendsto f la lb := by simp only [filter_eq_bot_of_is_empty la, tendsto_bot] lemma eventually_eq_of_left_inv_of_right_inv {f : α → β} {g₁ g₂ : β → α} {fa : filter α} {fb : filter β} (hleft : ∀ᶠ x in fa, g₁ (f x) = x) (hright : ∀ᶠ y in fb, f (g₂ y) = y) (htendsto : tendsto g₂ fb fa) : g₁ =ᶠ[fb] g₂ := (htendsto.eventually hleft).mp $ hright.mono $ λ y hr hl, (congr_arg g₁ hr.symm).trans hl lemma tendsto_iff_comap {f : α → β} {l₁ : filter α} {l₂ : filter β} : tendsto f l₁ l₂ ↔ l₁ ≤ l₂.comap f := map_le_iff_le_comap alias tendsto_iff_comap ↔ filter.tendsto.le_comap _ lemma tendsto_congr' {f₁ f₂ : α → β} {l₁ : filter α} {l₂ : filter β} (hl : f₁ =ᶠ[l₁] f₂) : tendsto f₁ l₁ l₂ ↔ tendsto f₂ l₁ l₂ := by rw [tendsto, tendsto, map_congr hl] lemma tendsto.congr' {f₁ f₂ : α → β} {l₁ : filter α} {l₂ : filter β} (hl : f₁ =ᶠ[l₁] f₂) (h : tendsto f₁ l₁ l₂) : tendsto f₂ l₁ l₂ := (tendsto_congr' hl).1 h theorem tendsto_congr {f₁ f₂ : α → β} {l₁ : filter α} {l₂ : filter β} (h : ∀ x, f₁ x = f₂ x) : tendsto f₁ l₁ l₂ ↔ tendsto f₂ l₁ l₂ := tendsto_congr' (univ_mem' h) theorem tendsto.congr {f₁ f₂ : α → β} {l₁ : filter α} {l₂ : filter β} (h : ∀ x, f₁ x = f₂ x) : tendsto f₁ l₁ l₂ → tendsto f₂ l₁ l₂ := (tendsto_congr h).1 lemma tendsto_id' {x y : filter α} : x ≤ y → tendsto id x y := by simp only [tendsto, map_id, forall_true_iff] {contextual := tt} lemma tendsto_id {x : filter α} : tendsto id x x := tendsto_id' $ le_refl x lemma tendsto.comp {f : α → β} {g : β → γ} {x : filter α} {y : filter β} {z : filter γ} (hg : tendsto g y z) (hf : tendsto f x y) : tendsto (g ∘ f) x z := calc map (g ∘ f) x = map g (map f x) : by rw [map_map] ... ≤ map g y : map_mono hf ... ≤ z : hg lemma tendsto.mono_left {f : α → β} {x y : filter α} {z : filter β} (hx : tendsto f x z) (h : y ≤ x) : tendsto f y z := (map_mono h).trans hx lemma tendsto.mono_right {f : α → β} {x : filter α} {y z : filter β} (hy : tendsto f x y) (hz : y ≤ z) : tendsto f x z := le_trans hy hz lemma tendsto.ne_bot {f : α → β} {x : filter α} {y : filter β} (h : tendsto f x y) [hx : ne_bot x] : ne_bot y := (hx.map _).mono h lemma tendsto_map {f : α → β} {x : filter α} : tendsto f x (map f x) := le_refl (map f x) lemma tendsto_map' {f : β → γ} {g : α → β} {x : filter α} {y : filter γ} (h : tendsto (f ∘ g) x y) : tendsto f (map g x) y := by rwa [tendsto, map_map] @[simp] lemma tendsto_map'_iff {f : β → γ} {g : α → β} {x : filter α} {y : filter γ} : tendsto f (map g x) y ↔ tendsto (f ∘ g) x y := by { rw [tendsto, map_map], refl } lemma tendsto_comap {f : α → β} {x : filter β} : tendsto f (comap f x) x := map_comap_le @[simp] lemma tendsto_comap_iff {f : α → β} {g : β → γ} {a : filter α} {c : filter γ} : tendsto f a (c.comap g) ↔ tendsto (g ∘ f) a c := ⟨λ h, tendsto_comap.comp h, λ h, map_le_iff_le_comap.mp $ by rwa [map_map]⟩ lemma tendsto_comap'_iff {m : α → β} {f : filter α} {g : filter β} {i : γ → α} (h : range i ∈ f) : tendsto (m ∘ i) (comap i f) g ↔ tendsto m f g := by { rw [tendsto, ← map_compose], simp only [(∘), map_comap_of_mem h, tendsto] } lemma tendsto.of_tendsto_comp {f : α → β} {g : β → γ} {a : filter α} {b : filter β} {c : filter γ} (hfg : tendsto (g ∘ f) a c) (hg : comap g c ≤ b) : tendsto f a b := begin rw tendsto_iff_comap at hfg ⊢, calc a ≤ comap (g ∘ f) c : hfg ... ≤ comap f b : by simpa [comap_comap] using comap_mono hg end lemma comap_eq_of_inverse {f : filter α} {g : filter β} {φ : α → β} (ψ : β → α) (eq : ψ ∘ φ = id) (hφ : tendsto φ f g) (hψ : tendsto ψ g f) : comap φ g = f := begin refine ((comap_mono $ map_le_iff_le_comap.1 hψ).trans _).antisymm (map_le_iff_le_comap.1 hφ), rw [comap_comap, eq, comap_id], exact le_rfl end lemma map_eq_of_inverse {f : filter α} {g : filter β} {φ : α → β} (ψ : β → α) (eq : φ ∘ ψ = id) (hφ : tendsto φ f g) (hψ : tendsto ψ g f) : map φ f = g := begin refine le_antisymm hφ (le_trans _ (map_mono hψ)), rw [map_map, eq, map_id], exact le_rfl end lemma tendsto_inf {f : α → β} {x : filter α} {y₁ y₂ : filter β} : tendsto f x (y₁ ⊓ y₂) ↔ tendsto f x y₁ ∧ tendsto f x y₂ := by simp only [tendsto, le_inf_iff, iff_self] lemma tendsto_inf_left {f : α → β} {x₁ x₂ : filter α} {y : filter β} (h : tendsto f x₁ y) : tendsto f (x₁ ⊓ x₂) y := le_trans (map_mono inf_le_left) h lemma tendsto_inf_right {f : α → β} {x₁ x₂ : filter α} {y : filter β} (h : tendsto f x₂ y) : tendsto f (x₁ ⊓ x₂) y := le_trans (map_mono inf_le_right) h lemma tendsto.inf {f : α → β} {x₁ x₂ : filter α} {y₁ y₂ : filter β} (h₁ : tendsto f x₁ y₁) (h₂ : tendsto f x₂ y₂) : tendsto f (x₁ ⊓ x₂) (y₁ ⊓ y₂) := tendsto_inf.2 ⟨tendsto_inf_left h₁, tendsto_inf_right h₂⟩ @[simp] lemma tendsto_infi {f : α → β} {x : filter α} {y : ι → filter β} : tendsto f x (⨅ i, y i) ↔ ∀ i, tendsto f x (y i) := by simp only [tendsto, iff_self, le_infi_iff] lemma tendsto_infi' {f : α → β} {x : ι → filter α} {y : filter β} (i : ι) (hi : tendsto f (x i) y) : tendsto f (⨅ i, x i) y := hi.mono_left $ infi_le _ _ @[simp] lemma tendsto_sup {f : α → β} {x₁ x₂ : filter α} {y : filter β} : tendsto f (x₁ ⊔ x₂) y ↔ tendsto f x₁ y ∧ tendsto f x₂ y := by simp only [tendsto, map_sup, sup_le_iff] lemma tendsto.sup {f : α → β} {x₁ x₂ : filter α} {y : filter β} : tendsto f x₁ y → tendsto f x₂ y → tendsto f (x₁ ⊔ x₂) y := λ h₁ h₂, tendsto_sup.mpr ⟨ h₁, h₂ ⟩ @[simp] lemma tendsto_supr {f : α → β} {x : ι → filter α} {y : filter β} : tendsto f (⨆ i, x i) y ↔ ∀ i, tendsto f (x i) y := by simp only [tendsto, map_supr, supr_le_iff] @[simp] lemma tendsto_principal {f : α → β} {l : filter α} {s : set β} : tendsto f l (𝓟 s) ↔ ∀ᶠ a in l, f a ∈ s := by simp only [tendsto, le_principal_iff, mem_map', filter.eventually] @[simp] lemma tendsto_principal_principal {f : α → β} {s : set α} {t : set β} : tendsto f (𝓟 s) (𝓟 t) ↔ ∀ a ∈ s, f a ∈ t := by simp only [tendsto_principal, eventually_principal] @[simp] lemma tendsto_pure {f : α → β} {a : filter α} {b : β} : tendsto f a (pure b) ↔ ∀ᶠ x in a, f x = b := by simp only [tendsto, le_pure_iff, mem_map', mem_singleton_iff, filter.eventually] lemma tendsto_pure_pure (f : α → β) (a : α) : tendsto f (pure a) (pure (f a)) := tendsto_pure.2 rfl lemma tendsto_const_pure {a : filter α} {b : β} : tendsto (λ x, b) a (pure b) := tendsto_pure.2 $ univ_mem' $ λ _, rfl lemma pure_le_iff {a : α} {l : filter α} : pure a ≤ l ↔ ∀ s ∈ l, a ∈ s := iff.rfl lemma tendsto_pure_left {f : α → β} {a : α} {l : filter β} : tendsto f (pure a) l ↔ ∀ s ∈ l, f a ∈ s := iff.rfl @[simp] lemma map_inf_principal_preimage {f : α → β} {s : set β} {l : filter α} : map f (l ⊓ 𝓟 (f ⁻¹' s)) = map f l ⊓ 𝓟 s := filter.ext $ λ t, by simp only [mem_map', mem_inf_principal, mem_set_of_eq, mem_preimage] /-- If two filters are disjoint, then a function cannot tend to both of them along a non-trivial filter. -/ lemma tendsto.not_tendsto {f : α → β} {a : filter α} {b₁ b₂ : filter β} (hf : tendsto f a b₁) [ne_bot a] (hb : disjoint b₁ b₂) : ¬ tendsto f a b₂ := λ hf', (tendsto_inf.2 ⟨hf, hf'⟩).ne_bot.ne hb.eq_bot lemma tendsto.if {l₁ : filter α} {l₂ : filter β} {f g : α → β} {p : α → Prop} [∀ x, decidable (p x)] (h₀ : tendsto f (l₁ ⊓ 𝓟 {x | p x}) l₂) (h₁ : tendsto g (l₁ ⊓ 𝓟 { x | ¬ p x }) l₂) : tendsto (λ x, if p x then f x else g x) l₁ l₂ := begin simp only [tendsto_def, mem_inf_principal] at *, intros s hs, filter_upwards [h₀ s hs, h₁ s hs], simp only [mem_preimage], intros x hp₀ hp₁, split_ifs, exacts [hp₀ h, hp₁ h] end lemma tendsto.piecewise {l₁ : filter α} {l₂ : filter β} {f g : α → β} {s : set α} [∀ x, decidable (x ∈ s)] (h₀ : tendsto f (l₁ ⊓ 𝓟 s) l₂) (h₁ : tendsto g (l₁ ⊓ 𝓟 sᶜ) l₂) : tendsto (piecewise s f g) l₁ l₂ := h₀.if h₁ /-! ### Products of filters -/ section prod variables {s : set α} {t : set β} {f : filter α} {g : filter β} /- The product filter cannot be defined using the monad structure on filters. For example: F := do {x ← seq, y ← top, return (x, y)} hence: s ∈ F ↔ ∃ n, [n..∞] × univ ⊆ s G := do {y ← top, x ← seq, return (x, y)} hence: s ∈ G ↔ ∀ i:ℕ, ∃ n, [n..∞] × {i} ⊆ s Now ⋃ i, [i..∞] × {i} is in G but not in F. As product filter we want to have F as result. -/ /-- Product of filters. This is the filter generated by cartesian products of elements of the component filters. -/ protected def prod (f : filter α) (g : filter β) : filter (α × β) := f.comap prod.fst ⊓ g.comap prod.snd localized "infix ` ×ᶠ `:60 := filter.prod" in filter lemma prod_mem_prod {s : set α} {t : set β} {f : filter α} {g : filter β} (hs : s ∈ f) (ht : t ∈ g) : set.prod s t ∈ f ×ᶠ g := inter_mem_inf (preimage_mem_comap hs) (preimage_mem_comap ht) lemma mem_prod_iff {s : set (α×β)} {f : filter α} {g : filter β} : s ∈ f ×ᶠ g ↔ (∃ t₁ ∈ f, ∃ t₂ ∈ g, set.prod t₁ t₂ ⊆ s) := begin simp only [filter.prod], split, { rintro ⟨t₁, ⟨s₁, hs₁, hts₁⟩, t₂, ⟨s₂, hs₂, hts₂⟩, rfl⟩, exact ⟨s₁, hs₁, s₂, hs₂, λ p ⟨h, h'⟩, ⟨hts₁ h, hts₂ h'⟩⟩ }, { rintro ⟨t₁, ht₁, t₂, ht₂, h⟩, exact mem_inf_of_inter (preimage_mem_comap ht₁) (preimage_mem_comap ht₂) h } end @[simp] lemma prod_mem_prod_iff {s : set α} {t : set β} {f : filter α} {g : filter β} [f.ne_bot] [g.ne_bot] : s.prod t ∈ f ×ᶠ g ↔ s ∈ f ∧ t ∈ g := ⟨λ h, let ⟨s', hs', t', ht', H⟩ := mem_prod_iff.1 h in (prod_subset_prod_iff.1 H).elim (λ ⟨hs's, ht't⟩, ⟨mem_of_superset hs' hs's, mem_of_superset ht' ht't⟩) (λ h, h.elim (λ hs'e, absurd hs'e (nonempty_of_mem hs').ne_empty) (λ ht'e, absurd ht'e (nonempty_of_mem ht').ne_empty)), λ h, prod_mem_prod h.1 h.2⟩ lemma comap_prod (f : α → β × γ) (b : filter β) (c : filter γ) : comap f (b ×ᶠ c) = (comap (prod.fst ∘ f) b) ⊓ (comap (prod.snd ∘ f) c) := by erw [comap_inf, filter.comap_comap, filter.comap_comap] lemma prod_top {f : filter α} : f ×ᶠ (⊤ : filter β) = f.comap prod.fst := by rw [filter.prod, comap_top, inf_top_eq] lemma sup_prod (f₁ f₂ : filter α) (g : filter β) : (f₁ ⊔ f₂) ×ᶠ g = (f₁ ×ᶠ g) ⊔ (f₂ ×ᶠ g) := by rw [filter.prod, comap_sup, inf_sup_right, ← filter.prod, ← filter.prod] lemma prod_sup (f : filter α) (g₁ g₂ : filter β) : f ×ᶠ (g₁ ⊔ g₂) = (f ×ᶠ g₁) ⊔ (f ×ᶠ g₂) := by rw [filter.prod, comap_sup, inf_sup_left, ← filter.prod, ← filter.prod] lemma eventually_prod_iff {p : α × β → Prop} {f : filter α} {g : filter β} : (∀ᶠ x in f ×ᶠ g, p x) ↔ ∃ (pa : α → Prop) (ha : ∀ᶠ x in f, pa x) (pb : β → Prop) (hb : ∀ᶠ y in g, pb y), ∀ {x}, pa x → ∀ {y}, pb y → p (x, y) := by simpa only [set.prod_subset_iff] using @mem_prod_iff α β p f g lemma tendsto_fst {f : filter α} {g : filter β} : tendsto prod.fst (f ×ᶠ g) f := tendsto_inf_left tendsto_comap lemma tendsto_snd {f : filter α} {g : filter β} : tendsto prod.snd (f ×ᶠ g) g := tendsto_inf_right tendsto_comap lemma tendsto.prod_mk {f : filter α} {g : filter β} {h : filter γ} {m₁ : α → β} {m₂ : α → γ} (h₁ : tendsto m₁ f g) (h₂ : tendsto m₂ f h) : tendsto (λ x, (m₁ x, m₂ x)) f (g ×ᶠ h) := tendsto_inf.2 ⟨tendsto_comap_iff.2 h₁, tendsto_comap_iff.2 h₂⟩ lemma eventually.prod_inl {la : filter α} {p : α → Prop} (h : ∀ᶠ x in la, p x) (lb : filter β) : ∀ᶠ x in la ×ᶠ lb, p (x : α × β).1 := tendsto_fst.eventually h lemma eventually.prod_inr {lb : filter β} {p : β → Prop} (h : ∀ᶠ x in lb, p x) (la : filter α) : ∀ᶠ x in la ×ᶠ lb, p (x : α × β).2 := tendsto_snd.eventually h lemma eventually.prod_mk {la : filter α} {pa : α → Prop} (ha : ∀ᶠ x in la, pa x) {lb : filter β} {pb : β → Prop} (hb : ∀ᶠ y in lb, pb y) : ∀ᶠ p in la ×ᶠ lb, pa (p : α × β).1 ∧ pb p.2 := (ha.prod_inl lb).and (hb.prod_inr la) lemma eventually.curry {la : filter α} {lb : filter β} {p : α × β → Prop} (h : ∀ᶠ x in la ×ᶠ lb, p x) : ∀ᶠ x in la, ∀ᶠ y in lb, p (x, y) := begin rcases eventually_prod_iff.1 h with ⟨pa, ha, pb, hb, h⟩, exact ha.mono (λ a ha, hb.mono $ λ b hb, h ha hb) end lemma prod_infi_left [nonempty ι] {f : ι → filter α} {g : filter β}: (⨅ i, f i) ×ᶠ g = (⨅ i, (f i) ×ᶠ g) := by { rw [filter.prod, comap_infi, infi_inf], simp only [filter.prod, eq_self_iff_true] } lemma prod_infi_right [nonempty ι] {f : filter α} {g : ι → filter β} : f ×ᶠ (⨅ i, g i) = (⨅ i, f ×ᶠ (g i)) := by { rw [filter.prod, comap_infi, inf_infi], simp only [filter.prod, eq_self_iff_true] } @[mono] lemma prod_mono {f₁ f₂ : filter α} {g₁ g₂ : filter β} (hf : f₁ ≤ f₂) (hg : g₁ ≤ g₂) : f₁ ×ᶠ g₁ ≤ f₂ ×ᶠ g₂ := inf_le_inf (comap_mono hf) (comap_mono hg) lemma prod_comap_comap_eq {α₁ : Type u} {α₂ : Type v} {β₁ : Type w} {β₂ : Type x} {f₁ : filter α₁} {f₂ : filter α₂} {m₁ : β₁ → α₁} {m₂ : β₂ → α₂} : (comap m₁ f₁) ×ᶠ (comap m₂ f₂) = comap (λ p : β₁×β₂, (m₁ p.1, m₂ p.2)) (f₁ ×ᶠ f₂) := by simp only [filter.prod, comap_comap, eq_self_iff_true, comap_inf] lemma prod_comm' : f ×ᶠ g = comap (prod.swap) (g ×ᶠ f) := by simp only [filter.prod, comap_comap, (∘), inf_comm, prod.fst_swap, eq_self_iff_true, prod.snd_swap, comap_inf] lemma prod_comm : f ×ᶠ g = map (λ p : β×α, (p.2, p.1)) (g ×ᶠ f) := by { rw [prod_comm', ← map_swap_eq_comap_swap], refl } lemma prod_map_map_eq {α₁ : Type u} {α₂ : Type v} {β₁ : Type w} {β₂ : Type x} {f₁ : filter α₁} {f₂ : filter α₂} {m₁ : α₁ → β₁} {m₂ : α₂ → β₂} : (map m₁ f₁) ×ᶠ (map m₂ f₂) = map (λ p : α₁×α₂, (m₁ p.1, m₂ p.2)) (f₁ ×ᶠ f₂) := le_antisymm (λ s hs, let ⟨s₁, hs₁, s₂, hs₂, h⟩ := mem_prod_iff.mp hs in filter.sets_of_superset _ (prod_mem_prod (image_mem_map hs₁) (image_mem_map hs₂)) $ calc set.prod (m₁ '' s₁) (m₂ '' s₂) = (λ p : α₁×α₂, (m₁ p.1, m₂ p.2)) '' set.prod s₁ s₂ : set.prod_image_image_eq ... ⊆ _ : by rwa [image_subset_iff]) ((tendsto.comp le_rfl tendsto_fst).prod_mk (tendsto.comp le_rfl tendsto_snd)) lemma prod_map_map_eq' {α₁ : Type*} {α₂ : Type*} {β₁ : Type*} {β₂ : Type*} (f : α₁ → α₂) (g : β₁ → β₂) (F : filter α₁) (G : filter β₁) : (map f F) ×ᶠ (map g G) = map (prod.map f g) (F ×ᶠ G) := prod_map_map_eq lemma tendsto.prod_map {δ : Type*} {f : α → γ} {g : β → δ} {a : filter α} {b : filter β} {c : filter γ} {d : filter δ} (hf : tendsto f a c) (hg : tendsto g b d) : tendsto (prod.map f g) (a ×ᶠ b) (c ×ᶠ d) := begin erw [tendsto, ← prod_map_map_eq], exact filter.prod_mono hf hg, end lemma map_prod (m : α × β → γ) (f : filter α) (g : filter β) : map m (f ×ᶠ g) = (f.map (λ a b, m (a, b))).seq g := begin simp [filter.ext_iff, mem_prod_iff, mem_map_seq_iff], intro s, split, exact λ ⟨t, ht, s, hs, h⟩, ⟨s, hs, t, ht, λ x hx y hy, @h ⟨x, y⟩ ⟨hx, hy⟩⟩, exact λ ⟨s, hs, t, ht, h⟩, ⟨t, ht, s, hs, λ ⟨x, y⟩ ⟨hx, hy⟩, h x hx y hy⟩ end lemma prod_eq {f : filter α} {g : filter β} : f ×ᶠ g = (f.map prod.mk).seq g := have h : _ := map_prod id f g, by rwa [map_id] at h lemma prod_inf_prod {f₁ f₂ : filter α} {g₁ g₂ : filter β} : (f₁ ×ᶠ g₁) ⊓ (f₂ ×ᶠ g₂) = (f₁ ⊓ f₂) ×ᶠ (g₁ ⊓ g₂) := by simp only [filter.prod, comap_inf, inf_comm, inf_assoc, inf_left_comm] @[simp] lemma prod_bot {f : filter α} : f ×ᶠ (⊥ : filter β) = ⊥ := by simp [filter.prod] @[simp] lemma bot_prod {g : filter β} : (⊥ : filter α) ×ᶠ g = ⊥ := by simp [filter.prod] @[simp] lemma prod_principal_principal {s : set α} {t : set β} : (𝓟 s) ×ᶠ (𝓟 t) = 𝓟 (set.prod s t) := by simp only [filter.prod, comap_principal, principal_eq_iff_eq, comap_principal, inf_principal]; refl @[simp] lemma pure_prod {a : α} {f : filter β} : pure a ×ᶠ f = map (prod.mk a) f := by rw [prod_eq, map_pure, pure_seq_eq_map] @[simp] lemma prod_pure {f : filter α} {b : β} : f ×ᶠ pure b = map (λ a, (a, b)) f := by rw [prod_eq, seq_pure, map_map] lemma prod_pure_pure {a : α} {b : β} : (pure a) ×ᶠ (pure b) = pure (a, b) := by simp lemma prod_eq_bot {f : filter α} {g : filter β} : f ×ᶠ g = ⊥ ↔ (f = ⊥ ∨ g = ⊥) := begin split, { intro h, rcases mem_prod_iff.1 (empty_mem_iff_bot.2 h) with ⟨s, hs, t, ht, hst⟩, rw [subset_empty_iff, set.prod_eq_empty_iff] at hst, cases hst with s_eq t_eq, { left, exact empty_mem_iff_bot.1 (s_eq ▸ hs) }, { right, exact empty_mem_iff_bot.1 (t_eq ▸ ht) } }, { rintro (rfl | rfl), exact bot_prod, exact prod_bot } end lemma prod_ne_bot {f : filter α} {g : filter β} : ne_bot (f ×ᶠ g) ↔ (ne_bot f ∧ ne_bot g) := by simp only [ne_bot_iff, ne, prod_eq_bot, not_or_distrib] lemma ne_bot.prod {f : filter α} {g : filter β} (hf : ne_bot f) (hg : ne_bot g) : ne_bot (f ×ᶠ g) := prod_ne_bot.2 ⟨hf, hg⟩ instance prod_ne_bot' {f : filter α} {g : filter β} [hf : ne_bot f] [hg : ne_bot g] : ne_bot (f ×ᶠ g) := hf.prod hg lemma tendsto_prod_iff {f : α × β → γ} {x : filter α} {y : filter β} {z : filter γ} : filter.tendsto f (x ×ᶠ y) z ↔ ∀ W ∈ z, ∃ U ∈ x, ∃ V ∈ y, ∀ x y, x ∈ U → y ∈ V → f (x, y) ∈ W := by simp only [tendsto_def, mem_prod_iff, prod_sub_preimage_iff, exists_prop, iff_self] end prod /-! ### Coproducts of filters -/ section coprod variables {f : filter α} {g : filter β} /-- Coproduct of filters. -/ protected def coprod (f : filter α) (g : filter β) : filter (α × β) := f.comap prod.fst ⊔ g.comap prod.snd lemma mem_coprod_iff {s : set (α×β)} {f : filter α} {g : filter β} : s ∈ f.coprod g ↔ ((∃ t₁ ∈ f, prod.fst ⁻¹' t₁ ⊆ s) ∧ (∃ t₂ ∈ g, prod.snd ⁻¹' t₂ ⊆ s)) := by simp [filter.coprod] @[mono] lemma coprod_mono {f₁ f₂ : filter α} {g₁ g₂ : filter β} (hf : f₁ ≤ f₂) (hg : g₁ ≤ g₂) : f₁.coprod g₁ ≤ f₂.coprod g₂ := sup_le_sup (comap_mono hf) (comap_mono hg) lemma coprod_ne_bot_iff : (f.coprod g).ne_bot ↔ f.ne_bot ∧ nonempty β ∨ nonempty α ∧ g.ne_bot := by simp [filter.coprod] @[instance] lemma coprod_ne_bot_left [ne_bot f] [nonempty β] : (f.coprod g).ne_bot := coprod_ne_bot_iff.2 (or.inl ⟨‹_›, ‹_›⟩) @[instance] lemma coprod_ne_bot_right [ne_bot g] [nonempty α] : (f.coprod g).ne_bot := coprod_ne_bot_iff.2 (or.inr ⟨‹_›, ‹_›⟩) lemma principal_coprod_principal (s : set α) (t : set β) : (𝓟 s).coprod (𝓟 t) = 𝓟 (sᶜ.prod tᶜ)ᶜ := begin rw [filter.coprod, comap_principal, comap_principal, sup_principal], congr, ext x, simp ; tauto, end -- this inequality can be strict; see `map_const_principal_coprod_map_id_principal` and -- `map_prod_map_const_id_principal_coprod_principal` below. lemma map_prod_map_coprod_le {α₁ : Type u} {α₂ : Type v} {β₁ : Type w} {β₂ : Type x} {f₁ : filter α₁} {f₂ : filter α₂} {m₁ : α₁ → β₁} {m₂ : α₂ → β₂} : map (prod.map m₁ m₂) (f₁.coprod f₂) ≤ (map m₁ f₁).coprod (map m₂ f₂) := begin intros s, simp only [mem_map, mem_coprod_iff], rintro ⟨⟨u₁, hu₁, h₁⟩, u₂, hu₂, h₂⟩, refine ⟨⟨m₁ ⁻¹' u₁, hu₁, λ _ hx, h₁ _⟩, ⟨m₂ ⁻¹' u₂, hu₂, λ _ hx, h₂ _⟩⟩; convert hx end /-- Characterization of the coproduct of the `filter.map`s of two principal filters `𝓟 {a}` and `𝓟 {i}`, the first under the constant function `λ a, b` and the second under the identity function. Together with the next lemma, `map_prod_map_const_id_principal_coprod_principal`, this provides an example showing that the inequality in the lemma `map_prod_map_coprod_le` can be strict. -/ lemma map_const_principal_coprod_map_id_principal {α β ι : Type*} (a : α) (b : β) (i : ι) : (map (λ _ : α, b) (𝓟 {a})).coprod (map id (𝓟 {i})) = 𝓟 (({b} : set β).prod (univ : set ι) ∪ (univ : set β).prod {i}) := begin rw [map_principal, map_principal, principal_coprod_principal], congr, ext ⟨b', i'⟩, simp, tauto, end /-- Characterization of the `filter.map` of the coproduct of two principal filters `𝓟 {a}` and `𝓟 {i}`, under the `prod.map` of two functions, respectively the constant function `λ a, b` and the identity function. Together with the previous lemma, `map_const_principal_coprod_map_id_principal`, this provides an example showing that the inequality in the lemma `map_prod_map_coprod_le` can be strict. -/ lemma map_prod_map_const_id_principal_coprod_principal {α β ι : Type*} (a : α) (b : β) (i : ι) : map (prod.map (λ _ : α, b) id) ((𝓟 {a}).coprod (𝓟 {i})) = 𝓟 (({b} : set β).prod (univ : set ι)) := begin rw [principal_coprod_principal, map_principal], congr, ext ⟨b', i'⟩, split, { rintro ⟨⟨a'', i''⟩, h₁, h₂, h₃⟩, simp }, { rintro ⟨h₁, h₂⟩, use (a, i'), simpa using h₁.symm } end lemma tendsto.prod_map_coprod {δ : Type*} {f : α → γ} {g : β → δ} {a : filter α} {b : filter β} {c : filter γ} {d : filter δ} (hf : tendsto f a c) (hg : tendsto g b d) : tendsto (prod.map f g) (a.coprod b) (c.coprod d) := map_prod_map_coprod_le.trans (coprod_mono hf hg) end coprod /-! ### `n`-ary coproducts of filters -/ section Coprod variables {δ : Type*} {κ : δ → Type*} -- {f : Π d, filter (κ d)} /-- Coproduct of filters. -/ protected def Coprod (f : Π d, filter (κ d)) : filter (Π d, κ d) := ⨆ d : δ, (f d).comap (λ k, k d) lemma mem_Coprod_iff {s : set (Π d, κ d)} {f : Π d, filter (κ d)} : (s ∈ (filter.Coprod f)) ↔ (∀ d : δ, (∃ t₁ ∈ f d, (λ k : (Π d, κ d), k d) ⁻¹' t₁ ⊆ s)) := by simp [filter.Coprod] lemma Coprod_ne_bot_iff' {f : Π d, filter (κ d)} : ne_bot (filter.Coprod f) ↔ (∀ d, nonempty (κ d)) ∧ ∃ d, ne_bot (f d) := by simp only [filter.Coprod, supr_ne_bot, ← exists_and_distrib_left, ← comap_eval_ne_bot_iff'] @[simp] lemma Coprod_ne_bot_iff [∀ d, nonempty (κ d)] {f : Π d, filter (κ d)} : ne_bot (filter.Coprod f) ↔ ∃ d, ne_bot (f d) := by simp [Coprod_ne_bot_iff', *] lemma ne_bot.Coprod [∀ d, nonempty (κ d)] {f : Π d, filter (κ d)} {d : δ} (h : ne_bot (f d)) : ne_bot (filter.Coprod f) := Coprod_ne_bot_iff.2 ⟨d, h⟩ @[instance] lemma Coprod_ne_bot [∀ d, nonempty (κ d)] [nonempty δ] (f : Π d, filter (κ d)) [H : ∀ d, ne_bot (f d)] : ne_bot (filter.Coprod f) := (H (classical.arbitrary δ)).Coprod @[mono] lemma Coprod_mono {f₁ f₂ : Π d, filter (κ d)} (hf : ∀ d, f₁ d ≤ f₂ d) : filter.Coprod f₁ ≤ filter.Coprod f₂ := supr_le_supr $ λ d, comap_mono (hf d) lemma map_pi_map_Coprod_le {μ : δ → Type*} {f : Π d, filter (κ d)} {m : Π d, κ d → μ d} : map (λ (k : Π d, κ d), λ d, m d (k d)) (filter.Coprod f) ≤ filter.Coprod (λ d, map (m d) (f d)) := begin intros s h, rw [mem_map', mem_Coprod_iff], intros d, rw mem_Coprod_iff at h, obtain ⟨t, H, hH⟩ := h d, rw mem_map at H, refine ⟨{x : κ d | m d x ∈ t}, H, _⟩, intros x hx, simp only [mem_set_of_eq, preimage_set_of_eq] at hx, rw mem_set_of_eq, exact set.mem_of_subset_of_mem hH (mem_preimage.mpr hx), end lemma tendsto.pi_map_Coprod {μ : δ → Type*} {f : Π d, filter (κ d)} {m : Π d, κ d → μ d} {g : Π d, filter (μ d)} (hf : ∀ d, tendsto (m d) (f d) (g d)) : tendsto (λ (k : Π d, κ d), λ d, m d (k d)) (filter.Coprod f) (filter.Coprod g) := map_pi_map_Coprod_le.trans (Coprod_mono hf) end Coprod end filter open_locale filter lemma set.eq_on.eventually_eq {α β} {s : set α} {f g : α → β} (h : eq_on f g s) : f =ᶠ[𝓟 s] g := h lemma set.eq_on.eventually_eq_of_mem {α β} {s : set α} {l : filter α} {f g : α → β} (h : eq_on f g s) (hl : s ∈ l) : f =ᶠ[l] g := h.eventually_eq.filter_mono $ filter.le_principal_iff.2 hl lemma set.subset.eventually_le {α} {l : filter α} {s t : set α} (h : s ⊆ t) : s ≤ᶠ[l] t := filter.eventually_of_forall h lemma set.maps_to.tendsto {α β} {s : set α} {t : set β} {f : α → β} (h : maps_to f s t) : filter.tendsto f (𝓟 s) (𝓟 t) := filter.tendsto_principal_principal.2 h
87b21a341dfd69a009e2008ba905fdb2f1d615d2
9cb9db9d79fad57d80ca53543dc07efb7c4f3838
/src/pseudo_normed_group/CLC.lean
24391434f9ad2ee2e6cfc5ef8412532f1c41af06
[]
no_license
mr-infty/lean-liquid
3ff89d1f66244b434654c59bdbd6b77cb7de0109
a8db559073d2101173775ccbd85729d3a4f1ed4d
refs/heads/master
1,678,465,145,334
1,614,565,310,000
1,614,565,310,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
7,286
lean
import pseudo_normed_group.LC import locally_constant.Vhat open_locale classical nnreal noncomputable theory local attribute [instance] type_pow open NormedGroup opposite Profinite pseudo_normed_group category_theory breen_deligne open profinitely_filtered_pseudo_normed_group universe variable u variables (r : ℝ≥0) (V : NormedGroup) variables (r' : ℝ≥0) {M M₁ M₂ M₃ : Type u} variables [profinitely_filtered_pseudo_normed_group_with_Tinv r' M] variables [profinitely_filtered_pseudo_normed_group_with_Tinv r' M₁] variables [profinitely_filtered_pseudo_normed_group_with_Tinv r' M₂] variables [profinitely_filtered_pseudo_normed_group_with_Tinv r' M₃] variables (c c₁ c₂ c₃ c₄ : ℝ≥0) (l m n : ℕ) variables (f : profinitely_filtered_pseudo_normed_group_with_Tinv_hom r' M₁ M₂) variables (g : profinitely_filtered_pseudo_normed_group_with_Tinv_hom r' M₂ M₃) /-- The "functor" that sends `M` and `c` to `V-hat((filtration M c)^n)` -/ def CLCFP (V : NormedGroup) (r' : ℝ≥0) (M : Type*) (c : ℝ≥0) (n : ℕ) [profinitely_filtered_pseudo_normed_group_with_Tinv r' M] : NormedGroup := Completion.obj (LCFP V r' M c n) namespace CLCFP @[simps] def map : CLCFP V r' M₂ c n ⟶ CLCFP V r' M₁ c n := Completion.map (LCFP.map V r' c n f) variables (M) @[simp] lemma map_id : map V r' c n (profinitely_filtered_pseudo_normed_group_with_Tinv_hom.id) = 𝟙 (CLCFP V r' M c n) := by { delta map, rw LCFP.map_id, apply category_theory.functor.map_id } variables {M} lemma map_comp : map V r' c n (g.comp f) = map V r' c n g ≫ map V r' c n f := by { delta map, rw LCFP.map_comp, apply category_theory.functor.map_comp } @[simps] def res [fact (c₁ ≤ c₂)] : CLCFP V r' M c₂ n ⟶ CLCFP V r' M c₁ n := Completion.map (LCFP.res V r' c₁ c₂ n) @[simp] lemma res_refl : @res V r' M _ c c n _ = 𝟙 _ := by { delta res, rw LCFP.res_refl, apply category_theory.functor.map_id } lemma res_comp_res [fact (c₁ ≤ c₂)] [fact (c₂ ≤ c₃)] [fact (c₁ ≤ c₃)] : res V r' c₂ c₃ n ≫ res V r' c₁ c₂ n = @res V r' M _ c₁ c₃ n _ := by simp only [res, ← category_theory.functor.map_comp, ← op_comp, LCFP.res_comp_res] lemma map_comp_res [fact (c₁ ≤ c₂)] : map V r' c₂ n f ≫ res V r' c₁ c₂ n = res V r' c₁ c₂ n ≫ map V r' c₁ n f := by simp only [map, res, ← category_theory.functor.map_comp, ← op_comp, LCFP.map_comp_res] section Tinv open profinitely_filtered_pseudo_normed_group_with_Tinv variables [fact (0 < r')] @[simps] def Tinv : CLCFP V r' M c n ⟶ CLCFP V r' M (r' * c) n := Completion.map (LCFP.Tinv V r' c n) lemma map_comp_Tinv : map V r' c n f ≫ Tinv V r' c n = Tinv V r' c n ≫ map V r' (r' * c) n f := by simp only [Tinv, map, ← category_theory.functor.map_comp, ← op_comp, LCFP.map_comp_Tinv] lemma res_comp_Tinv [fact (c₁ ≤ c₂)] : res V r' c₁ c₂ n ≫ (@Tinv V r' M _ c₁ n _) = Tinv V r' c₂ n ≫ res V r' (r' * c₁) (r' * c₂) n := by simp only [Tinv, res, ← category_theory.functor.map_comp, ← op_comp, LCFP.res_comp_Tinv] end Tinv section T_inv variables [normed_with_aut r V] [fact (0 < r)] @[simps] def T_inv : CLCFP V r' M c n ⟶ CLCFP V r' M c n := Completion.map (LCFP.T_inv r V r' c n) lemma map_comp_T_inv : map V r' c n f ≫ T_inv r V r' c n = T_inv r V r' c n ≫ map V r' c n f := by simp only [T_inv, map, ← category_theory.functor.map_comp, ← op_comp, LCFP.map_comp_T_inv] lemma res_comp_T_inv [fact (c₁ ≤ c₂)] : res V r' c₁ c₂ n ≫ (@T_inv r V r' M _ c₁ n _ _) = T_inv r V r' c₂ n ≫ res V r' c₁ c₂ n := by simp only [T_inv, res, ← category_theory.functor.map_comp, ← op_comp, LCFP.res_comp_T_inv] end T_inv end CLCFP namespace breen_deligne open CLCFP variables (M) {l m n} namespace basic_universal_map variables (ϕ : basic_universal_map m n) @[simps] def eval_CLCFP : CLCFP V r' M c₂ n ⟶ CLCFP V r' M c₁ m := Completion.map (ϕ.eval_LCFP V r' M c₁ c₂) lemma map_comp_eval_CLCFP [ϕ.suitable c₁ c₂] : map V r' c₂ n f ≫ ϕ.eval_CLCFP V r' M₁ c₁ c₂ = ϕ.eval_CLCFP V r' M₂ c₁ c₂ ≫ map V r' c₁ m f := by simp only [map, eval_CLCFP, ← category_theory.functor.map_comp, ← op_comp, map_comp_eval_LCFP] lemma res_comp_eval_CLCFP [fact (c₁ ≤ c₂)] [ϕ.suitable c₂ c₄] [ϕ.suitable c₁ c₃] [fact (c₃ ≤ c₄)] : res V r' c₃ c₄ n ≫ ϕ.eval_CLCFP V r' M c₁ c₃ = ϕ.eval_CLCFP V r' M c₂ c₄ ≫ res V r' c₁ c₂ m := by simp only [res, eval_CLCFP, ← category_theory.functor.map_comp, ← op_comp, res_comp_eval_LCFP V r' _ c₁ c₂ c₃ c₄] lemma Tinv_comp_eval_CLCFP [fact (0 < r')] [ϕ.suitable c₁ c₂] : Tinv V r' c₂ n ≫ ϕ.eval_CLCFP V r' M (r' * c₁) (r' * c₂) = ϕ.eval_CLCFP V r' M c₁ c₂ ≫ Tinv V r' c₁ m := by simp only [Tinv, eval_CLCFP, ← category_theory.functor.map_comp, ← op_comp, Tinv_comp_eval_LCFP V r' _ c₁ c₂] lemma T_inv_comp_eval_CLCFP [normed_with_aut r V] [fact (0 < r)] [ϕ.suitable c₁ c₂] : T_inv r V r' c₂ n ≫ ϕ.eval_CLCFP V r' M c₁ c₂ = ϕ.eval_CLCFP V r' M c₁ c₂ ≫ T_inv r V r' c₁ m := by simp only [T_inv, eval_CLCFP, ← category_theory.functor.map_comp, ← op_comp, T_inv_comp_eval_LCFP r V r' c₁ c₂] end basic_universal_map namespace universal_map variables (ϕ : universal_map m n) def eval_CLCFP : CLCFP V r' M c₂ n ⟶ CLCFP V r' M c₁ m := Completion.map (ϕ.eval_LCFP V r' M c₁ c₂) @[simp] lemma eval_CLCFP_zero : (0 : universal_map m n).eval_CLCFP V r' M c₁ c₂ = 0 := by simp only [eval_CLCFP, eval_LCFP_zero, NormedGroup.Completion.map_zero] open category_theory.limits lemma eval_CLCFP_comp (g : universal_map m n) (f : universal_map l m) [hg : g.suitable c₂ c₃] [hf : f.suitable c₁ c₂] : (comp g f).eval_CLCFP V r' M c₁ c₃ = g.eval_CLCFP V r' M c₂ c₃ ≫ f.eval_CLCFP V r' M c₁ c₂ := by simp only [eval_CLCFP, ← functor.map_comp, eval_LCFP_comp V r' M c₁ c₂ c₃] lemma map_comp_eval_CLCFP [ϕ.suitable c₁ c₂] : map V r' c₂ n f ≫ ϕ.eval_CLCFP V r' M₁ c₁ c₂ = ϕ.eval_CLCFP V r' M₂ c₁ c₂ ≫ map V r' c₁ m f := by simp only [eval_CLCFP, map, ← functor.map_comp, map_comp_eval_LCFP V r' c₁ c₂] lemma res_comp_eval_CLCFP [fact (c₁ ≤ c₂)] [ϕ.suitable c₂ c₄] [ϕ.suitable c₁ c₃] [fact (c₃ ≤ c₄)] : res V r' c₃ c₄ n ≫ ϕ.eval_CLCFP V r' M c₁ c₃ = ϕ.eval_CLCFP V r' M c₂ c₄ ≫ res V r' c₁ c₂ m := by simp only [eval_CLCFP, res, ← functor.map_comp, res_comp_eval_LCFP V r' _ c₁ c₂] lemma Tinv_comp_eval_CLCFP [fact (0 < r')] [ϕ.suitable c₁ c₂] : Tinv V r' c₂ n ≫ ϕ.eval_CLCFP V r' M (r' * c₁) (r' * c₂) = ϕ.eval_CLCFP V r' M c₁ c₂ ≫ Tinv V r' c₁ m := by simp only [eval_CLCFP, Tinv, ← functor.map_comp, Tinv_comp_eval_LCFP V r' _ c₁ c₂] lemma T_inv_comp_eval_CLCFP [normed_with_aut r V] [fact (0 < r)] [ϕ.suitable c₁ c₂] : T_inv r V r' c₂ n ≫ ϕ.eval_CLCFP V r' M₁ c₁ c₂ = ϕ.eval_CLCFP V r' M₁ c₁ c₂ ≫ T_inv r V r' c₁ m := by simp only [eval_CLCFP, T_inv, ← functor.map_comp, T_inv_comp_eval_LCFP r V r' c₁ c₂] end universal_map end breen_deligne
a74a48ee10e26267ea2c3d95d9d6f585307bb058
92bfaf170880e47d55bf51d5a782fffd76db2f5f
/melting_point/graph.lean
37faa4c1e3bda7f94f8bac9b4f5080d384c47086
[]
no_license
forked-from-1kasper/melting_point
d33403e1985d876a2c7c06859962cc0c37570189
e5ea4a0917de086b7e5b122e8d5aa90d2761d147
refs/heads/master
1,624,785,375,577
1,618,305,367,000
1,618,305,367,000
222,729,018
2
0
null
null
null
null
UTF-8
Lean
false
false
2,467
lean
import melting_point.core namespace melting_point.graph universes u v def nat.cases {α : Sort u} (zero : α) (succ : α → α) : ℕ → α | 0 := zero | (n + 1) := succ (nat.cases n) inductive ord | zero | succ : ord → ord | lim : (ℕ → ord) → ord def ord.add : ord → ord → ord | ord.zero y := y | (ord.succ x) y := ord.succ (ord.add x y) | (ord.lim f) y := ord.lim (λ n, ord.add (f n) y) instance : has_zero ord := ⟨ord.zero⟩ instance : has_one ord := ⟨ord.succ 0⟩ instance : has_add ord := ⟨ord.add⟩ def ord.finite : ℕ → ord := nat.cases ord.zero ord.succ def ω := ord.lim ord.finite inductive iszero : ord → Prop | intro : iszero 0 def nonzero : ord → Prop := not ∘ iszero instance iszero.dec : decidable_pred iszero := begin intro x, cases x, { apply decidable.is_true, exact iszero.intro }, repeat { apply decidable.is_false, intro h, cases h } end def graph (α : Type u) := α → α → ord def flat {α : Type u} (G : graph α) : α → α → Prop := λ x y, nonzero (G x y) inductive R {α : Type u} (φ : α → α → Prop) : α → α → Prop | refl {x : α} : R x x | intro {x y : α} : φ x y → R x y def S {α : Type u} (φ : α → α → Prop) := λ x y, φ x y ∨ φ y x inductive T {α : Type u} (φ : α → α → Prop) : α → α → Prop | intro {x y : α} : φ x y → T x y | trans {x y z : α} : T x y → T y z → T x z def equivalence {α : Type u} (φ : α → α → Prop) := R (S (T φ)) def way {α : Type u} (G : graph α) := T (flat G) def path {α : Type u} (G : graph α) := equivalence (flat G) def path.inj {α : Type u} (G : graph α) {x y : α} : way G x y → path G x y := R.intro ∘ or.inl def unidirectional {α : Type u} (G : graph α) := ∀ x y, iszero (G x y) ∨ iszero (G y x) def acyclic {α : Type u} (G : graph α) : Prop := ∀ x, ¬way G x x def full {α : Type u} (φ : α → α → Prop) := ∀ x y, φ x y def complete {α : Type u} (G : graph α) := full (flat G) def connected {α : Type u} (G : graph α) := full (path G) def tree {α : Type u} (G : graph α) := connected G ∧ acyclic G inductive Koenigsberg | Altstadt | Kneiphof | Lomse | Vorstadt namespace Koenigsberg def G : graph Koenigsberg | Kneiphof Lomse := 1 | Altstadt Lomse := 1 | Lomse Vorstadt := 1 | Altstadt Kneiphof := 2 | Altstadt Vorstadt := 2 | _ _ := 0 end Koenigsberg end melting_point.graph
a942edd0dafd12a2ea199a9bedeb469009b6fb8d
9dd3f3912f7321eb58ee9aa8f21778ad6221f87c
/tests/lean/run/rw_set3.lean
e96522db7f8a2c452de0b712dbc6ffb230878069
[ "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
217
lean
open tactic nat constant f : nat → nat constant g : nat → nat axiom foo : ∀ x, f x = 1 axiom bla : ∀ x, f x = 2 attribute [simp] foo attribute [simp] bla print [simp] default example : f 5 = 2 := by simp
06e07ae839fda45b276d6e848b9f70ee511e5d8c
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/linear_algebra/matrix/zpow.lean
70ea8d648dac7722998d4d8b2458e64137f37ba0
[ "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
12,436
lean
/- Copyright (c) 2021 Yakov Pechersky. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yakov Pechersky -/ import linear_algebra.matrix.nonsingular_inverse /-! # Integer powers of square matrices In this file, we define integer power of matrices, relying on the nonsingular inverse definition for negative powers. ## Implementation details The main definition is a direct recursive call on the integer inductive type, as provided by the `div_inv_monoid.zpow` default implementation. The lemma names are taken from `algebra.group_with_zero.power`. ## Tags matrix inverse, matrix powers -/ open_locale matrix namespace matrix variables {n' : Type*} [decidable_eq n'] [fintype n'] {R : Type*} [comm_ring R] local notation `M` := matrix n' n' R noncomputable instance : div_inv_monoid M := { ..(show monoid M, by apply_instance), ..(show has_inv M, by apply_instance) } section nat_pow @[simp] theorem inv_pow' (A : M) (n : ℕ) : (A⁻¹) ^ n = (A ^ n)⁻¹ := begin induction n with n ih, { simp }, { rw [pow_succ A, mul_eq_mul, mul_inv_rev, ← ih, ← mul_eq_mul, ← pow_succ'] } end theorem pow_sub' (A : M) {m n : ℕ} (ha : is_unit A.det) (h : n ≤ m) : A ^ (m - n) = A ^ m ⬝ (A ^ n)⁻¹ := begin rw [←tsub_add_cancel_of_le h, pow_add, mul_eq_mul, matrix.mul_assoc, mul_nonsing_inv, tsub_add_cancel_of_le h, matrix.mul_one], simpa using ha.pow n end theorem pow_inv_comm' (A : M) (m n : ℕ) : (A⁻¹) ^ m ⬝ A ^ n = A ^ n ⬝ (A⁻¹) ^ m := begin induction n with n IH generalizing m, { simp }, cases m, { simp }, rcases nonsing_inv_cancel_or_zero A with ⟨h, h'⟩ | h, { calc A⁻¹ ^ (m + 1) ⬝ A ^ (n + 1) = A⁻¹ ^ m ⬝ (A⁻¹ ⬝ A) ⬝ A ^ n : by simp only [pow_succ' A⁻¹, pow_succ A, mul_eq_mul, matrix.mul_assoc] ... = A ^ n ⬝ A⁻¹ ^ m : by simp only [h, matrix.mul_one, matrix.one_mul, IH m] ... = A ^ n ⬝ (A ⬝ A⁻¹) ⬝ A⁻¹ ^ m : by simp only [h', matrix.mul_one, matrix.one_mul] ... = A ^ (n + 1) ⬝ A⁻¹ ^ (m + 1) : by simp only [pow_succ' A, pow_succ A⁻¹, mul_eq_mul, matrix.mul_assoc] }, { simp [h] } end end nat_pow section zpow open int @[simp] theorem one_zpow : ∀ (n : ℤ), (1 : M) ^ n = 1 | (n : ℕ) := by rw [zpow_coe_nat, one_pow] | -[1+ n] := by rw [zpow_neg_succ_of_nat, one_pow, inv_one] lemma zero_zpow : ∀ z : ℤ, z ≠ 0 → (0 : M) ^ z = 0 | (n : ℕ) h := by { rw [zpow_coe_nat, zero_pow], refine lt_of_le_of_ne n.zero_le (ne.symm _), simpa using h } | -[1+n] h := by simp [zero_pow n.zero_lt_succ] lemma zero_zpow_eq (n : ℤ) : (0 : M) ^ n = if n = 0 then 1 else 0 := begin split_ifs with h, { rw [h, zpow_zero] }, { rw [zero_zpow _ h] } end theorem inv_zpow (A : M) : ∀n:ℤ, A⁻¹ ^ n = (A ^ n)⁻¹ | (n : ℕ) := by rw [zpow_coe_nat, zpow_coe_nat, inv_pow'] | -[1+ n] := by rw [zpow_neg_succ_of_nat, zpow_neg_succ_of_nat, inv_pow'] @[simp] lemma zpow_neg_one (A : M) : A ^ (-1 : ℤ) = A⁻¹ := begin convert div_inv_monoid.zpow_neg' 0 A, simp only [zpow_one, int.coe_nat_zero, int.coe_nat_succ, zpow_eq_pow, zero_add] end theorem zpow_coe_nat (A : M) (n : ℕ) : A ^ (n : ℤ) = (A ^ n) := zpow_coe_nat _ _ @[simp] theorem zpow_neg_coe_nat (A : M) (n : ℕ) : A ^ (-n : ℤ) = (A ^ n)⁻¹ := begin cases n, { simp }, { exact div_inv_monoid.zpow_neg' _ _ } end lemma _root_.is_unit.det_zpow {A : M} (h : is_unit A.det) (n : ℤ) : is_unit (A ^ n).det := begin cases n, { simpa using h.pow n }, { simpa using h.pow n.succ } end lemma is_unit_det_zpow_iff {A : M} {z : ℤ} : is_unit (A ^ z).det ↔ is_unit A.det ∨ z = 0 := begin induction z using int.induction_on with z IH z IH, { simp }, { rw [←int.coe_nat_succ, zpow_coe_nat, det_pow, is_unit_pow_succ_iff, ←int.coe_nat_zero, int.coe_nat_eq_coe_nat_iff], simp }, { rw [←neg_add', ←int.coe_nat_succ, zpow_neg_coe_nat, is_unit_nonsing_inv_det_iff, det_pow, is_unit_pow_succ_iff, neg_eq_zero, ←int.coe_nat_zero, int.coe_nat_eq_coe_nat_iff], simp } end theorem zpow_neg {A : M} (h : is_unit A.det) : ∀ (n : ℤ), A ^ -n = (A ^ n)⁻¹ | (n : ℕ) := zpow_neg_coe_nat _ _ | -[1+ n] := by { rw [zpow_neg_succ_of_nat, neg_neg_of_nat_succ, of_nat_eq_coe, zpow_coe_nat, nonsing_inv_nonsing_inv], rw det_pow, exact h.pow _ } lemma inv_zpow' {A : M} (h : is_unit A.det) (n : ℤ) : (A ⁻¹) ^ n = A ^ (-n) := by rw [zpow_neg h, inv_zpow] lemma zpow_add_one {A : M} (h : is_unit A.det) : ∀ n : ℤ, A ^ (n + 1) = A ^ n * A | (n : ℕ) := by simp only [← nat.cast_succ, pow_succ', zpow_coe_nat] | -((n : ℕ) + 1) := calc A ^ (-(n + 1) + 1 : ℤ) = (A ^ n)⁻¹ : by rw [neg_add, neg_add_cancel_right, zpow_neg h, zpow_coe_nat] ... = (A ⬝ A ^ n)⁻¹ ⬝ A : by rw [mul_inv_rev, matrix.mul_assoc, nonsing_inv_mul _ h, matrix.mul_one] ... = A ^ -(n + 1 : ℤ) * A : by rw [zpow_neg h, ← int.coe_nat_succ, zpow_coe_nat, pow_succ, mul_eq_mul, mul_eq_mul] lemma zpow_sub_one {A : M} (h : is_unit A.det) (n : ℤ) : A ^ (n - 1) = A ^ n * A⁻¹ := calc A ^ (n - 1) = A ^ (n - 1) * A * A⁻¹ : by rw [mul_assoc, mul_eq_mul A, mul_nonsing_inv _ h, mul_one] ... = A^n * A⁻¹ : by rw [← zpow_add_one h, sub_add_cancel] lemma zpow_add {A : M} (ha : is_unit A.det) (m n : ℤ) : A ^ (m + n) = A ^ m * A ^ n := begin induction n using int.induction_on with n ihn n ihn, case hz : { simp }, { simp only [← add_assoc, zpow_add_one ha, ihn, mul_assoc] }, { rw [zpow_sub_one ha, ← mul_assoc, ← ihn, ← zpow_sub_one ha, add_sub_assoc] } end lemma zpow_add_of_nonpos {A : M} {m n : ℤ} (hm : m ≤ 0) (hn : n ≤ 0) : A ^ (m + n) = A ^ m * A ^ n := begin rcases nonsing_inv_cancel_or_zero A with ⟨h, h'⟩ | h, { exact zpow_add (is_unit_det_of_left_inverse h) m n }, { obtain ⟨k, rfl⟩ := exists_eq_neg_of_nat hm, obtain ⟨l, rfl⟩ := exists_eq_neg_of_nat hn, simp_rw [←neg_add, ←int.coe_nat_add, zpow_neg_coe_nat, ←inv_pow', h, pow_add] } end lemma zpow_add_of_nonneg {A : M} {m n : ℤ} (hm : 0 ≤ m) (hn : 0 ≤ n) : A ^ (m + n) = A ^ m * A ^ n := begin obtain ⟨k, rfl⟩ := eq_coe_of_zero_le hm, obtain ⟨l, rfl⟩ := eq_coe_of_zero_le hn, rw [←int.coe_nat_add, zpow_coe_nat, zpow_coe_nat, zpow_coe_nat, pow_add], end theorem zpow_one_add {A : M} (h : is_unit A.det) (i : ℤ) : A ^ (1 + i) = A * A ^ i := by rw [zpow_add h, zpow_one] theorem semiconj_by.zpow_right {A X Y : M} (hx : is_unit X.det) (hy : is_unit Y.det) (h : semiconj_by A X Y) : ∀ m : ℤ, semiconj_by A (X^m) (Y^m) | (n : ℕ) := by simp [h.pow_right n] | -[1+n] := begin have hx' : is_unit (X ^ n.succ).det, { rw det_pow, exact hx.pow n.succ }, have hy' : is_unit (Y ^ n.succ).det, { rw det_pow, exact hy.pow n.succ }, rw [zpow_neg_succ_of_nat, zpow_neg_succ_of_nat, nonsing_inv_apply _ hx', nonsing_inv_apply _ hy', semiconj_by], refine (is_regular_of_is_left_regular_det hy'.is_regular.left).left _, rw [←mul_assoc, ←(h.pow_right n.succ).eq, mul_assoc, mul_eq_mul (X ^ _), mul_smul, mul_adjugate, mul_eq_mul, mul_eq_mul, mul_eq_mul, ←matrix.mul_assoc, mul_smul (Y ^ _) (↑(hy'.unit)⁻¹ : R), mul_adjugate, smul_smul, smul_smul, hx'.coe_inv_mul, hy'.coe_inv_mul, one_smul, matrix.mul_one, matrix.one_mul], end theorem commute.zpow_right {A B : M} (h : commute A B) (m : ℤ) : commute A (B^m) := begin rcases nonsing_inv_cancel_or_zero B with ⟨hB, hB'⟩ | hB, { refine semiconj_by.zpow_right _ _ h _; exact is_unit_det_of_left_inverse hB }, { cases m, { simpa using h.pow_right _ }, { simp [←inv_pow', hB] } } end theorem commute.zpow_left {A B : M} (h : commute A B) (m : ℤ) : commute (A^m) B := (commute.zpow_right h.symm m).symm theorem commute.zpow_zpow {A B : M} (h : commute A B) (m n : ℤ) : commute (A^m) (B^n) := commute.zpow_right (commute.zpow_left h _) _ theorem commute.zpow_self (A : M) (n : ℤ) : commute (A^n) A := commute.zpow_left (commute.refl A) _ theorem commute.self_zpow (A : M) (n : ℤ) : commute A (A^n) := commute.zpow_right (commute.refl A) _ theorem commute.zpow_zpow_self (A : M) (m n : ℤ) : commute (A^m) (A^n) := commute.zpow_zpow (commute.refl A) _ _ theorem zpow_bit0 (A : M) (n : ℤ) : A ^ bit0 n = A ^ n * A ^ n := begin cases le_total 0 n with nonneg nonpos, { exact zpow_add_of_nonneg nonneg nonneg }, { exact zpow_add_of_nonpos nonpos nonpos } end lemma zpow_add_one_of_ne_neg_one {A : M} : ∀ (n : ℤ), n ≠ -1 → A ^ (n + 1) = A ^ n * A | (n : ℕ) _ := by simp only [pow_succ', ← nat.cast_succ, zpow_coe_nat] | (-1) h := absurd rfl h | (-((n : ℕ) + 2)) _ := begin rcases nonsing_inv_cancel_or_zero A with ⟨h, h'⟩ | h, { apply zpow_add_one (is_unit_det_of_left_inverse h) }, { show A ^ (-((n + 1 : ℕ) : ℤ)) = A ^ -((n + 2 : ℕ) : ℤ) * A, simp_rw [zpow_neg_coe_nat, ←inv_pow', h, zero_pow nat.succ_pos', zero_mul] } end theorem zpow_bit1 (A : M) (n : ℤ) : A ^ bit1 n = A ^ n * A ^ n * A := begin rw [bit1, zpow_add_one_of_ne_neg_one, zpow_bit0], intro h, simpa using congr_arg bodd h end theorem zpow_mul (A : M) (h : is_unit A.det) : ∀ m n : ℤ, A ^ (m * n) = (A ^ m) ^ n | (m : ℕ) (n : ℕ) := by rw [zpow_coe_nat, zpow_coe_nat, ← pow_mul, ← zpow_coe_nat, int.coe_nat_mul] | (m : ℕ) -[1+ n] := by rw [zpow_coe_nat, zpow_neg_succ_of_nat, ← pow_mul, coe_nat_mul_neg_succ, ←int.coe_nat_mul, zpow_neg_coe_nat] | -[1+ m] (n : ℕ) := by rw [zpow_coe_nat, zpow_neg_succ_of_nat, ← inv_pow', ← pow_mul, neg_succ_mul_coe_nat, ←int.coe_nat_mul, zpow_neg_coe_nat, inv_pow'] | -[1+ m] -[1+ n] := by { rw [zpow_neg_succ_of_nat, zpow_neg_succ_of_nat, neg_succ_mul_neg_succ, ←int.coe_nat_mul, zpow_coe_nat, inv_pow', ←pow_mul, nonsing_inv_nonsing_inv], rw det_pow, exact h.pow _ } theorem zpow_mul' (A : M) (h : is_unit A.det) (m n : ℤ) : A ^ (m * n) = (A ^ n) ^ m := by rw [mul_comm, zpow_mul _ h] @[simp, norm_cast] lemma coe_units_zpow (u : Mˣ) : ∀ (n : ℤ), ((u ^ n : Mˣ) : M) = u ^ n | (n : ℕ) := by rw [_root_.zpow_coe_nat, zpow_coe_nat, units.coe_pow] | -[1+k] := by rw [zpow_neg_succ_of_nat, zpow_neg_succ_of_nat, ←inv_pow, u⁻¹.coe_pow, ←inv_pow', coe_units_inv] lemma zpow_ne_zero_of_is_unit_det [nonempty n'] [nontrivial R] {A : M} (ha : is_unit A.det) (z : ℤ) : A ^ z ≠ 0 := begin have := ha.det_zpow z, contrapose! this, rw [this, det_zero ‹_›], exact not_is_unit_zero end lemma zpow_sub {A : M} (ha : is_unit A.det) (z1 z2 : ℤ) : A ^ (z1 - z2) = A ^ z1 / A ^ z2 := by rw [sub_eq_add_neg, zpow_add ha, zpow_neg ha, div_eq_mul_inv] lemma commute.mul_zpow {A B : M} (h : commute A B) : ∀ (i : ℤ), (A * B) ^ i = (A ^ i) * (B ^ i) | (n : ℕ) := by simp [h.mul_pow n, -mul_eq_mul] | -[1+n] := by rw [zpow_neg_succ_of_nat, zpow_neg_succ_of_nat, zpow_neg_succ_of_nat, mul_eq_mul (_⁻¹), ←mul_inv_rev, ←mul_eq_mul, h.mul_pow n.succ, (h.pow_pow _ _).eq] theorem zpow_bit0' (A : M) (n : ℤ) : A ^ bit0 n = (A * A) ^ n := (zpow_bit0 A n).trans (commute.mul_zpow (commute.refl A) n).symm theorem zpow_bit1' (A : M) (n : ℤ) : A ^ bit1 n = (A * A) ^ n * A := by rw [zpow_bit1, commute.mul_zpow (commute.refl A)] theorem zpow_neg_mul_zpow_self (n : ℤ) {A : M} (h : is_unit A.det) : A ^ (-n) * A ^ n = 1 := by rw [zpow_neg h, mul_eq_mul, nonsing_inv_mul _ (h.det_zpow _)] theorem one_div_pow {A : M} (n : ℕ) : (1 / A) ^ n = 1 / A ^ n := by simp only [one_div, inv_pow'] theorem one_div_zpow {A : M} (n : ℤ) : (1 / A) ^ n = 1 / A ^ n := by simp only [one_div, inv_zpow] @[simp] theorem transpose_zpow (A : M) : ∀ (n : ℤ), (A ^ n)ᵀ = Aᵀ ^ n | (n : ℕ) := by rw [zpow_coe_nat, zpow_coe_nat, transpose_pow] | -[1+ n] := by rw [zpow_neg_succ_of_nat, zpow_neg_succ_of_nat, transpose_nonsing_inv, transpose_pow] @[simp] theorem conj_transpose_zpow [star_ring R] (A : M) : ∀ (n : ℤ), (A ^ n)ᴴ = Aᴴ ^ n | (n : ℕ) := by rw [zpow_coe_nat, zpow_coe_nat, conj_transpose_pow] | -[1+ n] := by rw [zpow_neg_succ_of_nat, zpow_neg_succ_of_nat, conj_transpose_nonsing_inv, conj_transpose_pow] end zpow end matrix
35a2ce0707686a5e043d2fa765e692287698da08
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/algebra/category/Group/biproducts.lean
77988d003a749a9ce998ce4dc2a54395bfa2f837
[ "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
3,608
lean
/- Copyright (c) 2020 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import algebra.group.pi import algebra.category.Group.preadditive import category_theory.limits.shapes.biproducts import algebra.category.Group.limits /-! # The category of abelian groups has finite biproducts -/ open category_theory open category_theory.limits open_locale big_operators universe u namespace AddCommGroup /-- Construct limit data for a binary product in `AddCommGroup`, using `AddCommGroup.of (G × H)`. -/ def binary_product_limit_cone (G H : AddCommGroup.{u}) : limits.limit_cone (pair G H) := { cone := { X := AddCommGroup.of (G × H), π := { app := λ j, walking_pair.cases_on j (add_monoid_hom.fst G H) (add_monoid_hom.snd G H) }}, is_limit := { lift := λ s, add_monoid_hom.prod (s.π.app walking_pair.left) (s.π.app walking_pair.right), fac' := begin rintros s (⟨⟩|⟨⟩); { ext x, simp, }, end, uniq' := λ s m w, begin ext; [rw ← w walking_pair.left, rw ← w walking_pair.right]; refl, end, } } instance has_binary_product (G H : AddCommGroup.{u}) : has_binary_product G H := has_limit.mk (binary_product_limit_cone G H) instance (G H : AddCommGroup.{u}) : has_binary_biproduct G H := has_binary_biproduct.of_has_binary_product _ _ /-- We verify that the biproduct in AddCommGroup is isomorphic to the cartesian product of the underlying types: -/ noncomputable def biprod_iso_prod (G H : AddCommGroup.{u}) : (G ⊞ H : AddCommGroup) ≅ AddCommGroup.of (G × H) := is_limit.cone_point_unique_up_to_iso (binary_biproduct.is_limit G H) (binary_product_limit_cone G H).is_limit -- Furthermore, our biproduct will automatically function as a coproduct. example (G H : AddCommGroup.{u}) : has_colimit (pair G H) := by apply_instance variables {J : Type u} (F : (discrete J) ⥤ AddCommGroup.{u}) namespace has_limit /-- The map from an arbitrary cone over a indexed family of abelian groups to the cartesian product of those groups. -/ def lift (s : cone F) : s.X ⟶ AddCommGroup.of (Π j, F.obj j) := { to_fun := λ x j, s.π.app j x, map_zero' := by { ext, simp }, map_add' := λ x y, by { ext, simp }, } @[simp] lemma lift_apply (s : cone F) (x : s.X) (j : J) : (lift F s) x j = s.π.app j x := rfl /-- Construct limit data for a product in `AddCommGroup`, using `AddCommGroup.of (Π j, F.obj j)`. -/ def product_limit_cone : limits.limit_cone F := { cone := { X := AddCommGroup.of (Π j, F.obj j), π := discrete.nat_trans (λ j, pi.eval_add_monoid_hom (λ j, F.obj j) j), }, is_limit := { lift := lift F, fac' := λ s j, by { ext, simp, }, uniq' := λ s m w, begin ext x j, dsimp only [has_limit.lift], simp only [add_monoid_hom.coe_mk], exact congr_arg (λ f : s.X ⟶ F.obj j, (f : s.X → F.obj j) x) (w j), end, }, } end has_limit section open has_limit variables [decidable_eq J] [fintype J] instance (f : J → AddCommGroup.{u}) : has_biproduct f := has_biproduct.of_has_product _ /-- We verify that the biproduct we've just defined is isomorphic to the AddCommGroup structure on the dependent function type -/ noncomputable def biproduct_iso_pi (f : J → AddCommGroup.{u}) : (⨁ f : AddCommGroup) ≅ AddCommGroup.of (Π j, f j) := is_limit.cone_point_unique_up_to_iso (biproduct.is_limit f) (product_limit_cone (discrete.functor f)).is_limit end instance : has_finite_biproducts AddCommGroup := ⟨λ J _ _, by exactI { has_biproduct := λ f, by apply_instance }⟩ end AddCommGroup
947b5b3c302a1caeb3a5d877f33b116b2f96b0b1
9e90bb7eb4d1bde1805f9eb6187c333fdf09588a
/src/stump/setup_definition.lean
1d6f83a297ac1fa095fcced9b69fd2f87433fdf1
[ "Apache-2.0" ]
permissive
alexjbest/stump-learnable
6311d0c3a1a1a0e65ce83edcbb3b4b7cecabb851
f8fd812fc646d2ece312ff6ffc2a19848ac76032
refs/heads/master
1,659,486,805,691
1,590,454,024,000
1,590,454,024,000
266,173,720
0
0
Apache-2.0
1,590,169,884,000
1,590,169,883,000
null
UTF-8
Lean
false
false
959
lean
/- Copyright © 2019, Oracle and/or its affiliates. All rights reserved. -/ import measure_theory.measurable_space import measure_theory.borel_space import topology.instances.nnreal import ..lib.basic import ..lib.util namespace stump notation `ℍ` := nnreal noncomputable instance meas_ℍ: measurable_space ℍ := begin apply_instance, end noncomputable instance topo_ℍ: topological_space ℍ := begin apply_instance, end noncomputable instance meas_lbl: measurable_space (ℍ × bool) := begin apply_instance, end variables (μ: probability_measure ℍ) (target: ℍ) noncomputable def rlt (x: nnreal) (y: nnreal) : bool := x < y noncomputable def rle (x: nnreal) (y: nnreal) : bool := x ≤ y noncomputable def label (target: ℍ): ℍ → ℍ × bool := λ x: ℍ, (x,rle x target) def error_set (h: ℍ) := {x: ℍ | label h x ≠ label target x} noncomputable def error := λ h, μ (error_set h target) end stump
d4da6ff6bda8ac44170e43138898e2169c795cb9
43dcf09a5df9dc4729cdc024e8680eeaacd05af3
/order.lean
0e46a1b074ed88fe72c31f196da4d16254e035ac
[]
no_license
khoek/lmath
f9ea911aabee1eb276a5319e70a5e62e6bfe8fb1
a4f35205e6b5a3f16926234bf8eb7f7b5f56e47f
refs/heads/master
1,611,452,778,710
1,532,531,556,000
1,532,569,670,000
122,820,532
0
0
null
null
null
null
UTF-8
Lean
false
false
331
lean
structure order (α : Type) := mk :: (sim : α → α → Prop) (h_refl : ∀ a : α, sim a a) (h_antisymm : ∀ a b : α, sim a b ∧ sim b a → a = b) (h_trans : ∀ a b c : α, sim a b → sim b c → sim a b) structure total_order (α : Type) extends order α := mk :: (h_total : ∀ a b : α, sim a b ∨ sim b a)
82d73064eb5b31e34290c1288965ab3daf79c382
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/topology/algebra/infinite_sum_auto.lean
0629b58b1387a73a9b413b46d7dfbbc0a4fd0724
[]
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
54,545
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 Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.algebra.big_operators.intervals import Mathlib.topology.instances.real import Mathlib.topology.algebra.module import Mathlib.data.indicator_function import Mathlib.data.equiv.encodable.lattice import Mathlib.order.filter.at_top_bot import Mathlib.PostPort universes u_1 u_2 u_3 u_4 u_5 u_6 namespace Mathlib /-! # Infinite sum over a topological monoid This sum is known as unconditionally convergent, as it sums to the same value under all possible permutations. For Euclidean spaces (finite dimensional Banach spaces) this is equivalent to absolute convergence. Note: There are summable sequences which are not unconditionally convergent! The other way holds generally, see `has_sum.tendsto_sum_nat`. ## References * Bourbaki: General Topology (1995), Chapter 3 §5 (Infinite sums in commutative groups) -/ /-- Infinite sum on a topological monoid The `at_top` filter on `finset β` is the limit of all finite sets towards the entire type. So we sum up bigger and bigger sets. This sum operation is invariant under reordering. In particular, the function `ℕ → ℝ` sending `n` to `(-1)^n / (n+1)` does not have a sum for this definition, but a series which is absolutely convergent will have the correct sum. This is based on Mario Carneiro's [infinite sum `df-tsms` in Metamath](http://us.metamath.org/mpeuni/df-tsms.html). For the definition or many statements, `α` does not need to be a topological monoid. We only add this assumption later, for the lemmas where it is relevant. -/ def has_sum {α : Type u_1} {β : Type u_2} [add_comm_monoid α] [topological_space α] (f : β → α) (a : α) := filter.tendsto (fun (s : finset β) => finset.sum s fun (b : β) => f b) filter.at_top (nhds a) /-- `summable f` means that `f` has some (infinite) sum. Use `tsum` to get the value. -/ def summable {α : Type u_1} {β : Type u_2} [add_comm_monoid α] [topological_space α] (f : β → α) := ∃ (a : α), has_sum f a /-- `∑' i, f i` is the sum of `f` it exists, or 0 otherwise -/ def tsum {α : Type u_1} [add_comm_monoid α] [topological_space α] {β : Type u_2} (f : β → α) : α := dite (summable f) (fun (h : summable f) => classical.some h) fun (h : ¬summable f) => 0 -- see Note [operator precedence of big operators] theorem summable.has_sum {α : Type u_1} {β : Type u_2} [add_comm_monoid α] [topological_space α] {f : β → α} (ha : summable f) : has_sum f (tsum fun (b : β) => f b) := sorry theorem has_sum.summable {α : Type u_1} {β : Type u_2} [add_comm_monoid α] [topological_space α] {f : β → α} {a : α} (h : has_sum f a) : summable f := Exists.intro a h /-- Constant zero function has sum `0` -/ theorem has_sum_zero {α : Type u_1} {β : Type u_2} [add_comm_monoid α] [topological_space α] : has_sum (fun (b : β) => 0) 0 := sorry theorem summable_zero {α : Type u_1} {β : Type u_2} [add_comm_monoid α] [topological_space α] : summable fun (b : β) => 0 := has_sum.summable has_sum_zero theorem tsum_eq_zero_of_not_summable {α : Type u_1} {β : Type u_2} [add_comm_monoid α] [topological_space α] {f : β → α} (h : ¬summable f) : (tsum fun (b : β) => f b) = 0 := sorry theorem has_sum.has_sum_of_sum_eq {α : Type u_1} {β : Type u_2} {γ : Type u_3} [add_comm_monoid α] [topological_space α] {f : β → α} {a : α} {g : γ → α} (h_eq : ∀ (u : finset γ), ∃ (v : finset β), ∀ (v' : finset β), v ⊆ v' → ∃ (u' : finset γ), u ⊆ u' ∧ (finset.sum u' fun (x : γ) => g x) = finset.sum v' fun (b : β) => f b) (hf : has_sum g a) : has_sum f a := le_trans (filter.map_at_top_finset_sum_le_of_sum_eq h_eq) hf theorem has_sum_iff_has_sum {α : Type u_1} {β : Type u_2} {γ : Type u_3} [add_comm_monoid α] [topological_space α] {f : β → α} {a : α} {g : γ → α} (h₁ : ∀ (u : finset γ), ∃ (v : finset β), ∀ (v' : finset β), v ⊆ v' → ∃ (u' : finset γ), u ⊆ u' ∧ (finset.sum u' fun (x : γ) => g x) = finset.sum v' fun (b : β) => f b) (h₂ : ∀ (v : finset β), ∃ (u : finset γ), ∀ (u' : finset γ), u ⊆ u' → ∃ (v' : finset β), v ⊆ v' ∧ (finset.sum v' fun (b : β) => f b) = finset.sum u' fun (x : γ) => g x) : has_sum f a ↔ has_sum g a := { mp := has_sum.has_sum_of_sum_eq h₂, mpr := has_sum.has_sum_of_sum_eq h₁ } theorem function.injective.has_sum_iff {α : Type u_1} {β : Type u_2} {γ : Type u_3} [add_comm_monoid α] [topological_space α] {f : β → α} {a : α} {g : γ → β} (hg : function.injective g) (hf : ∀ (x : β), ¬x ∈ set.range g → f x = 0) : has_sum (f ∘ g) a ↔ has_sum f a := sorry theorem function.injective.summable_iff {α : Type u_1} {β : Type u_2} {γ : Type u_3} [add_comm_monoid α] [topological_space α] {f : β → α} {g : γ → β} (hg : function.injective g) (hf : ∀ (x : β), ¬x ∈ set.range g → f x = 0) : summable (f ∘ g) ↔ summable f := exists_congr fun (_x : α) => function.injective.has_sum_iff hg hf theorem has_sum_subtype_iff_of_support_subset {α : Type u_1} {β : Type u_2} [add_comm_monoid α] [topological_space α] {f : β → α} {a : α} {s : set β} (hf : function.support f ⊆ s) : has_sum (f ∘ coe) a ↔ has_sum f a := sorry theorem has_sum_subtype_iff_indicator {α : Type u_1} {β : Type u_2} [add_comm_monoid α] [topological_space α] {f : β → α} {a : α} {s : set β} : has_sum (f ∘ coe) a ↔ has_sum (set.indicator s f) a := sorry @[simp] theorem has_sum_subtype_support {α : Type u_1} {β : Type u_2} [add_comm_monoid α] [topological_space α] {f : β → α} {a : α} : has_sum (f ∘ coe) a ↔ has_sum f a := has_sum_subtype_iff_of_support_subset (set.subset.refl (function.support f)) theorem has_sum_fintype {α : Type u_1} {β : Type u_2} [add_comm_monoid α] [topological_space α] [fintype β] (f : β → α) : has_sum f (finset.sum finset.univ fun (b : β) => f b) := order_top.tendsto_at_top_nhds fun (s : finset β) => finset.sum s fun (b : β) => f b protected theorem finset.has_sum {α : Type u_1} {β : Type u_2} [add_comm_monoid α] [topological_space α] (s : finset β) (f : β → α) : has_sum (f ∘ coe) (finset.sum s fun (b : β) => f b) := eq.mpr (id (Eq._oldrec (Eq.refl (has_sum (f ∘ coe) (finset.sum s fun (b : β) => f b))) (Eq.symm finset.sum_attach))) (has_sum_fintype (f ∘ coe)) protected theorem finset.summable {α : Type u_1} {β : Type u_2} [add_comm_monoid α] [topological_space α] (s : finset β) (f : β → α) : summable (f ∘ coe) := has_sum.summable (finset.has_sum s f) protected theorem set.finite.summable {α : Type u_1} {β : Type u_2} [add_comm_monoid α] [topological_space α] {s : set β} (hs : set.finite s) (f : β → α) : summable (f ∘ coe) := sorry /-- If a function `f` vanishes outside of a finite set `s`, then it `has_sum` `∑ b in s, f b`. -/ theorem has_sum_sum_of_ne_finset_zero {α : Type u_1} {β : Type u_2} [add_comm_monoid α] [topological_space α] {f : β → α} {s : finset β} (hf : ∀ (b : β), ¬b ∈ s → f b = 0) : has_sum f (finset.sum s fun (b : β) => f b) := iff.mp (has_sum_subtype_iff_of_support_subset (iff.mpr function.support_subset_iff' hf)) (finset.has_sum s f) theorem summable_of_ne_finset_zero {α : Type u_1} {β : Type u_2} [add_comm_monoid α] [topological_space α] {f : β → α} {s : finset β} (hf : ∀ (b : β), ¬b ∈ s → f b = 0) : summable f := has_sum.summable (has_sum_sum_of_ne_finset_zero hf) theorem has_sum_single {α : Type u_1} {β : Type u_2} [add_comm_monoid α] [topological_space α] {f : β → α} (b : β) (hf : ∀ (b' : β), b' ≠ b → f b' = 0) : has_sum f (f b) := sorry theorem has_sum_ite_eq {α : Type u_1} {β : Type u_2} [add_comm_monoid α] [topological_space α] (b : β) (a : α) : has_sum (fun (b' : β) => ite (b' = b) a 0) a := sorry theorem equiv.has_sum_iff {α : Type u_1} {β : Type u_2} {γ : Type u_3} [add_comm_monoid α] [topological_space α] {f : β → α} {a : α} (e : γ ≃ β) : has_sum (f ∘ ⇑e) a ↔ has_sum f a := sorry theorem equiv.summable_iff {α : Type u_1} {β : Type u_2} {γ : Type u_3} [add_comm_monoid α] [topological_space α] {f : β → α} (e : γ ≃ β) : summable (f ∘ ⇑e) ↔ summable f := exists_congr fun (a : α) => equiv.has_sum_iff e theorem summable.prod_symm {α : Type u_1} {β : Type u_2} {γ : Type u_3} [add_comm_monoid α] [topological_space α] {f : β × γ → α} (hf : summable f) : summable fun (p : γ × β) => f (prod.swap p) := iff.mpr (equiv.summable_iff (equiv.prod_comm γ β)) hf theorem equiv.has_sum_iff_of_support {α : Type u_1} {β : Type u_2} {γ : Type u_3} [add_comm_monoid α] [topological_space α] {f : β → α} {a : α} {g : γ → α} (e : ↥(function.support f) ≃ ↥(function.support g)) (he : ∀ (x : ↥(function.support f)), g ↑(coe_fn e x) = f ↑x) : has_sum f a ↔ has_sum g a := sorry theorem has_sum_iff_has_sum_of_ne_zero_bij {α : Type u_1} {β : Type u_2} {γ : Type u_3} [add_comm_monoid α] [topological_space α] {f : β → α} {a : α} {g : γ → α} (i : ↥(function.support g) → β) (hi : ∀ {x y : ↥(function.support g)}, i x = i y → ↑x = ↑y) (hf : function.support f ⊆ set.range i) (hfg : ∀ (x : ↥(function.support g)), f (i x) = g ↑x) : has_sum f a ↔ has_sum g a := sorry theorem equiv.summable_iff_of_support {α : Type u_1} {β : Type u_2} {γ : Type u_3} [add_comm_monoid α] [topological_space α] {f : β → α} {g : γ → α} (e : ↥(function.support f) ≃ ↥(function.support g)) (he : ∀ (x : ↥(function.support f)), g ↑(coe_fn e x) = f ↑x) : summable f ↔ summable g := exists_congr fun (_x : α) => equiv.has_sum_iff_of_support e he protected theorem has_sum.map {α : Type u_1} {β : Type u_2} {γ : Type u_3} [add_comm_monoid α] [topological_space α] {f : β → α} {a : α} [add_comm_monoid γ] [topological_space γ] (hf : has_sum f a) (g : α →+ γ) (hg : continuous ⇑g) : has_sum (⇑g ∘ f) (coe_fn g a) := sorry protected theorem summable.map {α : Type u_1} {β : Type u_2} {γ : Type u_3} [add_comm_monoid α] [topological_space α] {f : β → α} [add_comm_monoid γ] [topological_space γ] (hf : summable f) (g : α →+ γ) (hg : continuous ⇑g) : summable (⇑g ∘ f) := has_sum.summable (has_sum.map (summable.has_sum hf) g hg) /-- If `f : ℕ → α` has sum `a`, then the partial sums `∑_{i=0}^{n-1} f i` converge to `a`. -/ theorem has_sum.tendsto_sum_nat {α : Type u_1} [add_comm_monoid α] [topological_space α] {a : α} {f : ℕ → α} (h : has_sum f a) : filter.tendsto (fun (n : ℕ) => finset.sum (finset.range n) fun (i : ℕ) => f i) filter.at_top (nhds a) := filter.tendsto.comp h filter.tendsto_finset_range theorem has_sum.unique {α : Type u_1} {β : Type u_2} [add_comm_monoid α] [topological_space α] {f : β → α} {a₁ : α} {a₂ : α} [t2_space α] : has_sum f a₁ → has_sum f a₂ → a₁ = a₂ := tendsto_nhds_unique theorem summable.has_sum_iff_tendsto_nat {α : Type u_1} [add_comm_monoid α] [topological_space α] [t2_space α] {f : ℕ → α} {a : α} (hf : summable f) : has_sum f a ↔ filter.tendsto (fun (n : ℕ) => finset.sum (finset.range n) fun (i : ℕ) => f i) filter.at_top (nhds a) := sorry theorem equiv.summable_iff_of_has_sum_iff {α : Type u_1} {β : Type u_2} {γ : Type u_3} [add_comm_monoid α] [topological_space α] {α' : Type u_4} [add_comm_monoid α'] [topological_space α'] (e : α' ≃ α) {f : β → α} {g : γ → α'} (he : ∀ {a : α'}, has_sum f (coe_fn e a) ↔ has_sum g a) : summable f ↔ summable g := sorry theorem has_sum.add {α : Type u_1} {β : Type u_2} [add_comm_monoid α] [topological_space α] {f : β → α} {g : β → α} {a : α} {b : α} [has_continuous_add α] (hf : has_sum f a) (hg : has_sum g b) : has_sum (fun (b : β) => f b + g b) (a + b) := sorry theorem summable.add {α : Type u_1} {β : Type u_2} [add_comm_monoid α] [topological_space α] {f : β → α} {g : β → α} [has_continuous_add α] (hf : summable f) (hg : summable g) : summable fun (b : β) => f b + g b := has_sum.summable (has_sum.add (summable.has_sum hf) (summable.has_sum hg)) theorem has_sum_sum {α : Type u_1} {β : Type u_2} {γ : Type u_3} [add_comm_monoid α] [topological_space α] [has_continuous_add α] {f : γ → β → α} {a : γ → α} {s : finset γ} : (∀ (i : γ), i ∈ s → has_sum (f i) (a i)) → has_sum (fun (b : β) => finset.sum s fun (i : γ) => f i b) (finset.sum s fun (i : γ) => a i) := sorry theorem summable_sum {α : Type u_1} {β : Type u_2} {γ : Type u_3} [add_comm_monoid α] [topological_space α] [has_continuous_add α] {f : γ → β → α} {s : finset γ} (hf : ∀ (i : γ), i ∈ s → summable (f i)) : summable fun (b : β) => finset.sum s fun (i : γ) => f i b := has_sum.summable (has_sum_sum fun (i : γ) (hi : i ∈ s) => summable.has_sum (hf i hi)) theorem has_sum.add_compl {α : Type u_1} {β : Type u_2} [add_comm_monoid α] [topological_space α] {f : β → α} {a : α} {b : α} [has_continuous_add α] {s : set β} (ha : has_sum (f ∘ coe) a) (hb : has_sum (f ∘ coe) b) : has_sum f (a + b) := sorry theorem summable.add_compl {α : Type u_1} {β : Type u_2} [add_comm_monoid α] [topological_space α] {f : β → α} [has_continuous_add α] {s : set β} (hs : summable (f ∘ coe)) (hsc : summable (f ∘ coe)) : summable f := has_sum.summable (has_sum.add_compl (summable.has_sum hs) (summable.has_sum hsc)) theorem has_sum.compl_add {α : Type u_1} {β : Type u_2} [add_comm_monoid α] [topological_space α] {f : β → α} {a : α} {b : α} [has_continuous_add α] {s : set β} (ha : has_sum (f ∘ coe) a) (hb : has_sum (f ∘ coe) b) : has_sum f (a + b) := sorry theorem summable.compl_add {α : Type u_1} {β : Type u_2} [add_comm_monoid α] [topological_space α] {f : β → α} [has_continuous_add α] {s : set β} (hs : summable (f ∘ coe)) (hsc : summable (f ∘ coe)) : summable f := has_sum.summable (has_sum.compl_add (summable.has_sum hs) (summable.has_sum hsc)) theorem has_sum.sigma {α : Type u_1} {β : Type u_2} [add_comm_monoid α] [topological_space α] [has_continuous_add α] [regular_space α] {γ : β → Type u_3} {f : (sigma fun (b : β) => γ b) → α} {g : β → α} {a : α} (ha : has_sum f a) (hf : ∀ (b : β), has_sum (fun (c : γ b) => f (sigma.mk b c)) (g b)) : has_sum g a := sorry /-- If a series `f` on `β × γ` has sum `a` and for each `b` the restriction of `f` to `{b} × γ` has sum `g b`, then the series `g` has sum `a`. -/ theorem has_sum.prod_fiberwise {α : Type u_1} {β : Type u_2} {γ : Type u_3} [add_comm_monoid α] [topological_space α] [has_continuous_add α] [regular_space α] {f : β × γ → α} {g : β → α} {a : α} (ha : has_sum f a) (hf : ∀ (b : β), has_sum (fun (c : γ) => f (b, c)) (g b)) : has_sum g a := has_sum.sigma (iff.mpr (equiv.has_sum_iff (equiv.sigma_equiv_prod β γ)) ha) hf theorem summable.sigma' {α : Type u_1} {β : Type u_2} [add_comm_monoid α] [topological_space α] [has_continuous_add α] [regular_space α] {γ : β → Type u_3} {f : (sigma fun (b : β) => γ b) → α} (ha : summable f) (hf : ∀ (b : β), summable fun (c : γ b) => f (sigma.mk b c)) : summable fun (b : β) => tsum fun (c : γ b) => f (sigma.mk b c) := has_sum.summable (has_sum.sigma (summable.has_sum ha) fun (b : β) => summable.has_sum (hf b)) theorem has_sum.sigma_of_has_sum {α : Type u_1} {β : Type u_2} [add_comm_monoid α] [topological_space α] [has_continuous_add α] [regular_space α] {γ : β → Type u_3} {f : (sigma fun (b : β) => γ b) → α} {g : β → α} {a : α} (ha : has_sum g a) (hf : ∀ (b : β), has_sum (fun (c : γ b) => f (sigma.mk b c)) (g b)) (hf' : summable f) : has_sum f a := sorry theorem has_sum.tsum_eq {α : Type u_1} {β : Type u_2} [add_comm_monoid α] [topological_space α] [t2_space α] {f : β → α} {a : α} (ha : has_sum f a) : (tsum fun (b : β) => f b) = a := has_sum.unique (summable.has_sum (Exists.intro a ha)) ha theorem summable.has_sum_iff {α : Type u_1} {β : Type u_2} [add_comm_monoid α] [topological_space α] [t2_space α] {f : β → α} {a : α} (h : summable f) : has_sum f a ↔ (tsum fun (b : β) => f b) = a := { mp := has_sum.tsum_eq, mpr := fun (eq : (tsum fun (b : β) => f b) = a) => eq ▸ summable.has_sum h } @[simp] theorem tsum_zero {α : Type u_1} {β : Type u_2} [add_comm_monoid α] [topological_space α] [t2_space α] : (tsum fun (b : β) => 0) = 0 := has_sum.tsum_eq has_sum_zero theorem tsum_eq_sum {α : Type u_1} {β : Type u_2} [add_comm_monoid α] [topological_space α] [t2_space α] {f : β → α} {s : finset β} (hf : ∀ (b : β), ¬b ∈ s → f b = 0) : (tsum fun (b : β) => f b) = finset.sum s fun (b : β) => f b := has_sum.tsum_eq (has_sum_sum_of_ne_finset_zero hf) theorem tsum_fintype {α : Type u_1} {β : Type u_2} [add_comm_monoid α] [topological_space α] [t2_space α] [fintype β] (f : β → α) : (tsum fun (b : β) => f b) = finset.sum finset.univ fun (b : β) => f b := has_sum.tsum_eq (has_sum_fintype f) @[simp] theorem finset.tsum_subtype {α : Type u_1} {β : Type u_2} [add_comm_monoid α] [topological_space α] [t2_space α] (s : finset β) (f : β → α) : (tsum fun (x : Subtype fun (x : β) => x ∈ s) => f ↑x) = finset.sum s fun (x : β) => f x := has_sum.tsum_eq (finset.has_sum s f) @[simp] theorem finset.tsum_subtype' {α : Type u_1} {β : Type u_2} [add_comm_monoid α] [topological_space α] [t2_space α] (s : finset β) (f : β → α) : (tsum fun (x : ↥↑s) => f ↑x) = finset.sum s fun (x : β) => f x := finset.tsum_subtype s f theorem tsum_eq_single {α : Type u_1} {β : Type u_2} [add_comm_monoid α] [topological_space α] [t2_space α] {f : β → α} (b : β) (hf : ∀ (b' : β), b' ≠ b → f b' = 0) : (tsum fun (b : β) => f b) = f b := has_sum.tsum_eq (has_sum_single b hf) @[simp] theorem tsum_ite_eq {α : Type u_1} {β : Type u_2} [add_comm_monoid α] [topological_space α] [t2_space α] (b : β) (a : α) : (tsum fun (b' : β) => ite (b' = b) a 0) = a := has_sum.tsum_eq (has_sum_ite_eq b a) theorem equiv.tsum_eq_tsum_of_has_sum_iff_has_sum {α : Type u_1} {β : Type u_2} {γ : Type u_3} [add_comm_monoid α] [topological_space α] [t2_space α] {α' : Type u_4} [add_comm_monoid α'] [topological_space α'] (e : α' ≃ α) (h0 : coe_fn e 0 = 0) {f : β → α} {g : γ → α'} (h : ∀ {a : α'}, has_sum f (coe_fn e a) ↔ has_sum g a) : (tsum fun (b : β) => f b) = coe_fn e (tsum fun (c : γ) => g c) := sorry theorem tsum_eq_tsum_of_has_sum_iff_has_sum {α : Type u_1} {β : Type u_2} {γ : Type u_3} [add_comm_monoid α] [topological_space α] [t2_space α] {f : β → α} {g : γ → α} (h : ∀ {a : α}, has_sum f a ↔ has_sum g a) : (tsum fun (b : β) => f b) = tsum fun (c : γ) => g c := equiv.tsum_eq_tsum_of_has_sum_iff_has_sum (equiv.refl α) rfl h theorem equiv.tsum_eq {α : Type u_1} {β : Type u_2} {γ : Type u_3} [add_comm_monoid α] [topological_space α] [t2_space α] (j : γ ≃ β) (f : β → α) : (tsum fun (c : γ) => f (coe_fn j c)) = tsum fun (b : β) => f b := tsum_eq_tsum_of_has_sum_iff_has_sum fun (a : α) => equiv.has_sum_iff j theorem equiv.tsum_eq_tsum_of_support {α : Type u_1} {β : Type u_2} {γ : Type u_3} [add_comm_monoid α] [topological_space α] [t2_space α] {f : β → α} {g : γ → α} (e : ↥(function.support f) ≃ ↥(function.support g)) (he : ∀ (x : ↥(function.support f)), g ↑(coe_fn e x) = f ↑x) : (tsum fun (x : β) => f x) = tsum fun (y : γ) => g y := tsum_eq_tsum_of_has_sum_iff_has_sum fun (_x : α) => equiv.has_sum_iff_of_support e he theorem tsum_eq_tsum_of_ne_zero_bij {α : Type u_1} {β : Type u_2} {γ : Type u_3} [add_comm_monoid α] [topological_space α] [t2_space α] {f : β → α} {g : γ → α} (i : ↥(function.support g) → β) (hi : ∀ {x y : ↥(function.support g)}, i x = i y → ↑x = ↑y) (hf : function.support f ⊆ set.range i) (hfg : ∀ (x : ↥(function.support g)), f (i x) = g ↑x) : (tsum fun (x : β) => f x) = tsum fun (y : γ) => g y := tsum_eq_tsum_of_has_sum_iff_has_sum fun (_x : α) => has_sum_iff_has_sum_of_ne_zero_bij i hi hf hfg theorem tsum_subtype {α : Type u_1} {β : Type u_2} [add_comm_monoid α] [topological_space α] [t2_space α] (s : set β) (f : β → α) : (tsum fun (x : ↥s) => f ↑x) = tsum fun (x : β) => set.indicator s f x := tsum_eq_tsum_of_has_sum_iff_has_sum fun (_x : α) => has_sum_subtype_iff_indicator theorem tsum_add {α : Type u_1} {β : Type u_2} [add_comm_monoid α] [topological_space α] [t2_space α] {f : β → α} {g : β → α} [has_continuous_add α] (hf : summable f) (hg : summable g) : (tsum fun (b : β) => f b + g b) = (tsum fun (b : β) => f b) + tsum fun (b : β) => g b := has_sum.tsum_eq (has_sum.add (summable.has_sum hf) (summable.has_sum hg)) theorem tsum_sum {α : Type u_1} {β : Type u_2} {γ : Type u_3} [add_comm_monoid α] [topological_space α] [t2_space α] [has_continuous_add α] {f : γ → β → α} {s : finset γ} (hf : ∀ (i : γ), i ∈ s → summable (f i)) : (tsum fun (b : β) => finset.sum s fun (i : γ) => f i b) = finset.sum s fun (i : γ) => tsum fun (b : β) => f i b := has_sum.tsum_eq (has_sum_sum fun (i : γ) (hi : i ∈ s) => summable.has_sum (hf i hi)) theorem tsum_sigma' {α : Type u_1} {β : Type u_2} [add_comm_monoid α] [topological_space α] [t2_space α] [has_continuous_add α] [regular_space α] {γ : β → Type u_3} {f : (sigma fun (b : β) => γ b) → α} (h₁ : ∀ (b : β), summable fun (c : γ b) => f (sigma.mk b c)) (h₂ : summable f) : (tsum fun (p : sigma fun (b : β) => γ b) => f p) = tsum fun (b : β) => tsum fun (c : γ b) => f (sigma.mk b c) := Eq.symm (has_sum.tsum_eq (has_sum.sigma (summable.has_sum h₂) fun (b : β) => summable.has_sum (h₁ b))) theorem tsum_prod' {α : Type u_1} {β : Type u_2} {γ : Type u_3} [add_comm_monoid α] [topological_space α] [t2_space α] [has_continuous_add α] [regular_space α] {f : β × γ → α} (h : summable f) (h₁ : ∀ (b : β), summable fun (c : γ) => f (b, c)) : (tsum fun (p : β × γ) => f p) = tsum fun (b : β) => tsum fun (c : γ) => f (b, c) := Eq.symm (has_sum.tsum_eq (has_sum.prod_fiberwise (summable.has_sum h) fun (b : β) => summable.has_sum (h₁ b))) theorem tsum_comm' {α : Type u_1} {β : Type u_2} {γ : Type u_3} [add_comm_monoid α] [topological_space α] [t2_space α] [has_continuous_add α] [regular_space α] {f : β → γ → α} (h : summable (function.uncurry f)) (h₁ : ∀ (b : β), summable (f b)) (h₂ : ∀ (c : γ), summable fun (b : β) => f b c) : (tsum fun (c : γ) => tsum fun (b : β) => f b c) = tsum fun (b : β) => tsum fun (c : γ) => f b c := sorry /-- You can compute a sum over an encodably type by summing over the natural numbers and taking a supremum. This is useful for outer measures. -/ theorem tsum_supr_decode2 {α : Type u_1} {β : Type u_2} {γ : Type u_3} [add_comm_monoid α] [topological_space α] [t2_space α] [encodable γ] [complete_lattice β] (m : β → α) (m0 : m ⊥ = 0) (s : γ → β) : (tsum fun (i : ℕ) => m (supr fun (b : γ) => supr fun (H : b ∈ encodable.decode2 γ i) => s b)) = tsum fun (b : γ) => m (s b) := sorry /-- `tsum_supr_decode2` specialized to the complete lattice of sets. -/ theorem tsum_Union_decode2 {α : Type u_1} {β : Type u_2} {γ : Type u_3} [add_comm_monoid α] [topological_space α] [t2_space α] [encodable γ] (m : set β → α) (m0 : m ∅ = 0) (s : γ → set β) : (tsum fun (i : ℕ) => m (set.Union fun (b : γ) => set.Union fun (H : b ∈ encodable.decode2 γ i) => s b)) = tsum fun (b : γ) => m (s b) := tsum_supr_decode2 m m0 s /-! Some properties about measure-like functions. These could also be functions defined on complete sublattices of sets, with the property that they are countably sub-additive. `R` will probably be instantiated with `(≤)` in all applications. -/ /-- If a function is countably sub-additive then it is sub-additive on encodable types -/ theorem rel_supr_tsum {α : Type u_1} {β : Type u_2} {γ : Type u_3} [add_comm_monoid α] [topological_space α] [t2_space α] [encodable γ] [complete_lattice β] (m : β → α) (m0 : m ⊥ = 0) (R : α → α → Prop) (m_supr : ∀ (s : ℕ → β), R (m (supr fun (i : ℕ) => s i)) (tsum fun (i : ℕ) => m (s i))) (s : γ → β) : R (m (supr fun (b : γ) => s b)) (tsum fun (b : γ) => m (s b)) := sorry /-- If a function is countably sub-additive then it is sub-additive on finite sets -/ theorem rel_supr_sum {α : Type u_1} {β : Type u_2} {δ : Type u_4} [add_comm_monoid α] [topological_space α] [t2_space α] [complete_lattice β] (m : β → α) (m0 : m ⊥ = 0) (R : α → α → Prop) (m_supr : ∀ (s : ℕ → β), R (m (supr fun (i : ℕ) => s i)) (tsum fun (i : ℕ) => m (s i))) (s : δ → β) (t : finset δ) : R (m (supr fun (d : δ) => supr fun (H : d ∈ t) => s d)) (finset.sum t fun (d : δ) => m (s d)) := sorry /-- If a function is countably sub-additive then it is binary sub-additive -/ theorem rel_sup_add {α : Type u_1} {β : Type u_2} [add_comm_monoid α] [topological_space α] [t2_space α] [complete_lattice β] (m : β → α) (m0 : m ⊥ = 0) (R : α → α → Prop) (m_supr : ∀ (s : ℕ → β), R (m (supr fun (i : ℕ) => s i)) (tsum fun (i : ℕ) => m (s i))) (s₁ : β) (s₂ : β) : R (m (s₁ ⊔ s₂)) (m s₁ + m s₂) := sorry theorem pi.has_sum {α : Type u_1} {ι : Type u_5} {π : α → Type u_6} [(x : α) → add_comm_monoid (π x)] [(x : α) → topological_space (π x)] {f : ι → (x : α) → π x} {g : (x : α) → π x} : has_sum f g ↔ ∀ (x : α), has_sum (fun (i : ι) => f i x) (g x) := sorry theorem pi.summable {α : Type u_1} {ι : Type u_5} {π : α → Type u_6} [(x : α) → add_comm_monoid (π x)] [(x : α) → topological_space (π x)] {f : ι → (x : α) → π x} : summable f ↔ ∀ (x : α), summable fun (i : ι) => f i x := sorry theorem tsum_apply {α : Type u_1} {ι : Type u_5} {π : α → Type u_6} [(x : α) → add_comm_monoid (π x)] [(x : α) → topological_space (π x)] [∀ (x : α), t2_space (π x)] {f : ι → (x : α) → π x} {x : α} (hf : summable f) : tsum (fun (i : ι) => f i) x = tsum fun (i : ι) => f i x := Eq.symm (has_sum.tsum_eq (iff.mp pi.has_sum (summable.has_sum hf) x)) -- `by simpa using` speeds up elaboration. Why? theorem has_sum.neg {α : Type u_1} {β : Type u_2} [add_comm_group α] [topological_space α] [topological_add_group α] {f : β → α} {a : α} (h : has_sum f a) : has_sum (fun (b : β) => -f b) (-a) := eq.mpr (id (Eq.refl (has_sum (fun (b : β) => -f b) (-a)))) (eq.mp (Eq.refl (has_sum (⇑(-add_monoid_hom.id α) ∘ f) (coe_fn (-add_monoid_hom.id α) a))) (has_sum.map h (-add_monoid_hom.id α) continuous_neg)) theorem summable.neg {α : Type u_1} {β : Type u_2} [add_comm_group α] [topological_space α] [topological_add_group α] {f : β → α} (hf : summable f) : summable fun (b : β) => -f b := has_sum.summable (has_sum.neg (summable.has_sum hf)) theorem summable.of_neg {α : Type u_1} {β : Type u_2} [add_comm_group α] [topological_space α] [topological_add_group α] {f : β → α} (hf : summable fun (b : β) => -f b) : summable f := sorry theorem summable_neg_iff {α : Type u_1} {β : Type u_2} [add_comm_group α] [topological_space α] [topological_add_group α] {f : β → α} : (summable fun (b : β) => -f b) ↔ summable f := { mp := summable.of_neg, mpr := summable.neg } theorem has_sum.sub {α : Type u_1} {β : Type u_2} [add_comm_group α] [topological_space α] [topological_add_group α] {f : β → α} {g : β → α} {a₁ : α} {a₂ : α} (hf : has_sum f a₁) (hg : has_sum g a₂) : has_sum (fun (b : β) => f b - g b) (a₁ - a₂) := sorry theorem summable.sub {α : Type u_1} {β : Type u_2} [add_comm_group α] [topological_space α] [topological_add_group α] {f : β → α} {g : β → α} (hf : summable f) (hg : summable g) : summable fun (b : β) => f b - g b := has_sum.summable (has_sum.sub (summable.has_sum hf) (summable.has_sum hg)) theorem has_sum.has_sum_compl_iff {α : Type u_1} {β : Type u_2} [add_comm_group α] [topological_space α] [topological_add_group α] {f : β → α} {a₁ : α} {a₂ : α} {s : set β} (hf : has_sum (f ∘ coe) a₁) : has_sum (f ∘ coe) a₂ ↔ has_sum f (a₁ + a₂) := sorry theorem has_sum.has_sum_iff_compl {α : Type u_1} {β : Type u_2} [add_comm_group α] [topological_space α] [topological_add_group α] {f : β → α} {a₁ : α} {a₂ : α} {s : set β} (hf : has_sum (f ∘ coe) a₁) : has_sum f a₂ ↔ has_sum (f ∘ coe) (a₂ - a₁) := sorry theorem summable.summable_compl_iff {α : Type u_1} {β : Type u_2} [add_comm_group α] [topological_space α] [topological_add_group α] {f : β → α} {s : set β} (hf : summable (f ∘ coe)) : summable (f ∘ coe) ↔ summable f := sorry protected theorem finset.has_sum_compl_iff {α : Type u_1} {β : Type u_2} [add_comm_group α] [topological_space α] [topological_add_group α] {f : β → α} {a : α} (s : finset β) : has_sum (fun (x : Subtype fun (x : β) => ¬x ∈ s) => f ↑x) a ↔ has_sum f (a + finset.sum s fun (i : β) => f i) := sorry protected theorem finset.has_sum_iff_compl {α : Type u_1} {β : Type u_2} [add_comm_group α] [topological_space α] [topological_add_group α] {f : β → α} {a : α} (s : finset β) : has_sum f a ↔ has_sum (fun (x : Subtype fun (x : β) => ¬x ∈ s) => f ↑x) (a - finset.sum s fun (i : β) => f i) := has_sum.has_sum_iff_compl (finset.has_sum s f) protected theorem finset.summable_compl_iff {α : Type u_1} {β : Type u_2} [add_comm_group α] [topological_space α] [topological_add_group α] {f : β → α} (s : finset β) : (summable fun (x : Subtype fun (x : β) => ¬x ∈ s) => f ↑x) ↔ summable f := summable.summable_compl_iff (finset.summable s f) theorem set.finite.summable_compl_iff {α : Type u_1} {β : Type u_2} [add_comm_group α] [topological_space α] [topological_add_group α] {f : β → α} {s : set β} (hs : set.finite s) : summable (f ∘ coe) ↔ summable f := summable.summable_compl_iff (set.finite.summable hs f) theorem tsum_neg {α : Type u_1} {β : Type u_2} [add_comm_group α] [topological_space α] [topological_add_group α] {f : β → α} [t2_space α] (hf : summable f) : (tsum fun (b : β) => -f b) = -tsum fun (b : β) => f b := has_sum.tsum_eq (has_sum.neg (summable.has_sum hf)) theorem tsum_sub {α : Type u_1} {β : Type u_2} [add_comm_group α] [topological_space α] [topological_add_group α] {f : β → α} {g : β → α} [t2_space α] (hf : summable f) (hg : summable g) : (tsum fun (b : β) => f b - g b) = (tsum fun (b : β) => f b) - tsum fun (b : β) => g b := has_sum.tsum_eq (has_sum.sub (summable.has_sum hf) (summable.has_sum hg)) theorem tsum_add_tsum_compl {α : Type u_1} {β : Type u_2} [add_comm_group α] [topological_space α] [topological_add_group α] {f : β → α} [t2_space α] {s : set β} (hs : summable (f ∘ coe)) (hsc : summable (f ∘ coe)) : ((tsum fun (x : ↥s) => f ↑x) + tsum fun (x : ↥(sᶜ)) => f ↑x) = tsum fun (x : β) => f x := Eq.symm (has_sum.tsum_eq (has_sum.add_compl (summable.has_sum hs) (summable.has_sum hsc))) theorem sum_add_tsum_compl {α : Type u_1} {β : Type u_2} [add_comm_group α] [topological_space α] [topological_add_group α] {f : β → α} [t2_space α] {s : finset β} (hf : summable f) : ((finset.sum s fun (x : β) => f x) + tsum fun (x : ↥(↑sᶜ)) => f ↑x) = tsum fun (x : β) => f x := Eq.symm (has_sum.tsum_eq (has_sum.add_compl (finset.has_sum s f) (summable.has_sum (iff.mpr (finset.summable_compl_iff s) hf)))) /-! ### Sums on subtypes If `s` is a finset of `α`, we show that the summability of `f` in the whole space and on the subtype `univ - s` are equivalent, and relate their sums. For a function defined on `ℕ`, we deduce the formula `(∑ i in range k, f i) + (∑' i, f (i + k)) = (∑' i, f i)`, in `sum_add_tsum_nat_add`. -/ theorem has_sum_nat_add_iff {α : Type u_1} [add_comm_group α] [topological_space α] [topological_add_group α] {f : ℕ → α} (k : ℕ) {a : α} : has_sum (fun (n : ℕ) => f (n + k)) a ↔ has_sum f (a + finset.sum (finset.range k) fun (i : ℕ) => f i) := sorry theorem summable_nat_add_iff {α : Type u_1} [add_comm_group α] [topological_space α] [topological_add_group α] {f : ℕ → α} (k : ℕ) : (summable fun (n : ℕ) => f (n + k)) ↔ summable f := iff.symm (equiv.summable_iff_of_has_sum_iff (equiv.add_right (finset.sum (finset.range k) fun (i : ℕ) => f i)) fun (a : α) => iff.symm (has_sum_nat_add_iff k)) theorem has_sum_nat_add_iff' {α : Type u_1} [add_comm_group α] [topological_space α] [topological_add_group α] {f : ℕ → α} (k : ℕ) {a : α} : has_sum (fun (n : ℕ) => f (n + k)) (a - finset.sum (finset.range k) fun (i : ℕ) => f i) ↔ has_sum f a := sorry theorem sum_add_tsum_nat_add {α : Type u_1} [add_comm_group α] [topological_space α] [topological_add_group α] [t2_space α] {f : ℕ → α} (k : ℕ) (h : summable f) : ((finset.sum (finset.range k) fun (i : ℕ) => f i) + tsum fun (i : ℕ) => f (i + k)) = tsum fun (i : ℕ) => f i := sorry theorem tsum_eq_zero_add {α : Type u_1} [add_comm_group α] [topological_space α] [topological_add_group α] [t2_space α] {f : ℕ → α} (hf : summable f) : (tsum fun (b : ℕ) => f b) = f 0 + tsum fun (b : ℕ) => f (b + 1) := sorry /-- For `f : ℕ → α`, then `∑' k, f (k + i)` tends to zero. This does not require a summability assumption on `f`, as otherwise all sums are zero. -/ theorem tendsto_sum_nat_add {α : Type u_1} [add_comm_group α] [topological_space α] [topological_add_group α] [t2_space α] (f : ℕ → α) : filter.tendsto (fun (i : ℕ) => tsum fun (k : ℕ) => f (k + i)) filter.at_top (nhds 0) := sorry theorem has_sum.mul_left {α : Type u_1} {β : Type u_2} [semiring α] [topological_space α] [topological_semiring α] {f : β → α} {a₁ : α} (a₂ : α) (h : has_sum f a₁) : has_sum (fun (b : β) => a₂ * f b) (a₂ * a₁) := eq.mpr (id (Eq.refl (has_sum (fun (b : β) => a₂ * f b) (a₂ * a₁)))) (eq.mp (Eq.refl (has_sum (⇑(add_monoid_hom.mul_left a₂) ∘ f) (coe_fn (add_monoid_hom.mul_left a₂) a₁))) (has_sum.map h (add_monoid_hom.mul_left a₂) (continuous.mul continuous_const continuous_id))) theorem has_sum.mul_right {α : Type u_1} {β : Type u_2} [semiring α] [topological_space α] [topological_semiring α] {f : β → α} {a₁ : α} (a₂ : α) (hf : has_sum f a₁) : has_sum (fun (b : β) => f b * a₂) (a₁ * a₂) := eq.mpr (id (Eq.refl (has_sum (fun (b : β) => f b * a₂) (a₁ * a₂)))) (eq.mp (Eq.refl (has_sum (⇑(add_monoid_hom.mul_right a₂) ∘ f) (coe_fn (add_monoid_hom.mul_right a₂) a₁))) (has_sum.map hf (add_monoid_hom.mul_right a₂) (continuous.mul continuous_id continuous_const))) theorem summable.mul_left {α : Type u_1} {β : Type u_2} [semiring α] [topological_space α] [topological_semiring α] {f : β → α} (a : α) (hf : summable f) : summable fun (b : β) => a * f b := has_sum.summable (has_sum.mul_left a (summable.has_sum hf)) theorem summable.mul_right {α : Type u_1} {β : Type u_2} [semiring α] [topological_space α] [topological_semiring α] {f : β → α} (a : α) (hf : summable f) : summable fun (b : β) => f b * a := has_sum.summable (has_sum.mul_right a (summable.has_sum hf)) theorem summable.tsum_mul_left {α : Type u_1} {β : Type u_2} [semiring α] [topological_space α] [topological_semiring α] {f : β → α} [t2_space α] (a : α) (hf : summable f) : (tsum fun (b : β) => a * f b) = a * tsum fun (b : β) => f b := has_sum.tsum_eq (has_sum.mul_left a (summable.has_sum hf)) theorem summable.tsum_mul_right {α : Type u_1} {β : Type u_2} [semiring α] [topological_space α] [topological_semiring α] {f : β → α} [t2_space α] (a : α) (hf : summable f) : (tsum fun (b : β) => f b * a) = (tsum fun (b : β) => f b) * a := has_sum.tsum_eq (has_sum.mul_right a (summable.has_sum hf)) theorem has_sum.smul {α : Type u_1} {β : Type u_2} {R : Type u_5} [semiring R] [topological_space R] [topological_space α] [add_comm_monoid α] [semimodule R α] [topological_semimodule R α] {f : β → α} {a : α} {r : R} (hf : has_sum f a) : has_sum (fun (z : β) => r • f z) (r • a) := has_sum.map hf (const_smul_hom α r) (continuous.smul continuous_const continuous_id) theorem summable.smul {α : Type u_1} {β : Type u_2} {R : Type u_5} [semiring R] [topological_space R] [topological_space α] [add_comm_monoid α] [semimodule R α] [topological_semimodule R α] {f : β → α} {r : R} (hf : summable f) : summable fun (z : β) => r • f z := has_sum.summable (has_sum.smul (summable.has_sum hf)) theorem tsum_smul {α : Type u_1} {β : Type u_2} {R : Type u_5} [semiring R] [topological_space R] [topological_space α] [add_comm_monoid α] [semimodule R α] [topological_semimodule R α] {f : β → α} [t2_space α] {r : R} (hf : summable f) : (tsum fun (z : β) => r • f z) = r • tsum fun (z : β) => f z := has_sum.tsum_eq (has_sum.smul (summable.has_sum hf)) theorem has_sum.div_const {α : Type u_1} {β : Type u_2} [division_ring α] [topological_space α] [topological_semiring α] {f : β → α} {a : α} (h : has_sum f a) (b : α) : has_sum (fun (x : β) => f x / b) (a / b) := sorry theorem has_sum_mul_left_iff {α : Type u_1} {β : Type u_2} [division_ring α] [topological_space α] [topological_semiring α] {f : β → α} {a₁ : α} {a₂ : α} (h : a₂ ≠ 0) : has_sum f a₁ ↔ has_sum (fun (b : β) => a₂ * f b) (a₂ * a₁) := sorry theorem has_sum_mul_right_iff {α : Type u_1} {β : Type u_2} [division_ring α] [topological_space α] [topological_semiring α] {f : β → α} {a₁ : α} {a₂ : α} (h : a₂ ≠ 0) : has_sum f a₁ ↔ has_sum (fun (b : β) => f b * a₂) (a₁ * a₂) := sorry theorem summable_mul_left_iff {α : Type u_1} {β : Type u_2} [division_ring α] [topological_space α] [topological_semiring α] {f : β → α} {a : α} (h : a ≠ 0) : summable f ↔ summable fun (b : β) => a * f b := sorry theorem summable_mul_right_iff {α : Type u_1} {β : Type u_2} [division_ring α] [topological_space α] [topological_semiring α] {f : β → α} {a : α} (h : a ≠ 0) : summable f ↔ summable fun (b : β) => f b * a := sorry theorem tsum_mul_left {α : Type u_1} {β : Type u_2} [division_ring α] [topological_space α] [topological_semiring α] {f : β → α} {a : α} [t2_space α] : (tsum fun (x : β) => a * f x) = a * tsum fun (x : β) => f x := sorry theorem tsum_mul_right {α : Type u_1} {β : Type u_2} [division_ring α] [topological_space α] [topological_semiring α] {f : β → α} {a : α} [t2_space α] : (tsum fun (x : β) => f x * a) = (tsum fun (x : β) => f x) * a := sorry theorem has_sum_le {α : Type u_1} {β : Type u_2} [ordered_add_comm_monoid α] [topological_space α] [order_closed_topology α] {f : β → α} {g : β → α} {a₁ : α} {a₂ : α} (h : ∀ (b : β), f b ≤ g b) (hf : has_sum f a₁) (hg : has_sum g a₂) : a₁ ≤ a₂ := le_of_tendsto_of_tendsto' hf hg fun (s : finset β) => finset.sum_le_sum fun (b : β) (_x : b ∈ s) => h b theorem has_sum_le_inj {α : Type u_1} {β : Type u_2} {γ : Type u_3} [ordered_add_comm_monoid α] [topological_space α] [order_closed_topology α] {f : β → α} {a₁ : α} {a₂ : α} {g : γ → α} (i : β → γ) (hi : function.injective i) (hs : ∀ (c : γ), ¬c ∈ set.range i → 0 ≤ g c) (h : ∀ (b : β), f b ≤ g (i b)) (hf : has_sum f a₁) (hg : has_sum g a₂) : a₁ ≤ a₂ := sorry theorem tsum_le_tsum_of_inj {α : Type u_1} {β : Type u_2} {γ : Type u_3} [ordered_add_comm_monoid α] [topological_space α] [order_closed_topology α] {f : β → α} {g : γ → α} (i : β → γ) (hi : function.injective i) (hs : ∀ (c : γ), ¬c ∈ set.range i → 0 ≤ g c) (h : ∀ (b : β), f b ≤ g (i b)) (hf : summable f) (hg : summable g) : tsum f ≤ tsum g := has_sum_le_inj i hi hs h (summable.has_sum hf) (summable.has_sum hg) theorem sum_le_has_sum {α : Type u_1} {β : Type u_2} [ordered_add_comm_monoid α] [topological_space α] [order_closed_topology α] {a : α} {f : β → α} (s : finset β) (hs : ∀ (b : β), ¬b ∈ s → 0 ≤ f b) (hf : has_sum f a) : (finset.sum s fun (b : β) => f b) ≤ a := sorry theorem le_has_sum {α : Type u_1} {β : Type u_2} [ordered_add_comm_monoid α] [topological_space α] [order_closed_topology α] {f : β → α} {a : α} (hf : has_sum f a) (b : β) (hb : ∀ (b' : β), b' ≠ b → 0 ≤ f b') : f b ≤ a := sorry theorem sum_le_tsum {α : Type u_1} {β : Type u_2} [ordered_add_comm_monoid α] [topological_space α] [order_closed_topology α] {f : β → α} (s : finset β) (hs : ∀ (b : β), ¬b ∈ s → 0 ≤ f b) (hf : summable f) : (finset.sum s fun (b : β) => f b) ≤ tsum f := sum_le_has_sum s hs (summable.has_sum hf) theorem le_tsum {α : Type u_1} {β : Type u_2} [ordered_add_comm_monoid α] [topological_space α] [order_closed_topology α] {f : β → α} (hf : summable f) (b : β) (hb : ∀ (b' : β), b' ≠ b → 0 ≤ f b') : f b ≤ tsum fun (b : β) => f b := le_has_sum (summable.has_sum hf) b hb theorem tsum_le_tsum {α : Type u_1} {β : Type u_2} [ordered_add_comm_monoid α] [topological_space α] [order_closed_topology α] {f : β → α} {g : β → α} (h : ∀ (b : β), f b ≤ g b) (hf : summable f) (hg : summable g) : (tsum fun (b : β) => f b) ≤ tsum fun (b : β) => g b := has_sum_le h (summable.has_sum hf) (summable.has_sum hg) theorem has_sum.nonneg {α : Type u_1} {β : Type u_2} [ordered_add_comm_monoid α] [topological_space α] [order_closed_topology α] {g : β → α} {a : α} (h : ∀ (b : β), 0 ≤ g b) (ha : has_sum g a) : 0 ≤ a := has_sum_le h has_sum_zero ha theorem has_sum.nonpos {α : Type u_1} {β : Type u_2} [ordered_add_comm_monoid α] [topological_space α] [order_closed_topology α] {g : β → α} {a : α} (h : ∀ (b : β), g b ≤ 0) (ha : has_sum g a) : a ≤ 0 := has_sum_le h ha has_sum_zero theorem tsum_nonneg {α : Type u_1} {β : Type u_2} [ordered_add_comm_monoid α] [topological_space α] [order_closed_topology α] {g : β → α} (h : ∀ (b : β), 0 ≤ g b) : 0 ≤ tsum fun (b : β) => g b := sorry theorem tsum_nonpos {α : Type u_1} {β : Type u_2} [ordered_add_comm_monoid α] [topological_space α] [order_closed_topology α] {f : β → α} (h : ∀ (b : β), f b ≤ 0) : (tsum fun (b : β) => f b) ≤ 0 := sorry theorem le_has_sum' {α : Type u_1} {β : Type u_2} [canonically_ordered_add_monoid α] [topological_space α] [order_closed_topology α] {f : β → α} {a : α} (hf : has_sum f a) (b : β) : f b ≤ a := le_has_sum hf b fun (_x : β) (_x_1 : _x ≠ b) => zero_le (f _x) theorem le_tsum' {α : Type u_1} {β : Type u_2} [canonically_ordered_add_monoid α] [topological_space α] [order_closed_topology α] {f : β → α} (hf : summable f) (b : β) : f b ≤ tsum fun (b : β) => f b := le_tsum hf b fun (_x : β) (_x_1 : _x ≠ b) => zero_le (f _x) theorem has_sum_zero_iff {α : Type u_1} {β : Type u_2} [canonically_ordered_add_monoid α] [topological_space α] [order_closed_topology α] {f : β → α} : has_sum f 0 ↔ ∀ (x : β), f x = 0 := sorry theorem tsum_eq_zero_iff {α : Type u_1} {β : Type u_2} [canonically_ordered_add_monoid α] [topological_space α] [order_closed_topology α] {f : β → α} (hf : summable f) : (tsum fun (i : β) => f i) = 0 ↔ ∀ (x : β), f x = 0 := sorry theorem summable_iff_cauchy_seq_finset {α : Type u_1} {β : Type u_2} [add_comm_group α] [uniform_space α] [complete_space α] {f : β → α} : summable f ↔ cauchy_seq fun (s : finset β) => finset.sum s fun (b : β) => f b := iff.symm cauchy_map_iff_exists_tendsto theorem cauchy_seq_finset_iff_vanishing {α : Type u_1} {β : Type u_2} [add_comm_group α] [uniform_space α] [uniform_add_group α] {f : β → α} : (cauchy_seq fun (s : finset β) => finset.sum s fun (b : β) => f b) ↔ ∀ (e : set α), e ∈ nhds 0 → ∃ (s : finset β), ∀ (t : finset β), disjoint t s → (finset.sum t fun (b : β) => f b) ∈ e := sorry theorem summable_iff_vanishing {α : Type u_1} {β : Type u_2} [add_comm_group α] [uniform_space α] [uniform_add_group α] {f : β → α} [complete_space α] : summable f ↔ ∀ (e : set α), e ∈ nhds 0 → ∃ (s : finset β), ∀ (t : finset β), disjoint t s → (finset.sum t fun (b : β) => f b) ∈ e := sorry /- TODO: generalize to monoid with a uniform continuous subtraction operator: `(a + b) - b = a` -/ theorem summable.summable_of_eq_zero_or_self {α : Type u_1} {β : Type u_2} [add_comm_group α] [uniform_space α] [uniform_add_group α] {f : β → α} {g : β → α} [complete_space α] (hf : summable f) (h : ∀ (b : β), g b = 0 ∨ g b = f b) : summable g := sorry protected theorem summable.indicator {α : Type u_1} {β : Type u_2} [add_comm_group α] [uniform_space α] [uniform_add_group α] {f : β → α} [complete_space α] (hf : summable f) (s : set β) : summable (set.indicator s f) := summable.summable_of_eq_zero_or_self hf (set.indicator_eq_zero_or_self s f) theorem summable.comp_injective {α : Type u_1} {β : Type u_2} {γ : Type u_3} [add_comm_group α] [uniform_space α] [uniform_add_group α] {f : β → α} [complete_space α] {i : γ → β} (hf : summable f) (hi : function.injective i) : summable (f ∘ i) := sorry theorem summable.subtype {α : Type u_1} {β : Type u_2} [add_comm_group α] [uniform_space α] [uniform_add_group α] {f : β → α} [complete_space α] (hf : summable f) (s : set β) : summable (f ∘ coe) := summable.comp_injective hf subtype.coe_injective theorem summable_subtype_and_compl {α : Type u_1} {β : Type u_2} [add_comm_group α] [uniform_space α] [uniform_add_group α] {f : β → α} [complete_space α] {s : set β} : ((summable fun (x : ↥s) => f ↑x) ∧ summable fun (x : ↥(sᶜ)) => f ↑x) ↔ summable f := { mp := iff.mpr and_imp summable.add_compl, mpr := fun (h : summable f) => { left := summable.subtype h s, right := summable.subtype h (sᶜ) } } theorem summable.sigma_factor {α : Type u_1} {β : Type u_2} [add_comm_group α] [uniform_space α] [uniform_add_group α] [complete_space α] {γ : β → Type u_3} {f : (sigma fun (b : β) => γ b) → α} (ha : summable f) (b : β) : summable fun (c : γ b) => f (sigma.mk b c) := summable.comp_injective ha sigma_mk_injective theorem summable.sigma {α : Type u_1} {β : Type u_2} [add_comm_group α] [uniform_space α] [uniform_add_group α] [complete_space α] [regular_space α] {γ : β → Type u_3} {f : (sigma fun (b : β) => γ b) → α} (ha : summable f) : summable fun (b : β) => tsum fun (c : γ b) => f (sigma.mk b c) := summable.sigma' ha fun (b : β) => summable.sigma_factor ha b theorem summable.prod_factor {α : Type u_1} {β : Type u_2} {γ : Type u_3} [add_comm_group α] [uniform_space α] [uniform_add_group α] [complete_space α] {f : β × γ → α} (h : summable f) (b : β) : summable fun (c : γ) => f (b, c) := summable.comp_injective h fun (c₁ c₂ : γ) (h : (fun (c : γ) => (b, c)) c₁ = (fun (c : γ) => (b, c)) c₂) => and.right (iff.mp prod.ext_iff h) theorem tsum_sigma {α : Type u_1} {β : Type u_2} [add_comm_group α] [uniform_space α] [uniform_add_group α] [complete_space α] [regular_space α] {γ : β → Type u_3} {f : (sigma fun (b : β) => γ b) → α} (ha : summable f) : (tsum fun (p : sigma fun (b : β) => γ b) => f p) = tsum fun (b : β) => tsum fun (c : γ b) => f (sigma.mk b c) := tsum_sigma' (fun (b : β) => summable.sigma_factor ha b) ha theorem tsum_prod {α : Type u_1} {β : Type u_2} {γ : Type u_3} [add_comm_group α] [uniform_space α] [uniform_add_group α] [complete_space α] [regular_space α] {f : β × γ → α} (h : summable f) : (tsum fun (p : β × γ) => f p) = tsum fun (b : β) => tsum fun (c : γ) => f (b, c) := tsum_prod' h (summable.prod_factor h) theorem tsum_comm {α : Type u_1} {β : Type u_2} {γ : Type u_3} [add_comm_group α] [uniform_space α] [uniform_add_group α] [complete_space α] [regular_space α] {f : β → γ → α} (h : summable (function.uncurry f)) : (tsum fun (c : γ) => tsum fun (b : β) => f b c) = tsum fun (b : β) => tsum fun (c : γ) => f b c := tsum_comm' h (summable.prod_factor h) (summable.prod_factor (summable.prod_symm h)) theorem summable.vanishing {α : Type u_1} {G : Type u_5} [topological_space G] [add_comm_group G] [topological_add_group G] {f : α → G} (hf : summable f) {e : set G} (he : e ∈ nhds 0) : ∃ (s : finset α), ∀ (t : finset α), disjoint t s → (finset.sum t fun (k : α) => f k) ∈ e := sorry /-- Series divergence test: if `f` is a convergent series, then `f x` tends to zero along `cofinite`. -/ theorem summable.tendsto_cofinite_zero {α : Type u_1} {G : Type u_5} [topological_space G] [add_comm_group G] [topological_add_group G] {f : α → G} (hf : summable f) : filter.tendsto f filter.cofinite (nhds 0) := sorry theorem summable_abs_iff {α : Type u_1} {β : Type u_2} [linear_ordered_add_comm_group β] [uniform_space β] [uniform_add_group β] [complete_space β] {f : α → β} : (summable fun (x : α) => abs (f x)) ↔ summable f := sorry theorem summable.of_abs {α : Type u_1} {β : Type u_2} [linear_ordered_add_comm_group β] [uniform_space β] [uniform_add_group β] [complete_space β] {f : α → β} : (summable fun (x : α) => abs (f x)) → summable f := iff.mp summable_abs_iff /-- If the extended distance between consequent points of a sequence is estimated by a summable series of `nnreal`s, then the original sequence is a Cauchy sequence. -/ theorem cauchy_seq_of_edist_le_of_summable {α : Type u_1} [emetric_space α] {f : ℕ → α} (d : ℕ → nnreal) (hf : ∀ (n : ℕ), edist (f n) (f (Nat.succ n)) ≤ ↑(d n)) (hd : summable d) : cauchy_seq f := sorry /-- If the distance between consequent points of a sequence is estimated by a summable series, then the original sequence is a Cauchy sequence. -/ theorem cauchy_seq_of_dist_le_of_summable {α : Type u_1} [metric_space α] {f : ℕ → α} (d : ℕ → ℝ) (hf : ∀ (n : ℕ), dist (f n) (f (Nat.succ n)) ≤ d n) (hd : summable d) : cauchy_seq f := sorry theorem cauchy_seq_of_summable_dist {α : Type u_1} [metric_space α] {f : ℕ → α} (h : summable fun (n : ℕ) => dist (f n) (f (Nat.succ n))) : cauchy_seq f := cauchy_seq_of_dist_le_of_summable (fun (n : ℕ) => dist (f n) (f (Nat.succ n))) (fun (_x : ℕ) => le_refl (dist (f _x) (f (Nat.succ _x)))) h theorem dist_le_tsum_of_dist_le_of_tendsto {α : Type u_1} [metric_space α] {f : ℕ → α} (d : ℕ → ℝ) (hf : ∀ (n : ℕ), dist (f n) (f (Nat.succ n)) ≤ d n) (hd : summable d) {a : α} (ha : filter.tendsto f filter.at_top (nhds a)) (n : ℕ) : dist (f n) a ≤ tsum fun (m : ℕ) => d (n + m) := sorry theorem dist_le_tsum_of_dist_le_of_tendsto₀ {α : Type u_1} [metric_space α] {f : ℕ → α} (d : ℕ → ℝ) (hf : ∀ (n : ℕ), dist (f n) (f (Nat.succ n)) ≤ d n) (hd : summable d) {a : α} (ha : filter.tendsto f filter.at_top (nhds a)) : dist (f 0) a ≤ tsum d := sorry theorem dist_le_tsum_dist_of_tendsto {α : Type u_1} [metric_space α] {f : ℕ → α} (h : summable fun (n : ℕ) => dist (f n) (f (Nat.succ n))) {a : α} (ha : filter.tendsto f filter.at_top (nhds a)) (n : ℕ) : dist (f n) a ≤ tsum fun (m : ℕ) => dist (f (n + m)) (f (Nat.succ (n + m))) := (fun (this : dist (f n) a ≤ tsum fun (m : ℕ) => (fun (n : ℕ) => dist (f n) (f (Nat.succ n))) (n + m)) => this) (dist_le_tsum_of_dist_le_of_tendsto (fun (n : ℕ) => dist (f n) (f (Nat.succ n))) (fun (_x : ℕ) => le_refl (dist (f _x) (f (Nat.succ _x)))) h ha n) theorem dist_le_tsum_dist_of_tendsto₀ {α : Type u_1} [metric_space α] {f : ℕ → α} (h : summable fun (n : ℕ) => dist (f n) (f (Nat.succ n))) {a : α} (ha : filter.tendsto f filter.at_top (nhds a)) : dist (f 0) a ≤ tsum fun (n : ℕ) => dist (f n) (f (Nat.succ n)) := sorry end Mathlib
e6463b762f9b7f5b817b04ffba2f1098d0463f20
367134ba5a65885e863bdc4507601606690974c1
/src/data/zsqrtd/to_real.lean
64efbd5a493870437de783dba30da53c77a2409e
[ "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
846
lean
/- Copyright (c) 2021 Eric Wieser. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Eric Wieser -/ import data.real.sqrt import data.zsqrtd.basic /-! # Image of `zsqrtd` in `ℝ` This file defines `zsqrtd.to_real` and related lemmas. It is in a separate file to avoid pulling in all of `data.real` into `data.zsqrtd`. -/ namespace zsqrtd /-- The image of `zsqrtd` in `ℝ`, using `real.sqrt` which takes the positive root of `d`. If the negative root is desired, use `to_real h a.conj`. -/ @[simps] noncomputable def to_real {d : ℤ} (h : 0 ≤ d) : ℤ√d →+* ℝ := lift ⟨real.sqrt d, real.mul_self_sqrt (int.cast_nonneg.mpr h)⟩ lemma to_real_injective {d : ℤ} (h0d : 0 ≤ d) (hd : ∀ n : ℤ, d ≠ n*n) : function.injective (to_real h0d) := lift_injective _ hd end zsqrtd
7357b7203305bb92aabec619b5887a1e9e7f6c86
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/data/equiv/ring_aut.lean
42dbccc8a7e741faf7ba4e7c9b4224e0da91d3a1
[ "Apache-2.0" ]
permissive
robertylewis/mathlib
3d16e3e6daf5ddde182473e03a1b601d2810952c
1d13f5b932f5e40a8308e3840f96fc882fae01f0
refs/heads/master
1,651,379,945,369
1,644,276,960,000
1,644,276,960,000
98,875,504
0
0
Apache-2.0
1,644,253,514,000
1,501,495,700,000
Lean
UTF-8
Lean
false
false
2,178
lean
/- Copyright (c) 2018 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Callum Sutton, Yury Kudryashov -/ import data.equiv.mul_add_aut import data.equiv.ring /-! # Ring automorphisms This file defines the automorphism group structure on `ring_aut R := ring_equiv R R`. ## Implementation notes The definition of multiplication in the automorphism group agrees with function composition, multiplication in `equiv.perm`, and multiplication in `category_theory.End`, but not with `category_theory.comp`. This file is kept separate from `data/equiv/ring` so that `group_theory.perm` is free to use equivalences (and other files that use them) before the group structure is defined. ## Tags ring_aut -/ /-- The group of ring automorphisms. -/ @[reducible] def ring_aut (R : Type*) [has_mul R] [has_add R] := ring_equiv R R namespace ring_aut variables (R : Type*) [has_mul R] [has_add R] /-- The group operation on automorphisms of a ring is defined by `λ g h, ring_equiv.trans h g`. This means that multiplication agrees with composition, `(g*h)(x) = g (h x)`. -/ instance : group (ring_aut R) := by refine_struct { mul := λ g h, ring_equiv.trans h g, one := ring_equiv.refl R, inv := ring_equiv.symm, div := _, npow := @npow_rec _ ⟨ring_equiv.refl R⟩ ⟨λ g h, ring_equiv.trans h g⟩, zpow := @zpow_rec _ ⟨ring_equiv.refl R⟩ ⟨λ g h, ring_equiv.trans h g⟩ ⟨ring_equiv.symm⟩ }; intros; ext; try { refl }; apply equiv.left_inv instance : inhabited (ring_aut R) := ⟨1⟩ /-- Monoid homomorphism from ring automorphisms to additive automorphisms. -/ def to_add_aut : ring_aut R →* add_aut R := by refine_struct { to_fun := ring_equiv.to_add_equiv }; intros; refl /-- Monoid homomorphism from ring automorphisms to multiplicative automorphisms. -/ def to_mul_aut : ring_aut R →* mul_aut R := by refine_struct { to_fun := ring_equiv.to_mul_equiv }; intros; refl /-- Monoid homomorphism from ring automorphisms to permutations. -/ def to_perm : ring_aut R →* equiv.perm R := by refine_struct { to_fun := ring_equiv.to_equiv }; intros; refl end ring_aut
8ed77812b1d2458ae8eccb1f42b50b26317c0755
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/ring_theory/ring_invo.lean
061d9a836cf933b6517bdadd6c126bd87e2a7f45
[ "Apache-2.0" ]
permissive
AntoineChambert-Loir/mathlib
64aabb896129885f12296a799818061bc90da1ff
07be904260ab6e36a5769680b6012f03a4727134
refs/heads/master
1,693,187,631,771
1,636,719,886,000
1,636,719,886,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
2,028
lean
/- Copyright (c) 2018 Andreas Swerdlow. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Andreas Swerdlow, Kenny Lau -/ import data.equiv.ring import algebra.opposites /-! # Ring involutions This file defines a ring involution as a structure extending `R ≃+* Rᵒᵖ`, with the additional fact `f.involution : (f (f x).unop).unop = x`. ## Notations We provide a coercion to a function `R → Rᵒᵖ`. ## References * <https://en.wikipedia.org/wiki/Involution_(mathematics)#Ring_theory> ## Tags Ring involution -/ variables (R : Type*) /-- A ring involution -/ structure ring_invo [semiring R] extends R ≃+* Rᵒᵖ := (involution' : ∀ x, (to_fun (to_fun x).unop).unop = x) namespace ring_invo variables {R} [semiring R] /-- Construct a ring involution from a ring homomorphism. -/ def mk' (f : R →+* Rᵒᵖ) (involution : ∀ r, (f (f r).unop).unop = r) : ring_invo R := { inv_fun := λ r, (f r.unop).unop, left_inv := λ r, involution r, right_inv := λ r, congr_arg opposite.op (involution (r.unop)), involution' := involution, ..f } instance : has_coe_to_fun (ring_invo R) (λ _, R → Rᵒᵖ) := ⟨λ f, f.to_ring_equiv.to_fun⟩ @[simp] lemma to_fun_eq_coe (f : ring_invo R) : f.to_fun = f := rfl @[simp] lemma involution (f : ring_invo R) (x : R) : (f (f x).unop).unop = x := f.involution' x instance has_coe_to_ring_equiv : has_coe (ring_invo R) (R ≃+* Rᵒᵖ) := ⟨ring_invo.to_ring_equiv⟩ @[norm_cast] lemma coe_ring_equiv (f : ring_invo R) (a : R) : (f : R ≃+* Rᵒᵖ) a = f a := rfl @[simp] lemma map_eq_zero_iff (f : ring_invo R) {x : R} : f x = 0 ↔ x = 0 := f.to_ring_equiv.map_eq_zero_iff end ring_invo open ring_invo section comm_ring variables [comm_ring R] /-- The identity function of a `comm_ring` is a ring involution. -/ protected def ring_invo.id : ring_invo R := { involution' := λ r, rfl, ..(ring_equiv.to_opposite R) } instance : inhabited (ring_invo R) := ⟨ring_invo.id _⟩ end comm_ring
408a719aa27cd33e36586b060721c0704692cfe5
ce6917c5bacabee346655160b74a307b4a5ab620
/src/ch3/ex0305.lean
166ed16f5849c1a16067deb53bc2c07b6506b79a
[]
no_license
Ailrun/Theorem_Proving_in_Lean
ae6a23f3c54d62d401314d6a771e8ff8b4132db2
2eb1b5caf93c6a5a555c79e9097cf2ba5a66cf68
refs/heads/master
1,609,838,270,467
1,586,846,743,000
1,586,846,743,000
240,967,761
1
0
null
null
null
null
UTF-8
Lean
false
false
83
lean
variables p q : Prop variables (hp : p) (hq : q) #check (⟨hp, hq⟩ : p ∧ q)
adcc2f42958b388b62d8dd904b36dcb94e4d10e5
94e33a31faa76775069b071adea97e86e218a8ee
/src/set_theory/surreal/basic.lean
1781d11f732772046566b232ff79267809763336
[ "Apache-2.0" ]
permissive
urkud/mathlib
eab80095e1b9f1513bfb7f25b4fa82fa4fd02989
6379d39e6b5b279df9715f8011369a301b634e41
refs/heads/master
1,658,425,342,662
1,658,078,703,000
1,658,078,703,000
186,910,338
0
0
Apache-2.0
1,568,512,083,000
1,557,958,709,000
Lean
UTF-8
Lean
false
false
13,910
lean
/- Copyright (c) 2019 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Scott Morrison -/ import algebra.order.hom.monoid import set_theory.game.ordinal /-! # Surreal numbers The basic theory of surreal numbers, built on top of the theory of combinatorial (pre-)games. A pregame is `numeric` if all the Left options are strictly smaller than all the Right options, and all those options are themselves numeric. In terms of combinatorial games, the numeric games have "frozen"; you can only make your position worse by playing, and Left is some definite "number" of moves ahead (or behind) Right. A surreal number is an equivalence class of numeric pregames. In fact, the surreals form a complete ordered field, containing a copy of the reals (and much else besides!) but we do not yet have a complete development. ## Order properties Surreal numbers inherit the relations `≤` and `<` from games (`surreal.has_le` and `surreal.has_lt`), and these relations satisfy the axioms of a partial order. ## Algebraic operations We show that the surreals form a linear ordered commutative group. One can also map all the ordinals into the surreals! ### Multiplication of surreal numbers The proof that multiplication lifts to surreal numbers is surprisingly difficult and is currently missing in the library. A sample proof can be found in Theorem 3.8 in the second reference below. The difficulty lies in the length of the proof and the number of theorems that need to proven simultaneously. This will make for a fun and challenging project. The branch `surreal_mul` contains some progress on this proof. ### Todo - Define the field structure on the surreals. ## References * [Conway, *On numbers and games*][conway2001] * [Schleicher, Stoll, *An introduction to Conway's games and numbers*][schleicher_stoll] -/ universes u local infix ` ≈ ` := pgame.equiv local infix ` ⧏ `:50 := pgame.lf namespace pgame /-- A pre-game is numeric if everything in the L set is less than everything in the R set, and all the elements of L and R are also numeric. -/ def numeric : pgame → Prop | ⟨l, r, L, R⟩ := (∀ i j, L i < R j) ∧ (∀ i, numeric (L i)) ∧ (∀ j, numeric (R j)) lemma numeric_def {x : pgame} : numeric x ↔ (∀ i j, x.move_left i < x.move_right j) ∧ (∀ i, numeric (x.move_left i)) ∧ (∀ j, numeric (x.move_right j)) := by { cases x, refl } namespace numeric lemma mk {x : pgame} (h₁ : ∀ i j, x.move_left i < x.move_right j) (h₂ : ∀ i, numeric (x.move_left i)) (h₃ : ∀ j, numeric (x.move_right j)) : numeric x := numeric_def.2 ⟨h₁, h₂, h₃⟩ lemma left_lt_right {x : pgame} (o : numeric x) (i : x.left_moves) (j : x.right_moves) : x.move_left i < x.move_right j := by { cases x, exact o.1 i j } lemma move_left {x : pgame} (o : numeric x) (i : x.left_moves) : numeric (x.move_left i) := by { cases x, exact o.2.1 i } lemma move_right {x : pgame} (o : numeric x) (j : x.right_moves) : numeric (x.move_right j) := by { cases x, exact o.2.2 j } end numeric @[elab_as_eliminator] theorem numeric_rec {C : pgame → Prop} (H : ∀ l r (L : l → pgame) (R : r → pgame), (∀ i j, L i < R j) → (∀ i, numeric (L i)) → (∀ i, numeric (R i)) → (∀ i, C (L i)) → (∀ i, C (R i)) → C ⟨l, r, L, R⟩) : ∀ x, numeric x → C x | ⟨l, r, L, R⟩ ⟨h, hl, hr⟩ := H _ _ _ _ h hl hr (λ i, numeric_rec _ (hl i)) (λ i, numeric_rec _ (hr i)) theorem lf_asymm {x y : pgame} (ox : numeric x) (oy : numeric y) : x ⧏ y → ¬ y ⧏ x := begin refine numeric_rec (λ xl xr xL xR hx oxl oxr IHxl IHxr, _) x ox y oy, refine numeric_rec (λ yl yr yL yR hy oyl oyr IHyl IHyr, _), rw [mk_lf_mk, mk_lf_mk], rintro (⟨i, h₁⟩ | ⟨j, h₁⟩) (⟨i, h₂⟩ | ⟨j, h₂⟩), { exact IHxl _ _ (oyl _) (h₁.move_left_lf _) (h₂.move_left_lf _) }, { exact (le_trans h₂ h₁).not_gf (lf_of_lt (hy _ _)) }, { exact (le_trans h₁ h₂).not_gf (lf_of_lt (hx _ _)) }, { exact IHxr _ _ (oyr _) (h₁.lf_move_right _) (h₂.lf_move_right _) }, end theorem le_of_lf {x y : pgame} (h : x ⧏ y) (ox : numeric x) (oy : numeric y) : x ≤ y := not_lf.1 (lf_asymm ox oy h) alias le_of_lf ← lf.le theorem lt_of_lf {x y : pgame} (h : x ⧏ y) (ox : numeric x) (oy : numeric y) : x < y := (lt_or_fuzzy_of_lf h).resolve_right (not_fuzzy_of_le (h.le ox oy)) alias lt_of_lf ← lf.lt theorem lf_iff_lt {x y : pgame} (ox : numeric x) (oy : numeric y) : x ⧏ y ↔ x < y := ⟨λ h, h.lt ox oy, lf_of_lt⟩ /-- Definition of `x ≤ y` on numeric pre-games, in terms of `<` -/ theorem le_iff_forall_lt {x y : pgame} (ox : x.numeric) (oy : y.numeric) : x ≤ y ↔ (∀ i, x.move_left i < y) ∧ ∀ j, x < y.move_right j := begin refine le_iff_forall_lf.trans (and_congr _ _); refine forall_congr (λ i, lf_iff_lt _ _); apply_rules [numeric.move_left, numeric.move_right] end /-- Definition of `x < y` on numeric pre-games, in terms of `≤` -/ theorem lt_iff_exists_le {x y : pgame} (ox : x.numeric) (oy : y.numeric) : x < y ↔ (∃ i, x ≤ y.move_left i) ∨ ∃ j, x.move_right j ≤ y := by rw [←lf_iff_lt ox oy, lf_iff_exists_le] theorem lt_of_exists_le {x y : pgame} (ox : x.numeric) (oy : y.numeric) : ((∃ i, x ≤ y.move_left i) ∨ ∃ j, x.move_right j ≤ y) → x < y := (lt_iff_exists_le ox oy).2 /-- The definition of `x < y` on numeric pre-games, in terms of `<` two moves later. -/ theorem lt_def {x y : pgame} (ox : x.numeric) (oy : y.numeric) : 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' := begin rw [←lf_iff_lt ox oy, lf_def], refine or_congr _ _; refine exists_congr (λ x_1, _); refine and_congr _ _; refine (forall_congr $ λ i, lf_iff_lt _ _); apply_rules [numeric.move_left, numeric.move_right] end theorem not_fuzzy {x y : pgame} (ox : numeric x) (oy : numeric y) : ¬ fuzzy x y := λ h, not_lf.2 ((lf_of_fuzzy h).le ox oy) h.2 theorem lt_or_equiv_or_gt {x y : pgame} (ox : numeric x) (oy : numeric y) : x < y ∨ x ≈ y ∨ y < x := (lf_or_equiv_or_gf x y).imp (λ h, h.lt ox oy) $ or.imp_right $ λ h, h.lt oy ox theorem numeric_of_is_empty (x : pgame) [is_empty x.left_moves] [is_empty x.right_moves] : numeric x := numeric.mk is_empty_elim is_empty_elim is_empty_elim theorem numeric_of_is_empty_left_moves (x : pgame) [is_empty x.left_moves] : (∀ j, numeric (x.move_right j)) → numeric x := numeric.mk is_empty_elim is_empty_elim theorem numeric_of_is_empty_right_moves (x : pgame) [is_empty x.right_moves] (H : ∀ i, numeric (x.move_left i)) : numeric x := numeric.mk (λ _, is_empty_elim) H is_empty_elim theorem numeric_zero : numeric 0 := numeric_of_is_empty 0 theorem numeric_one : numeric 1 := numeric_of_is_empty_right_moves 1 $ λ _, numeric_zero theorem numeric.neg : Π {x : pgame} (o : numeric x), numeric (-x) | ⟨l, r, L, R⟩ o := ⟨λ j i, neg_lt_neg_iff.2 (o.1 i j), λ j, (o.2.2 j).neg, λ i, (o.2.1 i).neg⟩ namespace numeric theorem move_left_lt {x : pgame} (o : numeric x) (i) : x.move_left i < x := (pgame.move_left_lf i).lt (o.move_left i) o theorem move_left_le {x : pgame} (o : numeric x) (i) : x.move_left i ≤ x := (o.move_left_lt i).le theorem lt_move_right {x : pgame} (o : numeric x) (j) : x < x.move_right j := (pgame.lf_move_right j).lt o (o.move_right j) theorem le_move_right {x : pgame} (o : numeric x) (j) : x ≤ x.move_right j := (o.lt_move_right j).le theorem add : Π {x y : pgame} (ox : numeric x) (oy : numeric y), numeric (x + y) | ⟨xl, xr, xL, xR⟩ ⟨yl, yr, yL, yR⟩ ox oy := ⟨begin rintros (ix|iy) (jx|jy), { exact add_lt_add_right (ox.1 ix jx) _ }, { exact (add_lf_add_of_lf_of_le (pgame.lf_mk _ _ ix) (oy.le_move_right jy)).lt ((ox.move_left ix).add oy) (ox.add (oy.move_right jy)) }, { exact (add_lf_add_of_lf_of_le (pgame.mk_lf _ _ jx) (oy.move_left_le iy)).lt (ox.add (oy.move_left iy)) ((ox.move_right jx).add oy) }, { exact add_lt_add_left (oy.1 iy jy) ⟨xl, xr, xL, xR⟩ } end, begin split, { rintros (ix|iy), { exact (ox.move_left ix).add oy }, { exact ox.add (oy.move_left iy) } }, { rintros (jx|jy), { apply (ox.move_right jx).add oy }, { apply ox.add (oy.move_right jy) } } end⟩ using_well_founded { dec_tac := pgame_wf_tac } lemma sub {x y : pgame} (ox : numeric x) (oy : numeric y) : numeric (x - y) := ox.add oy.neg end numeric /-- Pre-games defined by natural numbers are numeric. -/ theorem numeric_nat : Π (n : ℕ), numeric n | 0 := numeric_zero | (n + 1) := (numeric_nat n).add numeric_one /-- Ordinal games are numeric. -/ theorem numeric_to_pgame (o : ordinal) : o.to_pgame.numeric := begin induction o using ordinal.induction with o IH, apply numeric_of_is_empty_right_moves, simpa using λ i, IH _ (ordinal.to_left_moves_to_pgame_symm_lt i) end end pgame /-- The equivalence on numeric pre-games. -/ def surreal.equiv (x y : {x // pgame.numeric x}) : Prop := x.1.equiv y.1 open pgame instance surreal.setoid : setoid {x // pgame.numeric x} := ⟨λ x y, x.1 ≈ y.1, λ x, equiv_rfl, λ x y, pgame.equiv.symm, λ x y z, pgame.equiv.trans⟩ /-- The type of surreal numbers. These are the numeric pre-games quotiented by the equivalence relation `x ≈ y ↔ x ≤ y ∧ y ≤ x`. In the quotient, the order becomes a total order. -/ def surreal := quotient surreal.setoid namespace surreal /-- Construct a surreal number from a numeric pre-game. -/ def mk (x : pgame) (h : x.numeric) : surreal := ⟦⟨x, h⟩⟧ instance : has_zero surreal := ⟨mk 0 numeric_zero⟩ instance : has_one surreal := ⟨mk 1 numeric_one⟩ instance : inhabited surreal := ⟨0⟩ /-- Lift an equivalence-respecting function on pre-games to surreals. -/ def lift {α} (f : ∀ x, numeric x → α) (H : ∀ {x y} (hx : numeric x) (hy : numeric y), x.equiv y → f x hx = f y hy) : surreal → α := quotient.lift (λ x : {x // numeric x}, f x.1 x.2) (λ x y, H x.2 y.2) /-- Lift a binary equivalence-respecting function on pre-games to surreals. -/ def lift₂ {α} (f : ∀ x y, numeric x → numeric y → α) (H : ∀ {x₁ y₁ x₂ y₂} (ox₁ : numeric x₁) (oy₁ : numeric y₁) (ox₂ : numeric x₂) (oy₂ : numeric y₂), x₁.equiv x₂ → y₁.equiv y₂ → f x₁ y₁ ox₁ oy₁ = f x₂ y₂ ox₂ oy₂) : surreal → surreal → α := lift (λ x ox, lift (λ y oy, f x y ox oy) (λ y₁ y₂ oy₁ oy₂, H _ _ _ _ equiv_rfl)) (λ x₁ x₂ ox₁ ox₂ h, funext $ quotient.ind $ by exact λ ⟨y, oy⟩, H _ _ _ _ h equiv_rfl) instance : has_le surreal := ⟨lift₂ (λ x y _ _, x ≤ y) (λ x₁ y₁ x₂ y₂ _ _ _ _ hx hy, propext (le_congr hx hy))⟩ instance : has_lt surreal := ⟨lift₂ (λ x y _ _, x < y) (λ x₁ y₁ x₂ y₂ _ _ _ _ hx hy, propext (lt_congr hx hy))⟩ /-- Addition on surreals is inherited from pre-game addition: the sum of `x = {xL | xR}` and `y = {yL | yR}` is `{xL + y, x + yL | xR + y, x + yR}`. -/ instance : has_add surreal := ⟨surreal.lift₂ (λ (x y : pgame) (ox) (oy), ⟦⟨x + y, ox.add oy⟩⟧) (λ x₁ y₁ x₂ y₂ _ _ _ _ hx hy, quotient.sound (pgame.add_congr hx hy))⟩ /-- Negation for surreal numbers is inherited from pre-game negation: the negation of `{L | R}` is `{-R | -L}`. -/ instance : has_neg surreal := ⟨surreal.lift (λ x ox, ⟦⟨-x, ox.neg⟩⟧) (λ _ _ _ _ a, quotient.sound (pgame.neg_equiv_neg_iff.2 a))⟩ instance : ordered_add_comm_group surreal := { add := (+), add_assoc := by { rintros ⟨_⟩ ⟨_⟩ ⟨_⟩, exact quotient.sound add_assoc_equiv }, zero := 0, zero_add := by { rintros ⟨_⟩, exact quotient.sound (pgame.zero_add_equiv a) }, add_zero := by { rintros ⟨_⟩, exact quotient.sound (pgame.add_zero_equiv a) }, neg := has_neg.neg, add_left_neg := by { rintros ⟨_⟩, exact quotient.sound (pgame.add_left_neg_equiv a) }, add_comm := by { rintros ⟨_⟩ ⟨_⟩, exact quotient.sound pgame.add_comm_equiv }, le := (≤), lt := (<), le_refl := by { rintros ⟨_⟩, apply @le_rfl pgame }, le_trans := by { rintros ⟨_⟩ ⟨_⟩ ⟨_⟩, apply @le_trans pgame }, lt_iff_le_not_le := by { rintros ⟨_, ox⟩ ⟨_, oy⟩, apply @lt_iff_le_not_le pgame }, le_antisymm := by { rintros ⟨_⟩ ⟨_⟩ h₁ h₂, exact quotient.sound ⟨h₁, h₂⟩ }, add_le_add_left := by { rintros ⟨_⟩ ⟨_⟩ hx ⟨_⟩, exact @add_le_add_left pgame _ _ _ _ _ hx _ } } noncomputable instance : linear_ordered_add_comm_group surreal := { le_total := by rintro ⟨⟨x, ox⟩⟩ ⟨⟨y, oy⟩⟩; classical; exact or_iff_not_imp_left.2 (λ h, (pgame.not_le.1 h).le oy ox), decidable_le := classical.dec_rel _, ..surreal.ordered_add_comm_group } instance : add_monoid_with_one surreal := add_monoid_with_one.unary /-- Casts a `surreal` number into a `game`. -/ def to_game : surreal →+o game := { to_fun := lift (λ x _, ⟦x⟧) (λ x y ox oy, quot.sound), map_zero' := rfl, map_add' := by { rintros ⟨_, _⟩ ⟨_, _⟩, refl }, monotone' := by { rintros ⟨_, _⟩ ⟨_, _⟩, exact id } } theorem zero_to_game : to_game 0 = 0 := rfl @[simp] theorem one_to_game : to_game 1 = 1 := rfl @[simp] theorem nat_to_game : ∀ n : ℕ, to_game n = n := map_nat_cast' _ one_to_game end surreal open surreal namespace ordinal /-- Converts an ordinal into the corresponding surreal. -/ noncomputable def to_surreal : ordinal ↪o surreal := { to_fun := λ o, mk _ (numeric_to_pgame o), inj' := λ a b h, to_pgame_equiv_iff.1 (quotient.exact h), map_rel_iff' := @to_pgame_le_iff } end ordinal
8bc4e2d1ac279bcfff4f558730ad8549c4715da1
dd0f5513e11c52db157d2fcc8456d9401a6cd9da
/04_Quantifiers_and_Equality.org.14.lean
57d89534cc4115f9ae50511ade20f0f7ae2347d8
[]
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
246
lean
/- page 52 -/ import standard import data.nat data.prod open nat prod variables (A B : Type) -- BEGIN example (f : A → B) (a : A) : (λ x, f x) a = f a := rfl example (a : A) (b : A) : pr1 (a, b) = a := rfl example : 2 + 3 = 5 := rfl -- END
f9e5f39fdee8836977edcde04989d60dc1a4866f
9028d228ac200bbefe3a711342514dd4e4458bff
/src/analysis/convex/basic.lean
c1189b597d8218625f4e145cd2a7f22ad51f076d
[ "Apache-2.0" ]
permissive
mcncm/mathlib
8d25099344d9d2bee62822cb9ed43aa3e09fa05e
fde3d78cadeec5ef827b16ae55664ef115e66f57
refs/heads/master
1,672,743,316,277
1,602,618,514,000
1,602,618,514,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
57,804
lean
/- Copyright (c) 2019 Alexander Bentkamp. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Alexander Bentkamp, Yury Kudriashov -/ import data.set.intervals.ord_connected import data.set.intervals.image_preimage import data.complex.module import linear_algebra.affine_space.basic import algebra.module.ordered /-! # Convex sets and functions on real vector spaces In a real vector space, we define the following objects and properties. * `segment x y` is the closed segment joining `x` and `y`. * A set `s` is `convex` if for any two points `x y ∈ s` it includes `segment x y`; * A function `f : E → β` is `convex_on` a set `s` if `s` is itself a convex set, and for any two points `x y ∈ s` the segment joining `(x, f x)` to `(y, f y)` is (non-strictly) above the graph of `f`; equivalently, `convex_on f s` means that the epigraph `{p : E × β | p.1 ∈ s ∧ f p.1 ≤ p.2}` is a convex set; * Center mass of a finite set of points with prescribed weights. * Convex hull of a set `s` is the minimal convex set that includes `s`. * Standard simplex `std_simplex ι [fintype ι]` is the intersection of the positive quadrant with the hyperplane `s.sum = 1` in the space `ι → ℝ`. We also provide various equivalent versions of the definitions above, prove that some specific sets are convex, and prove Jensen's inequality. Note: To define convexity for functions `f : E → β`, we need `β` to be an ordered vector space, defined using the instance `ordered_semimodule ℝ β`. ## Notations We use the following local notations: * `I = Icc (0:ℝ) 1`; * `[x, y] = segment x y`. They are defined using `local notation`, so they are not available outside of this file. -/ universes u' u v v' w x variables {E : Type u} {F : Type v} {ι : Type w} {ι' : Type x} {α : Type v'} [add_comm_group E] [vector_space ℝ E] [add_comm_group F] [vector_space ℝ F] [linear_ordered_field α] {s : set E} open set linear_map open_locale classical big_operators local notation `I` := (Icc 0 1 : set ℝ) section sets /-! ### Segment -/ /-- Segments in a vector space -/ def segment (x y : E) : set E := {z : E | ∃ (a b : ℝ) (ha : 0 ≤ a) (hb : 0 ≤ b) (hab : a + b = 1), a • x + b • y = z} local notation `[`x `, ` y `]` := segment x y lemma segment_symm (x y : E) : [x, y] = [y, x] := set.ext $ λ z, ⟨λ ⟨a, b, ha, hb, hab, H⟩, ⟨b, a, hb, ha, (add_comm _ _).trans hab, (add_comm _ _).trans H⟩, λ ⟨a, b, ha, hb, hab, H⟩, ⟨b, a, hb, ha, (add_comm _ _).trans hab, (add_comm _ _).trans H⟩⟩ lemma left_mem_segment (x y : E) : x ∈ [x, y] := ⟨1, 0, zero_le_one, le_refl 0, add_zero 1, by rw [zero_smul, one_smul, add_zero]⟩ lemma right_mem_segment (x y : E) : y ∈ [x, y] := segment_symm y x ▸ left_mem_segment y x lemma segment_same (x : E) : [x, x] = {x} := set.ext $ λ z, ⟨λ ⟨a, b, ha, hb, hab, hz⟩, by simpa only [(add_smul _ _ _).symm, mem_singleton_iff, hab, one_smul, eq_comm] using hz, λ h, mem_singleton_iff.1 h ▸ left_mem_segment z z⟩ lemma segment_eq_image (x y : E) : segment x y = (λ (θ : ℝ), (1 - θ) • x + θ • y) '' I := set.ext $ λ z, ⟨λ ⟨a, b, ha, hb, hab, hz⟩, ⟨b, ⟨hb, hab ▸ le_add_of_nonneg_left ha⟩, hab ▸ hz ▸ by simp only [add_sub_cancel]⟩, λ ⟨θ, ⟨hθ₀, hθ₁⟩, hz⟩, ⟨1-θ, θ, sub_nonneg.2 hθ₁, hθ₀, sub_add_cancel _ _, hz⟩⟩ lemma segment_eq_image' (x y : E) : segment x y = (λ (θ : ℝ), x + θ • (y - x)) '' I := by { convert segment_eq_image x y, ext θ, simp only [smul_sub, sub_smul, one_smul], abel } lemma segment_eq_image₂ (x y : E) : segment x y = (λ p:ℝ×ℝ, p.1 • x + p.2 • y) '' {p | 0 ≤ p.1 ∧ 0 ≤ p.2 ∧ p.1 + p.2 = 1} := by simp only [segment, image, prod.exists, mem_set_of_eq, exists_prop, and_assoc] lemma segment_eq_Icc {a b : ℝ} (h : a ≤ b) : [a, b] = Icc a b := begin rw [segment_eq_image'], show (((+) a) ∘ (λ t, t * (b - a))) '' Icc 0 1 = Icc a b, rw [image_comp, image_mul_right_Icc (@zero_le_one ℝ _) (sub_nonneg.2 h), image_const_add_Icc], simp end lemma segment_eq_Icc' (a b : ℝ) : [a, b] = Icc (min a b) (max a b) := by cases le_total a b; [skip, rw segment_symm]; simp [segment_eq_Icc, *] lemma segment_eq_interval (a b : ℝ) : segment a b = interval a b := segment_eq_Icc' _ _ lemma mem_segment_translate (a : E) {x b c} : a + x ∈ [a + b, a + c] ↔ x ∈ [b, c] := begin rw [segment_eq_image', segment_eq_image'], refine exists_congr (λ θ, and_congr iff.rfl _), simp only [add_sub_add_left_eq_sub, add_assoc, add_right_inj] end lemma segment_translate_preimage (a b c : E) : (λ x, a + x) ⁻¹' [a + b, a + c] = [b, c] := set.ext $ λ x, mem_segment_translate a lemma segment_translate_image (a b c: E) : (λx, a + x) '' [b, c] = [a + b, a + c] := segment_translate_preimage a b c ▸ image_preimage_eq $ add_left_surjective a /-! ### Convexity of sets -/ /-- Convexity of sets -/ def convex (s : set E) := ∀ ⦃x y : E⦄, x ∈ s → y ∈ s → ∀ ⦃a b : ℝ⦄, 0 ≤ a → 0 ≤ b → a + b = 1 → a • x + b • y ∈ s lemma convex_iff_forall_pos : convex s ↔ ∀ ⦃x y⦄, x ∈ s → y ∈ s → ∀ ⦃a b : ℝ⦄, 0 < a → 0 < b → a + b = 1 → a • x + b • y ∈ s := begin refine ⟨λ h x y hx hy a b ha hb hab, h hx hy (le_of_lt ha) (le_of_lt hb) hab, _⟩, intros h x y hx hy a b ha hb hab, cases eq_or_lt_of_le ha with ha ha, { subst a, rw [zero_add] at hab, simp [hab, hy] }, cases eq_or_lt_of_le hb with hb hb, { subst b, rw [add_zero] at hab, simp [hab, hx] }, exact h hx hy ha hb hab end lemma convex_iff_segment_subset : convex s ↔ ∀ ⦃x y⦄, x ∈ s → y ∈ s → [x, y] ⊆ s := by simp only [convex, segment_eq_image₂, subset_def, ball_image_iff, prod.forall, mem_set_of_eq, and_imp] lemma convex.segment_subset (h : convex s) {x y:E} (hx : x ∈ s) (hy : y ∈ s) : [x, y] ⊆ s := convex_iff_segment_subset.1 h hx hy /-- Alternative definition of set convexity, in terms of pointwise set operations. -/ lemma convex_iff_pointwise_add_subset: convex s ↔ ∀ ⦃a b : ℝ⦄, 0 ≤ a → 0 ≤ b → a + b = 1 → a • s + b • s ⊆ s := iff.intro begin rintros hA a b ha hb hab w ⟨au, bv, ⟨u, hu, rfl⟩, ⟨v, hv, rfl⟩, rfl⟩, exact hA hu hv ha hb hab end (λ h x y hx hy a b ha hb hab, (h ha hb hab) (set.add_mem_add ⟨_, hx, rfl⟩ ⟨_, hy, rfl⟩)) /-- Alternative definition of set convexity, using division -/ lemma convex_iff_div: convex s ↔ ∀ ⦃x y : E⦄, x ∈ s → y ∈ s → ∀ ⦃a b : ℝ⦄, 0 ≤ a → 0 ≤ b → 0 < a + b → (a/(a+b)) • x + (b/(a+b)) • y ∈ s := ⟨begin assume h x y hx hy a b ha hb hab, apply h hx hy, have ha', from mul_le_mul_of_nonneg_left ha (le_of_lt (inv_pos.2 hab)), rwa [mul_zero, ←div_eq_inv_mul] at ha', have hb', from mul_le_mul_of_nonneg_left hb (le_of_lt (inv_pos.2 hab)), rwa [mul_zero, ←div_eq_inv_mul] at hb', rw [←add_div], exact div_self (ne_of_lt hab).symm end, begin assume h x y hx hy a b ha hb hab, have h', from h hx hy ha hb, rw [hab, div_one, div_one] at h', exact h' zero_lt_one end⟩ /-! ### Examples of convex sets -/ lemma convex_empty : convex (∅ : set E) := by finish lemma convex_singleton (c : E) : convex ({c} : set E) := begin intros x y hx hy a b ha hb hab, rw [set.eq_of_mem_singleton hx, set.eq_of_mem_singleton hy, ←add_smul, hab, one_smul], exact mem_singleton c end lemma convex_univ : convex (set.univ : set E) := λ _ _ _ _ _ _ _ _ _, trivial lemma convex.inter {t : set E} (hs: convex s) (ht: convex t) : convex (s ∩ t) := λ x y (hx : x ∈ s ∩ t) (hy : y ∈ s ∩ t) a b (ha : 0 ≤ a) (hb : 0 ≤ b) (hab : a + b = 1), ⟨hs hx.left hy.left ha hb hab, ht hx.right hy.right ha hb hab⟩ lemma convex_sInter {S : set (set E)} (h : ∀ s ∈ S, convex s) : convex (⋂₀ S) := assume x y hx hy a b ha hb hab s hs, h s hs (hx s hs) (hy s hs) ha hb hab lemma convex_Inter {ι : Sort*} {s: ι → set E} (h: ∀ i : ι, convex (s i)) : convex (⋂ i, s i) := (sInter_range s) ▸ convex_sInter $ forall_range_iff.2 h lemma convex.prod {s : set E} {t : set F} (hs : convex s) (ht : convex t) : convex (s.prod t) := begin intros x y hx hy a b ha hb hab, apply mem_prod.2, exact ⟨hs (mem_prod.1 hx).1 (mem_prod.1 hy).1 ha hb hab, ht (mem_prod.1 hx).2 (mem_prod.1 hy).2 ha hb hab⟩ end lemma convex.combo_to_vadd {a b : ℝ} {x y : E} (h : a + b = 1) : a • x + b • y = b • (y - x) + x := eq.symm (calc b • (y - x) + x = b • (y - x) + (1 : ℝ) • x : by rw [one_smul] ... = b • (y - x) + (a + b) • x : by rw [h] ... = (b • y - b • x) + (a • x + b • x) : by rw [add_smul, smul_sub] ... = a • x + b • y : by abel ) /-- Applying an affine map to an affine combination of two points yields an affine combination of the images. -/ lemma convex.combo_affine_apply {a b : ℝ} {x y : E} {f : affine_map ℝ E F} (h : a + b = 1) : f (a • x + b • y) = a • f x + b • f y := begin simp only [convex.combo_to_vadd h, ← vsub_eq_sub, ← f.linear_map_vsub], exact affine_map.affine_apply_line_map f x (y - x) b, end /-- The preimage of a convex set under an affine map is convex. -/ lemma convex.affine_preimage (f : affine_map ℝ E F) {s : set F} (hs : convex s) : convex (f ⁻¹' s) := begin intros x y xs ys a b ha hb hab, rw [mem_preimage, convex.combo_affine_apply hab], exact hs xs ys ha hb hab, end /-- The image of a convex set under an affine map is convex. -/ lemma convex.affine_image (f : affine_map ℝ E F) {s : set E} (hs : convex s) : convex (f '' s) := begin rintros x y ⟨x', ⟨hx', hx'f⟩⟩ ⟨y', ⟨hy', hy'f⟩⟩ a b ha hb hab, refine ⟨a • x' + b • y', ⟨hs hx' hy' ha hb hab, _⟩⟩, rw [convex.combo_affine_apply hab, hx'f, hy'f] end lemma convex.linear_image (hs : convex s) (f : E →ₗ[ℝ] F) : convex (image f s) := hs.affine_image f.to_affine_map lemma convex.is_linear_image (hs : convex s) {f : E → F} (hf : is_linear_map ℝ f) : convex (f '' s) := hs.linear_image $ hf.mk' f lemma convex.linear_preimage {s : set F} (hs : convex s) (f : E →ₗ[ℝ] F) : convex (preimage f s) := hs.affine_preimage f.to_affine_map lemma convex.is_linear_preimage {s : set F} (hs : convex s) {f : E → F} (hf : is_linear_map ℝ f) : convex (preimage f s) := hs.linear_preimage $ hf.mk' f lemma convex.neg (hs : convex s) : convex ((λ z, -z) '' s) := hs.is_linear_image is_linear_map.is_linear_map_neg lemma convex.neg_preimage (hs : convex s) : convex ((λ z, -z) ⁻¹' s) := hs.is_linear_preimage is_linear_map.is_linear_map_neg lemma convex.smul (c : ℝ) (hs : convex s) : convex (c • s) := hs.linear_image (linear_map.lsmul _ _ c) lemma convex.smul_preimage (c : ℝ) (hs : convex s) : convex ((λ z, c • z) ⁻¹' s) := hs.linear_preimage (linear_map.lsmul _ _ c) lemma convex.add {t : set E} (hs : convex s) (ht : convex t) : convex (s + t) := by { rw ← add_image_prod, exact (hs.prod ht).is_linear_image is_linear_map.is_linear_map_add } lemma convex.sub {t : set E} (hs : convex s) (ht : convex t) : convex ((λx : E × E, x.1 - x.2) '' (s.prod t)) := (hs.prod ht).is_linear_image is_linear_map.is_linear_map_sub lemma convex.translate (hs : convex s) (z : E) : convex ((λx, z + x) '' s) := hs.affine_image $ affine_map.const ℝ E z +ᵥ affine_map.id ℝ E /-- The translation of a convex set is also convex -/ lemma convex.translate_preimage_right (hs : convex s) (a : E) : convex ((λ z, a + z) ⁻¹' s) := hs.affine_preimage $ affine_map.const ℝ E a +ᵥ affine_map.id ℝ E /-- The translation of a convex set is also convex -/ lemma convex.translate_preimage_left (hs : convex s) (a : E) : convex ((λ z, z + a) ⁻¹' s) := by simpa only [add_comm] using hs.translate_preimage_right a lemma convex.affinity (hs : convex s) (z : E) (c : ℝ) : convex ((λx, z + c • x) '' s) := hs.affine_image $ affine_map.const ℝ E z +ᵥ c • affine_map.id ℝ E lemma real.convex_iff_ord_connected {s : set ℝ} : convex s ↔ ord_connected s := begin simp only [convex_iff_segment_subset, segment_eq_interval, ord_connected_iff_interval_subset], exact forall_congr (λ x, forall_swap) end alias real.convex_iff_ord_connected ↔ convex.ord_connected set.ord_connected.convex lemma convex_Iio (r : ℝ) : convex (Iio r) := ord_connected_Iio.convex lemma convex_Ioi (r : ℝ) : convex (Ioi r) := ord_connected_Ioi.convex lemma convex_Iic (r : ℝ) : convex (Iic r) := ord_connected_Iic.convex lemma convex_Ici (r : ℝ) : convex (Ici r) := ord_connected_Ici.convex lemma convex_Ioo (r s : ℝ) : convex (Ioo r s) := ord_connected_Ioo.convex lemma convex_Ico (r s : ℝ) : convex (Ico r s) := ord_connected_Ico.convex lemma convex_Ioc (r : ℝ) (s : ℝ) : convex (Ioc r s) := ord_connected_Ioc.convex lemma convex_Icc (r : ℝ) (s : ℝ) : convex (Icc r s) := ord_connected_Icc.convex lemma convex_interval (r : ℝ) (s : ℝ) : convex (interval r s) := ord_connected_interval.convex lemma convex_segment (a b : E) : convex [a, b] := begin have : (λ (t : ℝ), a + t • (b - a)) = (λz : E, a + z) ∘ (λt:ℝ, t • (b - a)) := rfl, rw [segment_eq_image', this, image_comp], refine ((convex_Icc _ _).is_linear_image _).translate _, exact is_linear_map.is_linear_map_smul' _ end lemma convex_halfspace_lt {f : E → ℝ} (h : is_linear_map ℝ f) (r : ℝ) : convex {w | f w < r} := (convex_Iio r).is_linear_preimage h lemma convex_halfspace_le {f : E → ℝ} (h : is_linear_map ℝ f) (r : ℝ) : convex {w | f w ≤ r} := (convex_Iic r).is_linear_preimage h lemma convex_halfspace_gt {f : E → ℝ} (h : is_linear_map ℝ f) (r : ℝ) : convex {w | r < f w} := (convex_Ioi r).is_linear_preimage h lemma convex_halfspace_ge {f : E → ℝ} (h : is_linear_map ℝ f) (r : ℝ) : convex {w | r ≤ f w} := (convex_Ici r).is_linear_preimage h lemma convex_hyperplane {f : E → ℝ} (h : is_linear_map ℝ f) (r : ℝ) : convex {w | f w = r} := begin show convex (f ⁻¹' {p | p = r}), rw set_of_eq_eq_singleton, exact (convex_singleton r).is_linear_preimage h end lemma convex_halfspace_re_lt (r : ℝ) : convex {c : ℂ | c.re < r} := convex_halfspace_lt (is_linear_map.mk complex.add_re complex.smul_re) _ lemma convex_halfspace_re_le (r : ℝ) : convex {c : ℂ | c.re ≤ r} := convex_halfspace_le (is_linear_map.mk complex.add_re complex.smul_re) _ lemma convex_halfspace_re_gt (r : ℝ) : convex {c : ℂ | r < c.re } := convex_halfspace_gt (is_linear_map.mk complex.add_re complex.smul_re) _ lemma convex_halfspace_re_lge (r : ℝ) : convex {c : ℂ | r ≤ c.re} := convex_halfspace_ge (is_linear_map.mk complex.add_re complex.smul_re) _ lemma convex_halfspace_im_lt (r : ℝ) : convex {c : ℂ | c.im < r} := convex_halfspace_lt (is_linear_map.mk complex.add_im complex.smul_im) _ lemma convex_halfspace_im_le (r : ℝ) : convex {c : ℂ | c.im ≤ r} := convex_halfspace_le (is_linear_map.mk complex.add_im complex.smul_im) _ lemma convex_halfspace_im_gt (r : ℝ) : convex {c : ℂ | r < c.im } := convex_halfspace_gt (is_linear_map.mk complex.add_im complex.smul_im) _ lemma convex_halfspace_im_lge (r : ℝ) : convex {c : ℂ | r ≤ c.im} := convex_halfspace_ge (is_linear_map.mk complex.add_im complex.smul_im) _ /- Convex combinations in intervals -/ lemma convex.combo_self (a : α) {x y : α} (h : x + y = 1) : a = x * a + y * a := calc a = 1 * a : by rw [one_mul] ... = (x + y) * a : by rw [h] ... = x * a + y * a : by rw [add_mul] /-- If x is in an Ioo, it can be expressed as a convex combination of the endpoints. -/ lemma convex.mem_Ioo {a b x : α} (h : a < b) : x ∈ Ioo a b ↔ ∃ (x_a x_b : α), 0 < x_a ∧ 0 < x_b ∧ x_a + x_b = 1 ∧ x_a * a + x_b * b = x := begin split, { rintros ⟨h_ax, h_bx⟩, by_cases hab : ¬a < b, { exfalso; exact hab h }, { refine ⟨(b-x) / (b-a), (x-a) / (b-a), _⟩, refine ⟨div_pos (by linarith) (by linarith), div_pos (by linarith) (by linarith),_,_⟩; { field_simp [show b - a ≠ 0, by linarith], ring } } }, { rw [mem_Ioo], rintros ⟨xa, xb, ⟨hxa, hxb, hxaxb, h₂⟩⟩, rw [←h₂], exact ⟨by nlinarith [convex.combo_self a hxaxb], by nlinarith [convex.combo_self b hxaxb]⟩ } end /-- If x is in an Ioc, it can be expressed as a convex combination of the endpoints. -/ lemma convex.mem_Ioc {a b x : α} (h : a < b) : x ∈ Ioc a b ↔ ∃ (x_a x_b : α), 0 ≤ x_a ∧ 0 < x_b ∧ x_a + x_b = 1 ∧ x_a * a + x_b * b = x := begin split, { rintros ⟨h_ax, h_bx⟩, by_cases h_x : x = b, { exact ⟨0, 1, by linarith, by linarith, by ring, by {rw [h_x], ring}⟩ }, { rcases (convex.mem_Ioo h).mp ⟨h_ax, lt_of_le_of_ne h_bx h_x⟩ with ⟨x_a, x_b, Ioo_case⟩, exact ⟨x_a, x_b, by linarith, Ioo_case.2⟩ } }, { rw [mem_Ioc], rintros ⟨xa, xb, ⟨hxa, hxb, hxaxb, h₂⟩⟩, rw [←h₂], exact ⟨by nlinarith [convex.combo_self a hxaxb], by nlinarith [convex.combo_self b hxaxb]⟩ } end /-- If x is in an Ico, it can be expressed as a convex combination of the endpoints. -/ lemma convex.mem_Ico {a b x : α} (h : a < b) : x ∈ Ico a b ↔ ∃ (x_a x_b : α), 0 < x_a ∧ 0 ≤ x_b ∧ x_a + x_b = 1 ∧ x_a * a + x_b * b = x := begin split, { rintros ⟨h_ax, h_bx⟩, by_cases h_x : x = a, { exact ⟨1, 0, by linarith, by linarith, by ring, by {rw [h_x], ring}⟩ }, { rcases (convex.mem_Ioo h).mp ⟨lt_of_le_of_ne h_ax (ne.symm h_x), h_bx⟩ with ⟨x_a, x_b, Ioo_case⟩, exact ⟨x_a, x_b, Ioo_case.1, by linarith, (Ioo_case.2).2⟩ } }, { rw [mem_Ico], rintros ⟨xa, xb, ⟨hxa, hxb, hxaxb, h₂⟩⟩, rw [←h₂], exact ⟨by nlinarith [convex.combo_self a hxaxb], by nlinarith [convex.combo_self b hxaxb]⟩ } end /-- If x is in an Icc, it can be expressed as a convex combination of the endpoints. -/ lemma convex.mem_Icc {a b x : α} (h : a ≤ b): x ∈ Icc a b ↔ ∃ (x_a x_b : α), 0 ≤ x_a ∧ 0 ≤ x_b ∧ x_a + x_b = 1 ∧ x_a * a + x_b * b = x := begin split, { intro x_in_I, rw [Icc, mem_set_of_eq] at x_in_I, rcases x_in_I with ⟨h_ax, h_bx⟩, by_cases hab' : a = b, { exact ⟨0, 1, le_refl 0, by linarith, by ring, by linarith⟩ }, change a ≠ b at hab', replace h : a < b, exact lt_of_le_of_ne h hab', by_cases h_x : x = a, { exact ⟨1, 0, by linarith, by linarith, by ring, by {rw [h_x], ring}⟩ }, { rcases (convex.mem_Ioc h).mp ⟨lt_of_le_of_ne h_ax (ne.symm h_x), h_bx⟩ with ⟨x_a, x_b, Ioo_case⟩, exact ⟨x_a, x_b, Ioo_case.1, by linarith, (Ioo_case.2).2⟩ } }, { rw [mem_Icc], rintros ⟨xa, xb, ⟨hxa, hxb, hxaxb, h₂⟩⟩, rw [←h₂], exact ⟨by nlinarith [convex.combo_self a hxaxb], by nlinarith [convex.combo_self b hxaxb]⟩ } end section submodule open submodule lemma submodule.convex (K : submodule ℝ E) : convex (↑K : set E) := by { repeat {intro}, refine add_mem _ (smul_mem _ _ _) (smul_mem _ _ _); assumption } lemma subspace.convex (K : subspace ℝ E) : convex (↑K : set E) := K.convex end submodule end sets section functions variables {β : Type*} [ordered_add_comm_monoid β] [ordered_semimodule ℝ β] local notation `[`x `, ` y `]` := segment x y /-! ### Convex functions -/ /-- Convexity of functions -/ def convex_on (s : set E) (f : E → β) : Prop := convex s ∧ ∀ ⦃x y : E⦄, x ∈ s → y ∈ s → ∀ ⦃a b : ℝ⦄, 0 ≤ a → 0 ≤ b → a + b = 1 → f (a • x + b • y) ≤ a • f x + b • f y /-- Concavity of functions -/ def concave_on (s : set E) (f : E → β) : Prop := convex s ∧ ∀ ⦃x y : E⦄, x ∈ s → y ∈ s → ∀ ⦃a b : ℝ⦄, 0 ≤ a → 0 ≤ b → a + b = 1 → a • f x + b • f y ≤ f (a • x + b • y) /-- A function f is concave iff -f is convex -/ @[simp] lemma neg_convex_on_iff {γ : Type*} [ordered_add_comm_group γ] [ordered_semimodule ℝ γ] (s : set E) (f : E → γ) : convex_on s (-f) ↔ concave_on s f := begin split, { rintros ⟨hconv, h⟩, refine ⟨hconv, _⟩, intros x y xs ys a b ha hb hab, specialize h xs ys ha hb hab, simp [neg_apply, neg_le, add_comm] at h, exact h }, { rintros ⟨hconv, h⟩, refine ⟨hconv, _⟩, intros x y xs ys a b ha hb hab, specialize h xs ys ha hb hab, simp [neg_apply, neg_le, add_comm, h] } end /-- A function f is concave iff -f is convex -/ @[simp] lemma neg_concave_on_iff {γ : Type*} [ordered_add_comm_group γ] [ordered_semimodule ℝ γ] (s : set E) (f : E → γ) : concave_on s (-f) ↔ convex_on s f:= by rw [← neg_convex_on_iff s (-f), neg_neg f] lemma convex_on_id {s : set ℝ} (hs : convex s) : convex_on s id := ⟨hs, by { intros, refl }⟩ lemma concave_on_id {s : set ℝ} (hs : convex s) : concave_on s id := ⟨hs, by { intros, refl }⟩ lemma convex_on_const (c : β) (hs : convex s) : convex_on s (λ x:E, c) := ⟨hs, by { intros, simp only [← add_smul, *, one_smul] }⟩ lemma concave_on_const (c : β) (hs : convex s) : concave_on s (λ x:E, c) := @convex_on_const _ _ _ _ (order_dual β) _ _ c hs variables {t : set E} lemma convex_on_iff_div {f : E → β} : convex_on s f ↔ convex s ∧ ∀ ⦃x y : E⦄, x ∈ s → y ∈ s → ∀ ⦃a b : ℝ⦄, 0 ≤ a → 0 ≤ b → 0 < a + b → f ((a/(a+b)) • x + (b/(a+b)) • y) ≤ (a/(a+b)) • f x + (b/(a+b)) • f y := and_congr iff.rfl ⟨begin intros h x y hx hy a b ha hb hab, apply h hx hy (div_nonneg ha $ le_of_lt hab) (div_nonneg hb $ le_of_lt hab), rw [←add_div], exact div_self (ne_of_gt hab) end, begin intros h x y hx hy a b ha hb hab, simpa [hab, zero_lt_one] using h hx hy ha hb, end⟩ lemma concave_on_iff_div {f : E → β} : concave_on s f ↔ convex s ∧ ∀ ⦃x y : E⦄, x ∈ s → y ∈ s → ∀ ⦃a b : ℝ⦄, 0 ≤ a → 0 ≤ b → 0 < a + b → (a/(a+b)) • f x + (b/(a+b)) • f y ≤ f ((a/(a+b)) • x + (b/(a+b)) • y) := @convex_on_iff_div _ _ _ _ (order_dual β) _ _ _ /-- For a function on a convex set in a linear ordered space, in order to prove that it is convex it suffices to verify the inequality `f (a • x + b • y) ≤ a • f x + b • f y` only for `x < y` and positive `a`, `b`. The main use case is `E = ℝ` however one can apply it, e.g., to `ℝ^n` with lexicographic order. -/ lemma linear_order.convex_on_of_lt {f : E → β} [linear_order E] (hs : convex s) (hf : ∀ ⦃x y : E⦄, x ∈ s → y ∈ s → x < y → ∀ ⦃a b : ℝ⦄, 0 < a → 0 < b → a + b = 1 → f (a • x + b • y) ≤ a • f x + b • f y) : convex_on s f := begin use hs, intros x y hx hy a b ha hb hab, wlog hxy : x<=y using [x y a b, y x b a], { exact le_total _ _ }, { cases eq_or_lt_of_le hxy with hxy hxy, by { subst y, rw [← add_smul, ← add_smul, hab, one_smul, one_smul] }, cases eq_or_lt_of_le ha with ha ha, by { subst a, rw [zero_add] at hab, subst b, simp }, cases eq_or_lt_of_le hb with hb hb, by { subst b, rw [add_zero] at hab, subst a, simp }, exact hf hx hy hxy ha hb hab } end /-- For a function on a convex set in a linear ordered space, in order to prove that it is concave it suffices to verify the inequality `a • f x + b • f y ≤ f (a • x + b • y)` only for `x < y` and positive `a`, `b`. The main use case is `E = ℝ` however one can apply it, e.g., to `ℝ^n` with lexicographic order. -/ lemma linear_order.concave_on_of_lt {f : E → β} [linear_order E] (hs : convex s) (hf : ∀ ⦃x y : E⦄, x ∈ s → y ∈ s → x < y → ∀ ⦃a b : ℝ⦄, 0 < a → 0 < b → a + b = 1 → a • f x + b • f y ≤ f (a • x + b • y)) : concave_on s f := @linear_order.convex_on_of_lt _ _ _ _ (order_dual β) _ _ f _ hs hf /-- For a function `f` defined on a convex subset `D` of `ℝ`, if for any three points `x<y<z` the slope of the secant line of `f` on `[x, y]` is less than or equal to the slope of the secant line of `f` on `[x, z]`, then `f` is convex on `D`. This way of proving convexity of a function is used in the proof of convexity of a function with a monotone derivative. -/ lemma convex_on_real_of_slope_mono_adjacent {s : set ℝ} (hs : convex s) {f : ℝ → ℝ} (hf : ∀ {x y z : ℝ}, x ∈ s → z ∈ s → x < y → y < z → (f y - f x) / (y - x) ≤ (f z - f y) / (z - y)) : convex_on s f := linear_order.convex_on_of_lt hs begin assume x z hx hz hxz a b ha hb hab, let y := a * x + b * z, have hxy : x < y, { rw [← one_mul x, ← hab, add_mul], exact add_lt_add_left ((mul_lt_mul_left hb).2 hxz) _ }, have hyz : y < z, { rw [← one_mul z, ← hab, add_mul], exact add_lt_add_right ((mul_lt_mul_left ha).2 hxz) _ }, have : (f y - f x) * (z - y) ≤ (f z - f y) * (y - x), from (div_le_div_iff (sub_pos.2 hxy) (sub_pos.2 hyz)).1 (hf hx hz hxy hyz), have A : z - y + (y - x) = z - x, by abel, have B : 0 < z - x, from sub_pos.2 (lt_trans hxy hyz), rw [sub_mul, sub_mul, sub_le_iff_le_add', ← add_sub_assoc, le_sub_iff_add_le, ← mul_add, A, ← le_div_iff B, add_div, mul_div_assoc, mul_div_assoc, mul_comm (f x), mul_comm (f z)] at this, rw [eq_comm, ← sub_eq_iff_eq_add] at hab; subst a, convert this; symmetry; simp only [div_eq_iff (ne_of_gt B), y]; ring end /-- For a function `f` defined on a subset `D` of `ℝ`, if `f` is convex on `D`, then for any three points `x<y<z`, the slope of the secant line of `f` on `[x, y]` is less than or equal to the slope of the secant line of `f` on `[x, z]`. -/ lemma convex_on.slope_mono_adjacent {s : set ℝ} {f : ℝ → ℝ} (hf : convex_on s f) {x y z : ℝ} (hx : x ∈ s) (hz : z ∈ s) (hxy : x < y) (hyz : y < z) : (f y - f x) / (y - x) ≤ (f z - f y) / (z - y) := begin have h₁ : 0 < y - x := by linarith, have h₂ : 0 < z - y := by linarith, have h₃ : 0 < z - x := by linarith, suffices : f y / (y - x) + f y / (z - y) ≤ f x / (y - x) + f z / (z - y), by { ring at this ⊢, linarith }, set a := (z - y) / (z - x), set b := (y - x) / (z - x), have heqz : a • x + b • z = y, by { field_simp, rw div_eq_iff; [ring, linarith], }, have key, from hf.2 hx hz (show 0 ≤ a, by apply div_nonneg; linarith) (show 0 ≤ b, by apply div_nonneg; linarith) (show a + b = 1, by { field_simp, rw div_eq_iff; [ring, linarith], }), rw heqz at key, replace key := mul_le_mul_of_nonneg_left key (le_of_lt h₃), field_simp [ne_of_gt h₁, ne_of_gt h₂, ne_of_gt h₃, mul_comm (z - x) _] at key ⊢, rw div_le_div_right, { linarith, }, { nlinarith, }, end /-- For a function `f` defined on a convex subset `D` of `ℝ`, `f` is convex on `D` iff for any three points `x<y<z` the slope of the secant line of `f` on `[x, y]` is less than or equal to the slope of the secant line of `f` on `[x, z]`. -/ lemma convex_on_real_iff_slope_mono_adjacent {s : set ℝ} (hs : convex s) {f : ℝ → ℝ} : convex_on s f ↔ (∀ {x y z : ℝ}, x ∈ s → z ∈ s → x < y → y < z → (f y - f x) / (y - x) ≤ (f z - f y) / (z - y)) := ⟨convex_on.slope_mono_adjacent, convex_on_real_of_slope_mono_adjacent hs⟩ /-- For a function `f` defined on a convex subset `D` of `ℝ`, if for any three points `x<y<z` the slope of the secant line of `f` on `[x, y]` is greater than or equal to the slope of the secant line of `f` on `[x, z]`, then `f` is concave on `D`. -/ lemma concave_on_real_of_slope_mono_adjacent {s : set ℝ} (hs : convex s) {f : ℝ → ℝ} (hf : ∀ {x y z : ℝ}, x ∈ s → z ∈ s → x < y → y < z → (f z - f y) / (z - y) ≤ (f y - f x) / (y - x)) : concave_on s f := begin rw [←neg_convex_on_iff], apply convex_on_real_of_slope_mono_adjacent hs, intros x y z xs zs xy yz, rw [←neg_le_neg_iff, ←neg_div, ←neg_div, neg_sub, neg_sub], simp only [hf xs zs xy yz, neg_sub_neg, pi.neg_apply], end /-- For a function `f` defined on a subset `D` of `ℝ`, if `f` is concave on `D`, then for any three points `x<y<z`, the slope of the secant line of `f` on `[x, y]` is greater than or equal to the slope of the secant line of `f` on `[x, z]`. -/ lemma concave_on.slope_mono_adjacent {s : set ℝ} {f : ℝ → ℝ} (hf : concave_on s f) {x y z : ℝ} (hx : x ∈ s) (hz : z ∈ s) (hxy : x < y) (hyz : y < z) : (f z - f y) / (z - y) ≤ (f y - f x) / (y - x) := begin rw [←neg_le_neg_iff, ←neg_div, ←neg_div, neg_sub, neg_sub], rw [←neg_sub_neg (f y), ←neg_sub_neg (f z)], simp_rw [←pi.neg_apply], rw [←neg_convex_on_iff] at hf, apply convex_on.slope_mono_adjacent hf; assumption, end /-- For a function `f` defined on a convex subset `D` of `ℝ`, `f` is concave on `D` iff for any three points `x<y<z` the slope of the secant line of `f` on `[x, y]` is greater than or equal to the slope of the secant line of `f` on `[x, z]`. -/ lemma concave_on_real_iff_slope_mono_adjacent {s : set ℝ} (hs : convex s) {f : ℝ → ℝ} : concave_on s f ↔ (∀ {x y z : ℝ}, x ∈ s → z ∈ s → x < y → y < z → (f z - f y) / (z - y) ≤ (f y - f x) / (y - x)) := ⟨concave_on.slope_mono_adjacent, concave_on_real_of_slope_mono_adjacent hs⟩ lemma convex_on.subset {f : E → β} (h_convex_on : convex_on t f) (h_subset : s ⊆ t) (h_convex : convex s) : convex_on s f := begin apply and.intro h_convex, intros x y hx hy, exact h_convex_on.2 (h_subset hx) (h_subset hy), end lemma concave_on.subset {f : E → β} (h_concave_on : concave_on t f) (h_subset : s ⊆ t) (h_convex : convex s) : concave_on s f := @convex_on.subset _ _ _ _ (order_dual β) _ _ t f h_concave_on h_subset h_convex lemma convex_on.add {f g : E → β} (hf : convex_on s f) (hg : convex_on s g) : convex_on s (λx, f x + g x) := begin apply and.intro hf.1, intros x y hx hy a b ha hb hab, calc f (a • x + b • y) + g (a • x + b • y) ≤ (a • f x + b • f y) + (a • g x + b • g y) : add_le_add (hf.2 hx hy ha hb hab) (hg.2 hx hy ha hb hab) ... = a • f x + a • g x + b • f y + b • g y : by abel ... = a • (f x + g x) + b • (f y + g y) : by simp [smul_add, add_assoc] end lemma concave_on.add {f g : E → β} (hf : concave_on s f) (hg : concave_on s g) : concave_on s (λx, f x + g x) := @convex_on.add _ _ _ _ (order_dual β) _ _ f g hf hg lemma convex_on.smul {f : E → β} {c : ℝ} (hc : 0 ≤ c) (hf : convex_on s f) : convex_on s (λx, c • f x) := begin apply and.intro hf.1, intros x y hx hy a b ha hb hab, calc c • f (a • x + b • y) ≤ c • (a • f x + b • f y) : smul_le_smul_of_nonneg (hf.2 hx hy ha hb hab) hc ... = a • (c • f x) + b • (c • f y) : by simp only [smul_add, smul_comm] end lemma concave_on.smul {f : E → β} {c : ℝ} (hc : 0 ≤ c) (hf : concave_on s f) : concave_on s (λx, c • f x) := @convex_on.smul _ _ _ _ (order_dual β) _ _ f c hc hf /-- A convex function on a segment is upper-bounded by the max of its endpoints. -/ lemma convex_on.le_on_segment' {γ : Type*} [decidable_linear_ordered_add_comm_group γ] [ordered_semimodule ℝ γ] {f : E → γ} {x y : E} {a b : ℝ} (hf : convex_on s f) (hx : x ∈ s) (hy : y ∈ s) (ha : 0 ≤ a) (hb : 0 ≤ b) (hab : a + b = 1) : f (a • x + b • y) ≤ max (f x) (f y) := calc f (a • x + b • y) ≤ a • f x + b • f y : hf.2 hx hy ha hb hab ... ≤ a • max (f x) (f y) + b • max (f x) (f y) : add_le_add (smul_le_smul_of_nonneg (le_max_left _ _) ha) (smul_le_smul_of_nonneg (le_max_right _ _) hb) ... ≤ max (f x) (f y) : by rw [←add_smul, hab, one_smul] /-- A concave function on a segment is lower-bounded by the min of its endpoints. -/ lemma concave_on.le_on_segment' {γ : Type*} [decidable_linear_ordered_add_comm_group γ] [ordered_semimodule ℝ γ] {f : E → γ} {x y : E} {a b : ℝ} (hf : concave_on s f) (hx : x ∈ s) (hy : y ∈ s) (ha : 0 ≤ a) (hb : 0 ≤ b) (hab : a + b = 1) : min (f x) (f y) ≤ f (a • x + b • y) := @convex_on.le_on_segment' _ _ _ _ (order_dual γ) _ _ f x y a b hf hx hy ha hb hab /-- A convex function on a segment is upper-bounded by the max of its endpoints. -/ lemma convex_on.le_on_segment {γ : Type*} [decidable_linear_ordered_add_comm_group γ] [ordered_semimodule ℝ γ] {f : E → γ} (hf : convex_on s f) {x y z : E} (hx : x ∈ s) (hy : y ∈ s) (hz : z ∈ [x, y]) : f z ≤ max (f x) (f y) := let ⟨a, b, ha, hb, hab, hz⟩ := hz in hz ▸ hf.le_on_segment' hx hy ha hb hab /-- A concave function on a segment is lower-bounded by the min of its endpoints. -/ lemma concave_on.le_on_segment {γ : Type*} [decidable_linear_ordered_add_comm_group γ] [ordered_semimodule ℝ γ] {f : E → γ} (hf : concave_on s f) {x y z : E} (hx : x ∈ s) (hy : y ∈ s) (hz : z ∈ [x, y]) : min (f x) (f y) ≤ f z := @convex_on.le_on_segment _ _ _ _ (order_dual γ) _ _ f hf x y z hx hy hz lemma convex_on.convex_le {f : E → β} (hf : convex_on s f) (r : β) : convex {x ∈ s | f x ≤ r} := convex_iff_segment_subset.2 $ λ x y hx hy z hz, begin refine ⟨hf.1.segment_subset hx.1 hy.1 hz,_⟩, rcases hz with ⟨za,zb,hza,hzb,hzazb,H⟩, rw ←H, calc f (za • x + zb • y) ≤ za • (f x) + zb • (f y) : hf.2 hx.1 hy.1 hza hzb hzazb ... ≤ za • r + zb • r : add_le_add (smul_le_smul_of_nonneg hx.2 hza) (smul_le_smul_of_nonneg hy.2 hzb) ... ≤ r : by simp [←add_smul, hzazb] end lemma concave_on.concave_le {f : E → β} (hf : concave_on s f) (r : β) : convex {x ∈ s | r ≤ f x} := @convex_on.convex_le _ _ _ _ (order_dual β) _ _ f hf r lemma convex_on.convex_lt {γ : Type*} [ordered_cancel_add_comm_monoid γ] [ordered_semimodule ℝ γ] {f : E → γ} (hf : convex_on s f) (r : γ) : convex {x ∈ s | f x < r} := begin intros a b as bs xa xb hxa hxb hxaxb, refine ⟨hf.1 as.1 bs.1 hxa hxb hxaxb,_⟩, dsimp, by_cases H : xa = 0, { have H' : xb = 1 := by rwa [H, zero_add] at hxaxb, rw [H, H', zero_smul, one_smul, zero_add], exact bs.2 }, { calc f (xa • a + xb • b) ≤ xa • (f a) + xb • (f b) : hf.2 as.1 bs.1 hxa hxb hxaxb ... < xa • r + xb • (f b) : (add_lt_add_iff_right (xb • (f b))).mpr (smul_lt_smul_of_pos as.2 (lt_of_le_of_ne hxa (ne.symm H))) ... ≤ xa • r + xb • r : (add_le_add_iff_left (xa • r)).mpr (smul_le_smul_of_nonneg (le_of_lt bs.2) hxb) ... = r : by simp only [←add_smul, hxaxb, one_smul] } end lemma concave_on.convex_lt {γ : Type*} [ordered_cancel_add_comm_monoid γ] [ordered_semimodule ℝ γ] {f : E → γ} (hf : concave_on s f) (r : γ) : convex {x ∈ s | r < f x} := @convex_on.convex_lt _ _ _ _ (order_dual γ) _ _ f hf r lemma convex_on.convex_epigraph {γ : Type*} [ordered_add_comm_group γ] [ordered_semimodule ℝ γ] {f : E → γ} (hf : convex_on s f) : convex {p : E × γ | p.1 ∈ s ∧ f p.1 ≤ p.2} := begin rintros ⟨x, r⟩ ⟨y, t⟩ ⟨hx, hr⟩ ⟨hy, ht⟩ a b ha hb hab, refine ⟨hf.1 hx hy ha hb hab, _⟩, calc f (a • x + b • y) ≤ a • f x + b • f y : hf.2 hx hy ha hb hab ... ≤ a • r + b • t : add_le_add (smul_le_smul_of_nonneg hr ha) (smul_le_smul_of_nonneg ht hb) end lemma concave_on.convex_hypograph {γ : Type*} [ordered_add_comm_group γ] [ordered_semimodule ℝ γ] {f : E → γ} (hf : concave_on s f) : convex {p : E × γ | p.1 ∈ s ∧ p.2 ≤ f p.1} := @convex_on.convex_epigraph _ _ _ _ (order_dual γ) _ _ f hf lemma convex_on_iff_convex_epigraph {γ : Type*} [ordered_add_comm_group γ] [ordered_semimodule ℝ γ] {f : E → γ} : convex_on s f ↔ convex {p : E × γ | p.1 ∈ s ∧ f p.1 ≤ p.2} := begin refine ⟨convex_on.convex_epigraph, λ h, ⟨_, _⟩⟩, { assume x y hx hy a b ha hb hab, exact (@h (x, f x) (y, f y) ⟨hx, le_refl _⟩ ⟨hy, le_refl _⟩ a b ha hb hab).1 }, { assume x y hx hy a b ha hb hab, exact (@h (x, f x) (y, f y) ⟨hx, le_refl _⟩ ⟨hy, le_refl _⟩ a b ha hb hab).2 } end lemma concave_on_iff_convex_hypograph {γ : Type*} [ordered_add_comm_group γ] [ordered_semimodule ℝ γ] {f : E → γ} : concave_on s f ↔ convex {p : E × γ | p.1 ∈ s ∧ p.2 ≤ f p.1} := @convex_on_iff_convex_epigraph _ _ _ _ (order_dual γ) _ _ f /-- If a function is convex on s, it remains convex when precomposed by an affine map -/ lemma convex_on.comp_affine_map {f : F → β} (g : affine_map ℝ E F) {s : set F} (hf : convex_on s f) : convex_on (g ⁻¹' s) (f ∘ g) := begin refine ⟨hf.1.affine_preimage _,_⟩, intros x y xs ys a b ha hb hab, calc (f ∘ g) (a • x + b • y) = f (g (a • x + b • y)) : rfl ... = f (a • (g x) + b • (g y)) : by rw [convex.combo_affine_apply hab] ... ≤ a • f (g x) + b • f (g y) : hf.2 xs ys ha hb hab ... = a • (f ∘ g) x + b • (f ∘ g) y : rfl end /-- If a function is concave on s, it remains concave when precomposed by an affine map -/ lemma concave_on.comp_affine_map {f : F → β} (g : affine_map ℝ E F) {s : set F} (hf : concave_on s f) : concave_on (g ⁻¹' s) (f ∘ g) := @convex_on.comp_affine_map _ _ _ _ _ _ (order_dual β) _ _ f g s hf /-- If g is convex on s, so is (g ∘ f) on f ⁻¹' s for a linear f. -/ lemma convex_on.comp_linear_map {g : F → β} {s : set F} (hg : convex_on s g) (f : E →ₗ[ℝ] F) : convex_on (f ⁻¹' s) (g ∘ f) := hg.comp_affine_map f.to_affine_map /-- If g is concave on s, so is (g ∘ f) on f ⁻¹' s for a linear f. -/ lemma concave_on.comp_linear_map {g : F → β} {s : set F} (hg : concave_on s g) (f : E →ₗ[ℝ] F) : concave_on (f ⁻¹' s) (g ∘ f) := hg.comp_affine_map f.to_affine_map /-- If a function is convex on s, it remains convex after a translation. -/ lemma convex_on.translate_right {f : E → β} {s : set E} {a : E} (hf : convex_on s f) : convex_on ((λ z, a + z) ⁻¹' s) (f ∘ (λ z, a + z)) := hf.comp_affine_map $ affine_map.const ℝ E a +ᵥ affine_map.id ℝ E /-- If a function is concave on s, it remains concave after a translation. -/ lemma concave_on.translate_right {f : E → β} {s : set E} {a : E} (hf : concave_on s f) : concave_on ((λ z, a + z) ⁻¹' s) (f ∘ (λ z, a + z)) := hf.comp_affine_map $ affine_map.const ℝ E a +ᵥ affine_map.id ℝ E /-- If a function is convex on s, it remains convex after a translation. -/ lemma convex_on.translate_left {f : E → β} {s : set E} {a : E} (hf : convex_on s f) : convex_on ((λ z, a + z) ⁻¹' s) (f ∘ (λ z, z + a)) := by simpa only [add_comm] using hf.translate_right /-- If a function is concave on s, it remains concave after a translation. -/ lemma concave_on.translate_left {f : E → β} {s : set E} {a : E} (hf : concave_on s f) : concave_on ((λ z, a + z) ⁻¹' s) (f ∘ (λ z, z + a)) := by simpa only [add_comm] using hf.translate_right end functions section center_mass /-- Center mass of a finite collection of points with prescribed weights. Note that we require neither `0 ≤ w i` nor `∑ w = 1`. -/ noncomputable def finset.center_mass (t : finset ι) (w : ι → ℝ) (z : ι → E) : E := (∑ i in t, w i)⁻¹ • (∑ i in t, w i • z i) variables (i j : ι) (c : ℝ) (t : finset ι) (w : ι → ℝ) (z : ι → E) open finset lemma finset.center_mass_empty : (∅ : finset ι).center_mass w z = 0 := by simp only [center_mass, sum_empty, smul_zero] lemma finset.center_mass_pair (hne : i ≠ j) : ({i, j} : finset ι).center_mass w z = (w i / (w i + w j)) • z i + (w j / (w i + w j)) • z j := by simp only [center_mass, sum_pair hne, smul_add, (mul_smul _ _ _).symm, div_eq_inv_mul] variable {w} lemma finset.center_mass_insert (ha : i ∉ t) (hw : ∑ j in t, w j ≠ 0) : (insert i t).center_mass w z = (w i / (w i + ∑ j in t, w j)) • z i + ((∑ j in t, w j) / (w i + ∑ j in t, w j)) • t.center_mass w z := begin simp only [center_mass, sum_insert ha, smul_add, (mul_smul _ _ _).symm], congr' 2, { apply mul_comm }, { rw [div_mul_eq_mul_div, mul_inv_cancel hw, one_div] } end lemma finset.center_mass_singleton (hw : w i ≠ 0) : ({i} : finset ι).center_mass w z = z i := by rw [center_mass, sum_singleton, sum_singleton, ← mul_smul, inv_mul_cancel hw, one_smul] lemma finset.center_mass_eq_of_sum_1 (hw : ∑ i in t, w i = 1) : t.center_mass w z = ∑ i in t, w i • z i := by simp only [finset.center_mass, hw, inv_one, one_smul] lemma finset.center_mass_smul : t.center_mass w (λ i, c • z i) = c • t.center_mass w z := by simp only [finset.center_mass, finset.smul_sum, (mul_smul _ _ _).symm, mul_comm c, mul_assoc] /-- A convex combination of two centers of mass is a center of mass as well. This version deals with two different index types. -/ lemma finset.center_mass_segment' (s : finset ι) (t : finset ι') (ws : ι → ℝ) (zs : ι → E) (wt : ι' → ℝ) (zt : ι' → E) (hws : ∑ i in s, ws i = 1) (hwt : ∑ i in t, wt i = 1) (a b : ℝ) (hab : a + b = 1): a • s.center_mass ws zs + b • t.center_mass wt zt = (s.image sum.inl ∪ t.image sum.inr).center_mass (sum.elim (λ i, a * ws i) (λ j, b * wt j)) (sum.elim zs zt) := begin rw [s.center_mass_eq_of_sum_1 _ hws, t.center_mass_eq_of_sum_1 _ hwt, smul_sum, smul_sum, ← finset.sum_sum_elim, finset.center_mass_eq_of_sum_1], { congr' with ⟨⟩; simp only [sum.elim_inl, sum.elim_inr, mul_smul] }, { rw [sum_sum_elim, ← mul_sum, ← mul_sum, hws, hwt, mul_one, mul_one, hab] } end /-- A convex combination of two centers of mass is a center of mass as well. This version works if two centers of mass share the set of original points. -/ lemma finset.center_mass_segment (s : finset ι) (w₁ w₂ : ι → ℝ) (z : ι → E) (hw₁ : ∑ i in s, w₁ i = 1) (hw₂ : ∑ i in s, w₂ i = 1) (a b : ℝ) (hab : a + b = 1): a • s.center_mass w₁ z + b • s.center_mass w₂ z = s.center_mass (λ i, a * w₁ i + b * w₂ i) z := have hw : ∑ i in s, (a * w₁ i + b * w₂ i) = 1, by simp only [mul_sum.symm, sum_add_distrib, mul_one, *], by simp only [finset.center_mass_eq_of_sum_1, smul_sum, sum_add_distrib, add_smul, mul_smul, *] lemma finset.center_mass_ite_eq (hi : i ∈ t) : t.center_mass (λ j, if (i = j) then 1 else 0) z = z i := begin rw [finset.center_mass_eq_of_sum_1], transitivity ∑ j in t, if (i = j) then z i else 0, { congr' with i, split_ifs, exacts [h ▸ one_smul _ _, zero_smul _ _] }, { rw [sum_ite_eq, if_pos hi] }, { rw [sum_ite_eq, if_pos hi] } end variables {t w} lemma finset.center_mass_subset {t' : finset ι} (ht : t ⊆ t') (h : ∀ i ∈ t', i ∉ t → w i = 0) : t.center_mass w z = t'.center_mass w z := begin rw [center_mass, sum_subset ht h, smul_sum, center_mass, smul_sum], apply sum_subset ht, assume i hit' hit, rw [h i hit' hit, zero_smul, smul_zero] end lemma finset.center_mass_filter_ne_zero : (t.filter (λ i, w i ≠ 0)).center_mass w z = t.center_mass w z := finset.center_mass_subset z (filter_subset _) $ λ i hit hit', by simpa only [hit, mem_filter, true_and, ne.def, not_not] using hit' variable {z} /-- Center mass of a finite subset of a convex set belongs to the set provided that all weights are non-negative, and the total weight is positive. -/ lemma convex.center_mass_mem (hs : convex s) : (∀ i ∈ t, 0 ≤ w i) → (0 < ∑ i in t, w i) → (∀ i ∈ t, z i ∈ s) → t.center_mass w z ∈ s := begin induction t using finset.induction with i t hi ht, { simp [lt_irrefl] }, intros h₀ hpos hmem, have zi : z i ∈ s, from hmem _ (mem_insert_self _ _), have hs₀ : ∀ j ∈ t, 0 ≤ w j, from λ j hj, h₀ j $ mem_insert_of_mem hj, rw [sum_insert hi] at hpos, by_cases hsum_t : ∑ j in t, w j = 0, { have ws : ∀ j ∈ t, w j = 0, from (sum_eq_zero_iff_of_nonneg hs₀).1 hsum_t, have wz : ∑ j in t, w j • z j = 0, from sum_eq_zero (λ i hi, by simp [ws i hi]), simp only [center_mass, sum_insert hi, wz, hsum_t, add_zero], simp only [hsum_t, add_zero] at hpos, rw [← mul_smul, inv_mul_cancel (ne_of_gt hpos), one_smul], exact zi }, { rw [finset.center_mass_insert _ _ _ hi hsum_t], refine convex_iff_div.1 hs zi (ht hs₀ _ _) _ (sum_nonneg hs₀) hpos, { exact lt_of_le_of_ne (sum_nonneg hs₀) (ne.symm hsum_t) }, { intros j hj, exact hmem j (mem_insert_of_mem hj) }, { exact h₀ _ (mem_insert_self _ _) } } end lemma convex.sum_mem (hs : convex s) (h₀ : ∀ i ∈ t, 0 ≤ w i) (h₁ : ∑ i in t, w i = 1) (hz : ∀ i ∈ t, z i ∈ s) : ∑ i in t, w i • z i ∈ s := by simpa only [h₁, center_mass, inv_one, one_smul] using hs.center_mass_mem h₀ (h₁.symm ▸ zero_lt_one) hz lemma convex_iff_sum_mem : convex s ↔ (∀ (t : finset E) (w : E → ℝ), (∀ i ∈ t, 0 ≤ w i) → ∑ i in t, w i = 1 → (∀ x ∈ t, x ∈ s) → ∑ x in t, w x • x ∈ s ) := begin refine ⟨λ hs t w hw₀ hw₁ hts, hs.sum_mem hw₀ hw₁ hts, _⟩, intros h x y hx hy a b ha hb hab, by_cases h_cases: x = y, { rw [h_cases, ←add_smul, hab, one_smul], exact hy }, { convert h {x, y} (λ z, if z = y then b else a) _ _ _, { simp only [sum_pair h_cases, if_neg h_cases, if_pos rfl] }, { simp_intros i hi, cases hi; subst i; simp [ha, hb, if_neg h_cases] }, { simp only [sum_pair h_cases, if_neg h_cases, if_pos rfl, hab] }, { simp_intros i hi, cases hi; subst i; simp [hx, hy, if_neg h_cases] } } end /-- Jensen's inequality, `finset.center_mass` version. -/ lemma convex_on.map_center_mass_le {f : E → ℝ} (hf : convex_on s f) (h₀ : ∀ i ∈ t, 0 ≤ w i) (hpos : 0 < ∑ i in t, w i) (hmem : ∀ i ∈ t, z i ∈ s) : f (t.center_mass w z) ≤ t.center_mass w (f ∘ z) := begin have hmem' : ∀ i ∈ t, (z i, (f ∘ z) i) ∈ {p : E × ℝ | p.1 ∈ s ∧ f p.1 ≤ p.2}, from λ i hi, ⟨hmem i hi, le_refl _⟩, convert (hf.convex_epigraph.center_mass_mem h₀ hpos hmem').2; simp only [center_mass, function.comp, prod.smul_fst, prod.fst_sum, prod.smul_snd, prod.snd_sum] end /-- Jensen's inequality, `finset.sum` version. -/ lemma convex_on.map_sum_le {f : E → ℝ} (hf : convex_on s f) (h₀ : ∀ i ∈ t, 0 ≤ w i) (h₁ : ∑ i in t, w i = 1) (hmem : ∀ i ∈ t, z i ∈ s) : f (∑ i in t, w i • z i) ≤ ∑ i in t, w i * (f (z i)) := by simpa only [center_mass, h₁, inv_one, one_smul] using hf.map_center_mass_le h₀ (h₁.symm ▸ zero_lt_one) hmem /-- If a function `f` is convex on `s` takes value `y` at the center mass of some points `z i ∈ s`, then for some `i` we have `y ≤ f (z i)`. -/ lemma convex_on.exists_ge_of_center_mass {f : E → ℝ} (h : convex_on s f) (hw₀ : ∀ i ∈ t, 0 ≤ w i) (hws : 0 < ∑ i in t, w i) (hz : ∀ i ∈ t, z i ∈ s) : ∃ i ∈ t, f (t.center_mass w z) ≤ f (z i) := begin set y := t.center_mass w z, have : f y ≤ t.center_mass w (f ∘ z) := h.map_center_mass_le hw₀ hws hz, rw ← sum_filter_ne_zero at hws, rw [← finset.center_mass_filter_ne_zero (f ∘ z), center_mass, smul_eq_mul, ← div_eq_inv_mul, le_div_iff hws, mul_sum] at this, replace : ∃ i ∈ t.filter (λ i, w i ≠ 0), f y * w i ≤ w i • (f ∘ z) i := exists_le_of_sum_le (nonempty_of_sum_ne_zero (ne_of_gt hws)) this, rcases this with ⟨i, hi, H⟩, rw [mem_filter] at hi, use [i, hi.1], simp only [smul_eq_mul, mul_comm (w i)] at H, refine (mul_le_mul_right _).1 H, exact lt_of_le_of_ne (hw₀ i hi.1) hi.2.symm end end center_mass section convex_hull variable {t : set E} /-- Convex hull of a set `s` is the minimal convex set that includes `s` -/ def convex_hull (s : set E) : set E := ⋂ (t : set E) (hst : s ⊆ t) (ht : convex t), t variable (s) lemma subset_convex_hull : s ⊆ convex_hull s := set.subset_Inter $ λ t, set.subset_Inter $ λ hst, set.subset_Inter $ λ ht, hst lemma convex_convex_hull : convex (convex_hull s) := convex_Inter $ λ t, convex_Inter $ λ ht, convex_Inter id variable {s} lemma convex_hull_min (hst : s ⊆ t) (ht : convex t) : convex_hull s ⊆ t := set.Inter_subset_of_subset t $ set.Inter_subset_of_subset hst $ set.Inter_subset _ ht lemma convex_hull_mono (hst : s ⊆ t) : convex_hull s ⊆ convex_hull t := convex_hull_min (set.subset.trans hst $ subset_convex_hull t) (convex_convex_hull t) lemma convex.convex_hull_eq {s : set E} (hs : convex s) : convex_hull s = s := set.subset.antisymm (convex_hull_min (set.subset.refl _) hs) (subset_convex_hull s) @[simp] lemma convex_hull_singleton {x : E} : convex_hull ({x} : set E) = {x} := (convex_singleton x).convex_hull_eq lemma is_linear_map.image_convex_hull {f : E → F} (hf : is_linear_map ℝ f) : f '' (convex_hull s) = convex_hull (f '' s) := begin refine set.subset.antisymm _ _, { rw [set.image_subset_iff], exact convex_hull_min (set.image_subset_iff.1 $ subset_convex_hull $ f '' s) ((convex_convex_hull (f '' s)).is_linear_preimage hf) }, { exact convex_hull_min (set.image_subset _ $ subset_convex_hull s) ((convex_convex_hull s).is_linear_image hf) } end lemma linear_map.image_convex_hull (f : E →ₗ[ℝ] F) : f '' (convex_hull s) = convex_hull (f '' s) := f.is_linear.image_convex_hull lemma finset.center_mass_mem_convex_hull (t : finset ι) {w : ι → ℝ} (hw₀ : ∀ i ∈ t, 0 ≤ w i) (hws : 0 < ∑ i in t, w i) {z : ι → E} (hz : ∀ i ∈ t, z i ∈ s) : t.center_mass w z ∈ convex_hull s := (convex_convex_hull s).center_mass_mem hw₀ hws (λ i hi, subset_convex_hull s $ hz i hi) -- TODO : Do we need other versions of the next lemma? /-- Convex hull of `s` is equal to the set of all centers of masses of `finset`s `t`, `z '' t ⊆ s`. This version allows finsets in any type in any universe. -/ lemma convex_hull_eq (s : set E) : convex_hull s = {x : E | ∃ (ι : Type u') (t : finset ι) (w : ι → ℝ) (z : ι → E) (hw₀ : ∀ i ∈ t, 0 ≤ w i) (hw₁ : ∑ i in t, w i = 1) (hz : ∀ i ∈ t, z i ∈ s) , t.center_mass w z = x} := begin refine subset.antisymm (convex_hull_min _ _) _, { intros x hx, use [punit, {punit.star}, λ _, 1, λ _, x, λ _ _, zero_le_one, finset.sum_singleton, λ _ _, hx], simp only [finset.center_mass, finset.sum_singleton, inv_one, one_smul] }, { rintros x y ⟨ι, sx, wx, zx, hwx₀, hwx₁, hzx, rfl⟩ ⟨ι', sy, wy, zy, hwy₀, hwy₁, hzy, rfl⟩ a b ha hb hab, rw [finset.center_mass_segment' _ _ _ _ _ _ hwx₁ hwy₁ _ _ hab], refine ⟨_, _, _, _, _, _, _, rfl⟩, { rintros i hi, rw [finset.mem_union, finset.mem_image, finset.mem_image] at hi, rcases hi with ⟨j, hj, rfl⟩|⟨j, hj, rfl⟩; simp only [sum.elim_inl, sum.elim_inr]; apply_rules [mul_nonneg, hwx₀, hwy₀] }, { simp [finset.sum_sum_elim, finset.mul_sum.symm, *] }, { intros i hi, rw [finset.mem_union, finset.mem_image, finset.mem_image] at hi, rcases hi with ⟨j, hj, rfl⟩|⟨j, hj, rfl⟩; simp only [sum.elim_inl, sum.elim_inr]; apply_rules [hzx, hzy] } }, { rintros _ ⟨ι, t, w, z, hw₀, hw₁, hz, rfl⟩, exact t.center_mass_mem_convex_hull hw₀ (hw₁.symm ▸ zero_lt_one) hz } end /-- Maximum principle for convex functions. If a function `f` is convex on the convex hull of `s`, then `f` can't have a maximum on `convex_hull s` outside of `s`. -/ lemma convex_on.exists_ge_of_mem_convex_hull {f : E → ℝ} (hf : convex_on (convex_hull s) f) {x} (hx : x ∈ convex_hull s) : ∃ y ∈ s, f x ≤ f y := begin rw convex_hull_eq at hx, rcases hx with ⟨α, t, w, z, hw₀, hw₁, hz, rfl⟩, rcases hf.exists_ge_of_center_mass hw₀ (hw₁.symm ▸ zero_lt_one) (λ i hi, subset_convex_hull s (hz i hi)) with ⟨i, hit, Hi⟩, exact ⟨z i, hz i hit, Hi⟩ end lemma finset.convex_hull_eq (s : finset E) : convex_hull ↑s = {x : E | ∃ (w : E → ℝ) (hw₀ : ∀ y ∈ s, 0 ≤ w y) (hw₁ : ∑ y in s, w y = 1), s.center_mass w id = x} := begin refine subset.antisymm (convex_hull_min _ _) _, { intros x hx, rw [finset.mem_coe] at hx, refine ⟨_, _, _, finset.center_mass_ite_eq _ _ _ hx⟩, { intros, split_ifs, exacts [zero_le_one, le_refl 0] }, { rw [finset.sum_ite_eq, if_pos hx] } }, { rintros x y ⟨wx, hwx₀, hwx₁, rfl⟩ ⟨wy, hwy₀, hwy₁, rfl⟩ a b ha hb hab, rw [finset.center_mass_segment _ _ _ _ hwx₁ hwy₁ _ _ hab], refine ⟨_, _, _, rfl⟩, { rintros i hi, apply_rules [add_nonneg, mul_nonneg, hwx₀, hwy₀], }, { simp only [finset.sum_add_distrib, finset.mul_sum.symm, mul_one, *] } }, { rintros _ ⟨w, hw₀, hw₁, rfl⟩, exact s.center_mass_mem_convex_hull (λ x hx, hw₀ _ hx) (hw₁.symm ▸ zero_lt_one) (λ x hx, hx) } end lemma set.finite.convex_hull_eq {s : set E} (hs : finite s) : convex_hull s = {x : E | ∃ (w : E → ℝ) (hw₀ : ∀ y ∈ s, 0 ≤ w y) (hw₁ : ∑ y in hs.to_finset, w y = 1), hs.to_finset.center_mass w id = x} := by simpa only [set.finite.coe_to_finset, set.finite.mem_to_finset, exists_prop] using hs.to_finset.convex_hull_eq lemma convex_hull_eq_union_convex_hull_finite_subsets (s : set E) : convex_hull s = ⋃ (t : finset E) (w : ↑t ⊆ s), convex_hull ↑t := begin refine subset.antisymm _ _, { rw [convex_hull_eq.{u}], rintros x ⟨ι, t, w, z, hw₀, hw₁, hz, rfl⟩, simp only [mem_Union], refine ⟨t.image z, _, _⟩, { rw [finset.coe_image, image_subset_iff], exact hz }, { apply t.center_mass_mem_convex_hull hw₀, { simp only [hw₁, zero_lt_one] }, { exact λ i hi, finset.mem_coe.2 (finset.mem_image_of_mem _ hi) } } }, { exact Union_subset (λ i, Union_subset convex_hull_mono), }, end lemma is_linear_map.convex_hull_image {f : E → F} (hf : is_linear_map ℝ f) (s : set E) : convex_hull (f '' s) = f '' convex_hull s := set.subset.antisymm (convex_hull_min (image_subset _ (subset_convex_hull s)) $ (convex_convex_hull s).is_linear_image hf) (image_subset_iff.2 $ convex_hull_min (image_subset_iff.1 $ subset_convex_hull _) ((convex_convex_hull _).is_linear_preimage hf)) lemma linear_map.convex_hull_image (f : E →ₗ[ℝ] F) (s : set E) : convex_hull (f '' s) = f '' convex_hull s := f.is_linear.convex_hull_image s end convex_hull /-! ### Simplex -/ section simplex variables (ι) [fintype ι] {f : ι → ℝ} /-- Standard simplex in the space of functions `ι → ℝ` is the set of vectors with non-negative coordinates with total sum `1`. -/ def std_simplex (ι : Type*) [fintype ι] : set (ι → ℝ) := { f | (∀ x, 0 ≤ f x) ∧ ∑ x, f x = 1 } lemma std_simplex_eq_inter : std_simplex ι = (⋂ x, {f | 0 ≤ f x}) ∩ {f | ∑ x, f x = 1} := by { ext f, simp only [std_simplex, set.mem_inter_eq, set.mem_Inter, set.mem_set_of_eq] } lemma convex_std_simplex : convex (std_simplex ι) := begin refine λ f g hf hg a b ha hb hab, ⟨λ x, _, _⟩, { apply_rules [add_nonneg, mul_nonneg, hf.1, hg.1] }, { erw [finset.sum_add_distrib, ← finset.smul_sum, ← finset.smul_sum, hf.2, hg.2, smul_eq_mul, smul_eq_mul, mul_one, mul_one], exact hab } end variable {ι} lemma ite_eq_mem_std_simplex (i : ι) : (λ j, ite (i = j) (1:ℝ) 0) ∈ std_simplex ι := ⟨λ j, by simp only; split_ifs; norm_num, by rw [finset.sum_ite_eq, if_pos (finset.mem_univ _)] ⟩ /-- `std_simplex ι` is the convex hull of the canonical basis in `ι → ℝ`. -/ lemma convex_hull_basis_eq_std_simplex : convex_hull (range $ λ(i j:ι), if i = j then (1:ℝ) else 0) = std_simplex ι := begin refine subset.antisymm (convex_hull_min _ (convex_std_simplex ι)) _, { rintros _ ⟨i, rfl⟩, exact ite_eq_mem_std_simplex i }, { rintros w ⟨hw₀, hw₁⟩, rw [pi_eq_sum_univ w, ← finset.univ.center_mass_eq_of_sum_1 _ hw₁], exact finset.univ.center_mass_mem_convex_hull (λ i hi, hw₀ i) (hw₁.symm ▸ zero_lt_one) (λ i hi, mem_range_self i) } end variable {ι} /-- Convex hull of a finite set is the image of the standard simplex in `s → ℝ` under the linear map sending each function `w` to `∑ x in s, w x • x`. Since we have no sums over finite sets, we use sum over `@finset.univ _ hs.fintype`. The map is defined in terms of operations on `(s → ℝ) →ₗ[ℝ] ℝ` so that later we will not need to prove that this map is linear. -/ lemma set.finite.convex_hull_eq_image {s : set E} (hs : finite s) : convex_hull s = by haveI := hs.fintype; exact (⇑(∑ x : s, (@linear_map.proj ℝ s _ (λ i, ℝ) _ _ x).smul_right x.1)) '' (std_simplex s) := begin rw [← convex_hull_basis_eq_std_simplex, ← linear_map.convex_hull_image, ← set.range_comp, (∘)], apply congr_arg, convert subtype.range_coe.symm, ext x, simp [linear_map.sum_apply, ite_smul, finset.filter_eq] end /-- All values of a function `f ∈ std_simplex ι` belong to `[0, 1]`. -/ lemma mem_Icc_of_mem_std_simplex (hf : f ∈ std_simplex ι) (x) : f x ∈ I := ⟨hf.1 x, hf.2 ▸ finset.single_le_sum (λ y hy, hf.1 y) (finset.mem_univ x)⟩ end simplex
f9c2729bdb027c1cd5e4f7b70f39115149279eb4
271e26e338b0c14544a889c31c30b39c989f2e0f
/stage0/src/Init/LeanExt.lean
79c201f02b981ccea9428fb77d5e61839625fac7
[ "Apache-2.0" ]
permissive
dgorokho/lean4
805f99b0b60c545b64ac34ab8237a8504f89d7d4
e949a052bad59b1c7b54a82d24d516a656487d8a
refs/heads/master
1,607,061,363,851
1,578,006,086,000
1,578,006,086,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
3,298
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude import Init.Data.String.Basic import Init.Data.UInt namespace Lean /- Basic Lean types used to implement basic extensions. Note that this file is part of the Lean `Init` library instead of `Lean` actual implementation. The idea is to allow users to implement simple parsers, macros and tactics without importing the whole `Lean` module. It also allow us to use extensions to develop the `Init` library. -/ /- Hierarchical names -/ inductive Name | anonymous : Name | str : Name → String → USize → Name | num : Name → Nat → USize → Name inductive ParserKind | leading | trailing /- Small DSL for describing parsers. We implement an interpreter for it at `Parser.lean` -/ inductive ParserDescrCore : ParserKind → Type | andthen {k : ParserKind} : ParserDescrCore k → ParserDescrCore k → ParserDescrCore k | orelse {k : ParserKind} : ParserDescrCore k → ParserDescrCore k → ParserDescrCore k | optional {k : ParserKind} : ParserDescrCore k → ParserDescrCore k | lookahead {k : ParserKind} : ParserDescrCore k → ParserDescrCore k | try {k : ParserKind} : ParserDescrCore k → ParserDescrCore k | many {k : ParserKind} : ParserDescrCore k → ParserDescrCore k | many1 {k : ParserKind} : ParserDescrCore k → ParserDescrCore k | sepBy {k : ParserKind} : ParserDescrCore k → ParserDescrCore k → ParserDescrCore k | sepBy1 {k : ParserKind} : ParserDescrCore k → ParserDescrCore k → ParserDescrCore k | node {k : ParserKind} : Name → ParserDescrCore k → ParserDescrCore k | symbol {k : ParserKind} : String → Nat → ParserDescrCore k | unicodeSymbol {k : ParserKind} : String → String → Nat → ParserDescrCore k | pushLeading : ParserDescrCore ParserKind.trailing | parser : Name → Nat → ParserDescrCore ParserKind.leading instance ParserDescrCore.inhabited {k} : Inhabited (ParserDescrCore k) := ⟨ParserDescrCore.symbol "" 0⟩ abbrev ParserDescr := ParserDescrCore ParserKind.leading abbrev TrailingParserDescr := ParserDescrCore ParserKind.trailing @[matchPattern] abbrev ParserDescr.andthen := @ParserDescrCore.andthen @[matchPattern] abbrev ParserDescr.orelse := @ParserDescrCore.orelse @[matchPattern] abbrev ParserDescr.optional := @ParserDescrCore.optional @[matchPattern] abbrev ParserDescr.lookahead := @ParserDescrCore.lookahead @[matchPattern] abbrev ParserDescr.try := @ParserDescrCore.try @[matchPattern] abbrev ParserDescr.many := @ParserDescrCore.many @[matchPattern] abbrev ParserDescr.many1 := @ParserDescrCore.many1 @[matchPattern] abbrev ParserDescr.sepBy := @ParserDescrCore.sepBy @[matchPattern] abbrev ParserDescr.sepBy1 := @ParserDescrCore.sepBy1 @[matchPattern] abbrev ParserDescr.node := @ParserDescrCore.node @[matchPattern] abbrev ParserDescr.symbol := @ParserDescrCore.symbol @[matchPattern] abbrev ParserDescr.unicodeSymbol := @ParserDescrCore.unicodeSymbol @[matchPattern] abbrev ParserDescr.pushLeading := @ParserDescrCore.pushLeading @[matchPattern] abbrev ParserDescr.parser := @ParserDescrCore.parser end Lean
7a7787e44e43860ddd8c05c07652bac4f5884d1f
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/data/pnat/find.lean
80ba4eafd2f56f47fcec330a820662d12ea9f2b9
[ "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
3,988
lean
/- Copyright (c) 2022 Yakov Pechersky. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yakov Pechersky, Floris van Doorn -/ import data.pnat.basic /-! # Explicit least witnesses to existentials on positive natural numbers > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. Implemented via calling out to `nat.find`. -/ namespace pnat variables {p q : ℕ+ → Prop} [decidable_pred p] [decidable_pred q] (h : ∃ n, p n) instance decidable_pred_exists_nat : decidable_pred (λ n' : ℕ, ∃ (n : ℕ+) (hn : n' = n), p n) := λ n', decidable_of_iff' (∃ (h : 0 < n'), p ⟨n', h⟩) $ subtype.exists.trans $ by simp_rw [subtype.coe_mk, @exists_comm (_ < _) (_ = _), exists_prop, exists_eq_left'] include h /-- The `pnat` version of `nat.find_x` -/ protected def find_x : {n // p n ∧ ∀ m : ℕ+, m < n → ¬p m} := begin have : ∃ (n' : ℕ) (n : ℕ+) (hn' : n' = n), p n, from exists.elim h (λ n hn, ⟨n, n, rfl, hn⟩), have n := nat.find_x this, refine ⟨⟨n, _⟩, _, λ m hm pm, _⟩, { obtain ⟨n', hn', -⟩ := n.prop.1, rw hn', exact n'.prop }, { obtain ⟨n', hn', pn'⟩ := n.prop.1, simpa [hn', subtype.coe_eta] using pn' }, { exact n.prop.2 m hm ⟨m, rfl, pm⟩ } end /-- If `p` is a (decidable) predicate on `ℕ+` and `hp : ∃ (n : ℕ+), p n` is a proof that there exists some positive natural number satisfying `p`, then `pnat.find hp` is the smallest positive natural number satisfying `p`. Note that `pnat.find` is protected, meaning that you can't just write `find`, even if the `pnat` namespace is open. The API for `pnat.find` is: * `pnat.find_spec` is the proof that `pnat.find hp` satisfies `p`. * `pnat.find_min` is the proof that if `m < pnat.find hp` then `m` does not satisfy `p`. * `pnat.find_min'` is the proof that if `m` does satisfy `p` then `pnat.find hp ≤ m`. -/ protected def find : ℕ+ := pnat.find_x h protected theorem find_spec : p (pnat.find h) := (pnat.find_x h).prop.left protected theorem find_min : ∀ {m : ℕ+}, m < pnat.find h → ¬p m := (pnat.find_x h).prop.right protected theorem find_min' {m : ℕ+} (hm : p m) : pnat.find h ≤ m := le_of_not_lt (λ l, pnat.find_min h l hm) variables {n m : ℕ+} lemma find_eq_iff : pnat.find h = m ↔ p m ∧ ∀ n < m, ¬ p n := begin split, { rintro rfl, exact ⟨pnat.find_spec h, λ _, pnat.find_min h⟩ }, { rintro ⟨hm, hlt⟩, exact le_antisymm (pnat.find_min' h hm) (not_lt.1 $ imp_not_comm.1 (hlt _) $ pnat.find_spec h) } end @[simp] lemma find_lt_iff (n : ℕ+) : pnat.find h < n ↔ ∃ m < n, p m := ⟨λ h2, ⟨pnat.find h, h2, pnat.find_spec h⟩, λ ⟨m, hmn, hm⟩, (pnat.find_min' h hm).trans_lt hmn⟩ @[simp] lemma find_le_iff (n : ℕ+) : pnat.find h ≤ n ↔ ∃ m ≤ n, p m := by simp only [exists_prop, ← lt_add_one_iff, find_lt_iff] @[simp] lemma le_find_iff (n : ℕ+) : n ≤ pnat.find h ↔ ∀ m < n, ¬ p m := by simp_rw [← not_lt, find_lt_iff, not_exists] @[simp] lemma lt_find_iff (n : ℕ+) : n < pnat.find h ↔ ∀ m ≤ n, ¬ p m := by simp only [← add_one_le_iff, le_find_iff, add_le_add_iff_right] @[simp] lemma find_eq_one : pnat.find h = 1 ↔ p 1 := by simp [find_eq_iff] @[simp] lemma one_le_find : 1 < pnat.find h ↔ ¬ p 1 := not_iff_not.mp $ by simp theorem find_mono (h : ∀ n, q n → p n) {hp : ∃ n, p n} {hq : ∃ n, q n} : pnat.find hp ≤ pnat.find hq := pnat.find_min' _ (h _ (pnat.find_spec hq)) lemma find_le {h : ∃ n, p n} (hn : p n) : pnat.find h ≤ n := (pnat.find_le_iff _ _).2 ⟨n, le_rfl, hn⟩ lemma find_comp_succ (h : ∃ n, p n) (h₂ : ∃ n, p (n + 1)) (h1 : ¬ p 1) : pnat.find h = pnat.find h₂ + 1 := begin refine (find_eq_iff _).2 ⟨pnat.find_spec h₂, λ n, pnat.rec_on n _ _⟩, { simp [h1] }, intros m IH hm, simp only [add_lt_add_iff_right, lt_find_iff] at hm, exact hm _ le_rfl end end pnat
9c9c303daaa9de9028fee5cfd6ed4b8d99b927b9
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/number_theory/divisors.lean
f069d24981d6093ac4d9c7dd771827c8586433a4
[ "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
16,356
lean
/- Copyright (c) 2020 Aaron Anderson. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Aaron Anderson -/ import algebra.big_operators.order import data.nat.interval import data.nat.factors /-! # Divisor finsets > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file defines sets of divisors of a natural number. This is particularly useful as background for defining Dirichlet convolution. ## Main Definitions Let `n : ℕ`. All of the following definitions are in the `nat` namespace: * `divisors n` is the `finset` of natural numbers that divide `n`. * `proper_divisors n` is the `finset` of natural numbers that divide `n`, other than `n`. * `divisors_antidiagonal n` is the `finset` of pairs `(x,y)` such that `x * y = n`. * `perfect n` is true when `n` is positive and the sum of `proper_divisors n` is `n`. ## Implementation details * `divisors 0`, `proper_divisors 0`, and `divisors_antidiagonal 0` are defined to be `∅`. ## Tags divisors, perfect numbers -/ open_locale classical open_locale big_operators open finset namespace nat variable (n : ℕ) /-- `divisors n` is the `finset` of divisors of `n`. As a special case, `divisors 0 = ∅`. -/ def divisors : finset ℕ := finset.filter (λ x : ℕ, x ∣ n) (finset.Ico 1 (n + 1)) /-- `proper_divisors n` is the `finset` of divisors of `n`, other than `n`. As a special case, `proper_divisors 0 = ∅`. -/ def proper_divisors : finset ℕ := finset.filter (λ x : ℕ, x ∣ n) (finset.Ico 1 n) /-- `divisors_antidiagonal n` is the `finset` of pairs `(x,y)` such that `x * y = n`. As a special case, `divisors_antidiagonal 0 = ∅`. -/ def divisors_antidiagonal : finset (ℕ × ℕ) := (Ico 1 (n + 1) ×ˢ Ico 1 (n + 1)).filter (λ x, x.fst * x.snd = n) variable {n} @[simp] lemma filter_dvd_eq_divisors (h : n ≠ 0) : (finset.range n.succ).filter (∣ n) = n.divisors := begin ext, simp only [divisors, mem_filter, mem_range, mem_Ico, and.congr_left_iff, iff_and_self], exact λ ha _, succ_le_iff.mpr (pos_of_dvd_of_pos ha h.bot_lt), end @[simp] lemma filter_dvd_eq_proper_divisors (h : n ≠ 0) : (finset.range n).filter (∣ n) = n.proper_divisors := begin ext, simp only [proper_divisors, mem_filter, mem_range, mem_Ico, and.congr_left_iff, iff_and_self], exact λ ha _, succ_le_iff.mpr (pos_of_dvd_of_pos ha h.bot_lt), end lemma proper_divisors.not_self_mem : ¬ n ∈ proper_divisors n := by simp [proper_divisors] @[simp] lemma mem_proper_divisors {m : ℕ} : n ∈ proper_divisors m ↔ n ∣ m ∧ n < m := begin rcases eq_or_ne m 0 with rfl | hm, { simp [proper_divisors] }, simp only [and_comm, ←filter_dvd_eq_proper_divisors hm, mem_filter, mem_range], end lemma insert_self_proper_divisors (h : n ≠ 0): insert n (proper_divisors n) = divisors n := by rw [divisors, proper_divisors, Ico_succ_right_eq_insert_Ico (one_le_iff_ne_zero.2 h), finset.filter_insert, if_pos (dvd_refl n)] lemma cons_self_proper_divisors (h : n ≠ 0) : cons n (proper_divisors n) proper_divisors.not_self_mem = divisors n := by rw [cons_eq_insert, insert_self_proper_divisors h] @[simp] lemma mem_divisors {m : ℕ} : n ∈ divisors m ↔ (n ∣ m ∧ m ≠ 0) := begin rcases eq_or_ne m 0 with rfl | hm, { simp [divisors] }, simp only [hm, ne.def, not_false_iff, and_true, ←filter_dvd_eq_divisors hm, mem_filter, mem_range, and_iff_right_iff_imp, lt_succ_iff], exact le_of_dvd hm.bot_lt, end lemma one_mem_divisors : 1 ∈ divisors n ↔ n ≠ 0 := by simp lemma mem_divisors_self (n : ℕ) (h : n ≠ 0) : n ∈ n.divisors := mem_divisors.2 ⟨dvd_rfl, h⟩ lemma dvd_of_mem_divisors {m : ℕ} (h : n ∈ divisors m) : n ∣ m := begin cases m, { apply dvd_zero }, { simp [mem_divisors.1 h], } end @[simp] lemma mem_divisors_antidiagonal {x : ℕ × ℕ} : x ∈ divisors_antidiagonal n ↔ x.fst * x.snd = n ∧ n ≠ 0 := begin simp only [divisors_antidiagonal, finset.mem_Ico, ne.def, finset.mem_filter, finset.mem_product], rw and_comm, apply and_congr_right, rintro rfl, split; intro h, { contrapose! h, simp [h], }, { rw [nat.lt_add_one_iff, nat.lt_add_one_iff], rw [mul_eq_zero, decidable.not_or_iff_and_not] at h, simp only [succ_le_of_lt (nat.pos_of_ne_zero h.1), succ_le_of_lt (nat.pos_of_ne_zero h.2), true_and], exact ⟨le_mul_of_pos_right (nat.pos_of_ne_zero h.2), le_mul_of_pos_left (nat.pos_of_ne_zero h.1)⟩ } end variable {n} lemma divisor_le {m : ℕ}: n ∈ divisors m → n ≤ m := begin cases m, { simp }, simp only [mem_divisors, m.succ_ne_zero, and_true, ne.def, not_false_iff], exact nat.le_of_dvd (nat.succ_pos m), end lemma divisors_subset_of_dvd {m : ℕ} (hzero : n ≠ 0) (h : m ∣ n) : divisors m ⊆ divisors n := finset.subset_iff.2 $ λ x hx, nat.mem_divisors.mpr (⟨(nat.mem_divisors.mp hx).1.trans h, hzero⟩) lemma divisors_subset_proper_divisors {m : ℕ} (hzero : n ≠ 0) (h : m ∣ n) (hdiff : m ≠ n) : divisors m ⊆ proper_divisors n := begin apply finset.subset_iff.2, intros x hx, exact nat.mem_proper_divisors.2 (⟨(nat.mem_divisors.1 hx).1.trans h, lt_of_le_of_lt (divisor_le hx) (lt_of_le_of_ne (divisor_le (nat.mem_divisors.2 ⟨h, hzero⟩)) hdiff)⟩) end @[simp] lemma divisors_zero : divisors 0 = ∅ := by { ext, simp } @[simp] lemma proper_divisors_zero : proper_divisors 0 = ∅ := by { ext, simp } lemma proper_divisors_subset_divisors : proper_divisors n ⊆ divisors n := filter_subset_filter _ $ Ico_subset_Ico_right n.le_succ @[simp] lemma divisors_one : divisors 1 = {1} := by { ext, simp } @[simp] lemma proper_divisors_one : proper_divisors 1 = ∅ := by rw [proper_divisors, Ico_self, filter_empty] lemma pos_of_mem_divisors {m : ℕ} (h : m ∈ n.divisors) : 0 < m := begin cases m, { rw [mem_divisors, zero_dvd_iff] at h, cases h.2 h.1 }, apply nat.succ_pos, end lemma pos_of_mem_proper_divisors {m : ℕ} (h : m ∈ n.proper_divisors) : 0 < m := pos_of_mem_divisors (proper_divisors_subset_divisors h) lemma one_mem_proper_divisors_iff_one_lt : 1 ∈ n.proper_divisors ↔ 1 < n := by rw [mem_proper_divisors, and_iff_right (one_dvd _)] @[simp] lemma divisors_antidiagonal_zero : divisors_antidiagonal 0 = ∅ := by { ext, simp } @[simp] lemma divisors_antidiagonal_one : divisors_antidiagonal 1 = {(1,1)} := by { ext, simp [mul_eq_one, prod.ext_iff], } @[simp] lemma swap_mem_divisors_antidiagonal {x : ℕ × ℕ} : x.swap ∈ divisors_antidiagonal n ↔ x ∈ divisors_antidiagonal n := by rw [mem_divisors_antidiagonal, mem_divisors_antidiagonal, mul_comm, prod.swap] lemma fst_mem_divisors_of_mem_antidiagonal {x : ℕ × ℕ} (h : x ∈ divisors_antidiagonal n) : x.fst ∈ divisors n := begin rw mem_divisors_antidiagonal at h, simp [dvd.intro _ h.1, h.2], end lemma snd_mem_divisors_of_mem_antidiagonal {x : ℕ × ℕ} (h : x ∈ divisors_antidiagonal n) : x.snd ∈ divisors n := begin rw mem_divisors_antidiagonal at h, simp [dvd.intro_left _ h.1, h.2], end @[simp] lemma map_swap_divisors_antidiagonal : (divisors_antidiagonal n).map (equiv.prod_comm _ _).to_embedding = divisors_antidiagonal n := begin rw [← coe_inj, coe_map, equiv.coe_to_embedding, equiv.coe_prod_comm, set.image_swap_eq_preimage_swap], ext, exact swap_mem_divisors_antidiagonal, end @[simp] lemma image_fst_divisors_antidiagonal : (divisors_antidiagonal n).image prod.fst = divisors n := by { ext, simp [has_dvd.dvd, @eq_comm _ n (_ * _)] } @[simp] lemma image_snd_divisors_antidiagonal : (divisors_antidiagonal n).image prod.snd = divisors n := begin rw [←map_swap_divisors_antidiagonal, map_eq_image, image_image], exact image_fst_divisors_antidiagonal end lemma map_div_right_divisors : n.divisors.map ⟨λ d, (d, n/d), λ p₁ p₂, congr_arg prod.fst⟩ = n.divisors_antidiagonal := begin ext ⟨d, nd⟩, simp only [mem_map, mem_divisors_antidiagonal, function.embedding.coe_fn_mk, mem_divisors, prod.ext_iff, exists_prop, and.left_comm, exists_eq_left], split, { rintro ⟨⟨⟨k, rfl⟩, hn⟩, rfl⟩, rw [nat.mul_div_cancel_left _ (left_ne_zero_of_mul hn).bot_lt], exact ⟨rfl, hn⟩ }, { rintro ⟨rfl, hn⟩, exact ⟨⟨dvd_mul_right _ _, hn⟩, nat.mul_div_cancel_left _ (left_ne_zero_of_mul hn).bot_lt⟩ } end lemma map_div_left_divisors : n.divisors.map ⟨λ d, (n/d, d), λ p₁ p₂, congr_arg prod.snd⟩ = n.divisors_antidiagonal := begin apply finset.map_injective (equiv.prod_comm _ _).to_embedding, rw [map_swap_divisors_antidiagonal, ←map_div_right_divisors, finset.map_map], refl, end lemma sum_divisors_eq_sum_proper_divisors_add_self : ∑ i in divisors n, i = ∑ i in proper_divisors n, i + n := begin rcases decidable.eq_or_ne n 0 with rfl|hn, { simp }, { rw [← cons_self_proper_divisors hn, finset.sum_cons, add_comm] } end /-- `n : ℕ` is perfect if and only the sum of the proper divisors of `n` is `n` and `n` is positive. -/ def perfect (n : ℕ) : Prop := (∑ i in proper_divisors n, i = n) ∧ 0 < n theorem perfect_iff_sum_proper_divisors (h : 0 < n) : perfect n ↔ ∑ i in proper_divisors n, i = n := and_iff_left h theorem perfect_iff_sum_divisors_eq_two_mul (h : 0 < n) : perfect n ↔ ∑ i in divisors n, i = 2 * n := begin rw [perfect_iff_sum_proper_divisors h, sum_divisors_eq_sum_proper_divisors_add_self, two_mul], split; intro h, { rw h }, { apply add_right_cancel h } end lemma mem_divisors_prime_pow {p : ℕ} (pp : p.prime) (k : ℕ) {x : ℕ} : x ∈ divisors (p ^ k) ↔ ∃ (j : ℕ) (H : j ≤ k), x = p ^ j := by rw [mem_divisors, nat.dvd_prime_pow pp, and_iff_left (ne_of_gt (pow_pos pp.pos k))] lemma prime.divisors {p : ℕ} (pp : p.prime) : divisors p = {1, p} := begin ext, rw [mem_divisors, dvd_prime pp, and_iff_left pp.ne_zero, finset.mem_insert, finset.mem_singleton] end lemma prime.proper_divisors {p : ℕ} (pp : p.prime) : proper_divisors p = {1} := by rw [← erase_insert proper_divisors.not_self_mem, insert_self_proper_divisors pp.ne_zero, pp.divisors, pair_comm, erase_insert (λ con, pp.ne_one (mem_singleton.1 con))] lemma divisors_prime_pow {p : ℕ} (pp : p.prime) (k : ℕ) : divisors (p ^ k) = (finset.range (k + 1)).map ⟨pow p, pow_right_injective pp.two_le⟩ := by { ext, simp [mem_divisors_prime_pow, pp, nat.lt_succ_iff, @eq_comm _ a] } lemma eq_proper_divisors_of_subset_of_sum_eq_sum {s : finset ℕ} (hsub : s ⊆ n.proper_divisors) : ∑ x in s, x = ∑ x in n.proper_divisors, x → s = n.proper_divisors := begin cases n, { rw [proper_divisors_zero, subset_empty] at hsub, simp [hsub] }, classical, rw [← sum_sdiff hsub], intros h, apply subset.antisymm hsub, rw [← sdiff_eq_empty_iff_subset], contrapose h, rw [← ne.def, ← nonempty_iff_ne_empty] at h, apply ne_of_lt, rw [← zero_add (∑ x in s, x), ← add_assoc, add_zero], apply add_lt_add_right, have hlt := sum_lt_sum_of_nonempty h (λ x hx, pos_of_mem_proper_divisors (sdiff_subset _ _ hx)), simp only [sum_const_zero] at hlt, apply hlt end lemma sum_proper_divisors_dvd (h : ∑ x in n.proper_divisors, x ∣ n) : (∑ x in n.proper_divisors, x = 1) ∨ (∑ x in n.proper_divisors, x = n) := begin cases n, { simp }, cases n, { contrapose! h, simp, }, rw or_iff_not_imp_right, intro ne_n, have hlt : ∑ x in n.succ.succ.proper_divisors, x < n.succ.succ := lt_of_le_of_ne (nat.le_of_dvd (nat.succ_pos _) h) ne_n, symmetry, rw [← mem_singleton, eq_proper_divisors_of_subset_of_sum_eq_sum (singleton_subset_iff.2 (mem_proper_divisors.2 ⟨h, hlt⟩)) sum_singleton, mem_proper_divisors], refine ⟨one_dvd _, nat.succ_lt_succ (nat.succ_pos _)⟩, end @[simp, to_additive] lemma prime.prod_proper_divisors {α : Type*} [comm_monoid α] {p : ℕ} {f : ℕ → α} (h : p.prime) : ∏ x in p.proper_divisors, f x = f 1 := by simp [h.proper_divisors] @[simp, to_additive] lemma prime.prod_divisors {α : Type*} [comm_monoid α] {p : ℕ} {f : ℕ → α} (h : p.prime) : ∏ x in p.divisors, f x = f p * f 1 := by rw [← cons_self_proper_divisors h.ne_zero, prod_cons, h.prod_proper_divisors] lemma proper_divisors_eq_singleton_one_iff_prime : n.proper_divisors = {1} ↔ n.prime := ⟨λ h, begin have h1 := mem_singleton.2 rfl, rw [← h, mem_proper_divisors] at h1, refine nat.prime_def_lt''.mpr ⟨h1.2, λ m hdvd, _⟩, rw [← mem_singleton, ← h, mem_proper_divisors], have hle := nat.le_of_dvd (lt_trans (nat.succ_pos _) h1.2) hdvd, exact or.imp_left (λ hlt, ⟨hdvd, hlt⟩) hle.lt_or_eq end, prime.proper_divisors⟩ lemma sum_proper_divisors_eq_one_iff_prime : ∑ x in n.proper_divisors, x = 1 ↔ n.prime := begin cases n, { simp [nat.not_prime_zero] }, cases n, { simp [nat.not_prime_one] }, rw [← proper_divisors_eq_singleton_one_iff_prime], refine ⟨λ h, _, λ h, h.symm ▸ sum_singleton⟩, rw [@eq_comm (finset ℕ) _ _], apply eq_proper_divisors_of_subset_of_sum_eq_sum (singleton_subset_iff.2 (one_mem_proper_divisors_iff_one_lt.2 (succ_lt_succ (nat.succ_pos _)))) (eq.trans sum_singleton h.symm) end lemma mem_proper_divisors_prime_pow {p : ℕ} (pp : p.prime) (k : ℕ) {x : ℕ} : x ∈ proper_divisors (p ^ k) ↔ ∃ (j : ℕ) (H : j < k), x = p ^ j := begin rw [mem_proper_divisors, nat.dvd_prime_pow pp, ← exists_and_distrib_right], simp only [exists_prop, and_assoc], apply exists_congr, intro a, split; intro h, { rcases h with ⟨h_left, rfl, h_right⟩, rwa pow_lt_pow_iff pp.one_lt at h_right, simpa, }, { rcases h with ⟨h_left, rfl⟩, rwa pow_lt_pow_iff pp.one_lt, simp [h_left, le_of_lt], }, end lemma proper_divisors_prime_pow {p : ℕ} (pp : p.prime) (k : ℕ) : proper_divisors (p ^ k) = (finset.range k).map ⟨pow p, pow_right_injective pp.two_le⟩ := by { ext, simp [mem_proper_divisors_prime_pow, pp, nat.lt_succ_iff, @eq_comm _ a], } @[simp, to_additive] lemma prod_proper_divisors_prime_pow {α : Type*} [comm_monoid α] {k p : ℕ} {f : ℕ → α} (h : p.prime) : ∏ x in (p ^ k).proper_divisors, f x = ∏ x in range k, f (p ^ x) := by simp [h, proper_divisors_prime_pow] @[simp, to_additive sum_divisors_prime_pow] lemma prod_divisors_prime_pow {α : Type*} [comm_monoid α] {k p : ℕ} {f : ℕ → α} (h : p.prime) : ∏ x in (p ^ k).divisors, f x = ∏ x in range (k + 1), f (p ^ x) := by simp [h, divisors_prime_pow] @[to_additive] lemma prod_divisors_antidiagonal {M : Type*} [comm_monoid M] (f : ℕ → ℕ → M) {n : ℕ} : ∏ i in n.divisors_antidiagonal, f i.1 i.2 = ∏ i in n.divisors, f i (n / i) := begin rw [←map_div_right_divisors, finset.prod_map], refl, end @[to_additive] lemma prod_divisors_antidiagonal' {M : Type*} [comm_monoid M] (f : ℕ → ℕ → M) {n : ℕ} : ∏ i in n.divisors_antidiagonal, f i.1 i.2 = ∏ i in n.divisors, f (n / i) i := begin rw [←map_swap_divisors_antidiagonal, finset.prod_map], exact prod_divisors_antidiagonal (λ i j, f j i), end /-- The factors of `n` are the prime divisors -/ lemma prime_divisors_eq_to_filter_divisors_prime (n : ℕ) : n.factors.to_finset = (divisors n).filter prime := begin rcases n.eq_zero_or_pos with rfl | hn, { simp }, { ext q, simpa [hn, hn.ne', mem_factors] using and_comm (prime q) (q ∣ n) } end @[simp] lemma image_div_divisors_eq_divisors (n : ℕ) : image (λ (x : ℕ), n / x) n.divisors = n.divisors := begin by_cases hn : n = 0, { simp [hn] }, ext, split, { rw mem_image, rintros ⟨x, hx1, hx2⟩, rw mem_divisors at *, refine ⟨_,hn⟩, rw ←hx2, exact div_dvd_of_dvd hx1.1 }, { rw [mem_divisors, mem_image], rintros ⟨h1, -⟩, exact ⟨n/a, mem_divisors.mpr ⟨div_dvd_of_dvd h1, hn⟩, nat.div_div_self h1 hn⟩ }, end @[simp, to_additive sum_div_divisors] lemma prod_div_divisors {α : Type*} [comm_monoid α] (n : ℕ) (f : ℕ → α) : ∏ d in n.divisors, f (n/d) = n.divisors.prod f := begin by_cases hn : n = 0, { simp [hn] }, rw ←prod_image, { exact prod_congr (image_div_divisors_eq_divisors n) (by simp) }, { intros x hx y hy h, rw mem_divisors at hx hy, exact (div_eq_iff_eq_of_dvd_dvd hn hx.1 hy.1).mp h } end end nat
618b4efad379795f5d564de9ce6a124b41a8f230
e61a235b8468b03aee0120bf26ec615c045005d2
/stage0/src/Init/Data/RBMap/Basic.lean
52af33ea028607ada6440ea75a1fbbd4eef604db
[ "Apache-2.0" ]
permissive
SCKelemen/lean4
140dc63a80539f7c61c8e43e1c174d8500ec3230
e10507e6615ddbef73d67b0b6c7f1e4cecdd82bc
refs/heads/master
1,660,973,595,917
1,590,278,033,000
1,590,278,033,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
11,736
lean
/- Copyright (c) 2017 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude import Init.Data.Repr import Init.Data.Option.Basic universes u v w w' inductive Rbcolor | red | black inductive RBNode (α : Type u) (β : α → Type v) | leaf : RBNode | node (color : Rbcolor) (lchild : RBNode) (key : α) (val : β key) (rchild : RBNode) : RBNode namespace RBNode variables {α : Type u} {β : α → Type v} {σ : Type w} open Rbcolor Nat def depth (f : Nat → Nat → Nat) : RBNode α β → Nat | leaf => 0 | node _ l _ _ r => succ (f (depth l) (depth r)) protected def min : RBNode α β → Option (Sigma (fun k => β k)) | leaf => none | node _ leaf k v _ => some ⟨k, v⟩ | node _ l k v _ => min l protected def max : RBNode α β → Option (Sigma (fun k => β k)) | leaf => none | node _ _ k v leaf => some ⟨k, v⟩ | node _ _ k v r => max r @[specialize] def fold (f : σ → ∀ (k : α), β k → σ) : σ → RBNode α β → σ | b, leaf => b | b, node _ l k v r => fold (f (fold b l) k v) r @[specialize] def mfold {m : Type w → Type w'} [Monad m] (f : σ → ∀ (k : α), β k → m σ) : σ → RBNode α β → m σ | b, leaf => pure b | b, node _ l k v r => do b ← mfold b l; b ← f b k v; mfold b r @[specialize] def revFold (f : σ → ∀ (k : α), β k → σ) : σ → RBNode α β → σ | b, leaf => b | b, node _ l k v r => revFold (f (revFold b r) k v) l @[specialize] def all (p : ∀ k, β k → Bool) : RBNode α β → Bool | leaf => true | node _ l k v r => p k v && all l && all r @[specialize] def any (p : ∀ k, β k → Bool) : RBNode α β → Bool | leaf => false | node _ l k v r => p k v || any l || any r def singleton (k : α) (v : β k) : RBNode α β := node red leaf k v leaf @[inline] def balance1 : ∀ a, β a → RBNode α β → RBNode α β → RBNode α β | kv, vv, t, node _ (node red l kx vx r₁) ky vy r₂ => node red (node black l kx vx r₁) ky vy (node black r₂ kv vv t) | kv, vv, t, node _ l₁ ky vy (node red l₂ kx vx r) => node red (node black l₁ ky vy l₂) kx vx (node black r kv vv t) | kv, vv, t, node _ l ky vy r => node black (node red l ky vy r) kv vv t | _, _, _, _ => leaf -- unreachable @[inline] def balance2 : RBNode α β → ∀ a, β a → RBNode α β → RBNode α β | t, kv, vv, node _ (node red l kx₁ vx₁ r₁) ky vy r₂ => node red (node black t kv vv l) kx₁ vx₁ (node black r₁ ky vy r₂) | t, kv, vv, node _ l₁ ky vy (node red l₂ kx₂ vx₂ r₂) => node red (node black t kv vv l₁) ky vy (node black l₂ kx₂ vx₂ r₂) | t, kv, vv, node _ l ky vy r => node black t kv vv (node red l ky vy r) | _, _, _, _ => leaf -- unreachable def isRed : RBNode α β → Bool | node red _ _ _ _ => true | _ => false def isBlack : RBNode α β → Bool | node black _ _ _ _ => true | _ => false section Insert variables (lt : α → α → Bool) @[specialize] def ins : RBNode α β → ∀ k, β k → RBNode α β | leaf, kx, vx => node red leaf kx vx leaf | node red a ky vy b, kx, vx => if lt kx ky then node red (ins a kx vx) ky vy b else if lt ky kx then node red a ky vy (ins b kx vx) else node red a kx vx b | node black a ky vy b, kx, vx => if lt kx ky then if isRed a then balance1 ky vy b (ins a kx vx) else node black (ins a kx vx) ky vy b else if lt ky kx then if isRed b then balance2 a ky vy (ins b kx vx) else node black a ky vy (ins b kx vx) else node black a kx vx b def setBlack : RBNode α β → RBNode α β | node _ l k v r => node black l k v r | e => e @[specialize] def insert (t : RBNode α β) (k : α) (v : β k) : RBNode α β := if isRed t then setBlack (ins lt t k v) else ins lt t k v end Insert def balance₃ : RBNode α β → ∀ k, β k → RBNode α β → RBNode α β | node red (node red a kx vx b) ky vy c, k, v, d => node red (node black a kx vx b) ky vy (node black c k v d) | node red a kx vx (node red b ky vy c), k, v, d => node red (node black a kx vx b) ky vy (node black c k v d) | a, k, v, node red b ky vy (node red c kz vz d) => node red (node black a k v b) ky vy (node black c kz vz d) | a, k, v, node red (node red b ky vy c) kz vz d => node red (node black a k v b) ky vy (node black c kz vz d) | l, k, v, r => node black l k v r def setRed : RBNode α β → RBNode α β | node _ a k v b => node red a k v b | e => e def balLeft : RBNode α β → ∀ k, β k → RBNode α β → RBNode α β | node red a kx vx b, k, v, r => node red (node black a kx vx b) k v r | l, k, v, node black a ky vy b => balance₃ l k v (node red a ky vy b) | l, k, v, node red (node black a ky vy b) kz vz c => node red (node black l k v a) ky vy (balance₃ b kz vz (setRed c)) | l, k, v, r => node red l k v r -- unreachable def balRight (l : RBNode α β) (k : α) (v : β k) (r : RBNode α β) : RBNode α β := match r with | (node red b ky vy c) => node red l k v (node black b ky vy c) | _ => match l with | node black a kx vx b => balance₃ (node red a kx vx b) k v r | node red a kx vx (node black b ky vy c) => node red (balance₃ (setRed a) kx vx b) ky vy (node black c k v r) | _ => node red l k v r -- unreachable -- TODO: use wellfounded recursion partial def appendTrees : RBNode α β → RBNode α β → RBNode α β | leaf, x => x | x, leaf => x | node red a kx vx b, node red c ky vy d => match appendTrees b c with | node red b' kz vz c' => node red (node red a kx vx b') kz vz (node red c' ky vy d) | bc => node red a kx vx (node red bc ky vy d) | node black a kx vx b, node black c ky vy d => match appendTrees b c with | node red b' kz vz c' => node red (node black a kx vx b') kz vz (node black c' ky vy d) | bc => balLeft a kx vx (node black bc ky vy d) | a, node red b kx vx c => node red (appendTrees a b) kx vx c | node red a kx vx b, c => node red a kx vx (appendTrees b c) section Erase variables (lt : α → α → Bool) @[specialize] def del (x : α) : RBNode α β → RBNode α β | leaf => leaf | node _ a y v b => if lt x y then if a.isBlack then balLeft (del a) y v b else node red (del a) y v b else if lt y x then if b.isBlack then balRight a y v (del b) else node red a y v (del b) else appendTrees a b @[specialize] def erase (x : α) (t : RBNode α β) : RBNode α β := let t := del lt x t; t.setBlack end Erase section Membership variable (lt : α → α → Bool) @[specialize] def findCore : RBNode α β → ∀ (k : α), Option (Sigma (fun k => β k)) | leaf, x => none | node _ a ky vy b, x => if lt x ky then findCore a x else if lt ky x then findCore b x else some ⟨ky, vy⟩ @[specialize] def find {β : Type v} : RBNode α (fun _ => β) → α → Option β | leaf, x => none | node _ a ky vy b, x => if lt x ky then find a x else if lt ky x then find b x else some vy @[specialize] def lowerBound : RBNode α β → α → Option (Sigma β) → Option (Sigma β) | leaf, x, lb => lb | node _ a ky vy b, x, lb => if lt x ky then lowerBound a x lb else if lt ky x then lowerBound b x (some ⟨ky, vy⟩) else some ⟨ky, vy⟩ end Membership inductive WellFormed (lt : α → α → Bool) : RBNode α β → Prop | leafWff : WellFormed leaf | insertWff {n n' : RBNode α β} {k : α} {v : β k} : WellFormed n → n' = insert lt n k v → WellFormed n' | eraseWff {n n' : RBNode α β} {k : α} : WellFormed n → n' = erase lt k n → WellFormed n' end RBNode open RBNode /- TODO(Leo): define dRBMap -/ def RBMap (α : Type u) (β : Type v) (lt : α → α → Bool) : Type (max u v) := {t : RBNode α (fun _ => β) // t.WellFormed lt } @[inline] def mkRBMap (α : Type u) (β : Type v) (lt : α → α → Bool) : RBMap α β lt := ⟨leaf, WellFormed.leafWff⟩ @[inline] def RBMap.empty {α : Type u} {β : Type v} {lt : α → α → Bool} : RBMap α β lt := mkRBMap _ _ _ instance (α : Type u) (β : Type v) (lt : α → α → Bool) : HasEmptyc (RBMap α β lt) := ⟨RBMap.empty⟩ namespace RBMap variables {α : Type u} {β : Type v} {σ : Type w} {lt : α → α → Bool} def depth (f : Nat → Nat → Nat) (t : RBMap α β lt) : Nat := t.val.depth f @[inline] def fold (f : σ → α → β → σ) : σ → RBMap α β lt → σ | b, ⟨t, _⟩ => t.fold f b @[inline] def revFold (f : σ → α → β → σ) : σ → RBMap α β lt → σ | b, ⟨t, _⟩ => t.revFold f b @[inline] def mfold {m : Type w → Type w'} [Monad m] (f : σ → α → β → m σ) : σ → RBMap α β lt → m σ | b, ⟨t, _⟩ => t.mfold f b @[inline] def mfor {m : Type w → Type w'} [Monad m] (f : α → β → m PUnit) (t : RBMap α β lt) : m PUnit := t.mfold (fun _ k v => f k v) ⟨⟩ @[inline] def isEmpty : RBMap α β lt → Bool | ⟨leaf, _⟩ => true | _ => false @[specialize] def toList : RBMap α β lt → List (α × β) | ⟨t, _⟩ => t.revFold (fun ps k v => (k, v)::ps) [] @[inline] protected def min : RBMap α β lt → Option (α × β) | ⟨t, _⟩ => match t.min with | some ⟨k, v⟩ => some (k, v) | none => none @[inline] protected def max : RBMap α β lt → Option (α × β) | ⟨t, _⟩ => match t.max with | some ⟨k, v⟩ => some (k, v) | none => none instance [HasRepr α] [HasRepr β] : HasRepr (RBMap α β lt) := ⟨fun t => "rbmapOf " ++ repr t.toList⟩ @[inline] def insert : RBMap α β lt → α → β → RBMap α β lt | ⟨t, w⟩, k, v => ⟨t.insert lt k v, WellFormed.insertWff w rfl⟩ @[inline] def erase : RBMap α β lt → α → RBMap α β lt | ⟨t, w⟩, k => ⟨t.erase lt k, WellFormed.eraseWff w rfl⟩ @[specialize] def ofList : List (α × β) → RBMap α β lt | [] => mkRBMap _ _ _ | ⟨k,v⟩::xs => (ofList xs).insert k v @[inline] def findCore? : RBMap α β lt → α → Option (Sigma (fun (k : α) => β)) | ⟨t, _⟩, x => t.findCore lt x @[inline] def find? : RBMap α β lt → α → Option β | ⟨t, _⟩, x => t.find lt x @[inline] def findD (t : RBMap α β lt) (k : α) (v₀ : β) : β := (t.find? k).getD v₀ /-- (lowerBound k) retrieves the kv pair of the largest key smaller than or equal to `k`, if it exists. -/ @[inline] def lowerBound : RBMap α β lt → α → Option (Sigma (fun (k : α) => β)) | ⟨t, _⟩, x => t.lowerBound lt x none @[inline] def contains (t : RBMap α β lt) (a : α) : Bool := (t.find? a).isSome @[inline] def fromList (l : List (α × β)) (lt : α → α → Bool) : RBMap α β lt := l.foldl (fun r p => r.insert p.1 p.2) (mkRBMap α β lt) @[inline] def all : RBMap α β lt → (α → β → Bool) → Bool | ⟨t, _⟩, p => t.all p @[inline] def any : RBMap α β lt → (α → β → Bool) → Bool | ⟨t, _⟩, p => t.any p def size (m : RBMap α β lt) : Nat := m.fold (fun sz _ _ => sz+1) 0 def maxDepth (t : RBMap α β lt) : Nat := t.val.depth Nat.max end RBMap def rbmapOf {α : Type u} {β : Type v} (l : List (α × β)) (lt : α → α → Bool) : RBMap α β lt := RBMap.fromList l lt
8a5a2df7b72ffd48e8637906ddc01743dfa65d17
a4673261e60b025e2c8c825dfa4ab9108246c32e
/src/Init/Data/Float.lean
014f3a5647f7b644811b0151058ca7eda5708221
[ "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
3,711
lean
/- Copyright (c) 2020 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude import Init.Core import Init.Data.ToString.Basic structure FloatSpec := (float : Type) (val : float) (lt : float → float → Prop) (le : float → float → Prop) (decLt : DecidableRel lt) (decLe : DecidableRel le) -- Just show FloatSpec is inhabited. constant floatSpec : FloatSpec := { float := Unit, val := (), lt := fun _ _ => True, le := fun _ _ => True, decLt := fun _ _ => inferInstanceAs (Decidable True), decLe := fun _ _ => inferInstanceAs (Decidable True) } structure Float := (val : floatSpec.float) instance : Inhabited Float := ⟨{ val := floatSpec.val }⟩ @[extern "lean_float_of_nat"] constant Float.ofNat : (@& Nat) → Float @[extern c inline "#1 + #2"] constant Float.add : Float → Float → Float @[extern c inline "#1 - #2"] constant Float.sub : Float → Float → Float @[extern c inline "#1 * #2"] constant Float.mul : Float → Float → Float @[extern c inline "#1 / #2"] constant Float.div : Float → Float → Float set_option bootstrap.gen_matcher_code false def Float.lt : Float → Float → Prop := fun a b => match a, b with | ⟨a⟩, ⟨b⟩ => floatSpec.lt a b def Float.le : Float → Float → Prop := fun a b => floatSpec.le a.val b.val instance : OfNat Float := ⟨Float.ofNat⟩ instance : Add Float := ⟨Float.add⟩ instance : Sub Float := ⟨Float.sub⟩ instance : Mul Float := ⟨Float.mul⟩ instance : Div Float := ⟨Float.div⟩ instance : HasLess Float := ⟨Float.lt⟩ instance : HasLessEq Float := ⟨Float.le⟩ @[extern c inline "#1 == #2"] constant Float.beq (a b : Float) : Bool instance : BEq Float := ⟨Float.beq⟩ @[extern c inline "#1 < #2"] constant Float.decLt (a b : Float) : Decidable (a < b) := match a, b with | ⟨a⟩, ⟨b⟩ => floatSpec.decLt a b @[extern c inline "#1 <= #2"] constant Float.decLe (a b : Float) : Decidable (a ≤ b) := match a, b with | ⟨a⟩, ⟨b⟩ => floatSpec.decLe a b instance floatDecLt (a b : Float) : Decidable (a < b) := Float.decLt a b instance floatDecLe (a b : Float) : Decidable (a ≤ b) := Float.decLe a b @[extern "lean_float_to_string"] constant Float.toString : Float → String instance : ToString Float := ⟨Float.toString⟩ abbrev Nat.toFloat (n : Nat) : Float := Float.ofNat n @[extern "sin"] constant Float.sin : Float → Float @[extern "cos"] constant Float.cos : Float → Float @[extern "tan"] constant Float.tan : Float → Float @[extern "asin"] constant Float.asin : Float → Float @[extern "acos"] constant Float.acos : Float → Float @[extern "atan"] constant Float.atan : Float → Float @[extern "atan2"] constant Float.atan2 : Float → Float → Float @[extern "sinh"] constant Float.sinh : Float → Float @[extern "cosh"] constant Float.cosh : Float → Float @[extern "tanh"] constant Float.tanh : Float → Float @[extern "asinh"] constant Float.asinh : Float → Float @[extern "acosh"] constant Float.acosh : Float → Float @[extern "atanh"] constant Float.atanh : Float → Float @[extern "exp"] constant Float.exp : Float → Float @[extern "exp2"] constant Float.exp2 : Float → Float @[extern "log"] constant Float.log : Float → Float @[extern "log2"] constant Float.log2 : Float → Float @[extern "log10"] constant Float.log10 : Float → Float @[extern "pow"] constant Float.pow : Float → Float → Float @[extern "sqrt"] constant Float.sqrt : Float → Float @[extern "cbrt"] constant Float.cbrt : Float → Float instance : Pow Float Float := ⟨Float.pow⟩
6192c171119cb48eb0aa42c1a0ec9343835e5ceb
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/measure_theory/pi_system.lean
966bb5c5913ba716727758234977196d8808edae
[ "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
21,378
lean
/- Copyright (c) 2021 Martin Zinkevich. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Martin Zinkevich -/ import measure_theory.measurable_space_def import data.equiv.encodable.lattice /-! # Induction principles for measurable sets, related to π-systems and λ-systems. ## Main statements * The main theorem of this file is Dynkin's π-λ theorem, which appears here as an induction principle `induction_on_inter`. Suppose `s` is a collection of subsets of `α` such that the intersection of two members of `s` belongs to `s` whenever it is nonempty. Let `m` be the σ-algebra generated by `s`. In order to check that a predicate `C` holds on every member of `m`, it suffices to check that `C` holds on the members of `s` and that `C` is preserved by complementation and *disjoint* countable unions. * The proof of this theorem relies on the notion of `is_pi_system`, i.e., a collection of sets which is closed under binary non-empty intersections. Note that this is a small variation around the usual notion in the literature, which often requires that a π-system is non-empty, and closed also under disjoint intersections. This variation turns out to be convenient for the formalization. * The proof of Dynkin's π-λ theorem also requires the notion of `dynkin_system`, i.e., a collection of sets which contains the empty set, is closed under complementation and under countable union of pairwise disjoint sets. The disjointness condition is the only difference with `σ`-algebras. * `generate_pi_system g` gives the minimal π-system containing `g`. This can be considered a Galois insertion into both measurable spaces and sets. * `generate_from_generate_pi_system_eq` proves that if you start from a collection of sets `g`, take the generated π-system, and then the generated σ-algebra, you get the same result as the σ-algebra generated from `g`. This is useful because there are connections between independent sets that are π-systems and the generated independent spaces. * `mem_generate_pi_system_Union_elim` and `mem_generate_pi_system_Union_elim'` show that any element of the π-system generated from the union of a set of π-systems can be represented as the intersection of a finite number of elements from these sets. ## Implementation details * `is_pi_system` is a predicate, not a type. Thus, we don't explicitly define the galois insertion, nor do we define a complete lattice. In theory, we could define a complete lattice and galois insertion on the subtype corresponding to `is_pi_system`. -/ open measurable_space set open_locale classical /-- A π-system is a collection of subsets of `α` that is closed under binary intersection of non-disjoint sets. Usually it is also required that the collection is nonempty, but we don't do that here. -/ def is_pi_system {α} (C : set (set α)) : Prop := ∀ s t ∈ C, (s ∩ t : set α).nonempty → s ∩ t ∈ C namespace measurable_space lemma is_pi_system_measurable_set {α:Type*} [measurable_space α] : is_pi_system {s : set α | measurable_set s} := λ s hs t ht _, hs.inter ht end measurable_space lemma is_pi_system.singleton {α} (S : set α) : is_pi_system ({S} : set (set α)) := begin intros s h_s t h_t h_ne, rw [set.mem_singleton_iff.1 h_s, set.mem_singleton_iff.1 h_t, set.inter_self, set.mem_singleton_iff], end section order variables {α : Type*} {ι ι' : Sort*} [linear_order α] lemma is_pi_system_image_Iio (s : set α) : is_pi_system (Iio '' s) := begin rintro _ ⟨a, ha, rfl⟩ _ ⟨b, hb, rfl⟩ -, exact ⟨a ⊓ b, inf_ind a b ha hb, Iio_inter_Iio.symm⟩ end lemma is_pi_system_Iio : is_pi_system (range Iio : set (set α)) := @image_univ α _ Iio ▸ is_pi_system_image_Iio univ lemma is_pi_system_image_Ioi (s : set α) : is_pi_system (Ioi '' s) := @is_pi_system_image_Iio (order_dual α) _ s lemma is_pi_system_Ioi : is_pi_system (range Ioi : set (set α)) := @image_univ α _ Ioi ▸ is_pi_system_image_Ioi univ lemma is_pi_system_Ixx_mem {Ixx : α → α → set α} {p : α → α → Prop} (Hne : ∀ {a b}, (Ixx a b).nonempty → p a b) (Hi : ∀ {a₁ b₁ a₂ b₂}, Ixx a₁ b₁ ∩ Ixx a₂ b₂ = Ixx (max a₁ a₂) (min b₁ b₂)) (s t : set α) : is_pi_system {S | ∃ (l ∈ s) (u ∈ t) (hlu : p l u), Ixx l u = S} := begin rintro _ ⟨l₁, hls₁, u₁, hut₁, hlu₁, rfl⟩ _ ⟨l₂, hls₂, u₂, hut₂, hlu₂, rfl⟩, simp only [Hi, ← sup_eq_max, ← inf_eq_min], exact λ H, ⟨l₁ ⊔ l₂, sup_ind l₁ l₂ hls₁ hls₂, u₁ ⊓ u₂, inf_ind u₁ u₂ hut₁ hut₂, Hne H, rfl⟩ end lemma is_pi_system_Ixx {Ixx : α → α → set α} {p : α → α → Prop} (Hne : ∀ {a b}, (Ixx a b).nonempty → p a b) (Hi : ∀ {a₁ b₁ a₂ b₂}, Ixx a₁ b₁ ∩ Ixx a₂ b₂ = Ixx (max a₁ a₂) (min b₁ b₂)) (f : ι → α) (g : ι' → α) : @is_pi_system α ({S | ∃ i j (h : p (f i) (g j)), Ixx (f i) (g j) = S}) := by simpa only [exists_range_iff] using is_pi_system_Ixx_mem @Hne @Hi (range f) (range g) lemma is_pi_system_Ioo_mem (s t : set α) : is_pi_system {S | ∃ (l ∈ s) (u ∈ t) (h : l < u), Ioo l u = S} := is_pi_system_Ixx_mem (λ a b ⟨x, hax, hxb⟩, hax.trans hxb) (λ _ _ _ _, Ioo_inter_Ioo) s t lemma is_pi_system_Ioo (f : ι → α) (g : ι' → α) : @is_pi_system α {S | ∃ l u (h : f l < g u), Ioo (f l) (g u) = S} := is_pi_system_Ixx (λ a b ⟨x, hax, hxb⟩, hax.trans hxb) (λ _ _ _ _, Ioo_inter_Ioo) f g lemma is_pi_system_Ioc_mem (s t : set α) : is_pi_system {S | ∃ (l ∈ s) (u ∈ t) (h : l < u), Ioc l u = S} := is_pi_system_Ixx_mem (λ a b ⟨x, hax, hxb⟩, hax.trans_le hxb) (λ _ _ _ _, Ioc_inter_Ioc) s t lemma is_pi_system_Ioc (f : ι → α) (g : ι' → α) : @is_pi_system α {S | ∃ i j (h : f i < g j), Ioc (f i) (g j) = S} := is_pi_system_Ixx (λ a b ⟨x, hax, hxb⟩, hax.trans_le hxb) (λ _ _ _ _, Ioc_inter_Ioc) f g lemma is_pi_system_Ico_mem (s t : set α) : is_pi_system {S | ∃ (l ∈ s) (u ∈ t) (h : l < u), Ico l u = S} := is_pi_system_Ixx_mem (λ a b ⟨x, hax, hxb⟩, hax.trans_lt hxb) (λ _ _ _ _, Ico_inter_Ico) s t lemma is_pi_system_Ico (f : ι → α) (g : ι' → α) : @is_pi_system α {S | ∃ i j (h : f i < g j), Ico (f i) (g j) = S} := is_pi_system_Ixx (λ a b ⟨x, hax, hxb⟩, hax.trans_lt hxb) (λ _ _ _ _, Ico_inter_Ico) f g lemma is_pi_system_Icc_mem (s t : set α) : is_pi_system {S | ∃ (l ∈ s) (u ∈ t) (h : l ≤ u), Icc l u = S} := is_pi_system_Ixx_mem (λ a b, nonempty_Icc.1) (λ _ _ _ _, Icc_inter_Icc) s t lemma is_pi_system_Icc (f : ι → α) (g : ι' → α) : @is_pi_system α {S | ∃ i j (h : f i ≤ g j), Icc (f i) (g j) = S} := is_pi_system_Ixx (λ a b, nonempty_Icc.1) (λ _ _ _ _, Icc_inter_Icc) f g end order /-- Given a collection `S` of subsets of `α`, then `generate_pi_system S` is the smallest π-system containing `S`. -/ inductive generate_pi_system {α} (S : set (set α)) : set (set α) | base {s : set α} (h_s : s ∈ S) : generate_pi_system s | inter {s t : set α} (h_s : generate_pi_system s) (h_t : generate_pi_system t) (h_nonempty : (s ∩ t).nonempty) : generate_pi_system (s ∩ t) lemma is_pi_system_generate_pi_system {α} (S : set (set α)) : is_pi_system (generate_pi_system S) := λ s h_s t h_t h_nonempty, generate_pi_system.inter h_s h_t h_nonempty lemma subset_generate_pi_system_self {α} (S : set (set α)) : S ⊆ generate_pi_system S := λ s, generate_pi_system.base lemma generate_pi_system_subset_self {α} {S : set (set α)} (h_S : is_pi_system S) : generate_pi_system S ⊆ S := begin intros x h, induction h with s h_s s u h_gen_s h_gen_u h_nonempty h_s h_u, { exact h_s, }, { exact h_S _ h_s _ h_u h_nonempty, }, end lemma generate_pi_system_eq {α} {S : set (set α)} (h_pi : is_pi_system S) : generate_pi_system S = S := set.subset.antisymm (generate_pi_system_subset_self h_pi) (subset_generate_pi_system_self S) lemma generate_pi_system_mono {α} {S T : set (set α)} (hST : S ⊆ T) : generate_pi_system S ⊆ generate_pi_system T := begin intros t ht, induction ht with s h_s s u h_gen_s h_gen_u h_nonempty h_s h_u, { exact generate_pi_system.base (set.mem_of_subset_of_mem hST h_s),}, { exact is_pi_system_generate_pi_system T _ h_s _ h_u h_nonempty, }, end lemma generate_pi_system_measurable_set {α} [M : measurable_space α] {S : set (set α)} (h_meas_S : ∀ s ∈ S, measurable_set s) (t : set α) (h_in_pi : t ∈ generate_pi_system S) : measurable_set t := begin induction h_in_pi with s h_s s u h_gen_s h_gen_u h_nonempty h_s h_u, { apply h_meas_S _ h_s, }, { apply measurable_set.inter h_s h_u, }, end lemma generate_from_measurable_set_of_generate_pi_system {α} {g : set (set α)} (t : set α) (ht : t ∈ generate_pi_system g) : (generate_from g).measurable_set' t := @generate_pi_system_measurable_set α (generate_from g) g (λ s h_s_in_g, measurable_set_generate_from h_s_in_g) t ht lemma generate_from_generate_pi_system_eq {α} {g : set (set α)} : generate_from (generate_pi_system g) = generate_from g := begin apply le_antisymm; apply generate_from_le, { exact λ t h_t, generate_from_measurable_set_of_generate_pi_system t h_t, }, { exact λ t h_t, measurable_set_generate_from (generate_pi_system.base h_t), }, end /- Every element of the π-system generated by the union of a family of π-systems is a finite intersection of elements from the π-systems. For an indexed union version, see `mem_generate_pi_system_Union_elim'`. -/ lemma mem_generate_pi_system_Union_elim {α β} {g : β → set (set α)} (h_pi : ∀ b, is_pi_system (g b)) (t : set α) (h_t : t ∈ generate_pi_system (⋃ b, g b)) : ∃ (T : finset β) (f : β → set α), (t = ⋂ b ∈ T, f b) ∧ (∀ b ∈ T, f b ∈ g b) := begin induction h_t with s h_s s t' h_gen_s h_gen_t' h_nonempty h_s h_t', { rcases h_s with ⟨t', ⟨⟨b, rfl⟩, h_s_in_t'⟩⟩, refine ⟨{b}, (λ _, s), _⟩, simpa using h_s_in_t', }, { rcases h_t' with ⟨T_t', ⟨f_t', ⟨rfl, h_t'⟩⟩⟩, rcases h_s with ⟨T_s, ⟨f_s, ⟨rfl, h_s⟩ ⟩ ⟩, use [(T_s ∪ T_t'), (λ (b:β), if (b ∈ T_s) then (if (b ∈ T_t') then (f_s b ∩ (f_t' b)) else (f_s b)) else (if (b ∈ T_t') then (f_t' b) else (∅ : set α)))], split, { ext a, simp_rw [set.mem_inter_iff, set.mem_Inter, finset.mem_union, or_imp_distrib], rw ← forall_and_distrib, split; intros h1 b; by_cases hbs : b ∈ T_s; by_cases hbt : b ∈ T_t'; specialize h1 b; simp only [hbs, hbt, if_true, if_false, true_implies_iff, and_self, false_implies_iff, and_true, true_and] at h1 ⊢, all_goals { exact h1, }, }, intros b h_b, split_ifs with hbs hbt hbt, { refine h_pi b (f_s b) (h_s b hbs) (f_t' b) (h_t' b hbt) (set.nonempty.mono _ h_nonempty), exact set.inter_subset_inter (set.bInter_subset_of_mem hbs) (set.bInter_subset_of_mem hbt), }, { exact h_s b hbs, }, { exact h_t' b hbt, }, { rw finset.mem_union at h_b, apply false.elim (h_b.elim hbs hbt), }, }, end /- Every element of the π-system generated by an indexed union of a family of π-systems is a finite intersection of elements from the π-systems. For a total union version, see `mem_generate_pi_system_Union_elim`. -/ lemma mem_generate_pi_system_Union_elim' {α β} {g : β → set (set α)} {s: set β} (h_pi : ∀ b ∈ s, is_pi_system (g b)) (t : set α) (h_t : t ∈ generate_pi_system (⋃ b ∈ s, g b)) : ∃ (T : finset β) (f : β → set α), (↑T ⊆ s) ∧ (t = ⋂ b ∈ T, f b) ∧ (∀ b ∈ T, f b ∈ g b) := begin have : t ∈ generate_pi_system (⋃ (b : subtype s), (g ∘ subtype.val) b), { suffices h1 : (⋃ (b : subtype s), (g ∘ subtype.val) b) = (⋃ b (H : b ∈ s), g b), by rwa h1, ext x, simp only [exists_prop, set.mem_Union, function.comp_app, subtype.exists, subtype.coe_mk], refl }, rcases @mem_generate_pi_system_Union_elim α (subtype s) (g ∘ subtype.val) (λ b, h_pi b.val b.property) t this with ⟨T, ⟨f,⟨ rfl, h_t'⟩⟩⟩, refine ⟨T.image subtype.val, function.extend subtype.val f (λ (b:β), (∅ : set α)), by simp, _, _⟩, { ext a, split; { simp only [set.mem_Inter, subtype.forall, finset.set_bInter_finset_image], intros h1 b h_b h_b_in_T, have h2 := h1 b h_b h_b_in_T, revert h2, rw function.extend_apply subtype.val_injective, apply id } }, { intros b h_b, simp_rw [finset.mem_image, exists_prop, subtype.exists, exists_and_distrib_right, exists_eq_right] at h_b, cases h_b, have h_b_alt : b = (subtype.mk b h_b_w).val := rfl, rw [h_b_alt, function.extend_apply subtype.val_injective], apply h_t', apply h_b_h }, end namespace measurable_space variable {α : Type*} /-- A Dynkin system is a collection of subsets of a type `α` that contains the empty set, is closed under complementation and under countable union of pairwise disjoint sets. The disjointness condition is the only difference with `σ`-algebras. The main purpose of Dynkin systems is to provide a powerful induction rule for σ-algebras generated by a collection of sets which is stable under intersection. A Dynkin system is also known as a "λ-system" or a "d-system". -/ structure dynkin_system (α : Type*) := (has : set α → Prop) (has_empty : has ∅) (has_compl : ∀ {a}, has a → has aᶜ) (has_Union_nat : ∀ {f : ℕ → set α}, pairwise (disjoint on f) → (∀ i, has (f i)) → has (⋃ i, f i)) namespace dynkin_system @[ext] lemma ext : ∀ {d₁ d₂ : dynkin_system α}, (∀ s : set α, d₁.has s ↔ d₂.has s) → d₁ = d₂ | ⟨s₁, _, _, _⟩ ⟨s₂, _, _, _⟩ h := have s₁ = s₂, from funext $ assume x, propext $ h x, by subst this variable (d : dynkin_system α) lemma has_compl_iff {a} : d.has aᶜ ↔ d.has a := ⟨λ h, by simpa using d.has_compl h, λ h, d.has_compl h⟩ lemma has_univ : d.has univ := by simpa using d.has_compl d.has_empty theorem has_Union {β} [encodable β] {f : β → set α} (hd : pairwise (disjoint on f)) (h : ∀ i, d.has (f i)) : d.has (⋃ i, f i) := by { rw ← encodable.Union_decode₂, exact d.has_Union_nat (encodable.Union_decode₂_disjoint_on hd) (λ n, encodable.Union_decode₂_cases d.has_empty h) } theorem has_union {s₁ s₂ : set α} (h₁ : d.has s₁) (h₂ : d.has s₂) (h : s₁ ∩ s₂ ⊆ ∅) : d.has (s₁ ∪ s₂) := by { rw union_eq_Union, exact d.has_Union (pairwise_disjoint_on_bool.2 h) (bool.forall_bool.2 ⟨h₂, h₁⟩) } lemma has_diff {s₁ s₂ : set α} (h₁ : d.has s₁) (h₂ : d.has s₂) (h : s₂ ⊆ s₁) : d.has (s₁ \ s₂) := begin apply d.has_compl_iff.1, simp [diff_eq, compl_inter], exact d.has_union (d.has_compl h₁) h₂ (λ x ⟨h₁, h₂⟩, h₁ (h h₂)), end instance : has_le (dynkin_system α) := { le := λ m₁ m₂, m₁.has ≤ m₂.has } lemma le_def {α} {a b : dynkin_system α} : a ≤ b ↔ a.has ≤ b.has := iff.rfl instance : partial_order (dynkin_system α) := { le_refl := assume a b, le_rfl, le_trans := assume a b c hab hbc, le_def.mpr (le_trans hab hbc), le_antisymm := assume a b h₁ h₂, ext $ assume s, ⟨h₁ s, h₂ s⟩, ..dynkin_system.has_le } /-- Every measurable space (σ-algebra) forms a Dynkin system -/ def of_measurable_space (m : measurable_space α) : dynkin_system α := { has := m.measurable_set', has_empty := m.measurable_set_empty, has_compl := m.measurable_set_compl, has_Union_nat := assume f _ hf, m.measurable_set_Union f hf } lemma of_measurable_space_le_of_measurable_space_iff {m₁ m₂ : measurable_space α} : of_measurable_space m₁ ≤ of_measurable_space m₂ ↔ m₁ ≤ m₂ := iff.rfl /-- The least Dynkin system containing a collection of basic sets. This inductive type gives the underlying collection of sets. -/ inductive generate_has (s : set (set α)) : set α → Prop | basic : ∀ t ∈ s, generate_has t | empty : generate_has ∅ | compl : ∀ {a}, generate_has a → generate_has aᶜ | Union : ∀ {f : ℕ → set α}, pairwise (disjoint on f) → (∀ i, generate_has (f i)) → generate_has (⋃ i, f i) lemma generate_has_compl {C : set (set α)} {s : set α} : generate_has C sᶜ ↔ generate_has C s := by { refine ⟨_, generate_has.compl⟩, intro h, convert generate_has.compl h, simp } /-- The least Dynkin system containing a collection of basic sets. -/ def generate (s : set (set α)) : dynkin_system α := { has := generate_has s, has_empty := generate_has.empty, has_compl := assume a, generate_has.compl, has_Union_nat := assume f, generate_has.Union } lemma generate_has_def {C : set (set α)} : (generate C).has = generate_has C := rfl instance : inhabited (dynkin_system α) := ⟨generate univ⟩ /-- If a Dynkin system is closed under binary intersection, then it forms a `σ`-algebra. -/ def to_measurable_space (h_inter : ∀ s₁ s₂, d.has s₁ → d.has s₂ → d.has (s₁ ∩ s₂)) := { measurable_space . measurable_set' := d.has, measurable_set_empty := d.has_empty, measurable_set_compl := assume s h, d.has_compl h, measurable_set_Union := λ f hf, begin rw ←Union_disjointed, exact d.has_Union (disjoint_disjointed _) (λ n, disjointed_rec (λ t i h, h_inter _ _ h $ d.has_compl $ hf i) (hf n)), end } lemma of_measurable_space_to_measurable_space (h_inter : ∀ s₁ s₂, d.has s₁ → d.has s₂ → d.has (s₁ ∩ s₂)) : of_measurable_space (d.to_measurable_space h_inter) = d := ext $ assume s, iff.rfl /-- If `s` is in a Dynkin system `d`, we can form the new Dynkin system `{s ∩ t | t ∈ d}`. -/ def restrict_on {s : set α} (h : d.has s) : dynkin_system α := { has := λ t, d.has (t ∩ s), has_empty := by simp [d.has_empty], has_compl := assume t hts, have tᶜ ∩ s = ((t ∩ s)ᶜ) \ sᶜ, from set.ext $ assume x, by { by_cases x ∈ s; simp [h] }, by { rw [this], exact d.has_diff (d.has_compl hts) (d.has_compl h) (compl_subset_compl.mpr $ inter_subset_right _ _) }, has_Union_nat := assume f hd hf, begin rw [inter_comm, inter_Union], apply d.has_Union_nat, { exact λ i j h x ⟨⟨_, h₁⟩, _, h₂⟩, hd i j h ⟨h₁, h₂⟩ }, { simpa [inter_comm] using hf }, end } lemma generate_le {s : set (set α)} (h : ∀ t ∈ s, d.has t) : generate s ≤ d := λ t ht, ht.rec_on h d.has_empty (assume a _ h, d.has_compl h) (assume f hd _ hf, d.has_Union hd hf) lemma generate_has_subset_generate_measurable {C : set (set α)} {s : set α} (hs : (generate C).has s) : (generate_from C).measurable_set' s := generate_le (of_measurable_space (generate_from C)) (λ t, measurable_set_generate_from) s hs lemma generate_inter {s : set (set α)} (hs : is_pi_system s) {t₁ t₂ : set α} (ht₁ : (generate s).has t₁) (ht₂ : (generate s).has t₂) : (generate s).has (t₁ ∩ t₂) := have generate s ≤ (generate s).restrict_on ht₂, from generate_le _ $ assume s₁ hs₁, have (generate s).has s₁, from generate_has.basic s₁ hs₁, have generate s ≤ (generate s).restrict_on this, from generate_le _ $ assume s₂ hs₂, show (generate s).has (s₂ ∩ s₁), from (s₂ ∩ s₁).eq_empty_or_nonempty.elim (λ h, h.symm ▸ generate_has.empty) (λ h, generate_has.basic _ $ hs _ hs₂ _ hs₁ h), have (generate s).has (t₂ ∩ s₁), from this _ ht₂, show (generate s).has (s₁ ∩ t₂), by rwa [inter_comm], this _ ht₁ /-- **Dynkin's π-λ theorem**: Given a collection of sets closed under binary intersections, then the Dynkin system it generates is equal to the σ-algebra it generates. This result is known as the π-λ theorem. A collection of sets closed under binary intersection is called a π-system (often requiring additionnally that is is non-empty, but we drop this condition in the formalization). -/ lemma generate_from_eq {s : set (set α)} (hs : is_pi_system s) : generate_from s = (generate s).to_measurable_space (λ t₁ t₂, generate_inter hs) := le_antisymm (generate_from_le $ assume t ht, generate_has.basic t ht) (of_measurable_space_le_of_measurable_space_iff.mp $ by { rw [of_measurable_space_to_measurable_space], exact (generate_le _ $ assume t ht, measurable_set_generate_from ht) }) end dynkin_system theorem induction_on_inter {C : set α → Prop} {s : set (set α)} [m : measurable_space α] (h_eq : m = generate_from s) (h_inter : is_pi_system s) (h_empty : C ∅) (h_basic : ∀ t ∈ s, C t) (h_compl : ∀ t, measurable_set t → C t → C tᶜ) (h_union : ∀ f : ℕ → set α, pairwise (disjoint on f) → (∀ i, measurable_set (f i)) → (∀ i, C (f i)) → C (⋃ i, f i)) : ∀ ⦃t⦄, measurable_set t → C t := have eq : measurable_set = dynkin_system.generate_has s, by { rw [h_eq, dynkin_system.generate_from_eq h_inter], refl }, assume t ht, have dynkin_system.generate_has s t, by rwa [eq] at ht, this.rec_on h_basic h_empty (assume t ht, h_compl t $ by { rw [eq], exact ht }) (assume f hf ht, h_union f hf $ assume i, by { rw [eq], exact ht _ }) end measurable_space
7427f3e0aa273300493cb7b32d2e4712bffeac64
76c77df8a58af24dbf1d75c7012076a42244d728
/src/ch7.lean
bf81dc22e1634bfb8eaf17dcf3af1ade5e2dcaa8
[]
no_license
kris-brown/theorem_proving_in_lean
7a7a584ba2c657a35335dc895d49d991c997a0c9
774460c21bf857daff158210741bd88d1c8323cd
refs/heads/master
1,668,278,123,743
1,593,445,161,000
1,593,445,161,000
265,748,924
0
1
null
null
null
null
UTF-8
Lean
false
false
16,281
lean
import tactic -- Section 7.1: Enumerated Types namespace s71 inductive weekday : Type | sunday : weekday | monday : weekday | tuesday : weekday | wednesday : weekday | thursday : weekday | friday : weekday | saturday : weekday #check weekday.sunday #check weekday.monday open weekday #check sunday #check monday -- rec on def number_of_day (d : weekday) : ℕ := weekday.rec_on d 1 2 3 4 5 6 7 #reduce number_of_day weekday.sunday #reduce number_of_day weekday.monday #reduce number_of_day weekday.tuesday -- Less general, cases on def number_of_day2 (d : weekday) : ℕ := weekday.cases_on d 1 2 3 4 5 6 7 -- Group functions associated with datatype namespace weekday @[reducible] private def cases_on := @weekday.cases_on def number_of_day (d : weekday) : nat := cases_on d 1 2 3 4 5 6 7 end weekday #reduce weekday.number_of_day weekday.sunday open weekday (renaming cases_on → cases_on) #reduce number_of_day sunday #check cases_on namespace weekday def next (d : weekday) : weekday := weekday.cases_on d monday tuesday wednesday thursday friday saturday sunday def previous (d : weekday) : weekday := weekday.cases_on d saturday sunday monday tuesday wednesday thursday friday #reduce next (next tuesday) #reduce next (previous tuesday) example : next (previous tuesday) = tuesday := rfl end weekday -- Prove an invariant open weekday (renaming cases_on → cases_on) theorem next_previous (d: weekday) : next (previous d) = d := weekday.cases_on d (show next (previous sunday) = sunday, from rfl) (show next (previous monday) = monday, from rfl) (show next (previous tuesday) = tuesday, from rfl) (show next (previous wednesday) = wednesday, from rfl) (show next (previous thursday) = thursday, from rfl) (show next (previous friday) = friday, from rfl) (show next (previous saturday) = saturday, from rfl) --more succinct theorem next_previous2 (d: weekday) : next (previous d) = d := weekday.cases_on d rfl rfl rfl rfl rfl rfl rfl -- Use parallel combinator ; in tactic proof theorem next_previous3 (d: weekday) : next (previous d) = d := by apply weekday.cases_on d; refl -- standard library enum types namespace hidden inductive empty : Type inductive unit : Type | star : unit inductive bool : Type | ff : bool | tt : bool end hidden end s71 -- Section 7.2: Constructors with Arguments namespace s72 universes u v inductive prodd (α : Type u) (β : Type v) | mk : α → β → prodd inductive summ (α : Type u) (β : Type v) | inl {} : α → summ | inr {} : β → summ def fst {α : Type u} {β : Type v} (p : prodd α β) : α := prodd.rec_on p (λ a b, a) def snd {α : Type u} {β : Type v} (p : α × β) : β := prod.rec_on p (λ a b, b) def prod_example (p : bool × ℕ) : ℕ := prod.rec_on p (λ b n, cond b (2 * n) (2 * n + 1)) #reduce prod_example (tt, 3) #reduce prod_example (ff, 3) def sum_example (s : ℕ ⊕ ℕ) : ℕ := sum.cases_on s (λ n, 2 * n) (λ n, 2 * n + 1) #reduce sum_example (sum.inl 3) #reduce sum_example (sum.inr 3) -- simultaneously introduces the inductive type, prod, its constructor, mk, the usual eliminators (rec and rec_on), as well as the projections, fst and snd, as defined above. structure prod3 (α β : Type) := mk :: (fst : α) (snd : β) structure color := (red : nat) (green : nat) (blue : nat) def yellow := color.mk 255 255 0 #reduce color.red yellow structure Semigroup := (carrier : Type u) (mul : carrier → carrier → carrier) (mul_assoc : ∀ a b c, mul (mul a b) c = mul a (mul b c)) inductive sigma {α : Type u} (β : α → Type v) | dpair : Π a : α, β a → sigma inductive option (α : Type u) | none {} : option | some : α → option inductive inhabited (α : Type u) | mk : α → inhabited end s72 -- Section 7.3: Inductively defined propositions namespace s73 inductive false : Prop inductive true : Prop | intro : true inductive and (a b : Prop) : Prop | intro : a → b → and inductive or (a b : Prop) : Prop | intro_left : a → or | intro_right : b → or universe u inductive Exists {α : Type u} (p : α → Prop) : Prop | intro : ∀ (a : α), p a → Exists def exists.intro := @Exists.intro -- false, true, and, + or are perfectly analogous to the definitions of empty, unit, prod, and sum. --difference is that the first group yields elements of Prop, and the second yields elements of Type u -- sort of a hybrid between ∃ x : α, P and Σ x : α, P. inductive subtype {α : Type u} (p : α → Prop) | mk : Π x : α, p x → subtype section structure subtype2 {α : Sort u} (p : α → Prop) := (val : α) (property : p val) variables {α : Type u} (p : α → Prop) #check subtype2 p #check { x : α // p x} end end s73 -- Section 7.4: Defining the nats namespace s74 inductive nat : Type | zero : nat | succ : nat → nat #check @nat.rec_on -- 'motive C', major premise n, and two minor premises namespace nat def add (m n : nat) : nat := nat.rec_on n m (λ _ add_m_n, succ add_m_n) -- try it out #reduce add (succ zero) (succ (succ zero)) instance : has_zero nat := has_zero.mk zero instance : has_add nat := has_add.mk add theorem add_zero (m : nat) : m + 0 = m := rfl theorem add_succ (m n : nat) : m + succ n = succ (m + n) := rfl theorem zero_add (n : nat) : 0 + n = n := nat.rec_on n (show 0 + zero = zero, from rfl) (assume n, assume ih : 0 + n = n, show 0 + succ n = succ n, from calc 0 + succ n = succ (0 + n) : rfl ... = succ n : by rw ih) theorem zero_add' (n : nat) : 0 + n = n := nat.rec_on n rfl (λ n ih, by rw [add_succ, ih]) theorem zero_add''(n : nat) : 0 + n = n := nat.rec_on n rfl (λ n ih, by simp only [add_succ, ih]) theorem add_assoc (m n k : nat) : m + n + k = m + (n + k) := nat.rec_on k (show m + n + 0 = m + (n + 0), from rfl) (assume k, assume ih : m + n + k = m + (n + k), show m + n + succ k = m + (n + succ k), from calc m + n + succ k = succ (m + n + k) : rfl ... = succ (m + (n + k)) : by rw ih ... = m + succ (n + k) : rfl ... = m + (n + succ k) : rfl) theorem add_assoc' (m n k : nat) : m + n + k = m + (n + k) := nat.rec_on k rfl (λ k ih, by simp only [add_succ, ih]) theorem succ_add (m n : nat) : succ m + n = succ (m + n) := nat.rec_on n (show succ m + 0 = succ (m + 0), from rfl) (assume n, assume ih : succ m + n = succ (m + n), show succ m + succ n = succ (m + succ n), from calc succ m + succ n = succ (succ m + n) : rfl ... = succ (succ (m + n)) : by rw ih ... = succ (m + succ n) : rfl) theorem succ_add' (m n : nat) : succ m + n = succ (m + n) := nat.rec_on n rfl (λ n ih, by simp only [add_succ, ih]) theorem add_comm (m n : nat) : m + n = n + m := nat.rec_on n (show m + 0 = 0 + m, by rw [nat.zero_add, nat.add_zero]) (assume n, assume ih : m + n = n + m, calc m + succ n = succ (m + n) : rfl ... = succ (n + m) : by rw ih ... = succ n + m : by rw succ_add) end nat end s74 -- Section 7.5: Other recursive datatypes namespace s75 universe u inductive list (α : Type u) | nil {} : list | cons : α → list → list namespace list variable {α : Type} notation h :: t := cons h t def append (s t : list α) : list α := list.rec t (λ x l u, x::u) s notation s ++ t := append s t theorem nil_append (t : list α) : nil ++ t = t := rfl theorem cons_append (x : α) (s t : list α) : x::s ++ t = x::(s ++ t) := rfl notation `[` l:(foldr `,` (h t, cons h t) nil) `]` := l section open nat #check [1, 2, 3, 4, 5] #check ([1, 2, 3, 4, 5] : list int) end end list inductive binary_tree | leaf : binary_tree | node : binary_tree → binary_tree → binary_tree inductive cbtree | leaf : cbtree | sup : (ℕ → cbtree) → cbtree namespace cbtree def succ (t : cbtree) : cbtree := sup (λ n, t) def omega : cbtree := sup (λ n, nat.rec_on n leaf (λ n t, succ t)) end cbtree end s75 -- Section 7.6: Tactics for inductive types namespace s76 open nat variable p : ℕ → Prop example (hz : p 0) (hs : ∀ n, p (succ n)) : ∀ n, p n := begin intro n, cases n, { exact hz }, -- goal is p 0 apply hs -- goal is a : ℕ ⊢ p (succ a) end example (n : ℕ) (h : n ≠ 0) : succ (pred n) = n := begin cases n with m, -- first goal: h : 0 ≠ 0 ⊢ succ (pred 0) = 0 { apply (absurd rfl h) }, -- second goal: h : succ m ≠ 0 ⊢ succ (pred (succ a)) = succ a reflexivity end def f37 (n : ℕ) : ℕ := begin cases n, exact 3, exact 7 end example : f37 0 = 3 := rfl example : f37 5 = 7 := rfl universe u def tuple (α : Type u) (n : ℕ) := { l : list α // list.length l = n } variables {α : Type u} {n : ℕ} def f {n : ℕ} (t : tuple α n) : ℕ := begin cases n, exact 3, exact 7 end def myList : list ℕ := 0 :: 1 :: 2 :: list.nil def my_tuple : tuple ℕ 3 := ⟨myList, rfl⟩ def my_tuple2 : tuple ℕ 0 := ⟨list.nil, rfl⟩ example : f my_tuple = 7 := rfl example : f my_tuple2 = 3 := rfl inductive foo : Type | bar1 : ℕ → ℕ → foo | bar2 : ℕ → ℕ → ℕ → foo def silly (x : foo) : ℕ := begin cases x with a b c d e, exact b, -- a, b are in the context exact e -- c, d, e are in the context end --Difficult to keep track of which variables are associated w/ which case -- Same as above but better syntax def silly' (x : foo) : ℕ := begin cases x, case foo.bar2 : c d e -- Can do in any order { exact e }, case foo.bar1 : a b { exact b } end --Cases on an arbitrary expr open nat variable natprop : ℕ → Prop example (hz : natprop 0) (hs : ∀ n, natprop (succ n)) (m k : ℕ) : natprop (m + 3 * k) := begin cases (m + 3 * k), { exact hz }, -- goal is natprop 0 apply hs -- goal is a : ℕ ⊢ natprop (succ a) end -- above is equivalent to this example (hz : natprop 0) (hs : ∀ n, natprop (succ n)) (m k : ℕ) : natprop (m + 3 * k) := begin generalize : (m + 3 * k) = n, cases n, { exact hz }, -- goal is natprop 0 apply hs -- goal is a : ℕ ⊢ natprop (succ a) end example (p : Prop) (m n : ℕ) (h₁ : m < n → p) (h₂ : m ≥ n → p) : p := begin cases lt_or_ge m n with hlt hge, { exact h₁ hlt }, exact h₂ hge end #check nat.sub_self example (m n : ℕ) : m - n = 0 ∨ m ≠ n := begin cases decidable.em (m = n) with heq hne, { rw heq, left, exact nat.sub_self n }, right, exact hne end def f' (m k : ℕ) : ℕ := begin cases m - k, exact 3, exact 7 end example : f' 5 7 = 3 := rfl example : f' 10 2 = 7 := rfl -- Induction instead of 'cases' theorem zero_add (n : ℕ) : 0 + n = n := begin induction n with n ih, refl, rw [add_succ, ih] end theorem zero_add' (n : ℕ) : 0 + n = n := begin induction n, case zero : { refl }, case succ : n ih { rw [add_succ, ih]} end theorem succ_add (m n : ℕ) : succ m + n = succ (m + n) := begin induction n, case zero : { refl }, case succ : n ih { rw [add_succ, ih] } end theorem add_comm (m n : ℕ) : m + n = n + m := begin induction n, case zero : { rw zero_add, refl }, case succ : n ih { rw [add_succ, ih, succ_add] } end theorem zero_add'' (n : ℕ) : 0 + n = n := by induction n; simp only [*, add_zero, add_succ] theorem succ_add' (m n : ℕ) : succ m + n = succ (m + n) := by induction n; simp only [*, add_zero, add_succ] theorem add_comm' (m n : ℕ) : m + n = n + m := by induction n; simp only [*, add_zero, add_succ, succ_add, zero_add] theorem add_assoc (m n k : ℕ) : m + n + k = m + (n + k) := by induction k; simp only [*, add_zero, add_succ] -- Injectivity of the IDT constructors example (m n k : ℕ) (h : succ (succ m) = succ (succ n)) : n + k = m + k := begin injection h with h', injection h' with h'', rw h'' end example (m n k : ℕ) (h : succ (succ m) = succ (succ n)) : n + k = m + k := begin injections with h' h'', rw h'' end example (m n k : ℕ) (h : succ (succ m) = succ (succ n)) : n + k = m + k := by injections; simp * example (m n : ℕ) (h : succ m = 0) : n = n + 7 := by injections example (m n : ℕ) (h : succ m = 0) : n = n + 7 := by contradiction example (h : 7 = 4) : false := by injections end s76 -- Section 7.7: inductive families namespace s77 universe u open nat inductive vector (α : Type u) : nat → Type u | nil {} : vector zero | cons {n : ℕ} (a : α) (v : vector n) : vector (succ n) inductive eq {α : Sort u} (a : α) : α → Prop | refl : eq a @[elab_as_eliminator] theorem subst {α : Type u} {a b : α} {p : α → Prop} (h₁ : eq a b) (h₂ : p a) : p b := eq.rec h₂ h₁ #check subst theorem symm {α : Type u} {a b : α} (h : eq a b) : eq b a := subst h (eq.refl a) end s77 -- Section 7.9: mutual and nested inductive types namespace s79 mutual inductive even, odd with even : ℕ → Prop | even_zero : even 0 | even_succ : ∀ n, odd n → even (n + 1) with odd : ℕ → Prop | odd_succ : ∀ n, even n → odd (n + 1) universe u mutual inductive tree, list_tree (α : Type u) with tree : Type u | node : α → list_tree → tree with list_tree : Type u | nil {} : list_tree | cons : tree → list_tree → list_tree -- this is much more convenient, does the same thing under the hood (allowing us to use list theorems) inductive tree' (α : Type u) | mk : α → list tree' → tree' end s79 -- Exercises namespace s7x -- 1 --define multiplication, the predecessor function, truncated subtraction, and exponentiation namespace nat def mult (m n : ℕ) : ℕ := nat.rec_on n 0 (λ _ add_m_n, m + add_m_n) #reduce mult 6 4 def pred (n : nat) : nat := nat.rec_on n 0 (λ n pred_n, n) #reduce pred 21 def tsub (m n : nat) : nat := nat.rec_on n m (λ n tsub_m_n, pred tsub_m_n) #reduce tsub 21 4 def exp (m n : nat) : nat := nat.rec_on n 1 (λ n exp_m_n, mult m exp_m_n) #reduce exp 3 4 end nat --2a variable {α : Type} open list --lemma append_nil (t : list α) : t ++ nil = t := list.append_nil example (s t : list α) : length (s ++ t) = length s + length t := list.rec_on t (show length (s ++ nil) = length s + length nil, by calc length (s ++ nil) = length s : by rw append_nil ... = length s + length nil : by refl) (assume x : α, assume y : list α , assume ih : length (s ++ y) = length (s) + length(y), show length (s ++ x::y) = length (s) + length(x::y), by calc length (s ++ x::y) = length (s ++ y) + 1 : by simp ... = length (s) + length(x::y): by simp ) example (t : list α) : list.length (list.reverse t) = list.length t := sorry example (t : list α) : list.reverse (list.reverse t) = t := sorry -- 2b implement the following theorem append_nil (t : list α) : t ++ list.nil = t := list.rec_on t (show nil ++ nil = nil, by refl) (assume x : α, assume y : list α, assume ih : y ++ nil = y, show x::y ++ nil = x::y , by {injections; simp}) theorem append_assoc (r s t : list α) : r ++ s ++ t = r ++ (s ++ t) := sorry --3 --4 --5 theorem trans {α : Type u} {a b c : α} (h₁ : eq a b) (h₂ : eq b c) : eq a c := sorry theorem congr {α β : Type u} {a b : α} (f : α → β) (h : eq a b) : eq (f a) (f b) := sorry end s7x
ae175a92b63423551ff81fb0c05da352a0ed88aa
b7f22e51856f4989b970961f794f1c435f9b8f78
/tests/lean/run/refine2.lean
1694579422658bc6a6ba5663bb72bb91bde50fa4
[ "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
157
lean
import logic example {A : Type} (f : A → A) (a b : A) : f a = b → f (f a) = f b := begin intro fa_eq_b, refine (congr_arg f _), exact fa_eq_b end
7cfabbd4bb4a56c8226d4a5c607ded43c6c22b5a
75bd9c50a345718d735a7533c007cf45f9da9a83
/src/data/mv_polynomial/basic.lean
70ddb3f7ebf7c6195596a8d48861ff6298fbd8dd
[ "Apache-2.0" ]
permissive
jtbarker/mathlib
a1a3b1ddc16179826260578410746756ef18032c
392d3e376b44265ef2dedbd92231d3177acc1fd0
refs/heads/master
1,671,246,411,096
1,600,801,712,000
1,600,801,712,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
34,623
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Johan Commelin, Mario Carneiro -/ import data.polynomial.eval /-! # Multivariate polynomials This file defines polynomial rings over a base ring (or even semiring), with variables from a general type `σ` (which could be infinite). ## Important definitions Let `R` be a commutative ring (or a semiring) and let `σ` be an arbitrary type. This file creates the type `mv_polynomial σ R`, which mathematicians might denote $R[X_i : i \in σ]$. It is the type of multivariate (a.k.a. multivariable) polynomials, with variables corresponding to the terms in `σ`, and coefficients in `R`. ### Notation In the definitions below, we use the following notation: + `σ : Type*` (indexing the variables) + `R : Type*` `[comm_semiring R]` (the coefficients) + `s : σ →₀ ℕ`, a function from `σ` to `ℕ` which is zero away from a finite set. This will give rise to a monomial in `mv_polynomial σ R` which mathematicians might call `X^s` + `a : R` + `i : σ`, with corresponding monomial `X i`, often denoted `X_i` by mathematicians + `p : mv_polynomial σ R` ### Definitions * `mv_polynomial σ R` : the type of polynomials with variables of type `σ` and coefficients in the commutative semiring `R` * `monomial s a` : the monomial which mathematically would be denoted `a * X^s` * `C a` : the constant polynomial with value `a` * `X i` : the degree one monomial corresponding to i; mathematically this might be denoted `Xᵢ`. * `coeff s p` : the coefficient of `s` in `p`. * `eval₂ (f : R → S₁) (g : σ → S₁) p` : given a semiring homomorphism from `R` to another semiring `S₁`, and a map `σ → S₁`, evaluates `p` at this valuation, returning a term of type `S₁`. Note that `eval₂` can be made using `eval` and `map` (see below), and it has been suggested that sticking to `eval` and `map` might make the code less brittle. * `eval (g : σ → R) p` : given a map `σ → R`, evaluates `p` at this valuation, returning a term of type `R` * `map (f : R → S₁) p` : returns the multivariate polynomial obtained from `p` by the change of coefficient semiring corresponding to `f` ## Implementation notes Recall that if `Y` has a zero, then `X →₀ Y` is the type of functions from `X` to `Y` with finite support, i.e. such that only finitely many elements of `X` get sent to non-zero terms in `Y`. The definition of `mv_polynomial σ R` is `(σ →₀ ℕ) →₀ R` ; here `σ →₀ ℕ` denotes the space of all monomials in the variables, and the function to `R` sends a monomial to its coefficient in the polynomial being represented. ## Tags polynomial, multivariate polynomial, multivariable polynomial S₁ S₂ S₃ -/ noncomputable theory open_locale classical big_operators open set function finsupp add_monoid_algebra open_locale big_operators universes u v w x variables {R : Type u} {S₁ : Type v} {S₂ : Type w} {S₃ : Type x} /-- Multivariate polynomial, where `σ` is the index set of the variables and `R` is the coefficient ring -/ def mv_polynomial (σ : Type*) (R : Type*) [comm_semiring R] := add_monoid_algebra R (σ →₀ ℕ) namespace mv_polynomial variables {σ : Type*} {a a' a₁ a₂ : R} {e : ℕ} {n m : σ} {s : σ →₀ ℕ} section comm_semiring variables [comm_semiring R] {p q : mv_polynomial σ R} instance decidable_eq_mv_polynomial [decidable_eq σ] [decidable_eq R] : decidable_eq (mv_polynomial σ R) := finsupp.decidable_eq instance : comm_semiring (mv_polynomial σ R) := add_monoid_algebra.comm_semiring instance : inhabited (mv_polynomial σ R) := ⟨0⟩ instance : has_scalar R (mv_polynomial σ R) := add_monoid_algebra.has_scalar instance : semimodule R (mv_polynomial σ R) := add_monoid_algebra.semimodule instance : algebra R (mv_polynomial σ R) := add_monoid_algebra.algebra /-- the coercion turning an `mv_polynomial` into the function which reports the coefficient of a given monomial -/ def coeff_coe_to_fun : has_coe_to_fun (mv_polynomial σ R) := finsupp.has_coe_to_fun local attribute [instance] coeff_coe_to_fun /-- `monomial s a` is the monomial `a * X^s` -/ def monomial (s : σ →₀ ℕ) (a : R) : mv_polynomial σ R := single s a /-- `C a` is the constant polynomial with value `a` -/ def C : R →+* mv_polynomial σ R := { to_fun := monomial 0, map_zero' := by simp [monomial], map_one' := rfl, map_add' := λ a a', single_add, map_mul' := λ a a', by simp [monomial, single_mul_single] } variables (R σ) theorem algebra_map_eq : algebra_map R (mv_polynomial σ R) = C := rfl variables {R σ} /-- `X n` is the degree `1` monomial `1*n` -/ def X (n : σ) : mv_polynomial σ R := monomial (single n 1) 1 @[simp] lemma C_0 : C 0 = (0 : mv_polynomial σ R) := by simp [C, monomial]; refl @[simp] lemma C_1 : C 1 = (1 : mv_polynomial σ R) := rfl lemma C_mul_monomial : C a * monomial s a' = monomial s (a * a') := by simp [C, monomial, single_mul_single] @[simp] lemma C_add : (C (a + a') : mv_polynomial σ R) = C a + C a' := single_add @[simp] lemma C_mul : (C (a * a') : mv_polynomial σ R) = C a * C a' := C_mul_monomial.symm @[simp] lemma C_pow (a : R) (n : ℕ) : (C (a^n) : mv_polynomial σ R) = (C a)^n := by induction n; simp [pow_succ, *] lemma C_injective (σ : Type*) (R : Type*) [comm_ring R] : function.injective (C : R → mv_polynomial σ R) := finsupp.single_injective _ @[simp] lemma C_inj {σ : Type*} (R : Type*) [comm_ring R] (r s : R) : (C r : mv_polynomial σ R) = C s ↔ r = s := (C_injective σ R).eq_iff lemma C_eq_coe_nat (n : ℕ) : (C ↑n : mv_polynomial σ R) = n := by induction n; simp [nat.succ_eq_add_one, *] theorem C_mul' : mv_polynomial.C a * p = a • p := begin apply finsupp.induction p, { exact (mul_zero $ mv_polynomial.C a).trans (@smul_zero R (mv_polynomial σ R) _ _ _ a).symm }, intros p b f haf hb0 ih, rw [mul_add, ih, @smul_add R (mv_polynomial σ R) _ _ _ a], congr' 1, rw [add_monoid_algebra.mul_def, finsupp.smul_single], simp only [mv_polynomial.C], dsimp [mv_polynomial.monomial], rw [finsupp.sum_single_index, finsupp.sum_single_index, zero_add], { rw [mul_zero, finsupp.single_zero] }, { rw finsupp.sum_single_index, all_goals { rw [zero_mul, finsupp.single_zero] }, } end lemma smul_eq_C_mul (p : mv_polynomial σ R) (a : R) : a • p = C a * p := C_mul'.symm lemma X_pow_eq_single : X n ^ e = monomial (single n e) (1 : R) := begin induction e, { simp [X], refl }, { simp [pow_succ, e_ih], simp [X, monomial, single_mul_single, nat.succ_eq_add_one, add_comm] } end lemma monomial_add_single : monomial (s + single n e) a = (monomial s a * X n ^ e) := by rw [X_pow_eq_single, monomial, monomial, monomial, single_mul_single]; simp lemma monomial_single_add : monomial (single n e + s) a = (X n ^ e * monomial s a) := by rw [X_pow_eq_single, monomial, monomial, monomial, single_mul_single]; simp lemma single_eq_C_mul_X {s : σ} {a : R} {n : ℕ} : monomial (single s n) a = C a * (X s)^n := by { rw [← zero_add (single s n), monomial_add_single, C], refl } @[simp] lemma monomial_add {s : σ →₀ ℕ} {a b : R} : monomial s a + monomial s b = monomial s (a + b) := by simp [monomial] @[simp] lemma monomial_mul {s s' : σ →₀ ℕ} {a b : R} : monomial s a * monomial s' b = monomial (s + s') (a * b) := by rw [monomial, monomial, monomial, add_monoid_algebra.single_mul_single] @[simp] lemma monomial_zero {s : σ →₀ ℕ}: monomial s (0 : R) = 0 := by rw [monomial, single_zero]; refl @[simp] lemma sum_monomial {A : Type*} [add_comm_monoid A] {u : σ →₀ ℕ} {r : R} {b : (σ →₀ ℕ) → R → A} (w : b u 0 = 0) : sum (monomial u r) b = b u r := sum_single_index w lemma monomial_eq : monomial s a = C a * (s.prod $ λn e, X n ^ e : mv_polynomial σ R) := begin apply @finsupp.induction σ ℕ _ _ s, { simp only [C, prod_zero_index]; exact (mul_one _).symm }, { assume n e s hns he ih, rw [monomial_single_add, ih, prod_add_index, prod_single_index, mul_left_comm], { simp only [pow_zero], }, { intro a, simp only [pow_zero], }, { intros, rw pow_add, }, } end @[recursor 5] lemma induction_on {M : mv_polynomial σ R → Prop} (p : mv_polynomial σ R) (h_C : ∀a, M (C a)) (h_add : ∀p q, M p → M q → M (p + q)) (h_X : ∀p n, M p → M (p * X n)) : M p := have ∀s a, M (monomial s a), begin assume s a, apply @finsupp.induction σ ℕ _ _ s, { show M (monomial 0 a), from h_C a, }, { assume n e p hpn he ih, have : ∀e:ℕ, M (monomial p a * X n ^ e), { intro e, induction e, { simp [ih] }, { simp [ih, pow_succ', (mul_assoc _ _ _).symm, h_X, e_ih] } }, simp [add_comm, monomial_add_single, this] } end, finsupp.induction p (by have : M (C 0) := h_C 0; rwa [C_0] at this) (assume s a p hsp ha hp, h_add _ _ (this s a) hp) theorem induction_on' {P : mv_polynomial σ R → Prop} (p : mv_polynomial σ R) (h1 : ∀ (u : σ →₀ ℕ) (a : R), P (monomial u a)) (h2 : ∀ (p q : mv_polynomial σ R), P p → P q → P (p + q)) : P p := finsupp.induction p (suffices P (monomial 0 0), by rwa monomial_zero at this, show P (monomial 0 0), from h1 0 0) (λ a b f ha hb hPf, h2 _ _ (h1 _ _) hPf) lemma hom_eq_hom [semiring S₂] (f g : mv_polynomial σ R →+* S₂) (hC : ∀a:R, f (C a) = g (C a)) (hX : ∀n:σ, f (X n) = g (X n)) (p : mv_polynomial σ R) : f p = g p := mv_polynomial.induction_on p hC begin assume p q hp hq, rw [is_semiring_hom.map_add f, is_semiring_hom.map_add g, hp, hq] end begin assume p n hp, rw [is_semiring_hom.map_mul f, is_semiring_hom.map_mul g, hp, hX] end lemma is_id (f : mv_polynomial σ R →+* mv_polynomial σ R) (hC : ∀a:R, f (C a) = (C a)) (hX : ∀n:σ, f (X n) = (X n)) (p : mv_polynomial σ R) : f p = p := hom_eq_hom f (ring_hom.id _) hC hX p lemma ring_hom_ext {A : Type*} [comm_semiring A] (f g : mv_polynomial σ R →+* A) (hC : ∀ r, f (C r) = g (C r)) (hX : ∀ i, f (X i) = g (X i)) : f = g := begin ext p : 1, apply mv_polynomial.induction_on' p, { intros m r, rw [monomial_eq, finsupp.prod], simp only [monomial_eq, ring_hom.map_mul, ring_hom.map_prod, ring_hom.map_pow, hC, hX], }, { intros p q hp hq, simp only [ring_hom.map_add, hp, hq] } end lemma alg_hom_ext {A : Type*} [comm_semiring A] [algebra R A] (f g : mv_polynomial σ R →ₐ[R] A) (hf : ∀ i : σ, f (X i) = g (X i)) : f = g := begin apply alg_hom.coe_ring_hom_injective, apply ring_hom_ext, { intro r, calc f (C r) = algebra_map R A r : f.commutes r ... = g (C r) : (g.commutes r).symm }, { simpa only [hf] }, end @[simp] lemma alg_hom_C (f : mv_polynomial σ R →ₐ[R] mv_polynomial σ R) (r : R) : f (C r) = C r := f.commutes r section coeff section -- While setting up `coeff`, we make `mv_polynomial` reducible so we can treat it as a function. local attribute [reducible] mv_polynomial /-- The coefficient of the monomial `m` in the multi-variable polynomial `p`. -/ def coeff (m : σ →₀ ℕ) (p : mv_polynomial σ R) : R := p m end lemma ext (p q : mv_polynomial σ R) : (∀ m, coeff m p = coeff m q) → p = q := ext lemma ext_iff (p q : mv_polynomial σ R) : p = q ↔ (∀ m, coeff m p = coeff m q) := ⟨ λ h m, by rw h, ext p q⟩ @[simp] lemma coeff_add (m : σ →₀ ℕ) (p q : mv_polynomial σ R) : coeff m (p + q) = coeff m p + coeff m q := add_apply @[simp] lemma coeff_zero (m : σ →₀ ℕ) : coeff m (0 : mv_polynomial σ R) = 0 := rfl @[simp] lemma coeff_zero_X (i : σ) : coeff 0 (X i : mv_polynomial σ R) = 0 := single_eq_of_ne (λ h, by cases single_eq_zero.1 h) instance coeff.is_add_monoid_hom (m : σ →₀ ℕ) : is_add_monoid_hom (coeff m : mv_polynomial σ R → R) := { map_add := coeff_add m, map_zero := coeff_zero m } lemma coeff_sum {X : Type*} (s : finset X) (f : X → mv_polynomial σ R) (m : σ →₀ ℕ) : coeff m (∑ x in s, f x) = ∑ x in s, coeff m (f x) := (s.sum_hom _).symm lemma monic_monomial_eq (m) : monomial m (1:R) = (m.prod $ λn e, X n ^ e : mv_polynomial σ R) := by simp [monomial_eq] @[simp] lemma coeff_monomial (m n) (a) : coeff m (monomial n a : mv_polynomial σ R) = if n = m then a else 0 := by convert single_apply @[simp] lemma coeff_C (m) (a) : coeff m (C a : mv_polynomial σ R) = if 0 = m then a else 0 := by convert single_apply lemma coeff_X_pow (i : σ) (m) (k : ℕ) : coeff m (X i ^ k : mv_polynomial σ R) = if single i k = m then 1 else 0 := begin have := coeff_monomial m (finsupp.single i k) (1:R), rwa [@monomial_eq _ _ (1:R) (finsupp.single i k) _, C_1, one_mul, finsupp.prod_single_index] at this, exact pow_zero _ end lemma coeff_X' (i : σ) (m) : coeff m (X i : mv_polynomial σ R) = if single i 1 = m then 1 else 0 := by rw [← coeff_X_pow, pow_one] @[simp] lemma coeff_X (i : σ) : coeff (single i 1) (X i : mv_polynomial σ R) = 1 := by rw [coeff_X', if_pos rfl] @[simp] lemma coeff_C_mul (m) (a : R) (p : mv_polynomial σ R) : coeff m (C a * p) = a * coeff m p := begin rw [mul_def], simp only [C, monomial], dsimp, rw [monomial], rw sum_single_index, { simp only [zero_add], convert sum_apply, simp only [single_apply, finsupp.sum], rw finset.sum_eq_single m, { rw if_pos rfl, refl }, { intros m' hm' H, apply if_neg, exact H }, { intros hm, rw if_pos rfl, rw not_mem_support_iff at hm, simp [hm] } }, simp only [zero_mul, single_zero, zero_add, sum_zero], end lemma coeff_mul (p q : mv_polynomial σ R) (n : σ →₀ ℕ) : coeff n (p * q) = ∑ x in (antidiagonal n).support, coeff x.1 p * coeff x.2 q := begin rw mul_def, have := @finset.sum_sigma (σ →₀ ℕ) R _ _ p.support (λ _, q.support) (λ x, if (x.1 + x.2 = n) then coeff x.1 p * coeff x.2 q else 0), convert this.symm using 1; clear this, { rw [coeff], repeat {rw sum_apply, apply finset.sum_congr rfl, intros, dsimp only}, convert single_apply }, { have : (antidiagonal n).support.filter (λ x, x.1 ∈ p.support ∧ x.2 ∈ q.support) ⊆ (antidiagonal n).support := finset.filter_subset _, rw [← finset.sum_sdiff this, finset.sum_eq_zero, zero_add], swap, { intros x hx, rw [finset.mem_sdiff, not_iff_not_of_iff (finset.mem_filter), not_and, not_and, not_mem_support_iff] at hx, by_cases H : x.1 ∈ p.support, { rw [coeff, coeff, hx.2 hx.1 H, mul_zero] }, { rw not_mem_support_iff at H, rw [coeff, H, zero_mul] } }, symmetry, rw [← finset.sum_sdiff (finset.filter_subset _), finset.sum_eq_zero, zero_add], swap, { intros x hx, rw [finset.mem_sdiff, not_iff_not_of_iff (finset.mem_filter), not_and] at hx, simp only [if_neg (hx.2 hx.1)] }, { apply finset.sum_bij, swap 5, { intros x hx, exact (x.1, x.2) }, { intros x hx, rw [finset.mem_filter, finset.mem_sigma] at hx, simpa [finset.mem_filter, mem_antidiagonal_support] using hx.symm }, { intros x hx, rw finset.mem_filter at hx, simp only [if_pos hx.2], }, { rintros ⟨i,j⟩ ⟨k,l⟩ hij hkl, simpa using and.intro }, { rintros ⟨i,j⟩ hij, refine ⟨⟨i,j⟩, _, _⟩, { apply_instance }, { rw [finset.mem_filter, mem_antidiagonal_support] at hij, simpa [finset.mem_filter, finset.mem_sigma] using hij.symm }, { refl } } }, all_goals { apply_instance } } end @[simp] lemma coeff_mul_X (m) (s : σ) (p : mv_polynomial σ R) : coeff (m + single s 1) (p * X s) = coeff m p := begin have : (m, single s 1) ∈ (m + single s 1).antidiagonal.support := mem_antidiagonal_support.2 rfl, rw [coeff_mul, ← finset.insert_erase this, finset.sum_insert (finset.not_mem_erase _ _), finset.sum_eq_zero, add_zero, coeff_X, mul_one], rintros ⟨i,j⟩ hij, rw [finset.mem_erase, mem_antidiagonal_support] at hij, by_cases H : single s 1 = j, { subst j, simpa using hij }, { rw [coeff_X', if_neg H, mul_zero] }, end lemma coeff_mul_X' (m) (s : σ) (p : mv_polynomial σ R) : coeff m (p * X s) = if s ∈ m.support then coeff (m - single s 1) p else 0 := begin split_ifs with h h, { conv_rhs {rw ← coeff_mul_X _ s}, congr' with t, by_cases hj : s = t, { subst t, simp only [nat_sub_apply, add_apply, single_eq_same], refine (nat.sub_add_cancel $ nat.pos_of_ne_zero _).symm, rwa mem_support_iff at h }, { simp [single_eq_of_ne hj] } }, { delta coeff, rw ← not_mem_support_iff, intro hm, apply h, have H := support_mul _ _ hm, simp only [finset.mem_bind] at H, rcases H with ⟨j, hj, i', hi', H⟩, delta X monomial at hi', rw mem_support_single at hi', cases hi', subst i', erw finset.mem_singleton at H, subst m, rw [mem_support_iff, add_apply, single_apply, if_pos rfl], intro H, rw [_root_.add_eq_zero_iff] at H, exact one_ne_zero H.2 } end lemma eq_zero_iff {p : mv_polynomial σ R} : p = 0 ↔ ∀ d, coeff d p = 0 := by { rw ext_iff, simp only [coeff_zero], } lemma ne_zero_iff {p : mv_polynomial σ R} : p ≠ 0 ↔ ∃ d, coeff d p ≠ 0 := by { rw [ne.def, eq_zero_iff], push_neg, } lemma exists_coeff_ne_zero {p : mv_polynomial σ R} (h : p ≠ 0) : ∃ d, coeff d p ≠ 0 := ne_zero_iff.mp h end coeff section constant_coeff /-- `constant_coeff p` returns the constant term of the polynomial `p`, defined as `coeff 0 p`. This is a ring homomorphism. -/ def constant_coeff : mv_polynomial σ R →+* R := { to_fun := coeff 0, map_one' := by simp [coeff, add_monoid_algebra.one_def], map_mul' := by simp [coeff_mul, finsupp.support_single_ne_zero], map_zero' := coeff_zero _, map_add' := coeff_add _ } lemma constant_coeff_eq : (constant_coeff : mv_polynomial σ R → R) = coeff 0 := rfl @[simp] lemma constant_coeff_C (r : R) : constant_coeff (C r : mv_polynomial σ R) = r := by simp [constant_coeff_eq] @[simp] lemma constant_coeff_X (i : σ) : constant_coeff (X i : mv_polynomial σ R) = 0 := by simp [constant_coeff_eq] lemma constant_coeff_monomial (d : σ →₀ ℕ) (r : R) : constant_coeff (monomial d r) = if d = 0 then r else 0 := by rw [constant_coeff_eq, coeff_monomial] end constant_coeff section as_sum @[simp] lemma support_sum_monomial_coeff (p : mv_polynomial σ R) : ∑ v in p.support, monomial v (coeff v p) = p := finsupp.sum_single p lemma as_sum (p : mv_polynomial σ R) : p = ∑ v in p.support, monomial v (coeff v p) := (support_sum_monomial_coeff p).symm end as_sum section eval₂ variables [comm_semiring S₁] variables (f : R →+* S₁) (g : σ → S₁) /-- Evaluate a polynomial `p` given a valuation `g` of all the variables and a ring hom `f` from the scalar ring to the target -/ def eval₂ (p : mv_polynomial σ R) : S₁ := p.sum (λs a, f a * s.prod (λn e, g n ^ e)) lemma eval₂_eq (g : R →+* S₁) (x : σ → S₁) (f : mv_polynomial σ R) : f.eval₂ g x = ∑ d in f.support, g (f.coeff d) * ∏ i in d.support, x i ^ d i := rfl lemma eval₂_eq' [fintype σ] (g : R →+* S₁) (x : σ → S₁) (f : mv_polynomial σ R) : f.eval₂ g x = ∑ d in f.support, g (f.coeff d) * ∏ i, x i ^ d i := by { simp only [eval₂_eq, ← finsupp.prod_pow], refl } @[simp] lemma eval₂_zero : (0 : mv_polynomial σ R).eval₂ f g = 0 := finsupp.sum_zero_index section @[simp] lemma eval₂_add : (p + q).eval₂ f g = p.eval₂ f g + q.eval₂ f g := finsupp.sum_add_index (by simp [is_semiring_hom.map_zero f]) (by simp [add_mul, is_semiring_hom.map_add f]) @[simp] lemma eval₂_monomial : (monomial s a).eval₂ f g = f a * s.prod (λn e, g n ^ e) := finsupp.sum_single_index (by simp [is_semiring_hom.map_zero f]) @[simp] lemma eval₂_C (a) : (C a).eval₂ f g = f a := by simp [eval₂_monomial, C, prod_zero_index] @[simp] lemma eval₂_one : (1 : mv_polynomial σ R).eval₂ f g = 1 := (eval₂_C _ _ _).trans (is_semiring_hom.map_one f) @[simp] lemma eval₂_X (n) : (X n).eval₂ f g = g n := by simp [eval₂_monomial, is_semiring_hom.map_one f, X, prod_single_index, pow_one] lemma eval₂_mul_monomial : ∀{s a}, (p * monomial s a).eval₂ f g = p.eval₂ f g * f a * s.prod (λn e, g n ^ e) := begin apply mv_polynomial.induction_on p, { assume a' s a, simp [C_mul_monomial, eval₂_monomial, is_semiring_hom.map_mul f] }, { assume p q ih_p ih_q, simp [add_mul, eval₂_add, ih_p, ih_q] }, { assume p n ih s a, from calc (p * X n * monomial s a).eval₂ f g = (p * monomial (single n 1 + s) a).eval₂ f g : by simp [monomial_single_add, -add_comm, pow_one, mul_assoc] ... = (p * monomial (single n 1) 1).eval₂ f g * f a * s.prod (λn e, g n ^ e) : by simp [ih, prod_single_index, prod_add_index, pow_one, pow_add, mul_assoc, mul_left_comm, is_semiring_hom.map_one f, -add_comm] } end @[simp] lemma eval₂_mul : ∀{p}, (p * q).eval₂ f g = p.eval₂ f g * q.eval₂ f g := begin apply mv_polynomial.induction_on q, { simp [C, eval₂_monomial, eval₂_mul_monomial, prod_zero_index] }, { simp [mul_add, eval₂_add] {contextual := tt} }, { simp [X, eval₂_monomial, eval₂_mul_monomial, (mul_assoc _ _ _).symm] { contextual := tt} } end @[simp] lemma eval₂_pow {p:mv_polynomial σ R} : ∀{n:ℕ}, (p ^ n).eval₂ f g = (p.eval₂ f g)^n | 0 := eval₂_one _ _ | (n + 1) := by rw [pow_add, pow_one, pow_add, pow_one, eval₂_mul, eval₂_pow] instance eval₂.is_semiring_hom : is_semiring_hom (eval₂ f g) := { map_zero := eval₂_zero _ _, map_one := eval₂_one _ _, map_add := λ p q, eval₂_add _ _, map_mul := λ p q, eval₂_mul _ _ } /-- `mv_polynomial.eval₂` as a `ring_hom`. -/ def eval₂_hom (f : R →+* S₁) (g : σ → S₁) : mv_polynomial σ R →+* S₁ := ring_hom.of (eval₂ f g) @[simp] lemma coe_eval₂_hom (f : R →+* S₁) (g : σ → S₁) : ⇑(eval₂_hom f g) = eval₂ f g := rfl lemma eval₂_hom_congr {f₁ f₂ : R →+* S₁} {g₁ g₂ : σ → S₁} {p₁ p₂ : mv_polynomial σ R} : f₁ = f₂ → g₁ = g₂ → p₁ = p₂ → eval₂_hom f₁ g₁ p₁ = eval₂_hom f₂ g₂ p₂ := by rintros rfl rfl rfl; refl end @[simp] lemma eval₂_hom_C (f : R →+* S₁) (g : σ → S₁) (r : R) : eval₂_hom f g (C r) = f r := eval₂_C f g r @[simp] lemma eval₂_hom_X' (f : R →+* S₁) (g : σ → S₁) (i : σ) : eval₂_hom f g (X i) = g i := eval₂_X f g i @[simp] lemma comp_eval₂_hom [comm_semiring S₂] (f : R →+* S₁) (g : σ → S₁) (φ : S₁ →+* S₂) : φ.comp (eval₂_hom f g) = (eval₂_hom (φ.comp f) (λ i, φ (g i))) := begin apply mv_polynomial.ring_hom_ext, { intro r, rw [ring_hom.comp_apply, eval₂_hom_C, eval₂_hom_C, ring_hom.comp_apply] }, { intro i, rw [ring_hom.comp_apply, eval₂_hom_X', eval₂_hom_X'] } end lemma map_eval₂_hom [comm_semiring S₂] (f : R →+* S₁) (g : σ → S₁) (φ : S₁ →+* S₂) (p : mv_polynomial σ R) : φ (eval₂_hom f g p) = (eval₂_hom (φ.comp f) (λ i, φ (g i)) p) := by { rw ← comp_eval₂_hom, refl } lemma eval₂_hom_monomial (f : R →+* S₁) (g : σ → S₁) (d : σ →₀ ℕ) (r : R) : eval₂_hom f g (monomial d r) = f r * d.prod (λ i k, g i ^ k) := by simp only [monomial_eq, ring_hom.map_mul, eval₂_hom_C, finsupp.prod, ring_hom.map_prod, ring_hom.map_pow, eval₂_hom_X'] section local attribute [instance, priority 10] is_semiring_hom.comp lemma eval₂_comp_left {S₂} [comm_semiring S₂] (k : S₁ →+* S₂) (f : R →+* S₁) (g : σ → S₁) (p) : k (eval₂ f g p) = eval₂ (k.comp f) (k ∘ g) p := by apply mv_polynomial.induction_on p; simp [ eval₂_add, k.map_add, eval₂_mul, k.map_mul] {contextual := tt} end @[simp] lemma eval₂_eta (p : mv_polynomial σ R) : eval₂ C X p = p := by apply mv_polynomial.induction_on p; simp [eval₂_add, eval₂_mul] {contextual := tt} lemma eval₂_congr (g₁ g₂ : σ → S₁) (h : ∀ {i : σ} {c : σ →₀ ℕ}, i ∈ c.support → coeff c p ≠ 0 → g₁ i = g₂ i) : p.eval₂ f g₁ = p.eval₂ f g₂ := begin apply finset.sum_congr rfl, intros c hc, dsimp, congr' 1, apply finset.prod_congr rfl, intros i hi, dsimp, congr' 1, apply h hi, rwa finsupp.mem_support_iff at hc end @[simp] lemma eval₂_prod (s : finset S₂) (p : S₂ → mv_polynomial σ R) : eval₂ f g (∏ x in s, p x) = ∏ x in s, eval₂ f g (p x) := (s.prod_hom _).symm @[simp] lemma eval₂_sum (s : finset S₂) (p : S₂ → mv_polynomial σ R) : eval₂ f g (∑ x in s, p x) = ∑ x in s, eval₂ f g (p x) := (s.sum_hom _).symm attribute [to_additive] eval₂_prod lemma eval₂_assoc (q : S₂ → mv_polynomial σ R) (p : mv_polynomial S₂ R) : eval₂ f (λ t, eval₂ f g (q t)) p = eval₂ f g (eval₂ C q p) := begin show _ = eval₂_hom f g (eval₂ C q p), rw eval₂_comp_left (eval₂_hom f g), congr' with a, simp, end end eval₂ section eval variables {f : σ → R} /-- Evaluate a polynomial `p` given a valuation `f` of all the variables -/ def eval (f : σ → R) : mv_polynomial σ R →+* R := eval₂_hom (ring_hom.id _) f lemma eval_eq (x : σ → R) (f : mv_polynomial σ R) : eval x f = ∑ d in f.support, f.coeff d * ∏ i in d.support, x i ^ d i := rfl lemma eval_eq' [fintype σ] (x : σ → R) (f : mv_polynomial σ R) : eval x f = ∑ d in f.support, f.coeff d * ∏ i, x i ^ d i := eval₂_eq' (ring_hom.id R) x f lemma eval_monomial : eval f (monomial s a) = a * s.prod (λn e, f n ^ e) := eval₂_monomial _ _ @[simp] lemma eval_C : ∀ a, eval f (C a) = a := eval₂_C _ _ @[simp] lemma eval_X : ∀ n, eval f (X n) = f n := eval₂_X _ _ @[simp] lemma smul_eval (x) (p : mv_polynomial σ R) (s) : eval x (s • p) = s * eval x p := by rw [smul_eq_C_mul, (eval x).map_mul, eval_C] lemma eval_sum {ι : Type*} (s : finset ι) (f : ι → mv_polynomial σ R) (g : σ → R) : eval g (∑ i in s, f i) = ∑ i in s, eval g (f i) := (eval g).map_sum _ _ @[to_additive] lemma eval_prod {ι : Type*} (s : finset ι) (f : ι → mv_polynomial σ R) (g : σ → R) : eval g (∏ i in s, f i) = ∏ i in s, eval g (f i) := (eval g).map_prod _ _ theorem eval_assoc {τ} (f : σ → mv_polynomial τ R) (g : τ → R) (p : mv_polynomial σ R) : eval (eval g ∘ f) p = eval g (eval₂ C f p) := begin rw eval₂_comp_left (eval g), unfold eval, simp only [coe_eval₂_hom], congr' with a, simp end end eval section map variables [comm_semiring S₁] variables (f : R →+* S₁) /-- `map f p` maps a polynomial `p` across a ring hom `f` -/ def map : mv_polynomial σ R →+* mv_polynomial σ S₁ := eval₂_hom (C.comp f) X @[simp] theorem map_monomial (s : σ →₀ ℕ) (a : R) : map f (monomial s a) = monomial s (f a) := (eval₂_monomial _ _).trans monomial_eq.symm @[simp] theorem map_C : ∀ (a : R), map f (C a : mv_polynomial σ R) = C (f a) := map_monomial _ _ @[simp] theorem map_X : ∀ (n : σ), map f (X n : mv_polynomial σ R) = X n := eval₂_X _ _ theorem map_id : ∀ (p : mv_polynomial σ R), map (ring_hom.id R) p = p := eval₂_eta theorem map_map [comm_semiring S₂] (g : S₁ →+* S₂) (p : mv_polynomial σ R) : map g (map f p) = map (g.comp f) p := (eval₂_comp_left (map g) (C.comp f) X p).trans $ begin congr, { ext1 a, simp only [map_C, comp_app, ring_hom.coe_comp], }, { ext1 n, simp only [map_X, comp_app], } end theorem eval₂_eq_eval_map (g : σ → S₁) (p : mv_polynomial σ R) : p.eval₂ f g = eval g (map f p) := begin unfold map eval, simp only [coe_eval₂_hom], have h := eval₂_comp_left (eval₂_hom _ g), dsimp at h, rw h, congr, { ext1 a, simp only [coe_eval₂_hom, ring_hom.id_apply, comp_app, eval₂_C, ring_hom.coe_comp], }, { ext1 n, simp only [comp_app, eval₂_X], }, end lemma eval₂_comp_right {S₂} [comm_semiring S₂] (k : S₁ →+* S₂) (f : R →+* S₁) (g : σ → S₁) (p) : k (eval₂ f g p) = eval₂ k (k ∘ g) (map f p) := begin apply mv_polynomial.induction_on p, { intro r, rw [eval₂_C, map_C, eval₂_C] }, { intros p q hp hq, rw [eval₂_add, k.map_add, (map f).map_add, eval₂_add, hp, hq] }, { intros p s hp, rw [eval₂_mul, k.map_mul, (map f).map_mul, eval₂_mul, map_X, hp, eval₂_X, eval₂_X] } end lemma map_eval₂ (f : R →+* S₁) (g : S₂ → mv_polynomial S₃ R) (p : mv_polynomial S₂ R) : map f (eval₂ C g p) = eval₂ C (map f ∘ g) (map f p) := begin apply mv_polynomial.induction_on p, { intro r, rw [eval₂_C, map_C, map_C, eval₂_C] }, { intros p q hp hq, rw [eval₂_add, (map f).map_add, hp, hq, (map f).map_add, eval₂_add] }, { intros p s hp, rw [eval₂_mul, (map f).map_mul, hp, (map f).map_mul, map_X, eval₂_mul, eval₂_X, eval₂_X] } end lemma coeff_map (p : mv_polynomial σ R) : ∀ (m : σ →₀ ℕ), coeff m (map f p) = f (coeff m p) := begin apply mv_polynomial.induction_on p; clear p, { intros r m, rw [map_C], simp only [coeff_C], split_ifs, {refl}, rw f.map_zero }, { intros p q hp hq m, simp only [hp, hq, (map f).map_add, coeff_add], rw f.map_add }, { intros p i hp m, simp only [hp, (map f).map_mul, map_X], simp only [hp, mem_support_iff, coeff_mul_X'], split_ifs, {refl}, rw is_semiring_hom.map_zero f } end lemma map_injective (hf : function.injective f) : function.injective (map f : mv_polynomial σ R → mv_polynomial σ S₁) := begin intros p q h, simp only [ext_iff, coeff_map] at h ⊢, intro m, exact hf (h m), end @[simp] lemma eval_map (f : R →+* S₁) (g : σ → S₁) (p : mv_polynomial σ R) : eval g (map f p) = eval₂ f g p := by { apply mv_polynomial.induction_on p; { simp { contextual := tt } } } @[simp] lemma eval₂_map [comm_semiring S₂] (f : R →+* S₁) (g : σ → S₂) (φ : S₁ →+* S₂) (p : mv_polynomial σ R) : eval₂ φ g (map f p) = eval₂ (φ.comp f) g p := by { rw [← eval_map, ← eval_map, map_map], } @[simp] lemma eval₂_hom_map_hom [comm_semiring S₂] (f : R →+* S₁) (g : σ → S₂) (φ : S₁ →+* S₂) (p : mv_polynomial σ R) : eval₂_hom φ g (map f p) = eval₂_hom (φ.comp f) g p := eval₂_map f g φ p @[simp] lemma constant_coeff_map (f : R →+* S₁) (φ : mv_polynomial σ R) : constant_coeff (mv_polynomial.map f φ) = f (constant_coeff φ) := coeff_map f φ 0 lemma constant_coeff_comp_map (f : R →+* S₁) : (constant_coeff : mv_polynomial σ S₁ →+* S₁).comp (mv_polynomial.map f) = f.comp (constant_coeff) := by { ext, apply constant_coeff_map } lemma support_map_subset (p : mv_polynomial σ R) : (map f p).support ⊆ p.support := begin intro x, simp only [finsupp.mem_support_iff], contrapose!, change p.coeff x = 0 → (map f p).coeff x = 0, rw coeff_map, intro hx, rw hx, exact ring_hom.map_zero f end lemma support_map_of_injective (p : mv_polynomial σ R) {f : R →+* S₁} (hf : injective f) : (map f p).support = p.support := begin apply finset.subset.antisymm, { exact mv_polynomial.support_map_subset _ _ }, intros x hx, rw finsupp.mem_support_iff, contrapose! hx, simp only [not_not, finsupp.mem_support_iff], change (map f p).coeff x = 0 at hx, rw [coeff_map, ← f.map_zero] at hx, exact hf hx end end map section aeval /-! ### The algebra of multivariate polynomials -/ variables (f : σ → S₁) variables [comm_semiring S₁] [algebra R S₁] [comm_semiring S₂] /-- A map `σ → S₁` where `S₁` is an algebra over `R` generates an `R`-algebra homomorphism from multivariate polynomials over `σ` to `S₁`. -/ def aeval : mv_polynomial σ R →ₐ[R] S₁ := { commutes' := λ r, eval₂_C _ _ _ .. eval₂_hom (algebra_map R S₁) f } theorem aeval_def (p : mv_polynomial σ R) : aeval f p = eval₂ (algebra_map R S₁) f p := rfl lemma aeval_eq_eval₂_hom (p : mv_polynomial σ R) : aeval f p = eval₂_hom (algebra_map R S₁) f p := rfl @[simp] lemma aeval_X (s : σ) : aeval f (X s : mv_polynomial _ R) = f s := eval₂_X _ _ _ @[simp] lemma aeval_C (r : R) : aeval f (C r) = algebra_map R S₁ r := eval₂_C _ _ _ theorem eval_unique (φ : mv_polynomial σ R →ₐ[R] S₁) : φ = aeval (φ ∘ X) := begin ext p, apply mv_polynomial.induction_on p, { intro r, rw aeval_C, exact φ.commutes r }, { intros f g ih1 ih2, rw [φ.map_add, ih1, ih2, alg_hom.map_add] }, { intros p j ih, rw [φ.map_mul, alg_hom.map_mul, aeval_X, ih] } end lemma comp_aeval {B : Type*} [comm_semiring B] [algebra R B] (φ : S₁ →ₐ[R] B) : φ.comp (aeval f) = (aeval (λ i, φ (f i))) := begin apply mv_polynomial.alg_hom_ext, intros i, rw [alg_hom.comp_apply, aeval_X, aeval_X], end @[simp] lemma map_aeval {B : Type*} [comm_semiring B] (g : σ → S₁) (φ : S₁ →+* B) (p : mv_polynomial σ R) : φ (aeval g p) = (eval₂_hom (φ.comp (algebra_map R S₁)) (λ i, φ (g i)) p) := by { rw ← comp_eval₂_hom, refl } @[simp] lemma aeval_zero (p : mv_polynomial σ R) : aeval (0 : σ → S₁) p = algebra_map _ _ (constant_coeff p) := begin apply mv_polynomial.induction_on p, { simp only [aeval_C, forall_const, if_true, constant_coeff_C, eq_self_iff_true] }, { intros, simp only [*, alg_hom.map_add, ring_hom.map_add, coeff_add] }, { intros, simp only [ring_hom.map_mul, constant_coeff_X, pi.zero_apply, ring_hom.map_zero, eq_self_iff_true, mem_support_iff, not_true, aeval_X, if_false, ne.def, mul_zero, alg_hom.map_mul, zero_apply] } end @[simp] lemma aeval_zero' (p : mv_polynomial σ R) : aeval (λ _, 0 : σ → S₁) p = algebra_map _ _ (constant_coeff p) := aeval_zero p lemma aeval_monomial (g : σ → S₁) (d : σ →₀ ℕ) (r : R) : aeval g (monomial d r) = algebra_map _ _ r * d.prod (λ i k, g i ^ k) := eval₂_hom_monomial _ _ _ _ lemma eval₂_hom_eq_zero (f : R →+* S₂) (g : σ → S₂) (φ : mv_polynomial σ R) (h : ∀ d, φ.coeff d ≠ 0 → ∃ i ∈ d.support, g i = 0) : eval₂_hom f g φ = 0 := begin rw [φ.as_sum, ring_hom.map_sum, finset.sum_eq_zero], intros d hd, obtain ⟨i, hi, hgi⟩ : ∃ i ∈ d.support, g i = 0 := h d (finsupp.mem_support_iff.mp hd), rw [eval₂_hom_monomial, finsupp.prod, finset.prod_eq_zero hi, mul_zero], rw [hgi, zero_pow], rwa [nat.pos_iff_ne_zero, ← finsupp.mem_support_iff] end lemma aeval_eq_zero [algebra R S₂] (f : σ → S₂) (φ : mv_polynomial σ R) (h : ∀ d, φ.coeff d ≠ 0 → ∃ i ∈ d.support, f i = 0) : aeval f φ = 0 := eval₂_hom_eq_zero _ _ _ h end aeval end comm_semiring end mv_polynomial
8f6f3abac6b8e2c436af3be6497866ff6573f06e
0d9b0a832bc57849732c5bd008a7a142f7e49656
/src/soko_level29.lean
c7c8d4e9a44b795fa1a07152bfd5e9ea4d0634c5
[]
no_license
mirefek/sokoban.lean
bb9414af67894e4d8ce75f8c8d7031df02d371d0
451c92308afb4d3f8e566594b9751286f93b899b
refs/heads/master
1,681,025,245,267
1,618,997,832,000
1,618,997,832,000
359,491,681
10
0
null
null
null
null
UTF-8
Lean
false
false
21,625
lean
import .sokolevel def soko_level_29 := sokolevel.from_string " ##### # ## # $ ######### ## # # ###### ## # $#$#@ # # # # $ # $ # # ### ######### ## # ## ..*..... # ## ## ## *.*..*.* # ## # $########## ##$ # # $ $ $ $ # # # # # # # ################### " theorem solvable_level_29 : soko_level_29.solvable := begin sokolevel.solve_up, sokolevel.solve_left, sokolevel.solve_left, sokolevel.solve_left, sokolevel.solve_left, sokolevel.solve_left, sokolevel.solve_down, sokolevel.solve_down, sokolevel.solve_down, sokolevel.solve_down, sokolevel.solve_right, sokolevel.solve_down, sokolevel.solve_right, sokolevel.solve_right, sokolevel.solve_up, sokolevel.solve_right, sokolevel.solve_right, sokolevel.solve_right, sokolevel.solve_right, sokolevel.solve_right, sokolevel.solve_down, sokolevel.solve_left, sokolevel.solve_down, sokolevel.solve_down, sokolevel.solve_left, sokolevel.solve_left, sokolevel.solve_left, sokolevel.solve_down, sokolevel.solve_left, sokolevel.solve_left, sokolevel.solve_up, sokolevel.solve_right, sokolevel.solve_right, sokolevel.solve_right, sokolevel.solve_right, sokolevel.solve_down, sokolevel.solve_right, sokolevel.solve_right, sokolevel.solve_up, sokolevel.solve_left, sokolevel.solve_up, sokolevel.solve_up, sokolevel.solve_up, sokolevel.solve_left, sokolevel.solve_left, sokolevel.solve_left, sokolevel.solve_left, sokolevel.solve_down, sokolevel.solve_left, sokolevel.solve_left, sokolevel.solve_up, sokolevel.solve_left, sokolevel.solve_up, sokolevel.solve_up, sokolevel.solve_up, sokolevel.solve_left, sokolevel.solve_left, sokolevel.solve_up, sokolevel.solve_up, sokolevel.solve_left, sokolevel.solve_up, sokolevel.solve_left, sokolevel.solve_left, sokolevel.solve_down, sokolevel.solve_right, sokolevel.solve_down, sokolevel.solve_down, sokolevel.solve_down, sokolevel.solve_down, sokolevel.solve_down, sokolevel.solve_down, sokolevel.solve_down, sokolevel.solve_left, sokolevel.solve_down, sokolevel.solve_down, sokolevel.solve_right, sokolevel.solve_up, sokolevel.solve_up, sokolevel.solve_up, sokolevel.solve_up, sokolevel.solve_down, sokolevel.solve_down, sokolevel.solve_down, sokolevel.solve_right, sokolevel.solve_right, sokolevel.solve_down, sokolevel.solve_right, sokolevel.solve_right, sokolevel.solve_up, sokolevel.solve_left, sokolevel.solve_left, sokolevel.solve_left, sokolevel.solve_right, sokolevel.solve_right, sokolevel.solve_right, sokolevel.solve_right, sokolevel.solve_right, sokolevel.solve_down, sokolevel.solve_right, sokolevel.solve_right, sokolevel.solve_up, sokolevel.solve_left, sokolevel.solve_left, sokolevel.solve_left, sokolevel.solve_left, sokolevel.solve_right, sokolevel.solve_right, sokolevel.solve_right, sokolevel.solve_right, sokolevel.solve_right, sokolevel.solve_right, sokolevel.solve_down, sokolevel.solve_right, sokolevel.solve_right, sokolevel.solve_up, sokolevel.solve_left, sokolevel.solve_left, sokolevel.solve_left, sokolevel.solve_left, sokolevel.solve_right, sokolevel.solve_right, sokolevel.solve_right, sokolevel.solve_up, sokolevel.solve_up, sokolevel.solve_up, sokolevel.solve_left, sokolevel.solve_left, sokolevel.solve_left, sokolevel.solve_left, sokolevel.solve_down, sokolevel.solve_left, sokolevel.solve_left, sokolevel.solve_up, sokolevel.solve_left, sokolevel.solve_up, sokolevel.solve_up, sokolevel.solve_up, sokolevel.solve_left, sokolevel.solve_left, sokolevel.solve_up, sokolevel.solve_up, sokolevel.solve_left, sokolevel.solve_up, sokolevel.solve_left, sokolevel.solve_left, sokolevel.solve_down, sokolevel.solve_right, sokolevel.solve_down, sokolevel.solve_down, sokolevel.solve_down, sokolevel.solve_left, sokolevel.solve_down, sokolevel.solve_down, sokolevel.solve_right, sokolevel.solve_down, sokolevel.solve_down, sokolevel.solve_left, sokolevel.solve_down, sokolevel.solve_down, sokolevel.solve_right, sokolevel.solve_up, sokolevel.solve_right, sokolevel.solve_right, sokolevel.solve_down, sokolevel.solve_right, sokolevel.solve_right, sokolevel.solve_up, sokolevel.solve_right, sokolevel.solve_right, sokolevel.solve_down, sokolevel.solve_right, sokolevel.solve_right, sokolevel.solve_up, sokolevel.solve_right, sokolevel.solve_right, sokolevel.solve_right, sokolevel.solve_up, sokolevel.solve_up, sokolevel.solve_up, sokolevel.solve_left, sokolevel.solve_left, sokolevel.solve_left, sokolevel.solve_left, sokolevel.solve_down, sokolevel.solve_left, sokolevel.solve_left, sokolevel.solve_up, sokolevel.solve_left, sokolevel.solve_up, sokolevel.solve_up, sokolevel.solve_up, sokolevel.solve_up, sokolevel.solve_right, sokolevel.solve_right, sokolevel.solve_right, sokolevel.solve_right, sokolevel.solve_right, sokolevel.solve_down, sokolevel.solve_right, sokolevel.solve_right, sokolevel.solve_down, sokolevel.solve_right, sokolevel.solve_right, sokolevel.solve_up, sokolevel.solve_right, sokolevel.solve_right, sokolevel.solve_down, sokolevel.solve_left, sokolevel.solve_down, sokolevel.solve_down, sokolevel.solve_down, sokolevel.solve_down, sokolevel.solve_right, sokolevel.solve_down, sokolevel.solve_down, sokolevel.solve_left, sokolevel.solve_up, sokolevel.solve_left, sokolevel.solve_left, sokolevel.solve_left, sokolevel.solve_up, sokolevel.solve_up, sokolevel.solve_up, sokolevel.solve_left, sokolevel.solve_left, sokolevel.solve_left, sokolevel.solve_left, sokolevel.solve_down, sokolevel.solve_left, sokolevel.solve_left, sokolevel.solve_up, sokolevel.solve_left, sokolevel.solve_left, sokolevel.solve_down, sokolevel.solve_right, sokolevel.solve_right, sokolevel.solve_right, sokolevel.solve_left, sokolevel.solve_up, sokolevel.solve_left, sokolevel.solve_up, sokolevel.solve_up, sokolevel.solve_up, sokolevel.solve_left, sokolevel.solve_left, sokolevel.solve_up, sokolevel.solve_up, sokolevel.solve_left, sokolevel.solve_up, sokolevel.solve_left, sokolevel.solve_left, sokolevel.solve_down, sokolevel.solve_right, sokolevel.solve_down, sokolevel.solve_down, sokolevel.solve_down, sokolevel.solve_left, sokolevel.solve_down, sokolevel.solve_down, sokolevel.solve_right, sokolevel.solve_down, sokolevel.solve_down, sokolevel.solve_left, sokolevel.solve_down, sokolevel.solve_down, sokolevel.solve_right, sokolevel.solve_up, sokolevel.solve_right, sokolevel.solve_right, sokolevel.solve_down, sokolevel.solve_right, sokolevel.solve_right, sokolevel.solve_up, sokolevel.solve_right, sokolevel.solve_right, sokolevel.solve_down, sokolevel.solve_right, sokolevel.solve_right, sokolevel.solve_up, sokolevel.solve_right, sokolevel.solve_right, sokolevel.solve_down, sokolevel.solve_right, sokolevel.solve_right, sokolevel.solve_up, sokolevel.solve_left, sokolevel.solve_up, sokolevel.solve_up, sokolevel.solve_up, sokolevel.solve_left, sokolevel.solve_left, sokolevel.solve_left, sokolevel.solve_left, sokolevel.solve_left, sokolevel.solve_down, sokolevel.solve_left, sokolevel.solve_left, sokolevel.solve_up, sokolevel.solve_up, sokolevel.solve_up, sokolevel.solve_up, sokolevel.solve_up, sokolevel.solve_right, sokolevel.solve_right, sokolevel.solve_right, sokolevel.solve_right, sokolevel.solve_right, sokolevel.solve_down, sokolevel.solve_down, sokolevel.solve_left, sokolevel.solve_left, sokolevel.solve_left, sokolevel.solve_left, sokolevel.solve_left, sokolevel.solve_up, sokolevel.solve_up, sokolevel.solve_right, sokolevel.solve_down, sokolevel.solve_left, sokolevel.solve_down, sokolevel.solve_right, sokolevel.solve_right, sokolevel.solve_right, sokolevel.solve_left, sokolevel.solve_left, sokolevel.solve_up, sokolevel.solve_left, sokolevel.solve_left, sokolevel.solve_left, sokolevel.solve_down, sokolevel.solve_right, sokolevel.solve_up, sokolevel.solve_left, sokolevel.solve_up, sokolevel.solve_up, sokolevel.solve_left, sokolevel.solve_up, sokolevel.solve_left, sokolevel.solve_left, sokolevel.solve_down, sokolevel.solve_right, sokolevel.solve_down, sokolevel.solve_down, sokolevel.solve_down, sokolevel.solve_left, sokolevel.solve_down, sokolevel.solve_down, sokolevel.solve_right, sokolevel.solve_down, sokolevel.solve_down, sokolevel.solve_left, sokolevel.solve_down, sokolevel.solve_down, sokolevel.solve_right, sokolevel.solve_up, sokolevel.solve_right, sokolevel.solve_right, sokolevel.solve_down, sokolevel.solve_right, sokolevel.solve_right, sokolevel.solve_up, sokolevel.solve_right, sokolevel.solve_right, sokolevel.solve_down, sokolevel.solve_right, sokolevel.solve_right, sokolevel.solve_up, sokolevel.solve_right, sokolevel.solve_right, sokolevel.solve_down, sokolevel.solve_right, sokolevel.solve_right, sokolevel.solve_up, sokolevel.solve_left, sokolevel.solve_up, sokolevel.solve_up, sokolevel.solve_up, sokolevel.solve_left, sokolevel.solve_left, sokolevel.solve_left, sokolevel.solve_left, sokolevel.solve_left, sokolevel.solve_down, sokolevel.solve_left, sokolevel.solve_left, sokolevel.solve_up, sokolevel.solve_up, sokolevel.solve_up, sokolevel.solve_right, sokolevel.solve_up, sokolevel.solve_left, sokolevel.solve_down, sokolevel.solve_down, sokolevel.solve_down, sokolevel.solve_down, sokolevel.solve_right, sokolevel.solve_right, sokolevel.solve_up, sokolevel.solve_left, sokolevel.solve_down, sokolevel.solve_left, sokolevel.solve_up, sokolevel.solve_up, sokolevel.solve_up, sokolevel.solve_right, sokolevel.solve_up, sokolevel.solve_up, sokolevel.solve_right, sokolevel.solve_right, sokolevel.solve_right, sokolevel.solve_right, sokolevel.solve_down, sokolevel.solve_right, sokolevel.solve_right, sokolevel.solve_down, sokolevel.solve_right, sokolevel.solve_right, sokolevel.solve_up, sokolevel.solve_right, sokolevel.solve_right, sokolevel.solve_down, sokolevel.solve_left, sokolevel.solve_down, sokolevel.solve_down, sokolevel.solve_down, sokolevel.solve_down, sokolevel.solve_right, sokolevel.solve_down, sokolevel.solve_left, sokolevel.solve_left, sokolevel.solve_left, sokolevel.solve_down, sokolevel.solve_left, sokolevel.solve_up, sokolevel.solve_up, sokolevel.solve_up, sokolevel.solve_right, sokolevel.solve_up, sokolevel.solve_left, sokolevel.solve_left, sokolevel.solve_left, sokolevel.solve_left, sokolevel.solve_left, sokolevel.solve_left, sokolevel.solve_down, sokolevel.solve_left, sokolevel.solve_left, sokolevel.solve_up, sokolevel.solve_up, sokolevel.solve_up, sokolevel.solve_right, sokolevel.solve_up, sokolevel.solve_up, sokolevel.solve_right, sokolevel.solve_right, sokolevel.solve_right, sokolevel.solve_right, sokolevel.solve_down, sokolevel.solve_right, sokolevel.solve_right, sokolevel.solve_down, sokolevel.solve_right, sokolevel.solve_right, sokolevel.solve_up, sokolevel.solve_right, sokolevel.solve_down, sokolevel.solve_down, sokolevel.solve_down, sokolevel.solve_down, sokolevel.solve_down, sokolevel.solve_right, sokolevel.solve_down, sokolevel.solve_left, sokolevel.solve_left, sokolevel.solve_left, sokolevel.solve_down, sokolevel.solve_left, sokolevel.solve_up, sokolevel.solve_up, sokolevel.solve_up, sokolevel.solve_right, sokolevel.solve_up, sokolevel.solve_left, sokolevel.solve_left, sokolevel.solve_left, sokolevel.solve_left, sokolevel.solve_left, sokolevel.solve_right, sokolevel.solve_right, sokolevel.solve_right, sokolevel.solve_right, sokolevel.solve_down, sokolevel.solve_down, sokolevel.solve_down, sokolevel.solve_right, sokolevel.solve_right, sokolevel.solve_right, sokolevel.solve_up, sokolevel.solve_up, sokolevel.solve_up, sokolevel.solve_up, sokolevel.solve_up, sokolevel.solve_left, sokolevel.solve_left, sokolevel.solve_left, sokolevel.solve_up, sokolevel.solve_left, sokolevel.solve_up, sokolevel.solve_left, sokolevel.solve_left, sokolevel.solve_left, sokolevel.solve_left, sokolevel.solve_left, sokolevel.solve_down, sokolevel.solve_down, sokolevel.solve_left, sokolevel.solve_left, sokolevel.solve_left, sokolevel.solve_up, sokolevel.solve_up, sokolevel.solve_up, sokolevel.solve_left, sokolevel.solve_up, sokolevel.solve_left, sokolevel.solve_left, sokolevel.solve_down, sokolevel.solve_right, sokolevel.solve_down, sokolevel.solve_down, sokolevel.solve_down, sokolevel.solve_left, sokolevel.solve_down, sokolevel.solve_down, sokolevel.solve_right, sokolevel.solve_down, sokolevel.solve_down, sokolevel.solve_left, sokolevel.solve_down, sokolevel.solve_down, sokolevel.solve_right, sokolevel.solve_up, sokolevel.solve_right, sokolevel.solve_right, sokolevel.solve_down, sokolevel.solve_right, sokolevel.solve_right, sokolevel.solve_up, sokolevel.solve_right, sokolevel.solve_right, sokolevel.solve_down, sokolevel.solve_right, sokolevel.solve_right, sokolevel.solve_up, sokolevel.solve_right, sokolevel.solve_right, sokolevel.solve_down, sokolevel.solve_right, sokolevel.solve_up, sokolevel.solve_up, sokolevel.solve_up, sokolevel.solve_right, sokolevel.solve_up, sokolevel.solve_left, sokolevel.solve_left, sokolevel.solve_left, sokolevel.solve_left, sokolevel.solve_right, sokolevel.solve_right, sokolevel.solve_right, sokolevel.solve_down, sokolevel.solve_down, sokolevel.solve_down, sokolevel.solve_left, sokolevel.solve_left, sokolevel.solve_left, sokolevel.solve_down, sokolevel.solve_left, sokolevel.solve_left, sokolevel.solve_up, sokolevel.solve_right, sokolevel.solve_right, sokolevel.solve_right, sokolevel.solve_right, sokolevel.solve_down, sokolevel.solve_right, sokolevel.solve_up, sokolevel.solve_up, sokolevel.solve_up, sokolevel.solve_right, sokolevel.solve_up, sokolevel.solve_left, sokolevel.solve_left, sokolevel.solve_left, sokolevel.solve_right, sokolevel.solve_right, sokolevel.solve_down, sokolevel.solve_down, sokolevel.solve_down, sokolevel.solve_left, sokolevel.solve_left, sokolevel.solve_left, sokolevel.solve_left, sokolevel.solve_left, sokolevel.solve_left, sokolevel.solve_left, sokolevel.solve_down, sokolevel.solve_left, sokolevel.solve_left, sokolevel.solve_up, sokolevel.solve_right, sokolevel.solve_right, sokolevel.solve_right, sokolevel.solve_right, sokolevel.solve_right, sokolevel.solve_right, sokolevel.solve_right, sokolevel.solve_right, sokolevel.solve_down, sokolevel.solve_right, sokolevel.solve_up, sokolevel.solve_up, sokolevel.solve_up, sokolevel.solve_right, sokolevel.solve_up, sokolevel.solve_left, sokolevel.solve_left, sokolevel.solve_right, sokolevel.solve_down, sokolevel.solve_down, sokolevel.solve_down, sokolevel.solve_right, sokolevel.solve_right, sokolevel.solve_right, sokolevel.solve_up, sokolevel.solve_up, sokolevel.solve_up, sokolevel.solve_up, sokolevel.solve_up, sokolevel.solve_left, sokolevel.solve_left, sokolevel.solve_left, sokolevel.solve_up, sokolevel.solve_left, sokolevel.solve_up, sokolevel.solve_left, sokolevel.solve_left, sokolevel.solve_left, sokolevel.solve_left, sokolevel.solve_left, sokolevel.solve_down, sokolevel.solve_down, sokolevel.solve_left, sokolevel.solve_left, sokolevel.solve_left, sokolevel.solve_up, sokolevel.solve_up, sokolevel.solve_up, sokolevel.solve_left, sokolevel.solve_up, sokolevel.solve_left, sokolevel.solve_left, sokolevel.solve_down, sokolevel.solve_right, sokolevel.solve_down, sokolevel.solve_down, sokolevel.solve_down, sokolevel.solve_left, sokolevel.solve_down, sokolevel.solve_down, sokolevel.solve_right, sokolevel.solve_down, sokolevel.solve_down, sokolevel.solve_left, sokolevel.solve_down, sokolevel.solve_right, sokolevel.solve_right, sokolevel.solve_right, sokolevel.solve_right, sokolevel.solve_right, sokolevel.solve_right, sokolevel.solve_right, sokolevel.solve_right, sokolevel.solve_right, sokolevel.solve_right, sokolevel.solve_right, sokolevel.solve_down, sokolevel.solve_right, sokolevel.solve_up, sokolevel.solve_up, sokolevel.solve_up, sokolevel.solve_right, sokolevel.solve_up, sokolevel.solve_left, sokolevel.solve_down, sokolevel.solve_down, sokolevel.solve_down, sokolevel.solve_left, sokolevel.solve_left, sokolevel.solve_left, sokolevel.solve_left, sokolevel.solve_left, sokolevel.solve_left, sokolevel.solve_left, sokolevel.solve_left, sokolevel.solve_left, sokolevel.solve_left, sokolevel.solve_left, sokolevel.solve_up, sokolevel.solve_up, sokolevel.solve_up, sokolevel.solve_left, sokolevel.solve_up, sokolevel.solve_up, sokolevel.solve_right, sokolevel.solve_down, sokolevel.solve_down, sokolevel.solve_down, sokolevel.solve_down, sokolevel.solve_left, sokolevel.solve_down, sokolevel.solve_right, sokolevel.solve_right, sokolevel.solve_right, sokolevel.solve_right, sokolevel.solve_right, sokolevel.solve_right, sokolevel.solve_right, sokolevel.solve_right, sokolevel.solve_right, sokolevel.solve_right, sokolevel.solve_right, sokolevel.solve_down, sokolevel.solve_right, sokolevel.solve_up, sokolevel.solve_up, sokolevel.solve_up, sokolevel.solve_down, sokolevel.solve_down, sokolevel.solve_right, sokolevel.solve_right, sokolevel.solve_right, sokolevel.solve_up, sokolevel.solve_up, sokolevel.solve_up, sokolevel.solve_up, sokolevel.solve_up, sokolevel.solve_left, sokolevel.solve_left, sokolevel.solve_left, sokolevel.solve_up, sokolevel.solve_left, sokolevel.solve_up, sokolevel.solve_left, sokolevel.solve_left, sokolevel.solve_left, sokolevel.solve_left, sokolevel.solve_left, sokolevel.solve_down, sokolevel.solve_down, sokolevel.solve_left, sokolevel.solve_left, sokolevel.solve_left, sokolevel.solve_up, sokolevel.solve_up, sokolevel.solve_up, sokolevel.solve_left, sokolevel.solve_up, sokolevel.solve_left, sokolevel.solve_down, sokolevel.solve_down, sokolevel.solve_down, sokolevel.solve_down, sokolevel.solve_down, sokolevel.solve_down, sokolevel.solve_down, sokolevel.solve_down, sokolevel.solve_left, sokolevel.solve_down, sokolevel.solve_right, sokolevel.solve_right, sokolevel.solve_right, sokolevel.solve_right, sokolevel.solve_right, sokolevel.solve_right, sokolevel.solve_right, sokolevel.solve_right, sokolevel.solve_right, sokolevel.solve_right, sokolevel.solve_right, sokolevel.solve_down, sokolevel.solve_right, sokolevel.solve_up, sokolevel.solve_up, sokolevel.solve_down, sokolevel.solve_right, sokolevel.solve_right, sokolevel.solve_right, sokolevel.solve_up, sokolevel.solve_up, sokolevel.solve_up, sokolevel.solve_up, sokolevel.solve_up, sokolevel.solve_left, sokolevel.solve_left, sokolevel.solve_left, sokolevel.solve_up, sokolevel.solve_left, sokolevel.solve_up, sokolevel.solve_left, sokolevel.solve_left, sokolevel.solve_left, sokolevel.solve_left, sokolevel.solve_left, sokolevel.solve_left, sokolevel.solve_down, sokolevel.solve_down, sokolevel.solve_down, sokolevel.solve_down, sokolevel.solve_left, sokolevel.solve_down, sokolevel.solve_right, sokolevel.solve_right, sokolevel.solve_left, sokolevel.solve_up, sokolevel.solve_up, sokolevel.solve_up, sokolevel.solve_left, sokolevel.solve_left, sokolevel.solve_up, sokolevel.solve_right, sokolevel.solve_down, sokolevel.solve_right, sokolevel.solve_right, sokolevel.solve_up, sokolevel.solve_up, sokolevel.solve_left, sokolevel.solve_down, sokolevel.solve_down, sokolevel.solve_down, sokolevel.solve_down, sokolevel.solve_left, sokolevel.solve_down, sokolevel.solve_right, sokolevel.solve_up, sokolevel.solve_up, sokolevel.solve_up, sokolevel.solve_up, sokolevel.solve_up, sokolevel.solve_right, sokolevel.solve_right, sokolevel.solve_right, sokolevel.solve_right, sokolevel.solve_right, sokolevel.solve_down, sokolevel.solve_down, sokolevel.solve_left, sokolevel.solve_left, sokolevel.solve_left, sokolevel.solve_left, sokolevel.solve_up, sokolevel.solve_left, sokolevel.solve_down, sokolevel.solve_down, sokolevel.solve_down, sokolevel.solve_up, sokolevel.solve_up, sokolevel.solve_up, sokolevel.solve_up, sokolevel.solve_right, sokolevel.solve_right, sokolevel.solve_right, sokolevel.solve_down, sokolevel.solve_up, sokolevel.solve_right, sokolevel.solve_right, sokolevel.solve_down, sokolevel.solve_down, sokolevel.solve_left, sokolevel.solve_left, sokolevel.solve_left, sokolevel.solve_left, sokolevel.soko_simp, sokolevel.solve_up, sokolevel.soko_simp, sokolevel.solve_left, sokolevel.soko_simp, sokolevel.solve_down, sokolevel.soko_simp, sokolevel.solve_down, sokolevel.soko_simp, sokolevel.solve_finish end
0217e011e2fdaea3225453dd681932b79148ae1d
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/linear_algebra/linear_pmap.lean
9362c87be5b207059479bdda2a88911f93e8f1aa
[ "Apache-2.0" ]
permissive
jjgarzella/mathlib
96a345378c4e0bf26cf604aed84f90329e4896a2
395d8716c3ad03747059d482090e2bb97db612c8
refs/heads/master
1,686,480,124,379
1,625,163,323,000
1,625,163,323,000
281,190,421
2
0
Apache-2.0
1,595,268,170,000
1,595,268,169,000
null
UTF-8
Lean
false
false
16,691
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 linear_algebra.basic import linear_algebra.prod /-! # Partially defined linear maps A `linear_pmap R E F` is a linear map from a submodule of `E` to `F`. We define a `semilattice_inf_bot` instance on this this, and define three operations: * `mk_span_singleton` defines a partial linear map defined on the span of a singleton. * `sup` takes two partial linear maps `f`, `g` that agree on the intersection of their domains, and returns the unique partial linear map on `f.domain ⊔ g.domain` that extends both `f` and `g`. * `Sup` takes a `directed_on (≤)` set of partial linear maps, and returns the unique partial linear map on the `Sup` of their domains that extends all these maps. Partially defined maps are currently used in `mathlib` to prove Hahn-Banach theorem and its variations. Namely, `linear_pmap.Sup` implies that every chain of `linear_pmap`s is bounded above. Another possible use (not yet in `mathlib`) would be the theory of unbounded linear operators. -/ open set universes u v w /-- A `linear_pmap R E F` is a linear map from a submodule of `E` to `F`. -/ structure linear_pmap (R : Type u) [ring R] (E : Type v) [add_comm_group E] [module R E] (F : Type w) [add_comm_group F] [module R F] := (domain : submodule R E) (to_fun : domain →ₗ[R] F) variables {R : Type*} [ring R] {E : Type*} [add_comm_group E] [module R E] {F : Type*} [add_comm_group F] [module R F] {G : Type*} [add_comm_group G] [module R G] namespace linear_pmap open submodule instance : has_coe_to_fun (linear_pmap R E F) := ⟨λ f : linear_pmap R E F, f.domain → F, λ f, f.to_fun⟩ @[simp] lemma to_fun_eq_coe (f : linear_pmap R E F) (x : f.domain) : f.to_fun x = f x := rfl @[simp] lemma map_zero (f : linear_pmap R E F) : f 0 = 0 := f.to_fun.map_zero lemma map_add (f : linear_pmap R E F) (x y : f.domain) : f (x + y) = f x + f y := f.to_fun.map_add x y lemma map_neg (f : linear_pmap R E F) (x : f.domain) : f (-x) = -f x := f.to_fun.map_neg x lemma map_sub (f : linear_pmap R E F) (x y : f.domain) : f (x - y) = f x - f y := f.to_fun.map_sub x y lemma map_smul (f : linear_pmap R E F) (c : R) (x : f.domain) : f (c • x) = c • f x := f.to_fun.map_smul c x @[simp] lemma mk_apply (p : submodule R E) (f : p →ₗ[R] F) (x : p) : mk p f x = f x := rfl /-- The unique `linear_pmap` on `R ∙ x` that sends `x` to `y`. This version works for modules over rings, and requires a proof of `∀ c, c • x = 0 → c • y = 0`. -/ noncomputable def mk_span_singleton' (x : E) (y : F) (H : ∀ c : R, c • x = 0 → c • y = 0) : linear_pmap R E F := { domain := R ∙ x, to_fun := have H : ∀ c₁ c₂ : R, c₁ • x = c₂ • x → c₁ • y = c₂ • y, { intros c₁ c₂ h, rw [← sub_eq_zero, ← sub_smul] at h ⊢, exact H _ h }, { to_fun := λ z, (classical.some (mem_span_singleton.1 z.prop) • y), map_add' := λ y z, begin rw [← add_smul], apply H, simp only [add_smul, sub_smul, classical.some_spec (mem_span_singleton.1 _)], apply coe_add end, map_smul' := λ c z, begin rw [smul_smul], apply H, simp only [mul_smul, classical.some_spec (mem_span_singleton.1 _)], apply coe_smul end } } @[simp] lemma domain_mk_span_singleton (x : E) (y : F) (H : ∀ c : R, c • x = 0 → c • y = 0) : (mk_span_singleton' x y H).domain = R ∙ x := rfl @[simp] lemma mk_span_singleton_apply (x : E) (y : F) (H : ∀ c : R, c • x = 0 → c • y = 0) (c : R) (h) : mk_span_singleton' x y H ⟨c • x, h⟩ = c • y := begin dsimp [mk_span_singleton'], rw [← sub_eq_zero, ← sub_smul], apply H, simp only [sub_smul, one_smul, sub_eq_zero], apply classical.some_spec (mem_span_singleton.1 h), end /-- The unique `linear_pmap` on `span R {x}` that sends a non-zero vector `x` to `y`. This version works for modules over division rings. -/ @[reducible] noncomputable def mk_span_singleton {K E F : Type*} [division_ring K] [add_comm_group E] [module K E] [add_comm_group F] [module K F] (x : E) (y : F) (hx : x ≠ 0) : linear_pmap K E F := mk_span_singleton' x y $ λ c hc, (smul_eq_zero.1 hc).elim (λ hc, by rw [hc, zero_smul]) (λ hx', absurd hx' hx) /-- Projection to the first coordinate as a `linear_pmap` -/ protected def fst (p : submodule R E) (p' : submodule R F) : linear_pmap R (E × F) E := { domain := p.prod p', to_fun := (linear_map.fst R E F).comp (p.prod p').subtype } @[simp] lemma fst_apply (p : submodule R E) (p' : submodule R F) (x : p.prod p') : linear_pmap.fst p p' x = (x : E × F).1 := rfl /-- Projection to the second coordinate as a `linear_pmap` -/ protected def snd (p : submodule R E) (p' : submodule R F) : linear_pmap R (E × F) F := { domain := p.prod p', to_fun := (linear_map.snd R E F).comp (p.prod p').subtype } @[simp] lemma snd_apply (p : submodule R E) (p' : submodule R F) (x : p.prod p') : linear_pmap.snd p p' x = (x : E × F).2 := rfl instance : has_neg (linear_pmap R E F) := ⟨λ f, ⟨f.domain, -f.to_fun⟩⟩ @[simp] lemma neg_apply (f : linear_pmap R E F) (x) : (-f) x = -(f x) := rfl instance : has_le (linear_pmap R E F) := ⟨λ f g, f.domain ≤ g.domain ∧ ∀ ⦃x : f.domain⦄ ⦃y : g.domain⦄ (h : (x:E) = y), f x = g y⟩ lemma eq_of_le_of_domain_eq {f g : linear_pmap R E F} (hle : f ≤ g) (heq : f.domain = g.domain) : f = g := begin rcases f with ⟨f_dom, f⟩, rcases g with ⟨g_dom, g⟩, change f_dom = g_dom at heq, subst g_dom, have : f = g, from linear_map.ext (λ x, hle.2 rfl), subst g end /-- Given two partial linear maps `f`, `g`, the set of points `x` such that both `f` and `g` are defined at `x` and `f x = g x` form a submodule. -/ def eq_locus (f g : linear_pmap R E F) : submodule R E := { carrier := {x | ∃ (hf : x ∈ f.domain) (hg : x ∈ g.domain), f ⟨x, hf⟩ = g ⟨x, hg⟩}, zero_mem' := ⟨zero_mem _, zero_mem _, f.map_zero.trans g.map_zero.symm⟩, add_mem' := λ x y ⟨hfx, hgx, hx⟩ ⟨hfy, hgy, hy⟩, ⟨add_mem _ hfx hfy, add_mem _ hgx hgy, by erw [f.map_add ⟨x, hfx⟩ ⟨y, hfy⟩, g.map_add ⟨x, hgx⟩ ⟨y, hgy⟩, hx, hy]⟩, smul_mem' := λ c x ⟨hfx, hgx, hx⟩, ⟨smul_mem _ c hfx, smul_mem _ c hgx, by erw [f.map_smul c ⟨x, hfx⟩, g.map_smul c ⟨x, hgx⟩, hx]⟩ } instance : has_inf (linear_pmap R E F) := ⟨λ f g, ⟨f.eq_locus g, f.to_fun.comp $ of_le $ λ x hx, hx.fst⟩⟩ instance : has_bot (linear_pmap R E F) := ⟨⟨⊥, 0⟩⟩ instance : inhabited (linear_pmap R E F) := ⟨⊥⟩ instance : semilattice_inf_bot (linear_pmap R E F) := { le := (≤), le_refl := λ f, ⟨le_refl f.domain, λ x y h, subtype.eq h ▸ rfl⟩, le_trans := λ f g h ⟨fg_le, fg_eq⟩ ⟨gh_le, gh_eq⟩, ⟨le_trans fg_le gh_le, λ x z hxz, have hxy : (x:E) = of_le fg_le x, from rfl, (fg_eq hxy).trans (gh_eq $ hxy.symm.trans hxz)⟩, le_antisymm := λ f g fg gf, eq_of_le_of_domain_eq fg (le_antisymm fg.1 gf.1), bot := ⊥, bot_le := λ f, ⟨bot_le, λ x y h, have hx : x = 0, from subtype.eq ((mem_bot R).1 x.2), have hy : y = 0, from subtype.eq (h.symm.trans (congr_arg _ hx)), by rw [hx, hy, map_zero, map_zero]⟩, inf := (⊓), le_inf := λ f g h ⟨fg_le, fg_eq⟩ ⟨fh_le, fh_eq⟩, ⟨λ x hx, ⟨fg_le hx, fh_le hx, by refine (fg_eq _).symm.trans (fh_eq _); [exact ⟨x, hx⟩, refl, refl]⟩, λ x ⟨y, yg, hy⟩ h, by { apply fg_eq, exact h }⟩, inf_le_left := λ f g, ⟨λ x hx, hx.fst, λ x y h, congr_arg f $ subtype.eq $ by exact h⟩, inf_le_right := λ f g, ⟨λ x hx, hx.snd.fst, λ ⟨x, xf, xg, hx⟩ y h, hx.trans $ congr_arg g $ subtype.eq $ by exact h⟩ } lemma le_of_eq_locus_ge {f g : linear_pmap R E F} (H : f.domain ≤ f.eq_locus g) : f ≤ g := suffices f ≤ f ⊓ g, from le_trans this inf_le_right, ⟨H, λ x y hxy, ((inf_le_left : f ⊓ g ≤ f).2 hxy.symm).symm⟩ lemma domain_mono : strict_mono (@domain R _ E _ _ F _ _) := λ f g hlt, lt_of_le_of_ne hlt.1.1 $ λ heq, ne_of_lt hlt $ eq_of_le_of_domain_eq (le_of_lt hlt) heq private lemma sup_aux (f g : linear_pmap R E F) (h : ∀ (x : f.domain) (y : g.domain), (x:E) = y → f x = g y) : ∃ fg : ↥(f.domain ⊔ g.domain) →ₗ[R] F, ∀ (x : f.domain) (y : g.domain) (z), (x:E) + y = ↑z → fg z = f x + g y := begin choose x hx y hy hxy using λ z : f.domain ⊔ g.domain, mem_sup.1 z.prop, set fg := λ z, f ⟨x z, hx z⟩ + g ⟨y z, hy z⟩, have fg_eq : ∀ (x' : f.domain) (y' : g.domain) (z' : f.domain ⊔ g.domain) (H : (x':E) + y' = z'), fg z' = f x' + g y', { intros x' y' z' H, dsimp [fg], rw [add_comm, ← sub_eq_sub_iff_add_eq_add, eq_comm, ← map_sub, ← map_sub], apply h, simp only [← eq_sub_iff_add_eq] at hxy, simp only [coe_sub, coe_mk, coe_mk, hxy, ← sub_add, ← sub_sub, sub_self, zero_sub, ← H], apply neg_add_eq_sub }, refine ⟨{ to_fun := fg, .. }, fg_eq⟩, { rintros ⟨z₁, hz₁⟩ ⟨z₂, hz₂⟩, rw [← add_assoc, add_right_comm (f _), ← map_add, add_assoc, ← map_add], apply fg_eq, simp only [coe_add, coe_mk, ← add_assoc], rw [add_right_comm (x _), hxy, add_assoc, hxy, coe_mk, coe_mk] }, { intros c z, rw [smul_add, ← map_smul, ← map_smul], apply fg_eq, simp only [coe_smul, coe_mk, ← smul_add, hxy] }, end /-- Given two partial linear maps that agree on the intersection of their domains, `f.sup g h` is the unique partial linear map on `f.domain ⊔ g.domain` that agrees with `f` and `g`. -/ protected noncomputable def sup (f g : linear_pmap R E F) (h : ∀ (x : f.domain) (y : g.domain), (x:E) = y → f x = g y) : linear_pmap R E F := ⟨_, classical.some (sup_aux f g h)⟩ @[simp] lemma domain_sup (f g : linear_pmap R E F) (h : ∀ (x : f.domain) (y : g.domain), (x:E) = y → f x = g y) : (f.sup g h).domain = f.domain ⊔ g.domain := rfl lemma sup_apply {f g : linear_pmap R E F} (H : ∀ (x : f.domain) (y : g.domain), (x:E) = y → f x = g y) (x y z) (hz : (↑x:E) + ↑y = ↑z) : f.sup g H z = f x + g y := classical.some_spec (sup_aux f g H) x y z hz protected lemma left_le_sup (f g : linear_pmap R E F) (h : ∀ (x : f.domain) (y : g.domain), (x:E) = y → f x = g y) : f ≤ f.sup g h := begin refine ⟨le_sup_left, λ z₁ z₂ hz, _⟩, rw [← add_zero (f _), ← g.map_zero], refine (sup_apply h _ _ _ _).symm, simpa end protected lemma right_le_sup (f g : linear_pmap R E F) (h : ∀ (x : f.domain) (y : g.domain), (x:E) = y → f x = g y) : g ≤ f.sup g h := begin refine ⟨le_sup_right, λ z₁ z₂ hz, _⟩, rw [← zero_add (g _), ← f.map_zero], refine (sup_apply h _ _ _ _).symm, simpa end protected lemma sup_le {f g h : linear_pmap R E F} (H : ∀ (x : f.domain) (y : g.domain), (x:E) = y → f x = g y) (fh : f ≤ h) (gh : g ≤ h) : f.sup g H ≤ h := have Hf : f ≤ (f.sup g H) ⊓ h, from le_inf (f.left_le_sup g H) fh, have Hg : g ≤ (f.sup g H) ⊓ h, from le_inf (f.right_le_sup g H) gh, le_of_eq_locus_ge $ sup_le Hf.1 Hg.1 /-- Hypothesis for `linear_pmap.sup` holds, if `f.domain` is disjoint with `g.domain`. -/ lemma sup_h_of_disjoint (f g : linear_pmap R E F) (h : disjoint f.domain g.domain) (x : f.domain) (y : g.domain) (hxy : (x:E) = y) : f x = g y := begin rw [disjoint_def] at h, have hy : y = 0, from subtype.eq (h y (hxy ▸ x.2) y.2), have hx : x = 0, from subtype.eq (hxy.trans $ congr_arg _ hy), simp [*] end section variables {K : Type*} [division_ring K] [module K E] [module K F] /-- Extend a `linear_pmap` to `f.domain ⊔ K ∙ x`. -/ noncomputable def sup_span_singleton (f : linear_pmap K E F) (x : E) (y : F) (hx : x ∉ f.domain) : linear_pmap K E F := f.sup (mk_span_singleton x y (λ h₀, hx $ h₀.symm ▸ f.domain.zero_mem)) $ sup_h_of_disjoint _ _ $ by simpa [disjoint_span_singleton] @[simp] lemma domain_sup_span_singleton (f : linear_pmap K E F) (x : E) (y : F) (hx : x ∉ f.domain) : (f.sup_span_singleton x y hx).domain = f.domain ⊔ K ∙ x := rfl @[simp] lemma sup_span_singleton_apply_mk (f : linear_pmap K E F) (x : E) (y : F) (hx : x ∉ f.domain) (x' : E) (hx' : x' ∈ f.domain) (c : K) : f.sup_span_singleton x y hx ⟨x' + c • x, mem_sup.2 ⟨x', hx', _, mem_span_singleton.2 ⟨c, rfl⟩, rfl⟩⟩ = f ⟨x', hx'⟩ + c • y := begin erw [sup_apply _ ⟨x', hx'⟩ ⟨c • x, _⟩, mk_span_singleton_apply], refl, exact mem_span_singleton.2 ⟨c, rfl⟩ end end private lemma Sup_aux (c : set (linear_pmap R E F)) (hc : directed_on (≤) c) : ∃ f : ↥(Sup (domain '' c)) →ₗ[R] F, (⟨_, f⟩ : linear_pmap R E F) ∈ upper_bounds c := begin cases c.eq_empty_or_nonempty with ceq cne, { subst c, simp }, have hdir : directed_on (≤) (domain '' c), from directed_on_image.2 (hc.mono domain_mono.monotone), have P : Π x : Sup (domain '' c), {p : c // (x : E) ∈ p.val.domain }, { rintros x, apply classical.indefinite_description, have := (mem_Sup_of_directed (cne.image _) hdir).1 x.2, rwa [bex_image_iff, set_coe.exists'] at this }, set f : Sup (domain '' c) → F := λ x, (P x).val.val ⟨x, (P x).property⟩, have f_eq : ∀ (p : c) (x : Sup (domain '' c)) (y : p.1.1) (hxy : (x : E) = y), f x = p.1 y, { intros p x y hxy, rcases hc (P x).1.1 (P x).1.2 p.1 p.2 with ⟨q, hqc, hxq, hpq⟩, refine (hxq.2 _).trans (hpq.2 _).symm, exacts [of_le hpq.1 y, hxy, rfl] }, refine ⟨{ to_fun := f, .. }, _⟩, { intros x y, rcases hc (P x).1.1 (P x).1.2 (P y).1.1 (P y).1.2 with ⟨p, hpc, hpx, hpy⟩, set x' := of_le hpx.1 ⟨x, (P x).2⟩, set y' := of_le hpy.1 ⟨y, (P y).2⟩, rw [f_eq ⟨p, hpc⟩ x x' rfl, f_eq ⟨p, hpc⟩ y y' rfl, f_eq ⟨p, hpc⟩ (x + y) (x' + y') rfl, map_add] }, { intros c x, rw [f_eq (P x).1 (c • x) (c • ⟨x, (P x).2⟩) rfl, ← map_smul] }, { intros p hpc, refine ⟨le_Sup $ mem_image_of_mem domain hpc, λ x y hxy, eq.symm _⟩, exact f_eq ⟨p, hpc⟩ _ _ hxy.symm } end /-- Glue a collection of partially defined linear maps to a linear map defined on `Sup` of these submodules. -/ protected noncomputable def Sup (c : set (linear_pmap R E F)) (hc : directed_on (≤) c) : linear_pmap R E F := ⟨_, classical.some $ Sup_aux c hc⟩ protected lemma le_Sup {c : set (linear_pmap R E F)} (hc : directed_on (≤) c) {f : linear_pmap R E F} (hf : f ∈ c) : f ≤ linear_pmap.Sup c hc := classical.some_spec (Sup_aux c hc) hf protected lemma Sup_le {c : set (linear_pmap R E F)} (hc : directed_on (≤) c) {g : linear_pmap R E F} (hg : ∀ f ∈ c, f ≤ g) : linear_pmap.Sup c hc ≤ g := le_of_eq_locus_ge $ Sup_le $ λ _ ⟨f, hf, eq⟩, eq ▸ have f ≤ (linear_pmap.Sup c hc) ⊓ g, from le_inf (linear_pmap.le_Sup _ hf) (hg f hf), this.1 end linear_pmap namespace linear_map /-- Restrict a linear map to a submodule, reinterpreting the result as a `linear_pmap`. -/ def to_pmap (f : E →ₗ[R] F) (p : submodule R E) : linear_pmap R E F := ⟨p, f.comp p.subtype⟩ @[simp] lemma to_pmap_apply (f : E →ₗ[R] F) (p : submodule R E) (x : p) : f.to_pmap p x = f x := rfl /-- Compose a linear map with a `linear_pmap` -/ def comp_pmap (g : F →ₗ[R] G) (f : linear_pmap R E F) : linear_pmap R E G := { domain := f.domain, to_fun := g.comp f.to_fun } @[simp] lemma comp_pmap_apply (g : F →ₗ[R] G) (f : linear_pmap R E F) (x) : g.comp_pmap f x = g (f x) := rfl end linear_map namespace linear_pmap /-- Restrict codomain of a `linear_pmap` -/ def cod_restrict (f : linear_pmap R E F) (p : submodule R F) (H : ∀ x, f x ∈ p) : linear_pmap R E p := { domain := f.domain, to_fun := f.to_fun.cod_restrict p H } /-- Compose two `linear_pmap`s -/ def comp (g : linear_pmap R F G) (f : linear_pmap R E F) (H : ∀ x : f.domain, f x ∈ g.domain) : linear_pmap R E G := g.to_fun.comp_pmap $ f.cod_restrict _ H /-- `f.coprod g` is the partially defined linear map defined on `f.domain × g.domain`, and sending `p` to `f p.1 + g p.2`. -/ def coprod (f : linear_pmap R E G) (g : linear_pmap R F G) : linear_pmap R (E × F) G := { domain := f.domain.prod g.domain, to_fun := (f.comp (linear_pmap.fst f.domain g.domain) (λ x, x.2.1)).to_fun + (g.comp (linear_pmap.snd f.domain g.domain) (λ x, x.2.2)).to_fun } @[simp] lemma coprod_apply (f : linear_pmap R E G) (g : linear_pmap R F G) (x) : f.coprod g x = f ⟨(x : E × F).1, x.2.1⟩ + g ⟨(x : E × F).2, x.2.2⟩ := rfl end linear_pmap
4c8a1b8c05a78e6a9be131182b904e134026ad91
9db059bff49b1090a86ec0050ac6c577eb16ac67
/src/meetings/analysis.lean
e3f93e6b94acbe8c0ea4afb90e775119367a374f
[]
no_license
fpvandoorn/Harvard-tutoring
d64cd75c4c529009ee562c30e9cb245fe237e760
a8846c08e32cdc7b91a7e28adfa5d9b2810088b0
refs/heads/master
1,680,870,428,641
1,617,022,194,000
1,617,022,194,000
330,297,467
1
0
null
null
null
null
UTF-8
Lean
false
false
4,347
lean
import analysis.special_functions.trigonometric import analysis.special_functions.integrals import analysis.calculus.lhopital open set real topological_space measure_theory open_locale real topological_space big_operators ennreal /- # Analysis in Lean -/ example : deriv (λ x : ℝ, x^2) 2 = 4 := by norm_num example (x : ℝ) : deriv cos x = - sin x := by simp example (x : ℝ) : deriv (λ x, 2 * cos (cos x + 3) + 3) x = 2 * (sin (cos x + 3) * sin x) := by simp example : ∫ x : ℝ in 0..2, x ^ 3 = 4 := by norm_num example : ∫ x in 0..π, sin x / 2 = 1 := by norm_num example (x : ℝ) : ∫ t in 0..x, 2 * cos t = 2 * sin x := by simp /- Definitions in calculus: * Derivatives * Iterated derivatives * Analytic functions * Integration 1-dimensional calculus: * Fundamental theorem of calculus * L'Hôpital's rule * Intermediate value theorem Results in multivariable calculus: * Implicit function theorem * Inverse function theorem * Lagrange multipliers * The mean value theorem (vector-valued on a convex set) Various inequalities: * AM-GM inequality * Hölder's inequality * Minkowski inequality * Jensen's inequality -/ /- ## Differentiation -/ /- We want to define the derivative in a general setting. -/ #check @deriv /- Let `E` and `F` be normed spaces over `𝕜`. The Fréchet derivative of a map `f : E → F` at a point `x : E` is the continuous linear map `A : E → F` if `∥f y - f x - A (y - x)∥ / ∥ y - x ∥ ⟶ 0` as `y ⟶ x`. In other words: `f y = f x + A (y - x) + o (y - x)`. -/ #check @has_fderiv_at #check @has_fderiv_at_iff_tendsto #check @has_fderiv_at.unique /- We can also consider the derivative of `f` within a set `s` at the point `x`. -/ #check @has_fderiv_within_at #check @has_fderiv_within_at_iff_tendsto #check @unique_diff_within_at.eq /- `fderiv 𝕜 f x` is *the* Fréchet derivative of `f` at `x`. -/ #check @fderiv /- If `E = 𝕜`, then all these definitions simplify by applying the linear map to `(1 : 𝕜)`, and then the derivative is just an element in `F`. -/ #check @deriv open filter /- As an example, here are the statements of the mean value theorem and one version of l'Hôpital's rule for functions `ℝ → ℝ` `Icc a b` is `[a, b]` `Ico a b` is `[a, b)` -/ #check exists_has_deriv_at_eq_slope #check @has_deriv_at.lhopital_zero_nhds /- Integrals are defined in terms of the *Bochner integral*, which is a generalization of the *Lebesgue integral* for Banach spaces. -/ #check measurable_space /- A measure on a measurable space is a countably additive function into `ℝ≥0∞`/`[0,∞]` -/ #check measure_theory.measure example {X : Type*} [measurable_space X] (μ : measure X) : μ ∅ = 0 := by simp example {X : Type*} [measure_space X] : volume (∅ : set X) = 0 := by simp /- We can define the Lebesgue integral for nonnegative functions. -/ #check @simple_func.lintegral #check @lintegral example {X : Type*} [measurable_space X] (μ : measure X) {f g : X → ℝ≥0∞} (hf : measurable f) (hg : measurable g) : ∫⁻ a, f a + g a ∂μ = ∫⁻ a, f a ∂μ + ∫⁻ a, g a ∂μ := lintegral_add hf hg /- `f` is `μ`-integrable if `f` is measurable and `∫ x, ∥ f ∥ ∂μ < ∞` -/ #check @has_finite_integral #check @integrable /- The L¹ functions are the integrable functions modulo a.e.-equality. -/ #check measure.ae #check @Lp /- Now we can define the Bochner integral for simple L¹ functions. Since the simple L¹ functions are dense in all L¹ functions, we can continuously extend it. -/ #check @simple_func.integral #check @L1.integral variables {E : Type*} [normed_group E] [second_countable_topology E] [complete_space E] [normed_space ℝ E] [measurable_space E] [borel_space E] [second_countable_topology E] example {X : Type*} [measurable_space X] (μ : measure X) (A : set X) (f : X → E) : ∫ x in A, f x ∂μ = ∫ x, f x ∂(μ.restrict A) := by refl -- (μ.restrict A)(B) = μ (A ∩ B) /- The interval integral `∫ x in a..b, f x ∂μ` is defined to be the integral on `(a,b]` if `a ≤ b`. -/ #check @interval_integral.integral_of_le #check @interval_integral.integral_symm /- Here are parts 1 & 2 of the fundamental theorem of calculus. -/ #check @interval_integral.deriv_integral_right #check @interval_integral.integral_eq_sub_of_has_deriv_at
1262f76567da376d03155b66b9a4722112879781
63abd62053d479eae5abf4951554e1064a4c45b4
/src/data/sym2.lean
4cdc4b912aad40bedbbb214fbd87077b64e7eca0
[ "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,869
lean
/- Copyright (c) 2020 Kyle Miller All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Kyle Miller. -/ import tactic.linarith import data.sym open function open sym /-! # The symmetric square This file defines the symmetric square, which is `α × α` modulo swapping. This is also known as the type of unordered pairs. More generally, the symmetric square is the second symmetric power (see `data.sym`). The equivalence is `sym2.equiv_sym`. From the point of view that an unordered pair is equivalent to a multiset of cardinality two (see `sym2.equiv_multiset`), there is a `has_mem` instance `sym2.mem`, which is a `Prop`-valued membership test. Given `h : a ∈ z` for `z : sym2 α`, then `h.other` is the other element of the pair, defined using `classical.choice`. If `α` has decidable equality, then `h.other'` computably gives the other element. Recall that an undirected graph (allowing self loops, but no multiple edges) is equivalent to a symmetric relation on the vertex type `α`. Given a symmetric relation on `α`, the corresponding edge set is constructed by `sym2.from_rel`. ## Notation The symmetric square has a setoid instance, so `⟦(a, b)⟧` denotes a term of the symmetric square. ## Tags symmetric square, unordered pairs, symmetric powers -/ universe u variables {α : Type u} namespace sym2 /-- This is the relation capturing the notion of pairs equivalent up to permutations. -/ inductive rel (α : Type u) : (α × α) → (α × α) → Prop | refl (x y : α) : rel (x, y) (x, y) | swap (x y : α) : rel (x, y) (y, x) attribute [refl] rel.refl @[symm] lemma rel.symm {x y : α × α} : rel α x y → rel α y x := by rintro ⟨_, _⟩; constructor @[trans] lemma rel.trans {x y z : α × α} : rel α x y → rel α y z → rel α x z := by { intros a b, cases_matching* rel _ _ _; apply rel.refl <|> apply rel.swap } lemma rel.is_equivalence : equivalence (rel α) := by tidy; apply rel.trans; assumption instance rel.setoid (α : Type u) : setoid (α × α) := ⟨rel α, rel.is_equivalence⟩ end sym2 /-- `sym2 α` is the symmetric square of `α`, which, in other words, is the type of unordered pairs. It is equivalent in a natural way to multisets of cardinality 2 (see `sym2.equiv_multiset`). -/ @[reducible] def sym2 (α : Type u) := quotient (sym2.rel.setoid α) namespace sym2 lemma eq_swap {a b : α} : ⟦(a, b)⟧ = ⟦(b, a)⟧ := by { rw quotient.eq, apply rel.swap } lemma congr_right {a b c : α} : ⟦(a, b)⟧ = ⟦(a, c)⟧ ↔ b = c := by { split; intro h, { rw quotient.eq at h, cases h; refl }, rw h } lemma congr_left {a b c : α} : ⟦(b, a)⟧ = ⟦(c, a)⟧ ↔ b = c := by { split; intro h, { rw quotient.eq at h, cases h; refl }, rw h } /-- The functor `sym2` is functorial, and this function constructs the induced maps. -/ def map {α β : Type*} (f : α → β) : sym2 α → sym2 β := quotient.map (prod.map f f) (by { rintros _ _ h, cases h, { refl }, apply rel.swap }) @[simp] lemma map_id : sym2.map (@id α) = id := by tidy lemma map_comp {α β γ : Type*} {g : β → γ} {f : α → β} : sym2.map (g ∘ f) = sym2.map g ∘ sym2.map f := by tidy @[simp] lemma map_pair_eq {α β : Type*} (f : α → β) (x y : α) : map f ⟦(x, y)⟧ = ⟦(f x, f y)⟧ := by simp [map] section membership /-! ### Declarations about membership -/ /-- This is a predicate that determines whether a given term is a member of a term of the symmetric square. From this point of view, the symmetric square is the subtype of cardinality-two multisets on `α`. -/ def mem (x : α) (z : sym2 α) : Prop := ∃ (y : α), z = ⟦(x, y)⟧ instance : has_mem α (sym2 α) := ⟨mem⟩ lemma mk_has_mem (x y : α) : x ∈ ⟦(x, y)⟧ := ⟨y, rfl⟩ lemma mk_has_mem_right (x y : α) : y ∈ ⟦(x, y)⟧ := by { rw eq_swap, apply mk_has_mem } /-- Given an element of the unordered pair, give the other element using `classical.some`. See also `mem.other'` for the computable version. -/ noncomputable def mem.other {a : α} {z : sym2 α} (h : a ∈ z) : α := classical.some h @[simp] lemma mem_other_spec {a : α} {z : sym2 α} (h : a ∈ z) : ⟦(a, h.other)⟧ = z := by erw ← classical.some_spec h lemma eq_iff {x y z w : α} : ⟦(x, y)⟧ = ⟦(z, w)⟧ ↔ (x = z ∧ y = w) ∨ (x = w ∧ y = z) := begin split; intro h, { rw quotient.eq at h, cases h; tidy }, { cases h; rw [h.1, h.2], rw eq_swap } end @[simp] lemma mem_iff {a b c : α} : a ∈ ⟦(b, c)⟧ ↔ a = b ∨ a = c := { mp := by { rintro ⟨_, h⟩, rw eq_iff at h, tidy }, mpr := by { rintro ⟨_⟩; subst a, { apply mk_has_mem }, apply mk_has_mem_right } } lemma mem_other_mem {a : α} {z : sym2 α} (h : a ∈ z) : h.other ∈ z := by { convert mk_has_mem_right a h.other, rw mem_other_spec h } lemma elems_iff_eq {x y : α} {z : sym2 α} (hne : x ≠ y) : x ∈ z ∧ y ∈ z ↔ z = ⟦(x, y)⟧ := begin split, { refine quotient.rec_on_subsingleton z _, rintros ⟨z₁, z₂⟩ ⟨hx, hy⟩, rw eq_iff, cases mem_iff.mp hx with hx hx; cases mem_iff.mp hy with hy hy; cc }, { rintro rfl, simp }, end @[ext] lemma sym2_ext (z z' : sym2 α) (h : ∀ x, x ∈ z ↔ x ∈ z') : z = z' := begin refine quotient.rec_on_subsingleton z (λ w, _) h, refine quotient.rec_on_subsingleton z' (λ w', _), intro h, cases w with x y, cases w' with x' y', simp only [mem_iff] at h, apply eq_iff.mpr, have hx := h x, have hy := h y, have hx' := h x', have hy' := h y', simp only [true_iff, true_or, eq_self_iff_true, iff_true, or_true] at hx hy hx' hy', cases hx; subst x; cases hy; subst y; cases hx'; try { subst x' }; cases hy'; try { subst y' }; cc, end end membership /-- A type `α` is naturally included in the diagonal of `α × α`, and this function gives the image of this diagonal in `sym2 α`. -/ def diag (x : α) : sym2 α := ⟦(x, x)⟧ /-- A predicate for testing whether an element of `sym2 α` is on the diagonal. -/ def is_diag (z : sym2 α) : Prop := z ∈ set.range (@diag α) @[simp] lemma diag_is_diag (a : α) : is_diag (diag a) := by use a @[simp] lemma is_diag_iff_proj_eq (z : α × α) : is_diag ⟦z⟧ ↔ z.1 = z.2 := begin cases z with a, split, { rintro ⟨_, h⟩, erw eq_iff at h, cc }, { rintro ⟨⟩, use a, refl }, end instance is_diag.decidable_pred (α : Type u) [decidable_eq α] : decidable_pred (@is_diag α) := by { refine λ z, quotient.rec_on_subsingleton z (λ a, _), erw is_diag_iff_proj_eq, apply_instance } lemma mem_other_ne {a : α} {z : sym2 α} (hd : ¬is_diag z) (h : a ∈ z) : h.other ≠ a := begin intro hn, apply hd, have h' := sym2.mem_other_spec h, rw hn at h', rw ←h', simp, end section relations /-! ### Declarations about symmetric relations -/ variables {r : α → α → Prop} /-- Symmetric relations define a set on `sym2 α` by taking all those pairs of elements that are related. -/ def from_rel (sym : symmetric r) : set (sym2 α) := {z | quotient.rec_on z (λ z, r z.1 z.2) (by { rintros _ _ ⟨_,_⟩, tidy })} @[simp] lemma from_rel_proj_prop {sym : symmetric r} {z : α × α} : ⟦z⟧ ∈ from_rel sym ↔ r z.1 z.2 := by tidy @[simp] lemma from_rel_prop {sym : symmetric r} {a b : α} : ⟦(a, b)⟧ ∈ from_rel sym ↔ r a b := by simp only [from_rel_proj_prop] lemma from_rel_irreflexive {sym : symmetric r} : irreflexive r ↔ ∀ {z}, z ∈ from_rel sym → ¬is_diag z := { mp := by { intros h z hr hd, induction z, erw is_diag_iff_proj_eq at hd, erw from_rel_proj_prop at hr, tidy }, mpr := by { intros h x hr, rw ← @from_rel_prop _ _ sym at hr, exact h hr ⟨x, rfl⟩ }} lemma mem_from_rel_irrefl_other_ne {sym : symmetric r} (irrefl : irreflexive r) {a : α} {z : sym2 α} (hz : z ∈ from_rel sym) (h : a ∈ z) : h.other ≠ a := mem_other_ne (from_rel_irreflexive.mp irrefl hz) h instance from_rel.decidable_as_set (sym : symmetric r) [h : decidable_rel r] : decidable_pred (λ x, x ∈ sym2.from_rel sym) := λ (x : sym2 α), quotient.rec_on x (λ x', by { simp_rw from_rel_proj_prop, apply_instance }) (by tidy) instance from_rel.decidable_pred (sym : symmetric r) [h : decidable_rel r] : decidable_pred (sym2.from_rel sym) := by { change decidable_pred (λ x, x ∈ sym2.from_rel sym), apply_instance } end relations section sym_equiv /-! ### Equivalence to the second symmetric power -/ local attribute [instance] vector.perm.is_setoid private def from_vector {α : Type*} : vector α 2 → α × α | ⟨[a, b], h⟩ := (a, b) private lemma perm_card_two_iff {α : Type*} {a₁ b₁ a₂ b₂ : α} : [a₁, b₁].perm [a₂, b₂] ↔ (a₁ = a₂ ∧ b₁ = b₂) ∨ (a₁ = b₂ ∧ b₁ = a₂) := { mp := by { simp [← multiset.coe_eq_coe, ← multiset.cons_coe, multiset.cons_eq_cons]; tidy }, mpr := by { intro h, cases h; rw [h.1, h.2], apply list.perm.swap', refl } } /-- The symmetric square is equivalent to length-2 vectors up to permutations. -/ def sym2_equiv_sym' {α : Type*} : equiv (sym2 α) (sym' α 2) := { to_fun := quotient.map (λ (x : α × α), ⟨[x.1, x.2], rfl⟩) (by { rintros _ _ ⟨_⟩, { refl }, apply list.perm.swap', refl }), inv_fun := quotient.map from_vector (begin rintros ⟨x, hx⟩ ⟨y, hy⟩ h, cases x with _ x, { simp at hx; tauto }, cases x with _ x, { simp at hx; norm_num at hx }, cases x with _ x, swap, { exfalso, simp at hx; linarith [hx] }, cases y with _ y, { simp at hy; tauto }, cases y with _ y, { simp at hy; norm_num at hy }, cases y with _ y, swap, { exfalso, simp at hy; linarith [hy] }, rcases perm_card_two_iff.mp h with ⟨rfl,rfl⟩|⟨rfl,rfl⟩, { refl }, apply sym2.rel.swap, end), left_inv := by tidy, right_inv := λ x, begin refine quotient.rec_on_subsingleton x (λ x, _), { cases x with x hx, cases x with _ x, { simp at hx; tauto }, cases x with _ x, { simp at hx; norm_num at hx }, cases x with _ x, swap, { exfalso, simp at hx; linarith [hx] }, refl }, end } /-- The symmetric square is equivalent to the second symmetric power. -/ def equiv_sym (α : Type*) : sym2 α ≃ sym α 2 := equiv.trans sym2_equiv_sym' sym_equiv_sym'.symm /-- The symmetric square is equivalent to multisets of cardinality two. (This is currently a synonym for `equiv_sym`, but it's provided in case the definition for `sym` changes.) -/ def equiv_multiset (α : Type*) : sym2 α ≃ {s : multiset α // s.card = 2} := equiv_sym α end sym_equiv section decidable /-- An algorithm for computing `sym2.rel`. -/ def rel_bool [decidable_eq α] (x y : α × α) : bool := if x.1 = y.1 then x.2 = y.2 else if x.1 = y.2 then x.2 = y.1 else ff lemma rel_bool_spec [decidable_eq α] (x y : α × α) : ↥(rel_bool x y) ↔ rel α x y := begin cases x with x₁ x₂, cases y with y₁ y₂, dsimp [rel_bool], split_ifs; simp only [false_iff, bool.coe_sort_ff, bool.of_to_bool_iff], rotate 2, { contrapose! h, cases h; cc }, all_goals { subst x₁, split; intro h1, { subst h1; apply sym2.rel.swap }, { cases h1; cc } } end /-- Given `[decidable_eq α]` and `[fintype α]`, the following instance gives `fintype (sym2 α)`. -/ instance (α : Type*) [decidable_eq α] : decidable_rel (sym2.rel α) := λ x y, decidable_of_bool (rel_bool x y) (rel_bool_spec x y) /-- A function that gives the other element of a pair given one of the elements. Used in `mem.other'`. -/ private def pair_other [decidable_eq α] (a : α) (z : α × α) : α := if a = z.1 then z.2 else z.1 /-- Get the other element of the unordered pair using the decidable equality. This is the computable version of `mem.other`. -/ def mem.other' [decidable_eq α] {a : α} {z : sym2 α} (h : a ∈ z) : α := quot.rec (λ x h', pair_other a x) (begin clear h z, intros x y h, ext hy, convert_to pair_other a x = _, { have h' : ∀ {c e h}, @eq.rec _ ⟦x⟧ (λ s, a ∈ s → α) (λ _, pair_other a x) c e h = pair_other a x, { intros _ e _, subst e }, apply h', }, have h' := (rel_bool_spec x y).mpr h, cases x with x₁ x₂, cases y with y₁ y₂, cases mem_iff.mp hy with hy'; subst a; dsimp [rel_bool] at h'; split_ifs at h'; try { rw bool.of_to_bool_iff at h', subst x₁, subst x₂ }; dsimp [pair_other], simp only [ne.symm h_1, if_true, eq_self_iff_true, if_false], exfalso, exact bool.not_ff h', simp only [h_1, if_true, eq_self_iff_true, if_false], exfalso, exact bool.not_ff h', end) z h @[simp] lemma mem_other_spec' [decidable_eq α] {a : α} {z : sym2 α} (h : a ∈ z) : ⟦(a, h.other')⟧ = z := begin induction z, cases z with x y, have h' := mem_iff.mp h, dsimp [mem.other', quot.rec, pair_other], cases h'; subst a, { simp only [if_true, eq_self_iff_true], refl, }, { split_ifs, subst h_1, refl, rw eq_swap, refl, }, refl, end @[simp] lemma other_eq_other' [decidable_eq α] {a : α} {z : sym2 α} (h : a ∈ z) : h.other = h.other' := by rw [←congr_right, mem_other_spec' h, mem_other_spec] lemma mem_other_mem' [decidable_eq α] {a : α} {z : sym2 α} (h : a ∈ z) : h.other' ∈ z := by { rw ←other_eq_other', exact mem_other_mem h } lemma other_invol' [decidable_eq α] {a : α} {z : sym2 α} (ha : a ∈ z) (hb : ha.other' ∈ z): hb.other' = a := begin induction z, cases z with x y, dsimp [mem.other', quot.rec, pair_other] at hb, split_ifs at hb; dsimp [mem.other', quot.rec, pair_other], simp only [h, if_true, eq_self_iff_true], split_ifs, assumption, refl, simp only [h, if_false, if_true, eq_self_iff_true], cases mem_iff.mp ha; cc, refl, end lemma other_invol {a : α} {z : sym2 α} (ha : a ∈ z) (hb : ha.other ∈ z): hb.other = a := begin classical, rw other_eq_other' at hb ⊢, convert other_invol' ha hb, rw other_eq_other', end end decidable end sym2
8f580ea9bc559257c5adf5cd8a156b14daff160c
761fea1362b10b4c588c2dfc0ae90c70b119e35d
/src/dump.lean
2ae437a56d1c1ab25cba463a2e58104f1244a5f0
[]
no_license
holtzermann17/mm-lean
382a29fca5245f97cf488c525ed0c9594917f73b
a9130d71ed448f62df28d4128043b707bad85ccd
refs/heads/master
1,588,477,413,982
1,553,885,046,000
1,553,885,046,000
178,404,617
0
0
null
1,553,863,829,000
1,553,863,828,000
null
UTF-8
Lean
false
false
1,865
lean
import imports mathematica system.io open native tactic mathematica meta def gen_thm : tactic $ list (name × expr) := do env ← get_env, return $ env.fold [] (λ dcl l, match dcl with | declaration.defn nm _ tp val _ tt := (nm, tp) :: l | declaration.thm nm _ tp val := (nm, tp) :: l | _ := l end) -- todo: rewrite this using get_decl meta def gen_thm_by_name (ln : list name) : tactic $ list (name × expr) := do env ← get_env, return $ env.fold [] (λ dcl l, match dcl with | declaration.defn nm _ tp val _ tt := if nm ∈ ln then (nm, tp) :: l else l | declaration.thm nm _ tp val := if nm ∈ ln then (nm, tp) :: l else l | _ := l end) meta def write_string (s : string) : tactic unit := unsafe_run_io $ @write_file "temp.txt" s io.mode.write meta def dump (n : ℕ) : tactic format := do l ← gen_thm, let f := λ e : name × expr, (e.1, e.2, form_of_expr e.2) in do tactic.pp $ list.map f $ list.take n l >>= return meta def dump_all : tactic format := do l ← gen_thm, let f := λ e : name × expr, (e.1, e.2, form_of_expr e.2) in do tactic.pp $ list.map f $ l >>= return meta def dump_search (l : list string) : tactic format := do l ← monad.mapm parse_name_tac l, l ← gen_thm_by_name l, let f := λ e : name × expr, (e.1, e.2, form_of_expr e.2) in do tactic.pp $ list.map f $ l >>= return /- save the buffer manually -/ -- run_cmd dump 2 >>= trace -- run_cmd dump_all >>= trace def thms := ["add_comm", "add_assoc", "nat.lt_add_left"] run_cmd dump_search thms >>= trace /- dump with writing to files -/ -- run_cmd do -- d ← dump 2, -- write_string d.to_string -- run_cmd do -- d ← dump_all, -- write_string d.to_string -- run_cmd do -- d ← dump_search thms, -- write_string d.to_string
2c82acc23c5f9f0a8b971ba74fe815a133cf3fb4
26ac254ecb57ffcb886ff709cf018390161a9225
/src/computability/primrec.lean
7e24e71db4b10e605363a591132bf07a7b39c5d5
[ "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
51,998
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Mario Carneiro -/ import data.equiv.list /-! # The primitive recursive functions The primitive recursive functions are the least collection of functions `nat → nat` which are closed under projections (using the mkpair pairing function), composition, zero, successor, and primitive recursion (i.e. nat.rec where the motive is C n := nat). We can extend this definition to a large class of basic types by using canonical encodings of types as natural numbers (Gödel numbering), which we implement through the type class `encodable`. (More precisely, we need that the composition of encode with decode yields a primitive recursive function, so we have the `primcodable` type class for this.) ## References * [Mario Carneiro, *Formalizing computability theory via partial recursive functions*][carneiro2019] -/ open denumerable encodable namespace nat def elim {C : Sort*} : C → (ℕ → C → C) → ℕ → C := @nat.rec (λ _, C) @[simp] theorem elim_zero {C} (a f) : @nat.elim C a f 0 = a := rfl @[simp] theorem elim_succ {C} (a f n) : @nat.elim C a f (succ n) = f n (nat.elim a f n) := rfl def cases {C : Sort*} (a : C) (f : ℕ → C) : ℕ → C := nat.elim a (λ n _, f n) @[simp] theorem cases_zero {C} (a f) : @nat.cases C a f 0 = a := rfl @[simp] theorem cases_succ {C} (a f n) : @nat.cases C a f (succ n) = f n := rfl @[simp, reducible] def unpaired {α} (f : ℕ → ℕ → α) (n : ℕ) : α := f n.unpair.1 n.unpair.2 /-- The primitive recursive functions `ℕ → ℕ`. -/ inductive primrec : (ℕ → ℕ) → Prop | zero : primrec (λ n, 0) | succ : primrec succ | left : primrec (λ n, n.unpair.1) | right : primrec (λ n, n.unpair.2) | pair {f g} : primrec f → primrec g → primrec (λ n, mkpair (f n) (g n)) | comp {f g} : primrec f → primrec g → primrec (λ n, f (g n)) | prec {f g} : primrec f → primrec g → primrec (unpaired (λ z n, n.elim (f z) (λ y IH, g $ mkpair z $ mkpair y IH))) namespace primrec theorem of_eq {f g : ℕ → ℕ} (hf : primrec f) (H : ∀ n, f n = g n) : primrec g := (funext H : f = g) ▸ hf theorem const : ∀ (n : ℕ), primrec (λ _, n) | 0 := zero | (n+1) := succ.comp (const n) protected theorem id : primrec id := (left.pair right).of_eq $ λ n, by simp theorem prec1 {f} (m : ℕ) (hf : primrec f) : primrec (λ n, n.elim m (λ y IH, f $ mkpair y IH)) := ((prec (const m) (hf.comp right)).comp (zero.pair primrec.id)).of_eq $ λ n, by simp; dsimp; rw [unpair_mkpair] theorem cases1 {f} (m : ℕ) (hf : primrec f) : primrec (nat.cases m f) := (prec1 m (hf.comp left)).of_eq $ by simp [cases] theorem cases {f g} (hf : primrec f) (hg : primrec g) : primrec (unpaired (λ z n, n.cases (f z) (λ y, g $ mkpair z y))) := (prec hf (hg.comp (pair left (left.comp right)))).of_eq $ by simp [cases] protected theorem swap : primrec (unpaired (function.swap mkpair)) := (pair right left).of_eq $ λ n, by simp theorem swap' {f} (hf : primrec (unpaired f)) : primrec (unpaired (function.swap f)) := (hf.comp primrec.swap).of_eq $ λ n, by simp theorem pred : primrec pred := (cases1 0 primrec.id).of_eq $ λ n, by cases n; simp * theorem add : primrec (unpaired (+)) := (prec primrec.id ((succ.comp right).comp right)).of_eq $ λ p, by simp; induction p.unpair.2; simp [*, -add_comm, add_succ] theorem sub : primrec (unpaired has_sub.sub) := (prec primrec.id ((pred.comp right).comp right)).of_eq $ λ p, by simp; induction p.unpair.2; simp [*, -add_comm, sub_succ] theorem mul : primrec (unpaired (*)) := (prec zero (add.comp (pair left (right.comp right)))).of_eq $ λ p, by simp; induction p.unpair.2; simp [*, mul_succ, add_comm] theorem pow : primrec (unpaired (^)) := (prec (const 1) (mul.comp (pair (right.comp right) left))).of_eq $ λ p, by simp; induction p.unpair.2; simp [*, nat.pow_succ] end primrec end nat section prio set_option default_priority 100 -- see Note [default priority] /-- A `primcodable` type is an `encodable` type for which the encode/decode functions are primitive recursive. -/ class primcodable (α : Type*) extends encodable α := (prim [] : nat.primrec (λ n, encodable.encode (decode n))) end prio namespace primcodable open nat.primrec @[priority 10] instance of_denumerable (α) [denumerable α] : primcodable α := ⟨succ.of_eq $ by simp⟩ def of_equiv (α) {β} [primcodable α] (e : β ≃ α) : primcodable β := { prim := (primcodable.prim α).of_eq $ λ n, show encode (decode α n) = (option.cases_on (option.map e.symm (decode α n)) 0 (λ a, nat.succ (encode (e a))) : ℕ), by cases decode α n; dsimp; simp, ..encodable.of_equiv α e } instance empty : primcodable empty := ⟨zero⟩ instance unit : primcodable punit := ⟨(cases1 1 zero).of_eq $ λ n, by cases n; simp⟩ instance option {α : Type*} [h : primcodable α] : primcodable (option α) := ⟨(cases1 1 ((cases1 0 (succ.comp succ)).comp (primcodable.prim α))).of_eq $ λ n, by cases n; simp; cases decode α n; refl⟩ instance bool : primcodable bool := ⟨(cases1 1 (cases1 2 zero)).of_eq $ λ n, begin cases n, {refl}, cases n, {refl}, rw decode_ge_two, {refl}, exact dec_trivial end⟩ end primcodable /-- `primrec f` means `f` is primitive recursive (after encoding its input and output as natural numbers). -/ def primrec {α β} [primcodable α] [primcodable β] (f : α → β) : Prop := nat.primrec (λ n, encode ((decode α n).map f)) namespace primrec variables {α : Type*} {β : Type*} {σ : Type*} variables [primcodable α] [primcodable β] [primcodable σ] open nat.primrec protected theorem encode : primrec (@encode α _) := (primcodable.prim α).of_eq $ λ n, by cases decode α n; refl protected theorem decode : primrec (decode α) := succ.comp (primcodable.prim α) theorem dom_denumerable {α β} [denumerable α] [primcodable β] {f : α → β} : primrec f ↔ nat.primrec (λ n, encode (f (of_nat α n))) := ⟨λ h, (pred.comp h).of_eq $ λ n, by simp; refl, λ h, (succ.comp h).of_eq $ λ n, by simp; refl⟩ theorem nat_iff {f : ℕ → ℕ} : primrec f ↔ nat.primrec f := dom_denumerable theorem encdec : primrec (λ n, encode (decode α n)) := nat_iff.2 (primcodable.prim α) theorem option_some : primrec (@some α) := ((cases1 0 (succ.comp succ)).comp (primcodable.prim α)).of_eq $ λ n, by cases decode α n; simp theorem of_eq {f g : α → σ} (hf : primrec f) (H : ∀ n, f n = g n) : primrec g := (funext H : f = g) ▸ hf theorem const (x : σ) : primrec (λ a : α, x) := ((cases1 0 (const (encode x).succ)).comp (primcodable.prim α)).of_eq $ λ n, by cases decode α n; refl protected theorem id : primrec (@id α) := (primcodable.prim α).of_eq $ by simp theorem comp {f : β → σ} {g : α → β} (hf : primrec f) (hg : primrec g) : primrec (λ a, f (g a)) := ((cases1 0 (hf.comp $ pred.comp hg)).comp (primcodable.prim α)).of_eq $ λ n, begin cases decode α n, {refl}, simp [encodek] end theorem succ : primrec nat.succ := nat_iff.2 nat.primrec.succ theorem pred : primrec nat.pred := nat_iff.2 nat.primrec.pred theorem encode_iff {f : α → σ} : primrec (λ a, encode (f a)) ↔ primrec f := ⟨λ h, nat.primrec.of_eq h $ λ n, by cases decode α n; refl, primrec.encode.comp⟩ theorem of_nat_iff {α β} [denumerable α] [primcodable β] {f : α → β} : primrec f ↔ primrec (λ n, f (of_nat α n)) := dom_denumerable.trans $ nat_iff.symm.trans encode_iff protected theorem of_nat (α) [denumerable α] : primrec (of_nat α) := of_nat_iff.1 primrec.id theorem option_some_iff {f : α → σ} : primrec (λ a, some (f a)) ↔ primrec f := ⟨λ h, encode_iff.1 $ pred.comp $ encode_iff.2 h, option_some.comp⟩ theorem of_equiv {β} {e : β ≃ α} : by haveI := primcodable.of_equiv α e; exact primrec e := (primcodable.prim α).of_eq $ λ n, show _ = encode (option.map e (option.map _ _)), by cases decode α n; simp theorem of_equiv_symm {β} {e : β ≃ α} : by haveI := primcodable.of_equiv α e; exact primrec e.symm := by letI := primcodable.of_equiv α e; exact encode_iff.1 (show primrec (λ a, encode (e (e.symm a))), by simp [primrec.encode]) theorem of_equiv_iff {β} (e : β ≃ α) {f : σ → β} : by haveI := primcodable.of_equiv α e; exact primrec (λ a, e (f a)) ↔ primrec f := by letI := primcodable.of_equiv α e; exact ⟨λ h, (of_equiv_symm.comp h).of_eq (λ a, by simp), of_equiv.comp⟩ theorem of_equiv_symm_iff {β} (e : β ≃ α) {f : σ → α} : by haveI := primcodable.of_equiv α e; exact primrec (λ a, e.symm (f a)) ↔ primrec f := by letI := primcodable.of_equiv α e; exact ⟨λ h, (of_equiv.comp h).of_eq (λ a, by simp), of_equiv_symm.comp⟩ end primrec namespace primcodable open nat.primrec instance prod {α β} [primcodable α] [primcodable β] : primcodable (α × β) := ⟨((cases zero ((cases zero succ).comp (pair right ((primcodable.prim β).comp left)))).comp (pair right ((primcodable.prim α).comp left))).of_eq $ λ n, begin simp [nat.unpaired], cases decode α n.unpair.1, { simp }, cases decode β n.unpair.2; simp end⟩ end primcodable namespace primrec variables {α : Type*} {σ : Type*} [primcodable α] [primcodable σ] open nat.primrec theorem fst {α β} [primcodable α] [primcodable β] : primrec (@prod.fst α β) := ((cases zero ((cases zero (nat.primrec.succ.comp left)).comp (pair right ((primcodable.prim β).comp left)))).comp (pair right ((primcodable.prim α).comp left))).of_eq $ λ n, begin simp, cases decode α n.unpair.1; simp, cases decode β n.unpair.2; simp end theorem snd {α β} [primcodable α] [primcodable β] : primrec (@prod.snd α β) := ((cases zero ((cases zero (nat.primrec.succ.comp right)).comp (pair right ((primcodable.prim β).comp left)))).comp (pair right ((primcodable.prim α).comp left))).of_eq $ λ n, begin simp, cases decode α n.unpair.1; simp, cases decode β n.unpair.2; simp end theorem pair {α β γ} [primcodable α] [primcodable β] [primcodable γ] {f : α → β} {g : α → γ} (hf : primrec f) (hg : primrec g) : primrec (λ a, (f a, g a)) := ((cases1 0 (nat.primrec.succ.comp $ pair (nat.primrec.pred.comp hf) (nat.primrec.pred.comp hg))).comp (primcodable.prim α)).of_eq $ λ n, by cases decode α n; simp [encodek]; refl theorem unpair : primrec nat.unpair := (pair (nat_iff.2 nat.primrec.left) (nat_iff.2 nat.primrec.right)).of_eq $ λ n, by simp theorem list_nth₁ : ∀ (l : list α), primrec l.nth | [] := dom_denumerable.2 zero | (a::l) := dom_denumerable.2 $ (cases1 (encode a).succ $ dom_denumerable.1 $ list_nth₁ l).of_eq $ λ n, by cases n; simp end primrec /-- `primrec₂ f` means `f` is a binary primitive recursive function. This is technically unnecessary since we can always curry all the arguments together, but there are enough natural two-arg functions that it is convenient to express this directly. -/ def primrec₂ {α β σ} [primcodable α] [primcodable β] [primcodable σ] (f : α → β → σ) := primrec (λ p : α × β, f p.1 p.2) /-- `primrec_pred p` means `p : α → Prop` is a (decidable) primitive recursive predicate, which is to say that `to_bool ∘ p : α → bool` is primitive recursive. -/ def primrec_pred {α} [primcodable α] (p : α → Prop) [decidable_pred p] := primrec (λ a, to_bool (p a)) /-- `primrec_rel p` means `p : α → β → Prop` is a (decidable) primitive recursive relation, which is to say that `to_bool ∘ p : α → β → bool` is primitive recursive. -/ def primrec_rel {α β} [primcodable α] [primcodable β] (s : α → β → Prop) [∀ a b, decidable (s a b)] := primrec₂ (λ a b, to_bool (s a b)) namespace primrec₂ variables {α : Type*} {β : Type*} {σ : Type*} variables [primcodable α] [primcodable β] [primcodable σ] theorem of_eq {f g : α → β → σ} (hg : primrec₂ f) (H : ∀ a b, f a b = g a b) : primrec₂ g := (by funext a b; apply H : f = g) ▸ hg theorem const (x : σ) : primrec₂ (λ (a : α) (b : β), x) := primrec.const _ protected theorem pair : primrec₂ (@prod.mk α β) := primrec.pair primrec.fst primrec.snd theorem left : primrec₂ (λ (a : α) (b : β), a) := primrec.fst theorem right : primrec₂ (λ (a : α) (b : β), b) := primrec.snd theorem mkpair : primrec₂ nat.mkpair := by simp [primrec₂, primrec]; constructor theorem unpaired {f : ℕ → ℕ → α} : primrec (nat.unpaired f) ↔ primrec₂ f := ⟨λ h, by simpa using h.comp mkpair, λ h, h.comp primrec.unpair⟩ theorem unpaired' {f : ℕ → ℕ → ℕ} : nat.primrec (nat.unpaired f) ↔ primrec₂ f := primrec.nat_iff.symm.trans unpaired theorem encode_iff {f : α → β → σ} : primrec₂ (λ a b, encode (f a b)) ↔ primrec₂ f := primrec.encode_iff theorem option_some_iff {f : α → β → σ} : primrec₂ (λ a b, some (f a b)) ↔ primrec₂ f := primrec.option_some_iff theorem of_nat_iff {α β σ} [denumerable α] [denumerable β] [primcodable σ] {f : α → β → σ} : primrec₂ f ↔ primrec₂ (λ m n : ℕ, f (of_nat α m) (of_nat β n)) := (primrec.of_nat_iff.trans $ by simp).trans unpaired theorem uncurry {f : α → β → σ} : primrec (function.uncurry f) ↔ primrec₂ f := by rw [show function.uncurry f = λ (p : α × β), f p.1 p.2, from funext $ λ ⟨a, b⟩, rfl]; refl theorem curry {f : α × β → σ} : primrec₂ (function.curry f) ↔ primrec f := by rw [← uncurry, function.uncurry_curry] end primrec₂ section comp variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} {σ : Type*} variables [primcodable α] [primcodable β] [primcodable γ] [primcodable δ] [primcodable σ] theorem primrec.comp₂ {f : γ → σ} {g : α → β → γ} (hf : primrec f) (hg : primrec₂ g) : primrec₂ (λ a b, f (g a b)) := hf.comp hg theorem primrec₂.comp {f : β → γ → σ} {g : α → β} {h : α → γ} (hf : primrec₂ f) (hg : primrec g) (hh : primrec h) : primrec (λ a, f (g a) (h a)) := hf.comp (hg.pair hh) theorem primrec₂.comp₂ {f : γ → δ → σ} {g : α → β → γ} {h : α → β → δ} (hf : primrec₂ f) (hg : primrec₂ g) (hh : primrec₂ h) : primrec₂ (λ a b, f (g a b) (h a b)) := hf.comp hg hh theorem primrec_pred.comp {p : β → Prop} [decidable_pred p] {f : α → β} : primrec_pred p → primrec f → primrec_pred (λ a, p (f a)) := primrec.comp theorem primrec_rel.comp {R : β → γ → Prop} [∀ a b, decidable (R a b)] {f : α → β} {g : α → γ} : primrec_rel R → primrec f → primrec g → primrec_pred (λ a, R (f a) (g a)) := primrec₂.comp theorem primrec_rel.comp₂ {R : γ → δ → Prop} [∀ a b, decidable (R a b)] {f : α → β → γ} {g : α → β → δ} : primrec_rel R → primrec₂ f → primrec₂ g → primrec_rel (λ a b, R (f a b) (g a b)) := primrec_rel.comp end comp theorem primrec_pred.of_eq {α} [primcodable α] {p q : α → Prop} [decidable_pred p] [decidable_pred q] (hp : primrec_pred p) (H : ∀ a, p a ↔ q a) : primrec_pred q := primrec.of_eq hp (λ a, to_bool_congr (H a)) theorem primrec_rel.of_eq {α β} [primcodable α] [primcodable β] {r s : α → β → Prop} [∀ a b, decidable (r a b)] [∀ a b, decidable (s a b)] (hr : primrec_rel r) (H : ∀ a b, r a b ↔ s a b) : primrec_rel s := primrec₂.of_eq hr (λ a b, to_bool_congr (H a b)) namespace primrec₂ variables {α : Type*} {β : Type*} {σ : Type*} variables [primcodable α] [primcodable β] [primcodable σ] open nat.primrec theorem swap {f : α → β → σ} (h : primrec₂ f) : primrec₂ (function.swap f) := h.comp₂ primrec₂.right primrec₂.left theorem nat_iff {f : α → β → σ} : primrec₂ f ↔ nat.primrec (nat.unpaired $ λ m n : ℕ, encode $ (decode α m).bind $ λ a, (decode β n).map (f a)) := have ∀ (a : option α) (b : option β), option.map (λ (p : α × β), f p.1 p.2) (option.bind a (λ (a : α), option.map (prod.mk a) b)) = option.bind a (λ a, option.map (f a) b), by intros; cases a; [refl, {cases b; refl}], by simp [primrec₂, primrec, this] theorem nat_iff' {f : α → β → σ} : primrec₂ f ↔ primrec₂ (λ m n : ℕ, option.bind (decode α m) (λ a, option.map (f a) (decode β n))) := nat_iff.trans $ unpaired'.trans encode_iff end primrec₂ namespace primrec variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} {σ : Type*} variables [primcodable α] [primcodable β] [primcodable γ] [primcodable δ] [primcodable σ] theorem to₂ {f : α × β → σ} (hf : primrec f) : primrec₂ (λ a b, f (a, b)) := hf.of_eq $ λ ⟨a, b⟩, rfl theorem nat_elim {f : α → β} {g : α → ℕ × β → β} (hf : primrec f) (hg : primrec₂ g) : primrec₂ (λ a (n : ℕ), n.elim (f a) (λ n IH, g a (n, IH))) := primrec₂.nat_iff.2 $ ((nat.primrec.cases nat.primrec.zero $ (nat.primrec.prec hf $ nat.primrec.comp hg $ nat.primrec.left.pair $ (nat.primrec.left.comp nat.primrec.right).pair $ nat.primrec.pred.comp $ nat.primrec.right.comp nat.primrec.right).comp $ nat.primrec.right.pair $ nat.primrec.right.comp nat.primrec.left).comp $ nat.primrec.id.pair $ (primcodable.prim α).comp nat.primrec.left).of_eq $ λ n, begin simp, cases decode α n.unpair.1 with a, {refl}, simp [encodek], induction n.unpair.2 with m; simp [encodek], simp [ih, encodek] end theorem nat_elim' {f : α → ℕ} {g : α → β} {h : α → ℕ × β → β} (hf : primrec f) (hg : primrec g) (hh : primrec₂ h) : primrec (λ a, (f a).elim (g a) (λ n IH, h a (n, IH))) := (nat_elim hg hh).comp primrec.id hf theorem nat_elim₁ {f : ℕ → α → α} (a : α) (hf : primrec₂ f) : primrec (nat.elim a f) := nat_elim' primrec.id (const a) $ comp₂ hf primrec₂.right theorem nat_cases' {f : α → β} {g : α → ℕ → β} (hf : primrec f) (hg : primrec₂ g) : primrec₂ (λ a, nat.cases (f a) (g a)) := nat_elim hf $ hg.comp₂ primrec₂.left $ comp₂ fst primrec₂.right theorem nat_cases {f : α → ℕ} {g : α → β} {h : α → ℕ → β} (hf : primrec f) (hg : primrec g) (hh : primrec₂ h) : primrec (λ a, (f a).cases (g a) (h a)) := (nat_cases' hg hh).comp primrec.id hf theorem nat_cases₁ {f : ℕ → α} (a : α) (hf : primrec f) : primrec (nat.cases a f) := nat_cases primrec.id (const a) (comp₂ hf primrec₂.right) theorem nat_iterate {f : α → ℕ} {g : α → β} {h : α → β → β} (hf : primrec f) (hg : primrec g) (hh : primrec₂ h) : primrec (λ a, (h a)^[f a] (g a)) := (nat_elim' hf hg (hh.comp₂ primrec₂.left $ snd.comp₂ primrec₂.right)).of_eq $ λ a, by induction f a; simp [*, function.iterate_succ'] theorem option_cases {o : α → option β} {f : α → σ} {g : α → β → σ} (ho : primrec o) (hf : primrec f) (hg : primrec₂ g) : @primrec _ σ _ _ (λ a, option.cases_on (o a) (f a) (g a)) := encode_iff.1 $ (nat_cases (encode_iff.2 ho) (encode_iff.2 hf) $ pred.comp₂ $ primrec₂.encode_iff.2 $ (primrec₂.nat_iff'.1 hg).comp₂ ((@primrec.encode α _).comp fst).to₂ primrec₂.right).of_eq $ λ a, by cases o a with b; simp [encodek]; refl theorem option_bind {f : α → option β} {g : α → β → option σ} (hf : primrec f) (hg : primrec₂ g) : primrec (λ a, (f a).bind (g a)) := (option_cases hf (const none) hg).of_eq $ λ a, by cases f a; refl theorem option_bind₁ {f : α → option σ} (hf : primrec f) : primrec (λ o, option.bind o f) := option_bind primrec.id (hf.comp snd).to₂ theorem option_map {f : α → option β} {g : α → β → σ} (hf : primrec f) (hg : primrec₂ g) : primrec (λ a, (f a).map (g a)) := option_bind hf (option_some.comp₂ hg) theorem option_map₁ {f : α → σ} (hf : primrec f) : primrec (option.map f) := option_map primrec.id (hf.comp snd).to₂ theorem option_iget [inhabited α] : primrec (@option.iget α _) := (option_cases primrec.id (const $ default α) primrec₂.right).of_eq $ λ o, by cases o; refl theorem option_is_some : primrec (@option.is_some α) := (option_cases primrec.id (const ff) (const tt).to₂).of_eq $ λ o, by cases o; refl theorem option_get_or_else : primrec₂ (@option.get_or_else α) := primrec.of_eq (option_cases primrec₂.left primrec₂.right primrec₂.right) $ λ ⟨o, a⟩, by cases o; refl theorem bind_decode_iff {f : α → β → option σ} : primrec₂ (λ a n, (decode β n).bind (f a)) ↔ primrec₂ f := ⟨λ h, by simpa [encodek] using h.comp fst ((@primrec.encode β _).comp snd), λ h, option_bind (primrec.decode.comp snd) $ h.comp (fst.comp fst) snd⟩ theorem map_decode_iff {f : α → β → σ} : primrec₂ (λ a n, (decode β n).map (f a)) ↔ primrec₂ f := bind_decode_iff.trans primrec₂.option_some_iff theorem nat_add : primrec₂ ((+) : ℕ → ℕ → ℕ) := primrec₂.unpaired'.1 nat.primrec.add theorem nat_sub : primrec₂ (has_sub.sub : ℕ → ℕ → ℕ) := primrec₂.unpaired'.1 nat.primrec.sub theorem nat_mul : primrec₂ ((*) : ℕ → ℕ → ℕ) := primrec₂.unpaired'.1 nat.primrec.mul theorem cond {c : α → bool} {f : α → σ} {g : α → σ} (hc : primrec c) (hf : primrec f) (hg : primrec g) : primrec (λ a, cond (c a) (f a) (g a)) := (nat_cases (encode_iff.2 hc) hg (hf.comp fst).to₂).of_eq $ λ a, by cases c a; refl theorem ite {c : α → Prop} [decidable_pred c] {f : α → σ} {g : α → σ} (hc : primrec_pred c) (hf : primrec f) (hg : primrec g) : primrec (λ a, if c a then f a else g a) := by simpa using cond hc hf hg theorem nat_le : primrec_rel ((≤) : ℕ → ℕ → Prop) := (nat_cases nat_sub (const tt) (const ff).to₂).of_eq $ λ p, begin dsimp [function.swap], cases e : p.1 - p.2 with n, { simp [nat.sub_eq_zero_iff_le.1 e] }, { simp [not_le.2 (nat.lt_of_sub_eq_succ e)] } end theorem nat_min : primrec₂ (@min ℕ _) := ite nat_le fst snd theorem nat_max : primrec₂ (@max ℕ _) := ite nat_le snd fst theorem dom_bool (f : bool → α) : primrec f := (cond primrec.id (const (f tt)) (const (f ff))).of_eq $ λ b, by cases b; refl theorem dom_bool₂ (f : bool → bool → α) : primrec₂ f := (cond fst ((dom_bool (f tt)).comp snd) ((dom_bool (f ff)).comp snd)).of_eq $ λ ⟨a, b⟩, by cases a; refl protected theorem bnot : primrec bnot := dom_bool _ protected theorem band : primrec₂ band := dom_bool₂ _ protected theorem bor : primrec₂ bor := dom_bool₂ _ protected theorem not {p : α → Prop} [decidable_pred p] (hp : primrec_pred p) : primrec_pred (λ a, ¬ p a) := (primrec.bnot.comp hp).of_eq $ λ n, by simp protected theorem and {p q : α → Prop} [decidable_pred p] [decidable_pred q] (hp : primrec_pred p) (hq : primrec_pred q) : primrec_pred (λ a, p a ∧ q a) := (primrec.band.comp hp hq).of_eq $ λ n, by simp protected theorem or {p q : α → Prop} [decidable_pred p] [decidable_pred q] (hp : primrec_pred p) (hq : primrec_pred q) : primrec_pred (λ a, p a ∨ q a) := (primrec.bor.comp hp hq).of_eq $ λ n, by simp protected theorem eq [decidable_eq α] : primrec_rel (@eq α) := have primrec_rel (λ a b : ℕ, a = b), from (primrec.and nat_le nat_le.swap).of_eq $ λ a, by simp [le_antisymm_iff], (this.comp₂ (primrec.encode.comp₂ primrec₂.left) (primrec.encode.comp₂ primrec₂.right)).of_eq $ λ a b, encode_injective.eq_iff theorem nat_lt : primrec_rel ((<) : ℕ → ℕ → Prop) := (nat_le.comp snd fst).not.of_eq $ λ p, by simp theorem option_guard {p : α → β → Prop} [∀ a b, decidable (p a b)] (hp : primrec_rel p) {f : α → β} (hf : primrec f) : primrec (λ a, option.guard (p a) (f a)) := ite (hp.comp primrec.id hf) (option_some_iff.2 hf) (const none) theorem option_orelse : primrec₂ ((<|>) : option α → option α → option α) := (option_cases fst snd (fst.comp fst).to₂).of_eq $ λ ⟨o₁, o₂⟩, by cases o₁; cases o₂; refl protected theorem decode2 : primrec (decode2 α) := option_bind primrec.decode $ option_guard ((@primrec.eq _ _ nat.decidable_eq).comp (encode_iff.2 snd) (fst.comp fst)) snd theorem list_find_index₁ {p : α → β → Prop} [∀ a b, decidable (p a b)] (hp : primrec_rel p) : ∀ (l : list β), primrec (λ a, l.find_index (p a)) | [] := const 0 | (a::l) := ite (hp.comp primrec.id (const a)) (const 0) (succ.comp (list_find_index₁ l)) theorem list_index_of₁ [decidable_eq α] (l : list α) : primrec (λ a, l.index_of a) := list_find_index₁ primrec.eq l theorem dom_fintype [fintype α] (f : α → σ) : primrec f := let ⟨l, nd, m⟩ := fintype.exists_univ_list α in option_some_iff.1 $ begin haveI := decidable_eq_of_encodable α, refine ((list_nth₁ (l.map f)).comp (list_index_of₁ l)).of_eq (λ a, _), rw [list.nth_map, list.nth_le_nth (list.index_of_lt_length.2 (m _)), list.index_of_nth_le]; refl end theorem nat_bodd_div2 : primrec nat.bodd_div2 := (nat_elim' primrec.id (const (ff, 0)) (((cond fst (pair (const ff) (succ.comp snd)) (pair (const tt) snd)).comp snd).comp snd).to₂).of_eq $ λ n, begin simp [-nat.bodd_div2_eq], induction n with n IH, {refl}, simp [-nat.bodd_div2_eq, nat.bodd_div2, *], rcases nat.bodd_div2 n with ⟨_|_, m⟩; simp [nat.bodd_div2] end theorem nat_bodd : primrec nat.bodd := fst.comp nat_bodd_div2 theorem nat_div2 : primrec nat.div2 := snd.comp nat_bodd_div2 theorem nat_bit0 : primrec (@bit0 ℕ _) := nat_add.comp primrec.id primrec.id theorem nat_bit1 : primrec (@bit1 ℕ _ _) := nat_add.comp nat_bit0 (const 1) theorem nat_bit : primrec₂ nat.bit := (cond primrec.fst (nat_bit1.comp primrec.snd) (nat_bit0.comp primrec.snd)).of_eq $ λ n, by cases n.1; refl theorem nat_div_mod : primrec₂ (λ n k : ℕ, (n / k, n % k)) := let f (a : ℕ × ℕ) : ℕ × ℕ := a.1.elim (0, 0) (λ _ IH, if nat.succ IH.2 = a.2 then (nat.succ IH.1, 0) else (IH.1, nat.succ IH.2)) in have hf : primrec f, from nat_elim' fst (const (0, 0)) $ ((ite ((@primrec.eq ℕ _ _).comp (succ.comp $ snd.comp snd) fst) (pair (succ.comp $ fst.comp snd) (const 0)) (pair (fst.comp snd) (succ.comp $ snd.comp snd))) .comp (pair (snd.comp fst) (snd.comp snd))).to₂, suffices ∀ k n, (n / k, n % k) = f (n, k), from hf.of_eq $ λ ⟨m, n⟩, by simp [this], λ k n, begin have : (f (n, k)).2 + k * (f (n, k)).1 = n ∧ (0 < k → (f (n, k)).2 < k) ∧ (k = 0 → (f (n, k)).1 = 0), { induction n with n IH, {exact ⟨rfl, id, λ _, rfl⟩}, rw [λ n:ℕ, show f (n.succ, k) = _root_.ite ((f (n, k)).2.succ = k) (nat.succ (f (n, k)).1, 0) ((f (n, k)).1, (f (n, k)).2.succ), from rfl], by_cases h : (f (n, k)).2.succ = k; simp [h], { have := congr_arg nat.succ IH.1, refine ⟨_, λ k0, nat.no_confusion (h.trans k0)⟩, rwa [← nat.succ_add, h, add_comm, ← nat.mul_succ] at this }, { exact ⟨by rw [nat.succ_add, IH.1], λ k0, lt_of_le_of_ne (IH.2.1 k0) h, IH.2.2⟩ } }, revert this, cases f (n, k) with D M, simp, intros h₁ h₂ h₃, cases nat.eq_zero_or_pos k, { simp [h, h₃ h] at h₁ ⊢, simp [h₁] }, { exact (nat.div_mod_unique h).2 ⟨h₁, h₂ h⟩ } end theorem nat_div : primrec₂ ((/) : ℕ → ℕ → ℕ) := fst.comp₂ nat_div_mod theorem nat_mod : primrec₂ ((%) : ℕ → ℕ → ℕ) := snd.comp₂ nat_div_mod end primrec section variables {α : Type*} {β : Type*} {σ : Type*} variables [primcodable α] [primcodable β] [primcodable σ] variable (H : nat.primrec (λ n, encodable.encode (decode (list β) n))) include H open primrec private def prim : primcodable (list β) := ⟨H⟩ private lemma list_cases' {f : α → list β} {g : α → σ} {h : α → β × list β → σ} (hf : by haveI := prim H; exact primrec f) (hg : primrec g) (hh : by haveI := prim H; exact primrec₂ h) : @primrec _ σ _ _ (λ a, list.cases_on (f a) (g a) (λ b l, h a (b, l))) := by letI := prim H; exact have @primrec _ (option σ) _ _ (λ a, (decode (option (β × list β)) (encode (f a))).map (λ o, option.cases_on o (g a) (h a))), from ((@map_decode_iff _ (option (β × list β)) _ _ _ _ _).2 $ to₂ $ option_cases snd (hg.comp fst) (hh.comp₂ (fst.comp₂ primrec₂.left) primrec₂.right)) .comp primrec.id (encode_iff.2 hf), option_some_iff.1 $ this.of_eq $ λ a, by cases f a with b l; simp [encodek]; refl private lemma list_foldl' {f : α → list β} {g : α → σ} {h : α → σ × β → σ} (hf : by haveI := prim H; exact primrec f) (hg : primrec g) (hh : by haveI := prim H; exact primrec₂ h) : primrec (λ a, (f a).foldl (λ s b, h a (s, b)) (g a)) := by letI := prim H; exact let G (a : α) (IH : σ × list β) : σ × list β := list.cases_on IH.2 IH (λ b l, (h a (IH.1, b), l)) in let F (a : α) (n : ℕ) := (G a)^[n] (g a, f a) in have primrec (λ a, (F a (encode (f a))).1), from fst.comp $ nat_iterate (encode_iff.2 hf) (pair hg hf) $ list_cases' H (snd.comp snd) snd $ to₂ $ pair (hh.comp (fst.comp fst) $ pair ((fst.comp snd).comp fst) (fst.comp snd)) (snd.comp snd), this.of_eq $ λ a, begin have : ∀ n, F a n = ((list.take n (f a)).foldl (λ s b, h a (s, b)) (g a), list.drop n (f a)), { intro, simp [F], generalize : f a = l, generalize : g a = x, induction n with n IH generalizing l x, {refl}, simp, cases l with b l; simp [IH] }, rw [this, list.take_all_of_le (length_le_encode _)] end private lemma list_cons' : by haveI := prim H; exact primrec₂ (@list.cons β) := by letI := prim H; exact encode_iff.1 (succ.comp $ primrec₂.mkpair.comp (encode_iff.2 fst) (encode_iff.2 snd)) private lemma list_reverse' : by haveI := prim H; exact primrec (@list.reverse β) := by letI := prim H; exact (list_foldl' H primrec.id (const []) $ to₂ $ ((list_cons' H).comp snd fst).comp snd).of_eq (suffices ∀ l r, list.foldl (λ (s : list β) (b : β), b :: s) r l = list.reverse_core l r, from λ l, this l [], λ l, by induction l; simp [*, list.reverse_core]) end namespace primcodable variables {α : Type*} {β : Type*} variables [primcodable α] [primcodable β] open primrec instance sum : primcodable (α ⊕ β) := ⟨primrec.nat_iff.1 $ (encode_iff.2 (cond nat_bodd (((@primrec.decode β _).comp nat_div2).option_map $ to₂ $ nat_bit.comp (const tt) (primrec.encode.comp snd)) (((@primrec.decode α _).comp nat_div2).option_map $ to₂ $ nat_bit.comp (const ff) (primrec.encode.comp snd)))).of_eq $ λ n, show _ = encode (decode_sum n), begin simp [decode_sum], cases nat.bodd n; simp [decode_sum], { cases decode α n.div2; refl }, { cases decode β n.div2; refl } end⟩ instance list : primcodable (list α) := ⟨ by letI H := primcodable.prim (list ℕ); exact have primrec₂ (λ (a : α) (o : option (list ℕ)), o.map (list.cons (encode a))), from option_map snd $ (list_cons' H).comp ((@primrec.encode α _).comp (fst.comp fst)) snd, have primrec (λ n, (of_nat (list ℕ) n).reverse.foldl (λ o m, (decode α m).bind (λ a, o.map (list.cons (encode a)))) (some [])), from list_foldl' H ((list_reverse' H).comp (primrec.of_nat (list ℕ))) (const (some [])) (primrec.comp₂ (bind_decode_iff.2 $ primrec₂.swap this) primrec₂.right), nat_iff.1 $ (encode_iff.2 this).of_eq $ λ n, begin rw list.foldl_reverse, apply nat.case_strong_induction_on n, {refl}, intros n IH, simp, cases decode α n.unpair.1 with a, {refl}, simp, suffices : ∀ (o : option (list ℕ)) p (_ : encode o = encode p), encode (option.map (list.cons (encode a)) o) = encode (option.map (list.cons a) p), from this _ _ (IH _ (nat.unpair_le_right n)), intros o p IH, cases o; cases p; injection IH with h, exact congr_arg (λ k, (nat.mkpair (encode a) k).succ.succ) h end⟩ end primcodable namespace primrec variables {α : Type*} {β : Type*} {γ : Type*} {σ : Type*} variables [primcodable α] [primcodable β] [primcodable γ] [primcodable σ] theorem sum_inl : primrec (@sum.inl α β) := encode_iff.1 $ nat_bit0.comp primrec.encode theorem sum_inr : primrec (@sum.inr α β) := encode_iff.1 $ nat_bit1.comp primrec.encode theorem sum_cases {f : α → β ⊕ γ} {g : α → β → σ} {h : α → γ → σ} (hf : primrec f) (hg : primrec₂ g) (hh : primrec₂ h) : @primrec _ σ _ _ (λ a, sum.cases_on (f a) (g a) (h a)) := option_some_iff.1 $ (cond (nat_bodd.comp $ encode_iff.2 hf) (option_map (primrec.decode.comp $ nat_div2.comp $ encode_iff.2 hf) hh) (option_map (primrec.decode.comp $ nat_div2.comp $ encode_iff.2 hf) hg)).of_eq $ λ a, by cases f a with b c; simp [nat.div2_bit, nat.bodd_bit, encodek]; refl theorem list_cons : primrec₂ (@list.cons α) := list_cons' (primcodable.prim _) theorem list_cases {f : α → list β} {g : α → σ} {h : α → β × list β → σ} : primrec f → primrec g → primrec₂ h → @primrec _ σ _ _ (λ a, list.cases_on (f a) (g a) (λ b l, h a (b, l))) := list_cases' (primcodable.prim _) theorem list_foldl {f : α → list β} {g : α → σ} {h : α → σ × β → σ} : primrec f → primrec g → primrec₂ h → primrec (λ a, (f a).foldl (λ s b, h a (s, b)) (g a)) := list_foldl' (primcodable.prim _) theorem list_reverse : primrec (@list.reverse α) := list_reverse' (primcodable.prim _) theorem list_foldr {f : α → list β} {g : α → σ} {h : α → β × σ → σ} (hf : primrec f) (hg : primrec g) (hh : primrec₂ h) : primrec (λ a, (f a).foldr (λ b s, h a (b, s)) (g a)) := (list_foldl (list_reverse.comp hf) hg $ to₂ $ hh.comp fst $ (pair snd fst).comp snd).of_eq $ λ a, by simp [list.foldl_reverse] theorem list_head' : primrec (@list.head' α) := (list_cases primrec.id (const none) (option_some_iff.2 $ (fst.comp snd)).to₂).of_eq $ λ l, by cases l; refl theorem list_head [inhabited α] : primrec (@list.head α _) := (option_iget.comp list_head').of_eq $ λ l, l.head_eq_head'.symm theorem list_tail : primrec (@list.tail α) := (list_cases primrec.id (const []) (snd.comp snd).to₂).of_eq $ λ l, by cases l; refl theorem list_rec {f : α → list β} {g : α → σ} {h : α → β × list β × σ → σ} (hf : primrec f) (hg : primrec g) (hh : primrec₂ h) : @primrec _ σ _ _ (λ a, list.rec_on (f a) (g a) (λ b l IH, h a (b, l, IH))) := let F (a : α) := (f a).foldr (λ (b : β) (s : list β × σ), (b :: s.1, h a (b, s))) ([], g a) in have primrec F, from list_foldr hf (pair (const []) hg) $ to₂ $ pair ((list_cons.comp fst (fst.comp snd)).comp snd) hh, (snd.comp this).of_eq $ λ a, begin suffices : F a = (f a, list.rec_on (f a) (g a) (λ b l IH, h a (b, l, IH))), {rw this}, simp [F], induction f a with b l IH; simp * end theorem list_nth : primrec₂ (@list.nth α) := let F (l : list α) (n : ℕ) := l.foldl (λ (s : ℕ ⊕ α) (a : α), sum.cases_on s (@nat.cases (ℕ ⊕ α) (sum.inr a) sum.inl) sum.inr) (sum.inl n) in have hF : primrec₂ F, from list_foldl fst (sum_inl.comp snd) ((sum_cases fst (nat_cases snd (sum_inr.comp $ snd.comp fst) (sum_inl.comp snd).to₂).to₂ (sum_inr.comp snd).to₂).comp snd).to₂, have @primrec _ (option α) _ _ (λ p : list α × ℕ, sum.cases_on (F p.1 p.2) (λ _, none) some), from sum_cases hF (const none).to₂ (option_some.comp snd).to₂, this.to₂.of_eq $ λ l n, begin dsimp, symmetry, induction l with a l IH generalizing n, {refl}, cases n with n, { rw [(_ : F (a :: l) 0 = sum.inr a)], {refl}, clear IH, dsimp [F], induction l with b l IH; simp * }, { apply IH } end theorem list_inth [inhabited α] : primrec₂ (@list.inth α _) := option_iget.comp₂ list_nth theorem list_append : primrec₂ ((++) : list α → list α → list α) := (list_foldr fst snd $ to₂ $ comp (@list_cons α _) snd).to₂.of_eq $ λ l₁ l₂, by induction l₁; simp * theorem list_concat : primrec₂ (λ l (a:α), l ++ [a]) := list_append.comp fst (list_cons.comp snd (const [])) theorem list_map {f : α → list β} {g : α → β → σ} (hf : primrec f) (hg : primrec₂ g) : primrec (λ a, (f a).map (g a)) := (list_foldr hf (const []) $ to₂ $ list_cons.comp (hg.comp fst (fst.comp snd)) (snd.comp snd)).of_eq $ λ a, by induction f a; simp * theorem list_range : primrec list.range := (nat_elim' primrec.id (const []) ((list_concat.comp snd fst).comp snd).to₂).of_eq $ λ n, by simp; induction n; simp [*, list.range_concat]; refl theorem list_join : primrec (@list.join α) := (list_foldr primrec.id (const []) $ to₂ $ comp (@list_append α _) snd).of_eq $ λ l, by dsimp; induction l; simp * theorem list_length : primrec (@list.length α) := (list_foldr (@primrec.id (list α) _) (const 0) $ to₂ $ (succ.comp $ snd.comp snd).to₂).of_eq $ λ l, by dsimp; induction l; simp [*, -add_comm] theorem list_find_index {f : α → list β} {p : α → β → Prop} [∀ a b, decidable (p a b)] (hf : primrec f) (hp : primrec_rel p) : primrec (λ a, (f a).find_index (p a)) := (list_foldr hf (const 0) $ to₂ $ ite (hp.comp fst $ fst.comp snd) (const 0) (succ.comp $ snd.comp snd)).of_eq $ λ a, eq.symm $ by dsimp; induction f a with b l; [refl, simp [*, list.find_index]] theorem list_index_of [decidable_eq α] : primrec₂ (@list.index_of α _) := to₂ $ list_find_index snd $ primrec.eq.comp₂ (fst.comp fst).to₂ snd.to₂ theorem nat_strong_rec (f : α → ℕ → σ) {g : α → list σ → option σ} (hg : primrec₂ g) (H : ∀ a n, g a ((list.range n).map (f a)) = some (f a n)) : primrec₂ f := suffices primrec₂ (λ a n, (list.range n).map (f a)), from primrec₂.option_some_iff.1 $ (list_nth.comp (this.comp fst (succ.comp snd)) snd).to₂.of_eq $ λ a n, by simp [list.nth_range (nat.lt_succ_self n)]; refl, primrec₂.option_some_iff.1 $ (nat_elim (const (some [])) (to₂ $ option_bind (snd.comp snd) $ to₂ $ option_map (hg.comp (fst.comp fst) snd) (to₂ $ list_concat.comp (snd.comp fst) snd))).of_eq $ λ a n, begin simp, induction n with n IH, {refl}, simp [IH, H, list.range_concat] end end primrec namespace primcodable variables {α : Type*} {β : Type*} variables [primcodable α] [primcodable β] open primrec def subtype {p : α → Prop} [decidable_pred p] (hp : primrec_pred p) : primcodable (subtype p) := ⟨have primrec (λ n, (decode α n).bind (λ a, option.guard p a)), from option_bind primrec.decode (option_guard (hp.comp snd) snd), nat_iff.1 $ (encode_iff.2 this).of_eq $ λ n, show _ = encode ((decode α n).bind (λ a, _)), begin cases decode α n with a, {refl}, dsimp [option.guard], by_cases h : p a; simp [h]; refl end⟩ instance fin {n} : primcodable (fin n) := @of_equiv _ _ (subtype $ nat_lt.comp primrec.id (const n)) (equiv.fin_equiv_subtype _) instance vector {n} : primcodable (vector α n) := subtype ((@primrec.eq _ _ nat.decidable_eq).comp list_length (const _)) instance fin_arrow {n} : primcodable (fin n → α) := of_equiv _ (equiv.vector_equiv_fin _ _).symm instance array {n} : primcodable (array n α) := of_equiv _ (equiv.array_equiv_fin _ _) section ulower local attribute [instance, priority 100] encodable.decidable_range_encode encodable.decidable_eq_of_encodable instance ulower : primcodable (ulower α) := have primrec_pred (λ n, encodable.decode2 α n ≠ none), from primrec.not (primrec.eq.comp (primrec.option_bind primrec.decode (primrec.ite (primrec.eq.comp (primrec.encode.comp primrec.snd) primrec.fst) (primrec.option_some.comp primrec.snd) (primrec.const _))) (primrec.const _)), primcodable.subtype $ primrec_pred.of_eq this $ by simp [set.range, option.eq_none_iff_forall_not_mem, encodable.mem_decode2] end ulower end primcodable namespace primrec variables {α : Type*} {β : Type*} {γ : Type*} {σ : Type*} variables [primcodable α] [primcodable β] [primcodable γ] [primcodable σ] theorem subtype_val {p : α → Prop} [decidable_pred p] {hp : primrec_pred p} : by haveI := primcodable.subtype hp; exact primrec (@subtype.val α p) := begin letI := primcodable.subtype hp, refine (primcodable.prim (subtype p)).of_eq (λ n, _), rcases decode (subtype p) n with _|⟨a,h⟩; refl end theorem subtype_val_iff {p : β → Prop} [decidable_pred p] {hp : primrec_pred p} {f : α → subtype p} : by haveI := primcodable.subtype hp; exact primrec (λ a, (f a).1) ↔ primrec f := begin letI := primcodable.subtype hp, refine ⟨λ h, _, λ hf, subtype_val.comp hf⟩, refine nat.primrec.of_eq h (λ n, _), cases decode α n with a, {refl}, simp, cases f a; refl end theorem subtype_mk {p : β → Prop} [decidable_pred p] {hp : primrec_pred p} {f : α → β} {h : ∀ a, p (f a)} (hf : primrec f) : by haveI := primcodable.subtype hp; exact primrec (λ a, @subtype.mk β p (f a) (h a)) := subtype_val_iff.1 hf theorem option_get {f : α → option β} {h : ∀ a, (f a).is_some} : primrec f → primrec (λ a, option.get (h a)) := begin intro hf, refine (nat.primrec.pred.comp hf).of_eq (λ n, _), generalize hx : decode α n = x, cases x; simp end theorem ulower_down : primrec (ulower.down : α → ulower α) := by letI : ∀ a, decidable (a ∈ set.range (encode : α → ℕ)) := decidable_range_encode _; exact subtype_mk primrec.encode theorem ulower_up : primrec (ulower.up : ulower α → α) := by letI : ∀ a, decidable (a ∈ set.range (encode : α → ℕ)) := decidable_range_encode _; exact option_get (primrec.decode2.comp subtype_val) theorem fin_val_iff {n} {f : α → fin n} : primrec (λ a, (f a).1) ↔ primrec f := begin let : primcodable {a//id a<n}, swap, exactI (iff.trans (by refl) subtype_val_iff).trans (of_equiv_iff _) end theorem fin_val {n} : primrec (@fin.val n) := fin_val_iff.2 primrec.id theorem fin_succ {n} : primrec (@fin.succ n) := fin_val_iff.1 $ by simp [succ.comp fin_val] theorem vector_to_list {n} : primrec (@vector.to_list α n) := subtype_val theorem vector_to_list_iff {n} {f : α → vector β n} : primrec (λ a, (f a).to_list) ↔ primrec f := subtype_val_iff theorem vector_cons {n} : primrec₂ (@vector.cons α n) := vector_to_list_iff.1 $ by simp; exact list_cons.comp fst (vector_to_list_iff.2 snd) theorem vector_length {n} : primrec (@vector.length α n) := const _ theorem vector_head {n} : primrec (@vector.head α n) := option_some_iff.1 $ (list_head'.comp vector_to_list).of_eq $ λ ⟨a::l, h⟩, rfl theorem vector_tail {n} : primrec (@vector.tail α n) := vector_to_list_iff.1 $ (list_tail.comp vector_to_list).of_eq $ λ ⟨l, h⟩, by cases l; refl theorem vector_nth {n} : primrec₂ (@vector.nth α n) := option_some_iff.1 $ (list_nth.comp (vector_to_list.comp fst) (fin_val.comp snd)).of_eq $ λ a, by simp [vector.nth_eq_nth_le]; rw [← list.nth_le_nth] theorem list_of_fn : ∀ {n} {f : fin n → α → σ}, (∀ i, primrec (f i)) → primrec (λ a, list.of_fn (λ i, f i a)) | 0 f hf := const [] | (n+1) f hf := by simp [list.of_fn_succ]; exact list_cons.comp (hf 0) (list_of_fn (λ i, hf i.succ)) theorem vector_of_fn {n} {f : fin n → α → σ} (hf : ∀ i, primrec (f i)) : primrec (λ a, vector.of_fn (λ i, f i a)) := vector_to_list_iff.1 $ by simp [list_of_fn hf] theorem vector_nth' {n} : primrec (@vector.nth α n) := of_equiv_symm theorem vector_of_fn' {n} : primrec (@vector.of_fn α n) := of_equiv theorem fin_app {n} : primrec₂ (@id (fin n → σ)) := (vector_nth.comp (vector_of_fn'.comp fst) snd).of_eq $ λ ⟨v, i⟩, by simp theorem fin_curry₁ {n} {f : fin n → α → σ} : primrec₂ f ↔ ∀ i, primrec (f i) := ⟨λ h i, h.comp (const i) primrec.id, λ h, (vector_nth.comp ((vector_of_fn h).comp snd) fst).of_eq $ λ a, by simp⟩ theorem fin_curry {n} {f : α → fin n → σ} : primrec f ↔ primrec₂ f := ⟨λ h, fin_app.comp (h.comp fst) snd, λ h, (vector_nth'.comp (vector_of_fn (λ i, show primrec (λ a, f a i), from h.comp primrec.id (const i)))).of_eq $ λ a, by funext i; simp⟩ end primrec namespace nat open vector /-- An alternative inductive definition of `primrec` which does not use the pairing function on ℕ, and so has to work with n-ary functions on ℕ instead of unary functions. We prove that this is equivalent to the regular notion in `to_prim` and `of_prim`. -/ inductive primrec' : ∀ {n}, (vector ℕ n → ℕ) → Prop | zero : @primrec' 0 (λ _, 0) | succ : @primrec' 1 (λ v, succ v.head) | nth {n} (i : fin n) : primrec' (λ v, v.nth i) | comp {m n f} (g : fin n → vector ℕ m → ℕ) : primrec' f → (∀ i, primrec' (g i)) → primrec' (λ a, f (of_fn (λ i, g i a))) | prec {n f g} : @primrec' n f → @primrec' (n+2) g → primrec' (λ v : vector ℕ (n+1), v.head.elim (f v.tail) (λ y IH, g (y :: IH :: v.tail))) end nat namespace nat.primrec' open vector primrec nat (primrec') nat.primrec' hide ite theorem to_prim {n f} (pf : @primrec' n f) : primrec f := begin induction pf, case nat.primrec'.zero { exact const 0 }, case nat.primrec'.succ { exact primrec.succ.comp vector_head }, case nat.primrec'.nth : n i { exact vector_nth.comp primrec.id (const i) }, case nat.primrec'.comp : m n f g _ _ hf hg { exact hf.comp (vector_of_fn (λ i, hg i)) }, case nat.primrec'.prec : n f g _ _ hf hg { exact nat_elim' vector_head (hf.comp vector_tail) (hg.comp $ vector_cons.comp (fst.comp snd) $ vector_cons.comp (snd.comp snd) $ (@vector_tail _ _ (n+1)).comp fst).to₂ }, end theorem of_eq {n} {f g : vector ℕ n → ℕ} (hf : primrec' f) (H : ∀ i, f i = g i) : primrec' g := (funext H : f = g) ▸ hf theorem const {n} : ∀ m, @primrec' n (λ v, m) | 0 := zero.comp fin.elim0 (λ i, i.elim0) | (m+1) := succ.comp _ (λ i, const m) theorem head {n : ℕ} : @primrec' n.succ head := (nth 0).of_eq $ λ v, by simp [nth_zero] theorem tail {n f} (hf : @primrec' n f) : @primrec' n.succ (λ v, f v.tail) := (hf.comp _ (λ i, @nth _ i.succ)).of_eq $ λ v, by rw [← of_fn_nth v.tail]; congr; funext i; simp def vec {n m} (f : vector ℕ n → vector ℕ m) := ∀ i, primrec' (λ v, (f v).nth i) protected theorem nil {n} : @vec n 0 (λ _, nil) := λ i, i.elim0 protected theorem cons {n m f g} (hf : @primrec' n f) (hg : @vec n m g) : vec (λ v, f v :: g v) := λ i, fin.cases (by simp *) (λ i, by simp [hg i]) i theorem idv {n} : @vec n n id := nth theorem comp' {n m f g} (hf : @primrec' m f) (hg : @vec n m g) : primrec' (λ v, f (g v)) := (hf.comp _ hg).of_eq $ λ v, by simp theorem comp₁ (f : ℕ → ℕ) (hf : @primrec' 1 (λ v, f v.head)) {n g} (hg : @primrec' n g) : primrec' (λ v, f (g v)) := hf.comp _ (λ i, hg) theorem comp₂ (f : ℕ → ℕ → ℕ) (hf : @primrec' 2 (λ v, f v.head v.tail.head)) {n g h} (hg : @primrec' n g) (hh : @primrec' n h) : primrec' (λ v, f (g v) (h v)) := by simpa using hf.comp' (hg.cons $ hh.cons primrec'.nil) theorem prec' {n f g h} (hf : @primrec' n f) (hg : @primrec' n g) (hh : @primrec' (n+2) h) : @primrec' n (λ v, (f v).elim (g v) (λ (y IH : ℕ), h (y :: IH :: v))) := by simpa using comp' (prec hg hh) (hf.cons idv) theorem pred : @primrec' 1 (λ v, v.head.pred) := (prec' head (const 0) head).of_eq $ λ v, by simp; cases v.head; refl theorem add : @primrec' 2 (λ v, v.head + v.tail.head) := (prec head (succ.comp₁ _ (tail head))).of_eq $ λ v, by simp; induction v.head; simp [*, nat.succ_add] theorem sub : @primrec' 2 (λ v, v.head - v.tail.head) := begin suffices, simpa using comp₂ (λ a b, b - a) this (tail head) head, refine (prec head (pred.comp₁ _ (tail head))).of_eq (λ v, _), simp, induction v.head; simp [*, nat.sub_succ] end theorem mul : @primrec' 2 (λ v, v.head * v.tail.head) := (prec (const 0) (tail (add.comp₂ _ (tail head) (head)))).of_eq $ λ v, by simp; induction v.head; simp [*, nat.succ_mul]; rw add_comm theorem if_lt {n a b f g} (ha : @primrec' n a) (hb : @primrec' n b) (hf : @primrec' n f) (hg : @primrec' n g) : @primrec' n (λ v, if a v < b v then f v else g v) := (prec' (sub.comp₂ _ hb ha) hg (tail $ tail hf)).of_eq $ λ v, begin cases e : b v - a v, { simp [not_lt.2 (nat.le_of_sub_eq_zero e)] }, { simp [nat.lt_of_sub_eq_succ e] } end theorem mkpair : @primrec' 2 (λ v, v.head.mkpair v.tail.head) := if_lt head (tail head) (add.comp₂ _ (tail $ mul.comp₂ _ head head) head) (add.comp₂ _ (add.comp₂ _ (mul.comp₂ _ head head) head) (tail head)) protected theorem encode : ∀ {n}, @primrec' n encode | 0 := (const 0).of_eq (λ v, by rw v.eq_nil; refl) | (n+1) := (succ.comp₁ _ (mkpair.comp₂ _ head (tail encode))) .of_eq $ λ ⟨a::l, e⟩, rfl theorem sqrt : @primrec' 1 (λ v, v.head.sqrt) := begin suffices H : ∀ n : ℕ, n.sqrt = n.elim 0 (λ x y, if x.succ < y.succ*y.succ then y else y.succ), { simp [H], have := @prec' 1 _ _ (λ v, by have x := v.head; have y := v.tail.head; from if x.succ < y.succ*y.succ then y else y.succ) head (const 0) _, { convert this, funext, congr, funext x y, congr; simp }, have x1 := succ.comp₁ _ head, have y1 := succ.comp₁ _ (tail head), exact if_lt x1 (mul.comp₂ _ y1 y1) (tail head) y1 }, intro, symmetry, induction n with n IH, {refl}, dsimp, rw IH, split_ifs, { exact le_antisymm (nat.sqrt_le_sqrt (nat.le_succ _)) (nat.lt_succ_iff.1 $ nat.sqrt_lt.2 h) }, { exact nat.eq_sqrt.2 ⟨not_lt.1 h, nat.sqrt_lt.1 $ nat.lt_succ_iff.2 $ nat.sqrt_succ_le_succ_sqrt _⟩ }, end theorem unpair₁ {n f} (hf : @primrec' n f) : @primrec' n (λ v, (f v).unpair.1) := begin have s := sqrt.comp₁ _ hf, have fss := sub.comp₂ _ hf (mul.comp₂ _ s s), refine (if_lt fss s fss s).of_eq (λ v, _), simp [nat.unpair], split_ifs; refl end theorem unpair₂ {n f} (hf : @primrec' n f) : @primrec' n (λ v, (f v).unpair.2) := begin have s := sqrt.comp₁ _ hf, have fss := sub.comp₂ _ hf (mul.comp₂ _ s s), refine (if_lt fss s s (sub.comp₂ _ fss s)).of_eq (λ v, _), simp [nat.unpair], split_ifs; refl end theorem of_prim : ∀ {n f}, primrec f → @primrec' n f := suffices ∀ f, nat.primrec f → @primrec' 1 (λ v, f v.head), from λ n f hf, (pred.comp₁ _ $ (this _ hf).comp₁ (λ m, encodable.encode $ (decode (vector ℕ n) m).map f) primrec'.encode).of_eq (λ i, by simp [encodek]), λ f hf, begin induction hf, case nat.primrec.zero { exact const 0 }, case nat.primrec.succ { exact succ }, case nat.primrec.left { exact unpair₁ head }, case nat.primrec.right { exact unpair₂ head }, case nat.primrec.pair : f g _ _ hf hg { exact mkpair.comp₂ _ hf hg }, case nat.primrec.comp : f g _ _ hf hg { exact hf.comp₁ _ hg }, case nat.primrec.prec : f g _ _ hf hg { simpa using prec' (unpair₂ head) (hf.comp₁ _ (unpair₁ head)) (hg.comp₁ _ $ mkpair.comp₂ _ (unpair₁ $ tail $ tail head) (mkpair.comp₂ _ head (tail head))) }, end theorem prim_iff {n f} : @primrec' n f ↔ primrec f := ⟨to_prim, of_prim⟩ theorem prim_iff₁ {f : ℕ → ℕ} : @primrec' 1 (λ v, f v.head) ↔ primrec f := prim_iff.trans ⟨ λ h, (h.comp $ vector_of_fn $ λ i, primrec.id).of_eq (λ v, by simp), λ h, h.comp vector_head⟩ theorem prim_iff₂ {f : ℕ → ℕ → ℕ} : @primrec' 2 (λ v, f v.head v.tail.head) ↔ primrec₂ f := prim_iff.trans ⟨ λ h, (h.comp $ vector_cons.comp fst $ vector_cons.comp snd (primrec.const nil)).of_eq (λ v, by simp), λ h, h.comp vector_head (vector_head.comp vector_tail)⟩ theorem vec_iff {m n f} : @vec m n f ↔ primrec f := ⟨λ h, by simpa using vector_of_fn (λ i, to_prim (h i)), λ h i, of_prim $ vector_nth.comp h (primrec.const i)⟩ end nat.primrec' theorem primrec.nat_sqrt : primrec nat.sqrt := nat.primrec'.prim_iff₁.1 nat.primrec'.sqrt
e01da55ddd400e22e920b9403cd66b3f6aba329f
d6124c8dbe5661dcc5b8c9da0a56fbf1f0480ad6
/Papyrus/Script/Instructions.lean
57293fca05da225609d724c6783f6751d2aec93c
[ "Apache-2.0" ]
permissive
xubaiw/lean4-papyrus
c3fbbf8ba162eb5f210155ae4e20feb2d32c8182
02e82973a5badda26fc0f9fd15b3d37e2eb309e0
refs/heads/master
1,691,425,756,824
1,632,122,825,000
1,632,123,075,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
9,645
lean
import Lean.Parser import Papyrus.Builders import Papyrus.Script.Do import Papyrus.Script.Type import Papyrus.Script.Value import Papyrus.Script.ParserUtil namespace Papyrus.Script open Builder Lean Parser Term @[runParserAttributeHooks] def syncscope := nonReservedSymbol "syncscope " true >> "(" >> termParser >> ")" @[runParserAttributeHooks] def optSyncScope := Parser.optional (nonReservedSymbol "syncscope " true >> "(" >> termParser >> ")") @[runParserAttributeHooks] def atomicOrderingLit := leading_parser nonReservedSymbol "unordered" true <|> nonReservedSymbol "monotonic" true <|> nonReservedSymbol "acquire" true <|> nonReservedSymbol "release" true <|> nonReservedSymbol "acq_rel" true <|> nonReservedSymbol "seq_cst" true @[runParserAttributeHooks] def atomicOrderingTerm := leading_parser nonReservedSymbol "ordering" true >> "(" >> termParser >> ")" @[runParserAttributeHooks] def atomicOrdering := atomicOrderingTerm <|> atomicOrderingLit def expandAtomicOrderingLit (stx : Syntax) : (lit : String) → MacroM Syntax | "unordered" => mkCIdentFrom stx ``AtomicOrdering.unordered | "monotonic" => mkCIdentFrom stx ``AtomicOrdering.monotonic | "acquire" => mkCIdentFrom stx ``AtomicOrdering.acquire | "release" => mkCIdentFrom stx ``AtomicOrdering.release | "acq_rel" => mkCIdentFrom stx ``AtomicOrdering.acquireRelease | "seq_cst" => mkCIdentFrom stx ``AtomicOrdering.sequentiallyConsistent | _ => Macro.throwErrorAt stx "unknown atomic ordering" def expandAtomicOrdering : (order : Syntax) → MacroM Syntax | `(atomicOrdering| ordering($x:term)) => x | linkage => match linkage.isLit? ``atomicOrderingLit with | some val => expandAtomicOrderingLit linkage val | none => Macro.throwErrorAt linkage "ill-formed atomic ordering" -- TODO: convert string scopes (e.g., `"singlethread"`) to IDs def expandOptSyncScope (ssid? : Option Syntax) : MacroM Syntax := ssid?.getD (mkCIdent ``SyncScopeID.system) -- TODO: default `align` to ABI align of module when not provided def expandOptAlign (align? : Option Syntax) : MacroM Syntax := align?.getD (quote 1) -------------------------------------------------------------------------------- -- # Instructions -------------------------------------------------------------------------------- -- ## `ret` def voidTk := leading_parser nonReservedSymbol "void" true @[runParserAttributeHooks] def retInst := leading_parser nonReservedSymbol "ret " true >> (voidTk <|> valueParser) def expandRetInst : (stx : Syntax) → MacroM Syntax | `(retInst| ret void) => `(doElem| retVoid) | `(retInst| ret $v:llvmValue) => do `(doElem| ret $(← expandValueAsRefArrow v)) | stx => Macro.throwErrorAt stx "ill-formed ret instruction" macro x:retInst : bbDoElem => expandRetInst x scoped macro "llvm " x:retInst : doElem => expandRetInst x -- ## `br` @[runParserAttributeHooks] def brInst := leading_parser nonReservedSymbol "br " true >> valueParser >> Parser.optional (", " >> valueParser >> ", " >> valueParser) def expandBrInst : (stx : Syntax) → MacroM Syntax | `(brInst| br $cond, $ifTrue, $ifFalse) => do let cond ← expandValueAsRefArrow cond let ifTrue ← expandValueAsRefArrow ifTrue let ifFalse ← expandValueAsRefArrow ifFalse `(doElem| condBr $cond $ifTrue $ifFalse) | `(brInst| br $bb) => do `(doElem| br $(← expandValueAsRefArrow bb)) | stx => Macro.throwErrorAt stx "ill-formed br instruction" macro x:brInst : bbDoElem => expandBrInst x scoped macro "llvm " x:brInst : doElem => expandBrInst x -- ## `load` @[runParserAttributeHooks] def loadNotAtomicInst := leading_parser Parser.optional (nonReservedSymbol "volatile " true) >> typeParser >> ", " >> valueParser >> Parser.optional (", " >> nonReservedSymbol "align " true >> termParser) @[runParserAttributeHooks] def loadAtomicInst := leading_parser nonReservedSymbol "atomic " true >> Parser.optional (nonReservedSymbol "volatile " true) >> typeParser >> ", " >> valueParser >> Parser.optional (syncscope >> ppSpace) >> atomicOrdering >> ", " >> nonReservedSymbol "align " true >> termParser @[runParserAttributeHooks] def loadInst := leading_parser nonReservedSymbol "load " true >> (loadAtomicInst <|> loadNotAtomicInst) def expandLoadInst (name : Syntax) : (stx : Syntax) → MacroM Syntax | `(loadInst| load atomic $[volatile%$volatile?]? $ty:llvmType, $ptr:llvmValue $[syncscope($ssid?)]? $order, align $align) => do let ty ← expandTypeAsRefArrow ty let ptr ← expandValueAsRefArrow ptr let isVolatile := quote volatile?.isSome let order ← expandAtomicOrdering order let ssid ← expandOptSyncScope ssid? ``(load $ty $ptr $name $isVolatile $align $order $ssid) | `(loadInst| load $[volatile%$volatile?]? $ty:llvmType, $ptr:llvmValue $[, align $align?]?) => do let ty ← expandTypeAsRefArrow ty let ptr ← expandValueAsRefArrow ptr let isVolatile := quote volatile?.isSome let align ← expandOptAlign align? ``(load $ty $ptr $name $isVolatile $align) | inst => Macro.throwErrorAt inst "ill-formed load instruction" -- ## `store` @[runParserAttributeHooks] def storeNotAtomicInst := leading_parser Parser.optional (nonReservedSymbol "volatile " true) >> valueParser >> ", " >> valueParser >> Parser.optional (", " >> nonReservedSymbol "align " true >> termParser) @[runParserAttributeHooks] def storeAtomicInst := leading_parser nonReservedSymbol "atomic " true >> Parser.optional (nonReservedSymbol "volatile " true) >> valueParser >> ", " >> valueParser >> Parser.optional (syncscope >> ppSpace) >> atomicOrdering >> ", " >> nonReservedSymbol "align " true >> termParser @[runParserAttributeHooks] def storeInst := leading_parser nonReservedSymbol "store " true >> (storeAtomicInst <|> storeNotAtomicInst) def expandStoreInst : (stx : Syntax) → MacroM Syntax | `(storeInst| store atomic $[volatile%$volatile?]? $val:llvmValue, $ptr:llvmValue $[syncscope($ssid?)]? $order, align $align) => do let val ← expandValueAsRefArrow val let ptr ← expandValueAsRefArrow ptr let isVolatile := quote volatile?.isSome let order ← expandAtomicOrdering order let ssid ← expandOptSyncScope ssid? `(doElem| store $val $ptr $isVolatile $align $order $ssid) | `(storeInst| store $[volatile%$volatile?]? $val:llvmValue, $ptr:llvmValue $[, align $align?]?) => do let val ← expandValueAsRefArrow val let ptr ← expandValueAsRefArrow ptr let isVolatile := quote volatile?.isSome let align ← expandOptAlign align? `(doElem| store $val $ptr $isVolatile $align) | inst => Macro.throwErrorAt inst "ill-formed store instruction" macro x:storeInst : bbDoElem => expandStoreInst x scoped macro "llvm " x:storeInst : doElem => expandStoreInst x -- ## `getelementptr` @[runParserAttributeHooks] def getElementPtrInst := leading_parser nonReservedSymbol "getelementptr " true >> Parser.optional (nonReservedSymbol "inbounds " true) >> typeParser >> "," >> valueParser >> "," >> sepBy valueParser "," def expandGetElementPtrInst (name : Syntax) : (stx : Syntax) → MacroM Syntax | `(getElementPtrInst| getelementptr $[inbounds%$inbounds?]? $ty:llvmType, $ptr:llvmValue, $[$idxs:llvmValue],*) => do let tyx ← expandTypeAsRefArrow ty let ptrx ← expandValueAsRefArrow ptr let idxsx ← idxs.mapM expandValueAsRefArrow match inbounds? with | none => ``(getElementPtr $tyx $ptrx #[$[$idxsx],*] $name) | some _ => ``(getElementPtrInbounds $tyx $ptrx #[$[$idxsx],*] $name) | inst => Macro.throwErrorAt inst "ill-formed getelementptr instruction" -- ## `call` @[runParserAttributeHooks] def callInst := leading_parser nonReservedSymbol "call " true >> Parser.optional typeParser >> "@" >> termParser maxPrec >> "(" >> sepBy valueParser "," >> ")" def expandCallInst (name : Syntax) : (stx : Syntax) → MacroM Syntax | `(callInst| call $[$ty?]? @ $fn:term ($[$args],*)) => do let argsx ← args.mapM expandValueAsRefArrow match ty? with | none => ``(call $fn #[$[$argsx],*] $name) | some ty => let tyx ← expandTypeAsRefArrow ty ``(callAs $tyx $fn #[$[$argsx],*] $name) | inst => Macro.throwErrorAt inst "ill-formed call instruction" -------------------------------------------------------------------------------- -- # Namable Instructions -------------------------------------------------------------------------------- @[runParserAttributeHooks] def instruction := loadInst <|> getElementPtrInst <|> callInst def expandInstruction (name : Syntax) : (inst : Syntax) → MacroM Syntax | `(instruction| $inst:loadInst) => expandLoadInst name inst | `(instruction| $inst:getElementPtrInst) => expandGetElementPtrInst name inst | `(instruction| $inst:callInst) => expandCallInst name inst | inst => Macro.throwErrorAt inst "unknown instruction" -- ## Named Instructions @[runParserAttributeHooks] def namedInst := leading_parser "%" >> Parser.ident >> " = " >> instruction def expandNamedInst : Macro | `(namedInst| % $id:ident = $inst) => do let name := identAsStrLit id let inst ← expandInstruction name inst `(doElem| let $id:ident ← $inst:term) | stx => Macro.throwErrorAt stx "ill-formed named instruction" macro inst:namedInst : bbDoElem => expandNamedInst inst scoped macro "llvm " inst:namedInst : doElem => expandNamedInst inst -- ## Unnamed Instructions def expandUnnamedInst (inst : Syntax) : MacroM Syntax := do let name := Syntax.mkStrLit "" let inst ← expandInstruction name inst `(doElem| let a ← $inst:term) macro inst:instruction : bbDoElem => expandUnnamedInst inst scoped macro "llvm " inst:instruction : doElem => expandUnnamedInst inst
951f4f0a033f13c747e5aee388369ecde5fe62ad
968e2f50b755d3048175f176376eff7139e9df70
/examples/prop_logic_theory/unnamed_214.lean
b272d28ed91b155b15a642a982395e7df0a74f30
[]
no_license
gihanmarasingha/mth1001_sphinx
190a003269ba5e54717b448302a27ca26e31d491
05126586cbf5786e521be1ea2ef5b4ba3c44e74a
refs/heads/master
1,672,913,933,677
1,604,516,583,000
1,604,516,583,000
309,245,750
1
0
null
null
null
null
UTF-8
Lean
false
false
115
lean
variables p q r : Prop -- BEGIN example (h : (p ∧ q) ∧ r) : q := begin show q, from (h.left).right end -- END
5f6efd69b1b8d9f4bd896275ff5cbd45bf919de2
947b78d97130d56365ae2ec264df196ce769371a
/tests/lean/run/generalizeTelescope.lean
2cac11e6541f0aa5c07468a9f11e37bd8412be93
[ "Apache-2.0" ]
permissive
shyamalschandra/lean4
27044812be8698f0c79147615b1d5090b9f4b037
6e7a883b21eaf62831e8111b251dc9b18f40e604
refs/heads/master
1,671,417,126,371
1,601,859,995,000
1,601,860,020,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,439
lean
import Lean new_frontend open Lean open Lean.Meta inductive Vec (α : Type) : Nat → Type | nil : Vec α 0 | cons {n} : α → Vec α n → Vec α (n+1) set_option trace.Meta.debug true def nat := mkConst `Nat def succ := mkConst `Nat.succ def tst1 : MetaM Unit := withLocalDeclD `n nat $ fun n => do let n1 := mkApp succ n; let vecN1 := mkApp2 (mkConst `Vec) nat n1; withLocalDeclD `xs vecN1 $ fun xs => do generalizeTelescope #[n1, xs] `aux $ fun ys => do let t ← mkLambdaFVars ys ys.back; trace! `Meta.debug t; pure () #eval tst1 set_option pp.all true def tst2 : MetaM Unit := withLocalDeclD `n nat $ fun n => do let n1 := mkApp succ n; let vecN1 := mkApp2 (mkConst `Vec) nat n1; withLocalDeclD `xs vecN1 $ fun xs => do let e ← mkEqRefl xs; generalizeTelescope #[n1, xs, e] `aux $ fun ys => do let t ← mkLambdaFVars ys ys.back; trace! `Meta.debug t; pure () #eval tst2 def failIfSuccess (x : MetaM Unit) : MetaM Unit := whenM («catch» (x *> pure true) (fun _ => pure false)) $ throwError "unexpected success" def tst3 : MetaM Unit := withLocalDeclD `n nat $ fun n => do let n1 := mkApp succ n; let vecN1 := mkApp2 (mkConst `Vec) nat n1; withLocalDeclD `xs vecN1 $ fun xs => do let e ← mkEqRefl xs; failIfSuccess $ do { generalizeTelescope #[n1, e] `aux $ fun ys => do let t ← mkLambdaFVars ys ys.back; trace! `Meta.debug t; pure () }; trace! `Meta.debug "failed as expected" #eval tst3
3b90fb06f8f872a6125de8d74ea3b96d084e89ae
2c096fdfecf64e46ea7bc6ce5521f142b5926864
/src/Lean/Server/FileWorker.lean
ad33da466794c9ff5557776a9debf489dd7ad741
[ "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
Kha/lean4
1005785d2c8797ae266a303968848e5f6ce2fe87
b99e11346948023cd6c29d248cd8f3e3fb3474cf
refs/heads/master
1,693,355,498,027
1,669,080,461,000
1,669,113,138,000
184,748,176
0
0
Apache-2.0
1,665,995,520,000
1,556,884,930,000
Lean
UTF-8
Lean
false
false
23,238
lean
/- Copyright (c) 2020 Marc Huisinga. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Marc Huisinga, Wojciech Nawrocki -/ import Init.System.IO import Lean.Data.RBMap import Lean.Environment import Lean.Data.Lsp import Lean.Data.Json.FromToJson import Lean.Util.Paths import Lean.LoadDynlib import Lean.Server.Utils import Lean.Server.Snapshots import Lean.Server.AsyncList import Lean.Server.References import Lean.Server.FileWorker.Utils import Lean.Server.FileWorker.RequestHandling import Lean.Server.FileWorker.WidgetRequests import Lean.Server.Rpc.Basic import Lean.Widget.InteractiveDiagnostic /-! For general server architecture, see `README.md`. For details of IPC communication, see `Watchdog.lean`. This module implements per-file worker processes. File processing and requests+notifications against a file should be concurrent for two reasons: - By the LSP standard, requests should be cancellable. - Since Lean allows arbitrary user code to be executed during elaboration via the tactic framework, elaboration can be extremely slow and even not halt in some cases. Users should be able to work with the file while this is happening, e.g. make new changes to the file or send requests. To achieve these goals, elaboration is executed in a chain of tasks, where each task corresponds to the elaboration of one command. When the elaboration of one command is done, the next task is spawned. On didChange notifications, we search for the task in which the change occured. If we stumble across a task that has not yet finished before finding the task we're looking for, we terminate it and start the elaboration there, otherwise we start the elaboration at the task where the change occured. Requests iterate over tasks until they find the command that they need to answer the request. In order to not block the main thread, this is done in a request task. If a task that the request task waits for is terminated, a change occured somewhere before the command that the request is looking for and the request sends a "content changed" error. -/ namespace Lean.Server.FileWorker open Lsp open IO open Snapshots open JsonRpc structure WorkerContext where hIn : FS.Stream hOut : FS.Stream hLog : FS.Stream headerTask : Task (Except Error (Snapshot × SearchPath)) initParams : InitializeParams clientHasWidgets : Bool /-! # Asynchronous snapshot elaboration -/ section Elab structure AsyncElabState where snaps : Array Snapshot abbrev AsyncElabM := StateT AsyncElabState <| EIO ElabTaskError -- Placed here instead of Lean.Server.Utils because of an import loop private def publishIleanInfo (method : String) (m : DocumentMeta) (hOut : FS.Stream) (snaps : Array Snapshot) : IO Unit := do let trees := snaps.map fun snap => snap.infoTree let references := findModuleRefs m.text trees (localVars := true) let param := { version := m.version, references : LeanIleanInfoParams } hOut.writeLspNotification { method, param } private def publishIleanInfoUpdate : DocumentMeta → FS.Stream → Array Snapshot → IO Unit := publishIleanInfo "$/lean/ileanInfoUpdate" private def publishIleanInfoFinal : DocumentMeta → FS.Stream → Array Snapshot → IO Unit := publishIleanInfo "$/lean/ileanInfoFinal" /-- Elaborates the next command after `parentSnap` and emits diagnostics into `hOut`. -/ private def nextCmdSnap (ctx : WorkerContext) (m : DocumentMeta) (cancelTk : CancelToken) : AsyncElabM (Option Snapshot) := do cancelTk.check let s ← get let lastSnap := s.snaps.back if lastSnap.isAtEnd then publishDiagnostics m lastSnap.diagnostics.toArray ctx.hOut publishProgressDone m ctx.hOut -- This will overwrite existing ilean info for the file, in case something -- went wrong during the incremental updates. publishIleanInfoFinal m ctx.hOut s.snaps return none publishProgressAtPos m lastSnap.endPos ctx.hOut let snap ← compileNextCmd m.mkInputContext lastSnap ctx.clientHasWidgets set { s with snaps := s.snaps.push snap } -- TODO(MH): check for interrupt with increased precision cancelTk.check /- NOTE(MH): This relies on the client discarding old diagnostics upon receiving new ones while prefering newer versions over old ones. The former is necessary because we do not explicitly clear older diagnostics, while the latter is necessary because we do not guarantee that diagnostics are emitted in order. Specifically, it may happen that we interrupted this elaboration task right at this point and a newer elaboration task emits diagnostics, after which we emit old diagnostics because we did not yet detect the interrupt. Explicitly clearing diagnostics is difficult for a similar reason, because we cannot guarantee that no further diagnostics are emitted after clearing them. -/ -- NOTE(WN): this is *not* redundent even if there are no new diagnostics in this snapshot -- because empty diagnostics clear existing error/information squiggles. Therefore we always -- want to publish in case there was previously a message at this position. publishDiagnostics m snap.diagnostics.toArray ctx.hOut publishIleanInfoUpdate m ctx.hOut #[snap] return some snap /-- Elaborates all commands after the last snap (at least the header snap is assumed to exist), emitting the diagnostics into `hOut`. -/ def unfoldCmdSnaps (m : DocumentMeta) (snaps : Array Snapshot) (cancelTk : CancelToken) : ReaderT WorkerContext IO (AsyncList ElabTaskError Snapshot) := do let ctx ← read let headerSnap := snaps[0]! if headerSnap.msgLog.hasErrors then -- Treat header processing errors as fatal so users aren't swamped with -- followup errors publishProgressAtPos m headerSnap.beginPos ctx.hOut (kind := LeanFileProgressKind.fatalError) publishIleanInfoFinal m ctx.hOut #[headerSnap] return AsyncList.ofList [headerSnap] else -- This will overwrite existing ilean info for the file since this has a -- higher version number. publishIleanInfoUpdate m ctx.hOut snaps return AsyncList.ofList snaps.toList ++ (← AsyncList.unfoldAsync (nextCmdSnap ctx m cancelTk) { snaps }) end Elab -- Pending requests are tracked so they can be cancelled abbrev PendingRequestMap := RBMap RequestID (Task (Except IO.Error Unit)) compare structure WorkerState where doc : EditableDocument pendingRequests : PendingRequestMap /-- A map of RPC session IDs. We allow asynchronous elab tasks and request handlers to modify sessions. A single `Ref` ensures atomic transactions. -/ rpcSessions : RBMap UInt64 (IO.Ref RpcSession) compare abbrev WorkerM := ReaderT WorkerContext <| StateRefT WorkerState IO /- Worker initialization sequence. -/ section Initialization /-- Use `lake print-paths` to compile dependencies on the fly and add them to `LEAN_PATH`. Compilation progress is reported to `hOut` via LSP notifications. Return the search path for source files. -/ partial def lakeSetupSearchPath (lakePath : System.FilePath) (m : DocumentMeta) (imports : Array Import) (hOut : FS.Stream) : IO SearchPath := do let args := #["print-paths"] ++ imports.map (toString ·.module) let cmdStr := " ".intercalate (toString lakePath :: args.toList) let lakeProc ← Process.spawn { stdin := Process.Stdio.null stdout := Process.Stdio.piped stderr := Process.Stdio.piped cmd := lakePath.toString args } -- progress notification: report latest stderr line let rec processStderr (acc : String) : IO String := do let line ← lakeProc.stderr.getLine if line == "" then return acc else publishDiagnostics m #[{ range := ⟨⟨0, 0⟩, ⟨0, 0⟩⟩, severity? := DiagnosticSeverity.information, message := line }] hOut processStderr (acc ++ line) let stderr ← IO.asTask (processStderr "") Task.Priority.dedicated let stdout := String.trim (← lakeProc.stdout.readToEnd) let stderr ← IO.ofExcept stderr.get match (← lakeProc.wait) with | 0 => let Except.ok (paths : LeanPaths) ← pure (Json.parse stdout >>= fromJson?) | throwServerError s!"invalid output from `{cmdStr}`:\n{stdout}\nstderr:\n{stderr}" initSearchPath (← getBuildDir) paths.oleanPath paths.loadDynlibPaths.forM loadDynlib paths.srcPath.mapM realPathNormalized | 2 => pure [] -- no lakefile.lean | _ => throwServerError s!"`{cmdStr}` failed:\n{stdout}\nstderr:\n{stderr}" def compileHeader (m : DocumentMeta) (hOut : FS.Stream) (opts : Options) (hasWidgets : Bool) : IO (Snapshot × SearchPath) := do let (headerStx, headerParserState, msgLog) ← Parser.parseHeader m.mkInputContext let mut srcSearchPath ← initSrcSearchPath (← getBuildDir) let lakePath ← match (← IO.getEnv "LAKE") with | some path => pure <| System.FilePath.mk path | none => let lakePath ← match (← IO.getEnv "LEAN_SYSROOT") with | some path => pure <| System.FilePath.mk path / "bin" / "lake" | _ => pure <| (← appDir) / "lake" pure <| lakePath.withExtension System.FilePath.exeExtension let (headerEnv, msgLog) ← try if let some path := System.Uri.fileUriToPath? m.uri then -- NOTE: we assume for now that `lakefile.lean` does not have any non-stdlib deps -- NOTE: lake does not exist in stage 0 (yet?) if path.fileName != "lakefile.lean" && (← System.FilePath.pathExists lakePath) then let pkgSearchPath ← lakeSetupSearchPath lakePath m (Lean.Elab.headerToImports headerStx).toArray hOut srcSearchPath ← initSrcSearchPath (← getBuildDir) pkgSearchPath Elab.processHeader headerStx opts msgLog m.mkInputContext catch e => -- should be from `lake print-paths` let msgs := MessageLog.empty.add { fileName := "<ignored>", pos := ⟨0, 0⟩, data := e.toString } pure (← mkEmptyEnvironment, msgs) let mut headerEnv := headerEnv try if let some path := System.Uri.fileUriToPath? m.uri then headerEnv := headerEnv.setMainModule (← moduleNameOfFileName path none) catch _ => pure () let cmdState := Elab.Command.mkState headerEnv msgLog opts let cmdState := { cmdState with infoState := { enabled := true trees := #[Elab.InfoTree.context ({ env := headerEnv fileMap := m.text ngen := { namePrefix := `_worker } }) (Elab.InfoTree.node (Elab.Info.ofCommandInfo { elaborator := `header, stx := headerStx }) (headerStx[1].getArgs.toList.map (fun importStx => Elab.InfoTree.node (Elab.Info.ofCommandInfo { elaborator := `import stx := importStx }) #[].toPArray' )).toPArray' )].toPArray' }} let headerSnap := { beginPos := 0 stx := headerStx mpState := headerParserState cmdState := cmdState interactiveDiags := ← cmdState.messages.msgs.mapM (Widget.msgToInteractiveDiagnostic m.text · hasWidgets) tacticCache := (← IO.mkRef {}) } publishDiagnostics m headerSnap.diagnostics.toArray hOut return (headerSnap, srcSearchPath) def initializeWorker (meta : DocumentMeta) (i o e : FS.Stream) (initParams : InitializeParams) (opts : Options) : IO (WorkerContext × WorkerState) := do let clientHasWidgets := initParams.initializationOptions?.bind (·.hasWidgets?) |>.getD false let headerTask ← EIO.asTask <| compileHeader meta o opts (hasWidgets := clientHasWidgets) let cancelTk ← CancelToken.new let ctx := { hIn := i hOut := o hLog := e headerTask initParams clientHasWidgets } let cmdSnaps ← EIO.mapTask (t := headerTask) (match · with | Except.ok (s, _) => unfoldCmdSnaps meta #[s] cancelTk ctx | Except.error e => throw (e : ElabTaskError)) let doc : EditableDocument := ⟨meta, AsyncList.delayed cmdSnaps, cancelTk⟩ return (ctx, { doc := doc pendingRequests := RBMap.empty rpcSessions := RBMap.empty }) end Initialization section Updates def updatePendingRequests (map : PendingRequestMap → PendingRequestMap) : WorkerM Unit := do modify fun st => { st with pendingRequests := map st.pendingRequests } /-- Given the new document, updates editable doc state. -/ def updateDocument (newMeta : DocumentMeta) : WorkerM Unit := do let ctx ← read let oldDoc := (←get).doc -- The watchdog only restarts the file worker when the semantic content of the header changes. -- If e.g. a newline is deleted, it will not restart this file worker, but we still -- need to reparse the header so that the offsets are correct. let (newHeaderStx, newMpState, _) ← Parser.parseHeader newMeta.mkInputContext let cancelTk ← CancelToken.new -- Wait for at least one snapshot from the old doc, we don't want to unnecessarily re-run `print-paths` let headSnapTask := oldDoc.cmdSnaps.waitHead? let newSnaps ← EIO.mapTask (ε := ElabTaskError) (t := headSnapTask) fun headSnap?? => do let headSnap? ← MonadExcept.ofExcept headSnap?? -- There is always at least one snapshot absent exceptions let headSnap := headSnap?.get! let newHeaderSnap := { headSnap with stx := newHeaderStx, mpState := newMpState } oldDoc.cancelTk.set let changePos := oldDoc.meta.text.source.firstDiffPos newMeta.text.source -- Ignore exceptions, we are only interested in the successful snapshots let (cmdSnaps, _) ← oldDoc.cmdSnaps.getFinishedPrefix -- NOTE(WN): we invalidate eagerly as `endPos` consumes input greedily. To re-elaborate only -- when really necessary, we could do a whitespace-aware `Syntax` comparison instead. let mut validSnaps := cmdSnaps.takeWhile (fun s => s.endPos < changePos) if validSnaps.length ≤ 1 then validSnaps := [newHeaderSnap] else /- When at least one valid non-header snap exists, it may happen that a change does not fall within the syntactic range of that last snap but still modifies it by appending tokens. We check for this here. We do not currently handle crazy grammars in which an appended token can merge two or more previous commands into one. To do so would require reparsing the entire file. -/ let mut lastSnap := validSnaps.getLast! let preLastSnap := if validSnaps.length ≥ 2 then validSnaps.get! (validSnaps.length - 2) else newHeaderSnap let newLastStx ← parseNextCmd newMeta.mkInputContext preLastSnap if newLastStx != lastSnap.stx then validSnaps := validSnaps.dropLast unfoldCmdSnaps newMeta validSnaps.toArray cancelTk ctx modify fun st => { st with doc := ⟨newMeta, AsyncList.delayed newSnaps, cancelTk⟩ } end Updates /- Notifications are handled in the main thread. They may change global worker state such as the current file contents. -/ section NotificationHandling def handleDidChange (p : DidChangeTextDocumentParams) : WorkerM Unit := do let docId := p.textDocument let changes := p.contentChanges let oldDoc := (←get).doc let some newVersion ← pure docId.version? | throwServerError "Expected version number" if newVersion ≤ oldDoc.meta.version then -- TODO(WN): This happens on restart sometimes. IO.eprintln s!"Got outdated version number: {newVersion} ≤ {oldDoc.meta.version}" else if ¬ changes.isEmpty then let newDocText := foldDocumentChanges changes oldDoc.meta.text updateDocument ⟨docId.uri, newVersion, newDocText⟩ def handleCancelRequest (p : CancelParams) : WorkerM Unit := do updatePendingRequests (fun pendingRequests => pendingRequests.erase p.id) def handleRpcRelease (p : Lsp.RpcReleaseParams) : WorkerM Unit := do -- NOTE(WN): when the worker restarts e.g. due to changed imports, we may receive `rpc/release` -- for the previous RPC session. This is fine, just ignore. if let some seshRef := (← get).rpcSessions.find? p.sessionId then let monoMsNow ← IO.monoMsNow let discardRefs : StateM RpcObjectStore Unit := do for ref in p.refs do discard do rpcReleaseRef ref seshRef.modify fun st => let st := st.keptAlive monoMsNow let ((), objects) := discardRefs st.objects { st with objects } def handleRpcKeepAlive (p : Lsp.RpcKeepAliveParams) : WorkerM Unit := do match (← get).rpcSessions.find? p.sessionId with | none => return | some seshRef => seshRef.modify (·.keptAlive (← IO.monoMsNow)) end NotificationHandling /-! Requests here are handled synchronously rather than in the asynchronous `RequestM`. -/ section RequestHandling def handleRpcConnect (_ : RpcConnectParams) : WorkerM RpcConnected := do let (newId, newSesh) ← RpcSession.new let newSeshRef ← IO.mkRef newSesh modify fun st => { st with rpcSessions := st.rpcSessions.insert newId newSeshRef } return { sessionId := newId } end RequestHandling section MessageHandling def parseParams (paramType : Type) [FromJson paramType] (params : Json) : WorkerM paramType := match fromJson? params with | Except.ok parsed => pure parsed | Except.error inner => throwServerError s!"Got param with wrong structure: {params.compress}\n{inner}" def handleNotification (method : String) (params : Json) : WorkerM Unit := do let handle := fun paramType [FromJson paramType] (handler : paramType → WorkerM Unit) => parseParams paramType params >>= handler match method with | "textDocument/didChange" => handle DidChangeTextDocumentParams handleDidChange | "$/cancelRequest" => handle CancelParams handleCancelRequest | "$/lean/rpc/release" => handle RpcReleaseParams handleRpcRelease | "$/lean/rpc/keepAlive" => handle RpcKeepAliveParams handleRpcKeepAlive | _ => throwServerError s!"Got unsupported notification method: {method}" def queueRequest (id : RequestID) (requestTask : Task (Except IO.Error Unit)) : WorkerM Unit := do updatePendingRequests (fun pendingRequests => pendingRequests.insert id requestTask) def handleRequest (id : RequestID) (method : String) (params : Json) : WorkerM Unit := do let ctx ← read let st ← get if method == "$/lean/rpc/connect" then try let ps ← parseParams RpcConnectParams params let resp ← handleRpcConnect ps ctx.hOut.writeLspResponse ⟨id, resp⟩ catch e => ctx.hOut.writeLspResponseError { id code := ErrorCode.internalError message := toString e } return -- we assume that every request requires at least the header snapshot or the search path let t ← IO.bindTask ctx.headerTask fun x => do let (_, srcSearchPath) ← IO.ofExcept x let rc : RequestContext := { rpcSessions := st.rpcSessions srcSearchPath doc := st.doc hLog := ctx.hLog hOut := ctx.hOut initParams := ctx.initParams } let t? ← EIO.toIO' <| handleLspRequest method params rc let t₁ ← match t? with | Except.error e => IO.asTask do ctx.hOut.writeLspResponseError <| e.toLspResponseError id | Except.ok t => (IO.mapTask · t) fun | Except.ok resp => ctx.hOut.writeLspResponse ⟨id, resp⟩ | Except.error e => ctx.hOut.writeLspResponseError <| e.toLspResponseError id queueRequest id t end MessageHandling section MainLoop partial def mainLoop : WorkerM Unit := do let ctx ← read let mut st ← get let msg ← ctx.hIn.readLspMessage let filterFinishedTasks (acc : PendingRequestMap) (id : RequestID) (task : Task (Except IO.Error Unit)) : IO PendingRequestMap := do if (← hasFinished task) then /- Handler tasks are constructed so that the only possible errors here are failures of writing a response into the stream. -/ if let Except.error e := task.get then throwServerError s!"Failed responding to request {id}: {e}" pure <| acc.erase id else pure acc let pendingRequests ← st.pendingRequests.foldM (fun acc id task => filterFinishedTasks acc id task) st.pendingRequests st := { st with pendingRequests } -- Opportunistically (i.e. when we wake up on messages) check if any RPC session has expired. for (id, seshRef) in st.rpcSessions do let sesh ← seshRef.get if (← sesh.hasExpired) then st := { st with rpcSessions := st.rpcSessions.erase id } set st match msg with | Message.request id method (some params) => handleRequest id method (toJson params) mainLoop | Message.notification "exit" none => let doc := st.doc doc.cancelTk.set return () | Message.notification method (some params) => handleNotification method (toJson params) mainLoop | _ => throwServerError "Got invalid JSON-RPC message" end MainLoop def initAndRunWorker (i o e : FS.Stream) (opts : Options) : IO UInt32 := do let i ← maybeTee "fwIn.txt" false i let o ← maybeTee "fwOut.txt" true o let initParams ← i.readLspRequestAs "initialize" InitializeParams let ⟨_, param⟩ ← i.readLspNotificationAs "textDocument/didOpen" DidOpenTextDocumentParams let doc := param.textDocument /- NOTE(WN): `toFileMap` marks line beginnings as immediately following "\n", which should be enough to handle both LF and CRLF correctly. This is because LSP always refers to characters by (line, column), so if we get the line number correct it shouldn't matter that there is a CR there. -/ let meta : DocumentMeta := ⟨doc.uri, doc.version, doc.text.toFileMap⟩ let e := e.withPrefix s!"[{param.textDocument.uri}] " let _ ← IO.setStderr e try let (ctx, st) ← initializeWorker meta i o e initParams.param opts let _ ← StateRefT'.run (s := st) <| ReaderT.run (r := ctx) mainLoop return (0 : UInt32) catch e => IO.eprintln e publishDiagnostics meta #[{ range := ⟨⟨0, 0⟩, ⟨0, 0⟩⟩, severity? := DiagnosticSeverity.error, message := e.toString }] o return (1 : UInt32) @[export lean_server_worker_main] def workerMain (opts : Options) : IO UInt32 := do let i ← IO.getStdin let o ← IO.getStdout let e ← IO.getStderr try let exitCode ← initAndRunWorker i o e opts -- HACK: all `Task`s are currently "foreground", i.e. we join on them on main thread exit, but we definitely don't -- want to do that in the case of the worker processes, which can produce non-terminating tasks evaluating user code o.flush e.flush IO.Process.exit exitCode.toUInt8 catch err => e.putStrLn s!"worker initialization error: {err}" return (1 : UInt32) end Lean.Server.FileWorker
732491e9a666d55376aa15c145738870f56f532c
947fa6c38e48771ae886239b4edce6db6e18d0fb
/src/linear_algebra/tensor_product.lean
6b89a08161cca555dd71fff9479557094de6c182
[ "Apache-2.0" ]
permissive
ramonfmir/mathlib
c5dc8b33155473fab97c38bd3aa6723dc289beaa
14c52e990c17f5a00c0cc9e09847af16fabbed25
refs/heads/master
1,661,979,343,526
1,660,830,384,000
1,660,830,384,000
182,072,989
0
0
null
1,555,585,876,000
1,555,585,876,000
null
UTF-8
Lean
false
false
43,408
lean
/- Copyright (c) 2018 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau, Mario Carneiro -/ import group_theory.congruence import algebra.module.submodule.bilinear /-! # Tensor product of modules over commutative semirings. This file constructs the tensor product of modules over commutative semirings. Given a semiring `R` and modules over it `M` and `N`, the standard construction of the tensor product is `tensor_product R M N`. It is also a module over `R`. It comes with a canonical bilinear map `M → N → tensor_product R M N`. Given any bilinear map `M → N → P`, there is a unique linear map `tensor_product R M N → P` whose composition with the canonical bilinear map `M → N → tensor_product R M N` is the given bilinear map `M → N → P`. We start by proving basic lemmas about bilinear maps. ## Notations This file uses the localized notation `M ⊗ N` and `M ⊗[R] N` for `tensor_product R M N`, as well as `m ⊗ₜ n` and `m ⊗ₜ[R] n` for `tensor_product.tmul R m n`. ## Tags bilinear, tensor, tensor product -/ section semiring variables {R : Type*} [comm_semiring R] variables {R' : Type*} [monoid R'] variables {R'' : Type*} [semiring R''] variables {M : Type*} {N : Type*} {P : Type*} {Q : Type*} {S : Type*} variables [add_comm_monoid M] [add_comm_monoid N] [add_comm_monoid P] [add_comm_monoid Q] [add_comm_monoid S] variables [module R M] [module R N] [module R P] [module R Q] [module R S] variables [distrib_mul_action R' M] variables [module R'' M] include R variables (M N) namespace tensor_product section -- open free_add_monoid variables (R) /-- The relation on `free_add_monoid (M × N)` that generates a congruence whose quotient is the tensor product. -/ inductive eqv : free_add_monoid (M × N) → free_add_monoid (M × N) → Prop | of_zero_left : ∀ n : N, eqv (free_add_monoid.of (0, n)) 0 | of_zero_right : ∀ m : M, eqv (free_add_monoid.of (m, 0)) 0 | of_add_left : ∀ (m₁ m₂ : M) (n : N), eqv (free_add_monoid.of (m₁, n) + free_add_monoid.of (m₂, n)) (free_add_monoid.of (m₁ + m₂, n)) | of_add_right : ∀ (m : M) (n₁ n₂ : N), eqv (free_add_monoid.of (m, n₁) + free_add_monoid.of (m, n₂)) (free_add_monoid.of (m, n₁ + n₂)) | of_smul : ∀ (r : R) (m : M) (n : N), eqv (free_add_monoid.of (r • m, n)) (free_add_monoid.of (m, r • n)) | add_comm : ∀ x y, eqv (x + y) (y + x) end end tensor_product variables (R) /-- The tensor product of two modules `M` and `N` over the same commutative semiring `R`. The localized notations are `M ⊗ N` and `M ⊗[R] N`, accessed by `open_locale tensor_product`. -/ def tensor_product : Type* := (add_con_gen (tensor_product.eqv R M N)).quotient variables {R} localized "infix ` ⊗ `:100 := tensor_product _" in tensor_product localized "notation M ` ⊗[`:100 R `] `:0 N:100 := tensor_product R M N" in tensor_product namespace tensor_product section module instance : add_zero_class (M ⊗[R] N) := { .. (add_con_gen (tensor_product.eqv R M N)).add_monoid } instance : add_comm_semigroup (M ⊗[R] N) := { add_comm := λ x y, add_con.induction_on₂ x y $ λ x y, quotient.sound' $ add_con_gen.rel.of _ _ $ eqv.add_comm _ _, .. (add_con_gen (tensor_product.eqv R M N)).add_monoid } instance : inhabited (M ⊗[R] N) := ⟨0⟩ variables (R) {M N} /-- The canonical function `M → N → M ⊗ N`. The localized notations are `m ⊗ₜ n` and `m ⊗ₜ[R] n`, accessed by `open_locale tensor_product`. -/ def tmul (m : M) (n : N) : M ⊗[R] N := add_con.mk' _ $ free_add_monoid.of (m, n) variables {R} infix ` ⊗ₜ `:100 := tmul _ notation x ` ⊗ₜ[`:100 R `] `:0 y:100 := tmul R x y @[elab_as_eliminator] protected theorem induction_on {C : (M ⊗[R] N) → Prop} (z : M ⊗[R] N) (C0 : C 0) (C1 : ∀ {x y}, C $ x ⊗ₜ[R] y) (Cp : ∀ {x y}, C x → C y → C (x + y)) : C z := add_con.induction_on z $ λ x, free_add_monoid.rec_on x C0 $ λ ⟨m, n⟩ y ih, by { rw add_con.coe_add, exact Cp C1 ih } variables (M) @[simp] lemma zero_tmul (n : N) : (0 : M) ⊗ₜ[R] n = 0 := quotient.sound' $ add_con_gen.rel.of _ _ $ eqv.of_zero_left _ variables {M} lemma add_tmul (m₁ m₂ : M) (n : N) : (m₁ + m₂) ⊗ₜ n = m₁ ⊗ₜ n + m₂ ⊗ₜ[R] n := eq.symm $ quotient.sound' $ add_con_gen.rel.of _ _ $ eqv.of_add_left _ _ _ variables (N) @[simp] lemma tmul_zero (m : M) : m ⊗ₜ[R] (0 : N) = 0 := quotient.sound' $ add_con_gen.rel.of _ _ $ eqv.of_zero_right _ variables {N} lemma tmul_add (m : M) (n₁ n₂ : N) : m ⊗ₜ (n₁ + n₂) = m ⊗ₜ n₁ + m ⊗ₜ[R] n₂ := eq.symm $ quotient.sound' $ add_con_gen.rel.of _ _ $ eqv.of_add_right _ _ _ section variables (R R' M N) /-- A typeclass for `has_smul` structures which can be moved across a tensor product. This typeclass is generated automatically from a `is_scalar_tower` instance, but exists so that we can also add an instance for `add_comm_group.int_module`, allowing `z •` to be moved even if `R` does not support negation. Note that `module R' (M ⊗[R] N)` is available even without this typeclass on `R'`; it's only needed if `tensor_product.smul_tmul`, `tensor_product.smul_tmul'`, or `tensor_product.tmul_smul` is used. -/ class compatible_smul [distrib_mul_action R' N] := (smul_tmul : ∀ (r : R') (m : M) (n : N), (r • m) ⊗ₜ n = m ⊗ₜ[R] (r • n)) end /-- Note that this provides the default `compatible_smul R R M N` instance through `mul_action.is_scalar_tower.left`. -/ @[priority 100] instance compatible_smul.is_scalar_tower [has_smul R' R] [is_scalar_tower R' R M] [distrib_mul_action R' N] [is_scalar_tower R' R N] : compatible_smul R R' M N := ⟨λ r m n, begin conv_lhs {rw ← one_smul R m}, conv_rhs {rw ← one_smul R n}, rw [←smul_assoc, ←smul_assoc], exact (quotient.sound' $ add_con_gen.rel.of _ _ $ eqv.of_smul _ _ _), end⟩ /-- `smul` can be moved from one side of the product to the other .-/ lemma smul_tmul [distrib_mul_action R' N] [compatible_smul R R' M N] (r : R') (m : M) (n : N) : (r • m) ⊗ₜ n = m ⊗ₜ[R] (r • n) := compatible_smul.smul_tmul _ _ _ /-- Auxiliary function to defining scalar multiplication on tensor product. -/ def smul.aux {R' : Type*} [has_smul R' M] (r : R') : free_add_monoid (M × N) →+ M ⊗[R] N := free_add_monoid.lift $ λ p : M × N, (r • p.1) ⊗ₜ p.2 theorem smul.aux_of {R' : Type*} [has_smul R' M] (r : R') (m : M) (n : N) : smul.aux r (free_add_monoid.of (m, n)) = (r • m) ⊗ₜ[R] n := rfl variables [smul_comm_class R R' M] variables [smul_comm_class R R'' M] /-- Given two modules over a commutative semiring `R`, if one of the factors carries a (distributive) action of a second type of scalars `R'`, which commutes with the action of `R`, then the tensor product (over `R`) carries an action of `R'`. This instance defines this `R'` action in the case that it is the left module which has the `R'` action. Two natural ways in which this situation arises are: * Extension of scalars * A tensor product of a group representation with a module not carrying an action Note that in the special case that `R = R'`, since `R` is commutative, we just get the usual scalar action on a tensor product of two modules. This special case is important enough that, for performance reasons, we define it explicitly below. -/ instance left_has_smul : has_smul R' (M ⊗[R] N) := ⟨λ r, (add_con_gen (tensor_product.eqv R M N)).lift (smul.aux r : _ →+ M ⊗[R] N) $ add_con.add_con_gen_le $ λ x y hxy, match x, y, hxy with | _, _, (eqv.of_zero_left n) := (add_con.ker_rel _).2 $ by simp_rw [add_monoid_hom.map_zero, smul.aux_of, smul_zero, zero_tmul] | _, _, (eqv.of_zero_right m) := (add_con.ker_rel _).2 $ by simp_rw [add_monoid_hom.map_zero, smul.aux_of, tmul_zero] | _, _, (eqv.of_add_left m₁ m₂ n) := (add_con.ker_rel _).2 $ by simp_rw [add_monoid_hom.map_add, smul.aux_of, smul_add, add_tmul] | _, _, (eqv.of_add_right m n₁ n₂) := (add_con.ker_rel _).2 $ by simp_rw [add_monoid_hom.map_add, smul.aux_of, tmul_add] | _, _, (eqv.of_smul s m n) := (add_con.ker_rel _).2 $ by rw [smul.aux_of, smul.aux_of, ←smul_comm, smul_tmul] | _, _, (eqv.add_comm x y) := (add_con.ker_rel _).2 $ by simp_rw [add_monoid_hom.map_add, add_comm] end⟩ instance : has_smul R (M ⊗[R] N) := tensor_product.left_has_smul protected theorem smul_zero (r : R') : (r • 0 : M ⊗[R] N) = 0 := add_monoid_hom.map_zero _ protected theorem smul_add (r : R') (x y : M ⊗[R] N) : r • (x + y) = r • x + r • y := add_monoid_hom.map_add _ _ _ protected theorem zero_smul (x : M ⊗[R] N) : (0 : R'') • x = 0 := have ∀ (r : R'') (m : M) (n : N), r • (m ⊗ₜ[R] n) = (r • m) ⊗ₜ n := λ _ _ _, rfl, tensor_product.induction_on x (by rw tensor_product.smul_zero) (λ m n, by rw [this, zero_smul, zero_tmul]) (λ x y ihx ihy, by rw [tensor_product.smul_add, ihx, ihy, add_zero]) protected theorem one_smul (x : M ⊗[R] N) : (1 : R') • x = x := have ∀ (r : R') (m : M) (n : N), r • (m ⊗ₜ[R] n) = (r • m) ⊗ₜ n := λ _ _ _, rfl, tensor_product.induction_on x (by rw tensor_product.smul_zero) (λ m n, by rw [this, one_smul]) (λ x y ihx ihy, by rw [tensor_product.smul_add, ihx, ihy]) protected theorem add_smul (r s : R'') (x : M ⊗[R] N) : (r + s) • x = r • x + s • x := have ∀ (r : R'') (m : M) (n : N), r • (m ⊗ₜ[R] n) = (r • m) ⊗ₜ n := λ _ _ _, rfl, tensor_product.induction_on x (by simp_rw [tensor_product.smul_zero, add_zero]) (λ m n, by simp_rw [this, add_smul, add_tmul]) (λ x y ihx ihy, by { simp_rw tensor_product.smul_add, rw [ihx, ihy, add_add_add_comm] }) instance : add_comm_monoid (M ⊗[R] N) := { nsmul := λ n v, n • v, nsmul_zero' := by simp [tensor_product.zero_smul], nsmul_succ' := by simp [nat.succ_eq_one_add, tensor_product.one_smul, tensor_product.add_smul], .. tensor_product.add_comm_semigroup _ _, .. tensor_product.add_zero_class _ _} instance left_distrib_mul_action : distrib_mul_action R' (M ⊗[R] N) := have ∀ (r : R') (m : M) (n : N), r • (m ⊗ₜ[R] n) = (r • m) ⊗ₜ n := λ _ _ _, rfl, { smul := (•), smul_add := λ r x y, tensor_product.smul_add r x y, mul_smul := λ r s x, tensor_product.induction_on x (by simp_rw tensor_product.smul_zero) (λ m n, by simp_rw [this, mul_smul]) (λ x y ihx ihy, by { simp_rw tensor_product.smul_add, rw [ihx, ihy] }), one_smul := tensor_product.one_smul, smul_zero := tensor_product.smul_zero } instance : distrib_mul_action R (M ⊗[R] N) := tensor_product.left_distrib_mul_action theorem smul_tmul' (r : R') (m : M) (n : N) : r • (m ⊗ₜ[R] n) = (r • m) ⊗ₜ n := rfl @[simp] lemma tmul_smul [distrib_mul_action R' N] [compatible_smul R R' M N] (r : R') (x : M) (y : N) : x ⊗ₜ (r • y) = r • (x ⊗ₜ[R] y) := (smul_tmul _ _ _).symm lemma smul_tmul_smul (r s : R) (m : M) (n : N) : (r • m) ⊗ₜ[R] (s • n) = (r * s) • (m ⊗ₜ[R] n) := by simp only [tmul_smul, smul_tmul, mul_smul] instance left_module : module R'' (M ⊗[R] N) := { smul := (•), add_smul := tensor_product.add_smul, zero_smul := tensor_product.zero_smul, ..tensor_product.left_distrib_mul_action } instance : module R (M ⊗[R] N) := tensor_product.left_module instance [module R''ᵐᵒᵖ M] [is_central_scalar R'' M] : is_central_scalar R'' (M ⊗[R] N) := { op_smul_eq_smul := λ r x, tensor_product.induction_on x (by rw [smul_zero, smul_zero]) (λ x y, by rw [smul_tmul', smul_tmul', op_smul_eq_smul]) (λ x y hx hy, by rw [smul_add, smul_add, hx, hy]) } section -- Like `R'`, `R'₂` provides a `distrib_mul_action R'₂ (M ⊗[R] N)` variables {R'₂ : Type*} [monoid R'₂] [distrib_mul_action R'₂ M] variables [smul_comm_class R R'₂ M] [has_smul R'₂ R'] /-- `is_scalar_tower R'₂ R' M` implies `is_scalar_tower R'₂ R' (M ⊗[R] N)` -/ instance is_scalar_tower_left [is_scalar_tower R'₂ R' M] : is_scalar_tower R'₂ R' (M ⊗[R] N) := ⟨λ s r x, tensor_product.induction_on x (by simp) (λ m n, by rw [smul_tmul', smul_tmul', smul_tmul', smul_assoc]) (λ x y ihx ihy, by rw [smul_add, smul_add, smul_add, ihx, ihy])⟩ variables [distrib_mul_action R'₂ N] [distrib_mul_action R' N] variables [compatible_smul R R'₂ M N] [compatible_smul R R' M N] /-- `is_scalar_tower R'₂ R' N` implies `is_scalar_tower R'₂ R' (M ⊗[R] N)` -/ instance is_scalar_tower_right [is_scalar_tower R'₂ R' N] : is_scalar_tower R'₂ R' (M ⊗[R] N) := ⟨λ s r x, tensor_product.induction_on x (by simp) (λ m n, by rw [←tmul_smul, ←tmul_smul, ←tmul_smul, smul_assoc]) (λ x y ihx ihy, by rw [smul_add, smul_add, smul_add, ihx, ihy])⟩ end /-- A short-cut instance for the common case, where the requirements for the `compatible_smul` instances are sufficient. -/ instance is_scalar_tower [has_smul R' R] [is_scalar_tower R' R M] : is_scalar_tower R' R (M ⊗[R] N) := tensor_product.is_scalar_tower_left -- or right variables (R M N) /-- The canonical bilinear map `M → N → M ⊗[R] N`. -/ def mk : M →ₗ[R] N →ₗ[R] M ⊗[R] N := linear_map.mk₂ R (⊗ₜ) add_tmul (λ c m n, by rw [smul_tmul, tmul_smul]) tmul_add tmul_smul variables {R M N} @[simp] lemma mk_apply (m : M) (n : N) : mk R M N m n = m ⊗ₜ n := rfl lemma ite_tmul (x₁ : M) (x₂ : N) (P : Prop) [decidable P] : (if P then x₁ else 0) ⊗ₜ[R] x₂ = if P then x₁ ⊗ₜ x₂ else 0 := by { split_ifs; simp } lemma tmul_ite (x₁ : M) (x₂ : N) (P : Prop) [decidable P] : x₁ ⊗ₜ[R] (if P then x₂ else 0) = if P then x₁ ⊗ₜ x₂ else 0 := by { split_ifs; simp } section open_locale big_operators lemma sum_tmul {α : Type*} (s : finset α) (m : α → M) (n : N) : (∑ a in s, m a) ⊗ₜ[R] n = ∑ a in s, m a ⊗ₜ[R] n := begin classical, induction s using finset.induction with a s has ih h, { simp, }, { simp [finset.sum_insert has, add_tmul, ih], }, end lemma tmul_sum (m : M) {α : Type*} (s : finset α) (n : α → N) : m ⊗ₜ[R] (∑ a in s, n a) = ∑ a in s, m ⊗ₜ[R] n a := begin classical, induction s using finset.induction with a s has ih h, { simp, }, { simp [finset.sum_insert has, tmul_add, ih], }, end end variables (R M N) /-- The simple (aka pure) elements span the tensor product. -/ lemma span_tmul_eq_top : submodule.span R { t : M ⊗[R] N | ∃ m n, m ⊗ₜ n = t } = ⊤ := begin ext t, simp only [submodule.mem_top, iff_true], apply t.induction_on, { exact submodule.zero_mem _, }, { intros m n, apply submodule.subset_span, use [m, n], }, { intros t₁ t₂ ht₁ ht₂, exact submodule.add_mem _ ht₁ ht₂, }, end @[simp] lemma map₂_mk_top_top_eq_top : submodule.map₂ (mk R M N) ⊤ ⊤ = ⊤ := begin rw [← top_le_iff, ← span_tmul_eq_top, submodule.map₂_eq_span_image2], exact submodule.span_mono (λ _ ⟨m, n, h⟩, ⟨m, n, trivial, trivial, h⟩), end end module section UMP variables {M N P Q} variables (f : M →ₗ[R] N →ₗ[R] P) /-- Auxiliary function to constructing a linear map `M ⊗ N → P` given a bilinear map `M → N → P` with the property that its composition with the canonical bilinear map `M → N → M ⊗ N` is the given bilinear map `M → N → P`. -/ def lift_aux : (M ⊗[R] N) →+ P := (add_con_gen (tensor_product.eqv R M N)).lift (free_add_monoid.lift $ λ p : M × N, f p.1 p.2) $ add_con.add_con_gen_le $ λ x y hxy, match x, y, hxy with | _, _, (eqv.of_zero_left n) := (add_con.ker_rel _).2 $ by simp_rw [add_monoid_hom.map_zero, free_add_monoid.lift_eval_of, f.map_zero₂] | _, _, (eqv.of_zero_right m) := (add_con.ker_rel _).2 $ by simp_rw [add_monoid_hom.map_zero, free_add_monoid.lift_eval_of, (f m).map_zero] | _, _, (eqv.of_add_left m₁ m₂ n) := (add_con.ker_rel _).2 $ by simp_rw [add_monoid_hom.map_add, free_add_monoid.lift_eval_of, f.map_add₂] | _, _, (eqv.of_add_right m n₁ n₂) := (add_con.ker_rel _).2 $ by simp_rw [add_monoid_hom.map_add, free_add_monoid.lift_eval_of, (f m).map_add] | _, _, (eqv.of_smul r m n) := (add_con.ker_rel _).2 $ by simp_rw [free_add_monoid.lift_eval_of, f.map_smul₂, (f m).map_smul] | _, _, (eqv.add_comm x y) := (add_con.ker_rel _).2 $ by simp_rw [add_monoid_hom.map_add, add_comm] end lemma lift_aux_tmul (m n) : lift_aux f (m ⊗ₜ n) = f m n := zero_add _ variable {f} @[simp] lemma lift_aux.smul (r : R) (x) : lift_aux f (r • x) = r • lift_aux f x := tensor_product.induction_on x (smul_zero _).symm (λ p q, by rw [← tmul_smul, lift_aux_tmul, lift_aux_tmul, (f p).map_smul]) (λ p q ih1 ih2, by rw [smul_add, (lift_aux f).map_add, ih1, ih2, (lift_aux f).map_add, smul_add]) variable (f) /-- Constructing a linear map `M ⊗ N → P` given a bilinear map `M → N → P` with the property that its composition with the canonical bilinear map `M → N → M ⊗ N` is the given bilinear map `M → N → P`. -/ def lift : M ⊗ N →ₗ[R] P := { map_smul' := lift_aux.smul, .. lift_aux f } variable {f} @[simp] lemma lift.tmul (x y) : lift f (x ⊗ₜ y) = f x y := zero_add _ @[simp] lemma lift.tmul' (x y) : (lift f).1 (x ⊗ₜ y) = f x y := lift.tmul _ _ theorem ext' {g h : (M ⊗[R] N) →ₗ[R] P} (H : ∀ x y, g (x ⊗ₜ y) = h (x ⊗ₜ y)) : g = h := linear_map.ext $ λ z, tensor_product.induction_on z (by simp_rw linear_map.map_zero) H $ λ x y ihx ihy, by rw [g.map_add, h.map_add, ihx, ihy] theorem lift.unique {g : (M ⊗[R] N) →ₗ[R] P} (H : ∀ x y, g (x ⊗ₜ y) = f x y) : g = lift f := ext' $ λ m n, by rw [H, lift.tmul] theorem lift_mk : lift (mk R M N) = linear_map.id := eq.symm $ lift.unique $ λ x y, rfl theorem lift_compr₂ (g : P →ₗ[R] Q) : lift (f.compr₂ g) = g.comp (lift f) := eq.symm $ lift.unique $ λ x y, by simp theorem lift_mk_compr₂ (f : M ⊗ N →ₗ[R] P) : lift ((mk R M N).compr₂ f) = f := by rw [lift_compr₂ f, lift_mk, linear_map.comp_id] /-- This used to be an `@[ext]` lemma, but it fails very slowly when the `ext` tactic tries to apply it in some cases, notably when one wants to show equality of two linear maps. The `@[ext]` attribute is now added locally where it is needed. Using this as the `@[ext]` lemma instead of `tensor_product.ext'` allows `ext` to apply lemmas specific to `M →ₗ _` and `N →ₗ _`. See note [partially-applied ext lemmas]. -/ theorem ext {g h : M ⊗ N →ₗ[R] P} (H : (mk R M N).compr₂ g = (mk R M N).compr₂ h) : g = h := by rw [← lift_mk_compr₂ g, H, lift_mk_compr₂] local attribute [ext] ext example : M → N → (M → N → P) → P := λ m, flip $ λ f, f m variables (R M N P) /-- Linearly constructing a linear map `M ⊗ N → P` given a bilinear map `M → N → P` with the property that its composition with the canonical bilinear map `M → N → M ⊗ N` is the given bilinear map `M → N → P`. -/ def uncurry : (M →ₗ[R] N →ₗ[R] P) →ₗ[R] M ⊗[R] N →ₗ[R] P := linear_map.flip $ lift $ (linear_map.lflip _ _ _ _).comp (linear_map.flip linear_map.id) variables {R M N P} @[simp] theorem uncurry_apply (f : M →ₗ[R] N →ₗ[R] P) (m : M) (n : N) : uncurry R M N P f (m ⊗ₜ n) = f m n := by rw [uncurry, linear_map.flip_apply, lift.tmul]; refl variables (R M N P) /-- A linear equivalence constructing a linear map `M ⊗ N → P` given a bilinear map `M → N → P` with the property that its composition with the canonical bilinear map `M → N → M ⊗ N` is the given bilinear map `M → N → P`. -/ def lift.equiv : (M →ₗ[R] N →ₗ[R] P) ≃ₗ[R] (M ⊗ N →ₗ[R] P) := { inv_fun := λ f, (mk R M N).compr₂ f, left_inv := λ f, linear_map.ext₂ $ λ m n, lift.tmul _ _, right_inv := λ f, ext' $ λ m n, lift.tmul _ _, .. uncurry R M N P } @[simp] lemma lift.equiv_apply (f : M →ₗ[R] N →ₗ[R] P) (m : M) (n : N) : lift.equiv R M N P f (m ⊗ₜ n) = f m n := uncurry_apply f m n @[simp] lemma lift.equiv_symm_apply (f : M ⊗[R] N →ₗ[R] P) (m : M) (n : N) : (lift.equiv R M N P).symm f m n = f (m ⊗ₜ n) := rfl /-- Given a linear map `M ⊗ N → P`, compose it with the canonical bilinear map `M → N → M ⊗ N` to form a bilinear map `M → N → P`. -/ def lcurry : (M ⊗[R] N →ₗ[R] P) →ₗ[R] M →ₗ[R] N →ₗ[R] P := (lift.equiv R M N P).symm variables {R M N P} @[simp] theorem lcurry_apply (f : M ⊗[R] N →ₗ[R] P) (m : M) (n : N) : lcurry R M N P f m n = f (m ⊗ₜ n) := rfl /-- Given a linear map `M ⊗ N → P`, compose it with the canonical bilinear map `M → N → M ⊗ N` to form a bilinear map `M → N → P`. -/ def curry (f : M ⊗ N →ₗ[R] P) : M →ₗ[R] N →ₗ[R] P := lcurry R M N P f @[simp] theorem curry_apply (f : M ⊗ N →ₗ[R] P) (m : M) (n : N) : curry f m n = f (m ⊗ₜ n) := rfl lemma curry_injective : function.injective (curry : (M ⊗[R] N →ₗ[R] P) → (M →ₗ[R] N →ₗ[R] P)) := λ g h H, ext H theorem ext_threefold {g h : (M ⊗[R] N) ⊗[R] P →ₗ[R] Q} (H : ∀ x y z, g ((x ⊗ₜ y) ⊗ₜ z) = h ((x ⊗ₜ y) ⊗ₜ z)) : g = h := begin ext x y z, exact H x y z end -- We'll need this one for checking the pentagon identity! theorem ext_fourfold {g h : ((M ⊗[R] N) ⊗[R] P) ⊗[R] Q →ₗ[R] S} (H : ∀ w x y z, g (((w ⊗ₜ x) ⊗ₜ y) ⊗ₜ z) = h (((w ⊗ₜ x) ⊗ₜ y) ⊗ₜ z)) : g = h := begin ext w x y z, exact H w x y z, end end UMP variables {M N} section variables (R M) /-- The base ring is a left identity for the tensor product of modules, up to linear equivalence. -/ protected def lid : R ⊗ M ≃ₗ[R] M := linear_equiv.of_linear (lift $ linear_map.lsmul R M) (mk R R M 1) (linear_map.ext $ λ _, by simp) (ext' $ λ r m, by simp; rw [← tmul_smul, ← smul_tmul, smul_eq_mul, mul_one]) end @[simp] theorem lid_tmul (m : M) (r : R) : ((tensor_product.lid R M) : (R ⊗ M → M)) (r ⊗ₜ m) = r • m := begin dsimp [tensor_product.lid], simp, end @[simp] lemma lid_symm_apply (m : M) : (tensor_product.lid R M).symm m = 1 ⊗ₜ m := rfl section variables (R M N) /-- The tensor product of modules is commutative, up to linear equivalence. -/ protected def comm : M ⊗ N ≃ₗ[R] N ⊗ M := linear_equiv.of_linear (lift (mk R N M).flip) (lift (mk R M N).flip) (ext' $ λ m n, rfl) (ext' $ λ m n, rfl) @[simp] theorem comm_tmul (m : M) (n : N) : (tensor_product.comm R M N) (m ⊗ₜ n) = n ⊗ₜ m := rfl @[simp] theorem comm_symm_tmul (m : M) (n : N) : (tensor_product.comm R M N).symm (n ⊗ₜ m) = m ⊗ₜ n := rfl end section variables (R M) /-- The base ring is a right identity for the tensor product of modules, up to linear equivalence. -/ protected def rid : M ⊗[R] R ≃ₗ[R] M := linear_equiv.trans (tensor_product.comm R M R) (tensor_product.lid R M) end @[simp] theorem rid_tmul (m : M) (r : R) : (tensor_product.rid R M) (m ⊗ₜ r) = r • m := begin dsimp [tensor_product.rid, tensor_product.comm, tensor_product.lid], simp, end @[simp] lemma rid_symm_apply (m : M) : (tensor_product.rid R M).symm m = m ⊗ₜ 1 := rfl open linear_map section variables (R M N P) /-- The associator for tensor product of R-modules, as a linear equivalence. -/ protected def assoc : (M ⊗[R] N) ⊗[R] P ≃ₗ[R] M ⊗[R] (N ⊗[R] P) := begin refine linear_equiv.of_linear (lift $ lift $ comp (lcurry R _ _ _) $ mk _ _ _) (lift $ comp (uncurry R _ _ _) $ curry $ mk _ _ _) (ext $ linear_map.ext $ λ m, ext' $ λ n p, _) (ext $ flip_inj $ linear_map.ext $ λ p, ext' $ λ m n, _); repeat { rw lift.tmul <|> rw compr₂_apply <|> rw comp_apply <|> rw mk_apply <|> rw flip_apply <|> rw lcurry_apply <|> rw uncurry_apply <|> rw curry_apply <|> rw id_apply } end end @[simp] theorem assoc_tmul (m : M) (n : N) (p : P) : (tensor_product.assoc R M N P) ((m ⊗ₜ n) ⊗ₜ p) = m ⊗ₜ (n ⊗ₜ p) := rfl @[simp] theorem assoc_symm_tmul (m : M) (n : N) (p : P) : (tensor_product.assoc R M N P).symm (m ⊗ₜ (n ⊗ₜ p)) = (m ⊗ₜ n) ⊗ₜ p := rfl /-- The tensor product of a pair of linear maps between modules. -/ def map (f : M →ₗ[R] P) (g : N →ₗ[R] Q) : M ⊗ N →ₗ[R] P ⊗ Q := lift $ comp (compl₂ (mk _ _ _) g) f @[simp] theorem map_tmul (f : M →ₗ[R] P) (g : N →ₗ[R] Q) (m : M) (n : N) : map f g (m ⊗ₜ n) = f m ⊗ₜ g n := rfl lemma map_range_eq_span_tmul (f : M →ₗ[R] P) (g : N →ₗ[R] Q) : (map f g).range = submodule.span R { t | ∃ m n, (f m) ⊗ₜ (g n) = t } := begin simp only [← submodule.map_top, ← span_tmul_eq_top, submodule.map_span, set.mem_image, set.mem_set_of_eq], congr, ext t, split, { rintros ⟨_, ⟨⟨m, n, rfl⟩, rfl⟩⟩, use [m, n], simp only [map_tmul], }, { rintros ⟨m, n, rfl⟩, use [m ⊗ₜ n, m, n], simp only [map_tmul], }, end /-- Given submodules `p ⊆ P` and `q ⊆ Q`, this is the natural map: `p ⊗ q → P ⊗ Q`. -/ @[simp] def map_incl (p : submodule R P) (q : submodule R Q) : p ⊗[R] q →ₗ[R] P ⊗[R] Q := map p.subtype q.subtype section variables {P' Q' : Type*} variables [add_comm_monoid P'] [module R P'] variables [add_comm_monoid Q'] [module R Q'] lemma map_comp (f₂ : P →ₗ[R] P') (f₁ : M →ₗ[R] P) (g₂ : Q →ₗ[R] Q') (g₁ : N →ₗ[R] Q) : map (f₂.comp f₁) (g₂.comp g₁) = (map f₂ g₂).comp (map f₁ g₁) := ext' $ λ _ _, by simp only [linear_map.comp_apply, map_tmul] lemma lift_comp_map (i : P →ₗ[R] Q →ₗ[R] Q') (f : M →ₗ[R] P) (g : N →ₗ[R] Q) : (lift i).comp (map f g) = lift ((i.comp f).compl₂ g) := ext' $ λ _ _, by simp only [lift.tmul, map_tmul, linear_map.compl₂_apply, linear_map.comp_apply] local attribute [ext] ext @[simp] lemma map_id : map (id : M →ₗ[R] M) (id : N →ₗ[R] N) = id := by { ext, simp only [mk_apply, id_coe, compr₂_apply, id.def, map_tmul], } @[simp] lemma map_one : map (1 : M →ₗ[R] M) (1 : N →ₗ[R] N) = 1 := map_id lemma map_mul (f₁ f₂ : M →ₗ[R] M) (g₁ g₂ : N →ₗ[R] N) : map (f₁ * f₂) (g₁ * g₂) = (map f₁ g₁) * (map f₂ g₂) := map_comp f₁ f₂ g₁ g₂ @[simp] protected lemma map_pow (f : M →ₗ[R] M) (g : N →ₗ[R] N) (n : ℕ) : (map f g)^n = map (f^n) (g^n) := begin induction n with n ih, { simp only [pow_zero, map_one], }, { simp only [pow_succ', ih, map_mul], }, end lemma map_add_left (f₁ f₂ : M →ₗ[R] P) (g : N →ₗ[R] Q) : map (f₁ + f₂) g = map f₁ g + map f₂ g := by {ext, simp only [add_tmul, compr₂_apply, mk_apply, map_tmul, add_apply]} lemma map_add_right (f : M →ₗ[R] P) (g₁ g₂ : N →ₗ[R] Q) : map f (g₁ + g₂) = map f g₁ + map f g₂ := by {ext, simp only [tmul_add, compr₂_apply, mk_apply, map_tmul, add_apply]} lemma map_smul_left (r : R) (f : M →ₗ[R] P) (g : N →ₗ[R] Q) : map (r • f) g = r • map f g := by {ext, simp only [smul_tmul, compr₂_apply, mk_apply, map_tmul, smul_apply, tmul_smul]} lemma map_smul_right (r : R) (f : M →ₗ[R] P) (g : N →ₗ[R] Q) : map f (r • g) = r • map f g := by {ext, simp only [smul_tmul, compr₂_apply, mk_apply, map_tmul, smul_apply, tmul_smul]} variables (R M N P Q) /-- The tensor product of a pair of linear maps between modules, bilinear in both maps. -/ def map_bilinear : (M →ₗ[R] P) →ₗ[R] (N →ₗ[R] Q) →ₗ[R] (M ⊗[R] N →ₗ[R] P ⊗[R] Q) := linear_map.mk₂ R map map_add_left map_smul_left map_add_right map_smul_right /-- The canonical linear map from `P ⊗[R] (M →ₗ[R] Q)` to `(M →ₗ[R] P ⊗[R] Q)` -/ def ltensor_hom_to_hom_ltensor : P ⊗[R] (M →ₗ[R] Q) →ₗ[R] (M →ₗ[R] P ⊗[R] Q) := tensor_product.lift (llcomp R M Q _ ∘ₗ mk R P Q) /-- The canonical linear map from `(M →ₗ[R] P) ⊗[R] Q` to `(M →ₗ[R] P ⊗[R] Q)` -/ def rtensor_hom_to_hom_rtensor : (M →ₗ[R] P) ⊗[R] Q →ₗ[R] (M →ₗ[R] P ⊗[R] Q) := tensor_product.lift (llcomp R M P _ ∘ₗ (mk R P Q).flip).flip /-- The linear map from `(M →ₗ P) ⊗ (N →ₗ Q)` to `(M ⊗ N →ₗ P ⊗ Q)` sending `f ⊗ₜ g` to the `tensor_product.map f g`, the tensor product of the two maps. -/ def hom_tensor_hom_map : (M →ₗ[R] P) ⊗[R] (N →ₗ[R] Q) →ₗ[R] (M ⊗[R] N →ₗ[R] P ⊗[R] Q) := lift (map_bilinear R M N P Q) variables {R M N P Q} @[simp] lemma map_bilinear_apply (f : M →ₗ[R] P) (g : N →ₗ[R] Q) : map_bilinear R M N P Q f g = map f g := rfl @[simp] lemma ltensor_hom_to_hom_ltensor_apply (p : P) (f : M →ₗ[R] Q) (m : M) : ltensor_hom_to_hom_ltensor R M P Q (p ⊗ₜ f) m = p ⊗ₜ f m := rfl @[simp] lemma rtensor_hom_to_hom_rtensor_apply (f : M →ₗ[R] P) (q : Q) (m : M) : rtensor_hom_to_hom_rtensor R M P Q (f ⊗ₜ q) m = f m ⊗ₜ q := rfl @[simp] lemma hom_tensor_hom_map_apply (f : M →ₗ[R] P) (g : N →ₗ[R] Q) : hom_tensor_hom_map R M N P Q (f ⊗ₜ g) = map f g := by simp only [hom_tensor_hom_map, lift.tmul, map_bilinear_apply] end /-- If `M` and `P` are linearly equivalent and `N` and `Q` are linearly equivalent then `M ⊗ N` and `P ⊗ Q` are linearly equivalent. -/ def congr (f : M ≃ₗ[R] P) (g : N ≃ₗ[R] Q) : M ⊗ N ≃ₗ[R] P ⊗ Q := linear_equiv.of_linear (map f g) (map f.symm g.symm) (ext' $ λ m n, by simp; simp only [linear_equiv.apply_symm_apply]) (ext' $ λ m n, by simp; simp only [linear_equiv.symm_apply_apply]) @[simp] theorem congr_tmul (f : M ≃ₗ[R] P) (g : N ≃ₗ[R] Q) (m : M) (n : N) : congr f g (m ⊗ₜ n) = f m ⊗ₜ g n := rfl @[simp] theorem congr_symm_tmul (f : M ≃ₗ[R] P) (g : N ≃ₗ[R] Q) (p : P) (q : Q) : (congr f g).symm (p ⊗ₜ q) = f.symm p ⊗ₜ g.symm q := rfl variables (R M N P Q) /-- A tensor product analogue of `mul_left_comm`. -/ def left_comm : M ⊗[R] (N ⊗[R] P) ≃ₗ[R] N ⊗[R] (M ⊗[R] P) := let e₁ := (tensor_product.assoc R M N P).symm, e₂ := congr (tensor_product.comm R M N) (1 : P ≃ₗ[R] P), e₃ := (tensor_product.assoc R N M P) in e₁ ≪≫ₗ (e₂ ≪≫ₗ e₃) variables {M N P Q} @[simp] lemma left_comm_tmul (m : M) (n : N) (p : P) : left_comm R M N P (m ⊗ₜ (n ⊗ₜ p)) = n ⊗ₜ (m ⊗ₜ p) := rfl @[simp] lemma left_comm_symm_tmul (m : M) (n : N) (p : P) : (left_comm R M N P).symm (n ⊗ₜ (m ⊗ₜ p)) = m ⊗ₜ (n ⊗ₜ p) := rfl variables (M N P Q) /-- This special case is worth defining explicitly since it is useful for defining multiplication on tensor products of modules carrying multiplications (e.g., associative rings, Lie rings, ...). E.g., suppose `M = P` and `N = Q` and that `M` and `N` carry bilinear multiplications: `M ⊗ M → M` and `N ⊗ N → N`. Using `map`, we can define `(M ⊗ M) ⊗ (N ⊗ N) → M ⊗ N` which, when combined with this definition, yields a bilinear multiplication on `M ⊗ N`: `(M ⊗ N) ⊗ (M ⊗ N) → M ⊗ N`. In particular we could use this to define the multiplication in the `tensor_product.semiring` instance (currently defined "by hand" using `tensor_product.mul`). See also `mul_mul_mul_comm`. -/ def tensor_tensor_tensor_comm : (M ⊗[R] N) ⊗[R] (P ⊗[R] Q) ≃ₗ[R] (M ⊗[R] P) ⊗[R] (N ⊗[R] Q) := let e₁ := tensor_product.assoc R M N (P ⊗[R] Q), e₂ := congr (1 : M ≃ₗ[R] M) (left_comm R N P Q), e₃ := (tensor_product.assoc R M P (N ⊗[R] Q)).symm in e₁ ≪≫ₗ (e₂ ≪≫ₗ e₃) variables {M N P Q} @[simp] lemma tensor_tensor_tensor_comm_tmul (m : M) (n : N) (p : P) (q : Q) : tensor_tensor_tensor_comm R M N P Q ((m ⊗ₜ n) ⊗ₜ (p ⊗ₜ q)) = (m ⊗ₜ p) ⊗ₜ (n ⊗ₜ q) := rfl @[simp] lemma tensor_tensor_tensor_comm_symm_tmul (m : M) (n : N) (p : P) (q : Q) : (tensor_tensor_tensor_comm R M N P Q).symm ((m ⊗ₜ p) ⊗ₜ (n ⊗ₜ q)) = (m ⊗ₜ n) ⊗ₜ (p ⊗ₜ q) := rfl variables (M N P Q) /-- This special case is useful for describing the interplay between `dual_tensor_hom_equiv` and composition of linear maps. E.g., composition of linear maps gives a map `(M → N) ⊗ (N → P) → (M → P)`, and applying `dual_tensor_hom_equiv.symm` to the three hom-modules gives a map `(M.dual ⊗ N) ⊗ (N.dual ⊗ P) → (M.dual ⊗ P)`, which agrees with the application of `contract_right` on `N ⊗ N.dual` after the suitable rebracketting. -/ def tensor_tensor_tensor_assoc : (M ⊗[R] N) ⊗[R] (P ⊗[R] Q) ≃ₗ[R] M ⊗[R] (N ⊗[R] P) ⊗[R] Q := (tensor_product.assoc R (M ⊗[R] N) P Q).symm ≪≫ₗ congr (tensor_product.assoc R M N P) (1 : Q ≃ₗ[R] Q) variables {M N P Q} @[simp] lemma tensor_tensor_tensor_assoc_tmul (m : M) (n : N) (p : P) (q : Q) : tensor_tensor_tensor_assoc R M N P Q ((m ⊗ₜ n) ⊗ₜ (p ⊗ₜ q)) = m ⊗ₜ (n ⊗ₜ p) ⊗ₜ q := rfl @[simp] lemma tensor_tensor_tensor_assoc_symm_tmul (m : M) (n : N) (p : P) (q : Q) : (tensor_tensor_tensor_assoc R M N P Q).symm (m ⊗ₜ (n ⊗ₜ p) ⊗ₜ q) = (m ⊗ₜ n) ⊗ₜ (p ⊗ₜ q) := rfl end tensor_product namespace linear_map variables {R} (M) {N P Q} /-- `ltensor M f : M ⊗ N →ₗ M ⊗ P` is the natural linear map induced by `f : N →ₗ P`. -/ def ltensor (f : N →ₗ[R] P) : M ⊗ N →ₗ[R] M ⊗ P := tensor_product.map id f /-- `rtensor f M : N₁ ⊗ M →ₗ N₂ ⊗ M` is the natural linear map induced by `f : N₁ →ₗ N₂`. -/ def rtensor (f : N →ₗ[R] P) : N ⊗ M →ₗ[R] P ⊗ M := tensor_product.map f id variables (g : P →ₗ[R] Q) (f : N →ₗ[R] P) @[simp] lemma ltensor_tmul (m : M) (n : N) : f.ltensor M (m ⊗ₜ n) = m ⊗ₜ (f n) := rfl @[simp] lemma rtensor_tmul (m : M) (n : N) : f.rtensor M (n ⊗ₜ m) = (f n) ⊗ₜ m := rfl open tensor_product local attribute [ext] tensor_product.ext /-- `ltensor_hom M` is the natural linear map that sends a linear map `f : N →ₗ P` to `M ⊗ f`. -/ def ltensor_hom : (N →ₗ[R] P) →ₗ[R] (M ⊗[R] N →ₗ[R] M ⊗[R] P) := { to_fun := ltensor M, map_add' := λ f g, by { ext x y, simp only [compr₂_apply, mk_apply, add_apply, ltensor_tmul, tmul_add] }, map_smul' := λ r f, by { dsimp, ext x y, simp only [compr₂_apply, mk_apply, tmul_smul, smul_apply, ltensor_tmul] } } /-- `rtensor_hom M` is the natural linear map that sends a linear map `f : N →ₗ P` to `M ⊗ f`. -/ def rtensor_hom : (N →ₗ[R] P) →ₗ[R] (N ⊗[R] M →ₗ[R] P ⊗[R] M) := { to_fun := λ f, f.rtensor M, map_add' := λ f g, by { ext x y, simp only [compr₂_apply, mk_apply, add_apply, rtensor_tmul, add_tmul] }, map_smul' := λ r f, by { dsimp, ext x y, simp only [compr₂_apply, mk_apply, smul_tmul, tmul_smul, smul_apply, rtensor_tmul] } } @[simp] lemma coe_ltensor_hom : (ltensor_hom M : (N →ₗ[R] P) → (M ⊗[R] N →ₗ[R] M ⊗[R] P)) = ltensor M := rfl @[simp] lemma coe_rtensor_hom : (rtensor_hom M : (N →ₗ[R] P) → (N ⊗[R] M →ₗ[R] P ⊗[R] M)) = rtensor M := rfl @[simp] lemma ltensor_add (f g : N →ₗ[R] P) : (f + g).ltensor M = f.ltensor M + g.ltensor M := (ltensor_hom M).map_add f g @[simp] lemma rtensor_add (f g : N →ₗ[R] P) : (f + g).rtensor M = f.rtensor M + g.rtensor M := (rtensor_hom M).map_add f g @[simp] lemma ltensor_zero : ltensor M (0 : N →ₗ[R] P) = 0 := (ltensor_hom M).map_zero @[simp] lemma rtensor_zero : rtensor M (0 : N →ₗ[R] P) = 0 := (rtensor_hom M).map_zero @[simp] lemma ltensor_smul (r : R) (f : N →ₗ[R] P) : (r • f).ltensor M = r • (f.ltensor M) := (ltensor_hom M).map_smul r f @[simp] lemma rtensor_smul (r : R) (f : N →ₗ[R] P) : (r • f).rtensor M = r • (f.rtensor M) := (rtensor_hom M).map_smul r f lemma ltensor_comp : (g.comp f).ltensor M = (g.ltensor M).comp (f.ltensor M) := by { ext m n, simp only [compr₂_apply, mk_apply, comp_apply, ltensor_tmul] } lemma ltensor_comp_apply (x : M ⊗[R] N) : (g.comp f).ltensor M x = (g.ltensor M) ((f.ltensor M) x) := by { rw [ltensor_comp, coe_comp], } lemma rtensor_comp : (g.comp f).rtensor M = (g.rtensor M).comp (f.rtensor M) := by { ext m n, simp only [compr₂_apply, mk_apply, comp_apply, rtensor_tmul] } lemma rtensor_comp_apply (x : N ⊗[R] M) : (g.comp f).rtensor M x = (g.rtensor M) ((f.rtensor M) x) := by { rw [rtensor_comp, coe_comp], } lemma ltensor_mul (f g : module.End R N) : (f * g).ltensor M = (f.ltensor M) * (g.ltensor M) := ltensor_comp M f g lemma rtensor_mul (f g : module.End R N) : (f * g).rtensor M = (f.rtensor M) * (g.rtensor M) := rtensor_comp M f g variables (N) @[simp] lemma ltensor_id : (id : N →ₗ[R] N).ltensor M = id := map_id -- `simp` can prove this. lemma ltensor_id_apply (x : M ⊗[R] N) : (linear_map.id : N →ₗ[R] N).ltensor M x = x := by {rw [ltensor_id, id_coe, id.def], } @[simp] lemma rtensor_id : (id : N →ₗ[R] N).rtensor M = id := map_id -- `simp` can prove this. lemma rtensor_id_apply (x : N ⊗[R] M) : (linear_map.id : N →ₗ[R] N).rtensor M x = x := by { rw [rtensor_id, id_coe, id.def], } variables {N} @[simp] lemma ltensor_comp_rtensor (f : M →ₗ[R] P) (g : N →ₗ[R] Q) : (g.ltensor P).comp (f.rtensor N) = map f g := by simp only [ltensor, rtensor, ← map_comp, id_comp, comp_id] @[simp] lemma rtensor_comp_ltensor (f : M →ₗ[R] P) (g : N →ₗ[R] Q) : (f.rtensor Q).comp (g.ltensor M) = map f g := by simp only [ltensor, rtensor, ← map_comp, id_comp, comp_id] @[simp] lemma map_comp_rtensor (f : M →ₗ[R] P) (g : N →ₗ[R] Q) (f' : S →ₗ[R] M) : (map f g).comp (f'.rtensor _) = map (f.comp f') g := by simp only [ltensor, rtensor, ← map_comp, id_comp, comp_id] @[simp] lemma map_comp_ltensor (f : M →ₗ[R] P) (g : N →ₗ[R] Q) (g' : S →ₗ[R] N) : (map f g).comp (g'.ltensor _) = map f (g.comp g') := by simp only [ltensor, rtensor, ← map_comp, id_comp, comp_id] @[simp] lemma rtensor_comp_map (f' : P →ₗ[R] S) (f : M →ₗ[R] P) (g : N →ₗ[R] Q) : (f'.rtensor _).comp (map f g) = map (f'.comp f) g := by simp only [ltensor, rtensor, ← map_comp, id_comp, comp_id] @[simp] lemma ltensor_comp_map (g' : Q →ₗ[R] S) (f : M →ₗ[R] P) (g : N →ₗ[R] Q) : (g'.ltensor _).comp (map f g) = map f (g'.comp g) := by simp only [ltensor, rtensor, ← map_comp, id_comp, comp_id] variables {M} @[simp] lemma rtensor_pow (f : M →ₗ[R] M) (n : ℕ) : (f.rtensor N)^n = (f^n).rtensor N := by { have h := tensor_product.map_pow f (id : N →ₗ[R] N) n, rwa id_pow at h, } @[simp] lemma ltensor_pow (f : N →ₗ[R] N) (n : ℕ) : (f.ltensor M)^n = (f^n).ltensor M := by { have h := tensor_product.map_pow (id : M →ₗ[R] M) f n, rwa id_pow at h, } end linear_map end semiring section ring variables {R : Type*} [comm_semiring R] variables {M : Type*} {N : Type*} {P : Type*} {Q : Type*} {S : Type*} variables [add_comm_group M] [add_comm_group N] [add_comm_group P] [add_comm_group Q] [add_comm_group S] variables [module R M] [module R N] [module R P] [module R Q] [module R S] namespace tensor_product open_locale tensor_product open linear_map variables (R) /-- Auxiliary function to defining negation multiplication on tensor product. -/ def neg.aux : free_add_monoid (M × N) →+ M ⊗[R] N := free_add_monoid.lift $ λ p : M × N, (-p.1) ⊗ₜ p.2 variables {R} theorem neg.aux_of (m : M) (n : N) : neg.aux R (free_add_monoid.of (m, n)) = (-m) ⊗ₜ[R] n := rfl instance : has_neg (M ⊗[R] N) := { neg := (add_con_gen (tensor_product.eqv R M N)).lift (neg.aux R) $ add_con.add_con_gen_le $ λ x y hxy, match x, y, hxy with | _, _, (eqv.of_zero_left n) := (add_con.ker_rel _).2 $ by simp_rw [add_monoid_hom.map_zero, neg.aux_of, neg_zero, zero_tmul] | _, _, (eqv.of_zero_right m) := (add_con.ker_rel _).2 $ by simp_rw [add_monoid_hom.map_zero, neg.aux_of, tmul_zero] | _, _, (eqv.of_add_left m₁ m₂ n) := (add_con.ker_rel _).2 $ by simp_rw [add_monoid_hom.map_add, neg.aux_of, neg_add, add_tmul] | _, _, (eqv.of_add_right m n₁ n₂) := (add_con.ker_rel _).2 $ by simp_rw [add_monoid_hom.map_add, neg.aux_of, tmul_add] | _, _, (eqv.of_smul s m n) := (add_con.ker_rel _).2 $ by simp_rw [neg.aux_of, tmul_smul s, smul_tmul', smul_neg] | _, _, (eqv.add_comm x y) := (add_con.ker_rel _).2 $ by simp_rw [add_monoid_hom.map_add, add_comm] end } protected theorem add_left_neg (x : M ⊗[R] N) : -x + x = 0 := tensor_product.induction_on x (by { rw [add_zero], apply (neg.aux R).map_zero, }) (λ x y, by { convert (add_tmul (-x) x y).symm, rw [add_left_neg, zero_tmul], }) (λ x y hx hy, by { unfold has_neg.neg sub_neg_monoid.neg, rw add_monoid_hom.map_add, ac_change (-x + x) + (-y + y) = 0, rw [hx, hy, add_zero], }) instance : add_comm_group (M ⊗[R] N) := { neg := has_neg.neg, sub := _, sub_eq_add_neg := λ _ _, rfl, add_left_neg := λ x, by exact tensor_product.add_left_neg x, zsmul := λ n v, n • v, zsmul_zero' := by simp [tensor_product.zero_smul], zsmul_succ' := by simp [nat.succ_eq_one_add, tensor_product.one_smul, tensor_product.add_smul], zsmul_neg' := λ n x, begin change (- n.succ : ℤ) • x = - (((n : ℤ) + 1) • x), rw [← zero_add (-↑(n.succ) • x), ← tensor_product.add_left_neg (↑(n.succ) • x), add_assoc, ← add_smul, ← sub_eq_add_neg, sub_self, zero_smul, add_zero], refl, end, .. tensor_product.add_comm_monoid } lemma neg_tmul (m : M) (n : N) : (-m) ⊗ₜ n = -(m ⊗ₜ[R] n) := rfl lemma tmul_neg (m : M) (n : N) : m ⊗ₜ (-n) = -(m ⊗ₜ[R] n) := (mk R M N _).map_neg _ lemma tmul_sub (m : M) (n₁ n₂ : N) : m ⊗ₜ (n₁ - n₂) = (m ⊗ₜ[R] n₁) - (m ⊗ₜ[R] n₂) := (mk R M N _).map_sub _ _ lemma sub_tmul (m₁ m₂ : M) (n : N) : (m₁ - m₂) ⊗ₜ n = (m₁ ⊗ₜ[R] n) - (m₂ ⊗ₜ[R] n) := (mk R M N).map_sub₂ _ _ _ /-- While the tensor product will automatically inherit a ℤ-module structure from `add_comm_group.int_module`, that structure won't be compatible with lemmas like `tmul_smul` unless we use a `ℤ-module` instance provided by `tensor_product.left_module`. When `R` is a `ring` we get the required `tensor_product.compatible_smul` instance through `is_scalar_tower`, but when it is only a `semiring` we need to build it from scratch. The instance diamond in `compatible_smul` doesn't matter because it's in `Prop`. -/ instance compatible_smul.int : compatible_smul R ℤ M N := ⟨λ r m n, int.induction_on r (by simp) (λ r ih, by simpa [add_smul, tmul_add, add_tmul] using ih) (λ r ih, by simpa [sub_smul, tmul_sub, sub_tmul] using ih)⟩ instance compatible_smul.unit {S} [monoid S] [distrib_mul_action S M] [distrib_mul_action S N] [compatible_smul R S M N] : compatible_smul R Sˣ M N := ⟨λ s m n, (compatible_smul.smul_tmul (s : S) m n : _)⟩ end tensor_product namespace linear_map @[simp] lemma ltensor_sub (f g : N →ₗ[R] P) : (f - g).ltensor M = f.ltensor M - g.ltensor M := by simp only [← coe_ltensor_hom, map_sub] @[simp] lemma rtensor_sub (f g : N →ₗ[R] P) : (f - g).rtensor M = f.rtensor M - g.rtensor M := by simp only [← coe_rtensor_hom, map_sub] @[simp] lemma ltensor_neg (f : N →ₗ[R] P) : (-f).ltensor M = -(f.ltensor M) := by simp only [← coe_ltensor_hom, map_neg] @[simp] lemma rtensor_neg (f : N →ₗ[R] P) : (-f).rtensor M = -(f.rtensor M) := by simp only [← coe_rtensor_hom, map_neg] end linear_map end ring
add58e69abe389dfdf32cbf0e39ddd0922a58cd9
9be442d9ec2fcf442516ed6e9e1660aa9071b7bd
/tests/lean/linterSuspiciousUnexpanderPatterns.lean
3dc3961b94ed681009c6213ba239173192bb7fce
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
EdAyers/lean4
57ac632d6b0789cb91fab2170e8c9e40441221bd
37ba0df5841bde51dbc2329da81ac23d4f6a4de4
refs/heads/master
1,676,463,245,298
1,660,619,433,000
1,660,619,433,000
183,433,437
1
0
Apache-2.0
1,657,612,672,000
1,556,196,574,000
Lean
UTF-8
Lean
false
false
376
lean
import Lean set_option linter.suspiciousUnexpanderPatterns true @[appUnexpander List.nil] def unexpandListNilBad : Lean.PrettyPrinter.Unexpander | `(List.nil) => `([]) | _ => throw () /--hey-/ @[appUnexpander List.cons] private def unexpandListConsBad : Lean.PrettyPrinter.Unexpander | `(List.cons $x []) => `([$x]) | _ => throw ()
e7f2c8068b1980916e6b0920c5382c4d3650ea1c
d5bef83c55d40cb88f9a01b755c882a93348a847
/library/init/data/fin/basic.lean
148c96e66df3b897dc62ee23c5e9fe3632cf8a59
[ "Apache-2.0" ]
permissive
urkud/lean
587d78216e1f0c7f651566e9e92cf8ade285d58d
3526539070ea6268df5dd373deeb3ac8b9621952
refs/heads/master
1,660,171,634,921
1,657,873,466,000
1,657,873,466,000
249,789,456
0
0
Apache-2.0
1,585,075,263,000
1,585,075,263,000
null
UTF-8
Lean
false
false
1,534
lean
/- Copyright (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura -/ prelude import init.data.nat.basic open nat /-- `fin n` is the subtype of `ℕ` consisting of natural numbers strictly smaller than `n`. -/ def fin (n : ℕ) := {i : ℕ // i < n} namespace fin /-- Backwards-compatible constructor for `fin n`. -/ def mk {n : ℕ} (i) (h) : fin n := ⟨i, h⟩ protected def lt {n} (a b : fin n) : Prop := a.val < b.val protected def le {n} (a b : fin n) : Prop := a.val ≤ b.val instance {n} : has_lt (fin n) := ⟨fin.lt⟩ instance {n} : has_le (fin n) := ⟨fin.le⟩ instance decidable_lt {n} (a b : fin n) : decidable (a < b) := nat.decidable_lt _ _ instance decidable_le {n} (a b : fin n) : decidable (a ≤ b) := nat.decidable_le _ _ def {u} elim0 {α : fin 0 → Sort u} : Π (x : fin 0), α x | ⟨n, h⟩ := absurd h n.not_lt_zero variable {n : nat} lemma eq_of_veq : ∀ {i j : fin n}, i.val = j.val → i = j | ⟨iv, ilt₁⟩ ⟨.(iv), ilt₂⟩ rfl := rfl lemma veq_of_eq : ∀ {i j : fin n}, i = j → i.val = j.val | ⟨iv, ilt⟩ .(_) rfl := rfl lemma ne_of_vne {i j : fin n} (h : i.val ≠ j.val) : i ≠ j := λ h', absurd (veq_of_eq h') h lemma vne_of_ne {i j : fin n} (h : i ≠ j) : i.val ≠ j.val := λ h', absurd (eq_of_veq h') h end fin open fin instance (n : nat) : decidable_eq (fin n) := λ i j, decidable_of_decidable_of_iff (nat.decidable_eq i.val j.val) ⟨eq_of_veq, veq_of_eq⟩
c5e95b049e426d47581b15acbc81863d535ef554
968e2f50b755d3048175f176376eff7139e9df70
/examples/pred_logic/unnamed_610.lean
cc56303d668cddaed997bd9a0b3781acb4a978a4
[]
no_license
gihanmarasingha/mth1001_sphinx
190a003269ba5e54717b448302a27ca26e31d491
05126586cbf5786e521be1ea2ef5b4ba3c44e74a
refs/heads/master
1,672,913,933,677
1,604,516,583,000
1,604,516,583,000
309,245,750
1
0
null
null
null
null
UTF-8
Lean
false
false
723
lean
import tactic.interactive variables (U : Type*) (S T : U → Prop) -- BEGIN example (h₁ : ∃ x, S x ∧ T x) : ∃ y, S y := begin have h₂ : ∀ y, S y ∧ T y → ∃ y, S y, -- We'll show `h₂ : ∀ y, S y ∧ T y → ∃ y, S y`. { assume u : U, -- Assume `u : U`. It suffices to prove `S u ∧ T u → ∃ y, S y`. assume k₁ : S u ∧ T u, -- Assume `S u ∧ T u`. It suffices to prove `∃ y, S y`. have h₃ : S u, from k₁.left, -- We have `h₃ : S u` by left `∧` elim. on `k₁`, show ∃ y, S y, from exists.intro u h₃, }, -- We show `∃ y, S y` by exists intro. on `u` and `h₃`. exact exists.elim h₁ h₂, -- The result follows by exists elim. on `h₁` and `h₂`. end -- END
ae9760a984664378d42dd9d48c9abe86e3acfea8
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/category_theory/idempotents/functor_categories.lean
3df7fa5b83120d52b9a50f2b3835493484637635
[ "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
5,667
lean
/- Copyright (c) 2022 Joël Riou. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Joël Riou -/ import category_theory.idempotents.karoubi /-! # Idempotent completeness and functor categories > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. In this file we define an instance `functor_category_is_idempotent_complete` expressing that a functor category `J ⥤ C` is idempotent complete when the target category `C` is. We also provide a fully faithful functor `karoubi_functor_category_embedding : karoubi (J ⥤ C)) : J ⥤ karoubi C` for all categories `J` and `C`. -/ open category_theory open category_theory.category open category_theory.idempotents.karoubi open category_theory.limits namespace category_theory namespace idempotents variables {J C : Type*} [category J] [category C] (P Q : karoubi (J ⥤ C)) (f : P ⟶ Q) (X : J) @[simp, reassoc] lemma app_idem : P.p.app X ≫ P.p.app X = P.p.app X := congr_app P.idem X variables {P Q} @[simp, reassoc] lemma app_p_comp : P.p.app X ≫ f.f.app X = f.f.app X := congr_app (p_comp f) X @[simp, reassoc] lemma app_comp_p : f.f.app X ≫ Q.p.app X = f.f.app X := congr_app (comp_p f) X @[reassoc] lemma app_p_comm : P.p.app X ≫ f.f.app X = f.f.app X ≫ Q.p.app X := congr_app (p_comm f) X variables (J C) instance functor_category_is_idempotent_complete [is_idempotent_complete C] : is_idempotent_complete (J ⥤ C) := begin refine ⟨_⟩, intros F p hp, have hC := (is_idempotent_complete_iff_has_equalizer_of_id_and_idempotent C).mp infer_instance, haveI : ∀ (j : J), has_equalizer (𝟙 _) (p.app j) := λ j, hC _ _ (congr_app hp j), /- We construct the direct factor `Y` associated to `p : F ⟶ F` by computing the equalizer of the identity and `p.app j` on each object `(j : J)`. -/ let Y : J ⥤ C := { obj := λ j, limits.equalizer (𝟙 _) (p.app j), map := λ j j' φ, equalizer.lift (limits.equalizer.ι (𝟙 _) (p.app j) ≫ F.map φ) (by rw [comp_id, assoc, p.naturality φ, ← assoc, ← limits.equalizer.condition, comp_id]), map_id' := λ j, by { ext, simp only [comp_id, functor.map_id, equalizer.lift_ι, id_comp], }, map_comp' := λ j j' j'' φ φ', begin ext, simp only [assoc, functor.map_comp, equalizer.lift_ι, equalizer.lift_ι_assoc], end }, let i : Y ⟶ F := { app := λ j, equalizer.ι _ _, naturality' := λ j j' φ, by rw [equalizer.lift_ι], }, let e : F ⟶ Y := { app := λ j, equalizer.lift (p.app j) (by { rw comp_id, exact (congr_app hp j).symm, }), naturality' := λ j j' φ, begin ext, simp only [assoc, equalizer.lift_ι, nat_trans.naturality, equalizer.lift_ι_assoc], end }, use [Y, i, e], split; ext j, { simp only [nat_trans.comp_app, assoc, equalizer.lift_ι, nat_trans.id_app, id_comp, ← equalizer.condition, comp_id], }, { simp only [nat_trans.comp_app, equalizer.lift_ι], }, end namespace karoubi_functor_category_embedding variables {J C} /-- On objects, the functor which sends a formal direct factor `P` of a functor `F : J ⥤ C` to the functor `J ⥤ karoubi C` which sends `(j : J)` to the corresponding direct factor of `F.obj j`. -/ @[simps] def obj (P : karoubi (J ⥤ C)) : J ⥤ karoubi C := { obj := λ j, ⟨P.X.obj j, P.p.app j, congr_app P.idem j⟩, map := λ j j' φ, { f := P.p.app j ≫ P.X.map φ, comm := begin simp only [nat_trans.naturality, assoc], have h := congr_app P.idem j, rw [nat_trans.comp_app] at h, slice_rhs 1 3 { erw [h, h], }, end }, } /-- Tautological action on maps of the functor `karoubi (J ⥤ C) ⥤ (J ⥤ karoubi C)`. -/ @[simps] def map {P Q : karoubi (J ⥤ C)} (f : P ⟶ Q) : obj P ⟶ obj Q := { app := λ j, ⟨f.f.app j, congr_app f.comm j⟩, } end karoubi_functor_category_embedding variables (J C) /-- The tautological fully faithful functor `karoubi (J ⥤ C) ⥤ (J ⥤ karoubi C)`. -/ @[simps] def karoubi_functor_category_embedding : karoubi (J ⥤ C) ⥤ (J ⥤ karoubi C) := { obj := karoubi_functor_category_embedding.obj, map := λ P Q, karoubi_functor_category_embedding.map, } instance : full (karoubi_functor_category_embedding J C) := { preimage := λ P Q f, { f := { app := λ j, (f.app j).f, naturality' := λ j j' φ, begin rw ← karoubi.comp_p_assoc, have h := hom_ext.mp (f.naturality φ), simp only [comp_f] at h, dsimp [karoubi_functor_category_embedding] at h, erw [← h, assoc, ← P.p.naturality_assoc φ, p_comp (f.app j')], end }, comm := by { ext j, exact (f.app j).comm, } }, witness' := λ P Q f, by { ext j, refl, }, } instance : faithful (karoubi_functor_category_embedding J C) := { map_injective' := λ P Q f f' h, by { ext j, exact hom_ext.mp (congr_app h j), }, } /-- The composition of `(J ⥤ C) ⥤ karoubi (J ⥤ C)` and `karoubi (J ⥤ C) ⥤ (J ⥤ karoubi C)` equals the functor `(J ⥤ C) ⥤ (J ⥤ karoubi C)` given by the composition with `to_karoubi C : C ⥤ karoubi C`. -/ lemma to_karoubi_comp_karoubi_functor_category_embedding : (to_karoubi _) ⋙ karoubi_functor_category_embedding J C = (whiskering_right J _ _).obj (to_karoubi C) := begin apply functor.ext, { intros X Y f, ext j, dsimp [to_karoubi], simp only [eq_to_hom_app, eq_to_hom_refl, id_comp], erw [comp_id], }, { intro X, apply functor.ext, { intros j j' φ, ext, dsimp, simpa only [comp_id, id_comp], }, { intro j, refl, }, } end end idempotents end category_theory
d32491c1c4ca3a501f23a0f87bdfb56ee5aa6fad
22e97a5d648fc451e25a06c668dc03ac7ed7bc25
/src/algebra/classical_lie_algebras.lean
9bdd8a6480959f28b61cf71387d8981ae07adc67
[ "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
2,970
lean
/- Copyright (c) 2020 Oliver Nash. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Oliver Nash -/ import algebra.lie_algebra import linear_algebra.matrix /-! # Classical Lie algebras This file is the place to find definitions and basic properties of the classical Lie algebras: * Aₙ sl(n+1) * Bₙ so(2n+1) * Cₙ sp(2n) * Dₙ so(2n) As of April 2020, the definition of Aₙ is in place while the others still need to be provided. ## Tags classical lie algebra, special linear -/ universes u₁ u₂ namespace lie_algebra open_locale matrix variables (n : Type u₁) (R : Type u₂) variables [fintype n] [decidable_eq n] [nonzero_comm_ring R] local attribute [instance] matrix.lie_ring local attribute [instance] matrix.lie_algebra @[simp] lemma matrix_trace_commutator_zero (X Y : matrix n n R) : matrix.trace n R R ⁅X, Y⁆ = 0 := begin change matrix.trace n R R (X ⬝ Y - Y ⬝ X) = 0, simp only [matrix.trace_mul_comm, linear_map.map_sub, sub_self], end namespace special_linear /-- The special linear Lie algebra: square matrices of trace zero. -/ def sl : lie_subalgebra R (matrix n n R) := { lie_mem := λ X Y _ _, linear_map.mem_ker.2 $ matrix_trace_commutator_zero _ _ _ _, to_submodule := linear_map.ker (matrix.trace n R R) } lemma sl_bracket (A B : sl n R) : ⁅A, B⁆.val = A.val ⬝ B.val - B.val ⬝ A.val := rfl section elementary_basis variables {n} (i j : n) /-- It is useful to define these matrices for explicit calculations in sl n R. -/ abbreviation E : matrix n n R := λ i' j', if i = i' ∧ j = j' then 1 else 0 @[simp] lemma E_apply_one : E R i j i j = 1 := if_pos (and.intro rfl rfl) @[simp] lemma E_apply_zero (i' j' : n) (h : ¬(i = i' ∧ j = j')) : E R i j i' j' = 0 := if_neg h @[simp] lemma E_diag_zero (h : j ≠ i) : matrix.diag n R R (E R i j) = 0 := begin ext k, rw matrix.diag_apply, suffices : ¬(i = k ∧ j = k), by exact if_neg this, rintros ⟨e₁, e₂⟩, apply h, subst e₁, exact e₂, end lemma E_trace_zero (h : j ≠ i) : matrix.trace n R R (E R i j) = 0 := by simp [h] /-- When j ≠ i, the elementary matrices are elements of sl n R, in fact they are part of a natural basis of sl n R. -/ def Eb (h : j ≠ i) : sl n R := ⟨E R i j, by { change E R i j ∈ linear_map.ker (matrix.trace n R R), simp [E_trace_zero R i j h], }⟩ @[simp] lemma Eb_val (h : j ≠ i) : (Eb R i j h).val = E R i j := rfl end elementary_basis lemma sl_non_abelian (h : 1 < fintype.card n) : ¬lie_algebra.is_abelian ↥(sl n R) := begin rcases fintype.exists_pair_of_one_lt_card h with ⟨i, j, hij⟩, let A := Eb R i j hij, let B := Eb R j i hij.symm, intros c, have c' : A.val ⬝ B.val = B.val ⬝ A.val := by { rw [←sub_eq_zero, ←sl_bracket, c.abelian], refl, }, have : 1 = 0 := by simpa [matrix.mul_val, hij] using (congr_fun (congr_fun c' i) i), exact one_ne_zero this, end end special_linear end lie_algebra
7a918ef677747cf2c4037c25545e867d7ad35efb
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/tactic/dependencies.lean
cb8b07db811617d4e726bf9dd05ad035561efe7e
[ "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
30,414
lean
/- Copyright (c) 2020 Jannis Limperg. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jannis Limperg -/ import tactic.core /-! # Tactics About Dependencies This module provides tactics to compute dependencies and reverse dependencies of hypotheses. An expression `e` depends on a hypothesis `h` if `e` would not be valid if `h` were removed from the context. For example, the expression `e := x > 0` depends on `x`. We say that `x` is a dependency of `e` and that `e` is a reverse dependency of `x`. It is sometimes useful to consider *inclusive* dependency: `e` inclusively depends on `h` iff `e` depends on `h` or `e = h` (so inclusive dependency is the reflexive closure of regular dependency). Note that the standard library does not use quite the same terminology: * `kdependencies`/`kdeps` from the standard library compute reverse dependencies, not dependencies. * `kdepends_on` and functions derived from it ignore local definitions and therefore compute a weaker dependency relation (see next section). ## Local Definitions Determining dependencies of hypotheses is usually straightforward: a hypothesis `r : R` depends on another hypothesis `d : D` if `d` occurs in `R`. The implementation is more involved, however, in the presence of local definitions. Consider this context: ```lean n m : ℕ k : ℕ := m o : ℕ := k h : o > 0 ``` `h` depends on `o`, `k` and `m`, but only the dependency on `o` is syntactically obvious. `kdepends_on` ignores this complication and claims that `h` does not depend on `k` or `m`. We do not follow this example but process local definitions properly. This means that if the context contains a local definition, we need to compute the syntactic dependencies of `h`, then their dependencies, and so on. ## Direct Dependencies If you want to ignore local definitions while computing dependencies, this module also provides tactics to find the *direct* dependencies of a hypothesis. These are the hypotheses that syntactically appear in the hypothesis's type (or value, if the hypothesis is a local definition). -/ open native open expr_set (local_set_to_name_set) open name_set (local_list_to_name_set) namespace tactic /-! ### Direct Dependencies -/ /-! #### Checking whether hypotheses directly depend on each other -/ /-- `type_has_local_in_name_set h ns` returns true iff the type of `h` contains a local constant whose unique name appears in `ns`. -/ meta def type_has_local_in_name_set (h : expr) (ns : name_set) : tactic bool := do h_type ← infer_type h, pure $ h_type.has_local_in ns /-- `type_has_local_in_set h hs` returns true iff the type of `h` contains any of the local constants `hs`. -/ meta def type_has_local_in_set (h : expr) (hs : expr_set) : tactic bool := type_has_local_in_name_set h $ local_set_to_name_set hs /-- `type_has_local_in h hs` returns true iff the type of `h` contains any of the local constants `hs`. -/ meta def type_has_local_in (h : expr) (hs : list expr) : tactic bool := type_has_local_in_name_set h $ local_list_to_name_set hs /-- `local_def_value_has_local_in_name_set h ns` returns true iff `h` is a local definition whose value contains a local constant whose unique name appears in `ns`. -/ meta def local_def_value_has_local_in_name_set (h : expr) (ns : name_set) : tactic bool := do (some h_val) ← try_core $ local_def_value h | pure ff, pure $ h_val.has_local_in ns /-- `local_def_value_has_local_in_set h hs` returns true iff `h` is a local definition whose value contains any of the local constants `hs`. -/ meta def local_def_value_has_local_in_set (h : expr) (hs : expr_set) : tactic bool := local_def_value_has_local_in_name_set h $ local_set_to_name_set hs /-- `local_def_value_has_local_in h hs` returns true iff `h` is a local definition whose value contains any of the local constants `hs`. -/ meta def local_def_value_has_local_in (h : expr) (hs : list expr) : tactic bool := local_def_value_has_local_in_name_set h $ local_list_to_name_set hs /-- `hyp_directly_depends_on_local_name_set h ns` is true iff the hypothesis `h` directly depends on a hypothesis whose unique name appears in `ns`. -/ meta def hyp_directly_depends_on_local_name_set (h : expr) (ns : name_set) : tactic bool := list.mbor [ type_has_local_in_name_set h ns, local_def_value_has_local_in_name_set h ns ] /-- `hyp_directly_depends_on_local_set h hs` is true iff the hypothesis `h` directly depends on any of the hypotheses `hs`. -/ meta def hyp_directly_depends_on_local_set (h : expr) (hs : expr_set) : tactic bool := hyp_directly_depends_on_local_name_set h $ local_set_to_name_set hs /-- `hyp_directly_depends_on_locals h hs` is true iff the hypothesis `h` directly depends on any of the hypotheses `hs`. -/ meta def hyp_directly_depends_on_locals (h : expr) (hs : list expr) : tactic bool := hyp_directly_depends_on_local_name_set h $ local_list_to_name_set hs /-- `hyp_directly_depends_on_local_name_set_inclusive h ns` is true iff the hypothesis `h` directly depends on a hypothesis whose unique name appears in `ns` or `h`'s name appears in `ns`. -/ meta def hyp_directly_depends_on_local_name_set_inclusive (h : expr) (ns : name_set) : tactic bool := list.mbor [ pure $ ns.contains h.local_uniq_name , hyp_directly_depends_on_local_name_set h ns ] /-- `hyp_directly_depends_on_local_set_inclusive h ns` is true iff the hypothesis `h` directly depends on any of the hypotheses `hs` or `h` appears in `hs`. -/ meta def hyp_directly_depends_on_local_set_inclusive (h : expr) (hs : expr_set) : tactic bool := hyp_directly_depends_on_local_name_set_inclusive h $ local_set_to_name_set hs /-- `hyp_directly_depends_on_locals_inclusive h ns` is true iff the hypothesis `h` directly depends on any of the hypotheses `hs` or `h` appears in `hs`. -/ meta def hyp_directly_depends_on_locals_inclusive (h : expr) (hs : list expr) : tactic bool := hyp_directly_depends_on_local_name_set_inclusive h $ local_list_to_name_set hs /-! #### Computing the direct dependencies of a hypothesis -/ /-- `direct_dependency_set_of_hyp h` is the set of hypotheses that the hypothesis `h` directly depends on. These are the hypotheses that appear in `h`'s type or value (if `h` is a local definition). -/ meta def direct_dependency_set_of_hyp (h : expr) : tactic expr_set := do t ← infer_type h, let deps := t.list_local_consts', (some val) ← try_core $ local_def_value h | pure deps, let deps := deps.union val.list_local_consts', pure deps /-- `direct_dependency_name_set_of_hyp h` is the set of unique names of hypotheses that the hypothesis `h` directly depends on. These are the hypotheses that appear in `h`'s type or value (if `h` is a local definition). -/ meta def direct_dependency_name_set_of_hyp (h : expr) : tactic name_set := local_set_to_name_set <$> direct_dependency_set_of_hyp h /-- `direct_dependencies_of_hyp h` is the list of hypotheses that the hypothesis `h` directly depends on. These are the hypotheses that appear in `h`'s type or value (if `h` is a local definition). The dependencies are returned in no particular order. -/ meta def direct_dependencies_of_hyp (h : expr) : tactic (list expr) := rb_set.to_list <$> direct_dependency_set_of_hyp h /-- `direct_dependency_set_of_hyp_inclusive h` is the set of hypotheses that the hypothesis `h` directly depends on, plus `h` itself. -/ meta def direct_dependency_set_of_hyp_inclusive (h : expr) : tactic expr_set := do deps ← direct_dependency_set_of_hyp h, pure $ deps.insert h /-- `direct_dependency_name_set_of_hyp_inclusive h` is the set of unique names of hypotheses that the hypothesis `h` directly depends on, plus `h` itself. -/ meta def direct_dependency_name_set_of_hyp_inclusive (h : expr) : tactic name_set := local_set_to_name_set <$> direct_dependency_set_of_hyp_inclusive h /-- `direct_dependencies_of_hyp_inclusive h` is the list of hypotheses that the hypothesis `h` directly depends on, plus `h` itself. The dependencies are returned in no particular order. -/ meta def direct_dependencies_of_hyp_inclusive (h : expr) : tactic (list expr) := rb_set.to_list <$> direct_dependency_set_of_hyp_inclusive h /-! ### Indirect/Transitive Dependencies -/ /-! #### Checking whether hypotheses depend on each other -/ /-- `hyp_depends_on_local_name_set' cache h ns` is true iff `h` depends on any of the hypotheses whose unique names appear in `ns`. `cache` must be a set of hypotheses known *not* to depend (even indirectly) on any of the `ns`. This is a performance optimisation, so you can give an empty cache. The tactic also returns an expanded cache with hypotheses which the tactic has encountered. You probably want to use `tactic.hyp_depends_on_local_name_set` or `tactic.hyps_depend_on_local_name_set` instead of this tactic. -/ meta def hyp_depends_on_local_name_set' : expr_set → expr → name_set → tactic (bool × expr_set) := λ cache h ns, do ff ← pure $ cache.contains h | pure (ff, cache), direct_deps ← direct_dependency_set_of_hyp h, let has_dep := direct_deps.fold ff (λ d b, b || ns.contains d.local_uniq_name), ff ← pure has_dep | pure (tt, cache), (has_dep, cache) ← direct_deps.mfold (ff, cache) $ λ d ⟨b, cache⟩, if b then pure (tt, cache) else hyp_depends_on_local_name_set' cache d ns, if has_dep then pure (tt, cache) else pure (ff, cache.insert h) /-- `hyp_depends_on_local_name_set h ns` is true iff the hypothesis `h` depends on any of the hypotheses whose unique names appear in `ns`. If you need to check dependencies of multiple hypotheses, use `tactic.hyps_depend_on_local_name_set`. -/ meta def hyp_depends_on_local_name_set (h : expr) (ns : name_set) : tactic bool := do ctx_has_local_def ← context_upto_hyp_has_local_def h, if ctx_has_local_def then prod.fst <$> hyp_depends_on_local_name_set' mk_expr_set h ns else hyp_directly_depends_on_local_name_set h ns /-- `hyp_depends_on_local_set h hs` is true iff the hypothesis `h` depends on any of the hypotheses `hs`. If you need to check dependencies of multiple hypotheses, use `tactic.hyps_depend_on_local_set`. -/ meta def hyp_depends_on_local_set (h : expr) (hs : expr_set) : tactic bool := hyp_depends_on_local_name_set h $ local_set_to_name_set hs /-- `hyp_depends_on_locals h hs` is true iff the hypothesis `h` depends on any of the hypotheses `hs`. If you need to check dependencies of multiple hypotheses, use `tactic.hyps_depend_on_locals`. -/ meta def hyp_depends_on_locals (h : expr) (hs : list expr) : tactic bool := hyp_depends_on_local_name_set h $ local_list_to_name_set hs /-- `hyps_depend_on_local_name_set hs ns` returns, for each `h ∈ hs`, whether `h` depends on a hypothesis whose unique name appears in `ns`. This is the same as (but more efficient than) calling `tactic.hyp_depends_on_local_name_set` for every `h ∈ hs`. -/ meta def hyps_depend_on_local_name_set (hs : list expr) (ns : name_set) : tactic (list bool) := do ctx_has_local ← context_has_local_def, if ctx_has_local then let go : expr → list bool × expr_set → tactic (list bool × expr_set) := λ h ⟨deps, cache⟩, do { (h_dep, cache) ← hyp_depends_on_local_name_set' cache h ns, pure (h_dep :: deps, cache) } in prod.fst <$> hs.mfoldr go ([], mk_expr_map) else hs.mmap $ λ h, hyp_directly_depends_on_local_name_set h ns /-- `hyps_depend_on_local_set hs is` returns, for each `h ∈ hs`, whether `h` depends on any of the hypotheses `is`. This is the same as (but more efficient than) calling `tactic.hyp_depends_on_local_set` for every `h ∈ hs`. -/ meta def hyps_depend_on_local_set (hs : list expr) (is : expr_set) : tactic (list bool) := hyps_depend_on_local_name_set hs $ local_set_to_name_set is /-- `hyps_depend_on_locals hs is` returns, for each `h ∈ hs`, whether `h` depends on any of the hypotheses `is`. This is the same as (but more efficient than) calling `tactic.hyp_depends_on_locals` for every `h ∈ hs`. -/ meta def hyps_depend_on_locals (hs is : list expr) : tactic (list bool) := hyps_depend_on_local_name_set hs $ local_list_to_name_set is /-- `hyp_depends_on_local_name_set_inclusive' cache h ns` is true iff the hypothesis `h` inclusively depends on a hypothesis whose unique name appears in `ns`. `cache` must be a set of hypotheses known *not* to depend (even indirectly) on any of the `ns`. This is a performance optimisation, so you can give an empty cache. The tactic also returns an expanded cache with hypotheses which the tactic has encountered. Note that the cache records exclusive, not inclusive dependencies. You probably want to use `tactic.hyp_depends_on_local_name_set_inclusive` or `tactic.hyps_depend_on_local_name_set_inclusive` instead of this tactic. -/ meta def hyp_depends_on_local_name_set_inclusive' (cache : expr_set) (h : expr) (ns : name_set) : tactic (bool × expr_set) := if ns.contains h.local_uniq_name then pure (tt, cache) else hyp_depends_on_local_name_set' cache h ns /-- `hyp_depends_on_local_name_set_inclusive h ns` is true iff the hypothesis `h` inclusively depends on any of the hypotheses whose unique names appear in `ns`. If you need to check the dependencies of multiple hypotheses, use `tactic.hyps_depend_on_local_name_set_inclusive`. -/ meta def hyp_depends_on_local_name_set_inclusive (h : expr) (ns : name_set) : tactic bool := list.mbor [ pure $ ns.contains h.local_uniq_name, hyp_depends_on_local_name_set h ns ] /-- `hyp_depends_on_local_set_inclusive h hs` is true iff the hypothesis `h` inclusively depends on any of the hypotheses `hs`. If you need to check dependencies of multiple hypotheses, use `tactic.hyps_depend_on_local_set_inclusive`. -/ meta def hyp_depends_on_local_set_inclusive (h : expr) (hs : expr_set) : tactic bool := hyp_depends_on_local_name_set_inclusive h $ local_set_to_name_set hs /-- `hyp_depends_on_locals_inclusive h hs` is true iff the hypothesis `h` inclusively depends on any of the hypotheses `hs`. If you need to check dependencies of multiple hypotheses, use `tactic.hyps_depend_on_locals_inclusive`. -/ meta def hyp_depends_on_locals_inclusive (h : expr) (hs : list expr) : tactic bool := hyp_depends_on_local_name_set_inclusive h $ local_list_to_name_set hs /-- `hyps_depend_on_local_name_set_inclusive hs ns` returns, for each `h ∈ hs`, whether `h` inclusively depends on a hypothesis whose unique name appears in `ns`. This is the same as (but more efficient than) calling `tactic.hyp_depends_on_local_name_set_inclusive` for every `h ∈ hs`. -/ meta def hyps_depend_on_local_name_set_inclusive (hs : list expr) (ns : name_set) : tactic (list bool) := do ctx_has_local ← context_has_local_def, if ctx_has_local then let go : expr → list bool × expr_set → tactic (list bool × expr_set) := λ h ⟨deps, cache⟩, do { (h_dep, cache) ← hyp_depends_on_local_name_set_inclusive' cache h ns, pure (h_dep :: deps, cache) } in prod.fst <$> hs.mfoldr go ([], mk_expr_map) else hs.mmap $ λ h, hyp_directly_depends_on_local_name_set_inclusive h ns /-- `hyps_depend_on_local_set_inclusive hs is` returns, for each `h ∈ hs`, whether `h` depends inclusively on any of the hypotheses `is`. This is the same as (but more efficient than) calling `tactic.hyp_depends_on_local_set_inclusive` for every `h ∈ hs`. -/ meta def hyps_depend_on_local_set_inclusive (hs : list expr) (is : expr_set) : tactic (list bool) := hyps_depend_on_local_name_set_inclusive hs $ local_set_to_name_set is /-- `hyps_depend_on_locals_inclusive hs is` returns, for each `h ∈ hs`, whether `h` depends inclusively on any of the hypotheses `is`. This is the same as (but more efficient than) calling `tactic.hyp_depends_on_locals_inclusive` for every `h ∈ hs`. -/ meta def hyps_depend_on_locals_inclusive (hs is : list expr) : tactic (list bool) := hyps_depend_on_local_name_set_inclusive hs $ local_list_to_name_set is /-! #### Computing the dependencies of a hypothesis -/ /-- `dependency_set_of_hyp' cache h` is the set of dependencies of the hypothesis `h`. `cache` is a map from hypotheses to all their dependencies (including indirect dependencies). This is a performance optimisation, so you can give an empty cache. The tactic also returns an expanded cache with hypotheses which the tactic has encountered. You probably want to use `tactic.dependency_set_of_hyp` or `tactic.dependency_sets_of_hyps` instead of this tactic. -/ meta def dependency_set_of_hyp' : expr_map expr_set → expr → tactic (expr_set × expr_map expr_set) := λ cache h, do match cache.find h with | some deps := pure (deps, cache) | none := do direct_deps ← direct_dependency_set_of_hyp h, (deps, cache) ← direct_deps.mfold (direct_deps, cache) $ λ h' ⟨deps, cache⟩, do { (deps', cache) ← dependency_set_of_hyp' cache h', pure (deps.union deps', cache) }, pure (deps, cache.insert h deps) end /-- `dependency_set_of_hyp h` is the set of dependencies of the hypothesis `h`. If you need the dependencies of multiple hypotheses, use `tactic.dependency_sets_of_hyps`. -/ meta def dependency_set_of_hyp (h : expr) : tactic expr_set := do ctx_has_local ← context_upto_hyp_has_local_def h, if ctx_has_local then prod.fst <$> dependency_set_of_hyp' mk_expr_map h else direct_dependency_set_of_hyp h /-- `dependency_name_set_of_hyp h` is the set of unique names of the dependencies of the hypothesis `h`. If you need the dependencies of multiple hypotheses, use `tactic.dependency_name_sets_of_hyps`. -/ meta def dependency_name_set_of_hyp (h : expr) : tactic name_set := local_set_to_name_set <$> dependency_set_of_hyp h /-- `dependencies_of_hyp h` is the list of dependencies of the hypothesis `h`. The dependencies are returned in no particular order. If you need the dependencies of multiple hypotheses, use `tactic.dependencies_of_hyps`. -/ meta def dependencies_of_hyp (h : expr) : tactic (list expr) := rb_set.to_list <$> dependency_set_of_hyp h /-- `dependency_sets_of_hyps hs` returns, for each `h ∈ hs`, the set of dependencies of `h`. This is the same as (but more performant than) using `tactic.dependency_set_of_hyp` on every `h ∈ hs`. -/ meta def dependency_sets_of_hyps (hs : list expr) : tactic (list expr_set) := do ctx_has_def ← context_has_local_def, if ctx_has_def then let go : expr → list expr_set × expr_map expr_set → tactic (list expr_set × expr_map expr_set) := do λ h ⟨deps, cache⟩, do { (h_deps, cache) ← dependency_set_of_hyp' cache h, pure (h_deps :: deps, cache) } in prod.fst <$> hs.mfoldr go ([], mk_expr_map) else hs.mmap direct_dependency_set_of_hyp /-- `dependency_name_sets_of_hyps hs` returns, for each `h ∈ hs`, the set of unique names of the dependencies of `h`. This is the same as (but more performant than) using `tactic.dependency_name_set_of_hyp` on every `h ∈ hs`. -/ meta def dependency_name_sets_of_hyps (hs : list expr) : tactic (list name_set) := list.map local_set_to_name_set <$> dependency_sets_of_hyps hs /-- `dependencies_of_hyps hs` returns, for each `h ∈ hs`, the dependencies of `h`. The dependencies appear in no particular order in the returned lists. This is the same as (but more performant than) using `tactic.dependencies_of_hyp` on every `h ∈ hs`. -/ meta def dependencies_of_hyps (hs : list expr) : tactic (list (list expr)) := list.map rb_set.to_list <$> dependency_sets_of_hyps hs /-- `dependency_set_of_hyp_inclusive' cache h` is the set of dependencies of the hypothesis `h`, plus `h` itself. `cache` is a map from hypotheses to all their dependencies (including indirect dependencies). This is a performance optimisation, so you can give an empty cache. The tactic also returns an expanded cache with hypotheses which the tactic has encountered. Note that the cache records exclusive, not inclusive dependencies. You probably want to use `tactic.dependency_set_of_hyp_inclusive` or `tactic.dependency_sets_of_hyps_inclusive` instead of this tactic. -/ meta def dependency_set_of_hyp_inclusive' (cache : expr_map expr_set) (h : expr) : tactic (expr_set × expr_map expr_set) := do (deps, cache) ← dependency_set_of_hyp' cache h, pure (deps.insert h, cache) /-- `dependency_set_of_hyp_inclusive h` is the set of dependencies of the hypothesis `h`, plus `h` itself. If you need the dependencies of multiple hypotheses, use `tactic.dependency_sets_of_hyps_inclusive`. -/ meta def dependency_set_of_hyp_inclusive (h : expr) : tactic expr_set := do deps ← dependency_set_of_hyp h, pure $ deps.insert h /-- `dependency_name_set_of_hyp_inclusive h` is the set of unique names of the dependencies of the hypothesis `h`, plus the unique name of `h` itself. If you need the dependencies of multiple hypotheses, use `tactic.dependency_name_sets_of_hyps_inclusive`. -/ meta def dependency_name_set_of_hyp_inclusive (h : expr) : tactic name_set := local_set_to_name_set <$> dependency_set_of_hyp_inclusive h /-- `dependencies_of_hyp_inclusive h` is the list of dependencies of the hypothesis `h`, plus `h` itself. The dependencies are returned in no particular order. If you need the dependencies of multiple hypotheses, use `tactic.dependencies_of_hyps_inclusive`. -/ meta def dependencies_of_hyp_inclusive (h : expr) : tactic (list expr) := rb_set.to_list <$> dependency_set_of_hyp_inclusive h /-- `dependency_sets_of_hyps_inclusive hs` returns, for each `h ∈ hs`, the dependencies of `h`, plus `h` itself. This is the same as (but more performant than) using `tactic.dependency_set_of_hyp_inclusive` on every `h ∈ hs`. -/ meta def dependency_sets_of_hyps_inclusive (hs : list expr) : tactic (list expr_set) := do ctx_has_def ← context_has_local_def, if ctx_has_def then let go : expr → list expr_set × expr_map expr_set → tactic (list expr_set × expr_map expr_set) := λ h ⟨deps, cache⟩, do { (h_deps, cache) ← dependency_set_of_hyp_inclusive' cache h, pure (h_deps :: deps, cache) } in prod.fst <$> hs.mfoldr go ([], mk_expr_map) else hs.mmap direct_dependency_set_of_hyp_inclusive /-- `dependency_name_sets_of_hyps_inclusive hs` returns, for each `h ∈ hs`, the unique names of the dependencies of `h`, plus the unique name of `h` itself. This is the same as (but more performant than) using `tactic.dependency_name_set_of_hyp_inclusive` on every `h ∈ hs`. -/ meta def dependency_name_sets_of_hyps_inclusive (hs : list expr) : tactic (list name_set) := list.map local_set_to_name_set <$> dependency_sets_of_hyps_inclusive hs /-- `dependencies_of_hyps_inclusive hs` returns, for each `h ∈ hs`, the dependencies of `h`, plus `h` itself. The dependencies appear in no particular order in the returned lists. This is the same as (but more performant than) using `tactic.dependencies_of_hyp_inclusive` on every `h ∈ hs`. -/ meta def dependencies_of_hyps_inclusive (hs : list expr) : tactic (list (list expr)) := list.map rb_set.to_list <$> dependency_sets_of_hyps_inclusive hs /-! #### Computing the reverse dependencies of a hypothesis -/ private meta def reverse_dependencies_of_hyp_name_set_aux (hs : name_set) : list expr → list expr → name_set → tactic (list expr) | [] revdeps _ := pure revdeps.reverse | (H :: Hs) revdeps ns := do let H_uname := H.local_uniq_name, H_is_revdep ← list.mband [ pure $ ¬ hs.contains H_uname, hyp_directly_depends_on_local_name_set H ns ], if H_is_revdep then reverse_dependencies_of_hyp_name_set_aux Hs (H :: revdeps) (ns.insert H_uname) else reverse_dependencies_of_hyp_name_set_aux Hs revdeps ns /-- `reverse_dependencies_of_hyp_name_set hs` is the list of reverse dependencies of the hypotheses whose unique names appear in `hs`, excluding the `hs` themselves. The reverse dependencies are returned in the order in which they appear in the context. -/ meta def reverse_dependencies_of_hyp_name_set (hs : name_set) : tactic (list expr) := do ctx ← local_context, let ctx := ctx.after (λ h, hs.contains h.local_uniq_name), reverse_dependencies_of_hyp_name_set_aux hs ctx [] hs /-- `reverse_dependencies_of_hyp_set hs` is the list of reverse dependencies of the hypotheses `hs`, excluding the `hs` themselves. The reverse dependencies are returned in the order in which they appear in the context. -/ meta def reverse_dependencies_of_hyp_set (hs : expr_set) : tactic (list expr) := reverse_dependencies_of_hyp_name_set $ local_set_to_name_set hs /-- `reverse_dependencies_of_hyps hs` is the list of reverse dependencies of the hypotheses `hs`, excluding the `hs` themselves. The reverse dependencies are returned in the order in which they appear in the context. -/ meta def reverse_dependencies_of_hyps (hs : list expr) : tactic (list expr) := reverse_dependencies_of_hyp_name_set $ local_list_to_name_set hs private meta def reverse_dependencies_of_hyp_name_set_inclusive_aux : list expr → list expr → name_set → tactic (list expr) | [] revdeps _ := pure revdeps.reverse | (H :: Hs) revdeps ns := do let H_uname := H.local_uniq_name, H_is_revdep ← list.mbor [ pure $ ns.contains H.local_uniq_name, hyp_directly_depends_on_local_name_set H ns ], if H_is_revdep then reverse_dependencies_of_hyp_name_set_inclusive_aux Hs (H :: revdeps) (ns.insert H_uname) else reverse_dependencies_of_hyp_name_set_inclusive_aux Hs revdeps ns /-- `reverse_dependencies_of_hyp_name_set_inclusive hs` is the list of reverse dependencies of the hypotheses whose unique names appear in `hs`, including the `hs` themselves. The reverse dependencies are returned in the order in which they appear in the context. -/ meta def reverse_dependencies_of_hyp_name_set_inclusive (hs : name_set) : tactic (list expr) := do ctx ← local_context, let ctx := ctx.drop_while (λ h, ¬ hs.contains h.local_uniq_name), reverse_dependencies_of_hyp_name_set_inclusive_aux ctx [] hs /-- `reverse_dependencies_of_hyp_set_inclusive hs` is the list of reverse dependencies of the hypotheses `hs`, including the `hs` themselves. The inclusive reverse dependencies are returned in the order in which they appear in the context. -/ meta def reverse_dependencies_of_hyp_set_inclusive (hs : expr_set) : tactic (list expr) := reverse_dependencies_of_hyp_name_set_inclusive $ local_set_to_name_set hs /-- `reverse_dependencies_of_hyps_inclusive hs` is the list of reverse dependencies of the hypotheses `hs`, including the `hs` themselves. The reverse dependencies are returned in the order in which they appear in the context. -/ meta def reverse_dependencies_of_hyps_inclusive (hs : list expr) : tactic (list expr) := reverse_dependencies_of_hyp_name_set_inclusive $ local_list_to_name_set hs /-! ### Reverting a hypothesis and its reverse dependencies -/ /-- `revert_name_set hs` reverts the hypotheses whose unique names appear in `hs`, as well as any hypotheses that depend on them. Returns the number of reverted hypotheses and a list containing these hypotheses. The reverted hypotheses are returned in the order in which they used to appear in the context and are guaranteed to store the correct type (see `tactic.update_type`). -/ meta def revert_name_set (hs : name_set) : tactic (ℕ × list expr) := do to_revert ← reverse_dependencies_of_hyp_name_set_inclusive hs, to_revert_with_types ← to_revert.mmap update_type, num_reverted ← revert_lst to_revert, pure (num_reverted, to_revert_with_types) /-- `revert_set hs` reverts the hypotheses `hs`, as well as any hypotheses that depend on them. Returns the number of reverted hypotheses and a list containing these hypotheses. The reverted hypotheses are returned in the order in which they used to appear in the context and are guaranteed to store the correct type (see `tactic.update_type`). -/ meta def revert_set (hs : expr_set) : tactic (ℕ × list expr) := revert_name_set $ local_set_to_name_set hs /-- `revert_lst' hs` reverts the hypotheses `hs`, as well as any hypotheses that depend on them. Returns the number of reverted hypotheses and a list containing these hypotheses. The reverted hypotheses are returned in the order in which they used to appear in the context and are guaranteed to store the correct type (see `tactic.update_type`). This is a more informative version of `tactic.revert_lst`. -/ meta def revert_lst' (hs : list expr) : tactic (ℕ × list expr) := revert_name_set $ local_list_to_name_set hs /-- `revert_reverse_dependencies_of_hyp h` reverts all the hypotheses that depend on the hypothesis `h`, including the local definitions that have `h` in their value. This fixes a bug in `tactic.revert_kdependencies` that does not revert local definitions for which `h` only appears in the value. Returns the number of reverted hypotheses. -/ /- We cannot implement it as `revert e >> intro1` because that would change the local constant in the context. -/ meta def revert_reverse_dependencies_of_hyp (h : expr) : tactic ℕ := reverse_dependencies_of_hyp_name_set (mk_name_set.insert h.local_uniq_name) >>= revert_lst /-- `revert_reverse_dependencies_of_hyp_name_set hs` reverts all the hypotheses that depend on a hypothesis whose unique name appears in `hs`. The `hs` themselves are not reverted, unless they depend on each other. Returns the number of reverted hypotheses. -/ meta def revert_reverse_dependencies_of_hyp_name_set (hs : name_set) : tactic ℕ := reverse_dependencies_of_hyp_name_set hs >>= revert_lst /-- `revert_reverse_dependencies_of_hyp_set hs` reverts all the hypotheses that depend on a hypothesis in `hs`. The `hs` themselves are not reverted, unless they depend on each other. Returns the number of reverted hypotheses. -/ meta def revert_reverse_dependencies_of_hyp_set (hs : expr_set) : tactic ℕ := reverse_dependencies_of_hyp_set hs >>= revert_lst /-- `revert_reverse_dependencies_of_hyp hs` reverts all the hypotheses that depend on a hypothesis in `hs`. The `hs` themselves are not reverted, unless they depend on each other. Returns the number of reverted hypotheses. -/ meta def revert_reverse_dependencies_of_hyps (hs : list expr) : tactic ℕ := reverse_dependencies_of_hyps hs >>= revert_lst end tactic
80b63960473801432cf8a46c5c559fb39ad6a87c
5d76f062116fa5bd22eda20d6fd74da58dba65bb
/src/snarks/pinocchio/knowledge_soundness.lean
339f2e9b8f1947f5787ef5276ecd5a974d443955
[]
no_license
brando90/formal_baby_snark
59e4732dfb43f97776a3643f2731262f58d2bb81
4732da237784bd461ff949729cc011db83917907
refs/heads/master
1,682,650,246,414
1,621,103,975,000
1,621,103,975,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
28,821
lean
/- Author: Bolton Bailey -/ import data.mv_polynomial.basic import data.polynomial.div import data.polynomial.field_division import algebra.polynomial.big_operators import .vars /-! # Knowledge Soundness This file proves the knowledge-soundness property of the second, refined protocol described in the Pinocchio paper. -/ open_locale big_operators section noncomputable theory universes u /-- The finite field parameter of our SNARK -/ parameter {F : Type u} parameter [field F] /-- The naturals representing: m - m from paper - The QAP size n_in - n from paper - the number of inputs n_out - n' from paper - the number of outputs n_mid - (m - N) from paper - the number of internal gates d - the degree of h -/ parameters {n_in n_out n_mid d : ℕ} -- N from paper def n_stmt := n_in + n_out -- Alternative name def n_wit := n_mid def m := n_stmt + n_wit /-- fin-indexed collections of polynomials from the quadratic arithmetic program -/ parameter {v_stmt : fin n_stmt → polynomial F } parameter {w_stmt : fin n_stmt → polynomial F } parameter {y_stmt : fin n_stmt → polynomial F } parameter {v_wit : fin n_wit → polynomial F } parameter {w_wit : fin n_wit → polynomial F } parameter {y_wit : fin n_wit → polynomial F } parameter {v_0 : polynomial F } parameter {w_0 : polynomial F } parameter {y_0 : polynomial F } /-- The roots of the polynomial t -/ parameter {r : fin m → F} /-- t is the polynomial divisibility by which is used to verify satisfaction of the QAP -/ def t : polynomial F := ∏ i in (finset.fin_range m), (polynomial.X - polynomial.C (r i)) /-- t has degree m -/ lemma nat_degree_t : t.nat_degree = m := begin -- rw polynomial.nat_degree, rw t, rw polynomial.nat_degree_prod, simp, intros i hi, exact polynomial.X_sub_C_ne_zero (r i), end lemma monic_t : t.monic := begin rw t, apply polynomial.monic_prod_of_monic, intros i hi, exact polynomial.monic_X_sub_C (r i), end lemma degree_t_pos : 0 < m → 0 < t.degree := begin intro hm, suffices h : t.degree = some m, rw h, apply with_bot.some_lt_some.2, exact hm, have h := nat_degree_t, rw polynomial.nat_degree at h, induction h1 : t.degree, rw h1 at h, rw option.get_or_else at h, rw h at hm, have h2 := has_lt.lt.false hm, exfalso, exact h2, rw h1 at h, rw option.get_or_else at h, rw h, end -- -- Single variable form of V_wit -- def V_wit_sv (a_wit : fin n_wit → F) : polynomial F -- := ∑ i in finset.fin_range n_wit, a_wit i • u_wit i -- /-- The statement polynomial that the verifier computes from the statement bits, as a single variable polynomial -/ -- def V_stmt_sv (a_stmt : fin n_stmt → F) : polynomial F -- := ∑ i in (finset.fin_range n_stmt), a_stmt i • u_stmt i /-- Definition 2 from Pinocchio -/ def satisfying (c_stmt : fin n_stmt → F) (c_wit : fin n_wit → F) := ( (v_0 + (∑ i in (finset.fin_range n_stmt), c_stmt i • v_stmt i) + ∑ i in (finset.fin_range n_wit), c_wit i • v_wit i) * (w_0 + (∑ i in (finset.fin_range n_stmt), c_stmt i • w_stmt i) + (∑ i in (finset.fin_range n_wit), c_wit i • w_wit i)) - (y_0 + (∑ i in (finset.fin_range n_stmt), c_stmt i • y_stmt i) + (∑ i in (finset.fin_range n_wit), c_wit i • y_wit i))) %ₘ t = 0 /- Multivariable polynomial definititons and ultilities -/ /-- Helper for converting mv_polynomial to single -/ -- @[simp] -- def singlify : vars -> polynomial F -- | vars.X := polynomial.X -- | vars.Alpha := 1 -- | vars.Beta := 1 -- | vars.Gamma := 1 -- | vars.Delta := 1 -- Helpers for representing vars as polynomials def r_v_poly : mv_polynomial vars F := mv_polynomial.X vars.s def r_w_poly : mv_polynomial vars F := mv_polynomial.X vars.s def s_poly : mv_polynomial vars F := mv_polynomial.X vars.s def α_v_poly : mv_polynomial vars F := mv_polynomial.X vars.α_v def α_w_poly : mv_polynomial vars F := mv_polynomial.X vars.α_w def α_y_poly : mv_polynomial vars F := mv_polynomial.X vars.α_y def β_poly : mv_polynomial vars F := mv_polynomial.X vars.β def γ_poly : mv_polynomial vars F := mv_polynomial.X vars.γ /-- Additional variable defined in terms of others -/ def r_y_poly : mv_polynomial vars F := r_v_poly * r_w_poly -- The crs elements as multivariate polynomials of the toxic waste samples: Evaluation key elements def crs_v_wit_k (k : fin n_wit) : mv_polynomial vars F := r_v_poly * (v_wit k).eval₂ mv_polynomial.C s_poly def crs_w_wit_k (k : fin n_wit) : mv_polynomial vars F := r_w_poly * (w_wit k).eval₂ mv_polynomial.C s_poly def crs_y_wit_k (k : fin n_wit) : mv_polynomial vars F := r_y_poly * (y_wit k).eval₂ mv_polynomial.C s_poly def crs_α_v_wit_k (k : fin n_wit) : mv_polynomial vars F := α_v_poly * r_v_poly * (v_wit k).eval₂ mv_polynomial.C s_poly def crs_α_w_wit_k (k : fin n_wit) : mv_polynomial vars F := α_w_poly * r_w_poly * (w_wit k).eval₂ mv_polynomial.C s_poly def crs_α_y_wit_k (k : fin n_wit) : mv_polynomial vars F := α_y_poly * r_y_poly * (y_wit k).eval₂ mv_polynomial.C s_poly def crs_powers (i : fin d) : (mv_polynomial vars F) := s_poly^(i : ℕ) def crs_β_v_w_y_k (k : fin n_wit) : mv_polynomial vars F := β_poly * r_v_poly * (v_wit k).eval₂ mv_polynomial.C s_poly + β_poly * r_w_poly * (w_wit k).eval₂ mv_polynomial.C s_poly + β_poly * r_y_poly * (y_wit k).eval₂ mv_polynomial.C s_poly -- The crs elements as multivariate polynomials of the toxic waste samples: Verification key elements def crs_α_v : mv_polynomial vars F := α_v_poly def crs_α_w : mv_polynomial vars F := α_w_poly def crs_α_y : mv_polynomial vars F := α_y_poly def crs_γ : mv_polynomial vars F := γ_poly def crs_βγ : mv_polynomial vars F := β_poly * γ_poly def crs_t : mv_polynomial vars F := r_y_poly * (t).eval₂ mv_polynomial.C s_poly def crs_v_0 : mv_polynomial vars F := r_v_poly * (v_0).eval₂ mv_polynomial.C s_poly def crs_w_0 : mv_polynomial vars F := r_w_poly * (w_0).eval₂ mv_polynomial.C s_poly def crs_y_0 : mv_polynomial vars F := r_y_poly * (y_0).eval₂ mv_polynomial.C s_poly def crs_v_stmt (i : fin n_stmt) : mv_polynomial vars F := r_v_poly * (v_stmt i).eval₂ mv_polynomial.C s_poly def crs_w_stmt (i : fin n_stmt) : mv_polynomial vars F := r_w_poly * (w_stmt i).eval₂ mv_polynomial.C s_poly def crs_y_stmt (i : fin n_stmt) : mv_polynomial vars F := r_y_poly * (y_stmt i).eval₂ mv_polynomial.C s_poly -- Coefficients of the CRS elements in the representation of the v_wit proof element in the AGM parameters {v_wit_comp_crs_v_wit_k : fin n_wit → F} parameters {v_wit_comp_crs_w_wit_k : fin n_wit → F} parameters {v_wit_comp_crs_y_wit_k : fin n_wit → F} parameters {v_wit_comp_crs_α_v_wit_k : fin n_wit → F} parameters {v_wit_comp_crs_α_w_wit_k : fin n_wit → F} parameters {v_wit_comp_crs_α_y_wit_k : fin n_wit → F} parameters {v_wit_comp_crs_powers : fin d → F} parameters {v_wit_comp_crs_β_v_w_y_k : fin n_wit → F} parameters {v_wit_comp_crs_α_v : F} parameters {v_wit_comp_crs_α_w : F} parameters {v_wit_comp_crs_α_y : F} parameters {v_wit_comp_crs_γ : F} parameters {v_wit_comp_crs_βγ : F} parameters {v_wit_comp_crs_t : F} parameters {v_wit_comp_crs_v_0 : F} parameters {v_wit_comp_crs_w_0 : F} parameters {v_wit_comp_crs_y_0 : F} parameters {v_wit_comp_crs_v_stmt : fin n_stmt → F} parameters {v_wit_comp_crs_w_stmt : fin n_stmt → F} parameters {v_wit_comp_crs_y_stmt : fin n_stmt → F} /-- Polynomial form of the representation of the v_wit proof element in the AGM -/ def proof_v_wit : mv_polynomial vars F := ∑ i in (finset.fin_range n_wit), (v_wit_comp_crs_v_wit_k i) • (crs_v_wit_k i) + ∑ i in (finset.fin_range n_wit), (v_wit_comp_crs_y_wit_k i) • (crs_v_wit_k i) + ∑ i in (finset.fin_range n_wit), (v_wit_comp_crs_w_wit_k i) • (crs_v_wit_k i) + ∑ i in (finset.fin_range n_wit), (v_wit_comp_crs_α_v_wit_k i) • (crs_v_wit_k i) + ∑ i in (finset.fin_range n_wit), (v_wit_comp_crs_α_y_wit_k i) • (crs_v_wit_k i) + ∑ i in (finset.fin_range n_wit), (v_wit_comp_crs_α_w_wit_k i) • (crs_v_wit_k i) + ∑ i in (finset.fin_range d), (v_wit_comp_crs_powers i) • (crs_powers i) + ∑ i in (finset.fin_range n_wit), (v_wit_comp_crs_β_v_w_y_k i) • (crs_β_v_w_y_k i) + v_wit_comp_crs_α_v • crs_α_v + v_wit_comp_crs_α_w • crs_α_w + v_wit_comp_crs_α_y • crs_α_y + v_wit_comp_crs_γ • crs_γ + v_wit_comp_crs_βγ • crs_βγ + v_wit_comp_crs_t • crs_t + v_wit_comp_crs_v_0 • crs_v_0 + v_wit_comp_crs_w_0 • crs_w_0 + v_wit_comp_crs_y_0 • crs_y_0 + ∑ i in (finset.fin_range n_stmt), (v_wit_comp_crs_v_stmt i) • (crs_v_stmt i) + ∑ i in (finset.fin_range n_stmt), (v_wit_comp_crs_y_stmt i) • (crs_y_stmt i) + ∑ i in (finset.fin_range n_stmt), (v_wit_comp_crs_w_stmt i) • (crs_w_stmt i) -- Coefficients of the CRS elements in the representation of the w_wit proof element in the AGM parameters {w_wit_comp_crs_v_wit_k : fin n_wit → F} parameters {w_wit_comp_crs_w_wit_k : fin n_wit → F} parameters {w_wit_comp_crs_y_wit_k : fin n_wit → F} parameters {w_wit_comp_crs_α_v_wit_k : fin n_wit → F} parameters {w_wit_comp_crs_α_w_wit_k : fin n_wit → F} parameters {w_wit_comp_crs_α_y_wit_k : fin n_wit → F} parameters {w_wit_comp_crs_powers : fin d → F} parameters {w_wit_comp_crs_β_v_w_y_k : fin n_wit → F} parameters {w_wit_comp_crs_α_v : F} parameters {w_wit_comp_crs_α_w : F} parameters {w_wit_comp_crs_α_y : F} parameters {w_wit_comp_crs_γ : F} parameters {w_wit_comp_crs_βγ : F} parameters {w_wit_comp_crs_t : F} parameters {w_wit_comp_crs_v_0 : F} parameters {w_wit_comp_crs_w_0 : F} parameters {w_wit_comp_crs_y_0 : F} parameters {w_wit_comp_crs_v_stmt : fin n_stmt → F} parameters {w_wit_comp_crs_w_stmt : fin n_stmt → F} parameters {w_wit_comp_crs_y_stmt : fin n_stmt → F} /-- Polynomial form of the representation of the w_wit proof element in the AGM -/ def proof_w_wit : mv_polynomial vars F := ∑ i in (finset.fin_range n_wit), (w_wit_comp_crs_v_wit_k i) • (crs_v_wit_k i) + ∑ i in (finset.fin_range n_wit), (w_wit_comp_crs_y_wit_k i) • (crs_v_wit_k i) + ∑ i in (finset.fin_range n_wit), (w_wit_comp_crs_w_wit_k i) • (crs_v_wit_k i) + ∑ i in (finset.fin_range n_wit), (w_wit_comp_crs_α_v_wit_k i) • (crs_v_wit_k i) + ∑ i in (finset.fin_range n_wit), (w_wit_comp_crs_α_y_wit_k i) • (crs_v_wit_k i) + ∑ i in (finset.fin_range n_wit), (w_wit_comp_crs_α_w_wit_k i) • (crs_v_wit_k i) + ∑ i in (finset.fin_range d), (w_wit_comp_crs_powers i) • (crs_powers i) + ∑ i in (finset.fin_range n_wit), (w_wit_comp_crs_β_v_w_y_k i) • (crs_β_v_w_y_k i) + w_wit_comp_crs_α_v • crs_α_v + w_wit_comp_crs_α_w • crs_α_w + w_wit_comp_crs_α_y • crs_α_y + w_wit_comp_crs_γ • crs_γ + w_wit_comp_crs_βγ • crs_βγ + w_wit_comp_crs_t • crs_t + w_wit_comp_crs_v_0 • crs_v_0 + w_wit_comp_crs_w_0 • crs_w_0 + w_wit_comp_crs_y_0 • crs_y_0 + ∑ i in (finset.fin_range n_stmt), (w_wit_comp_crs_v_stmt i) • (crs_v_stmt i) + ∑ i in (finset.fin_range n_stmt), (w_wit_comp_crs_y_stmt i) • (crs_y_stmt i) + ∑ i in (finset.fin_range n_stmt), (w_wit_comp_crs_w_stmt i) • (crs_w_stmt i) -- Coefficients of the CRS elements in the representation of the y_wit proof element in the AGM parameters {y_wit_comp_crs_v_wit_k : fin n_wit → F} parameters {y_wit_comp_crs_w_wit_k : fin n_wit → F} parameters {y_wit_comp_crs_y_wit_k : fin n_wit → F} parameters {y_wit_comp_crs_α_v_wit_k : fin n_wit → F} parameters {y_wit_comp_crs_α_w_wit_k : fin n_wit → F} parameters {y_wit_comp_crs_α_y_wit_k : fin n_wit → F} parameters {y_wit_comp_crs_powers : fin d → F} parameters {y_wit_comp_crs_β_v_w_y_k : fin n_wit → F} parameters {y_wit_comp_crs_α_v : F} parameters {y_wit_comp_crs_α_w : F} parameters {y_wit_comp_crs_α_y : F} parameters {y_wit_comp_crs_γ : F} parameters {y_wit_comp_crs_βγ : F} parameters {y_wit_comp_crs_t : F} parameters {y_wit_comp_crs_v_0 : F} parameters {y_wit_comp_crs_w_0 : F} parameters {y_wit_comp_crs_y_0 : F} parameters {y_wit_comp_crs_v_stmt : fin n_stmt → F} parameters {y_wit_comp_crs_w_stmt : fin n_stmt → F} parameters {y_wit_comp_crs_y_stmt : fin n_stmt → F} /-- Polynomial form of the representation of the w_wit proof element in the AGM -/ def proof_y_wit : mv_polynomial vars F := ∑ i in (finset.fin_range n_wit), (y_wit_comp_crs_v_wit_k i) • (crs_v_wit_k i) + ∑ i in (finset.fin_range n_wit), (y_wit_comp_crs_y_wit_k i) • (crs_v_wit_k i) + ∑ i in (finset.fin_range n_wit), (y_wit_comp_crs_w_wit_k i) • (crs_v_wit_k i) + ∑ i in (finset.fin_range n_wit), (y_wit_comp_crs_α_v_wit_k i) • (crs_v_wit_k i) + ∑ i in (finset.fin_range n_wit), (y_wit_comp_crs_α_y_wit_k i) • (crs_v_wit_k i) + ∑ i in (finset.fin_range n_wit), (y_wit_comp_crs_α_w_wit_k i) • (crs_v_wit_k i) + ∑ i in (finset.fin_range d), (y_wit_comp_crs_powers i) • (crs_powers i) + ∑ i in (finset.fin_range n_wit), (y_wit_comp_crs_β_v_w_y_k i) • (crs_β_v_w_y_k i) + y_wit_comp_crs_α_v • crs_α_v + y_wit_comp_crs_α_w • crs_α_w + y_wit_comp_crs_α_y • crs_α_y + y_wit_comp_crs_γ • crs_γ + y_wit_comp_crs_βγ • crs_βγ + y_wit_comp_crs_t • crs_t + y_wit_comp_crs_v_0 • crs_v_0 + y_wit_comp_crs_w_0 • crs_w_0 + y_wit_comp_crs_y_0 • crs_y_0 + ∑ i in (finset.fin_range n_stmt), (y_wit_comp_crs_v_stmt i) • (crs_v_stmt i) + ∑ i in (finset.fin_range n_stmt), (y_wit_comp_crs_y_stmt i) • (crs_y_stmt i) + ∑ i in (finset.fin_range n_stmt), (y_wit_comp_crs_w_stmt i) • (crs_w_stmt i) -- Coefficients of the CRS elements in the representation of the h proof element in the AGM parameters {h_comp_crs_v_wit_k : fin n_wit → F} parameters {h_comp_crs_w_wit_k : fin n_wit → F} parameters {h_comp_crs_y_wit_k : fin n_wit → F} parameters {h_comp_crs_α_v_wit_k : fin n_wit → F} parameters {h_comp_crs_α_w_wit_k : fin n_wit → F} parameters {h_comp_crs_α_y_wit_k : fin n_wit → F} parameters {h_comp_crs_powers : fin d → F} parameters {h_comp_crs_β_v_w_y_k : fin n_wit → F} parameters {h_comp_crs_α_v : F} parameters {h_comp_crs_α_w : F} parameters {h_comp_crs_α_y : F} parameters {h_comp_crs_γ : F} parameters {h_comp_crs_βγ : F} parameters {h_comp_crs_t : F} parameters {h_comp_crs_v_0 : F} parameters {h_comp_crs_w_0 : F} parameters {h_comp_crs_y_0 : F} parameters {h_comp_crs_v_stmt : fin n_stmt → F} parameters {h_comp_crs_w_stmt : fin n_stmt → F} parameters {h_comp_crs_y_stmt : fin n_stmt → F} /-- Polynomial form of the representation of the h proof element in the AGM -/ def proof_h : mv_polynomial vars F := ∑ i in (finset.fin_range n_wit), (h_comp_crs_v_wit_k i) • (crs_v_wit_k i) + ∑ i in (finset.fin_range n_wit), (h_comp_crs_y_wit_k i) • (crs_v_wit_k i) + ∑ i in (finset.fin_range n_wit), (h_comp_crs_w_wit_k i) • (crs_v_wit_k i) + ∑ i in (finset.fin_range n_wit), (h_comp_crs_α_v_wit_k i) • (crs_v_wit_k i) + ∑ i in (finset.fin_range n_wit), (h_comp_crs_α_y_wit_k i) • (crs_v_wit_k i) + ∑ i in (finset.fin_range n_wit), (h_comp_crs_α_w_wit_k i) • (crs_v_wit_k i) + ∑ i in (finset.fin_range d), (h_comp_crs_powers i) • (crs_powers i) + ∑ i in (finset.fin_range n_wit), (h_comp_crs_β_v_w_y_k i) • (crs_β_v_w_y_k i) + h_comp_crs_α_v • crs_α_v + h_comp_crs_α_w • crs_α_w + h_comp_crs_α_y • crs_α_y + h_comp_crs_γ • crs_γ + h_comp_crs_βγ • crs_βγ + h_comp_crs_t • crs_t + h_comp_crs_v_0 • crs_v_0 + h_comp_crs_w_0 • crs_w_0 + h_comp_crs_y_0 • crs_y_0 + ∑ i in (finset.fin_range n_stmt), (h_comp_crs_v_stmt i) • (crs_v_stmt i) + ∑ i in (finset.fin_range n_stmt), (h_comp_crs_y_stmt i) • (crs_y_stmt i) + ∑ i in (finset.fin_range n_stmt), (h_comp_crs_w_stmt i) • (crs_w_stmt i) -- Coefficients of the CRS elements in the representation of the α_v_wit proof element in the AGM parameters {α_v_wit_comp_crs_v_wit_k : fin n_wit → F} parameters {α_v_wit_comp_crs_w_wit_k : fin n_wit → F} parameters {α_v_wit_comp_crs_y_wit_k : fin n_wit → F} parameters {α_v_wit_comp_crs_α_v_wit_k : fin n_wit → F} parameters {α_v_wit_comp_crs_α_w_wit_k : fin n_wit → F} parameters {α_v_wit_comp_crs_α_y_wit_k : fin n_wit → F} parameters {α_v_wit_comp_crs_powers : fin d → F} parameters {α_v_wit_comp_crs_β_v_w_y_k : fin n_wit → F} parameters {α_v_wit_comp_crs_α_v : F} parameters {α_v_wit_comp_crs_α_w : F} parameters {α_v_wit_comp_crs_α_y : F} parameters {α_v_wit_comp_crs_γ : F} parameters {α_v_wit_comp_crs_βγ : F} parameters {α_v_wit_comp_crs_t : F} parameters {α_v_wit_comp_crs_v_0 : F} parameters {α_v_wit_comp_crs_w_0 : F} parameters {α_v_wit_comp_crs_y_0 : F} parameters {α_v_wit_comp_crs_v_stmt : fin n_stmt → F} parameters {α_v_wit_comp_crs_w_stmt : fin n_stmt → F} parameters {α_v_wit_comp_crs_y_stmt : fin n_stmt → F} /-- Polynomial form of the representation of the α_v_wit proof element in the AGM -/ def proof_α_v_wit : mv_polynomial vars F := ∑ i in (finset.fin_range n_wit), (α_v_wit_comp_crs_v_wit_k i) • (crs_v_wit_k i) + ∑ i in (finset.fin_range n_wit), (α_v_wit_comp_crs_y_wit_k i) • (crs_v_wit_k i) + ∑ i in (finset.fin_range n_wit), (α_v_wit_comp_crs_w_wit_k i) • (crs_v_wit_k i) + ∑ i in (finset.fin_range n_wit), (α_v_wit_comp_crs_α_v_wit_k i) • (crs_v_wit_k i) + ∑ i in (finset.fin_range n_wit), (α_v_wit_comp_crs_α_y_wit_k i) • (crs_v_wit_k i) + ∑ i in (finset.fin_range n_wit), (α_v_wit_comp_crs_α_w_wit_k i) • (crs_v_wit_k i) + ∑ i in (finset.fin_range d), (α_v_wit_comp_crs_powers i) • (crs_powers i) + ∑ i in (finset.fin_range n_wit), (α_v_wit_comp_crs_β_v_w_y_k i) • (crs_β_v_w_y_k i) + α_v_wit_comp_crs_α_v • crs_α_v + α_v_wit_comp_crs_α_w • crs_α_w + α_v_wit_comp_crs_α_y • crs_α_y + α_v_wit_comp_crs_γ • crs_γ + α_v_wit_comp_crs_βγ • crs_βγ + α_v_wit_comp_crs_t • crs_t + α_v_wit_comp_crs_v_0 • crs_v_0 + α_v_wit_comp_crs_w_0 • crs_w_0 + α_v_wit_comp_crs_y_0 • crs_y_0 + ∑ i in (finset.fin_range n_stmt), (α_v_wit_comp_crs_v_stmt i) • (crs_v_stmt i) + ∑ i in (finset.fin_range n_stmt), (α_v_wit_comp_crs_y_stmt i) • (crs_y_stmt i) + ∑ i in (finset.fin_range n_stmt), (α_v_wit_comp_crs_w_stmt i) • (crs_w_stmt i) -- Coefficients of the CRS elements in the representation of the α_w_wit proof element in the AGM parameters {α_w_wit_comp_crs_v_wit_k : fin n_wit → F} parameters {α_w_wit_comp_crs_w_wit_k : fin n_wit → F} parameters {α_w_wit_comp_crs_y_wit_k : fin n_wit → F} parameters {α_w_wit_comp_crs_α_v_wit_k : fin n_wit → F} parameters {α_w_wit_comp_crs_α_w_wit_k : fin n_wit → F} parameters {α_w_wit_comp_crs_α_y_wit_k : fin n_wit → F} parameters {α_w_wit_comp_crs_powers : fin d → F} parameters {α_w_wit_comp_crs_β_v_w_y_k : fin n_wit → F} parameters {α_w_wit_comp_crs_α_v : F} parameters {α_w_wit_comp_crs_α_w : F} parameters {α_w_wit_comp_crs_α_y : F} parameters {α_w_wit_comp_crs_γ : F} parameters {α_w_wit_comp_crs_βγ : F} parameters {α_w_wit_comp_crs_t : F} parameters {α_w_wit_comp_crs_v_0 : F} parameters {α_w_wit_comp_crs_w_0 : F} parameters {α_w_wit_comp_crs_y_0 : F} parameters {α_w_wit_comp_crs_v_stmt : fin n_stmt → F} parameters {α_w_wit_comp_crs_w_stmt : fin n_stmt → F} parameters {α_w_wit_comp_crs_y_stmt : fin n_stmt → F} /-- Polynomial form of the representation of the α_w_wit proof element in the AGM -/ def proof_α_w_wit : mv_polynomial vars F := ∑ i in (finset.fin_range n_wit), (α_w_wit_comp_crs_v_wit_k i) • (crs_v_wit_k i) + ∑ i in (finset.fin_range n_wit), (α_w_wit_comp_crs_y_wit_k i) • (crs_v_wit_k i) + ∑ i in (finset.fin_range n_wit), (α_w_wit_comp_crs_w_wit_k i) • (crs_v_wit_k i) + ∑ i in (finset.fin_range n_wit), (α_w_wit_comp_crs_α_v_wit_k i) • (crs_v_wit_k i) + ∑ i in (finset.fin_range n_wit), (α_w_wit_comp_crs_α_y_wit_k i) • (crs_v_wit_k i) + ∑ i in (finset.fin_range n_wit), (α_w_wit_comp_crs_α_w_wit_k i) • (crs_v_wit_k i) + ∑ i in (finset.fin_range d), (α_w_wit_comp_crs_powers i) • (crs_powers i) + ∑ i in (finset.fin_range n_wit), (α_w_wit_comp_crs_β_v_w_y_k i) • (crs_β_v_w_y_k i) + α_w_wit_comp_crs_α_v • crs_α_v + α_w_wit_comp_crs_α_w • crs_α_w + α_w_wit_comp_crs_α_y • crs_α_y + α_w_wit_comp_crs_γ • crs_γ + α_w_wit_comp_crs_βγ • crs_βγ + α_w_wit_comp_crs_t • crs_t + α_w_wit_comp_crs_v_0 • crs_v_0 + α_w_wit_comp_crs_w_0 • crs_w_0 + α_w_wit_comp_crs_y_0 • crs_y_0 + ∑ i in (finset.fin_range n_stmt), (α_w_wit_comp_crs_v_stmt i) • (crs_v_stmt i) + ∑ i in (finset.fin_range n_stmt), (α_w_wit_comp_crs_y_stmt i) • (crs_y_stmt i) + ∑ i in (finset.fin_range n_stmt), (α_w_wit_comp_crs_w_stmt i) • (crs_w_stmt i) -- Coefficients of the CRS elements in the representation of the α_y_wit proof element in the AGM parameters {α_y_wit_comp_crs_v_wit_k : fin n_wit → F} parameters {α_y_wit_comp_crs_w_wit_k : fin n_wit → F} parameters {α_y_wit_comp_crs_y_wit_k : fin n_wit → F} parameters {α_y_wit_comp_crs_α_v_wit_k : fin n_wit → F} parameters {α_y_wit_comp_crs_α_w_wit_k : fin n_wit → F} parameters {α_y_wit_comp_crs_α_y_wit_k : fin n_wit → F} parameters {α_y_wit_comp_crs_powers : fin d → F} parameters {α_y_wit_comp_crs_β_v_w_y_k : fin n_wit → F} parameters {α_y_wit_comp_crs_α_v : F} parameters {α_y_wit_comp_crs_α_w : F} parameters {α_y_wit_comp_crs_α_y : F} parameters {α_y_wit_comp_crs_γ : F} parameters {α_y_wit_comp_crs_βγ : F} parameters {α_y_wit_comp_crs_t : F} parameters {α_y_wit_comp_crs_v_0 : F} parameters {α_y_wit_comp_crs_w_0 : F} parameters {α_y_wit_comp_crs_y_0 : F} parameters {α_y_wit_comp_crs_v_stmt : fin n_stmt → F} parameters {α_y_wit_comp_crs_w_stmt : fin n_stmt → F} parameters {α_y_wit_comp_crs_y_stmt : fin n_stmt → F} /-- Polynomial form of the representation of the α_y_wit proof element in the AGM -/ def proof_α_y_wit : mv_polynomial vars F := ∑ i in (finset.fin_range n_wit), (α_y_wit_comp_crs_v_wit_k i) • (crs_v_wit_k i) + ∑ i in (finset.fin_range n_wit), (α_y_wit_comp_crs_y_wit_k i) • (crs_v_wit_k i) + ∑ i in (finset.fin_range n_wit), (α_y_wit_comp_crs_w_wit_k i) • (crs_v_wit_k i) + ∑ i in (finset.fin_range n_wit), (α_y_wit_comp_crs_α_v_wit_k i) • (crs_v_wit_k i) + ∑ i in (finset.fin_range n_wit), (α_y_wit_comp_crs_α_y_wit_k i) • (crs_v_wit_k i) + ∑ i in (finset.fin_range n_wit), (α_y_wit_comp_crs_α_w_wit_k i) • (crs_v_wit_k i) + ∑ i in (finset.fin_range d), (α_y_wit_comp_crs_powers i) • (crs_powers i) + ∑ i in (finset.fin_range n_wit), (α_y_wit_comp_crs_β_v_w_y_k i) • (crs_β_v_w_y_k i) + α_y_wit_comp_crs_α_v • crs_α_v + α_y_wit_comp_crs_α_w • crs_α_w + α_y_wit_comp_crs_α_y • crs_α_y + α_y_wit_comp_crs_γ • crs_γ + α_y_wit_comp_crs_βγ • crs_βγ + α_y_wit_comp_crs_t • crs_t + α_y_wit_comp_crs_v_0 • crs_v_0 + α_y_wit_comp_crs_w_0 • crs_w_0 + α_y_wit_comp_crs_y_0 • crs_y_0 + ∑ i in (finset.fin_range n_stmt), (α_y_wit_comp_crs_v_stmt i) • (crs_v_stmt i) + ∑ i in (finset.fin_range n_stmt), (α_y_wit_comp_crs_y_stmt i) • (crs_y_stmt i) + ∑ i in (finset.fin_range n_stmt), (α_y_wit_comp_crs_w_stmt i) • (crs_w_stmt i) -- Coefficients of the CRS elements in the representation of the Z proof element in the AGM parameters {Z_comp_crs_v_wit_k : fin n_wit → F} parameters {Z_comp_crs_w_wit_k : fin n_wit → F} parameters {Z_comp_crs_y_wit_k : fin n_wit → F} parameters {Z_comp_crs_α_v_wit_k : fin n_wit → F} parameters {Z_comp_crs_α_w_wit_k : fin n_wit → F} parameters {Z_comp_crs_α_y_wit_k : fin n_wit → F} parameters {Z_comp_crs_powers : fin d → F} parameters {Z_comp_crs_β_v_w_y_k : fin n_wit → F} parameters {Z_comp_crs_α_v : F} parameters {Z_comp_crs_α_w : F} parameters {Z_comp_crs_α_y : F} parameters {Z_comp_crs_γ : F} parameters {Z_comp_crs_βγ : F} parameters {Z_comp_crs_t : F} parameters {Z_comp_crs_v_0 : F} parameters {Z_comp_crs_w_0 : F} parameters {Z_comp_crs_y_0 : F} parameters {Z_comp_crs_v_stmt : fin n_stmt → F} parameters {Z_comp_crs_w_stmt : fin n_stmt → F} parameters {Z_comp_crs_y_stmt : fin n_stmt → F} /-- Polynomial form of the representation of the Z proof element in the AGM -/ def proof_Z : mv_polynomial vars F := ∑ i in (finset.fin_range n_wit), (Z_comp_crs_v_wit_k i) • (crs_v_wit_k i) + ∑ i in (finset.fin_range n_wit), (Z_comp_crs_y_wit_k i) • (crs_v_wit_k i) + ∑ i in (finset.fin_range n_wit), (Z_comp_crs_w_wit_k i) • (crs_v_wit_k i) + ∑ i in (finset.fin_range n_wit), (Z_comp_crs_α_v_wit_k i) • (crs_v_wit_k i) + ∑ i in (finset.fin_range n_wit), (Z_comp_crs_α_y_wit_k i) • (crs_v_wit_k i) + ∑ i in (finset.fin_range n_wit), (Z_comp_crs_α_w_wit_k i) • (crs_v_wit_k i) + ∑ i in (finset.fin_range d), (Z_comp_crs_powers i) • (crs_powers i) + ∑ i in (finset.fin_range n_wit), (Z_comp_crs_β_v_w_y_k i) • (crs_β_v_w_y_k i) + Z_comp_crs_α_v • crs_α_v + Z_comp_crs_α_w • crs_α_w + Z_comp_crs_α_y • crs_α_y + Z_comp_crs_γ • crs_γ + Z_comp_crs_βγ • crs_βγ + Z_comp_crs_t • crs_t + Z_comp_crs_v_0 • crs_v_0 + Z_comp_crs_w_0 • crs_w_0 + Z_comp_crs_y_0 • crs_y_0 + ∑ i in (finset.fin_range n_stmt), (Z_comp_crs_v_stmt i) • (crs_v_stmt i) + ∑ i in (finset.fin_range n_stmt), (Z_comp_crs_y_stmt i) • (crs_y_stmt i) + ∑ i in (finset.fin_range n_stmt), (Z_comp_crs_w_stmt i) • (crs_w_stmt i) -- Single variable form of V_wit def v_wit_sv (a_wit : fin n_wit → F) : polynomial F := ∑ i in finset.fin_range n_wit, a_wit i • v_wit i /-- The statement polynomial that the verifier computes from the statement bits, as a single variable polynomial -/ def v_stmt_sv (a_stmt : fin n_stmt → F) : polynomial F := ∑ i in (finset.fin_range n_stmt), a_stmt i • v_stmt i /-- V_stmt as a multivariable polynomial of vars.X -/ def v_stmt_mv (a_stmt : fin n_stmt → F) : mv_polynomial vars F := (v_stmt_sv a_stmt).eval₂ mv_polynomial.C s_poly /-- The statement polynomial that the verifier computes from the statement bits, as a single variable polynomial -/ def y_stmt_sv (a_stmt : fin n_stmt → F) : polynomial F := ∑ i in (finset.fin_range n_stmt), a_stmt i • y_stmt i /-- V_stmt as a multivariable polynomial of vars.X -/ def y_stmt_mv (a_stmt : fin n_stmt → F) : mv_polynomial vars F := (y_stmt_sv a_stmt).eval₂ mv_polynomial.C s_poly /-- The statement polynomial that the verifier computes from the statement bits, as a single variable polynomial -/ def w_stmt_sv (a_stmt : fin n_stmt → F) : polynomial F := ∑ i in (finset.fin_range n_stmt), a_stmt i • w_stmt i /-- V_stmt as a multivariable polynomial of vars.X -/ def w_stmt_mv (a_stmt : fin n_stmt → F) : mv_polynomial vars F := (w_stmt_sv a_stmt).eval₂ mv_polynomial.C s_poly -- /-- V as a multivariable polynomial -/ -- def proof_v (a_stmt : fin n_stmt → F) : mv_polynomial vars F -- := v_stmt_mv a_stmt + proof_v_wit /-- Multivariable version of t -/ def t_mv : mv_polynomial vars F := t.eval₂ mv_polynomial.C s_poly /-- Show that if the adversary polynomials obey the equations, then the coefficients give a satisfying witness. -/ theorem soundness (c_stmt : fin n_stmt → F ) : (0 < m) -> (crs_v_0 + v_stmt_mv c_stmt + proof_v_wit) * (crs_w_0 + w_stmt_mv c_stmt + proof_w_wit) = (proof_h * t_mv) + crs_y_0 + y_stmt_mv c_stmt + proof_y_wit -> proof_α_v_wit = proof_v_wit * crs_α_v -> proof_α_w_wit = proof_w_wit * crs_α_w -> proof_α_y_wit = proof_y_wit * crs_α_y -> proof_Z * crs_γ = (proof_v_wit + proof_w_wit + proof_y_wit) * crs_βγ -> (satisfying c_stmt v_wit_comp_crs_v_wit_k) -- This shows that (a`+1, . . . , am) = (C`+1, . . . , Cm) is a witness for the statement (a1, . . . , a`) := begin intros hm eqnI eqnII eqnIII eqnIV eqnV, sorry, end end
fe34abf3def3b293bab0728d94d00209ae0844de
69d4931b605e11ca61881fc4f66db50a0a875e39
/src/data/matrix/basic.lean
d440024db7b804792189f4ab78facd58d3bacb62
[ "Apache-2.0" ]
permissive
abentkamp/mathlib
d9a75d291ec09f4637b0f30cc3880ffb07549ee5
5360e476391508e092b5a1e5210bd0ed22dc0755
refs/heads/master
1,682,382,954,948
1,622,106,077,000
1,622,106,077,000
149,285,665
0
0
null
null
null
null
UTF-8
Lean
false
false
54,448
lean
/- Copyright (c) 2018 Ellen Arlt. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Ellen Arlt, Blair Shi, Sean Leather, Mario Carneiro, Johan Commelin -/ import algebra.big_operators.pi import algebra.module.pi import algebra.module.linear_map import algebra.big_operators.ring import algebra.star.basic import data.equiv.ring import data.fintype.card import data.matrix.dmatrix /-! # Matrices -/ universes u u' v w open_locale big_operators open dmatrix /-- `matrix m n` is the type of matrices whose rows are indexed by the fintype `m` and whose columns are indexed by the fintype `n`. -/ @[nolint unused_arguments] def matrix (m : Type u) (n : Type u') [fintype m] [fintype n] (α : Type v) : Type (max u u' v) := m → n → α variables {l m n o : Type*} [fintype l] [fintype m] [fintype n] [fintype o] variables {m' : o → Type*} [∀ i, fintype (m' i)] variables {n' : o → Type*} [∀ i, fintype (n' i)] variables {R : Type*} {S : Type*} {α : Type v} {β : Type w} namespace matrix section ext variables {M N : matrix m n α} theorem ext_iff : (∀ i j, M i j = N i j) ↔ M = N := ⟨λ h, funext $ λ i, funext $ h i, λ h, by simp [h]⟩ @[ext] theorem ext : (∀ i j, M i j = N i j) → M = N := ext_iff.mp end ext /-- `M.map f` is the matrix obtained by applying `f` to each entry of the matrix `M`. -/ def map (M : matrix m n α) (f : α → β) : matrix m n β := λ i j, f (M i j) @[simp] lemma map_apply {M : matrix m n α} {f : α → β} {i : m} {j : n} : M.map f i j = f (M i j) := rfl @[simp] lemma map_map {M : matrix m n α} {β γ : Type*} {f : α → β} {g : β → γ} : (M.map f).map g = M.map (g ∘ f) := by { ext, simp, } /-- The transpose of a matrix. -/ def transpose (M : matrix m n α) : matrix n m α | x y := M y x localized "postfix `ᵀ`:1500 := matrix.transpose" in matrix /-- `matrix.col u` is the column matrix whose entries are given by `u`. -/ def col (w : m → α) : matrix m unit α | x y := w x /-- `matrix.row u` is the row matrix whose entries are given by `u`. -/ def row (v : n → α) : matrix unit n α | x y := v y instance [inhabited α] : inhabited (matrix m n α) := pi.inhabited _ instance [has_add α] : has_add (matrix m n α) := pi.has_add instance [add_semigroup α] : add_semigroup (matrix m n α) := pi.add_semigroup instance [add_comm_semigroup α] : add_comm_semigroup (matrix m n α) := pi.add_comm_semigroup instance [has_zero α] : has_zero (matrix m n α) := pi.has_zero instance [add_monoid α] : add_monoid (matrix m n α) := pi.add_monoid instance [add_comm_monoid α] : add_comm_monoid (matrix m n α) := pi.add_comm_monoid instance [has_neg α] : has_neg (matrix m n α) := pi.has_neg instance [has_sub α] : has_sub (matrix m n α) := pi.has_sub instance [add_group α] : add_group (matrix m n α) := pi.add_group instance [add_comm_group α] : add_comm_group (matrix m n α) := pi.add_comm_group instance [unique α] : unique (matrix m n α) := pi.unique instance [subsingleton α] : subsingleton (matrix m n α) := pi.subsingleton instance [nonempty m] [nonempty n] [nontrivial α] : nontrivial (matrix m n α) := function.nontrivial instance [has_scalar R α] : has_scalar R (matrix m n α) := pi.has_scalar instance [has_scalar R α] [has_scalar S α] [smul_comm_class R S α] : smul_comm_class R S (matrix m n α) := pi.smul_comm_class instance [has_scalar R S] [has_scalar R α] [has_scalar S α] [is_scalar_tower R S α] : is_scalar_tower R S (matrix m n α) := pi.is_scalar_tower instance [monoid R] [mul_action R α] : mul_action R (matrix m n α) := pi.mul_action _ instance [monoid R] [add_monoid α] [distrib_mul_action R α] : distrib_mul_action R (matrix m n α) := pi.distrib_mul_action _ instance [semiring R] [add_comm_monoid α] [module R α] : module R (matrix m n α) := pi.module _ _ _ @[simp] lemma map_zero [has_zero α] [has_zero β] {f : α → β} (h : f 0 = 0) : (0 : matrix m n α).map f = 0 := by { ext, simp [h], } lemma map_add [add_monoid α] [add_monoid β] (f : α →+ β) (M N : matrix m n α) : (M + N).map f = M.map f + N.map f := by { ext, simp, } lemma map_sub [add_group α] [add_group β] (f : α →+ β) (M N : matrix m n α) : (M - N).map f = M.map f - N.map f := by { ext, simp } lemma subsingleton_of_empty_left (hm : ¬ nonempty m) : subsingleton (matrix m n α) := ⟨λ M N, by { ext, contrapose! hm, use i }⟩ lemma subsingleton_of_empty_right (hn : ¬ nonempty n) : subsingleton (matrix m n α) := ⟨λ M N, by { ext, contrapose! hn, use j }⟩ end matrix /-- The `add_monoid_hom` between spaces of matrices induced by an `add_monoid_hom` between their coefficients. -/ def add_monoid_hom.map_matrix [add_monoid α] [add_monoid β] (f : α →+ β) : matrix m n α →+ matrix m n β := { to_fun := λ M, M.map f, map_zero' := by simp, map_add' := matrix.map_add f, } @[simp] lemma add_monoid_hom.map_matrix_apply [add_monoid α] [add_monoid β] (f : α →+ β) (M : matrix m n α) : f.map_matrix M = M.map f := rfl open_locale matrix namespace matrix section diagonal variables [decidable_eq n] /-- `diagonal d` is the square matrix such that `(diagonal d) i i = d i` and `(diagonal d) i j = 0` if `i ≠ j`. -/ def diagonal [has_zero α] (d : n → α) : matrix n n α := λ i j, if i = j then d i else 0 @[simp] theorem diagonal_apply_eq [has_zero α] {d : n → α} (i : n) : (diagonal d) i i = d i := by simp [diagonal] @[simp] theorem diagonal_apply_ne [has_zero α] {d : n → α} {i j : n} (h : i ≠ j) : (diagonal d) i j = 0 := by simp [diagonal, h] theorem diagonal_apply_ne' [has_zero α] {d : n → α} {i j : n} (h : j ≠ i) : (diagonal d) i j = 0 := diagonal_apply_ne h.symm @[simp] theorem diagonal_zero [has_zero α] : (diagonal (λ _, 0) : matrix n n α) = 0 := by simp [diagonal]; refl @[simp] lemma diagonal_transpose [has_zero α] (v : n → α) : (diagonal v)ᵀ = diagonal v := begin ext i j, by_cases h : i = j, { simp [h, transpose] }, { simp [h, transpose, diagonal_apply_ne' h] } end @[simp] theorem diagonal_add [add_monoid α] (d₁ d₂ : n → α) : diagonal d₁ + diagonal d₂ = diagonal (λ i, d₁ i + d₂ i) := by ext i j; by_cases h : i = j; simp [h] @[simp] lemma diagonal_map [has_zero α] [has_zero β] {f : α → β} (h : f 0 = 0) {d : n → α} : (diagonal d).map f = diagonal (λ m, f (d m)) := by { ext, simp only [diagonal, map_apply], split_ifs; simp [h], } section one variables [has_zero α] [has_one α] instance : has_one (matrix n n α) := ⟨diagonal (λ _, 1)⟩ @[simp] theorem diagonal_one : (diagonal (λ _, 1) : matrix n n α) = 1 := rfl theorem one_apply {i j} : (1 : matrix n n α) i j = if i = j then 1 else 0 := rfl @[simp] theorem one_apply_eq (i) : (1 : matrix n n α) i i = 1 := diagonal_apply_eq i @[simp] theorem one_apply_ne {i j} : i ≠ j → (1 : matrix n n α) i j = 0 := diagonal_apply_ne theorem one_apply_ne' {i j} : j ≠ i → (1 : matrix n n α) i j = 0 := diagonal_apply_ne' @[simp] lemma one_map [has_zero β] [has_one β] {f : α → β} (h₀ : f 0 = 0) (h₁ : f 1 = 1) : (1 : matrix n n α).map f = (1 : matrix n n β) := by { ext, simp only [one_apply, map_apply], split_ifs; simp [h₀, h₁], } end one section numeral @[simp] lemma bit0_apply [has_add α] (M : matrix m m α) (i : m) (j : m) : (bit0 M) i j = bit0 (M i j) := rfl variables [add_monoid α] [has_one α] lemma bit1_apply (M : matrix n n α) (i : n) (j : n) : (bit1 M) i j = if i = j then bit1 (M i j) else bit0 (M i j) := by dsimp [bit1]; by_cases h : i = j; simp [h] @[simp] lemma bit1_apply_eq (M : matrix n n α) (i : n) : (bit1 M) i i = bit1 (M i i) := by simp [bit1_apply] @[simp] lemma bit1_apply_ne (M : matrix n n α) {i j : n} (h : i ≠ j) : (bit1 M) i j = bit0 (M i j) := by simp [bit1_apply, h] end numeral end diagonal section dot_product /-- `dot_product v w` is the sum of the entrywise products `v i * w i` -/ def dot_product [has_mul α] [add_comm_monoid α] (v w : m → α) : α := ∑ i, v i * w i lemma dot_product_assoc [semiring α] (u : m → α) (v : m → n → α) (w : n → α) : dot_product (λ j, dot_product u (λ i, v i j)) w = dot_product u (λ i, dot_product (v i) w) := by simpa [dot_product, finset.mul_sum, finset.sum_mul, mul_assoc] using finset.sum_comm lemma dot_product_comm [comm_semiring α] (v w : m → α) : dot_product v w = dot_product w v := by simp_rw [dot_product, mul_comm] @[simp] lemma dot_product_punit [add_comm_monoid α] [has_mul α] (v w : punit → α) : dot_product v w = v ⟨⟩ * w ⟨⟩ := by simp [dot_product] @[simp] lemma dot_product_zero [semiring α] (v : m → α) : dot_product v 0 = 0 := by simp [dot_product] @[simp] lemma dot_product_zero' [semiring α] (v : m → α) : dot_product v (λ _, 0) = 0 := dot_product_zero v @[simp] lemma zero_dot_product [semiring α] (v : m → α) : dot_product 0 v = 0 := by simp [dot_product] @[simp] lemma zero_dot_product' [semiring α] (v : m → α) : dot_product (λ _, (0 : α)) v = 0 := zero_dot_product v @[simp] lemma add_dot_product [semiring α] (u v w : m → α) : dot_product (u + v) w = dot_product u w + dot_product v w := by simp [dot_product, add_mul, finset.sum_add_distrib] @[simp] lemma dot_product_add [semiring α] (u v w : m → α) : dot_product u (v + w) = dot_product u v + dot_product u w := by simp [dot_product, mul_add, finset.sum_add_distrib] @[simp] lemma diagonal_dot_product [decidable_eq m] [semiring α] (v w : m → α) (i : m) : dot_product (diagonal v i) w = v i * w i := have ∀ j ≠ i, diagonal v i j * w j = 0 := λ j hij, by simp [diagonal_apply_ne' hij], by convert finset.sum_eq_single i (λ j _, this j) _ using 1; simp @[simp] lemma dot_product_diagonal [decidable_eq m] [semiring α] (v w : m → α) (i : m) : dot_product v (diagonal w i) = v i * w i := have ∀ j ≠ i, v j * diagonal w i j = 0 := λ j hij, by simp [diagonal_apply_ne' hij], by convert finset.sum_eq_single i (λ j _, this j) _ using 1; simp @[simp] lemma dot_product_diagonal' [decidable_eq m] [semiring α] (v w : m → α) (i : m) : dot_product v (λ j, diagonal w j i) = v i * w i := have ∀ j ≠ i, v j * diagonal w j i = 0 := λ j hij, by simp [diagonal_apply_ne hij], by convert finset.sum_eq_single i (λ j _, this j) _ using 1; simp @[simp] lemma neg_dot_product [ring α] (v w : m → α) : dot_product (-v) w = - dot_product v w := by simp [dot_product] @[simp] lemma dot_product_neg [ring α] (v w : m → α) : dot_product v (-w) = - dot_product v w := by simp [dot_product] @[simp] lemma smul_dot_product [monoid R] [semiring α] [distrib_mul_action R α] [is_scalar_tower R α α] (x : R) (v w : m → α) : dot_product (x • v) w = x • dot_product v w := by simp [dot_product, finset.smul_sum, smul_mul_assoc] @[simp] lemma dot_product_smul [monoid R] [semiring α] [distrib_mul_action R α] [smul_comm_class R α α] (x : R) (v w : m → α) : dot_product v (x • w) = x • dot_product v w := by simp [dot_product, finset.smul_sum, mul_smul_comm] end dot_product /-- `M ⬝ N` is the usual product of matrices `M` and `N`, i.e. we have that `(M ⬝ N) i k` is the dot product of the `i`-th row of `M` by the `k`-th column of `Ǹ`. -/ protected def mul [has_mul α] [add_comm_monoid α] (M : matrix l m α) (N : matrix m n α) : matrix l n α := λ i k, dot_product (λ j, M i j) (λ j, N j k) localized "infixl ` ⬝ `:75 := matrix.mul" in matrix theorem mul_apply [has_mul α] [add_comm_monoid α] {M : matrix l m α} {N : matrix m n α} {i k} : (M ⬝ N) i k = ∑ j, M i j * N j k := rfl instance [has_mul α] [add_comm_monoid α] : has_mul (matrix n n α) := ⟨matrix.mul⟩ @[simp] theorem mul_eq_mul [has_mul α] [add_comm_monoid α] (M N : matrix n n α) : M * N = M ⬝ N := rfl theorem mul_apply' [has_mul α] [add_comm_monoid α] {M N : matrix n n α} {i k} : (M ⬝ N) i k = dot_product (λ j, M i j) (λ j, N j k) := rfl section semigroup variables [semiring α] protected theorem mul_assoc (L : matrix l m α) (M : matrix m n α) (N : matrix n o α) : (L ⬝ M) ⬝ N = L ⬝ (M ⬝ N) := by { ext, apply dot_product_assoc } instance : semigroup (matrix n n α) := { mul_assoc := matrix.mul_assoc, ..matrix.has_mul } end semigroup @[simp] theorem diagonal_neg [decidable_eq n] [add_group α] (d : n → α) : -diagonal d = diagonal (λ i, -d i) := by ext i j; by_cases i = j; simp [h] section semiring variables [semiring α] @[simp] protected theorem mul_zero (M : matrix m n α) : M ⬝ (0 : matrix n o α) = 0 := by { ext i j, apply dot_product_zero } @[simp] protected theorem zero_mul (M : matrix m n α) : (0 : matrix l m α) ⬝ M = 0 := by { ext i j, apply zero_dot_product } protected theorem mul_add (L : matrix m n α) (M N : matrix n o α) : L ⬝ (M + N) = L ⬝ M + L ⬝ N := by { ext i j, apply dot_product_add } protected theorem add_mul (L M : matrix l m α) (N : matrix m n α) : (L + M) ⬝ N = L ⬝ N + M ⬝ N := by { ext i j, apply add_dot_product } @[simp] theorem diagonal_mul [decidable_eq m] (d : m → α) (M : matrix m n α) (i j) : (diagonal d).mul M i j = d i * M i j := diagonal_dot_product _ _ _ @[simp] theorem mul_diagonal [decidable_eq n] (d : n → α) (M : matrix m n α) (i j) : (M ⬝ diagonal d) i j = M i j * d j := by { rw ← diagonal_transpose, apply dot_product_diagonal } @[simp] protected theorem one_mul [decidable_eq m] (M : matrix m n α) : (1 : matrix m m α) ⬝ M = M := by ext i j; rw [← diagonal_one, diagonal_mul, one_mul] @[simp] protected theorem mul_one [decidable_eq n] (M : matrix m n α) : M ⬝ (1 : matrix n n α) = M := by ext i j; rw [← diagonal_one, mul_diagonal, mul_one] instance [decidable_eq n] : monoid (matrix n n α) := { one_mul := matrix.one_mul, mul_one := matrix.mul_one, ..matrix.has_one, ..matrix.semigroup } instance [decidable_eq n] : semiring (matrix n n α) := { mul_zero := matrix.mul_zero, zero_mul := matrix.zero_mul, left_distrib := matrix.mul_add, right_distrib := matrix.add_mul, ..matrix.add_comm_monoid, ..matrix.monoid } @[simp] theorem diagonal_mul_diagonal [decidable_eq n] (d₁ d₂ : n → α) : (diagonal d₁) ⬝ (diagonal d₂) = diagonal (λ i, d₁ i * d₂ i) := by ext i j; by_cases i = j; simp [h] theorem diagonal_mul_diagonal' [decidable_eq n] (d₁ d₂ : n → α) : diagonal d₁ * diagonal d₂ = diagonal (λ i, d₁ i * d₂ i) := diagonal_mul_diagonal _ _ @[simp] lemma map_mul {L : matrix m n α} {M : matrix n o α} [semiring β] {f : α →+* β} : (L ⬝ M).map f = L.map f ⬝ M.map f := by { ext, simp [mul_apply, ring_hom.map_sum], } lemma is_add_monoid_hom_mul_left (M : matrix l m α) : is_add_monoid_hom (λ x : matrix m n α, M ⬝ x) := { to_is_add_hom := ⟨matrix.mul_add _⟩, map_zero := matrix.mul_zero _ } lemma is_add_monoid_hom_mul_right (M : matrix m n α) : is_add_monoid_hom (λ x : matrix l m α, x ⬝ M) := { to_is_add_hom := ⟨λ _ _, matrix.add_mul _ _ _⟩, map_zero := matrix.zero_mul _ } protected lemma sum_mul (s : finset β) (f : β → matrix l m α) (M : matrix m n α) : (∑ a in s, f a) ⬝ M = ∑ a in s, f a ⬝ M := (@finset.sum_hom _ _ _ _ _ s f (λ x, x ⬝ M) M.is_add_monoid_hom_mul_right).symm protected lemma mul_sum (s : finset β) (f : β → matrix m n α) (M : matrix l m α) : M ⬝ ∑ a in s, f a = ∑ a in s, M ⬝ f a := (@finset.sum_hom _ _ _ _ _ s f (λ x, M ⬝ x) M.is_add_monoid_hom_mul_left).symm @[simp] lemma row_mul_col_apply (v w : m → α) (i j) : (row v ⬝ col w) i j = dot_product v w := rfl end semiring section homs -- TODO: there should be a way to avoid restating these for each `foo_hom`. /-- A version of `one_map` where `f` is a ring hom. -/ @[simp] lemma ring_hom_map_one [decidable_eq n] [semiring α] [semiring β] (f : α →+* β) : (1 : matrix n n α).map f = 1 := one_map f.map_zero f.map_one /-- A version of `one_map` where `f` is a `ring_equiv`. -/ @[simp] lemma ring_equiv_map_one [decidable_eq n] [semiring α] [semiring β] (f : α ≃+* β) : (1 : matrix n n α).map f = 1 := one_map f.map_zero f.map_one /-- A version of `map_zero` where `f` is a `zero_hom`. -/ @[simp] lemma zero_hom_map_zero [has_zero α] [has_zero β] (f : zero_hom α β) : (0 : matrix n n α).map f = 0 := map_zero f.map_zero /-- A version of `map_zero` where `f` is a `add_monoid_hom`. -/ @[simp] lemma add_monoid_hom_map_zero [add_monoid α] [add_monoid β] (f : α →+ β) : (0 : matrix n n α).map f = 0 := map_zero f.map_zero /-- A version of `map_zero` where `f` is a `add_equiv`. -/ @[simp] lemma add_equiv_map_zero [add_monoid α] [add_monoid β] (f : α ≃+ β) : (0 : matrix n n α).map f = 0 := map_zero f.map_zero /-- A version of `map_zero` where `f` is a `linear_map`. -/ @[simp] lemma linear_map_map_zero [semiring R] [add_comm_monoid α] [add_comm_monoid β] [module R α] [module R β] (f : α →ₗ[R] β) : (0 : matrix n n α).map f = 0 := map_zero f.map_zero /-- A version of `map_zero` where `f` is a `linear_equiv`. -/ @[simp] lemma linear_equiv_map_zero [semiring R] [add_comm_monoid α] [add_comm_monoid β] [module R α] [module R β] (f : α ≃ₗ[R] β) : (0 : matrix n n α).map f = 0 := map_zero f.map_zero /-- A version of `map_zero` where `f` is a `ring_hom`. -/ @[simp] lemma ring_hom_map_zero [semiring α] [semiring β] (f : α →+* β) : (0 : matrix n n α).map f = 0 := map_zero f.map_zero /-- A version of `map_zero` where `f` is a `ring_equiv`. -/ @[simp] lemma ring_equiv_map_zero [semiring α] [semiring β] (f : α ≃+* β) : (0 : matrix n n α).map f = 0 := map_zero f.map_zero end homs end matrix /-- The `ring_hom` between spaces of square matrices induced by a `ring_hom` between their coefficients. -/ @[simps] def ring_hom.map_matrix [decidable_eq m] [semiring α] [semiring β] (f : α →+* β) : matrix m m α →+* matrix m m β := { to_fun := λ M, M.map f, map_one' := by simp, map_mul' := λ L M, matrix.map_mul, ..(f.to_add_monoid_hom).map_matrix } open_locale matrix namespace matrix section ring variables [ring α] @[simp] theorem neg_mul (M : matrix m n α) (N : matrix n o α) : (-M) ⬝ N = -(M ⬝ N) := by { ext, apply neg_dot_product } @[simp] theorem mul_neg (M : matrix m n α) (N : matrix n o α) : M ⬝ (-N) = -(M ⬝ N) := by { ext, apply dot_product_neg } protected theorem sub_mul (M M' : matrix m n α) (N : matrix n o α) : (M - M') ⬝ N = M ⬝ N - M' ⬝ N := by rw [sub_eq_add_neg, matrix.add_mul, neg_mul, sub_eq_add_neg] protected theorem mul_sub (M : matrix m n α) (N N' : matrix n o α) : M ⬝ (N - N') = M ⬝ N - M ⬝ N' := by rw [sub_eq_add_neg, matrix.mul_add, mul_neg, sub_eq_add_neg] end ring instance [decidable_eq n] [ring α] : ring (matrix n n α) := { ..matrix.semiring, ..matrix.add_comm_group } section semiring variables [semiring α] lemma smul_eq_diagonal_mul [decidable_eq m] (M : matrix m n α) (a : α) : a • M = diagonal (λ _, a) ⬝ M := by { ext, simp } @[simp] lemma smul_mul [monoid R] [distrib_mul_action R α] [is_scalar_tower R α α] (a : R) (M : matrix m n α) (N : matrix n l α) : (a • M) ⬝ N = a • M ⬝ N := by { ext, apply smul_dot_product } /-- This instance enables use with `smul_mul_assoc`. -/ instance semiring.is_scalar_tower [decidable_eq n] [monoid R] [distrib_mul_action R α] [is_scalar_tower R α α] : is_scalar_tower R (matrix n n α) (matrix n n α) := ⟨λ r m n, matrix.smul_mul r m n⟩ @[simp] lemma mul_smul [monoid R] [distrib_mul_action R α] [smul_comm_class R α α] (M : matrix m n α) (a : R) (N : matrix n l α) : M ⬝ (a • N) = a • M ⬝ N := by { ext, apply dot_product_smul } /-- This instance enables use with `mul_smul_comm`. -/ instance semiring.smul_comm_class [decidable_eq n] [monoid R] [distrib_mul_action R α] [smul_comm_class R α α] : smul_comm_class R (matrix n n α) (matrix n n α) := ⟨λ r m n, (matrix.mul_smul m r n).symm⟩ @[simp] lemma mul_mul_left (M : matrix m n α) (N : matrix n o α) (a : α) : (λ i j, a * M i j) ⬝ N = a • (M ⬝ N) := smul_mul a M N /-- The ring homomorphism `α →+* matrix n n α` sending `a` to the diagonal matrix with `a` on the diagonal. -/ def scalar (n : Type u) [decidable_eq n] [fintype n] : α →+* matrix n n α := { to_fun := λ a, a • 1, map_one' := by simp, map_mul' := by { intros, ext, simp [mul_assoc], }, .. (smul_add_hom α _).flip (1 : matrix n n α) } section scalar variable [decidable_eq n] @[simp] lemma coe_scalar : (scalar n : α → matrix n n α) = λ a, a • 1 := rfl lemma scalar_apply_eq (a : α) (i : n) : scalar n a i i = a := by simp only [coe_scalar, smul_eq_mul, mul_one, one_apply_eq, pi.smul_apply] lemma scalar_apply_ne (a : α) (i j : n) (h : i ≠ j) : scalar n a i j = 0 := by simp only [h, coe_scalar, one_apply_ne, ne.def, not_false_iff, pi.smul_apply, smul_zero] lemma scalar_inj [nonempty n] {r s : α} : scalar n r = scalar n s ↔ r = s := begin split, { intro h, inhabit n, rw [← scalar_apply_eq r (arbitrary n), ← scalar_apply_eq s (arbitrary n), h] }, { rintro rfl, refl } end end scalar end semiring section comm_semiring variables [comm_semiring α] lemma smul_eq_mul_diagonal [decidable_eq n] (M : matrix m n α) (a : α) : a • M = M ⬝ diagonal (λ _, a) := by { ext, simp [mul_comm] } @[simp] lemma mul_mul_right (M : matrix m n α) (N : matrix n o α) (a : α) : M ⬝ (λ i j, a * N i j) = a • (M ⬝ N) := mul_smul M a N lemma scalar.commute [decidable_eq n] (r : α) (M : matrix n n α) : commute (scalar n r) M := by simp [commute, semiconj_by] end comm_semiring section semiring variables [semiring α] /-- For two vectors `w` and `v`, `vec_mul_vec w v i j` is defined to be `w i * v j`. Put another way, `vec_mul_vec w v` is exactly `col w ⬝ row v`. -/ def vec_mul_vec (w : m → α) (v : n → α) : matrix m n α | x y := w x * v y /-- `mul_vec M v` is the matrix-vector product of `M` and `v`, where `v` is seen as a column matrix. Put another way, `mul_vec M v` is the vector whose entries are those of `M ⬝ col v` (see `col_mul_vec`). -/ def mul_vec (M : matrix m n α) (v : n → α) : m → α | i := dot_product (λ j, M i j) v /-- `vec_mul v M` is the vector-matrix product of `v` and `M`, where `v` is seen as a row matrix. Put another way, `vec_mul v M` is the vector whose entries are those of `row v ⬝ M` (see `row_vec_mul`). -/ def vec_mul (v : m → α) (M : matrix m n α) : n → α | j := dot_product v (λ i, M i j) instance mul_vec.is_add_monoid_hom_left (v : n → α) : is_add_monoid_hom (λM:matrix m n α, mul_vec M v) := { map_zero := by ext; simp [mul_vec]; refl, map_add := begin intros x y, ext m, apply add_dot_product end } lemma mul_vec_diagonal [decidable_eq m] (v w : m → α) (x : m) : mul_vec (diagonal v) w x = v x * w x := diagonal_dot_product v w x lemma vec_mul_diagonal [decidable_eq m] (v w : m → α) (x : m) : vec_mul v (diagonal w) x = v x * w x := dot_product_diagonal' v w x @[simp] lemma mul_vec_one [decidable_eq m] (v : m → α) : mul_vec 1 v = v := by { ext, rw [←diagonal_one, mul_vec_diagonal, one_mul] } @[simp] lemma vec_mul_one [decidable_eq m] (v : m → α) : vec_mul v 1 = v := by { ext, rw [←diagonal_one, vec_mul_diagonal, mul_one] } @[simp] lemma mul_vec_zero (A : matrix m n α) : mul_vec A 0 = 0 := by { ext, simp [mul_vec] } @[simp] lemma vec_mul_zero (A : matrix m n α) : vec_mul 0 A = 0 := by { ext, simp [vec_mul] } @[simp] lemma vec_mul_vec_mul (v : m → α) (M : matrix m n α) (N : matrix n o α) : vec_mul (vec_mul v M) N = vec_mul v (M ⬝ N) := by { ext, apply dot_product_assoc } @[simp] lemma mul_vec_mul_vec (v : o → α) (M : matrix m n α) (N : matrix n o α) : mul_vec M (mul_vec N v) = mul_vec (M ⬝ N) v := by { ext, symmetry, apply dot_product_assoc } lemma vec_mul_vec_eq (w : m → α) (v : n → α) : vec_mul_vec w v = (col w) ⬝ (row v) := by { ext i j, simp [vec_mul_vec, mul_apply], refl } lemma smul_mul_vec_assoc (A : matrix m n α) (b : n → α) (a : α) : (a • A).mul_vec b = a • (A.mul_vec b) := by { ext, apply smul_dot_product } lemma mul_vec_add (A : matrix m n α) (x y : n → α) : A.mul_vec (x + y) = A.mul_vec x + A.mul_vec y := by { ext, apply dot_product_add } lemma add_mul_vec (A B : matrix m n α) (x : n → α) : (A + B).mul_vec x = A.mul_vec x + B.mul_vec x := by { ext, apply add_dot_product } lemma vec_mul_add (A B : matrix m n α) (x : m → α) : vec_mul x (A + B) = vec_mul x A + vec_mul x B := by { ext, apply dot_product_add } lemma add_vec_mul (A : matrix m n α) (x y : m → α) : vec_mul (x + y) A = vec_mul x A + vec_mul y A := by { ext, apply add_dot_product } variables [decidable_eq m] [decidable_eq n] /-- `std_basis_matrix i j a` is the matrix with `a` in the `i`-th row, `j`-th column, and zeroes elsewhere. -/ def std_basis_matrix (i : m) (j : n) (a : α) : matrix m n α := (λ i' j', if i' = i ∧ j' = j then a else 0) @[simp] lemma smul_std_basis_matrix (i : m) (j : n) (a b : α) : b • std_basis_matrix i j a = std_basis_matrix i j (b • a) := by { unfold std_basis_matrix, ext, simp } @[simp] lemma std_basis_matrix_zero (i : m) (j : n) : std_basis_matrix i j (0 : α) = 0 := by { unfold std_basis_matrix, ext, simp } lemma std_basis_matrix_add (i : m) (j : n) (a b : α) : std_basis_matrix i j (a + b) = std_basis_matrix i j a + std_basis_matrix i j b := begin unfold std_basis_matrix, ext, split_ifs with h; simp [h], end lemma matrix_eq_sum_std_basis (x : matrix n m α) : x = ∑ (i : n) (j : m), std_basis_matrix i j (x i j) := begin ext, symmetry, iterate 2 { rw finset.sum_apply }, convert fintype.sum_eq_single i _, { simp [std_basis_matrix] }, { intros j hj, simp [std_basis_matrix, hj.symm] } end -- TODO: tie this up with the `basis` machinery of linear algebra -- this is not completely trivial because we are indexing by two types, instead of one -- TODO: add `std_basis_vec` lemma std_basis_eq_basis_mul_basis (i : m) (j : n) : std_basis_matrix i j 1 = vec_mul_vec (λ i', ite (i = i') 1 0) (λ j', ite (j = j') 1 0) := begin ext, norm_num [std_basis_matrix, vec_mul_vec], split_ifs; tauto, end @[elab_as_eliminator] protected lemma induction_on' {X : Type*} [semiring X] {M : matrix n n X → Prop} (m : matrix n n X) (h_zero : M 0) (h_add : ∀p q, M p → M q → M (p + q)) (h_std_basis : ∀ i j x, M (std_basis_matrix i j x)) : M m := begin rw [matrix_eq_sum_std_basis m, ← finset.sum_product'], apply finset.sum_induction _ _ h_add h_zero, { intros, apply h_std_basis, } end @[elab_as_eliminator] protected lemma induction_on [nonempty n] {X : Type*} [semiring X] {M : matrix n n X → Prop} (m : matrix n n X) (h_add : ∀p q, M p → M q → M (p + q)) (h_std_basis : ∀ i j x, M (std_basis_matrix i j x)) : M m := matrix.induction_on' m begin have i : n := classical.choice (by assumption), simpa using h_std_basis i i 0, end h_add h_std_basis end semiring section ring variables [ring α] lemma neg_vec_mul (v : m → α) (A : matrix m n α) : vec_mul (-v) A = - vec_mul v A := by { ext, apply neg_dot_product } lemma vec_mul_neg (v : m → α) (A : matrix m n α) : vec_mul v (-A) = - vec_mul v A := by { ext, apply dot_product_neg } lemma neg_mul_vec (v : n → α) (A : matrix m n α) : mul_vec (-A) v = - mul_vec A v := by { ext, apply neg_dot_product } lemma mul_vec_neg (v : n → α) (A : matrix m n α) : mul_vec A (-v) = - mul_vec A v := by { ext, apply dot_product_neg } end ring section comm_semiring variables [comm_semiring α] lemma mul_vec_smul_assoc (A : matrix m n α) (b : n → α) (a : α) : A.mul_vec (a • b) = a • (A.mul_vec b) := by { ext, apply dot_product_smul } lemma mul_vec_transpose (A : matrix m n α) (x : m → α) : mul_vec Aᵀ x = vec_mul x A := by { ext, apply dot_product_comm } lemma vec_mul_transpose (A : matrix m n α) (x : n → α) : vec_mul x Aᵀ = mul_vec A x := by { ext, apply dot_product_comm } end comm_semiring section transpose open_locale matrix /-- Tell `simp` what the entries are in a transposed matrix. Compare with `mul_apply`, `diagonal_apply_eq`, etc. -/ @[simp] lemma transpose_apply (M : matrix m n α) (i j) : M.transpose j i = M i j := rfl @[simp] lemma transpose_transpose (M : matrix m n α) : Mᵀᵀ = M := by ext; refl @[simp] lemma transpose_zero [has_zero α] : (0 : matrix m n α)ᵀ = 0 := by ext i j; refl @[simp] lemma transpose_one [decidable_eq n] [has_zero α] [has_one α] : (1 : matrix n n α)ᵀ = 1 := begin ext i j, unfold has_one.one transpose, by_cases i = j, { simp only [h, diagonal_apply_eq] }, { simp only [diagonal_apply_ne h, diagonal_apply_ne (λ p, h (symm p))] } end @[simp] lemma transpose_add [has_add α] (M : matrix m n α) (N : matrix m n α) : (M + N)ᵀ = Mᵀ + Nᵀ := by { ext i j, simp } @[simp] lemma transpose_sub [add_group α] (M : matrix m n α) (N : matrix m n α) : (M - N)ᵀ = Mᵀ - Nᵀ := by { ext i j, simp } @[simp] lemma transpose_mul [comm_semiring α] (M : matrix m n α) (N : matrix n l α) : (M ⬝ N)ᵀ = Nᵀ ⬝ Mᵀ := begin ext i j, apply dot_product_comm end @[simp] lemma transpose_smul [semiring α] (c : α) (M : matrix m n α) : (c • M)ᵀ = c • Mᵀ := by { ext i j, refl } @[simp] lemma transpose_neg [has_neg α] (M : matrix m n α) : (- M)ᵀ = - Mᵀ := by ext i j; refl lemma transpose_map {f : α → β} {M : matrix m n α} : Mᵀ.map f = (M.map f)ᵀ := by { ext, refl } end transpose section star_ring variables [decidable_eq n] [semiring α] [star_ring α] /-- When `R` is a `*`-(semi)ring, `matrix n n R` becomes a `*`-(semi)ring with the star operation given by taking the conjugate, and the star of each entry. -/ instance : star_ring (matrix n n α) := { star := λ M, M.transpose.map star, star_involutive := λ M, by { ext, simp, }, star_add := λ M N, by { ext, simp, }, star_mul := λ M N, by { ext, simp [mul_apply], }, } @[simp] lemma star_apply (M : matrix n n α) (i j) : star M i j = star (M j i) := rfl lemma star_mul (M N : matrix n n α) : star (M ⬝ N) = star N ⬝ star M := star_mul _ _ end star_ring /-- `M.minor row col` is the matrix obtained by reindexing the rows and the lines of `M`, such that `M.minor row col i j = M (row i) (col j)`. Note that the total number of row/colums doesn't have to be preserved. -/ def minor (A : matrix m n α) (row : l → m) (col : o → n) : matrix l o α := λ i j, A (row i) (col j) @[simp] lemma minor_apply (A : matrix m n α) (row : l → m) (col : o → n) (i j) : A.minor row col i j = A (row i) (col j) := rfl @[simp] lemma minor_id_id (A : matrix m n α) : A.minor id id = A := ext $ λ _ _, rfl @[simp] lemma minor_minor {l₂ o₂ : Type*} [fintype l₂] [fintype o₂] (A : matrix m n α) (row₁ : l → m) (col₁ : o → n) (row₂ : l₂ → l) (col₂ : o₂ → o) : (A.minor row₁ col₁).minor row₂ col₂ = A.minor (row₁ ∘ row₂) (col₁ ∘ col₂) := ext $ λ _ _, rfl @[simp] lemma transpose_minor (A : matrix m n α) (row : l → m) (col : o → n) : (A.minor row col)ᵀ = Aᵀ.minor col row := ext $ λ _ _, rfl lemma minor_add [has_add α] (A B : matrix m n α) : ((A + B).minor : (l → m) → (o → n) → matrix l o α) = A.minor + B.minor := rfl lemma minor_neg [has_neg α] (A : matrix m n α) : ((-A).minor : (l → m) → (o → n) → matrix l o α) = -A.minor := rfl lemma minor_sub [has_sub α] (A B : matrix m n α) : ((A - B).minor : (l → m) → (o → n) → matrix l o α) = A.minor - B.minor := rfl @[simp] lemma minor_zero [has_zero α] : ((0 : matrix m n α).minor : (l → m) → (o → n) → matrix l o α) = 0 := rfl lemma minor_smul {R : Type*} [semiring R] [add_comm_monoid α] [module R α] (r : R) (A : matrix m n α) : ((r • A : matrix m n α).minor : (l → m) → (o → n) → matrix l o α) = r • A.minor := rfl /-- If the minor doesn't repeat elements, then when applied to a diagonal matrix the result is diagonal. -/ lemma minor_diagonal [has_zero α] [decidable_eq m] [decidable_eq l] (d : m → α) (e : l → m) (he : function.injective e) : (diagonal d).minor e e = diagonal (d ∘ e) := ext $ λ i j, begin rw minor_apply, by_cases h : i = j, { rw [h, diagonal_apply_eq, diagonal_apply_eq], }, { rw [diagonal_apply_ne h, diagonal_apply_ne (he.ne h)], }, end lemma minor_one [has_zero α] [has_one α] [decidable_eq m] [decidable_eq l] (e : l → m) (he : function.injective e) : (1 : matrix m m α).minor e e = 1 := minor_diagonal _ e he lemma minor_mul [semiring α] {p q : Type*} [fintype p] [fintype q] (M : matrix m n α) (N : matrix n p α) (e₁ : l → m) (e₂ : o → n) (e₃ : q → p) (he₂ : function.bijective e₂) : (M ⬝ N).minor e₁ e₃ = (M.minor e₁ e₂) ⬝ (N.minor e₂ e₃) := ext $ λ _ _, (he₂.sum_comp _).symm /-! `simp` lemmas for `matrix.minor`s interaction with `matrix.diagonal`, `1`, and `matrix.mul` for when the mappings are bundled. -/ @[simp] lemma minor_diagonal_embedding [has_zero α] [decidable_eq m] [decidable_eq l] (d : m → α) (e : l ↪ m) : (diagonal d).minor e e = diagonal (d ∘ e) := minor_diagonal d e e.injective @[simp] lemma minor_diagonal_equiv [has_zero α] [decidable_eq m] [decidable_eq l] (d : m → α) (e : l ≃ m) : (diagonal d).minor e e = diagonal (d ∘ e) := minor_diagonal d e e.injective @[simp] lemma minor_one_embedding [has_zero α] [has_one α] [decidable_eq m] [decidable_eq l] (e : l ↪ m) : (1 : matrix m m α).minor e e = 1 := minor_one e e.injective @[simp] lemma minor_one_equiv [has_zero α] [has_one α] [decidable_eq m] [decidable_eq l] (e : l ≃ m) : (1 : matrix m m α).minor e e = 1 := minor_one e e.injective lemma minor_mul_equiv [semiring α] {p q : Type*} [fintype p] [fintype q] (M : matrix m n α) (N : matrix n p α) (e₁ : l → m) (e₂ : o ≃ n) (e₃ : q → p) : (M ⬝ N).minor e₁ e₃ = (M.minor e₁ e₂) ⬝ (N.minor e₂ e₃) := minor_mul M N e₁ e₂ e₃ e₂.bijective /-- The natural map that reindexes a matrix's rows and columns with equivalent types is an equivalence. -/ def reindex (eₘ : m ≃ l) (eₙ : n ≃ o) : matrix m n α ≃ matrix l o α := { to_fun := λ M, M.minor eₘ.symm eₙ.symm, inv_fun := λ M, M.minor eₘ eₙ, left_inv := λ M, by simp, right_inv := λ M, by simp, } @[simp] lemma reindex_apply (eₘ : m ≃ l) (eₙ : n ≃ o) (M : matrix m n α) : reindex eₘ eₙ M = M.minor eₘ.symm eₙ.symm := rfl @[simp] lemma reindex_refl_refl (A : matrix m n α) : reindex (equiv.refl _) (equiv.refl _) A = A := A.minor_id_id @[simp] lemma reindex_symm (eₘ : m ≃ l) (eₙ : n ≃ o) : (reindex eₘ eₙ).symm = (reindex eₘ.symm eₙ.symm : matrix l o α ≃ _) := rfl @[simp] lemma reindex_trans {l₂ o₂ : Type*} [fintype l₂] [fintype o₂] (eₘ : m ≃ l) (eₙ : n ≃ o) (eₘ₂ : l ≃ l₂) (eₙ₂ : o ≃ o₂) : (reindex eₘ eₙ).trans (reindex eₘ₂ eₙ₂) = (reindex (eₘ.trans eₘ₂) (eₙ.trans eₙ₂) : matrix m n α ≃ _) := equiv.ext $ λ A, (A.minor_minor eₘ.symm eₙ.symm eₘ₂.symm eₙ₂.symm : _) lemma transpose_reindex (eₘ : m ≃ l) (eₙ : n ≃ o) (M : matrix m n α) : (reindex eₘ eₙ M)ᵀ = (reindex eₙ eₘ Mᵀ) := rfl /-- The left `n × l` part of a `n × (l+r)` matrix. -/ @[reducible] def sub_left {m l r : nat} (A : matrix (fin m) (fin (l + r)) α) : matrix (fin m) (fin l) α := minor A id (fin.cast_add r) /-- The right `n × r` part of a `n × (l+r)` matrix. -/ @[reducible] def sub_right {m l r : nat} (A : matrix (fin m) (fin (l + r)) α) : matrix (fin m) (fin r) α := minor A id (fin.nat_add l) /-- The top `u × n` part of a `(u+d) × n` matrix. -/ @[reducible] def sub_up {d u n : nat} (A : matrix (fin (u + d)) (fin n) α) : matrix (fin u) (fin n) α := minor A (fin.cast_add d) id /-- The bottom `d × n` part of a `(u+d) × n` matrix. -/ @[reducible] def sub_down {d u n : nat} (A : matrix (fin (u + d)) (fin n) α) : matrix (fin d) (fin n) α := minor A (fin.nat_add u) id /-- The top-right `u × r` part of a `(u+d) × (l+r)` matrix. -/ @[reducible] def sub_up_right {d u l r : nat} (A: matrix (fin (u + d)) (fin (l + r)) α) : matrix (fin u) (fin r) α := sub_up (sub_right A) /-- The bottom-right `d × r` part of a `(u+d) × (l+r)` matrix. -/ @[reducible] def sub_down_right {d u l r : nat} (A : matrix (fin (u + d)) (fin (l + r)) α) : matrix (fin d) (fin r) α := sub_down (sub_right A) /-- The top-left `u × l` part of a `(u+d) × (l+r)` matrix. -/ @[reducible] def sub_up_left {d u l r : nat} (A : matrix (fin (u + d)) (fin (l + r)) α) : matrix (fin u) (fin (l)) α := sub_up (sub_left A) /-- The bottom-left `d × l` part of a `(u+d) × (l+r)` matrix. -/ @[reducible] def sub_down_left {d u l r : nat} (A: matrix (fin (u + d)) (fin (l + r)) α) : matrix (fin d) (fin (l)) α := sub_down (sub_left A) section row_col /-! ### `row_col` section Simplification lemmas for `matrix.row` and `matrix.col`. -/ open_locale matrix @[simp] lemma col_add [semiring α] (v w : m → α) : col (v + w) = col v + col w := by { ext, refl } @[simp] lemma col_smul [semiring α] (x : α) (v : m → α) : col (x • v) = x • col v := by { ext, refl } @[simp] lemma row_add [semiring α] (v w : m → α) : row (v + w) = row v + row w := by { ext, refl } @[simp] lemma row_smul [semiring α] (x : α) (v : m → α) : row (x • v) = x • row v := by { ext, refl } @[simp] lemma col_apply (v : m → α) (i j) : matrix.col v i j = v i := rfl @[simp] lemma row_apply (v : m → α) (i j) : matrix.row v i j = v j := rfl @[simp] lemma transpose_col (v : m → α) : (matrix.col v).transpose = matrix.row v := by {ext, refl} @[simp] lemma transpose_row (v : m → α) : (matrix.row v).transpose = matrix.col v := by {ext, refl} lemma row_vec_mul [semiring α] (M : matrix m n α) (v : m → α) : matrix.row (matrix.vec_mul v M) = matrix.row v ⬝ M := by {ext, refl} lemma col_vec_mul [semiring α] (M : matrix m n α) (v : m → α) : matrix.col (matrix.vec_mul v M) = (matrix.row v ⬝ M)ᵀ := by {ext, refl} lemma col_mul_vec [semiring α] (M : matrix m n α) (v : n → α) : matrix.col (matrix.mul_vec M v) = M ⬝ matrix.col v := by {ext, refl} lemma row_mul_vec [semiring α] (M : matrix m n α) (v : n → α) : matrix.row (matrix.mul_vec M v) = (M ⬝ matrix.col v)ᵀ := by {ext, refl} end row_col section update /-- Update, i.e. replace the `i`th row of matrix `A` with the values in `b`. -/ def update_row [decidable_eq n] (M : matrix n m α) (i : n) (b : m → α) : matrix n m α := function.update M i b /-- Update, i.e. replace the `j`th column of matrix `A` with the values in `b`. -/ def update_column [decidable_eq m] (M : matrix n m α) (j : m) (b : n → α) : matrix n m α := λ i, function.update (M i) j (b i) variables {M : matrix n m α} {i : n} {j : m} {b : m → α} {c : n → α} @[simp] lemma update_row_self [decidable_eq n] : update_row M i b i = b := function.update_same i b M @[simp] lemma update_column_self [decidable_eq m] : update_column M j c i j = c i := function.update_same j (c i) (M i) @[simp] lemma update_row_ne [decidable_eq n] {i' : n} (i_ne : i' ≠ i) : update_row M i b i' = M i' := function.update_noteq i_ne b M @[simp] lemma update_column_ne [decidable_eq m] {j' : m} (j_ne : j' ≠ j) : update_column M j c i j' = M i j' := function.update_noteq j_ne (c i) (M i) lemma update_row_apply [decidable_eq n] {i' : n} : update_row M i b i' j = if i' = i then b j else M i' j := begin by_cases i' = i, { rw [h, update_row_self, if_pos rfl] }, { rwa [update_row_ne h, if_neg h] } end lemma update_column_apply [decidable_eq m] {j' : m} : update_column M j c i j' = if j' = j then c i else M i j' := begin by_cases j' = j, { rw [h, update_column_self, if_pos rfl] }, { rwa [update_column_ne h, if_neg h] } end lemma update_row_transpose [decidable_eq m] : update_row Mᵀ j c = (update_column M j c)ᵀ := begin ext i' j, rw [transpose_apply, update_row_apply, update_column_apply], refl end lemma update_column_transpose [decidable_eq n] : update_column Mᵀ i b = (update_row M i b)ᵀ := begin ext i' j, rw [transpose_apply, update_row_apply, update_column_apply], refl end @[simp] lemma update_row_eq_self [decidable_eq m] (A : matrix m n α) {i : m} : A.update_row i (A i) = A := function.update_eq_self i A @[simp] lemma update_column_eq_self [decidable_eq n] (A : matrix m n α) {i : n} : A.update_column i (λ j, A j i) = A := funext $ λ j, function.update_eq_self i (A j) end update section block_matrices /-- We can form a single large matrix by flattening smaller 'block' matrices of compatible dimensions. -/ def from_blocks (A : matrix n l α) (B : matrix n m α) (C : matrix o l α) (D : matrix o m α) : matrix (n ⊕ o) (l ⊕ m) α := sum.elim (λ i, sum.elim (A i) (B i)) (λ i, sum.elim (C i) (D i)) @[simp] lemma from_blocks_apply₁₁ (A : matrix n l α) (B : matrix n m α) (C : matrix o l α) (D : matrix o m α) (i : n) (j : l) : from_blocks A B C D (sum.inl i) (sum.inl j) = A i j := rfl @[simp] lemma from_blocks_apply₁₂ (A : matrix n l α) (B : matrix n m α) (C : matrix o l α) (D : matrix o m α) (i : n) (j : m) : from_blocks A B C D (sum.inl i) (sum.inr j) = B i j := rfl @[simp] lemma from_blocks_apply₂₁ (A : matrix n l α) (B : matrix n m α) (C : matrix o l α) (D : matrix o m α) (i : o) (j : l) : from_blocks A B C D (sum.inr i) (sum.inl j) = C i j := rfl @[simp] lemma from_blocks_apply₂₂ (A : matrix n l α) (B : matrix n m α) (C : matrix o l α) (D : matrix o m α) (i : o) (j : m) : from_blocks A B C D (sum.inr i) (sum.inr j) = D i j := rfl /-- Given a matrix whose row and column indexes are sum types, we can extract the corresponding "top left" submatrix. -/ def to_blocks₁₁ (M : matrix (n ⊕ o) (l ⊕ m) α) : matrix n l α := λ i j, M (sum.inl i) (sum.inl j) /-- Given a matrix whose row and column indexes are sum types, we can extract the corresponding "top right" submatrix. -/ def to_blocks₁₂ (M : matrix (n ⊕ o) (l ⊕ m) α) : matrix n m α := λ i j, M (sum.inl i) (sum.inr j) /-- Given a matrix whose row and column indexes are sum types, we can extract the corresponding "bottom left" submatrix. -/ def to_blocks₂₁ (M : matrix (n ⊕ o) (l ⊕ m) α) : matrix o l α := λ i j, M (sum.inr i) (sum.inl j) /-- Given a matrix whose row and column indexes are sum types, we can extract the corresponding "bottom right" submatrix. -/ def to_blocks₂₂ (M : matrix (n ⊕ o) (l ⊕ m) α) : matrix o m α := λ i j, M (sum.inr i) (sum.inr j) lemma from_blocks_to_blocks (M : matrix (n ⊕ o) (l ⊕ m) α) : from_blocks M.to_blocks₁₁ M.to_blocks₁₂ M.to_blocks₂₁ M.to_blocks₂₂ = M := begin ext i j, rcases i; rcases j; refl, end @[simp] lemma to_blocks_from_blocks₁₁ (A : matrix n l α) (B : matrix n m α) (C : matrix o l α) (D : matrix o m α) : (from_blocks A B C D).to_blocks₁₁ = A := rfl @[simp] lemma to_blocks_from_blocks₁₂ (A : matrix n l α) (B : matrix n m α) (C : matrix o l α) (D : matrix o m α) : (from_blocks A B C D).to_blocks₁₂ = B := rfl @[simp] lemma to_blocks_from_blocks₂₁ (A : matrix n l α) (B : matrix n m α) (C : matrix o l α) (D : matrix o m α) : (from_blocks A B C D).to_blocks₂₁ = C := rfl @[simp] lemma to_blocks_from_blocks₂₂ (A : matrix n l α) (B : matrix n m α) (C : matrix o l α) (D : matrix o m α) : (from_blocks A B C D).to_blocks₂₂ = D := rfl lemma from_blocks_transpose (A : matrix n l α) (B : matrix n m α) (C : matrix o l α) (D : matrix o m α) : (from_blocks A B C D)ᵀ = from_blocks Aᵀ Cᵀ Bᵀ Dᵀ := begin ext i j, rcases i; rcases j; simp [from_blocks], end /-- Let `p` pick out certain rows and `q` pick out certain columns of a matrix `M`. Then `to_block M p q` is the corresponding block matrix. -/ def to_block (M : matrix m n α) (p : m → Prop) [decidable_pred p] (q : n → Prop) [decidable_pred q] : matrix {a // p a} {a // q a} α := M.minor coe coe @[simp] lemma to_block_apply (M : matrix m n α) (p : m → Prop) [decidable_pred p] (q : n → Prop) [decidable_pred q] (i : {a // p a}) (j : {a // q a}) : to_block M p q i j = M ↑i ↑j := rfl /-- Let `b` map rows and columns of a square matrix `M` to blocks. Then `to_square_block M b k` is the block `k` matrix. -/ def to_square_block (M : matrix m m α) {n : nat} (b : m → fin n) (k : fin n) : matrix {a // b a = k} {a // b a = k} α := M.minor coe coe @[simp] lemma to_square_block_def (M : matrix m m α) {n : nat} (b : m → fin n) (k : fin n) : to_square_block M b k = λ i j, M ↑i ↑j := rfl /-- Alternate version with `b : m → nat`. Let `b` map rows and columns of a square matrix `M` to blocks. Then `to_square_block' M b k` is the block `k` matrix. -/ def to_square_block' (M : matrix m m α) (b : m → nat) (k : nat) : matrix {a // b a = k} {a // b a = k} α := M.minor coe coe @[simp] lemma to_square_block_def' (M : matrix m m α) (b : m → nat) (k : nat) : to_square_block' M b k = λ i j, M ↑i ↑j := rfl /-- Let `p` pick out certain rows and columns of a square matrix `M`. Then `to_square_block_prop M p` is the corresponding block matrix. -/ def to_square_block_prop (M : matrix m m α) (p : m → Prop) [decidable_pred p] : matrix {a // p a} {a // p a} α := M.minor coe coe @[simp] lemma to_square_block_prop_def (M : matrix m m α) (p : m → Prop) [decidable_pred p] : to_square_block_prop M p = λ i j, M ↑i ↑j := rfl variables [semiring α] lemma from_blocks_smul (x : α) (A : matrix n l α) (B : matrix n m α) (C : matrix o l α) (D : matrix o m α) : x • (from_blocks A B C D) = from_blocks (x • A) (x • B) (x • C) (x • D) := begin ext i j, rcases i; rcases j; simp [from_blocks], end lemma from_blocks_add (A : matrix n l α) (B : matrix n m α) (C : matrix o l α) (D : matrix o m α) (A' : matrix n l α) (B' : matrix n m α) (C' : matrix o l α) (D' : matrix o m α) : (from_blocks A B C D) + (from_blocks A' B' C' D') = from_blocks (A + A') (B + B') (C + C') (D + D') := begin ext i j, rcases i; rcases j; refl, end lemma from_blocks_multiply {p q : Type*} [fintype p] [fintype q] (A : matrix n l α) (B : matrix n m α) (C : matrix o l α) (D : matrix o m α) (A' : matrix l p α) (B' : matrix l q α) (C' : matrix m p α) (D' : matrix m q α) : (from_blocks A B C D) ⬝ (from_blocks A' B' C' D') = from_blocks (A ⬝ A' + B ⬝ C') (A ⬝ B' + B ⬝ D') (C ⬝ A' + D ⬝ C') (C ⬝ B' + D ⬝ D') := begin ext i j, rcases i; rcases j; simp only [from_blocks, mul_apply, fintype.sum_sum_type, sum.elim_inl, sum.elim_inr, pi.add_apply], end variables [decidable_eq l] [decidable_eq m] @[simp] lemma from_blocks_diagonal (d₁ : l → α) (d₂ : m → α) : from_blocks (diagonal d₁) 0 0 (diagonal d₂) = diagonal (sum.elim d₁ d₂) := begin ext i j, rcases i; rcases j; simp [diagonal], end @[simp] lemma from_blocks_one : from_blocks (1 : matrix l l α) 0 0 (1 : matrix m m α) = 1 := by { ext i j, rcases i; rcases j; simp [one_apply] } end block_matrices section block_diagonal variables (M N : o → matrix m n α) [decidable_eq o] section has_zero variables [has_zero α] /-- `matrix.block_diagonal M` turns a homogenously-indexed collection of matrices `M : o → matrix m n α'` into a `m × o`-by-`n × o` block matrix which has the entries of `M` along the diagonal and zero elsewhere. See also `matrix.block_diagonal'` if the matrices may not have the same size everywhere. -/ def block_diagonal : matrix (m × o) (n × o) α | ⟨i, k⟩ ⟨j, k'⟩ := if k = k' then M k i j else 0 lemma block_diagonal_apply (ik jk) : block_diagonal M ik jk = if ik.2 = jk.2 then M ik.2 ik.1 jk.1 else 0 := by { cases ik, cases jk, refl } @[simp] lemma block_diagonal_apply_eq (i j k) : block_diagonal M (i, k) (j, k) = M k i j := if_pos rfl lemma block_diagonal_apply_ne (i j) {k k'} (h : k ≠ k') : block_diagonal M (i, k) (j, k') = 0 := if_neg h @[simp] lemma block_diagonal_transpose : (block_diagonal M)ᵀ = block_diagonal (λ k, (M k)ᵀ) := begin ext, simp only [transpose_apply, block_diagonal_apply, eq_comm], split_ifs with h, { rw h }, { refl } end @[simp] lemma block_diagonal_zero : block_diagonal (0 : o → matrix m n α) = 0 := by { ext, simp [block_diagonal_apply] } @[simp] lemma block_diagonal_diagonal [decidable_eq m] (d : o → m → α) : block_diagonal (λ k, diagonal (d k)) = diagonal (λ ik, d ik.2 ik.1) := begin ext ⟨i, k⟩ ⟨j, k'⟩, simp only [block_diagonal_apply, diagonal], split_ifs; finish end @[simp] lemma block_diagonal_one [decidable_eq m] [has_one α] : block_diagonal (1 : o → matrix m m α) = 1 := show block_diagonal (λ (_ : o), diagonal (λ (_ : m), (1 : α))) = diagonal (λ _, 1), by rw [block_diagonal_diagonal] end has_zero @[simp] lemma block_diagonal_add [add_monoid α] : block_diagonal (M + N) = block_diagonal M + block_diagonal N := begin ext, simp only [block_diagonal_apply, add_apply], split_ifs; simp end @[simp] lemma block_diagonal_neg [add_group α] : block_diagonal (-M) = - block_diagonal M := begin ext, simp only [block_diagonal_apply, neg_apply], split_ifs; simp end @[simp] lemma block_diagonal_sub [add_group α] : block_diagonal (M - N) = block_diagonal M - block_diagonal N := by simp [sub_eq_add_neg] @[simp] lemma block_diagonal_mul {p : Type*} [fintype p] [semiring α] (N : o → matrix n p α) : block_diagonal (λ k, M k ⬝ N k) = block_diagonal M ⬝ block_diagonal N := begin ext ⟨i, k⟩ ⟨j, k'⟩, simp only [block_diagonal_apply, mul_apply, ← finset.univ_product_univ, finset.sum_product], split_ifs with h; simp [h] end @[simp] lemma block_diagonal_smul {R : Type*} [semiring R] [add_comm_monoid α] [module R α] (x : R) : block_diagonal (x • M) = x • block_diagonal M := by { ext, simp only [block_diagonal_apply, pi.smul_apply], split_ifs; simp } end block_diagonal section block_diagonal' variables (M N : Π i, matrix (m' i) (n' i) α) [decidable_eq o] section has_zero variables [has_zero α] /-- `matrix.block_diagonal' M` turns `M : Π i, matrix (m i) (n i) α` into a `Σ i, m i`-by-`Σ i, n i` block matrix which has the entries of `M` along the diagonal and zero elsewhere. This is the dependently-typed version of `matrix.block_diagonal`. -/ def block_diagonal' : matrix (Σ i, m' i) (Σ i, n' i) α | ⟨k, i⟩ ⟨k', j⟩ := if h : k = k' then M k i (cast (congr_arg n' h.symm) j) else 0 lemma block_diagonal'_eq_block_diagonal (M : o → matrix m n α) {k k'} (i j) : block_diagonal M (i, k) (j, k') = block_diagonal' M ⟨k, i⟩ ⟨k', j⟩ := rfl lemma block_diagonal'_minor_eq_block_diagonal (M : o → matrix m n α) : (block_diagonal' M).minor (prod.to_sigma ∘ prod.swap) (prod.to_sigma ∘ prod.swap) = block_diagonal M := matrix.ext $ λ ⟨k, i⟩ ⟨k', j⟩, rfl lemma block_diagonal'_apply (ik jk) : block_diagonal' M ik jk = if h : ik.1 = jk.1 then M ik.1 ik.2 (cast (congr_arg n' h.symm) jk.2) else 0 := by { cases ik, cases jk, refl } @[simp] lemma block_diagonal'_apply_eq (k i j) : block_diagonal' M ⟨k, i⟩ ⟨k, j⟩ = M k i j := dif_pos rfl lemma block_diagonal'_apply_ne {k k'} (i j) (h : k ≠ k') : block_diagonal' M ⟨k, i⟩ ⟨k', j⟩ = 0 := dif_neg h @[simp] lemma block_diagonal'_transpose : (block_diagonal' M)ᵀ = block_diagonal' (λ k, (M k)ᵀ) := begin ext ⟨ii, ix⟩ ⟨ji, jx⟩, simp only [transpose_apply, block_diagonal'_apply, eq_comm], dsimp only, split_ifs with h₁ h₂ h₂, { subst h₁, refl, }, { exact (h₂ h₁.symm).elim }, { exact (h₁ h₂.symm).elim }, { refl } end @[simp] lemma block_diagonal'_zero : block_diagonal' (0 : Π i, matrix (m' i) (n' i) α) = 0 := by { ext, simp [block_diagonal'_apply] } @[simp] lemma block_diagonal'_diagonal [∀ i, decidable_eq (m' i)] (d : Π i, m' i → α) : block_diagonal' (λ k, diagonal (d k)) = diagonal (λ ik, d ik.1 ik.2) := begin ext ⟨i, k⟩ ⟨j, k'⟩, simp only [block_diagonal'_apply, diagonal], split_ifs; finish end @[simp] lemma block_diagonal'_one [∀ i, decidable_eq (m' i)] [has_one α] : block_diagonal' (1 : Π i, matrix (m' i) (m' i) α) = 1 := show block_diagonal' (λ (i : o), diagonal (λ (_ : m' i), (1 : α))) = diagonal (λ _, 1), by rw [block_diagonal'_diagonal] end has_zero @[simp] lemma block_diagonal'_add [add_monoid α] : block_diagonal' (M + N) = block_diagonal' M + block_diagonal' N := begin ext, simp only [block_diagonal'_apply, add_apply], split_ifs; simp end @[simp] lemma block_diagonal'_neg [add_group α] : block_diagonal' (-M) = - block_diagonal' M := begin ext, simp only [block_diagonal'_apply, neg_apply], split_ifs; simp end @[simp] lemma block_diagonal'_sub [add_group α] : block_diagonal' (M - N) = block_diagonal' M - block_diagonal' N := by simp [sub_eq_add_neg] @[simp] lemma block_diagonal'_mul {p : o → Type*} [Π i, fintype (p i)] [semiring α] (N : Π i, matrix (n' i) (p i) α) : block_diagonal' (λ k, M k ⬝ N k) = block_diagonal' M ⬝ block_diagonal' N := begin ext ⟨k, i⟩ ⟨k', j⟩, simp only [block_diagonal'_apply, mul_apply, ← finset.univ_sigma_univ, finset.sum_sigma], rw fintype.sum_eq_single k, { split_ifs; simp }, { intros j' hj', exact finset.sum_eq_zero (λ _ _, by rw [dif_neg hj'.symm, zero_mul]) }, end @[simp] lemma block_diagonal'_smul {R : Type*} [semiring R] [add_comm_monoid α] [module R α] (x : R) : block_diagonal' (x • M) = x • block_diagonal' M := by { ext, simp only [block_diagonal'_apply, pi.smul_apply], split_ifs; simp } end block_diagonal' end matrix namespace ring_hom variables [semiring α] [semiring β] lemma map_matrix_mul (M : matrix m n α) (N : matrix n o α) (i : m) (j : o) (f : α →+* β) : f (matrix.mul M N i j) = matrix.mul (λ i j, f (M i j)) (λ i j, f (N i j)) i j := by simp [matrix.mul_apply, ring_hom.map_sum] end ring_hom
25afc4882ab22b6f93182770f74394c0cfb07991
a8c03ed21a1bd6fc45901943b79dd6574ea3f0c2
/prover_state.lean
aa14d5a7af67a4fcca5090acc9361e2b1307193d
[]
no_license
gebner/resolution.lean
716c355fbb5204e5c4d0c5a7f3f3cc825892a2bf
c6fafe06fba1cfad73db68f2aa474b29fe892a2b
refs/heads/master
1,601,111,444,528
1,475,256,701,000
1,475,256,701,000
67,711,151
0
0
null
null
null
null
UTF-8
Lean
false
false
13,900
lean
import clause lpo cdcl_solver open tactic monad expr meta structure locked_cls := (id : name) (c : clause) (assertions : list expr) (reasons : list (list expr)) namespace locked_cls meta instance : has_to_tactic_format locked_cls := ⟨λc, do c_fmt ← pp c↣c, ass_fmt ← pp (c↣assertions↣for (λa, a↣local_type)), reasons_fmt ← pp (c↣reasons↣for (λr, r↣for (λa, a↣local_type))), return $ c_fmt ++ " <-- " ++ ass_fmt ++ " (reasons: " ++ reasons_fmt ++ ")" ⟩ end locked_cls meta structure active_cls := (id : name) (selected : list nat) (c : clause) (assertions : list expr) (from_model : bool) namespace active_cls meta instance : has_to_tactic_format active_cls := ⟨λc, do c_fmt ← pp c↣c, ass_fmt ← pp (c↣assertions↣for (λa, a↣local_type)), return $ c_fmt ++ " <-- " ++ ass_fmt ++ " (selected: " ++ to_fmt c↣selected ++ ", model: " ++ to_fmt c↣from_model ++ ")" ⟩ meta def clause_with_assertions (ac : active_cls) : clause := ac↣c↣close_constn ac↣assertions end active_cls meta structure passive_cls := (c : clause) (assertions : list expr) (from_model : bool) namespace passive_cls meta instance : has_to_tactic_format passive_cls := ⟨λc, pp c↣c⟩ meta def clause_with_assertions (pc : passive_cls) : clause := pc↣c↣close_constn pc↣assertions end passive_cls meta structure resolution_prover_state := (active : rb_map name active_cls) (passive : rb_map name passive_cls) (newly_derived : list clause) (prec : list expr) (locked : list locked_cls) (sat_solver : cdcl.state) (current_model : rb_map expr bool) (sat_hyps : rb_map expr (expr × expr)) (needs_sat_run : bool) (age : nat) open resolution_prover_state private meta def join_with_nl : list format → format := list.foldl (λx y, x ++ format.line ++ y) format.nil private meta def resolution_prover_state_tactic_fmt (s : resolution_prover_state) : tactic format := do active_fmts ← mapM pp (rb_map.values s↣active), passive_fmts ← mapM pp (rb_map.values s↣passive), new_fmts ← mapM pp s↣newly_derived, locked_fmts ← mapM pp s↣locked, sat_fmts ← mapM pp s↣sat_solver↣given, prec_fmts ← mapM pp s↣prec, return (join_with_nl ([to_fmt "active:"] ++ map (append (to_fmt " ")) active_fmts ++ [to_fmt "passive:"] ++ map (append (to_fmt " ")) passive_fmts ++ [to_fmt "new:"] ++ map (append (to_fmt " ")) new_fmts ++ [to_fmt "locked:"] ++ map (append (to_fmt " ")) locked_fmts ++ [to_fmt "sat formulas:"] ++ map (append (to_fmt " ")) sat_fmts ++ [to_fmt "precedence order: " ++ to_fmt prec_fmts])) meta instance : has_to_tactic_format resolution_prover_state := ⟨resolution_prover_state_tactic_fmt⟩ meta def resolution_prover := stateT resolution_prover_state tactic meta instance : monad resolution_prover := stateT.monad _ _ meta def resolution_prover_of_tactic {a} (tac : tactic a) : resolution_prover a := λs, do res ← tac, return (res, s) meta instance : has_coe_fam tactic resolution_prover := ⟨λa, resolution_prover_of_tactic⟩ meta def resolution_prover.fail {A B : Type} [has_to_format B] (msg : B) : resolution_prover A := @tactic.fail A _ _ msg meta def resolution_prover.failed {A : Type} : resolution_prover A := resolution_prover.fail "failed" meta def resolution_prover.orelse {A : Type} (p1 p2 : resolution_prover A) : resolution_prover A := take state, p1 state <|> p2 state meta instance : alternative resolution_prover := alternative.mk (@monad.map _ _) (@applicative.pure _ (monad_is_applicative resolution_prover)) (@applicative.seq _ (monad_is_applicative resolution_prover)) @resolution_prover.failed @resolution_prover.orelse meta def selection_strategy := passive_cls → resolution_prover (list nat) meta def get_active : resolution_prover (rb_map name active_cls) := do state ← stateT.read, return state↣active meta def add_active (a : active_cls) : resolution_prover unit := do state ← stateT.read, stateT.write { state with active := state↣active↣insert a↣id a } meta def get_passive : resolution_prover (rb_map name passive_cls) := liftM passive stateT.read meta def in_sat_solver {A} (cmd : cdcl.solver A) : resolution_prover A := do state ← stateT.read, result : A × cdcl.state ← ↑(cmd state↣sat_solver), stateT.write { state with sat_solver := result↣2 }, return result↣1 meta def mk_sat_var (v : expr) (suggested_ph : bool) : resolution_prover unit := do st ← stateT.read, if st↣sat_hyps↣contains v then return () else do hpv ← ↑mk_fresh_name, hnv ← ↑mk_fresh_name, univ ← ↑(infer_univ v), stateT.modify $ λst, { st with sat_hyps := st↣sat_hyps↣insert v (local_const hpv hpv binder_info.default v, local_const hnv hnv binder_info.default (if univ = level.zero then not_ v else imp v false_)) }, in_sat_solver $ cdcl.mk_var_core v suggested_ph meta def get_sat_hyp_core (v : expr) (ph : bool) : resolution_prover (option expr) := flip liftM stateT.read $ λst, match st↣sat_hyps↣find v with | some (hp, hn) := some $ if ph then hp else hn | none := none end meta def get_sat_hyp (v : expr) (ph : bool) : resolution_prover expr := do hyp_opt ← get_sat_hyp_core v ph, match hyp_opt with | some hyp := return hyp | none := resolution_prover.fail $ "unknown sat variable: " ++ v↣to_string end meta def add_sat_clause (c : clause) : resolution_prover unit := do already_added ← flip liftM stateT.read (λst, decidable.to_bool $ c↣type ∈ st↣sat_solver↣given↣for (λd, d↣type)), if already_added then return () else do forM c↣get_lits $ λl, mk_sat_var l↣formula l↣is_neg, in_sat_solver $ cdcl.mk_clause c, stateT.modify $ λst, { st with needs_sat_run := tt } meta def sat_eval_lit (v : expr) (pol : bool) : resolution_prover bool := do v_st ← flip liftM stateT.read $ λst, st↣current_model↣find v, match v_st with | some ph := return $ if pol then ph else bnot ph | none := return tt end meta def sat_eval_assertion (assertion : expr) : resolution_prover bool := match is_not assertion↣local_type with | some v := sat_eval_lit v ff | none := sat_eval_lit assertion↣local_type tt end meta def sat_eval_assertions : list expr → resolution_prover bool | (a::ass) := do v_a ← sat_eval_assertion a, if v_a then sat_eval_assertions ass else return ff | [] := return tt private meta def get_new_cls_id : resolution_prover name := do state ← stateT.read, stateT.write { state with age := state↣age + 1 }, cls_prefix ← ↑(get_unused_name `clause none), return $ mk_num_name cls_prefix state↣age meta def collect_ass_hyps (c : clause) : resolution_prover (list expr) := let lcs := contained_lconsts c↣proof in do st ← stateT.read, return (do hs ← st↣sat_hyps↣values, h ← [hs↣1, hs↣2], guard $ lcs↣contains h↣local_uniq_name, [h]) meta def register_as_passive (c : clause) : resolution_prover unit := do ass ← collect_ass_hyps c, ass_v ← sat_eval_assertions ass, id ← get_new_cls_id, c' ← return $ c↣close_constn ass, @coe _ (resolution_prover unit) _ (assertv id c'↣type c'↣proof), proof' ← ↑(get_local id), type : expr ← ↑(infer_type proof'), -- FIXME: otherwise "" c'' ← return { c with proof := app_of_list proof' ass }, if c↣num_quants = 0 ∧ c↣num_lits = 0 then add_sat_clause { c' with proof := proof' } else if ¬ass_v then do stateT.modify $ λst, { st with locked := ⟨ id, c'', ass, [] ⟩ :: st↣locked } else do stateT.modify $ λstate, { state with passive := state↣passive↣insert id { c := c'', assertions := ass, from_model := ff } } meta def remove_passive (id : name) : resolution_prover unit := do state ← stateT.read, stateT.write { state with passive := state↣passive↣erase id } meta def move_locked_to_passive : resolution_prover unit := do locked ← flip liftM stateT.read (λst, st↣locked), new_locked ← flip filterM locked (λlc, do reason_vals ← mapM sat_eval_assertions lc↣reasons, c_val ← sat_eval_assertions lc↣assertions, if reason_vals↣for_all (λr, r = ff) ∧ c_val then do stateT.modify $ λst, { st with passive := st↣passive↣insert lc↣id ⟨ lc↣c, lc↣assertions, ff ⟩ }, return ff else return tt ), stateT.modify $ λst, { st with locked := new_locked } meta def move_active_to_locked : resolution_prover unit := do active ← get_active, forM' active↣values $ λac, do c_val ← sat_eval_assertions ac↣assertions, if ¬c_val ∧ ac↣from_model then do stateT.modify $ λst, { st with active := st↣active↣erase ac↣id } else if ¬c_val ∧ ¬ac↣from_model then do stateT.modify $ λst, { st with active := st↣active↣erase ac↣id, locked := ⟨ ac↣id, ac↣c, ac↣assertions, [] ⟩ :: st↣locked } else return () meta def move_passive_to_locked : resolution_prover unit := do passive ← flip liftM stateT.read (λst, st↣passive), forM' passive↣to_list $ λpc, do c_val ← sat_eval_assertions pc↣2↣assertions, if ¬c_val ∧ pc↣2↣from_model then do stateT.modify $ λst, { st with passive := st↣passive↣erase pc↣1 } else if ¬c_val ∧ ¬pc↣2↣from_model then do stateT.modify $ λst, { st with passive := st↣passive↣erase pc↣1, locked := ⟨ pc↣1, pc↣2↣c, pc↣2↣assertions, [] ⟩ :: st↣locked } else return () meta def add_new_from_model_clauses (old_model : rb_map expr bool) : resolution_prover unit := do model ← flip liftM stateT.read (λst, st↣current_model), forM' model↣to_list $ λassg, do name ← ↑mk_fresh_name, hyp ← get_sat_hyp assg↣1 assg↣2, if old_model↣find assg↣1 = some assg↣2 then return () else do c ← ↑(clause.of_proof hyp), stateT.modify $ λst, { st with passive := st↣passive↣insert name ⟨ c, [hyp], tt ⟩ } meta def do_sat_run : resolution_prover (option expr) := do sat_result ← in_sat_solver $ cdcl.run (return none), stateT.modify $ λst, { st with needs_sat_run := ff }, old_model ← liftM resolution_prover_state.current_model stateT.read, match sat_result with | (cdcl.result.unsat proof) := return (some proof) | (cdcl.result.sat new_model) := do stateT.modify $ λst, { st with current_model := new_model }, move_locked_to_passive, move_active_to_locked, move_passive_to_locked, add_new_from_model_clauses old_model, return none end meta def take_newly_derived : resolution_prover (list clause) := do state ← stateT.read, stateT.write { state with newly_derived := [] }, return state↣newly_derived meta def remove_redundant (id : name) (parents : list active_cls) : resolution_prover unit := do guard $ parents↣for_all (λp, p↣id ≠ id), red_opt ← flip liftM stateT.read (λst, st↣active↣find id), match red_opt with | none := return () | some red := if red↣from_model then do stateT.modify $ λst, { st with active := st↣active↣erase id } else let reasons := parents↣for (λp, p↣assertions), assertion := red↣assertions in if reasons↣for_all (λr, r↣subset_of assertion) then do stateT.modify $ λst, { st with active := st↣active↣erase id } else do stateT.modify $ λst, { st with active := st↣active↣erase id, locked := ⟨ id, red↣c, red↣assertions, reasons ⟩ :: st↣locked } end meta def get_precedence : resolution_prover (list expr) := do state ← stateT.read, return state↣prec meta def get_term_order : resolution_prover (expr → expr → bool) := do state ← stateT.read, return $ lpo (prec_gt_of_name_list (map name_of_funsym state↣prec)) private meta def set_precedence (new_prec : list expr) : resolution_prover unit := do state ← stateT.read, stateT.write { state with prec := new_prec } meta def register_consts_in_precedence (consts : list expr) := do p ← get_precedence, p_set ← return (rb_map.set_of_list (map name_of_funsym p)), new_syms ← return $ list.filter (λc, ¬p_set↣contains (name_of_funsym c)) consts, set_precedence (new_syms ++ p) meta def add_inferred (c : clause) (parents : list active_cls) : resolution_prover unit := do c' : clause ← ↑c↣normalize, register_consts_in_precedence (contained_funsyms c'↣type)↣values, state ← stateT.read, stateT.write { state with newly_derived := c' :: state↣newly_derived } meta def inference := active_cls → resolution_prover unit meta def seq_inferences : list inference → inference | [] := λgiven, return () | (inf::infs) := λgiven, do inf given, now_active ← get_active, if rb_map.contains now_active given↣id then seq_inferences infs given else return () meta def simp_inference (simpl : active_cls → resolution_prover (option clause)) : inference := λgiven, do maybe_simpld ← simpl given, match maybe_simpld with | some simpld := do add_inferred simpld [given], remove_redundant given↣id [] | none := return () end meta def preprocessing_rule (f : list clause → resolution_prover (list clause)) : resolution_prover unit := do state ← stateT.read, newly_derived' ← f state↣newly_derived, state' ← stateT.read, stateT.write { state' with newly_derived := newly_derived' } meta def clause_selection_strategy := ℕ → resolution_prover name namespace resolution_prover_state meta def empty : resolution_prover_state := { active := rb_map.mk _ _, passive := rb_map.mk _ _, newly_derived := [], prec := [], age := 0, locked := [], sat_solver := cdcl.state.initial, current_model := rb_map.mk _ _, sat_hyps := rb_map.mk _ _, needs_sat_run := ff } meta def initial (clauses : list clause) : tactic resolution_prover_state := do after_setup ← forM' clauses (λc, add_inferred c []) empty, return after_setup.2 end resolution_prover_state
90c1084149624eccabb4d6a2780f23e034f107fd
6e41ee3ac9b96e8980a16295cc21f131e731884f
/tests/lean/slow/nat_wo_hints.lean
07c200530bb43ae705133aec7e447307a77b64ef
[ "Apache-2.0" ]
permissive
EgbertRijke/lean
3426cfa0e5b3d35d12fc3fd7318b35574cb67dc3
4f2e0c6d7fc9274d953cfa1c37ab2f3e799ab183
refs/heads/master
1,610,834,871,476
1,422,159,801,000
1,422,159,801,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
49,588
lean
---------------------------------------------------------------------------------------------------- -- Copyright (c) 2014 Floris van Doorn. All rights reserved. -- Released under Apache 2.0 license as described in the file LICENSE. -- Author: Floris van Doorn ---------------------------------------------------------------------------------------------------- import logic algebra.binary open tactic binary eq.ops eq open decidable namespace experiment inductive nat : Type := zero : nat, succ : nat → nat namespace nat notation `ℕ`:max := nat definition plus (x y : ℕ) : ℕ := nat.rec x (λ n r, succ r) y definition to_nat [coercion] (n : num) : ℕ := num.rec zero (λ n, pos_num.rec (succ zero) (λ n r, plus r (plus r (succ zero))) (λ n r, plus r r) n) n namespace helper_tactics definition apply_refl := apply @eq.refl tactic_hint apply_refl end helper_tactics open helper_tactics theorem nat_rec_zero {P : ℕ → Type} (x : P 0) (f : ∀m, P m → P (succ m)) : nat.rec x f 0 = x theorem nat_rec_succ {P : ℕ → Type} (x : P 0) (f : ∀m, P m → P (succ m)) (n : ℕ) : nat.rec x f (succ n) = f n (nat.rec x f n) theorem succ_ne_zero (n : ℕ) : succ n ≠ 0 := assume H : succ n = 0, have H2 : true = false, from let f := (nat.rec false (fun a b, true)) in calc true = f (succ n) : _ ... = f 0 : {H} ... = false : _, absurd H2 true_ne_false definition pred (n : ℕ) := nat.rec 0 (fun m x, m) n theorem pred_zero : pred 0 = 0 theorem pred_succ (n : ℕ) : pred (succ n) = n theorem zero_or_succ (n : ℕ) : n = 0 ∨ n = succ (pred n) := induction_on n (or.intro_left _ (eq.refl 0)) (take m IH, or.intro_right _ (show succ m = succ (pred (succ m)), from congr_arg succ (pred_succ m⁻¹))) theorem zero_or_succ2 (n : ℕ) : n = 0 ∨ ∃k, n = succ k := or_of_or_of_imp_of_imp (zero_or_succ n) (assume H, H) (assume H : n = succ (pred n), exists.intro (pred n) H) theorem case {P : ℕ → Prop} (n : ℕ) (H1: P 0) (H2 : ∀m, P (succ m)) : P n := induction_on n H1 (take m IH, H2 m) theorem discriminate {B : Prop} {n : ℕ} (H1: n = 0 → B) (H2 : ∀m, n = succ m → B) : B := or.elim (zero_or_succ n) (take H3 : n = 0, H1 H3) (take H3 : n = succ (pred n), H2 (pred n) H3) theorem succ_inj {n m : ℕ} (H : succ n = succ m) : n = m := calc n = pred (succ n) : pred_succ n⁻¹ ... = pred (succ m) : {H} ... = m : pred_succ m theorem succ_ne_self (n : ℕ) : succ n ≠ n := induction_on n (take H : 1 = 0, have ne : 1 ≠ 0, from succ_ne_zero 0, absurd H ne) (take k IH H, IH (succ_inj H)) theorem decidable_eq [instance] (n m : ℕ) : decidable (n = m) := have general : ∀n, decidable (n = m), from rec_on m (take n, rec_on n (inl (eq.refl 0)) (λ m iH, inr (succ_ne_zero m))) (λ (m' : ℕ) (iH1 : ∀n, decidable (n = m')), take n, rec_on n (inr (ne.symm (succ_ne_zero m'))) (λ (n' : ℕ) (iH2 : decidable (n' = succ m')), have d1 : decidable (n' = m'), from iH1 n', decidable.rec_on d1 (assume Heq : n' = m', inl (congr_arg succ Heq)) (assume Hne : n' ≠ m', have H1 : succ n' ≠ succ m', from assume Heq, absurd (succ_inj Heq) Hne, inr H1))), general n theorem two_step_induction_on {P : ℕ → Prop} (a : ℕ) (H1 : P 0) (H2 : P 1) (H3 : ∀ (n : ℕ) (IH1 : P n) (IH2 : P (succ n)), P (succ (succ n))) : P a := have stronger : P a ∧ P (succ a), from induction_on a (and.intro H1 H2) (take k IH, have IH1 : P k, from and.elim_left IH, have IH2 : P (succ k), from and.elim_right IH, and.intro IH2 (H3 k IH1 IH2)), and.elim_left stronger theorem sub_induction {P : ℕ → ℕ → Prop} (n m : ℕ) (H1 : ∀m, P 0 m) (H2 : ∀n, P (succ n) 0) (H3 : ∀n m, P n m → P (succ n) (succ m)) : P n m := have general : ∀m, P n m, from induction_on n (take m : ℕ, H1 m) (take k : ℕ, assume IH : ∀m, P k m, take m : ℕ, discriminate (assume Hm : m = 0, Hm⁻¹ ▸ (H2 k)) (take l : ℕ, assume Hm : m = succ l, Hm⁻¹ ▸ (H3 k l (IH l)))), general m -------------------------------------------------- add definition add (x y : ℕ) : ℕ := plus x y infixl `+` := add theorem add_zero (n : ℕ) : n + 0 = n theorem add_succ (n m : ℕ) : n + succ m = succ (n + m) ---------- comm, assoc theorem zero_add (n : ℕ) : 0 + n = n := induction_on n (add_zero 0) (take m IH, show 0 + succ m = succ m, from calc 0 + succ m = succ (0 + m) : add_succ _ _ ... = succ m : {IH}) theorem succ_add (n m : ℕ) : (succ n) + m = succ (n + m) := induction_on m (calc succ n + 0 = succ n : add_zero (succ n) ... = succ (n + 0) : {symm (add_zero n)}) (take k IH, calc succ n + succ k = succ (succ n + k) : add_succ _ _ ... = succ (succ (n + k)) : {IH} ... = succ (n + succ k) : {symm (add_succ _ _)}) theorem add_comm (n m : ℕ) : n + m = m + n := induction_on m (trans (add_zero _) (symm (zero_add _))) (take k IH, calc n + succ k = succ (n+k) : add_succ _ _ ... = succ (k + n) : {IH} ... = succ k + n : symm (succ_add _ _)) theorem succ_add_eq_add_succ (n m : ℕ) : succ n + m = n + succ m := calc succ n + m = succ (n + m) : succ_add n m ... = n +succ m : symm (add_succ n m) theorem add_comm_succ (n m : ℕ) : n + succ m = m + succ n := calc n + succ m = succ n + m : symm (succ_add_eq_add_succ n m) ... = m + succ n : add_comm (succ n) m theorem add_assoc (n m k : ℕ) : (n + m) + k = n + (m + k) := induction_on k (calc (n + m) + 0 = n + m : add_zero _ ... = n + (m + 0) : {symm (add_zero m)}) (take l IH, calc (n + m) + succ l = succ ((n + m) + l) : add_succ _ _ ... = succ (n + (m + l)) : {IH} ... = n + succ (m + l) : symm (add_succ _ _) ... = n + (m + succ l) : {symm (add_succ _ _)}) theorem add_left_comm (n m k : ℕ) : n + (m + k) = m + (n + k) := left_comm add_comm add_assoc n m k theorem add_right_comm (n m k : ℕ) : n + m + k = n + k + m := right_comm add_comm add_assoc n m k ---------- inversion theorem add_cancel_left {n m k : ℕ} : n + m = n + k → m = k := induction_on n (take H : 0 + m = 0 + k, calc m = 0 + m : symm (zero_add m) ... = 0 + k : H ... = k : zero_add k) (take (n : ℕ) (IH : n + m = n + k → m = k) (H : succ n + m = succ n + k), have H2 : succ (n + m) = succ (n + k), from calc succ (n + m) = succ n + m : symm (succ_add n m) ... = succ n + k : H ... = succ (n + k) : succ_add n k, have H3 : n + m = n + k, from succ_inj H2, IH H3) --rename to and_cancel_right theorem add_cancel_right {n m k : ℕ} (H : n + m = k + m) : n = k := have H2 : m + n = m + k, from calc m + n = n + m : add_comm m n ... = k + m : H ... = m + k : add_comm k m, add_cancel_left H2 theorem eq_zero_of_add_eq_zero_right {n m : ℕ} : n + m = 0 → n = 0 := induction_on n (take (H : 0 + m = 0), eq.refl 0) (take k IH, assume (H : succ k + m = 0), absurd (show succ (k + m) = 0, from calc succ (k + m) = succ k + m : symm (succ_add k m) ... = 0 : H) (succ_ne_zero (k + m))) theorem add_eq_zero_right {n m : ℕ} (H : n + m = 0) : m = 0 := eq_zero_of_add_eq_zero_right (trans (add_comm m n) H) theorem add_eq_zero {n m : ℕ} (H : n + m = 0) : n = 0 ∧ m = 0 := and.intro (eq_zero_of_add_eq_zero_right H) (add_eq_zero_right H) -- add_eq_self below ---------- misc theorem add_one (n:ℕ) : n + 1 = succ n := calc n + 1 = succ (n + 0) : add_succ _ _ ... = succ n : {add_zero _} theorem add_one_left (n:ℕ) : 1 + n = succ n := calc 1 + n = succ (0 + n) : succ_add _ _ ... = succ n : {zero_add _} --the following theorem has a terrible name, but since the name is not a substring or superstring of another name, it is at least easy to globally replace it theorem induction_plus_one {P : ℕ → Prop} (a : ℕ) (H1 : P 0) (H2 : ∀ (n : ℕ) (IH : P n), P (n + 1)) : P a := nat.rec H1 (take n IH, (add_one n) ▸ (H2 n IH)) a -------------------------------------------------- mul definition mul (n m : ℕ) := nat.rec 0 (fun m x, x + n) m infixl `*` := mul theorem mul_zero_right (n:ℕ) : n * 0 = 0 theorem mul_succ_right (n m:ℕ) : n * succ m = n * m + n set_option unifier.max_steps 100000 ---------- comm, distr, assoc, identity theorem mul_zero_left (n:ℕ) : 0 * n = 0 := induction_on n (mul_zero_right 0) (take m IH, calc 0 * succ m = 0 * m + 0 : mul_succ_right _ _ ... = 0 * m : add_zero _ ... = 0 : IH) theorem mul_succ_left (n m:ℕ) : (succ n) * m = (n * m) + m := induction_on m (calc succ n * 0 = 0 : mul_zero_right _ ... = n * 0 : symm (mul_zero_right _) ... = n * 0 + 0 : symm (add_zero _)) (take k IH, calc succ n * succ k = (succ n * k) + succ n : mul_succ_right _ _ ... = (n * k) + k + succ n : { IH } ... = (n * k) + (k + succ n) : add_assoc _ _ _ ... = (n * k) + (n + succ k) : {add_comm_succ _ _} ... = (n * k) + n + succ k : symm (add_assoc _ _ _) ... = (n * succ k) + succ k : {symm (mul_succ_right n k)}) theorem mul_comm (n m:ℕ) : n * m = m * n := induction_on m (trans (mul_zero_right _) (symm (mul_zero_left _))) (take k IH, calc n * succ k = n * k + n : mul_succ_right _ _ ... = k * n + n : {IH} ... = (succ k) * n : symm (mul_succ_left _ _)) theorem mul_add_distr_left (n m k : ℕ) : (n + m) * k = n * k + m * k := induction_on k (calc (n + m) * 0 = 0 : mul_zero_right _ ... = 0 + 0 : symm (add_zero _) ... = n * 0 + 0 : eq.refl _ ... = n * 0 + m * 0 : eq.refl _) (take l IH, calc (n + m) * succ l = (n + m) * l + (n + m) : mul_succ_right _ _ ... = n * l + m * l + (n + m) : {IH} ... = n * l + m * l + n + m : symm (add_assoc _ _ _) ... = n * l + n + m * l + m : {add_right_comm _ _ _} ... = n * l + n + (m * l + m) : add_assoc _ _ _ ... = n * succ l + (m * l + m) : {symm (mul_succ_right _ _)} ... = n * succ l + m * succ l : {symm (mul_succ_right _ _)}) theorem mul_add_distr_right (n m k : ℕ) : n * (m + k) = n * m + n * k := calc n * (m + k) = (m + k) * n : mul_comm _ _ ... = m * n + k * n : mul_add_distr_left _ _ _ ... = n * m + k * n : {mul_comm _ _} ... = n * m + n * k : {mul_comm _ _} theorem mul_assoc (n m k:ℕ) : (n * m) * k = n * (m * k) := induction_on k (calc (n * m) * 0 = 0 : mul_zero_right _ ... = n * 0 : symm (mul_zero_right _) ... = n * (m * 0) : {symm (mul_zero_right _)}) (take l IH, calc (n * m) * succ l = (n * m) * l + n * m : mul_succ_right _ _ ... = n * (m * l) + n * m : {IH} ... = n * (m * l + m) : symm (mul_add_distr_right _ _ _) ... = n * (m * succ l) : {symm (mul_succ_right _ _)}) theorem mul_comm_left (n m k : ℕ) : n * (m * k) = m * (n * k) := left_comm mul_comm mul_assoc n m k theorem mul_comm_right (n m k : ℕ) : n * m * k = n * k * m := right_comm mul_comm mul_assoc n m k theorem mul_one_right (n : ℕ) : n * 1 = n := calc n * 1 = n * 0 + n : mul_succ_right n 0 ... = 0 + n : {mul_zero_right n} ... = n : zero_add n theorem mul_one_left (n : ℕ) : 1 * n = n := calc 1 * n = n * 1 : mul_comm _ _ ... = n : mul_one_right n ---------- inversion theorem mul_eq_zero {n m : ℕ} (H : n * m = 0) : n = 0 ∨ m = 0 := discriminate (take Hn : n = 0, or.intro_left _ Hn) (take (k : ℕ), assume (Hk : n = succ k), discriminate (take (Hm : m = 0), or.intro_right _ Hm) (take (l : ℕ), assume (Hl : m = succ l), have Heq : succ (k * succ l + l) = n * m, from symm (calc n * m = n * succ l : { Hl } ... = succ k * succ l : { Hk } ... = k * succ l + succ l : mul_succ_left _ _ ... = succ (k * succ l + l) : add_succ _ _), absurd (trans Heq H) (succ_ne_zero _))) -- see more under "positivity" below -------------------------------------------------- le definition le (n m:ℕ) : Prop := ∃k, n + k = m infix `<=` := le infix `≤` := le theorem le_intro {n m k : ℕ} (H : n + k = m) : n ≤ m := exists.intro k H theorem le_elim {n m : ℕ} (H : n ≤ m) : ∃ k, n + k = m := H ---------- partial order (totality is part of lt) theorem le_intro2 (n m : ℕ) : n ≤ n + m := le_intro (eq.refl (n + m)) theorem le_refl (n : ℕ) : n ≤ n := le_intro (add_zero n) theorem zero_le (n : ℕ) : 0 ≤ n := le_intro (zero_add n) theorem le_zero {n : ℕ} (H : n ≤ 0) : n = 0 := obtain (k : ℕ) (Hk : n + k = 0), from le_elim H, eq_zero_of_add_eq_zero_right Hk theorem not_succ_zero_le (n : ℕ) : ¬ succ n ≤ 0 := assume H : succ n ≤ 0, have H2 : succ n = 0, from le_zero H, absurd H2 (succ_ne_zero n) theorem le_zero_inv {n : ℕ} (H : n ≤ 0) : n = 0 := obtain (k : ℕ) (Hk : n + k = 0), from le_elim H, eq_zero_of_add_eq_zero_right Hk theorem le_trans {n m k : ℕ} (H1 : n ≤ m) (H2 : m ≤ k) : n ≤ k := obtain (l1 : ℕ) (Hl1 : n + l1 = m), from le_elim H1, obtain (l2 : ℕ) (Hl2 : m + l2 = k), from le_elim H2, le_intro (calc n + (l1 + l2) = n + l1 + l2 : symm (add_assoc n l1 l2) ... = m + l2 : { Hl1 } ... = k : Hl2) theorem le_antisym {n m : ℕ} (H1 : n ≤ m) (H2 : m ≤ n) : n = m := obtain (k : ℕ) (Hk : n + k = m), from (le_elim H1), obtain (l : ℕ) (Hl : m + l = n), from (le_elim H2), have L1 : k + l = 0, from add_cancel_left (calc n + (k + l) = n + k + l : { symm (add_assoc n k l) } ... = m + l : { Hk } ... = n : Hl ... = n + 0 : symm (add_zero n)), have L2 : k = 0, from eq_zero_of_add_eq_zero_right L1, calc n = n + 0 : symm (add_zero n) ... = n + k : { symm L2 } ... = m : Hk ---------- interaction with add theorem add_le_left {n m : ℕ} (H : n ≤ m) (k : ℕ) : k + n ≤ k + m := obtain (l : ℕ) (Hl : n + l = m), from (le_elim H), le_intro (calc k + n + l = k + (n + l) : add_assoc k n l ... = k + m : { Hl }) theorem add_le_right {n m : ℕ} (H : n ≤ m) (k : ℕ) : n + k ≤ m + k := (add_comm k m) ▸ (add_comm k n) ▸ (add_le_left H k) theorem add_le {n m k l : ℕ} (H1 : n ≤ k) (H2 : m ≤ l) : n + m ≤ k + l := le_trans (add_le_right H1 m) (add_le_left H2 k) theorem add_le_left_inv {n m k : ℕ} (H : k + n ≤ k + m) : n ≤ m := obtain (l : ℕ) (Hl : k + n + l = k + m), from (le_elim H), le_intro (add_cancel_left (calc k + (n + l) = k + n + l : symm (add_assoc k n l) ... = k + m : Hl)) theorem add_le_right_inv {n m k : ℕ} (H : n + k ≤ m + k) : n ≤ m := add_le_left_inv (add_comm m k ▸ add_comm n k ▸ H) ---------- interaction with succ and pred theorem succ_le {n m : ℕ} (H : n ≤ m) : succ n ≤ succ m := add_one m ▸ add_one n ▸ add_le_right H 1 theorem succ_le_cancel {n m : ℕ} (H : succ n ≤ succ m) : n ≤ m := add_le_right_inv (add_one m⁻¹ ▸ add_one n⁻¹ ▸ H) theorem self_le_succ (n : ℕ) : n ≤ succ n := le_intro (add_one n) theorem le_imp_le_succ {n m : ℕ} (H : n ≤ m) : n ≤ succ m := le_trans H (self_le_succ m) theorem succ_le_left_or {n m : ℕ} (H : n ≤ m) : succ n ≤ m ∨ n = m := obtain (k : ℕ) (Hk : n + k = m), from (le_elim H), discriminate (assume H3 : k = 0, have Heq : n = m, from calc n = n + 0 : (add_zero n)⁻¹ ... = n + k : {H3⁻¹} ... = m : Hk, or.intro_right _ Heq) (take l:ℕ, assume H3 : k = succ l, have Hlt : succ n ≤ m, from (le_intro (calc succ n + l = n + succ l : succ_add_eq_add_succ n l ... = n + k : {H3⁻¹} ... = m : Hk)), or.intro_left _ Hlt) theorem succ_le_left {n m : ℕ} (H1 : n ≤ m) (H2 : n ≠ m) : succ n ≤ m := or_resolve_left (succ_le_left_or H1) H2 theorem succ_le_right_inv {n m : ℕ} (H : n ≤ succ m) : n ≤ m ∨ n = succ m := or_of_or_of_imp_of_imp (succ_le_left_or H) (take H2 : succ n ≤ succ m, show n ≤ m, from succ_le_cancel H2) (take H2 : n = succ m, H2) theorem succ_le_left_inv {n m : ℕ} (H : succ n ≤ m) : n ≤ m ∧ n ≠ m := obtain (k : ℕ) (H2 : succ n + k = m), from (le_elim H), and.intro (have H3 : n + succ k = m, from calc n + succ k = succ n + k : symm (succ_add_eq_add_succ n k) ... = m : H2, show n ≤ m, from le_intro H3) (assume H3 : n = m, have H4 : succ n ≤ n, from subst (symm H3) H, have H5 : succ n = n, from le_antisym H4 (self_le_succ n), show false, from absurd H5 (succ_ne_self n)) theorem le_pred_self (n : ℕ) : pred n ≤ n := case n (subst (symm pred_zero) (le_refl 0)) (take k : ℕ, subst (symm (pred_succ k)) (self_le_succ k)) theorem pred_le {n m : ℕ} (H : n ≤ m) : pred n ≤ pred m := discriminate (take Hn : n = 0, have H2 : pred n = 0, from calc pred n = pred 0 : {Hn} ... = 0 : pred_zero, subst (symm H2) (zero_le (pred m))) (take k : ℕ, assume Hn : n = succ k, obtain (l : ℕ) (Hl : n + l = m), from le_elim H, have H2 : pred n + l = pred m, from calc pred n + l = pred (succ k) + l : {Hn} ... = k + l : {pred_succ k} ... = pred (succ (k + l)) : symm (pred_succ (k + l)) ... = pred (succ k + l) : {symm (succ_add k l)} ... = pred (n + l) : {symm Hn} ... = pred m : {Hl}, le_intro H2) theorem pred_le_left_inv {n m : ℕ} (H : pred n ≤ m) : n ≤ m ∨ n = succ m := discriminate (take Hn : n = 0, or.intro_left _ (subst (symm Hn) (zero_le m))) (take k : ℕ, assume Hn : n = succ k, have H2 : pred n = k, from calc pred n = pred (succ k) : {Hn} ... = k : pred_succ k, have H3 : k ≤ m, from subst H2 H, have H4 : succ k ≤ m ∨ k = m, from succ_le_left_or H3, show n ≤ m ∨ n = succ m, from or_of_or_of_imp_of_imp H4 (take H5 : succ k ≤ m, show n ≤ m, from subst (symm Hn) H5) (take H5 : k = m, show n = succ m, from subst H5 Hn)) -- ### interaction with successor and predecessor theorem le_imp_succ_le_or_eq {n m : ℕ} (H : n ≤ m) : succ n ≤ m ∨ n = m := obtain (k : ℕ) (Hk : n + k = m), from (le_elim H), discriminate (assume H3 : k = 0, have Heq : n = m, from calc n = n + 0 : symm (add_zero n) ... = n + k : {symm H3} ... = m : Hk, or.intro_right _ Heq) (take l : nat, assume H3 : k = succ l, have Hlt : succ n ≤ m, from (le_intro (calc succ n + l = n + succ l : succ_add_eq_add_succ n l ... = n + k : {symm H3} ... = m : Hk)), or.intro_left _ Hlt) theorem le_ne_imp_succ_le {n m : ℕ} (H1 : n ≤ m) (H2 : n ≠ m) : succ n ≤ m := or_resolve_left (le_imp_succ_le_or_eq H1) H2 theorem le_succ_imp_le_or_eq {n m : ℕ} (H : n ≤ succ m) : n ≤ m ∨ n = succ m := or_of_or_of_imp_left (le_imp_succ_le_or_eq H) (take H2 : succ n ≤ succ m, show n ≤ m, from succ_le_cancel H2) theorem succ_le_imp_le_and_ne {n m : ℕ} (H : succ n ≤ m) : n ≤ m ∧ n ≠ m := and.intro (le_trans (self_le_succ n) H) (assume H2 : n = m, have H3 : succ n ≤ n, from subst (symm H2) H, have H4 : succ n = n, from le_antisym H3 (self_le_succ n), show false, from absurd H4 (succ_ne_self n)) theorem pred_le_self (n : ℕ) : pred n ≤ n := case n (subst (symm pred_zero) (le_refl 0)) (take k : nat, subst (symm (pred_succ k)) (self_le_succ k)) theorem pred_le_imp_le_or_eq {n m : ℕ} (H : pred n ≤ m) : n ≤ m ∨ n = succ m := discriminate (take Hn : n = 0, or.intro_left _ (subst (symm Hn) (zero_le m))) (take k : nat, assume Hn : n = succ k, have H2 : pred n = k, from calc pred n = pred (succ k) : {Hn} ... = k : pred_succ k, have H3 : k ≤ m, from subst H2 H, have H4 : succ k ≤ m ∨ k = m, from le_imp_succ_le_or_eq H3, show n ≤ m ∨ n = succ m, from or_of_or_of_imp_of_imp H4 (take H5 : succ k ≤ m, show n ≤ m, from subst (symm Hn) H5) (take H5 : k = m, show n = succ m, from subst H5 Hn)) ---------- interaction with mul theorem mul_le_left {n m : ℕ} (H : n ≤ m) (k : ℕ) : k * n ≤ k * m := obtain (l : ℕ) (Hl : n + l = m), from (le_elim H), induction_on k (have H2 : 0 * n = 0 * m, from calc 0 * n = 0 : mul_zero_left n ... = 0 * m : symm (mul_zero_left m), show 0 * n ≤ 0 * m, from subst H2 (le_refl (0 * n))) (take (l : ℕ), assume IH : l * n ≤ l * m, have H2 : l * n + n ≤ l * m + m, from add_le IH H, have H3 : succ l * n ≤ l * m + m, from subst (symm (mul_succ_left l n)) H2, show succ l * n ≤ succ l * m, from subst (symm (mul_succ_left l m)) H3) theorem mul_le_right {n m : ℕ} (H : n ≤ m) (k : ℕ) : n * k ≤ m * k := mul_comm k m ▸ mul_comm k n ▸ (mul_le_left H k) theorem mul_le {n m k l : ℕ} (H1 : n ≤ k) (H2 : m ≤ l) : n * m ≤ k * l := le_trans (mul_le_right H1 m) (mul_le_left H2 k) -- mul_le_[left|right]_inv below -------------------------------------------------- lt definition lt (n m : ℕ) := succ n ≤ m infix `<` := lt theorem lt_intro {n m k : ℕ} (H : succ n + k = m) : n < m := le_intro H theorem lt_elim {n m : ℕ} (H : n < m) : ∃ k, succ n + k = m := le_elim H theorem lt_intro2 (n m : ℕ) : n < n + succ m := lt_intro (succ_add_eq_add_succ n m) -------------------------------------------------- ge, gt definition ge (n m : ℕ) := m ≤ n infix `>=` := ge infix `≥` := ge definition gt (n m : ℕ) := m < n infix `>` := gt ---------- basic facts theorem lt_ne {n m : ℕ} (H : n < m) : n ≠ m := and.elim_right (succ_le_left_inv H) theorem lt_irrefl (n : ℕ) : ¬ n < n := assume H : n < n, absurd (eq.refl n) (lt_ne H) theorem lt_zero (n : ℕ) : 0 < succ n := succ_le (zero_le n) theorem lt_zero_inv (n : ℕ) : ¬ n < 0 := assume H : n < 0, have H2 : succ n = 0, from le_zero_inv H, absurd H2 (succ_ne_zero n) theorem lt_positive {n m : ℕ} (H : n < m) : ∃k, m = succ k := discriminate (take (Hm : m = 0), absurd (subst Hm H) (lt_zero_inv n)) (take (l : ℕ) (Hm : m = succ l), exists.intro l Hm) ---------- interaction with le theorem lt_imp_le_succ {n m : ℕ} (H : n < m) : succ n ≤ m := H theorem le_succ_imp_lt {n m : ℕ} (H : succ n ≤ m) : n < m := H theorem self_lt_succ (n : ℕ) : n < succ n := le_refl (succ n) theorem lt_imp_le {n m : ℕ} (H : n < m) : n ≤ m := and.elim_left (succ_le_imp_le_and_ne H) theorem le_imp_lt_or_eq {n m : ℕ} (H : n ≤ m) : n < m ∨ n = m := le_imp_succ_le_or_eq H theorem le_ne_imp_lt {n m : ℕ} (H1 : n ≤ m) (H2 : n ≠ m) : n < m := le_ne_imp_succ_le H1 H2 theorem le_imp_lt_succ {n m : ℕ} (H : n ≤ m) : n < succ m := succ_le H theorem lt_succ_imp_le {n m : ℕ} (H : n < succ m) : n ≤ m := succ_le_cancel H ---------- trans, antisym theorem lt_le_trans {n m k : ℕ} (H1 : n < m) (H2 : m ≤ k) : n < k := le_trans H1 H2 theorem le_lt_trans {n m k : ℕ} (H1 : n ≤ m) (H2 : m < k) : n < k := le_trans (succ_le H1) H2 theorem lt_trans {n m k : ℕ} (H1 : n < m) (H2 : m < k) : n < k := lt_le_trans H1 (lt_imp_le H2) theorem le_imp_not_gt {n m : ℕ} (H : n ≤ m) : ¬ n > m := assume H2 : m < n, absurd (le_lt_trans H H2) (lt_irrefl n) theorem lt_imp_not_ge {n m : ℕ} (H : n < m) : ¬ n ≥ m := assume H2 : m ≤ n, absurd (lt_le_trans H H2) (lt_irrefl n) theorem lt_antisym {n m : ℕ} (H : n < m) : ¬ m < n := le_imp_not_gt (lt_imp_le H) ---------- interaction with add theorem add_lt_left {n m : ℕ} (H : n < m) (k : ℕ) : k + n < k + m := add_succ k n ▸ add_le_left H k theorem add_lt_right {n m : ℕ} (H : n < m) (k : ℕ) : n + k < m + k := add_comm k m ▸ add_comm k n ▸ add_lt_left H k theorem add_le_lt {n m k l : ℕ} (H1 : n ≤ k) (H2 : m < l) : n + m < k + l := le_lt_trans (add_le_right H1 m) (add_lt_left H2 k) theorem add_lt_le {n m k l : ℕ} (H1 : n < k) (H2 : m ≤ l) : n + m < k + l := lt_le_trans (add_lt_right H1 m) (add_le_left H2 k) theorem add_lt {n m k l : ℕ} (H1 : n < k) (H2 : m < l) : n + m < k + l := add_lt_le H1 (lt_imp_le H2) theorem add_lt_left_inv {n m k : ℕ} (H : k + n < k + m) : n < m := add_le_left_inv (add_succ k n⁻¹ ▸ H) theorem add_lt_right_inv {n m k : ℕ} (H : n + k < m + k) : n < m := add_lt_left_inv (add_comm m k ▸ add_comm n k ▸ H) ---------- interaction with succ (see also the interaction with le) theorem succ_lt {n m : ℕ} (H : n < m) : succ n < succ m := add_one m ▸ add_one n ▸ add_lt_right H 1 theorem succ_lt_inv {n m : ℕ} (H : succ n < succ m) : n < m := add_lt_right_inv (add_one m⁻¹ ▸ add_one n⁻¹ ▸ H) theorem lt_self_succ (n : ℕ) : n < succ n := le_refl (succ n) theorem succ_lt_right {n m : ℕ} (H : n < m) : n < succ m := lt_trans H (lt_self_succ m) ---------- totality of lt and le theorem le_or_lt (n m : ℕ) : n ≤ m ∨ m < n := induction_on n (or.intro_left _ (zero_le m)) (take (k : ℕ), assume IH : k ≤ m ∨ m < k, or.elim IH (assume H : k ≤ m, obtain (l : ℕ) (Hl : k + l = m), from le_elim H, discriminate (assume H2 : l = 0, have H3 : m = k, from calc m = k + l : symm Hl ... = k + 0 : {H2} ... = k : add_zero k, have H4 : m < succ k, from subst H3 (lt_self_succ m), or.intro_right _ H4) (take l2 : ℕ, assume H2 : l = succ l2, have H3 : succ k + l2 = m, from calc succ k + l2 = k + succ l2 : succ_add_eq_add_succ k l2 ... = k + l : {symm H2} ... = m : Hl, or.intro_left _ (le_intro H3))) (assume H : m < k, or.intro_right _ (succ_lt_right H))) theorem trichotomy_alt (n m : ℕ) : (n < m ∨ n = m) ∨ m < n := or_of_or_of_imp_of_imp (le_or_lt n m) (assume H : n ≤ m, le_imp_lt_or_eq H) (assume H : m < n, H) theorem trichotomy (n m : ℕ) : n < m ∨ n = m ∨ m < n := iff.elim_left or.assoc (trichotomy_alt n m) theorem le_total (n m : ℕ) : n ≤ m ∨ m ≤ n := or_of_or_of_imp_of_imp (le_or_lt n m) (assume H : n ≤ m, H) (assume H : m < n, lt_imp_le H) -- interaction with mul under "positivity" theorem strong_induction_on {P : ℕ → Prop} (n : ℕ) (IH : ∀n, (∀m, m < n → P m) → P n) : P n := have stronger : ∀k, k ≤ n → P k, from induction_on n (take (k : ℕ), assume H : k ≤ 0, have H2 : k = 0, from le_zero_inv H, have H3 : ∀m, m < k → P m, from (take m : ℕ, assume H4 : m < k, have H5 : m < 0, from subst H2 H4, absurd H5 (lt_zero_inv m)), show P k, from IH k H3) (take l : ℕ, assume IHl : ∀k, k ≤ l → P k, take k : ℕ, assume H : k ≤ succ l, or.elim (succ_le_right_inv H) (assume H2 : k ≤ l, show P k, from IHl k H2) (assume H2 : k = succ l, have H3 : ∀m, m < k → P m, from (take m : ℕ, assume H4 : m < k, have H5 : m ≤ l, from lt_succ_imp_le (subst H2 H4), show P m, from IHl m H5), show P k, from IH k H3)), stronger n (le_refl n) theorem case_strong_induction_on {P : ℕ → Prop} (a : ℕ) (H0 : P 0) (Hind : ∀(n : ℕ), (∀m, m ≤ n → P m) → P (succ n)) : P a := strong_induction_on a (take n, case n (assume H : (∀m, m < 0 → P m), H0) (take n, assume H : (∀m, m < succ n → P m), Hind n (take m, assume H1 : m ≤ n, H m (le_imp_lt_succ H1)))) theorem add_eq_self {n m : ℕ} (H : n + m = n) : m = 0 := discriminate (take Hm : m = 0, Hm) (take k : ℕ, assume Hm : m = succ k, have H2 : succ n + k = n, from calc succ n + k = n + succ k : succ_add_eq_add_succ n k ... = n + m : {symm Hm} ... = n : H, have H3 : n < n, from lt_intro H2, have H4 : n ≠ n, from lt_ne H3, absurd (eq.refl n) H4) -------------------------------------------------- positivity -- we use " _ > 0" as canonical way of denoting that a number is positive ---------- basic theorem zero_or_positive (n : ℕ) : n = 0 ∨ n > 0 := or_of_or_of_imp_of_imp (or.swap (le_imp_lt_or_eq (zero_le n))) (take H : 0 = n, symm H) (take H : n > 0, H) theorem succ_positive {n m : ℕ} (H : n = succ m) : n > 0 := subst (symm H) (lt_zero m) theorem ne_zero_positive {n : ℕ} (H : n ≠ 0) : n > 0 := or.elim (zero_or_positive n) (take H2 : n = 0, absurd H2 H) (take H2 : n > 0, H2) theorem pos_imp_eq_succ {n : ℕ} (H : n > 0) : ∃l, n = succ l := discriminate (take H2, absurd (subst H2 H) (lt_irrefl 0)) (take l Hl, exists.intro l Hl) theorem add_positive_right (n : ℕ) {k : ℕ} (H : k > 0) : n + k > n := obtain (l : ℕ) (Hl : k = succ l), from pos_imp_eq_succ H, subst (symm Hl) (lt_intro2 n l) theorem add_positive_left (n : ℕ) {k : ℕ} (H : k > 0) : k + n > n := subst (add_comm n k) (add_positive_right n H) -- Positivity -- --------- -- -- Writing "t > 0" is the preferred way to assert that a natural number is positive. -- ### basic -- See also succ_pos. theorem succ_pos (n : ℕ) : 0 < succ n := succ_le (zero_le n) theorem case_zero_pos {P : ℕ → Prop} (y : ℕ) (H0 : P 0) (H1 : ∀y, y > 0 → P y) : P y := case y H0 (take y', H1 _ (succ_pos _)) theorem zero_or_pos (n : ℕ) : n = 0 ∨ n > 0 := or_of_or_of_imp_left (or.swap (le_imp_lt_or_eq (zero_le n))) (take H : 0 = n, symm H) theorem succ_imp_pos {n m : ℕ} (H : n = succ m) : n > 0 := subst (symm H) (succ_pos m) theorem ne_zero_pos {n : ℕ} (H : n ≠ 0) : n > 0 := or.elim (zero_or_pos n) (take H2 : n = 0, absurd H2 H) (take H2 : n > 0, H2) theorem add_pos_right (n : ℕ) {k : ℕ} (H : k > 0) : n + k > n := subst (add_zero n) (add_lt_left H n) theorem add_pos_left (n : ℕ) {k : ℕ} (H : k > 0) : k + n > n := subst (add_comm n k) (add_pos_right n H) ---------- mul theorem mul_positive {n m : ℕ} (Hn : n > 0) (Hm : m > 0) : n * m > 0 := obtain (k : ℕ) (Hk : n = succ k), from pos_imp_eq_succ Hn, obtain (l : ℕ) (Hl : m = succ l), from pos_imp_eq_succ Hm, succ_positive (calc n * m = succ k * m : {Hk} ... = succ k * succ l : {Hl} ... = succ k * l + succ k : mul_succ_right (succ k) l ... = succ (succ k * l + k) : add_succ _ _) theorem mul_positive_inv_left {n m : ℕ} (H : n * m > 0) : n > 0 := discriminate (assume H2 : n = 0, have H3 : n * m = 0, from calc n * m = 0 * m : {H2} ... = 0 : mul_zero_left m, have H4 : 0 > 0, from subst H3 H, absurd H4 (lt_irrefl 0)) (take l : ℕ, assume Hl : n = succ l, subst (symm Hl) (lt_zero l)) theorem mul_positive_inv_right {n m : ℕ} (H : n * m > 0) : m > 0 := mul_positive_inv_left (subst (mul_comm n m) H) theorem mul_left_inj {n m k : ℕ} (Hn : n > 0) (H : n * m = n * k) : m = k := have general : ∀m, n * m = n * k → m = k, from induction_on k (take m:ℕ, assume H : n * m = n * 0, have H2 : n * m = 0, from calc n * m = n * 0 : H ... = 0 : mul_zero_right n, have H3 : n = 0 ∨ m = 0, from mul_eq_zero H2, or_resolve_right H3 (ne.symm (lt_ne Hn))) (take (l : ℕ), assume (IH : ∀ m, n * m = n * l → m = l), take (m : ℕ), assume (H : n * m = n * succ l), have H2 : n * succ l > 0, from mul_positive Hn (lt_zero l), have H3 : m > 0, from mul_positive_inv_right (subst (symm H) H2), obtain (l2:ℕ) (Hm : m = succ l2), from pos_imp_eq_succ H3, have H4 : n * l2 + n = n * l + n, from calc n * l2 + n = n * succ l2 : symm (mul_succ_right n l2) ... = n * m : {symm Hm} ... = n * succ l : H ... = n * l + n : mul_succ_right n l, have H5 : n * l2 = n * l, from add_cancel_right H4, calc m = succ l2 : Hm ... = succ l : {IH l2 H5}), general m H theorem mul_right_inj {n m k : ℕ} (Hm : m > 0) (H : n * m = k * m) : n = k := mul_left_inj Hm (subst (mul_comm k m) (subst (mul_comm n m) H)) -- mul_eq_one below ---------- interaction of mul with le and lt theorem mul_lt_left {n m k : ℕ} (Hk : k > 0) (H : n < m) : k * n < k * m := have H2 : k * n < k * n + k, from add_positive_right (k * n) Hk, have H3 : k * n + k ≤ k * m, from subst (mul_succ_right k n) (mul_le_left H k), lt_le_trans H2 H3 theorem mul_lt_right {n m k : ℕ} (Hk : k > 0) (H : n < m) : n * k < m * k := subst (mul_comm k m) (subst (mul_comm k n) (mul_lt_left Hk H)) theorem mul_le_lt {n m k l : ℕ} (Hk : k > 0) (H1 : n ≤ k) (H2 : m < l) : n * m < k * l := le_lt_trans (mul_le_right H1 m) (mul_lt_left Hk H2) theorem mul_lt_le {n m k l : ℕ} (Hl : l > 0) (H1 : n < k) (H2 : m ≤ l) : n * m < k * l := le_lt_trans (mul_le_left H2 n) (mul_lt_right Hl H1) theorem mul_lt {n m k l : ℕ} (H1 : n < k) (H2 : m < l) : n * m < k * l := have H3 : n * m ≤ k * m, from mul_le_right (lt_imp_le H1) m, have H4 : k * m < k * l, from mul_lt_left (le_lt_trans (zero_le n) H1) H2, le_lt_trans H3 H4 theorem mul_lt_left_inv {n m k : ℕ} (H : k * n < k * m) : n < m := have general : ∀ m, k * n < k * m → n < m, from induction_on n (take m : ℕ, assume H2 : k * 0 < k * m, have H3 : 0 < k * m, from mul_zero_right k ▸ H2, show 0 < m, from mul_positive_inv_right H3) (take l : ℕ, assume IH : ∀ m, k * l < k * m → l < m, take m : ℕ, assume H2 : k * succ l < k * m, have H3 : 0 < k * m, from le_lt_trans (zero_le _) H2, have H4 : 0 < m, from mul_positive_inv_right H3, obtain (l2 : ℕ) (Hl2 : m = succ l2), from pos_imp_eq_succ H4, have H5 : k * l + k < k * m, from mul_succ_right k l ▸ H2, have H6 : k * l + k < k * succ l2, from Hl2 ▸ H5, have H7 : k * l + k < k * l2 + k, from mul_succ_right k l2 ▸ H6, have H8 : k * l < k * l2, from add_lt_right_inv H7, have H9 : l < l2, from IH l2 H8, have H10 : succ l < succ l2, from succ_lt H9, show succ l < m, from Hl2⁻¹ ▸ H10), general m H theorem mul_lt_right_inv {n m k : ℕ} (H : n * k < m * k) : n < m := mul_lt_left_inv (mul_comm m k ▸ mul_comm n k ▸ H) theorem mul_le_left_inv {n m k : ℕ} (H : succ k * n ≤ succ k * m) : n ≤ m := have H2 : succ k * n < succ k * m + succ k, from le_lt_trans H (lt_intro2 _ _), have H3 : succ k * n < succ k * succ m, from subst (symm (mul_succ_right (succ k) m)) H2, have H4 : n < succ m, from mul_lt_left_inv H3, show n ≤ m, from lt_succ_imp_le H4 theorem mul_le_right_inv {n m k : ℕ} (H : n * succ m ≤ k * succ m) : n ≤ k := mul_le_left_inv (subst (mul_comm k (succ m)) (subst (mul_comm n (succ m)) H)) theorem mul_eq_one_left {n m : ℕ} (H : n * m = 1) : n = 1 := have H2 : n * m > 0, from subst (symm H) (lt_zero 0), have H3 : n > 0, from mul_positive_inv_left H2, have H4 : m > 0, from mul_positive_inv_right H2, or.elim (le_or_lt n 1) (assume H5 : n ≤ 1, show n = 1, from le_antisym H5 H3) (assume H5 : n > 1, have H6 : n * m ≥ 2 * 1, from mul_le H5 H4, have H7 : 1 ≥ 2, from subst (mul_one_right 2) (subst H H6), absurd (self_lt_succ 1) (le_imp_not_gt H7)) theorem mul_eq_one_right {n m : ℕ} (H : n * m = 1) : m = 1 := mul_eq_one_left (subst (mul_comm n m) H) theorem mul_eq_one {n m : ℕ} (H : n * m = 1) : n = 1 ∧ m = 1 := and.intro (mul_eq_one_left H) (mul_eq_one_right H) -------------------------------------------------- sub definition sub (n m : ℕ) : ℕ := nat.rec n (fun m x, pred x) m infixl `-` := sub theorem sub_zero_right (n : ℕ) : n - 0 = n theorem sub_succ_right (n m : ℕ) : n - succ m = pred (n - m) theorem sub_zero_left (n : ℕ) : 0 - n = 0 := induction_on n (sub_zero_right 0) (take k : ℕ, assume IH : 0 - k = 0, calc 0 - succ k = pred (0 - k) : sub_succ_right 0 k ... = pred 0 : {IH} ... = 0 : pred_zero) theorem sub_succ_succ (n m : ℕ) : succ n - succ m = n - m := induction_on m (calc succ n - 1 = pred (succ n - 0) : sub_succ_right (succ n) 0 ... = pred (succ n) : {sub_zero_right (succ n)} ... = n : pred_succ n ... = n - 0 : symm (sub_zero_right n)) (take k : ℕ, assume IH : succ n - succ k = n - k, calc succ n - succ (succ k) = pred (succ n - succ k) : sub_succ_right (succ n) (succ k) ... = pred (n - k) : {IH} ... = n - succ k : symm (sub_succ_right n k)) theorem sub_one (n : ℕ) : n - 1 = pred n := calc n - 1 = pred (n - 0) : sub_succ_right n 0 ... = pred n : {sub_zero_right n} theorem sub_self (n : ℕ) : n - n = 0 := induction_on n (sub_zero_right 0) (take k IH, trans (sub_succ_succ k k) IH) theorem sub_add_add_right (n m k : ℕ) : (n + k) - (m + k) = n - m := induction_on k (calc (n + 0) - (m + 0) = n - (m + 0) : {add_zero _} ... = n - m : {add_zero _}) (take l : ℕ, assume IH : (n + l) - (m + l) = n - m, calc (n + succ l) - (m + succ l) = succ (n + l) - (m + succ l) : {add_succ _ _} ... = succ (n + l) - succ (m + l) : {add_succ _ _} ... = (n + l) - (m + l) : sub_succ_succ _ _ ... = n - m : IH) theorem sub_add_add_left (n m k : ℕ) : (k + n) - (k + m) = n - m := subst (add_comm m k) (subst (add_comm n k) (sub_add_add_right n m k)) theorem sub_add_left (n m : ℕ) : n + m - m = n := induction_on m (subst (symm (add_zero n)) (sub_zero_right n)) (take k : ℕ, assume IH : n + k - k = n, calc n + succ k - succ k = succ (n + k) - succ k : {add_succ n k} ... = n + k - k : sub_succ_succ _ _ ... = n : IH) theorem sub_sub (n m k : ℕ) : n - m - k = n - (m + k) := induction_on k (calc n - m - 0 = n - m : sub_zero_right _ ... = n - (m + 0) : {symm (add_zero m)}) (take l : ℕ, assume IH : n - m - l = n - (m + l), calc n - m - succ l = pred (n - m - l) : sub_succ_right (n - m) l ... = pred (n - (m + l)) : {IH} ... = n - succ (m + l) : symm (sub_succ_right n (m + l)) ... = n - (m + succ l) : {symm (add_succ m l)}) theorem succ_sub_sub (n m k : ℕ) : succ n - m - succ k = n - m - k := calc succ n - m - succ k = succ n - (m + succ k) : sub_sub _ _ _ ... = succ n - succ (m + k) : {add_succ m k} ... = n - (m + k) : sub_succ_succ _ _ ... = n - m - k : symm (sub_sub n m k) theorem sub_add_right_eq_zero (n m : ℕ) : n - (n + m) = 0 := calc n - (n + m) = n - n - m : symm (sub_sub n n m) ... = 0 - m : {sub_self n} ... = 0 : sub_zero_left m theorem sub_comm (m n k : ℕ) : m - n - k = m - k - n := calc m - n - k = m - (n + k) : sub_sub m n k ... = m - (k + n) : {add_comm n k} ... = m - k - n : symm (sub_sub m k n) theorem succ_sub_one (n : ℕ) : succ n - 1 = n := sub_succ_succ n 0 ⬝ sub_zero_right n ---------- mul theorem mul_pred_left (n m : ℕ) : pred n * m = n * m - m := induction_on n (calc pred 0 * m = 0 * m : {pred_zero} ... = 0 : mul_zero_left _ ... = 0 - m : symm (sub_zero_left m) ... = 0 * m - m : {symm (mul_zero_left m)}) (take k : ℕ, assume IH : pred k * m = k * m - m, calc pred (succ k) * m = k * m : {pred_succ k} ... = k * m + m - m : symm (sub_add_left _ _) ... = succ k * m - m : {symm (mul_succ_left k m)}) theorem mul_pred_right (n m : ℕ) : n * pred m = n * m - n := calc n * pred m = pred m * n : mul_comm _ _ ... = m * n - n : mul_pred_left m n ... = n * m - n : {mul_comm m n} theorem mul_sub_distr_left (n m k : ℕ) : (n - m) * k = n * k - m * k := induction_on m (calc (n - 0) * k = n * k : {sub_zero_right n} ... = n * k - 0 : symm (sub_zero_right _) ... = n * k - 0 * k : {symm (mul_zero_left _)}) (take l : ℕ, assume IH : (n - l) * k = n * k - l * k, calc (n - succ l) * k = pred (n - l) * k : {sub_succ_right n l} ... = (n - l) * k - k : mul_pred_left _ _ ... = n * k - l * k - k : {IH} ... = n * k - (l * k + k) : sub_sub _ _ _ ... = n * k - (succ l * k) : {symm (mul_succ_left l k)}) theorem mul_sub_distr_right (n m k : ℕ) : n * (m - k) = n * m - n * k := calc n * (m - k) = (m - k) * n : mul_comm _ _ ... = m * n - k * n : mul_sub_distr_left _ _ _ ... = n * m - k * n : {mul_comm _ _} ... = n * m - n * k : {mul_comm _ _} -------------------------------------------------- max, min, iteration, maybe: sub, div theorem succ_sub {m n : ℕ} : m ≥ n → succ m - n = succ (m - n) := sub_induction n m (take k, assume H : 0 ≤ k, calc succ k - 0 = succ k : sub_zero_right (succ k) ... = succ (k - 0) : {symm (sub_zero_right k)}) (take k, assume H : succ k ≤ 0, absurd H (not_succ_zero_le k)) (take k l, assume IH : k ≤ l → succ l - k = succ (l - k), take H : succ k ≤ succ l, calc succ (succ l) - succ k = succ l - k : sub_succ_succ (succ l) k ... = succ (l - k) : IH (succ_le_cancel H) ... = succ (succ l - succ k) : {symm (sub_succ_succ l k)}) theorem le_imp_sub_eq_zero {n m : ℕ} (H : n ≤ m) : n - m = 0 := obtain (k : ℕ) (Hk : n + k = m), from le_elim H, subst Hk (sub_add_right_eq_zero n k) theorem add_sub_le {n m : ℕ} : n ≤ m → n + (m - n) = m := sub_induction n m (take k, assume H : 0 ≤ k, calc 0 + (k - 0) = k - 0 : zero_add (k - 0) ... = k : sub_zero_right k) (take k, assume H : succ k ≤ 0, absurd H (not_succ_zero_le k)) (take k l, assume IH : k ≤ l → k + (l - k) = l, take H : succ k ≤ succ l, calc succ k + (succ l - succ k) = succ k + (l - k) : {sub_succ_succ l k} ... = succ (k + (l - k)) : succ_add k (l - k) ... = succ l : {IH (succ_le_cancel H)}) theorem add_sub_ge_left {n m : ℕ} : n ≥ m → n - m + m = n := subst (add_comm m (n - m)) add_sub_le theorem add_sub_ge {n m : ℕ} (H : n ≥ m) : n + (m - n) = n := calc n + (m - n) = n + 0 : {le_imp_sub_eq_zero H} ... = n : add_zero n theorem add_sub_le_left {n m : ℕ} : n ≤ m → n - m + m = m := subst (add_comm m (n - m)) add_sub_ge theorem le_add_sub_left (n m : ℕ) : n ≤ n + (m - n) := or.elim (le_total n m) (assume H : n ≤ m, subst (symm (add_sub_le H)) H) (assume H : m ≤ n, subst (symm (add_sub_ge H)) (le_refl n)) theorem le_add_sub_right (n m : ℕ) : m ≤ n + (m - n) := or.elim (le_total n m) (assume H : n ≤ m, subst (symm (add_sub_le H)) (le_refl m)) (assume H : m ≤ n, subst (symm (add_sub_ge H)) H) theorem sub_split {P : ℕ → Prop} {n m : ℕ} (H1 : n ≤ m → P 0) (H2 : ∀k, m + k = n -> P k) : P (n - m) := or.elim (le_total n m) (assume H3 : n ≤ m, subst (symm (le_imp_sub_eq_zero H3)) (H1 H3)) (assume H3 : m ≤ n, H2 (n - m) (add_sub_le H3)) theorem sub_le_self (n m : ℕ) : n - m ≤ n := sub_split (assume H : n ≤ m, zero_le n) (take k : ℕ, assume H : m + k = n, le_intro (subst (add_comm m k) H)) theorem le_elim_sub (n m : ℕ) (H : n ≤ m) : ∃k, m - k = n := obtain (k : ℕ) (Hk : n + k = m), from le_elim H, exists.intro k (calc m - k = n + k - k : {symm Hk} ... = n : sub_add_left n k) theorem add_sub_assoc {m k : ℕ} (H : k ≤ m) (n : ℕ) : n + m - k = n + (m - k) := have l1 : k ≤ m → n + m - k = n + (m - k), from sub_induction k m (take m : ℕ, assume H : 0 ≤ m, calc n + m - 0 = n + m : sub_zero_right (n + m) ... = n + (m - 0) : {symm (sub_zero_right m)}) (take k : ℕ, assume H : succ k ≤ 0, absurd H (not_succ_zero_le k)) (take k m, assume IH : k ≤ m → n + m - k = n + (m - k), take H : succ k ≤ succ m, calc n + succ m - succ k = succ (n + m) - succ k : {add_succ n m} ... = n + m - k : sub_succ_succ (n + m) k ... = n + (m - k) : IH (succ_le_cancel H) ... = n + (succ m - succ k) : {symm (sub_succ_succ m k)}), l1 H theorem sub_eq_zero_imp_le {n m : ℕ} : n - m = 0 → n ≤ m := sub_split (assume H1 : n ≤ m, assume H2 : 0 = 0, H1) (take k : ℕ, assume H1 : m + k = n, assume H2 : k = 0, have H3 : n = m, from subst (add_zero m) (subst H2 (symm H1)), subst H3 (le_refl n)) theorem sub_sub_split {P : ℕ → ℕ → Prop} {n m : ℕ} (H1 : ∀k, n = m + k -> P k 0) (H2 : ∀k, m = n + k → P 0 k) : P (n - m) (m - n) := or.elim (le_total n m) (assume H3 : n ≤ m, le_imp_sub_eq_zero H3⁻¹ ▸ (H2 (m - n) (add_sub_le H3⁻¹))) (assume H3 : m ≤ n, le_imp_sub_eq_zero H3⁻¹ ▸ (H1 (n - m) (add_sub_le H3⁻¹))) theorem sub_intro {n m k : ℕ} (H : n + m = k) : k - n = m := have H2 : k - n + n = m + n, from calc k - n + n = k : add_sub_ge_left (le_intro H) ... = n + m : symm H ... = m + n : add_comm n m, add_cancel_right H2 theorem sub_lt {x y : ℕ} (xpos : x > 0) (ypos : y > 0) : x - y < x := obtain (x' : ℕ) (xeq : x = succ x'), from pos_imp_eq_succ xpos, obtain (y' : ℕ) (yeq : y = succ y'), from pos_imp_eq_succ ypos, have xsuby_eq : x - y = x' - y', from calc x - y = succ x' - y : {xeq} ... = succ x' - succ y' : {yeq} ... = x' - y' : sub_succ_succ _ _, have H1 : x' - y' ≤ x', from sub_le_self _ _, have H2 : x' < succ x', from self_lt_succ _, show x - y < x, from xeq⁻¹ ▸ xsuby_eq⁻¹ ▸ le_lt_trans H1 H2 -- Max, min, iteration, and absolute difference -- -------------------------------------------- definition max (n m : ℕ) : ℕ := n + (m - n) definition min (n m : ℕ) : ℕ := m - (m - n) theorem max_le {n m : ℕ} (H : n ≤ m) : n + (m - n) = m := add_sub_le H theorem max_ge {n m : ℕ} (H : n ≥ m) : n + (m - n) = n := add_sub_ge H theorem left_le_max (n m : ℕ) : n ≤ n + (m - n) := le_add_sub_left n m theorem right_le_max (n m : ℕ) : m ≤ max n m := le_add_sub_right n m -- ### absolute difference -- This section is still incomplete definition dist (n m : ℕ) := (n - m) + (m - n) theorem dist_comm (n m : ℕ) : dist n m = dist m n := add_comm (n - m) (m - n) theorem dist_eq_zero {n m : ℕ} (H : dist n m = 0) : n = m := have H2 : n - m = 0, from eq_zero_of_add_eq_zero_right H, have H3 : n ≤ m, from sub_eq_zero_imp_le H2, have H4 : m - n = 0, from add_eq_zero_right H, have H5 : m ≤ n, from sub_eq_zero_imp_le H4, le_antisym H3 H5 theorem dist_le {n m : ℕ} (H : n ≤ m) : dist n m = m - n := calc dist n m = (n - m) + (m - n) : eq.refl _ ... = 0 + (m - n) : {le_imp_sub_eq_zero H} ... = m - n : zero_add (m - n) theorem dist_ge {n m : ℕ} (H : n ≥ m) : dist n m = n - m := subst (dist_comm m n) (dist_le H) theorem dist_zero_right (n : ℕ) : dist n 0 = n := trans (dist_ge (zero_le n)) (sub_zero_right n) theorem dist_zero_left (n : ℕ) : dist 0 n = n := trans (dist_le (zero_le n)) (sub_zero_right n) theorem dist_intro {n m k : ℕ} (H : n + m = k) : dist k n = m := calc dist k n = k - n : dist_ge (le_intro H) ... = m : sub_intro H theorem dist_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)) : eq.refl _ ... = (n - m) + ((m + k) - (n + k)) : {sub_add_add_right _ _ _} ... = (n - m) + (m - n) : {sub_add_add_right _ _ _} theorem dist_add_left (k n m : ℕ) : dist (k + n) (k + m) = dist n m := subst (add_comm m k) (subst (add_comm n k) (dist_add_right n k m)) theorem dist_ge_add_right {n m : ℕ} (H : n ≥ m) : dist n m + m = n := calc dist n m + m = n - m + m : {dist_ge H} ... = n : add_sub_ge_left H 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) : symm (dist_add_right n m k) ... = dist (k + l) (k + m) : {H} ... = dist l m : dist_add_left k l m end nat end experiment
696c5720e1e46965dcbe586edce4e74f6d2b9183
aa5a655c05e5359a70646b7154e7cac59f0b4132
/src/Lean/Meta/DiscrTree.lean
bcb23418123c2fa19514ebf2d1dc578058da3d8d
[ "Apache-2.0" ]
permissive
lambdaxymox/lean4
ae943c960a42247e06eff25c35338268d07454cb
278d47c77270664ef29715faab467feac8a0f446
refs/heads/master
1,677,891,867,340
1,612,500,005,000
1,612,500,005,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
15,478
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Meta.Basic import Lean.Meta.FunInfo import Lean.Meta.InferType namespace Lean.Meta.DiscrTree /- (Imperfect) discrimination trees. We use a hybrid representation. - A `PersistentHashMap` for the root node which usually contains many children. - A sorted array of key/node pairs for inner nodes. The edges are labeled by keys: - Constant names (and arity). Universe levels are ignored. - Free variables (and arity). Thus, an entry in the discrimination tree may reference hypotheses from the local context. - Literals - Star/Wildcard. We use them to represent metavariables and terms we want to ignore. We ignore implicit arguments and proofs. - Other. We use to represent other kinds of terms (e.g., nested lambda, forall, sort, etc). We reduce terms using `TransparencyMode.reducible`. Thus, all reducible definitions in an expression `e` are unfolded before we insert it into the discrimination tree. Recall that projections from classes are **NOT** reducible. For example, the expressions `Add.add α (ringAdd ?α ?s) ?x ?x` and `Add.add Nat Nat.hasAdd a b` generates paths with the following keys respctively ``` ⟨Add.add, 4⟩, *, *, *, * ⟨Add.add, 4⟩, *, *, ⟨a,0⟩, ⟨b,0⟩ ``` That is, we don't reduce `Add.add Nat inst a b` into `Nat.add a b`. We say the `Add.add` applications are the de-facto canonical forms in the metaprogramming framework. Moreover, it is the metaprogrammer's responsibility to re-pack applications such as `Nat.add a b` into `Add.add Nat inst a b`. Remark: we store the arity in the keys 1- To be able to implement the "skip" operation when retrieving "candidate" unifiers. 2- Distinguish partial applications `f a`, `f a b`, and `f a b c`. -/ def Key.ctorIdx : Key → Nat | Key.star => 0 | Key.other => 1 | Key.lit _ => 2 | Key.fvar _ _ => 3 | Key.const _ _ => 4 def Key.lt : Key → Key → Bool | Key.lit v₁, Key.lit v₂ => v₁ < v₂ | Key.fvar n₁ a₁, Key.fvar n₂ a₂ => Name.quickLt n₁ n₂ || (n₁ == n₂ && a₁ < a₂) | Key.const n₁ a₁, Key.const n₂ a₂ => Name.quickLt n₁ n₂ || (n₁ == n₂ && a₁ < a₂) | k₁, k₂ => k₁.ctorIdx < k₂.ctorIdx instance : HasLess Key := ⟨fun a b => Key.lt a b⟩ instance (a b : Key) : Decidable (a < b) := inferInstanceAs (Decidable (Key.lt a b)) def Key.format : Key → Format | Key.star => "*" | Key.other => "◾" | Key.lit (Literal.natVal v) => fmt v | Key.lit (Literal.strVal v) => repr v | Key.const k _ => fmt k | Key.fvar k _ => fmt k instance : ToFormat Key := ⟨Key.format⟩ def Key.arity : Key → Nat | Key.const _ a => a | Key.fvar _ a => a | _ => 0 instance {α} : Inhabited (Trie α) := ⟨Trie.node #[] #[]⟩ def empty {α} : DiscrTree α := { root := {} } partial def Trie.format {α} [ToFormat α] : Trie α → Format | Trie.node vs cs => Format.group $ Format.paren $ "node" ++ (if vs.isEmpty then Format.nil else " " ++ fmt vs) ++ Format.join (cs.toList.map $ fun ⟨k, c⟩ => Format.line ++ Format.paren (fmt k ++ " => " ++ format c)) instance {α} [ToFormat α] : ToFormat (Trie α) := ⟨Trie.format⟩ partial def format {α} [ToFormat α] (d : DiscrTree α) : Format := let (_, r) := d.root.foldl (fun (p : Bool × Format) k c => (false, p.2 ++ (if p.1 then Format.nil else Format.line) ++ Format.paren (fmt k ++ " => " ++ fmt c))) (true, Format.nil) Format.group r instance {α} [ToFormat α] : ToFormat (DiscrTree α) := ⟨format⟩ /- The discrimination tree ignores implicit arguments and proofs. We use the following auxiliary id as a "mark". -/ private def tmpMVarId : MVarId := `_discr_tree_tmp private def tmpStar := mkMVar tmpMVarId instance {α} : Inhabited (DiscrTree α) where default := {} /-- Return true iff the argument should be treated as a "wildcard" by the discrimination tree. - We ignore proofs because of proof irrelevance. It doesn't make sense to try to index their structure. - We ignore instance implicit arguments (e.g., `[Add α]`) because they are "morally" canonical. Moreover, we may have many definitionally equal terms floating around. Example: `Ring.hasAdd Int Int.isRing` and `Int.hasAdd`. - We considered ignoring implicit arguments (e.g., `{α : Type}`) since users don't "see" them, and may not even understand why some simplification rule is not firing. However, in type class resolution, we have instance such as `Decidable (@Eq Nat x y)`, where `Nat` is an implicit argument. Thus, we would add the path ``` Decidable -> Eq -> * -> * -> * -> [Nat.decEq] ``` to the discrimination tree IF we ignored the implict `Nat` argument. This would be BAD since **ALL** decidable equality instances would be in the same path. So, we index implicit arguments if they are types. This setting seems sensible for simplification lemmas such as: ``` forall (x y : Unit), (@Eq Unit x y) = true ``` If we ignore the implicit argument `Unit`, the `DiscrTree` will say it is a candidate simplification lemma for any equality in our goal. Remark: if users have problems with the solution above, we may provide a `noIndexing` annotation, and `ignoreArg` would return true for any term of the form `noIndexing t`. -/ private def ignoreArg (a : Expr) (i : Nat) (infos : Array ParamInfo) : MetaM Bool := if h : i < infos.size then let info := infos.get ⟨i, h⟩ if info.instImplicit then pure true else if info.implicit then not <$> isType a else isProof a else isProof a private partial def pushArgsAux (infos : Array ParamInfo) : Nat → Expr → Array Expr → MetaM (Array Expr) | i, Expr.app f a _, todo => do if (← ignoreArg a i infos) then pushArgsAux infos (i-1) f (todo.push tmpStar) else pushArgsAux infos (i-1) f (todo.push a) | _, _, todo => pure todo private partial def whnfEta (e : Expr) : MetaM Expr := do let e ← whnf e match e.etaExpandedStrict? with | some e => whnfEta e | none => pure e /- TODO: add a parameter (wildcardConsts : NameSet) to `DiscrTree.insert`. Then, `DiscrTree` users may control which symbols should be treated as wildcards. Different `DiscrTree` users may populate this set using, for example, attributes. Remark: we currently tag `Nat.zero` and `Nat.succ` to avoid having to add special support for `Expr.lit`. Example, suppose the discrimination tree contains the entry `Nat.succ ?m |-> v`, and we are trying to retrieve the matches for `Expr.lit (Literal.natVal 1) _`. In this scenario, we want to retrieve `Nat.succ ?m |-> v` -/ private def shouldAddAsStar (constName : Name) : Bool := constName == `Nat.zero || constName == `Nat.succ def mkNoindexAnnotation (e : Expr) : Expr := mkAnnotation `noindex e def hasNoindexAnnotation (e : Expr) : Bool := annotation? `noindex e |>.isSome private def pushArgs (todo : Array Expr) (e : Expr) : MetaM (Key × Array Expr) := do if hasNoindexAnnotation e then return (Key.star, todo) else let e ← whnfEta e let fn := e.getAppFn let push (k : Key) (nargs : Nat) : MetaM (Key × Array Expr) := do let info ← getFunInfoNArgs fn nargs let todo ← pushArgsAux info.paramInfo (nargs-1) e todo return (k, todo) match fn with | Expr.lit v _ => return (Key.lit v, todo) | Expr.const c _ _ => if shouldAddAsStar c then return (Key.star, todo) else let nargs := e.getAppNumArgs push (Key.const c nargs) nargs | Expr.fvar fvarId _ => let nargs := e.getAppNumArgs push (Key.fvar fvarId nargs) nargs | Expr.mvar mvarId _ => if mvarId == tmpMVarId then -- We use `tmp to mark implicit arguments and proofs return (Key.star, todo) else if (← isReadOnlyOrSyntheticOpaqueExprMVar mvarId) then return (Key.other, todo) else return (Key.star, todo) | _ => return (Key.other, todo) partial def mkPathAux (todo : Array Expr) (keys : Array Key) : MetaM (Array Key) := do if todo.isEmpty then pure keys else let e := todo.back let todo := todo.pop let (k, todo) ← pushArgs todo e mkPathAux todo (keys.push k) private def initCapacity := 8 def mkPath (e : Expr) : MetaM (Array Key) := do withReducible do let todo : Array Expr := Array.mkEmpty initCapacity let keys : Array Key := Array.mkEmpty initCapacity mkPathAux (todo.push e) keys private partial def createNodes {α} (keys : Array Key) (v : α) (i : Nat) : Trie α := if h : i < keys.size then let k := keys.get ⟨i, h⟩ let c := createNodes keys v (i+1) Trie.node #[] #[(k, c)] else Trie.node #[v] #[] private def insertVal {α} [BEq α] (vs : Array α) (v : α) : Array α := if vs.contains v then vs else vs.push v private partial def insertAux {α} [BEq α] (keys : Array Key) (v : α) : Nat → Trie α → Trie α | i, Trie.node vs cs => if h : i < keys.size then let k := keys.get ⟨i, h⟩ let c := Id.run $ cs.binInsertM (fun a b => a.1 < b.1) (fun ⟨_, s⟩ => let c := insertAux keys v (i+1) s; (k, c)) -- merge with existing (fun _ => let c := createNodes keys v (i+1); (k, c)) (k, arbitrary) Trie.node vs c else Trie.node (insertVal vs v) cs def insertCore {α} [BEq α] (d : DiscrTree α) (keys : Array Key) (v : α) : DiscrTree α := if keys.isEmpty then panic! "invalid key sequence" else let k := keys[0] match d.root.find? k with | none => let c := createNodes keys v 1 { root := d.root.insert k c } | some c => let c := insertAux keys v 1 c { root := d.root.insert k c } def insert {α} [BEq α] (d : DiscrTree α) (e : Expr) (v : α) : MetaM (DiscrTree α) := do let keys ← mkPath e return d.insertCore keys v private def getKeyArgs (e : Expr) (isMatch? : Bool) : MetaM (Key × Array Expr) := do let e ← whnfEta e match e.getAppFn with | Expr.lit v _ => pure (Key.lit v, #[]) | Expr.const c _ _ => let nargs := e.getAppNumArgs pure (Key.const c nargs, e.getAppRevArgs) | Expr.fvar fvarId _ => let nargs := e.getAppNumArgs pure (Key.fvar fvarId nargs, e.getAppRevArgs) | Expr.mvar mvarId _ => if isMatch? then pure (Key.other, #[]) else do let ctx ← read if ctx.config.isDefEqStuckEx then /- When the configuration flag `isDefEqStuckEx` is set to true, we want `isDefEq` to throw an exception whenever it tries to assign a read-only metavariable. This feature is useful for type class resolution where we may want to notify the caller that the TC problem may be solveable later after it assigns `?m`. The method `DiscrTree.getUnify e` returns candidates `c` that may "unify" with `e`. That is, `isDefEq c e` may return true. Now, consider `DiscrTree.getUnify d (Add ?m)` where `?m` is a read-only metavariable, and the discrimination tree contains the keys `HadAdd Nat` and `Add Int`. If `isDefEqStuckEx` is set to true, we must treat `?m` as a regular metavariable here, otherwise we return the empty set of candidates. This is incorrect because it is equivalent to saying that there is no solution even if the caller assigns `?m` and try again. -/ pure (Key.star, #[]) else if (← isReadOnlyOrSyntheticOpaqueExprMVar mvarId) then pure (Key.other, #[]) else pure (Key.star, #[]) | _ => pure (Key.other, #[]) private abbrev getMatchKeyArgs (e : Expr) : MetaM (Key × Array Expr) := getKeyArgs e true private abbrev getUnifyKeyArgs (e : Expr) : MetaM (Key × Array Expr) := getKeyArgs e false private def getStarResult {α} (d : DiscrTree α) : Array α := let result : Array α := Array.mkEmpty initCapacity match d.root.find? Key.star with | none => result | some (Trie.node vs _) => result ++ vs partial def getMatch {α} (d : DiscrTree α) (e : Expr) : MetaM (Array α) := withReducible do let result := getStarResult d let (k, args) ← getMatchKeyArgs e match k with | Key.star => pure result | _ => match d.root.find? k with | none => pure result | some c => process args c result where process (todo : Array Expr) (c : Trie α) (result : Array α) : MetaM (Array α) := do match c with | Trie.node vs cs => if todo.isEmpty then return result ++ vs else if cs.isEmpty then return result else let e := todo.back let todo := todo.pop let first := cs[0] /- Recall that `Key.star` is the minimal key -/ let (k, args) ← getMatchKeyArgs e /- We must always visit `Key.star` edges since they are wildcards. Thus, `todo` is not used linearly when there is `Key.star` edge and there is an edge for `k` and `k != Key.star`. -/ let visitStarChild (result : Array α) : MetaM (Array α) := if first.1 == Key.star then process todo first.2 result else return result match k with | Key.star => visitStarChild result | _ => match cs.binSearch (k, arbitrary) (fun a b => a.1 < b.1) with | none => visitStarChild result | some c => let result ← visitStarChild result process (todo ++ args) c.2 result partial def getUnify {α} (d : DiscrTree α) (e : Expr) : MetaM (Array α) := withReducible do let (k, args) ← getUnifyKeyArgs e match k with | Key.star => d.root.foldlM (init := #[]) fun result k c => process k.arity #[] c result | _ => let result := getStarResult d match d.root.find? k with | none => return result | some c => process 0 args c result where process (skip : Nat) (todo : Array Expr) (c : Trie α) (result : Array α) : MetaM (Array α) := do match skip, c with | skip+1, Trie.node vs cs => if cs.isEmpty then return result else cs.foldlM (init := result) fun result ⟨k, c⟩ => process (skip + k.arity) todo c result | 0, Trie.node vs cs => do if todo.isEmpty then return result ++ vs else if cs.isEmpty then return result else let e := todo.back let todo := todo.pop let (k, args) ← getUnifyKeyArgs e match k with | Key.star => cs.foldlM (init := result) fun result ⟨k, c⟩ => process k.arity todo c result | _ => let first := cs[0] let visitStarChild (result : Array α) : MetaM (Array α) := if first.1 == Key.star then process 0 todo first.2 result else return result match cs.binSearch (k, arbitrary) (fun a b => a.1 < b.1) with | none => visitStarChild result | some c => process 0 (todo ++ args) c.2 (← visitStarChild result) end Lean.Meta.DiscrTree
3f3d45fb94bd2e86343397e8da1d2ecf77cf5a7e
5756a081670ba9c1d1d3fca7bd47cb4e31beae66
/Mathport/Syntax/Translate/Tactic/Mathlib/Ext.lean
3e91386c13c463fbd6ef9384dfe629a1354d3f3e
[ "Apache-2.0" ]
permissive
leanprover-community/mathport
2c9bdc8292168febf59799efdc5451dbf0450d4a
13051f68064f7638970d39a8fecaede68ffbf9e1
refs/heads/master
1,693,841,364,079
1,693,813,111,000
1,693,813,111,000
379,357,010
27
10
Apache-2.0
1,691,309,132,000
1,624,384,521,000
Lean
UTF-8
Lean
false
false
1,204
lean
/- Copyright (c) 2021 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import Mathport.Syntax.Translate.Tactic.Basic import Mathport.Syntax.Translate.Tactic.Mathlib.RCases open Lean namespace Mathport.Translate.Tactic open AST3 Parser -- # tactic.ext @[tr_user_attr ext] def trExtAttr : Parse1 Syntax.Attr := parse1 (ident)? fun n => do if n.isSome then warn! "unsupported: attribute [ext id]" return mkSimpleAttr `ext -- This creates a hygienic name, which might be pretty-printed as ext.1: -- `(attr| ext) @[tr_tactic ext1] def trExt1 : TacM Syntax.Tactic := do let hint ← parse (tk "?")? let pats ← liftM $ (← parse (rcasesPat true)*).mapM trRCasesPat match hint with | none => `(tactic| ext1 $[$pats]*) | some _ => `(tactic| ext1? $[$pats]*) @[tr_tactic ext] def trExt : TacM Syntax.Tactic := do let hint ← parse (tk "?")? let pats ← liftM $ (← parse rintroPatHi*).mapM trRIntroPat let depth := (← parse (tk ":" *> smallNat)?).map Quote.quote match hint with | none => `(tactic| ext $[$pats]* $[: $depth]?) | some _ => `(tactic| ext? $[$pats]* $[: $depth]?)
3a4bbfd24aaaf02b1683ead4889e6608a3ce8043
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/ring_theory/integral_closure.lean
7daebd198ba68491693b3b0e6ac77a990c6927ac
[ "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
39,697
lean
/- Copyright (c) 2019 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau -/ import linear_algebra.finite_dimensional import ring_theory.adjoin.fg import ring_theory.polynomial.scale_roots import ring_theory.polynomial.tower import linear_algebra.matrix.determinant /-! # Integral closure of a subring. If A is an R-algebra then `a : A` is integral over R if it is a root of a monic polynomial with coefficients in R. Enough theory is developed to prove that integral elements form a sub-R-algebra of A. ## Main definitions Let `R` be a `comm_ring` and let `A` be an R-algebra. * `ring_hom.is_integral_elem (f : R →+* A) (x : A)` : `x` is integral with respect to the map `f`, * `is_integral (x : A)` : `x` is integral over `R`, i.e., is a root of a monic polynomial with coefficients in `R`. * `integral_closure R A` : the integral closure of `R` in `A`, regarded as a sub-`R`-algebra of `A`. -/ open_locale classical open_locale big_operators open polynomial submodule section ring variables {R S A : Type*} variables [comm_ring R] [ring A] [ring S] (f : R →+* S) /-- An element `x` of `A` is said to be integral over `R` with respect to `f` if it is a root of a monic polynomial `p : polynomial R` evaluated under `f` -/ def ring_hom.is_integral_elem (f : R →+* A) (x : A) := ∃ p : polynomial R, monic p ∧ eval₂ f x p = 0 /-- A ring homomorphism `f : R →+* A` is said to be integral if every element `A` is integral with respect to the map `f` -/ def ring_hom.is_integral (f : R →+* A) := ∀ x : A, f.is_integral_elem x variables [algebra R A] (R) /-- An element `x` of an algebra `A` over a commutative ring `R` is said to be *integral*, if it is a root of some monic polynomial `p : polynomial R`. Equivalently, the element is integral over `R` with respect to the induced `algebra_map` -/ def is_integral (x : A) : Prop := (algebra_map R A).is_integral_elem x variable (A) /-- An algebra is integral if every element of the extension is integral over the base ring -/ def algebra.is_integral : Prop := (algebra_map R A).is_integral variables {R A} lemma ring_hom.is_integral_map {x : R} : f.is_integral_elem (f x) := ⟨X - C x, monic_X_sub_C _, by simp⟩ theorem is_integral_algebra_map {x : R} : is_integral R (algebra_map R A x) := (algebra_map R A).is_integral_map theorem is_integral_of_noetherian (H : is_noetherian R A) (x : A) : is_integral R x := begin let leval : (polynomial R →ₗ[R] A) := (aeval x).to_linear_map, let D : ℕ → submodule R A := λ n, (degree_le R n).map leval, let M := well_founded.min (is_noetherian_iff_well_founded.1 H) (set.range D) ⟨_, ⟨0, rfl⟩⟩, have HM : M ∈ set.range D := well_founded.min_mem _ _ _, cases HM with N HN, have HM : ¬M < D (N+1) := well_founded.not_lt_min (is_noetherian_iff_well_founded.1 H) (set.range D) _ ⟨N+1, rfl⟩, rw ← HN at HM, have HN2 : D (N+1) ≤ D N := classical.by_contradiction (λ H, HM (lt_of_le_not_le (map_mono (degree_le_mono (with_bot.coe_le_coe.2 (nat.le_succ N)))) H)), have HN3 : leval (X^(N+1)) ∈ D N, { exact HN2 (mem_map_of_mem (mem_degree_le.2 (degree_X_pow_le _))) }, rcases HN3 with ⟨p, hdp, hpe⟩, refine ⟨X^(N+1) - p, monic_X_pow_sub (mem_degree_le.1 hdp), _⟩, show leval (X ^ (N + 1) - p) = 0, rw [linear_map.map_sub, hpe, sub_self] end theorem is_integral_of_submodule_noetherian (S : subalgebra R A) (H : is_noetherian R S.to_submodule) (x : A) (hx : x ∈ S) : is_integral R x := begin suffices : is_integral R (show S, from ⟨x, hx⟩), { rcases this with ⟨p, hpm, hpx⟩, replace hpx := congr_arg S.val hpx, refine ⟨p, hpm, eq.trans _ hpx⟩, simp only [aeval_def, eval₂, sum_def], rw S.val.map_sum, refine finset.sum_congr rfl (λ n hn, _), rw [S.val.map_mul, S.val.map_pow, S.val.commutes, S.val_apply, subtype.coe_mk], }, refine is_integral_of_noetherian H ⟨x, hx⟩ end end ring section variables {R A B S : Type*} variables [comm_ring R] [comm_ring A] [comm_ring B] [comm_ring S] variables [algebra R A] [algebra R B] (f : R →+* S) theorem is_integral_alg_hom (f : A →ₐ[R] B) {x : A} (hx : is_integral R x) : is_integral R (f x) := let ⟨p, hp, hpx⟩ := hx in ⟨p, hp, by rw [← aeval_def, aeval_alg_hom_apply, aeval_def, hpx, f.map_zero]⟩ @[simp] theorem is_integral_alg_equiv (f : A ≃ₐ[R] B) {x : A} : is_integral R (f x) ↔ is_integral R x := ⟨λ h, by simpa using is_integral_alg_hom f.symm.to_alg_hom h, is_integral_alg_hom f.to_alg_hom⟩ theorem is_integral_of_is_scalar_tower [algebra A B] [is_scalar_tower R A B] (x : B) (hx : is_integral R x) : is_integral A x := let ⟨p, hp, hpx⟩ := hx in ⟨p.map $ algebra_map R A, monic_map _ hp, by rw [← aeval_def, ← is_scalar_tower.aeval_apply, aeval_def, hpx]⟩ theorem is_integral_of_subring {x : A} (T : subring R) (hx : is_integral T x) : is_integral R x := is_integral_of_is_scalar_tower x hx lemma is_integral.algebra_map [algebra A B] [is_scalar_tower R A B] {x : A} (h : is_integral R x) : is_integral R (algebra_map A B x) := begin rcases h with ⟨f, hf, hx⟩, use [f, hf], rw [is_scalar_tower.algebra_map_eq R A B, ← hom_eval₂, hx, ring_hom.map_zero] end lemma is_integral_algebra_map_iff [algebra A B] [is_scalar_tower R A B] {x : A} (hAB : function.injective (algebra_map A B)) : is_integral R (algebra_map A B x) ↔ is_integral R x := begin refine ⟨_, λ h, h.algebra_map⟩, rintros ⟨f, hf, hx⟩, use [f, hf], exact is_scalar_tower.aeval_eq_zero_of_aeval_algebra_map_eq_zero R A B hAB hx, end theorem is_integral_iff_is_integral_closure_finite {r : A} : is_integral R r ↔ ∃ s : set R, s.finite ∧ is_integral (subring.closure s) r := begin split; intro hr, { rcases hr with ⟨p, hmp, hpr⟩, refine ⟨_, set.finite_mem_finset _, p.restriction, monic_restriction.2 hmp, _⟩, erw [← aeval_def, is_scalar_tower.aeval_apply _ R, map_restriction, aeval_def, hpr] }, rcases hr with ⟨s, hs, hsr⟩, exact is_integral_of_subring _ hsr end theorem fg_adjoin_singleton_of_integral (x : A) (hx : is_integral R x) : (algebra.adjoin R ({x} : set A)).to_submodule.fg := begin rcases hx with ⟨f, hfm, hfx⟩, existsi finset.image ((^) x) (finset.range (nat_degree f + 1)), apply le_antisymm, { rw span_le, intros s hs, rw finset.mem_coe at hs, rcases finset.mem_image.1 hs with ⟨k, hk, rfl⟩, clear hk, exact (algebra.adjoin R {x}).pow_mem (algebra.subset_adjoin (set.mem_singleton _)) k }, intros r hr, change r ∈ algebra.adjoin R ({x} : set A) at hr, rw algebra.adjoin_singleton_eq_range_aeval at hr, rcases (aeval x).mem_range.mp hr with ⟨p, rfl⟩, rw ← mod_by_monic_add_div p hfm, rw ← aeval_def at hfx, rw [alg_hom.map_add, alg_hom.map_mul, hfx, zero_mul, add_zero], have : degree (p %ₘ f) ≤ degree f := degree_mod_by_monic_le p hfm, generalize_hyp : p %ₘ f = q at this ⊢, rw [← sum_C_mul_X_eq q, aeval_def, eval₂_sum, sum_def], refine sum_mem _ (λ k hkq, _), rw [eval₂_mul, eval₂_C, eval₂_pow, eval₂_X, ← algebra.smul_def], refine smul_mem _ _ (subset_span _), rw finset.mem_coe, refine finset.mem_image.2 ⟨_, _, rfl⟩, rw [finset.mem_range, nat.lt_succ_iff], refine le_of_not_lt (λ hk, _), rw [degree_le_iff_coeff_zero] at this, rw [mem_support_iff] at hkq, apply hkq, apply this, exact lt_of_le_of_lt degree_le_nat_degree (with_bot.coe_lt_coe.2 hk) end theorem fg_adjoin_of_finite {s : set A} (hfs : s.finite) (his : ∀ x ∈ s, is_integral R x) : (algebra.adjoin R s).to_submodule.fg := set.finite.induction_on hfs (λ _, ⟨{1}, submodule.ext $ λ x, by { erw [algebra.adjoin_empty, finset.coe_singleton, ← one_eq_span, one_eq_range, linear_map.mem_range, algebra.mem_bot], refl }⟩) (λ a s has hs ih his, by rw [← set.union_singleton, algebra.adjoin_union_coe_submodule]; exact fg_mul _ _ (ih $ λ i hi, his i $ set.mem_insert_of_mem a hi) (fg_adjoin_singleton_of_integral _ $ his a $ set.mem_insert a s)) his lemma is_noetherian_adjoin_finset [is_noetherian_ring R] (s : finset A) (hs : ∀ x ∈ s, is_integral R x) : is_noetherian R (algebra.adjoin R (↑s : set A)) := is_noetherian_of_fg_of_noetherian _ (fg_adjoin_of_finite s.finite_to_set hs) /-- If `S` is a sub-`R`-algebra of `A` and `S` is finitely-generated as an `R`-module, then all elements of `S` are integral over `R`. -/ theorem is_integral_of_mem_of_fg (S : subalgebra R A) (HS : S.to_submodule.fg) (x : A) (hx : x ∈ S) : is_integral R x := begin -- say `x ∈ S`. We want to prove that `x` is integral over `R`. -- Say `S` is generated as an `R`-module by the set `y`. cases HS with y hy, -- We can write `x` as `∑ rᵢ yᵢ` for `yᵢ ∈ Y`. obtain ⟨lx, hlx1, hlx2⟩ : ∃ (l : A →₀ R) (H : l ∈ finsupp.supported R R ↑y), (finsupp.total A A R id) l = x, { rwa [←(@finsupp.mem_span_image_iff_total A A R _ _ _ id ↑y x), set.image_id ↑y, hy] }, -- Note that `y ⊆ S`. have hyS : ∀ {p}, p ∈ y → p ∈ S := λ p hp, show p ∈ S.to_submodule, by { rw ← hy, exact subset_span hp }, -- Now `S` is a subalgebra so the product of two elements of `y` is also in `S`. have : ∀ (jk : (↑(y.product y) : set (A × A))), jk.1.1 * jk.1.2 ∈ S.to_submodule := λ jk, S.mul_mem (hyS (finset.mem_product.1 jk.2).1) (hyS (finset.mem_product.1 jk.2).2), rw [← hy, ← set.image_id ↑y] at this, simp only [finsupp.mem_span_image_iff_total] at this, -- Say `yᵢyⱼ = ∑rᵢⱼₖ yₖ` choose ly hly1 hly2, -- Now let `S₀` be the subring of `R` generated by the `rᵢ` and the `rᵢⱼₖ`. let S₀ : subring R := subring.closure ↑(lx.frange ∪ finset.bUnion finset.univ (finsupp.frange ∘ ly)), -- It suffices to prove that `x` is integral over `S₀`. refine is_integral_of_subring S₀ _, letI : comm_ring S₀ := subring.to_comm_ring S₀, letI : algebra S₀ A := algebra.of_subring S₀, -- Claim: the `S₀`-module span (in `A`) of the set `y ∪ {1}` is closed under -- multiplication (indeed, this is the motivation for the definition of `S₀`). have : span S₀ (insert 1 ↑y : set A) * span S₀ (insert 1 ↑y : set A) ≤ span S₀ (insert 1 ↑y : set A), { rw span_mul_span, refine span_le.2 (λ z hz, _), rcases set.mem_mul.1 hz with ⟨p, q, rfl | hp, hq, rfl⟩, { rw one_mul, exact subset_span hq }, rcases hq with rfl | hq, { rw mul_one, exact subset_span (or.inr hp) }, erw ← hly2 ⟨(p, q), finset.mem_product.2 ⟨hp, hq⟩⟩, rw [finsupp.total_apply, finsupp.sum], refine (span S₀ (insert 1 ↑y : set A)).sum_mem (λ t ht, _), have : ly ⟨(p, q), finset.mem_product.2 ⟨hp, hq⟩⟩ t ∈ S₀ := subring.subset_closure (finset.mem_union_right _ $ finset.mem_bUnion.2 ⟨⟨(p, q), finset.mem_product.2 ⟨hp, hq⟩⟩, finset.mem_univ _, finsupp.mem_frange.2 ⟨finsupp.mem_support_iff.1 ht, _, rfl⟩⟩), change (⟨_, this⟩ : S₀) • t ∈ _, exact smul_mem _ _ (subset_span $ or.inr $ hly1 _ ht) }, -- Hence this span is a subring. Call this subring `S₁`. let S₁ : subring A := { carrier := span S₀ (insert 1 ↑y : set A), one_mem' := subset_span $ or.inl rfl, mul_mem' := λ p q hp hq, this $ mul_mem_mul hp hq, zero_mem' := (span S₀ (insert 1 ↑y : set A)).zero_mem, add_mem' := λ _ _, (span S₀ (insert 1 ↑y : set A)).add_mem, neg_mem' := λ _, (span S₀ (insert 1 ↑y : set A)).neg_mem }, have : S₁ = (algebra.adjoin S₀ (↑y : set A)).to_subring, { ext z, suffices : z ∈ span ↥S₀ (insert 1 ↑y : set A) ↔ z ∈ (algebra.adjoin ↥S₀ (y : set A)).to_submodule, { simpa }, split; intro hz, { exact (span_le.2 (set.insert_subset.2 ⟨(algebra.adjoin S₀ ↑y).one_mem, algebra.subset_adjoin⟩)) hz }, { rw [subalgebra.mem_to_submodule, algebra.mem_adjoin_iff] at hz, suffices : subring.closure (set.range ⇑(algebra_map ↥S₀ A) ∪ ↑y) ≤ S₁, { exact this hz }, refine subring.closure_le.2 (set.union_subset _ (λ t ht, subset_span $ or.inr ht)), rw set.range_subset_iff, intro y, rw algebra.algebra_map_eq_smul_one, exact smul_mem _ y (subset_span (or.inl rfl)) } }, have foo : ∀ z, z ∈ S₁ ↔ z ∈ algebra.adjoin ↥S₀ (y : set A), simp [this], haveI : is_noetherian_ring ↥S₀ := is_noetherian_subring_closure _ (finset.finite_to_set _), refine is_integral_of_submodule_noetherian (algebra.adjoin S₀ ↑y) (is_noetherian_of_fg_of_noetherian _ ⟨insert 1 y, by { rw [finset.coe_insert], ext z, simp [S₁], convert foo z}⟩) _ _, rw [← hlx2, finsupp.total_apply, finsupp.sum], refine subalgebra.sum_mem _ (λ r hr, _), have : lx r ∈ S₀ := subring.subset_closure (finset.mem_union_left _ (finset.mem_image_of_mem _ hr)), change (⟨_, this⟩ : S₀) • r ∈ _, rw finsupp.mem_supported at hlx1, exact subalgebra.smul_mem _ (algebra.subset_adjoin $ hlx1 hr) _ end lemma ring_hom.is_integral_of_mem_closure {x y z : S} (hx : f.is_integral_elem x) (hy : f.is_integral_elem y) (hz : z ∈ subring.closure ({x, y} : set S)) : f.is_integral_elem z := begin letI : algebra R S := f.to_algebra, have := fg_mul _ _ (fg_adjoin_singleton_of_integral x hx) (fg_adjoin_singleton_of_integral y hy), rw [← algebra.adjoin_union_coe_submodule, set.singleton_union] at this, exact is_integral_of_mem_of_fg (algebra.adjoin R {x, y}) this z (algebra.mem_adjoin_iff.2 $ subring.closure_mono (set.subset_union_right _ _) hz), end theorem is_integral_of_mem_closure {x y z : A} (hx : is_integral R x) (hy : is_integral R y) (hz : z ∈ subring.closure ({x, y} : set A)) : is_integral R z := (algebra_map R A).is_integral_of_mem_closure hx hy hz lemma ring_hom.is_integral_zero : f.is_integral_elem 0 := f.map_zero ▸ f.is_integral_map theorem is_integral_zero : is_integral R (0:A) := (algebra_map R A).is_integral_zero lemma ring_hom.is_integral_one : f.is_integral_elem 1 := f.map_one ▸ f.is_integral_map theorem is_integral_one : is_integral R (1:A) := (algebra_map R A).is_integral_one lemma ring_hom.is_integral_add {x y : S} (hx : f.is_integral_elem x) (hy : f.is_integral_elem y) : f.is_integral_elem (x + y) := f.is_integral_of_mem_closure hx hy $ subring.add_mem _ (subring.subset_closure (or.inl rfl)) (subring.subset_closure (or.inr rfl)) theorem is_integral_add {x y : A} (hx : is_integral R x) (hy : is_integral R y) : is_integral R (x + y) := (algebra_map R A).is_integral_add hx hy lemma ring_hom.is_integral_neg {x : S} (hx : f.is_integral_elem x) : f.is_integral_elem (-x) := f.is_integral_of_mem_closure hx hx (subring.neg_mem _ (subring.subset_closure (or.inl rfl))) theorem is_integral_neg {x : A} (hx : is_integral R x) : is_integral R (-x) := (algebra_map R A).is_integral_neg hx lemma ring_hom.is_integral_sub {x y : S} (hx : f.is_integral_elem x) (hy : f.is_integral_elem y) : f.is_integral_elem (x - y) := by simpa only [sub_eq_add_neg] using f.is_integral_add hx (f.is_integral_neg hy) theorem is_integral_sub {x y : A} (hx : is_integral R x) (hy : is_integral R y) : is_integral R (x - y) := (algebra_map R A).is_integral_sub hx hy lemma ring_hom.is_integral_mul {x y : S} (hx : f.is_integral_elem x) (hy : f.is_integral_elem y) : f.is_integral_elem (x * y) := f.is_integral_of_mem_closure hx hy (subring.mul_mem _ (subring.subset_closure (or.inl rfl)) (subring.subset_closure (or.inr rfl))) theorem is_integral_mul {x y : A} (hx : is_integral R x) (hy : is_integral R y) : is_integral R (x * y) := (algebra_map R A).is_integral_mul hx hy variables (R A) /-- The integral closure of R in an R-algebra A. -/ def integral_closure : subalgebra R A := { carrier := { r | is_integral R r }, zero_mem' := is_integral_zero, one_mem' := is_integral_one, add_mem' := λ _ _, is_integral_add, mul_mem' := λ _ _, is_integral_mul, algebra_map_mem' := λ x, is_integral_algebra_map } theorem mem_integral_closure_iff_mem_fg {r : A} : r ∈ integral_closure R A ↔ ∃ M : subalgebra R A, M.to_submodule.fg ∧ r ∈ M := ⟨λ hr, ⟨algebra.adjoin R {r}, fg_adjoin_singleton_of_integral _ hr, algebra.subset_adjoin rfl⟩, λ ⟨M, Hf, hrM⟩, is_integral_of_mem_of_fg M Hf _ hrM⟩ variables {R} {A} lemma adjoin_le_integral_closure {x : A} (hx : is_integral R x) : algebra.adjoin R {x} ≤ integral_closure R A := begin rw [algebra.adjoin_le_iff], simp only [set_like.mem_coe, set.singleton_subset_iff], exact hx end lemma le_integral_closure_iff_is_integral {S : subalgebra R A} : S ≤ integral_closure R A ↔ algebra.is_integral R S := set_like.forall.symm.trans (forall_congr (λ x, show is_integral R (algebra_map S A x) ↔ is_integral R x, from is_integral_algebra_map_iff subtype.coe_injective)) lemma is_integral_sup {S T : subalgebra R A} : algebra.is_integral R ↥(S ⊔ T) ↔ algebra.is_integral R S ∧ algebra.is_integral R T := by simp only [←le_integral_closure_iff_is_integral, sup_le_iff] /-- Mapping an integral closure along an `alg_equiv` gives the integral closure. -/ lemma integral_closure_map_alg_equiv (f : A ≃ₐ[R] B) : (integral_closure R A).map (f : A →ₐ[R] B) = integral_closure R B := begin ext y, rw subalgebra.mem_map, split, { rintros ⟨x, hx, rfl⟩, exact is_integral_alg_hom f hx }, { intro hy, use [f.symm y, is_integral_alg_hom (f.symm : B →ₐ[R] A) hy], simp } end lemma integral_closure.is_integral (x : integral_closure R A) : is_integral R x := let ⟨p, hpm, hpx⟩ := x.2 in ⟨p, hpm, subtype.eq $ by rwa [← aeval_def, subtype.val_eq_coe, ← subalgebra.val_apply, aeval_alg_hom_apply] at hpx⟩ lemma ring_hom.is_integral_of_is_integral_mul_unit (x y : S) (r : R) (hr : f r * y = 1) (hx : f.is_integral_elem (x * y)) : f.is_integral_elem x := begin obtain ⟨p, ⟨p_monic, hp⟩⟩ := hx, refine ⟨scale_roots p r, ⟨(monic_scale_roots_iff r).2 p_monic, _⟩⟩, convert scale_roots_eval₂_eq_zero f hp, rw [mul_comm x y, ← mul_assoc, hr, one_mul], end theorem is_integral_of_is_integral_mul_unit {x y : A} {r : R} (hr : algebra_map R A r * y = 1) (hx : is_integral R (x * y)) : is_integral R x := (algebra_map R A).is_integral_of_is_integral_mul_unit x y r hr hx /-- Generalization of `is_integral_of_mem_closure` bootstrapped up from that lemma -/ lemma is_integral_of_mem_closure' (G : set A) (hG : ∀ x ∈ G, is_integral R x) : ∀ x ∈ (subring.closure G), is_integral R x := λ x hx, subring.closure_induction hx hG is_integral_zero is_integral_one (λ _ _, is_integral_add) (λ _, is_integral_neg) (λ _ _, is_integral_mul) lemma is_integral_of_mem_closure'' {S : Type*} [comm_ring S] {f : R →+* S} (G : set S) (hG : ∀ x ∈ G, f.is_integral_elem x) : ∀ x ∈ (subring.closure G), f.is_integral_elem x := λ x hx, @is_integral_of_mem_closure' R S _ _ f.to_algebra G hG x hx lemma is_integral.pow {x : A} (h : is_integral R x) (n : ℕ) : is_integral R (x ^ n) := (integral_closure R A).pow_mem h n lemma is_integral.nsmul {x : A} (h : is_integral R x) (n : ℕ) : is_integral R (n • x) := (integral_closure R A).nsmul_mem h n lemma is_integral.zsmul {x : A} (h : is_integral R x) (n : ℤ) : is_integral R (n • x) := (integral_closure R A).zsmul_mem h n lemma is_integral.multiset_prod {s : multiset A} (h : ∀ x ∈ s, is_integral R x) : is_integral R s.prod := (integral_closure R A).multiset_prod_mem h lemma is_integral.multiset_sum {s : multiset A} (h : ∀ x ∈ s, is_integral R x) : is_integral R s.sum := (integral_closure R A).multiset_sum_mem h lemma is_integral.prod {α : Type*} {s : finset α} (f : α → A) (h : ∀ x ∈ s, is_integral R (f x)) : is_integral R (∏ x in s, f x) := (integral_closure R A).prod_mem h lemma is_integral.sum {α : Type*} {s : finset α} (f : α → A) (h : ∀ x ∈ s, is_integral R (f x)) : is_integral R (∑ x in s, f x) := (integral_closure R A).sum_mem h lemma is_integral.det {n : Type*} [fintype n] [decidable_eq n] {M : matrix n n A} (h : ∀ i j, is_integral R (M i j)) : is_integral R M.det := begin rw [matrix.det_apply], exact is_integral.sum _ (λ σ hσ, is_integral.zsmul (is_integral.prod _ (λ i hi, h _ _)) _) end section variables (p : polynomial R) (x : S) /-- The monic polynomial whose roots are `p.leading_coeff * x` for roots `x` of `p`. -/ noncomputable def normalize_scale_roots (p : polynomial R) : polynomial R := ∑ i in p.support, monomial i (if i = p.nat_degree then 1 else p.coeff i * p.leading_coeff ^ (p.nat_degree - 1 - i)) lemma normalize_scale_roots_coeff_mul_leading_coeff_pow (i : ℕ) (hp : 1 ≤ nat_degree p) : (normalize_scale_roots p).coeff i * p.leading_coeff ^ i = p.coeff i * p.leading_coeff ^ (p.nat_degree - 1) := begin simp only [normalize_scale_roots, finset_sum_coeff, coeff_monomial, finset.sum_ite_eq', one_mul, zero_mul, mem_support_iff, ite_mul, ne.def, ite_not], split_ifs with h₁ h₂, { simp [h₁], }, { rw [h₂, leading_coeff, ← pow_succ, tsub_add_cancel_of_le hp], }, { rw [mul_assoc, ← pow_add, tsub_add_cancel_of_le], apply nat.le_pred_of_lt, rw lt_iff_le_and_ne, exact ⟨le_nat_degree_of_ne_zero h₁, h₂⟩, }, end lemma leading_coeff_smul_normalize_scale_roots (p : polynomial R) : p.leading_coeff • normalize_scale_roots p = scale_roots p p.leading_coeff := begin ext, simp only [coeff_scale_roots, normalize_scale_roots, coeff_monomial, coeff_smul, finset.smul_sum, ne.def, finset.sum_ite_eq', finset_sum_coeff, smul_ite, smul_zero, mem_support_iff], split_ifs with h₁ h₂, { simp [*] }, { simp [*] }, { rw [algebra.id.smul_eq_mul, mul_comm, mul_assoc, ← pow_succ', tsub_right_comm, tsub_add_cancel_of_le], rw nat.succ_le_iff, exact tsub_pos_of_lt (lt_of_le_of_ne (le_nat_degree_of_ne_zero h₁) h₂) }, end lemma normalize_scale_roots_support : (normalize_scale_roots p).support ≤ p.support := begin intro x, contrapose, simp only [not_mem_support_iff, normalize_scale_roots, finset_sum_coeff, coeff_monomial, finset.sum_ite_eq', mem_support_iff, ne.def, not_not, ite_eq_right_iff], intros h₁ h₂, exact (h₂ h₁).rec _, end lemma normalize_scale_roots_degree : (normalize_scale_roots p).degree = p.degree := begin apply le_antisymm, { exact finset.sup_mono (normalize_scale_roots_support p) }, { rw [← degree_scale_roots, ← leading_coeff_smul_normalize_scale_roots], exact degree_smul_le _ _ } end lemma normalize_scale_roots_eval₂_leading_coeff_mul (h : 1 ≤ p.nat_degree) (f : R →+* S) (x : S) : (normalize_scale_roots p).eval₂ f (f p.leading_coeff * x) = f p.leading_coeff ^ (p.nat_degree - 1) * (p.eval₂ f x) := begin rw [eval₂_eq_sum_range, eval₂_eq_sum_range, finset.mul_sum], apply finset.sum_congr, { rw nat_degree_eq_of_degree_eq (normalize_scale_roots_degree p) }, intros n hn, rw [mul_pow, ← mul_assoc, ← f.map_pow, ← f.map_mul, normalize_scale_roots_coeff_mul_leading_coeff_pow _ _ h, f.map_mul, f.map_pow], ring, end lemma normalize_scale_roots_monic (h : p ≠ 0) : (normalize_scale_roots p).monic := begin delta monic leading_coeff, rw nat_degree_eq_of_degree_eq (normalize_scale_roots_degree p), suffices : p = 0 → (0 : R) = 1, { simpa [normalize_scale_roots, coeff_monomial] }, exact λ h', (h h').rec _, end /-- Given a `p : polynomial R` and a `x : S` such that `p.eval₂ f x = 0`, `f p.leading_coeff * x` is integral. -/ lemma ring_hom.is_integral_elem_leading_coeff_mul (h : p.eval₂ f x = 0) : f.is_integral_elem (f p.leading_coeff * x) := begin by_cases h' : 1 ≤ p.nat_degree, { use normalize_scale_roots p, have : p ≠ 0 := λ h'', by { rw [h'', nat_degree_zero] at h', exact nat.not_succ_le_zero 0 h' }, use normalize_scale_roots_monic p this, rw [normalize_scale_roots_eval₂_leading_coeff_mul p h' f x, h, mul_zero] }, { by_cases hp : p.map f = 0, { apply_fun (λ q, coeff q p.nat_degree) at hp, rw [coeff_map, coeff_zero, coeff_nat_degree] at hp, rw [hp, zero_mul], exact f.is_integral_zero }, { rw [nat.one_le_iff_ne_zero, not_not] at h', rw [eq_C_of_nat_degree_eq_zero h', eval₂_C] at h, suffices : p.map f = 0, { exact (hp this).rec _ }, rw [eq_C_of_nat_degree_eq_zero h', map_C, h, C_eq_zero] } } end /-- Given a `p : polynomial R` and a root `x : S`, then `p.leading_coeff • x : S` is integral over `R`. -/ lemma is_integral_leading_coeff_smul [algebra R S] (h : aeval x p = 0) : is_integral R (p.leading_coeff • x) := begin rw aeval_def at h, rw algebra.smul_def, exact (algebra_map R S).is_integral_elem_leading_coeff_mul p x h, end end end section is_integral_closure /-- `is_integral_closure A R B` is the characteristic predicate stating `A` is the integral closure of `R` in `B`, i.e. that an element of `B` is integral over `R` iff it is an element of (the image of) `A`. -/ class is_integral_closure (A R B : Type*) [comm_ring R] [comm_semiring A] [comm_ring B] [algebra R B] [algebra A B] : Prop := (algebra_map_injective [] : function.injective (algebra_map A B)) (is_integral_iff : ∀ {x : B}, is_integral R x ↔ ∃ y, algebra_map A B y = x) instance integral_closure.is_integral_closure (R A : Type*) [comm_ring R] [comm_ring A] [algebra R A] : is_integral_closure (integral_closure R A) R A := ⟨subtype.coe_injective, λ x, ⟨λ h, ⟨⟨x, h⟩, rfl⟩, by { rintro ⟨⟨_, h⟩, rfl⟩, exact h }⟩⟩ namespace is_integral_closure variables {R A B : Type*} [comm_ring R] [comm_ring A] [comm_ring B] variables [algebra R B] [algebra A B] [is_integral_closure A R B] variables (R) {A} (B) protected theorem is_integral [algebra R A] [is_scalar_tower R A B] (x : A) : is_integral R x := (is_integral_algebra_map_iff (algebra_map_injective A R B)).mp $ show is_integral R (algebra_map A B x), from is_integral_iff.mpr ⟨x, rfl⟩ theorem is_integral_algebra [algebra R A] [is_scalar_tower R A B] : algebra.is_integral R A := λ x, is_integral_closure.is_integral R B x variables {R} (A) {B} /-- If `x : B` is integral over `R`, then it is an element of the integral closure of `R` in `B`. -/ noncomputable def mk' (x : B) (hx : is_integral R x) : A := classical.some (is_integral_iff.mp hx) @[simp] lemma algebra_map_mk' (x : B) (hx : is_integral R x) : algebra_map A B (mk' A x hx) = x := classical.some_spec (is_integral_iff.mp hx) @[simp] lemma mk'_one (h : is_integral R (1 : B) := is_integral_one) : mk' A 1 h = 1 := algebra_map_injective A R B $ by rw [algebra_map_mk', ring_hom.map_one] @[simp] lemma mk'_zero (h : is_integral R (0 : B) := is_integral_zero) : mk' A 0 h = 0 := algebra_map_injective A R B $ by rw [algebra_map_mk', ring_hom.map_zero] @[simp] lemma mk'_add (x y : B) (hx : is_integral R x) (hy : is_integral R y) : mk' A (x + y) (is_integral_add hx hy) = mk' A x hx + mk' A y hy := algebra_map_injective A R B $ by simp only [algebra_map_mk', ring_hom.map_add] @[simp] lemma mk'_mul (x y : B) (hx : is_integral R x) (hy : is_integral R y) : mk' A (x * y) (is_integral_mul hx hy) = mk' A x hx * mk' A y hy := algebra_map_injective A R B $ by simp only [algebra_map_mk', ring_hom.map_mul] @[simp] lemma mk'_algebra_map [algebra R A] [is_scalar_tower R A B] (x : R) (h : is_integral R (algebra_map R B x) := is_integral_algebra_map) : is_integral_closure.mk' A (algebra_map R B x) h = algebra_map R A x := algebra_map_injective A R B $ by rw [algebra_map_mk', ← is_scalar_tower.algebra_map_apply] section lift variables {R} (A B) {S : Type*} [comm_ring S] [algebra R S] [algebra S B] [is_scalar_tower R S B] variables [algebra R A] [is_scalar_tower R A B] (h : algebra.is_integral R S) /-- If `B / S / R` is a tower of ring extensions where `S` is integral over `R`, then `S` maps (uniquely) into an integral closure `B / A / R`. -/ noncomputable def lift : S →ₐ[R] A := { to_fun := λ x, mk' A (algebra_map S B x) (is_integral.algebra_map (h x)), map_one' := by simp only [ring_hom.map_one, mk'_one], map_zero' := by simp only [ring_hom.map_zero, mk'_zero], map_add' := λ x y, by simp_rw [← mk'_add, ring_hom.map_add], map_mul' := λ x y, by simp_rw [← mk'_mul, ring_hom.map_mul], commutes' := λ x, by simp_rw [← is_scalar_tower.algebra_map_apply, mk'_algebra_map] } @[simp] lemma algebra_map_lift (x : S) : algebra_map A B (lift A B h x) = algebra_map S B x := algebra_map_mk' _ _ _ end lift section equiv variables (R A B) (A' : Type*) [comm_ring A'] [algebra A' B] [is_integral_closure A' R B] variables [algebra R A] [algebra R A'] [is_scalar_tower R A B] [is_scalar_tower R A' B] /-- Integral closures are all isomorphic to each other. -/ noncomputable def equiv : A ≃ₐ[R] A' := alg_equiv.of_alg_hom (lift _ B (is_integral_algebra R B)) (lift _ B (is_integral_algebra R B)) (by { ext x, apply algebra_map_injective A' R B, simp }) (by { ext x, apply algebra_map_injective A R B, simp }) @[simp] lemma algebra_map_equiv (x : A) : algebra_map A' B (equiv R A B A' x) = algebra_map A B x := algebra_map_lift _ _ _ _ end equiv end is_integral_closure end is_integral_closure section algebra open algebra variables {R A B S T : Type*} variables [comm_ring R] [comm_ring A] [comm_ring B] [comm_ring S] [comm_ring T] variables [algebra A B] [algebra R B] (f : R →+* S) (g : S →+* T) lemma is_integral_trans_aux (x : B) {p : polynomial A} (pmonic : monic p) (hp : aeval x p = 0) : is_integral (adjoin R (↑(p.map $ algebra_map A B).frange : set B)) x := begin generalize hS : (↑(p.map $ algebra_map A B).frange : set B) = S, have coeffs_mem : ∀ i, (p.map $ algebra_map A B).coeff i ∈ adjoin R S, { intro i, by_cases hi : (p.map $ algebra_map A B).coeff i = 0, { rw hi, exact subalgebra.zero_mem _ }, rw ← hS, exact subset_adjoin (coeff_mem_frange _ _ hi) }, obtain ⟨q, hq⟩ : ∃ q : polynomial (adjoin R S), q.map (algebra_map (adjoin R S) B) = (p.map $ algebra_map A B), { rw ← set.mem_range, exact (polynomial.mem_map_range _).2 (λ i, ⟨⟨_, coeffs_mem i⟩, rfl⟩) }, use q, split, { suffices h : (q.map (algebra_map (adjoin R S) B)).monic, { refine monic_of_injective _ h, exact subtype.val_injective }, { rw hq, exact monic_map _ pmonic } }, { convert hp using 1, replace hq := congr_arg (eval x) hq, convert hq using 1; symmetry; apply eval_map }, end variables [algebra R A] [is_scalar_tower R A B] /-- If A is an R-algebra all of whose elements are integral over R, and x is an element of an A-algebra that is integral over A, then x is integral over R.-/ lemma is_integral_trans (A_int : is_integral R A) (x : B) (hx : is_integral A x) : is_integral R x := begin rcases hx with ⟨p, pmonic, hp⟩, let S : set B := ↑(p.map $ algebra_map A B).frange, refine is_integral_of_mem_of_fg (adjoin R (S ∪ {x})) _ _ (subset_adjoin $ or.inr rfl), refine fg_trans (fg_adjoin_of_finite (finset.finite_to_set _) (λ x hx, _)) _, { rw [finset.mem_coe, frange, finset.mem_image] at hx, rcases hx with ⟨i, _, rfl⟩, rw coeff_map, exact is_integral_alg_hom (is_scalar_tower.to_alg_hom R A B) (A_int _) }, { apply fg_adjoin_singleton_of_integral, exact is_integral_trans_aux _ pmonic hp } end /-- If A is an R-algebra all of whose elements are integral over R, and B is an A-algebra all of whose elements are integral over A, then all elements of B are integral over R.-/ lemma algebra.is_integral_trans (hA : is_integral R A) (hB : is_integral A B) : is_integral R B := λ x, is_integral_trans hA x (hB x) lemma ring_hom.is_integral_trans (hf : f.is_integral) (hg : g.is_integral) : (g.comp f).is_integral := @algebra.is_integral_trans R S T _ _ _ g.to_algebra (g.comp f).to_algebra f.to_algebra (@is_scalar_tower.of_algebra_map_eq R S T _ _ _ f.to_algebra g.to_algebra (g.comp f).to_algebra (ring_hom.comp_apply g f)) hf hg lemma ring_hom.is_integral_of_surjective (hf : function.surjective f) : f.is_integral := λ x, (hf x).rec_on (λ y hy, (hy ▸ f.is_integral_map : f.is_integral_elem x)) lemma is_integral_of_surjective (h : function.surjective (algebra_map R A)) : is_integral R A := (algebra_map R A).is_integral_of_surjective h /-- If `R → A → B` is an algebra tower with `A → B` injective, then if the entire tower is an integral extension so is `R → A` -/ lemma is_integral_tower_bot_of_is_integral (H : function.injective (algebra_map A B)) {x : A} (h : is_integral R (algebra_map A B x)) : is_integral R x := begin rcases h with ⟨p, ⟨hp, hp'⟩⟩, refine ⟨p, ⟨hp, _⟩⟩, rw [is_scalar_tower.algebra_map_eq R A B, ← eval₂_map, eval₂_hom, ← ring_hom.map_zero (algebra_map A B)] at hp', rw [eval₂_eq_eval_map], exact H hp', end lemma ring_hom.is_integral_tower_bot_of_is_integral (hg : function.injective g) (hfg : (g.comp f).is_integral) : f.is_integral := λ x, @is_integral_tower_bot_of_is_integral R S T _ _ _ g.to_algebra (g.comp f).to_algebra f.to_algebra (@is_scalar_tower.of_algebra_map_eq R S T _ _ _ f.to_algebra g.to_algebra (g.comp f).to_algebra (ring_hom.comp_apply g f)) hg x (hfg (g x)) lemma is_integral_tower_bot_of_is_integral_field {R A B : Type*} [comm_ring R] [field A] [comm_ring B] [nontrivial B] [algebra R A] [algebra A B] [algebra R B] [is_scalar_tower R A B] {x : A} (h : is_integral R (algebra_map A B x)) : is_integral R x := is_integral_tower_bot_of_is_integral (algebra_map A B).injective h lemma ring_hom.is_integral_elem_of_is_integral_elem_comp {x : T} (h : (g.comp f).is_integral_elem x) : g.is_integral_elem x := let ⟨p, ⟨hp, hp'⟩⟩ := h in ⟨p.map f, monic_map f hp, by rwa ← eval₂_map at hp'⟩ lemma ring_hom.is_integral_tower_top_of_is_integral (h : (g.comp f).is_integral) : g.is_integral := λ x, ring_hom.is_integral_elem_of_is_integral_elem_comp f g (h x) /-- If `R → A → B` is an algebra tower, then if the entire tower is an integral extension so is `A → B`. -/ lemma is_integral_tower_top_of_is_integral {x : B} (h : is_integral R x) : is_integral A x := begin rcases h with ⟨p, ⟨hp, hp'⟩⟩, refine ⟨p.map (algebra_map R A), ⟨monic_map (algebra_map R A) hp, _⟩⟩, rw [is_scalar_tower.algebra_map_eq R A B, ← eval₂_map] at hp', exact hp', end lemma ring_hom.is_integral_quotient_of_is_integral {I : ideal S} (hf : f.is_integral) : (ideal.quotient_map I f le_rfl).is_integral := begin rintros ⟨x⟩, obtain ⟨p, ⟨p_monic, hpx⟩⟩ := hf x, refine ⟨p.map (ideal.quotient.mk _), ⟨monic_map _ p_monic, _⟩⟩, simpa only [hom_eval₂, eval₂_map] using congr_arg (ideal.quotient.mk I) hpx end lemma is_integral_quotient_of_is_integral {I : ideal A} (hRA : is_integral R A) : is_integral (R ⧸ I.comap (algebra_map R A)) (A ⧸ I) := (algebra_map R A).is_integral_quotient_of_is_integral hRA lemma is_integral_quotient_map_iff {I : ideal S} : (ideal.quotient_map I f le_rfl).is_integral ↔ ((ideal.quotient.mk I).comp f : R →+* S ⧸ I).is_integral := begin let g := ideal.quotient.mk (I.comap f), have := ideal.quotient_map_comp_mk le_rfl, refine ⟨λ h, _, λ h, ring_hom.is_integral_tower_top_of_is_integral g _ (this ▸ h)⟩, refine this ▸ ring_hom.is_integral_trans g (ideal.quotient_map I f le_rfl) _ h, exact ring_hom.is_integral_of_surjective g ideal.quotient.mk_surjective, end /-- If the integral extension `R → S` is injective, and `S` is a field, then `R` is also a field. -/ lemma is_field_of_is_integral_of_is_field {R S : Type*} [comm_ring R] [nontrivial R] [comm_ring S] [is_domain S] [algebra R S] (H : is_integral R S) (hRS : function.injective (algebra_map R S)) (hS : is_field S) : is_field R := begin refine ⟨⟨0, 1, zero_ne_one⟩, mul_comm, λ a ha, _⟩, -- Let `a_inv` be the inverse of `algebra_map R S a`, -- then we need to show that `a_inv` is of the form `algebra_map R S b`. obtain ⟨a_inv, ha_inv⟩ := hS.mul_inv_cancel (λ h, ha (hRS (trans h (ring_hom.map_zero _).symm))), -- Let `p : polynomial R` be monic with root `a_inv`, -- and `q` be `p` with coefficients reversed (so `q(a) = q'(a) * a + 1`). -- We claim that `q(a) = 0`, so `-q'(a)` is the inverse of `a`. obtain ⟨p, p_monic, hp⟩ := H a_inv, use -∑ (i : ℕ) in finset.range p.nat_degree, (p.coeff i) * a ^ (p.nat_degree - i - 1), -- `q(a) = 0`, because multiplying everything with `a_inv^n` gives `p(a_inv) = 0`. -- TODO: this could be a lemma for `polynomial.reverse`. have hq : ∑ (i : ℕ) in finset.range (p.nat_degree + 1), (p.coeff i) * a ^ (p.nat_degree - i) = 0, { apply (algebra_map R S).injective_iff.mp hRS, have a_inv_ne_zero : a_inv ≠ 0 := right_ne_zero_of_mul (mt ha_inv.symm.trans one_ne_zero), refine (mul_eq_zero.mp _).resolve_right (pow_ne_zero p.nat_degree a_inv_ne_zero), rw [eval₂_eq_sum_range] at hp, rw [ring_hom.map_sum, finset.sum_mul], refine (finset.sum_congr rfl (λ i hi, _)).trans hp, rw [ring_hom.map_mul, mul_assoc], congr, have : a_inv ^ p.nat_degree = a_inv ^ (p.nat_degree - i) * a_inv ^ i, { rw [← pow_add a_inv, tsub_add_cancel_of_le (nat.le_of_lt_succ (finset.mem_range.mp hi))] }, rw [ring_hom.map_pow, this, ← mul_assoc, ← mul_pow, ha_inv, one_pow, one_mul] }, -- Since `q(a) = 0` and `q(a) = q'(a) * a + 1`, we have `a * -q'(a) = 1`. -- TODO: we could use a lemma for `polynomial.div_X` here. rw [finset.sum_range_succ_comm, p_monic.coeff_nat_degree, one_mul, tsub_self, pow_zero, add_eq_zero_iff_eq_neg, eq_comm] at hq, rw [mul_comm, ← neg_mul_eq_neg_mul, finset.sum_mul], convert hq using 2, refine finset.sum_congr rfl (λ i hi, _), have : 1 ≤ p.nat_degree - i := le_tsub_of_add_le_left (finset.mem_range.mp hi), rw [mul_assoc, ← pow_succ', tsub_add_cancel_of_le this] end lemma is_field_of_is_integral_of_is_field' {R S : Type*} [comm_ring R] [comm_ring S] [is_domain S] [algebra R S] (H : algebra.is_integral R S) (hR : is_field R) : is_field S := begin letI := hR.to_field R, refine ⟨⟨0, 1, zero_ne_one⟩, mul_comm, λ x hx, _⟩, let A := algebra.adjoin R ({x} : set S), haveI : is_noetherian R A := is_noetherian_of_fg_of_noetherian A.to_submodule (fg_adjoin_singleton_of_integral x (H x)), haveI : module.finite R A := module.is_noetherian.finite R A, obtain ⟨y, hy⟩ := linear_map.surjective_of_injective (@lmul_left_injective R A _ _ _ _ ⟨x, subset_adjoin (set.mem_singleton x)⟩ (λ h, hx (subtype.ext_iff.mp h))) 1, exact ⟨y, subtype.ext_iff.mp hy⟩, end lemma is_integral.is_field_iff_is_field {R S : Type*} [comm_ring R] [nontrivial R] [comm_ring S] [is_domain S] [algebra R S] (H : algebra.is_integral R S) (hRS : function.injective (algebra_map R S)) : is_field R ↔ is_field S := ⟨is_field_of_is_integral_of_is_field' H, is_field_of_is_integral_of_is_field H hRS⟩ end algebra theorem integral_closure_idem {R : Type*} {A : Type*} [comm_ring R] [comm_ring A] [algebra R A] : integral_closure (integral_closure R A : set A) A = ⊥ := eq_bot_iff.2 $ λ x hx, algebra.mem_bot.2 ⟨⟨x, @is_integral_trans _ _ _ _ _ _ _ _ (integral_closure R A).algebra _ integral_closure.is_integral x hx⟩, rfl⟩ section is_domain variables {R S : Type*} [comm_ring R] [comm_ring S] [is_domain S] [algebra R S] instance : is_domain (integral_closure R S) := infer_instance end is_domain
c410f474fe3c2af57a41ef91590b8f587403f4b9
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/data/nat/digits.lean
a69c1ce229fe611a22fbed896a41dae35c771c9d
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
22,853
lean
/- Copyright (c) 2020 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison, Shing Tak Lam, Mario Carneiro -/ import data.int.modeq import data.nat.bits import data.nat.log import data.list.indexes import data.list.palindrome import algebra.parity import tactic.interval_cases import tactic.linarith /-! # Digits of a natural number > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This provides a basic API for extracting the digits of a natural number in a given base, and reconstructing numbers from their digits. We also prove some divisibility tests based on digits, in particular completing Theorem #85 from https://www.cs.ru.nl/~freek/100/. A basic `norm_digits` tactic is also provided for proving goals of the form `nat.digits a b = l` where `a` and `b` are numerals. -/ namespace nat variables {n : ℕ} /-- (Impl.) An auxiliary definition for `digits`, to help get the desired definitional unfolding. -/ def digits_aux_0 : ℕ → list ℕ | 0 := [] | (n+1) := [n+1] /-- (Impl.) An auxiliary definition for `digits`, to help get the desired definitional unfolding. -/ def digits_aux_1 (n : ℕ) : list ℕ := list.replicate n 1 /-- (Impl.) An auxiliary definition for `digits`, to help get the desired definitional unfolding. -/ def digits_aux (b : ℕ) (h : 2 ≤ b) : ℕ → list ℕ | 0 := [] | (n+1) := have (n+1)/b < n+1 := nat.div_lt_self (nat.succ_pos _) h, (n+1) % b :: digits_aux ((n+1)/b) @[simp] lemma digits_aux_zero (b : ℕ) (h : 2 ≤ b) : digits_aux b h 0 = [] := by rw digits_aux lemma digits_aux_def (b : ℕ) (h : 2 ≤ b) (n : ℕ) (w : 0 < n) : digits_aux b h n = n % b :: digits_aux b h (n/b) := begin cases n, { cases w, }, { rw [digits_aux], } end /-- `digits b n` gives the digits, in little-endian order, of a natural number `n` in a specified base `b`. In any base, we have `of_digits b L = L.foldr (λ x y, x + b * y) 0`. * For any `2 ≤ b`, we have `l < b` for any `l ∈ digits b n`, and the last digit is not zero. This uniquely specifies the behaviour of `digits b`. * For `b = 1`, we define `digits 1 n = list.replicate n 1`. * For `b = 0`, we define `digits 0 n = [n]`, except `digits 0 0 = []`. Note this differs from the existing `nat.to_digits` in core, which is used for printing numerals. In particular, `nat.to_digits b 0 = [0]`, while `digits b 0 = []`. -/ def digits : ℕ → ℕ → list ℕ | 0 := digits_aux_0 | 1 := digits_aux_1 | (b+2) := digits_aux (b+2) (by norm_num) @[simp] lemma digits_zero (b : ℕ) : digits b 0 = [] := by rcases b with _|⟨_|⟨_⟩⟩; simp [digits, digits_aux_0, digits_aux_1] @[simp] lemma digits_zero_zero : digits 0 0 = [] := rfl @[simp] lemma digits_zero_succ (n : ℕ) : digits 0 (n.succ) = [n+1] := rfl theorem digits_zero_succ' : ∀ {n : ℕ}, n ≠ 0 → digits 0 n = [n] | 0 h := (h rfl).elim | (n+1) _ := rfl @[simp] lemma digits_one (n : ℕ) : digits 1 n = list.replicate n 1 := rfl @[simp] lemma digits_one_succ (n : ℕ) : digits 1 (n + 1) = 1 :: digits 1 n := rfl @[simp] lemma digits_add_two_add_one (b n : ℕ) : digits (b+2) (n+1) = (((n+1) % (b+2)) :: digits (b+2) ((n+1) / (b+2))) := by { rw [digits, digits_aux_def], exact succ_pos n } theorem digits_def' : ∀ {b : ℕ} (h : 1 < b) {n : ℕ} (w : 0 < n), digits b n = n % b :: digits b (n/b) | 0 h := absurd h dec_trivial | 1 h := absurd h dec_trivial | (b+2) h := digits_aux_def _ _ @[simp] lemma digits_of_lt (b x : ℕ) (hx : x ≠ 0) (hxb : x < b) : digits b x = [x] := begin rcases exists_eq_succ_of_ne_zero hx with ⟨x, rfl⟩, rcases exists_eq_add_of_le' ((nat.le_add_left 1 x).trans_lt hxb) with ⟨b, rfl⟩, rw [digits_add_two_add_one, div_eq_of_lt hxb, digits_zero, mod_eq_of_lt hxb] end lemma digits_add (b : ℕ) (h : 1 < b) (x y : ℕ) (hxb : x < b) (hxy : x ≠ 0 ∨ y ≠ 0) : digits b (x + b * y) = x :: digits b y := begin rcases exists_eq_add_of_le' h with ⟨b, rfl : _ = _ + 2⟩, cases y, { simp [hxb, hxy.resolve_right (absurd rfl)] }, dsimp [digits], rw digits_aux_def, { congr, { simp [nat.add_mod, mod_eq_of_lt hxb], }, { simp [add_mul_div_left, div_eq_of_lt hxb] } }, { apply nat.succ_pos } end /-- `of_digits b L` takes a list `L` of natural numbers, and interprets them as a number in semiring, as the little-endian digits in base `b`. -/ -- If we had a function converting a list into a polynomial, -- and appropriate lemmas about that function, -- we could rewrite this in terms of that. def of_digits {α : Type*} [semiring α] (b : α) : list ℕ → α | [] := 0 | (h :: t) := h + b * of_digits t lemma of_digits_eq_foldr {α : Type*} [semiring α] (b : α) (L : list ℕ) : of_digits b L = L.foldr (λ x y, x + b * y) 0 := begin induction L with d L ih, { refl, }, { dsimp [of_digits], rw ih, }, end lemma of_digits_eq_sum_map_with_index_aux (b : ℕ) (l : list ℕ) : ((list.range l.length).zip_with ((λ (i a : ℕ), a * b ^ i) ∘ succ) l).sum = b * ((list.range l.length).zip_with (λ i a, a * b ^ i) l).sum := begin suffices : (list.range l.length).zip_with (((λ (i a : ℕ), a * b ^ i) ∘ succ)) l = (list.range l.length).zip_with (λ i a, b * (a * b ^ i)) l, { simp [this] }, congr, ext, simp [pow_succ], ring end lemma of_digits_eq_sum_map_with_index (b : ℕ) (L : list ℕ): of_digits b L = (L.map_with_index (λ i a, a * b ^ i)).sum := begin rw [list.map_with_index_eq_enum_map, list.enum_eq_zip_range, list.map_uncurry_zip_eq_zip_with, of_digits_eq_foldr], induction L with hd tl hl, { simp }, { simpa [list.range_succ_eq_map, list.zip_with_map_left, of_digits_eq_sum_map_with_index_aux] using or.inl hl } end @[simp] lemma of_digits_singleton {b n : ℕ} : of_digits b [n] = n := by simp [of_digits] @[simp] lemma of_digits_one_cons {α : Type*} [semiring α] (h : ℕ) (L : list ℕ) : of_digits (1 : α) (h :: L) = h + of_digits 1 L := by simp [of_digits] lemma of_digits_append {b : ℕ} {l1 l2 : list ℕ} : of_digits b (l1 ++ l2) = of_digits b l1 + b^(l1.length) * of_digits b l2 := begin induction l1 with hd tl IH, { simp [of_digits] }, { rw [of_digits, list.cons_append, of_digits, IH, list.length_cons, pow_succ'], ring } end @[norm_cast] lemma coe_of_digits (α : Type*) [semiring α] (b : ℕ) (L : list ℕ) : ((of_digits b L : ℕ) : α) = of_digits (b : α) L := begin induction L with d L ih, { simp [of_digits], }, { dsimp [of_digits], push_cast, rw ih, } end @[norm_cast] lemma coe_int_of_digits (b : ℕ) (L : list ℕ) : ((of_digits b L : ℕ) : ℤ) = of_digits (b : ℤ) L := begin induction L with d L ih, { refl, }, { dsimp [of_digits], push_cast } end lemma digits_zero_of_eq_zero {b : ℕ} (h : b ≠ 0) : ∀ {L : list ℕ} (h0 : of_digits b L = 0) (l ∈ L), l = 0 | (a :: L) h0 l (or.inl rfl) := nat.eq_zero_of_add_eq_zero_right h0 | (a :: L) h0 l (or.inr hL) := digits_zero_of_eq_zero (mul_right_injective₀ h (nat.eq_zero_of_add_eq_zero_left h0)) _ hL lemma digits_of_digits (b : ℕ) (h : 1 < b) (L : list ℕ) (w₁ : ∀ l ∈ L, l < b) (w₂ : ∀ (h : L ≠ []), L.last h ≠ 0) : digits b (of_digits b L) = L := begin induction L with d L ih, { dsimp [of_digits], simp }, { dsimp [of_digits], replace w₂ := w₂ (by simp), rw digits_add b h, { rw ih, { intros l m, apply w₁, exact list.mem_cons_of_mem _ m, }, { intro h, { rw [list.last_cons h] at w₂, convert w₂, }}}, { exact w₁ d (list.mem_cons_self _ _) }, { by_cases h' : L = [], { rcases h' with rfl, left, simpa using w₂ }, { right, contrapose! w₂, refine digits_zero_of_eq_zero h.ne_bot w₂ _ _, rw list.last_cons h', exact list.last_mem h' } } } end lemma of_digits_digits (b n : ℕ) : of_digits b (digits b n) = n := begin cases b with b, { cases n with n, { refl, }, { change of_digits 0 [n+1] = n+1, dsimp [of_digits], simp, } }, { cases b with b, { induction n with n ih, { refl, }, { simp only [ih, add_comm 1, of_digits_one_cons, nat.cast_id, digits_one_succ], } }, { apply nat.strong_induction_on n _, clear n, intros n h, cases n, { rw digits_zero, refl, }, { simp only [nat.succ_eq_add_one, digits_add_two_add_one], dsimp [of_digits], rw h _ (nat.div_lt_self' n b), rw [nat.mod_add_div], }, }, }, end lemma of_digits_one (L : list ℕ) : of_digits 1 L = L.sum := begin induction L with d L ih, { refl, }, { simp [of_digits, list.sum_cons, ih], } end /-! ### Properties This section contains various lemmas of properties relating to `digits` and `of_digits`. -/ lemma digits_eq_nil_iff_eq_zero {b n : ℕ} : digits b n = [] ↔ n = 0 := begin split, { intro h, have : of_digits b (digits b n) = of_digits b [], by rw h, convert this, rw of_digits_digits }, { rintro rfl, simp } end lemma digits_ne_nil_iff_ne_zero {b n : ℕ} : digits b n ≠ [] ↔ n ≠ 0 := not_congr digits_eq_nil_iff_eq_zero lemma digits_eq_cons_digits_div {b n : ℕ} (h : 1 < b) (w : n ≠ 0) : digits b n = ((n % b) :: digits b (n / b)) := begin rcases b with _|_|b, { rw [digits_zero_succ' w, nat.mod_zero, nat.div_zero, nat.digits_zero_zero] }, { norm_num at h }, rcases n with _|n, { norm_num at w }, simp, end lemma digits_last {b : ℕ} (m : ℕ) (h : 1 < b) (p q) : (digits b m).last p = (digits b (m/b)).last q := begin by_cases hm : m = 0, { simp [hm], }, simp only [digits_eq_cons_digits_div h hm], rw list.last_cons, end lemma digits.injective (b : ℕ) : function.injective b.digits := function.left_inverse.injective (of_digits_digits b) @[simp] lemma digits_inj_iff {b n m : ℕ} : b.digits n = b.digits m ↔ n = m := (digits.injective b).eq_iff lemma digits_len (b n : ℕ) (hb : 1 < b) (hn : n ≠ 0) : (b.digits n).length = b.log n + 1 := begin induction n using nat.strong_induction_on with n IH, rw [digits_eq_cons_digits_div hb hn, list.length], by_cases h : n / b = 0, { have hb0 : b ≠ 0 := (nat.succ_le_iff.1 hb).ne_bot, simp [h, log_eq_zero_iff, ← nat.div_eq_zero_iff hb0.bot_lt] }, { have hb' : 1 < b := one_lt_two.trans_le hb, have : n / b < n := div_lt_self (nat.pos_of_ne_zero hn) hb', rw [IH _ this h, log_div_base, tsub_add_cancel_of_le], refine nat.succ_le_of_lt (log_pos hb' _), contrapose! h, exact div_eq_of_lt h } end lemma last_digit_ne_zero (b : ℕ) {m : ℕ} (hm : m ≠ 0) : (digits b m).last (digits_ne_nil_iff_ne_zero.mpr hm) ≠ 0 := begin rcases b with _|_|b, { cases m, { cases hm rfl }, { simp } }, { cases m, { cases hm rfl }, simpa only [digits_one, list.last_replicate_succ m 1] using one_ne_zero }, revert hm, apply nat.strong_induction_on m, intros n IH hn, by_cases hnb : n < b + 2, { simpa only [digits_of_lt (b + 2) n hn hnb] }, { rw digits_last n (show 2 ≤ b + 2, from dec_trivial), refine IH _ (nat.div_lt_self hn.bot_lt dec_trivial) _, { rw ←pos_iff_ne_zero, exact nat.div_pos (le_of_not_lt hnb) dec_trivial } }, end /-- The digits in the base b+2 expansion of n are all less than b+2 -/ lemma digits_lt_base' {b m : ℕ} : ∀ {d}, d ∈ digits (b+2) m → d < b+2 := begin apply nat.strong_induction_on m, intros n IH d hd, cases n with n, { rw digits_zero at hd, cases hd }, -- base b+2 expansion of 0 has no digits rw digits_add_two_add_one at hd, cases hd, { rw hd, exact n.succ.mod_lt (by linarith) }, { exact IH _ (nat.div_lt_self (nat.succ_pos _) (by linarith)) hd } end /-- The digits in the base b expansion of n are all less than b, if b ≥ 2 -/ lemma digits_lt_base {b m d : ℕ} (hb : 1 < b) (hd : d ∈ digits b m) : d < b := begin rcases b with _ | _ | b; try {linarith}, exact digits_lt_base' hd, end /-- an n-digit number in base b + 2 is less than (b + 2)^n -/ lemma of_digits_lt_base_pow_length' {b : ℕ} {l : list ℕ} (hl : ∀ x ∈ l, x < b+2) : of_digits (b+2) l < (b+2)^(l.length) := begin induction l with hd tl IH, { simp [of_digits], }, { rw [of_digits, list.length_cons, pow_succ], have : (of_digits (b + 2) tl + 1) * (b+2) ≤ (b + 2) ^ tl.length * (b+2) := mul_le_mul (IH (λ x hx, hl _ (list.mem_cons_of_mem _ hx))) (by refl) dec_trivial (nat.zero_le _), suffices : ↑hd < b + 2, { linarith }, norm_cast, exact hl hd (list.mem_cons_self _ _) } end /-- an n-digit number in base b is less than b^n if b > 1 -/ lemma of_digits_lt_base_pow_length {b : ℕ} {l : list ℕ} (hb : 1 < b) (hl : ∀ x ∈ l, x < b) : of_digits b l < b^l.length := begin rcases b with _ | _ | b; try { linarith }, exact of_digits_lt_base_pow_length' hl, end /-- Any number m is less than (b+2)^(number of digits in the base b + 2 representation of m) -/ lemma lt_base_pow_length_digits' {b m : ℕ} : m < (b + 2) ^ (digits (b + 2) m).length := begin convert of_digits_lt_base_pow_length' (λ _, digits_lt_base'), rw of_digits_digits (b+2) m, end /-- Any number m is less than b^(number of digits in the base b representation of m) -/ lemma lt_base_pow_length_digits {b m : ℕ} (hb : 1 < b) : m < b^(digits b m).length := begin rcases b with _ | _ | b; try { linarith }, exact lt_base_pow_length_digits', end lemma of_digits_digits_append_digits {b m n : ℕ} : of_digits b (digits b n ++ digits b m) = n + b ^ (digits b n).length * m:= by rw [of_digits_append, of_digits_digits, of_digits_digits] lemma digits_len_le_digits_len_succ (b n : ℕ) : (digits b n).length ≤ (digits b (n + 1)).length := begin rcases decidable.eq_or_ne n 0 with rfl|hn, { simp }, cases le_or_lt b 1 with hb hb, { interval_cases b; simp [digits_zero_succ', hn] }, simpa [digits_len, hb, hn] using log_mono_right (le_succ _) end lemma le_digits_len_le (b n m : ℕ) (h : n ≤ m) : (digits b n).length ≤ (digits b m).length := monotone_nat_of_le_succ (digits_len_le_digits_len_succ b) h lemma pow_length_le_mul_of_digits {b : ℕ} {l : list ℕ} (hl : l ≠ []) (hl2 : l.last hl ≠ 0): (b + 2) ^ l.length ≤ (b + 2) * of_digits (b+2) l := begin rw [←list.init_append_last hl], simp only [list.length_append, list.length, zero_add, list.length_init, of_digits_append, list.length_init, of_digits_singleton, add_comm (l.length - 1), pow_add, pow_one], apply nat.mul_le_mul_left, refine le_trans _ (nat.le_add_left _ _), have : 0 < l.last hl, { rwa [pos_iff_ne_zero] }, convert nat.mul_le_mul_left _ this, rw [mul_one] end /-- Any non-zero natural number `m` is greater than (b+2)^((number of digits in the base (b+2) representation of m) - 1) -/ lemma base_pow_length_digits_le' (b m : ℕ) (hm : m ≠ 0) : (b + 2) ^ ((digits (b + 2) m).length) ≤ (b + 2) * m := begin have : digits (b + 2) m ≠ [], from digits_ne_nil_iff_ne_zero.mpr hm, convert pow_length_le_mul_of_digits this (last_digit_ne_zero _ hm), rwa of_digits_digits, end /-- Any non-zero natural number `m` is greater than b^((number of digits in the base b representation of m) - 1) -/ lemma base_pow_length_digits_le (b m : ℕ) (hb : 1 < b): m ≠ 0 → b ^ ((digits b m).length) ≤ b * m := begin rcases b with _ | _ | b; try { linarith }, exact base_pow_length_digits_le' b m, end /-! ### Binary -/ lemma digits_two_eq_bits (n : ℕ) : digits 2 n = n.bits.map (λ b, cond b 1 0) := begin induction n using nat.binary_rec_from_one with b n h ih, { simp, }, { simp, }, rw bits_append_bit _ _ (λ hn, absurd hn h), cases b, { rw digits_def' one_lt_two, { simpa [nat.bit, nat.bit0_val n], }, { simpa [pos_iff_ne_zero, bit_eq_zero_iff], }, }, { simpa [nat.bit, nat.bit1_val n, add_comm, digits_add 2 one_lt_two 1 n] }, end /-! ### Modular Arithmetic -/ -- This is really a theorem about polynomials. lemma dvd_of_digits_sub_of_digits {α : Type*} [comm_ring α] {a b k : α} (h : k ∣ a - b) (L : list ℕ) : k ∣ of_digits a L - of_digits b L := begin induction L with d L ih, { change k ∣ 0 - 0, simp, }, { simp only [of_digits, add_sub_add_left_eq_sub], exact dvd_mul_sub_mul h ih, } end lemma of_digits_modeq' (b b' : ℕ) (k : ℕ) (h : b ≡ b' [MOD k]) (L : list ℕ) : of_digits b L ≡ of_digits b' L [MOD k] := begin induction L with d L ih, { refl, }, { dsimp [of_digits], dsimp [nat.modeq] at *, conv_lhs { rw [nat.add_mod, nat.mul_mod, h, ih], }, conv_rhs { rw [nat.add_mod, nat.mul_mod], }, } end lemma of_digits_modeq (b k : ℕ) (L : list ℕ) : of_digits b L ≡ of_digits (b % k) L [MOD k] := of_digits_modeq' b (b % k) k (b.mod_modeq k).symm L lemma of_digits_mod (b k : ℕ) (L : list ℕ) : of_digits b L % k = of_digits (b % k) L % k := of_digits_modeq b k L lemma of_digits_zmodeq' (b b' : ℤ) (k : ℕ) (h : b ≡ b' [ZMOD k]) (L : list ℕ) : of_digits b L ≡ of_digits b' L [ZMOD k] := begin induction L with d L ih, { refl, }, { dsimp [of_digits], dsimp [int.modeq] at *, conv_lhs { rw [int.add_mod, int.mul_mod, h, ih], }, conv_rhs { rw [int.add_mod, int.mul_mod], }, } end lemma of_digits_zmodeq (b : ℤ) (k : ℕ) (L : list ℕ) : of_digits b L ≡ of_digits (b % k) L [ZMOD k] := of_digits_zmodeq' b (b % k) k (b.mod_modeq ↑k).symm L lemma of_digits_zmod (b : ℤ) (k : ℕ) (L : list ℕ) : of_digits b L % k = of_digits (b % k) L % k := of_digits_zmodeq b k L lemma modeq_digits_sum (b b' : ℕ) (h : b' % b = 1) (n : ℕ) : n ≡ (digits b' n).sum [MOD b] := begin rw ←of_digits_one, conv { congr, skip, rw ←(of_digits_digits b' n) }, convert of_digits_modeq _ _ _, exact h.symm, end lemma modeq_three_digits_sum (n : ℕ) : n ≡ (digits 10 n).sum [MOD 3] := modeq_digits_sum 3 10 (by norm_num) n lemma modeq_nine_digits_sum (n : ℕ) : n ≡ (digits 10 n).sum [MOD 9] := modeq_digits_sum 9 10 (by norm_num) n lemma zmodeq_of_digits_digits (b b' : ℕ) (c : ℤ) (h : b' ≡ c [ZMOD b]) (n : ℕ) : n ≡ of_digits c (digits b' n) [ZMOD b] := begin conv { congr, skip, rw ←(of_digits_digits b' n) }, rw coe_int_of_digits, apply of_digits_zmodeq' _ _ _ h, end lemma of_digits_neg_one : Π (L : list ℕ), of_digits (-1 : ℤ) L = (L.map (λ n : ℕ, (n : ℤ))).alternating_sum | [] := rfl | [n] := by simp [of_digits, list.alternating_sum] | (a :: b :: t) := begin simp only [of_digits, list.alternating_sum, list.map_cons, of_digits_neg_one t], ring, end lemma modeq_eleven_digits_sum (n : ℕ) : n ≡ ((digits 10 n).map (λ n : ℕ, (n : ℤ))).alternating_sum [ZMOD 11] := begin have t := zmodeq_of_digits_digits 11 10 (-1 : ℤ) (by unfold int.modeq; norm_num) n, rwa of_digits_neg_one at t end /-! ## Divisibility -/ lemma dvd_iff_dvd_digits_sum (b b' : ℕ) (h : b' % b = 1) (n : ℕ) : b ∣ n ↔ b ∣ (digits b' n).sum := begin rw ←of_digits_one, conv_lhs { rw ←(of_digits_digits b' n) }, rw [nat.dvd_iff_mod_eq_zero, nat.dvd_iff_mod_eq_zero, of_digits_mod, h], end /-- **Divisibility by 3 Rule** -/ lemma three_dvd_iff (n : ℕ) : 3 ∣ n ↔ 3 ∣ (digits 10 n).sum := dvd_iff_dvd_digits_sum 3 10 (by norm_num) n lemma nine_dvd_iff (n : ℕ) : 9 ∣ n ↔ 9 ∣ (digits 10 n).sum := dvd_iff_dvd_digits_sum 9 10 (by norm_num) n lemma dvd_iff_dvd_of_digits (b b' : ℕ) (c : ℤ) (h : (b : ℤ) ∣ (b' : ℤ) - c) (n : ℕ) : b ∣ n ↔ (b : ℤ) ∣ of_digits c (digits b' n) := begin rw ←int.coe_nat_dvd, exact dvd_iff_dvd_of_dvd_sub (zmodeq_of_digits_digits b b' c (int.modeq_iff_dvd.2 h).symm _).symm.dvd, end lemma eleven_dvd_iff : 11 ∣ n ↔ (11 : ℤ) ∣ ((digits 10 n).map (λ n : ℕ, (n : ℤ))).alternating_sum := begin have t := dvd_iff_dvd_of_digits 11 10 (-1 : ℤ) (by norm_num) n, rw of_digits_neg_one at t, exact t, end lemma eleven_dvd_of_palindrome (p : (digits 10 n).palindrome) (h : even (digits 10 n).length) : 11 ∣ n := begin let dig := (digits 10 n).map (coe : ℕ → ℤ), replace h : even dig.length := by rwa list.length_map, refine eleven_dvd_iff.2 ⟨0, (_ : dig.alternating_sum = 0)⟩, have := dig.alternating_sum_reverse, rw [(p.map _).reverse_eq, pow_succ, h.neg_one_pow, mul_one, neg_one_zsmul] at this, exact eq_zero_of_neg_eq this.symm, end /-! ### `norm_digits` tactic -/ namespace norm_digits theorem digits_succ (b n m r l) (e : r + b * m = n) (hr : r < b) (h : nat.digits b m = l ∧ 1 < b ∧ 0 < m) : nat.digits b n = r :: l ∧ 1 < b ∧ 0 < n := begin rcases h with ⟨h, b2, m0⟩, have b0 : 0 < b := by linarith, have n0 : 0 < n := by linarith [mul_pos b0 m0], refine ⟨_, b2, n0⟩, obtain ⟨rfl, rfl⟩ := (nat.div_mod_unique b0).2 ⟨e, hr⟩, subst h, exact nat.digits_def' b2 n0, end theorem digits_one (b n) (n0 : 0 < n) (nb : n < b) : nat.digits b n = [n] ∧ 1 < b ∧ 0 < n := begin have b2 : 1 < b := by linarith, refine ⟨_, b2, n0⟩, rw [nat.digits_def' b2 n0, nat.mod_eq_of_lt nb, (nat.div_eq_zero_iff ((zero_le n).trans_lt nb)).2 nb, nat.digits_zero], end open tactic /-- Helper function for the `norm_digits` tactic. -/ meta def eval_aux (eb : expr) (b : ℕ) : expr → ℕ → instance_cache → tactic (instance_cache × expr × expr) | en n ic := do let m := n / b, let r := n % b, (ic, er) ← ic.of_nat r, (ic, pr) ← norm_num.prove_lt_nat ic er eb, if m = 0 then do (_, pn0) ← norm_num.prove_pos ic en, return (ic, `([%%en] : list nat), `(digits_one %%eb %%en %%pn0 %%pr)) else do em ← expr.of_nat `(ℕ) m, (_, pe) ← norm_num.derive `(%%er + %%eb * %%em : ℕ), (ic, el, p) ← eval_aux em m ic, return (ic, `(@list.cons ℕ %%er %%el), `(digits_succ %%eb %%en %%em %%er %%el %%pe %%pr %%p)) /-- A tactic for normalizing expressions of the form `nat.digits a b = l` where `a` and `b` are numerals. ``` example : nat.digits 10 123 = [3,2,1] := by norm_num ``` -/ @[norm_num] meta def eval : expr → tactic (expr × expr) | `(nat.digits %%eb %%en) := do b ← expr.to_nat eb, n ← expr.to_nat en, if n = 0 then return (`([] : list ℕ), `(nat.digits_zero %%eb)) else if b = 0 then do ic ← mk_instance_cache `(ℕ), (_, pn0) ← norm_num.prove_ne_zero' ic en, return (`([%%en] : list ℕ), `(@nat.digits_zero_succ' %%en %%pn0)) else if b = 1 then do ic ← mk_instance_cache `(ℕ), s ← simp_lemmas.add_simp simp_lemmas.mk `list.replicate, (rhs, p2, _) ← simplify s [] `(list.replicate %%en 1), p ← mk_eq_trans `(nat.digits_one %%en) p2, return (rhs, p) else do ic ← mk_instance_cache `(ℕ), (_, l, p) ← eval_aux eb b en n ic, p ← mk_app ``and.left [p], return (l, p) | _ := failed end norm_digits end nat
7677df26574ef1c2348ac45af0f143ce3e00af44
5ae26df177f810c5006841e9c73dc56e01b978d7
/src/topology/metric_space/isometry.lean
2629d2a6e487e60bfd894593171cd81cf59ab655
[ "Apache-2.0" ]
permissive
ChrisHughes24/mathlib
98322577c460bc6b1fe5c21f42ce33ad1c3e5558
a2a867e827c2a6702beb9efc2b9282bd801d5f9a
refs/heads/master
1,583,848,251,477
1,565,164,247,000
1,565,164,247,000
129,409,993
0
1
Apache-2.0
1,565,164,817,000
1,523,628,059,000
Lean
UTF-8
Lean
false
false
13,056
lean
/- Copyright (c) 2018 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Isometries of emetric and metric spaces Authors: Sébastien Gouëzel We define isometries, i.e., maps between emetric spaces that preserve the edistance (on metric spaces, these are exactly the maps that preserve distances), and prove their basic properties. We also introduce isometric bijections. -/ import topology.metric_space.basic topology.bounded_continuous_function analysis.normed_space.basic topology.opens noncomputable theory universes u v w variables {α : Type u} {β : Type v} {γ : Type w} open function set /-- An isometry (also known as isometric embedding) is a map preserving the edistance between emetric spaces, or equivalently the distance between metric space. -/ def isometry [emetric_space α] [emetric_space β] (f : α → β) : Prop := ∀x1 x2 : α, edist (f x1) (f x2) = edist x1 x2 /-- On metric spaces, a map is an isometry if and only if it preserves distances. -/ lemma isometry_emetric_iff_metric [metric_space α] [metric_space β] {f : α → β} : isometry f ↔ (∀x y, dist (f x) (f y) = dist x y) := ⟨assume H x y, by simp [dist_edist, H x y], assume H x y, by simp [edist_dist, H x y]⟩ /-- An isometry preserves edistances. -/ theorem isometry.edist_eq [emetric_space α] [emetric_space β] {f : α → β} {x y : α} (hf : isometry f) : edist (f x) (f y) = edist x y := hf x y /-- An isometry preserves distances. -/ theorem isometry.dist_eq [metric_space α] [metric_space β] {f : α → β} {x y : α} (hf : isometry f) : dist (f x) (f y) = dist x y := by rw [dist_edist, dist_edist, hf] section emetric_isometry variables [emetric_space α] [emetric_space β] [emetric_space γ] variables {f : α → β} {x y z : α} {s : set α} /-- An isometry is injective -/ lemma isometry.injective (h : isometry f) : injective f := λx y hxy, edist_eq_zero.1 $ calc edist x y = edist (f x) (f y) : (h x y).symm ... = 0 : by rw [hxy]; simp /-- Any map on a subsingleton is an isometry -/ theorem isometry_subsingleton [subsingleton α] : isometry f := λx y, by rw subsingleton.elim x y; simp /-- The identity is an isometry -/ lemma isometry_id : isometry (id : α → α) := λx y, rfl /-- The composition of isometries is an isometry -/ theorem isometry.comp {g : β → γ} {f : α → β} (hg : isometry g) (hf : isometry f) : isometry (g ∘ f) := assume x y, calc edist ((g ∘ f) x) ((g ∘ f) y) = edist (f x) (f y) : hg _ _ ... = edist x y : hf _ _ /-- An isometry is an embedding -/ theorem isometry.uniform_embedding (hf : isometry f) : uniform_embedding f := begin refine emetric.uniform_embedding_iff.2 ⟨_, _, _⟩, { assume x y hxy, have : edist (f x) (f y) = 0 := by simp [hxy], have : edist x y = 0 := begin have A := hf x y, rwa this at A, exact eq.symm A end, by simpa using this }, { rw emetric.uniform_continuous_iff, assume ε εpos, existsi [ε, εpos], simp [hf.edist_eq] }, { assume δ δpos, existsi [δ, δpos], simp [hf.edist_eq] } end /-- An isometry is continuous. -/ lemma isometry.continuous (hf : isometry f) : continuous f := hf.uniform_embedding.embedding.continuous /-- The inverse of an isometry is an isometry. -/ lemma isometry.inv (e : α ≃ β) (h : isometry e.to_fun) : isometry e.inv_fun := λx y, by rw [← h, e.right_inv _, e.right_inv _] /-- Isometries preserve the diameter -/ lemma emetric.isometry.diam_image (hf : isometry f) {s : set α}: emetric.diam (f '' s) = emetric.diam s := begin refine le_antisymm _ _, { apply lattice.Sup_le _, simp only [and_imp, set.mem_image, set.mem_prod, exists_imp_distrib, prod.exists], assume b x x' z zs xz z' z's x'z' hb, rw [← hb, ← xz, ← x'z', hf z z'], exact emetric.edist_le_diam_of_mem zs z's }, { apply lattice.Sup_le _, simp only [and_imp, set.mem_image, set.mem_prod, exists_imp_distrib, prod.exists], assume b x x' xs x's hb, rw [← hb, ← hf x x'], exact emetric.edist_le_diam_of_mem (mem_image_of_mem _ xs) (mem_image_of_mem _ x's) } end /-- The injection from a subtype is an isometry -/ lemma isometry_subtype_val {s : set α} : isometry (subtype.val : s → α) := λx y, rfl end emetric_isometry --section /-- An isometry preserves the diameter in metric spaces -/ lemma metric.isometry.diam_image [metric_space α] [metric_space β] {f : α → β} {s : set α} (hf : isometry f) : metric.diam (f '' s) = metric.diam s := by rw [metric.diam, metric.diam, emetric.isometry.diam_image hf] /-- α and β are isometric if there is an isometric bijection between them. -/ structure isometric (α : Type*) (β : Type*) [emetric_space α] [emetric_space β] extends α ≃ β := (isometry_to_fun : isometry to_fun) (isometry_inv_fun : isometry inv_fun) infix ` ≃ᵢ `:25 := isometric namespace isometric variables [emetric_space α] [emetric_space β] [emetric_space γ] instance : has_coe_to_fun (α ≃ᵢ β) := ⟨λ_, α → β, λe, e.to_equiv⟩ lemma coe_eq_to_equiv (h : α ≃ᵢ β) (a : α) : h a = h.to_equiv a := rfl protected def to_homeomorph (h : α ≃ᵢ β) : α ≃ₜ β := { continuous_to_fun := (isometry_to_fun h).continuous, continuous_inv_fun := (isometry_inv_fun h).continuous, .. h.to_equiv } lemma coe_eq_to_homeomorph (h : α ≃ᵢ β) (a : α) : h a = h.to_homeomorph a := rfl lemma to_homeomorph_to_equiv (h : α ≃ᵢ β) : h.to_homeomorph.to_equiv = h.to_equiv := by ext; refl protected def refl (α : Type*) [emetric_space α] : α ≃ᵢ α := { isometry_to_fun := isometry_id, isometry_inv_fun := isometry_id, .. equiv.refl α } protected def trans (h₁ : α ≃ᵢ β) (h₂ : β ≃ᵢ γ) : α ≃ᵢ γ := { isometry_to_fun := h₂.isometry_to_fun.comp h₁.isometry_to_fun, isometry_inv_fun := h₁.isometry_inv_fun.comp h₂.isometry_inv_fun, .. equiv.trans h₁.to_equiv h₂.to_equiv } protected def symm (h : α ≃ᵢ β) : β ≃ᵢ α := { isometry_to_fun := h.isometry_inv_fun, isometry_inv_fun := h.isometry_to_fun, .. h.to_equiv.symm } protected lemma isometry (h : α ≃ᵢ β) : isometry h := h.isometry_to_fun lemma symm_comp_self (h : α ≃ᵢ β) : ⇑h.symm ∘ ⇑h = id := funext $ assume a, h.to_equiv.left_inv a lemma self_comp_symm (h : α ≃ᵢ β) : ⇑h ∘ ⇑h.symm = id := funext $ assume a, h.to_equiv.right_inv a lemma range_coe (h : α ≃ᵢ β) : range h = univ := eq_univ_of_forall $ assume b, ⟨h.symm b, congr_fun h.self_comp_symm b⟩ lemma image_symm (h : α ≃ᵢ β) : image h.symm = preimage h := image_eq_preimage_of_inverse h.symm.to_equiv.left_inv h.symm.to_equiv.right_inv lemma preimage_symm (h : α ≃ᵢ β) : preimage h.symm = image h := (image_eq_preimage_of_inverse h.to_equiv.left_inv h.to_equiv.right_inv).symm end isometric /-- An isometry induces an isometric isomorphism between the source space and the range of the isometry. -/ lemma isometry.isometric_on_range [emetric_space α] [emetric_space β] {f : α → β} (h : isometry f) : α ≃ᵢ range f := { isometry_to_fun := λx y, begin change edist ((equiv.set.range f _) x) ((equiv.set.range f _) y) = edist x y, rw [equiv.set.range_apply f h.injective, equiv.set.range_apply f h.injective], exact h x y end, isometry_inv_fun := begin apply isometry.inv, assume x y, change edist ((equiv.set.range f _) x) ((equiv.set.range f _) y) = edist x y, rw [equiv.set.range_apply f h.injective, equiv.set.range_apply f h.injective], exact h x y end, .. equiv.set.range f h.injective } lemma isometry.isometric_on_range_apply [emetric_space α] [emetric_space β] {f : α → β} (h : isometry f) (x : α) : h.isometric_on_range x = ⟨f x, mem_range_self _⟩ := begin dunfold isometry.isometric_on_range, rw ← equiv.set.range_apply f h.injective x, refl end namespace Kuratowski_embedding /- In this section, we show that any separable metric space can be embedded isometrically in ℓ^∞(ℝ) -/ @[reducible] def ℓ_infty_ℝ : Type := bounded_continuous_function ℕ ℝ open bounded_continuous_function metric topological_space variables {f g : ℓ_infty_ℝ} {n : ℕ} {C : ℝ} [metric_space α] (x : ℕ → α) (a b : α) /-- A metric space can be embedded in `l^∞(ℝ)` via the distances to points in a fixed countable set, if this set is dense. This map is given in the next definition, without density assumptions. -/ def embedding_of_subset : ℓ_infty_ℝ := of_normed_group_discrete (λn, dist a (x n) - dist (x 0) (x n)) (dist a (x 0)) (λ_, abs_dist_sub_le _ _ _) lemma embedding_of_subset_coe : embedding_of_subset x a n = dist a (x n) - dist (x 0) (x n) := rfl /-- The embedding map is always a semi-contraction. -/ lemma embedding_of_subset_dist_le (a b : α) : dist (embedding_of_subset x a) (embedding_of_subset x b) ≤ dist a b := begin refine (dist_le dist_nonneg).2 (λn, _), have A : dist a (x n) + (dist (x 0) (x n) + (-dist b (x n) + -dist (x 0) (x n))) = dist a (x n) - dist b (x n), by ring, simp only [embedding_of_subset_coe, real.dist_eq, A, add_comm, neg_add_rev, _root_.neg_neg, sub_eq_add_neg, add_left_comm], exact abs_dist_sub_le _ _ _ end /-- When the reference set is dense, the embedding map is an isometry on its image. -/ lemma embedding_of_subset_isometry (H : closure (range x) = univ) : isometry (embedding_of_subset x) := begin refine isometry_emetric_iff_metric.2 (λa b, _), refine le_antisymm (embedding_of_subset_dist_le x a b) (real.le_of_forall_epsilon_le (λe epos, _)), /- First step: find n with dist a (x n) < e -/ have A : a ∈ closure (range x), by { have B := mem_univ a, rwa [← H] at B }, rcases mem_closure_iff'.1 A (e/2) (half_pos epos) with ⟨d, ⟨drange, hd⟩⟩, cases drange with n dn, rw [← dn] at hd, /- Second step: use the norm control at index n to conclude -/ have C : dist b (x n) - dist a (x n) = embedding_of_subset x b n - embedding_of_subset x a n := by { simp [embedding_of_subset_coe] }, have := calc dist a b ≤ dist a (x n) + dist (x n) b : dist_triangle _ _ _ ... = 2 * dist a (x n) + (dist b (x n) - dist a (x n)) : by { simp [dist_comm], ring } ... ≤ 2 * dist a (x n) + abs (dist b (x n) - dist a (x n)) : by apply_rules [add_le_add_left, le_abs_self] ... ≤ 2 * (e/2) + abs (embedding_of_subset x b n - embedding_of_subset x a n) : begin rw [C], apply_rules [add_le_add, mul_le_mul_of_nonneg_left, le_of_lt hd, le_refl], norm_num end ... ≤ 2 * (e/2) + dist (embedding_of_subset x b) (embedding_of_subset x a) : begin rw [← coe_diff], apply add_le_add_left, rw [coe_diff, ←real.dist_eq], apply dist_coe_le_dist end ... = dist (embedding_of_subset x b) (embedding_of_subset x a) + e : by ring, simpa [dist_comm] using this end /-- Every separable metric space embeds isometrically in ℓ_infty_ℝ. -/ theorem exists_isometric_embedding (α : Type u) [metric_space α] [separable_space α] : ∃(f : α → ℓ_infty_ℝ), isometry f := begin classical, by_cases h : (univ : set α) = ∅, { use (λ_, 0), assume x, exact (ne_empty_of_mem (mem_univ x) h).elim }, { /- We construct a map x : ℕ → α with dense image -/ rcases exists_mem_of_ne_empty h with basepoint, haveI : inhabited α := ⟨basepoint⟩, have : ∃s:set α, countable s ∧ closure s = univ := separable_space.exists_countable_closure_eq_univ _, rcases this with ⟨S, ⟨S_countable, S_dense⟩⟩, rcases countable_iff_exists_surjective.1 S_countable with ⟨x, x_range⟩, have : closure (range x) = univ := univ_subset_iff.1 (by { rw [← S_dense], apply closure_mono, assumption }), /- Use embedding_of_subset to construct the desired isometry -/ exact ⟨embedding_of_subset x, embedding_of_subset_isometry x this⟩ } end /-- The Kuratowski embedding is an isometric embedding of a separable metric space in ℓ^∞(ℝ) -/ def Kuratowski_embedding (α : Type u) [metric_space α] [separable_space α] : α → ℓ_infty_ℝ := classical.some (exists_isometric_embedding α) /-- The Kuratowski embedding is an isometry -/ lemma Kuratowski_embedding_isometry (α : Type u) [metric_space α] [separable_space α] : isometry (Kuratowski_embedding α) := classical.some_spec (exists_isometric_embedding α) /-- Version of the Kuratowski embedding for nonempty compacts -/ def nonempty_compacts.Kuratowski_embedding (α : Type u) [metric_space α] [compact_space α] [nonempty α] : nonempty_compacts ℓ_infty_ℝ := ⟨range (Kuratowski_embedding α), begin split, { rcases exists_mem_of_nonempty α with ⟨x, hx⟩, have A : Kuratowski_embedding α x ∈ range (Kuratowski_embedding α) := ⟨x, by simp⟩, apply ne_empty_of_mem A }, { rw ← image_univ, exact compact_image compact_univ (Kuratowski_embedding_isometry α).continuous }, end⟩ end Kuratowski_embedding --namespace