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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
c3a9efba0d3e297dd0ced0432dadfde97d328192 | 367134ba5a65885e863bdc4507601606690974c1 | /src/category_theory/action.lean | 2bf3bb2616f49a9903fa88e9301766ef067e5b74 | [
"Apache-2.0"
] | permissive | kodyvajjha/mathlib | 9bead00e90f68269a313f45f5561766cfd8d5cad | b98af5dd79e13a38d84438b850a2e8858ec21284 | refs/heads/master | 1,624,350,366,310 | 1,615,563,062,000 | 1,615,563,062,000 | 162,666,963 | 0 | 0 | Apache-2.0 | 1,545,367,651,000 | 1,545,367,651,000 | null | UTF-8 | Lean | false | false | 3,181 | lean | /-
Copyright (c) 2020 David Wärn. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: David Wärn
-/
import category_theory.elements
import category_theory.single_obj
import group_theory.group_action.basic
/-!
# Actions as functors and as categories
From a multiplicative action M ↻ X, we can construct a functor from M to the category of
types, mapping the single object of M to X and an element `m : M` to map `X → X` given by
multiplication by `m`.
This functor induces a category structure on X -- a special case of the category of elements.
A morphism `x ⟶ y` in this category is simply a scalar `m : M` such that `m • x = y`. In the case
where M is a group, this category is a groupoid -- the `action groupoid'.
-/
open mul_action
namespace category_theory
universes u
variables (M : Type*) [monoid M] (X : Type u) [mul_action M X]
/-- A multiplicative action M ↻ X viewed as a functor mapping the single object of M to X
and an element `m : M` to the map `X → X` given by multiplication by `m`. -/
@[simps]
def action_as_functor : single_obj M ⥤ Type u :=
{ obj := λ _, X,
map := λ _ _, (•),
map_id' := λ _, funext $ mul_action.one_smul,
map_comp' := λ _ _ _ f g, funext $ λ x, (smul_smul g f x).symm }
/-- A multiplicative action M ↻ X induces a category strucure on X, where a morphism
from x to y is a scalar taking x to y. Due to implementation details, the object type
of this category is not equal to X, but is in bijection with X. -/
@[derive category]
def action_category := (action_as_functor M X).elements
namespace action_category
instance (G : Type*) [group G] [mul_action G X] : groupoid (action_category G X) :=
category_theory.groupoid_of_elements _
/-- The projection from the action category to the monoid, mapping a morphism to its
label. -/
def π : action_category M X ⥤ single_obj M :=
category_of_elements.π _
@[simp]
lemma π_map (p q : action_category M X) (f : p ⟶ q) : (π M X).map f = f.val := rfl
@[simp]
lemma π_obj (p : action_category M X) : (π M X).obj p = single_obj.star M :=
@subsingleton.elim unit _ _ _
/-- An object of the action category given by M ↻ X corresponds to an element of X. -/
def obj_equiv : X ≃ action_category M X :=
{ to_fun := λ x, ⟨single_obj.star M, x⟩,
inv_fun := λ p, p.2,
left_inv := by tidy,
right_inv := by tidy }
lemma hom_as_subtype (p q : action_category M X) :
(p ⟶ q) = { m : M // m • (obj_equiv M X).symm p = (obj_equiv M X).symm q } := rfl
instance [inhabited X] : inhabited (action_category M X) :=
{ default := obj_equiv M X (default X) }
variables {X} (x : X)
/-- The stabilizer of a point is isomorphic to the endomorphism monoid at the
corresponding point. In fact they are definitionally equivalent. -/
def stabilizer_iso_End : stabilizer.submonoid M x ≃* End (obj_equiv M X x) :=
mul_equiv.refl _
@[simp]
lemma stabilizer_iso_End_apply (f : stabilizer.submonoid M x) :
(stabilizer_iso_End M x).to_fun f = f := rfl
@[simp]
lemma stabilizer_iso_End_symm_apply (f : End _) :
(stabilizer_iso_End M x).inv_fun f = f := rfl
end action_category
end category_theory
|
7633928e9c5f7835d34bbe9576d6e2edb763322c | 0403d75087eccd9fdec22713ec7cff4d40c93610 | /lean/love04_functional_programming_demo.lean | 359eecf64fe8ea21353d978cad4bf03c1481e5da | [] | no_license | 5l1v3r1/logical_verification_2020 | 9660ae5a83915be2103183490cae279b888be83c | 000aa1fe212813b8458bf26c16b8a97597b7417e | refs/heads/master | 1,621,861,800,557 | 1,586,181,042,000 | 1,586,181,042,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 12,943 | lean | import .lovelib
/-! # LoVe Demo 4: Functional Programming
We take a closer look at the basics of typed functional programming: inductive
types, pattern matching, recursive functions, and proofs by induction. -/
set_option pp.beta true
namespace LoVe
/-! ## Inductive Types
Recall the definition of type `nat` (= `ℕ`): -/
#print nat
/-! Mottos:
* **No junk**: The type contains no values beyond those expressible using the
constructors.
* **No confusion**: Values built in a different ways are different.
For `nat` (= `ℕ`):
* "No junk" means that there are no special values, say, `–1` or `ε`, that
cannot be expressed using a finite combination of `zero` and `succ`.
* "No confusion" is what ensures that `zero` ≠ `succ x`.
In addition, inductive types are always finite. `succ (succ (succ …))` is not a
value.
## Structural Induction
__Structural induction__ is a generalization of mathematical induction to
inductive types. To prove a property `P[n]` for all natural numbers `n`, it
suffices to prove the base case
`P[0]`
and the induction step
`∀k, P[k] → P[k + 1]`
For lists, the base case is
`P[[]]`
and the induction step is
`∀y ys, P[ys] → P[y :: ys]`
In general, there is one subgoal per constructor, and induction hypotheses are
available for all constructor arguments of the type we are doing the induction
on. -/
lemma nat.succ_neq_self (n : ℕ) :
nat.succ n ≠ n :=
begin
induction n,
{ simp },
{ simp [n_ih] }
end
/-! The `case` tactic can be used to supply custom names, and potentially
reorder the cases. -/
lemma nat.succ_neq_self₂ (n : ℕ) :
nat.succ n ≠ n :=
begin
induction n,
case nat.succ : m ih {
simp [ih] },
case nat.zero {
simp }
end
/-! ## Structural Recursion
__Structural recursion__ is a form of recursion that allows us to peel off
one or more constructors from the value on which we recurse. Such functions are
guaranteed to call themselves only finitely many times before the recursion
stops. This is a prerequisite for establishing that the function terminates. -/
def fact : ℕ → ℕ
| 0 := 1
| (n + 1) := (n + 1) * fact n
def fact₂ : ℕ → ℕ
| 0 := 1
| 1 := 1
| (n + 1) := (n + 1) * fact₂ n
/-! For structurally recursive functions, Lean can automatically prove
termination. For more general recursive schemes, the termination check may fail.
Sometimes it does so for a good reason, as in the following example: -/
-- fails
def illegal : ℕ → ℕ
| n := illegal n + 1
constant immoral : ℕ → ℕ
axiom immoral_eq (n : ℕ) :
immoral n = immoral n + 1
lemma proof_of_false :
false :=
have immoral 0 = immoral 0 + 1 :=
immoral_eq 0,
have immoral 0 - immoral 0 = immoral 0 + 1 - immoral 0 :=
by cc,
have 0 = 1 :=
by simp [*] at *,
show false, from
by cc
/-! **Warning:** The above definitions of factorial are wrong.
## Pattern Matching Expressions
`match` _term₁_, …, _termM_ `with`
| _pattern₁₁_, …, _pattern₁M_ := _result₁_
⋮
| _patternN₁_, …, _patternNM_ := _resultN_
`end`
`match` allows nonrecursive pattern matching within terms.
In contrast to pattern matching after `lemma` or `def`, the patterns are
separated by commas, so parentheses are optional. -/
def bcount {α : Type} (p : α → bool) : list α → ℕ
| [] := 0
| (x :: xs) :=
match p x with
| tt := bcount xs + 1
| ff := bcount xs
end
def min (a b : ℕ) : ℕ :=
if a ≤ b then a else b
/-! ## Structures
Lean provides a convenient syntax for defining records, or structures. These are
essentially nonrecursive, single-constructor inductive types. -/
structure rgb : Type :=
(red green blue : ℕ)
#check rgb.mk
#check rgb.red
#check rgb.green
#check rgb.blue
namespace rgb_as_inductive
inductive rgb : Type
| mk : ℕ → ℕ → ℕ → rgb
def rgb.red : rgb → ℕ
| (rgb.mk r _ _) := r
def rgb.green : rgb → ℕ
| (rgb.mk _ g _) := g
def rgb.blue : rgb → ℕ
| (rgb.mk _ _ b) := b
end rgb_as_inductive
structure rgba extends rgb : Type :=
(alpha : ℕ)
#print rgba
def pure_red : rgb :=
{ red := 0xff,
green := 0x00,
blue := 0x00 }
def semitransparent_red : rgba :=
{ alpha := 0x7f,
..pure_red }
#print pure_red
#print semitransparent_red
def shuffle (c : rgb) : rgb :=
{ red := rgb.green c,
green := rgb.blue c,
blue := rgb.red c }
/-! `cases` performs a case distinction on the specified term. This gives rise
to as many subgoals as there are constructors in the definition of the term's
type. The tactic behaves almost the same as `induction` except that it does not
produce induction hypotheses. -/
lemma shuffle_shuffle_shuffle (c : rgb) :
shuffle (shuffle (shuffle c)) = c :=
begin
cases c,
refl
end
lemma shuffle_shuffle_shuffle₂ (c : rgb) :
shuffle (shuffle (shuffle c)) = c :=
match c with
| rgb.mk r g b := eq.refl _
end
/-! ## Type Classes
A __type class__ is a structure type combining abstract constants and their
properties. A type can be declared an instance of a type class by providing
concrete definitions for the constants and proving that the properties hold.
Based on the type, Lean retrieves the relevant instance. -/
#print inhabited
@[instance] def nat.inhabited : inhabited ℕ :=
{ default := 0 }
@[instance] def list.inhabited {α : Type} :
inhabited (list α) :=
{ default := [] }
#eval inhabited.default ℕ -- result: 0
#eval inhabited.default (list ℤ) -- result: []
def head {α : Type} [inhabited α] : list α → α
| [] := inhabited.default α
| (x :: _) := x
lemma head_head {α : Type} [inhabited α] (xs : list α) :
head [head xs] = head xs :=
begin
cases xs,
{ refl },
{ refl }
end
#eval head ([] : list ℕ) -- result: 0
#check list.head
@[instance] def fun.inhabited {α β : Type} [inhabited β] :
inhabited (α → β) :=
{ default := λa : α, inhabited.default β }
inductive empty : Type
@[instance] def fun_empty.inhabited {β : Type} :
inhabited (empty → β) :=
{ default := λa : empty, match a with end }
@[instance] def prod.inhabited {α β : Type}
[inhabited α] [inhabited β] :
inhabited (α × β) :=
{ default := (inhabited.default α, inhabited.default β) }
/-! Here are other type classes without properties: -/
#check has_zero
#check has_neg
#check has_add
#check has_one
#check has_inv
#check has_mul
#check (1 : ℕ)
#check (1 : ℤ)
#check (1 : ℝ)
#check (1 : linear_map _ _ _)
/-! We encountered these type classes in lecture 2: -/
#print is_commutative
#print is_associative
/-! ## Lists
`list` is an inductive polymorphic type constructed from `nil` and `cons`: -/
#print list
/-! `cases` can also be used on a hypothesis of the form `l = r`. It matches `r`
against `l` and replaces all occurrences of the variables occurring in `r` with
the corresponding terms in `l` everywhere in the goal. The remaining hypothesis
`l = l` can be removed using `clear h` if desired. -/
lemma injection_example {α : Type} (x y : α) (xs ys : list α)
(h : list.cons x xs = list.cons y ys) :
x = y ∧ xs = ys :=
begin
cases h,
clear h,
cc
end
/-! If `r` fails to match `l`, no subgoals emerge; the proof is complete. -/
lemma distinctness_example {α : Type} (x y : α)
(xs ys : list α) (h : [] = y :: ys) :
false :=
by cases h
def map {α β : Type} (f : α → β) : list α → list β
| [] := []
| (x :: xs) := f x :: map xs
def map₂ {α β : Type} : (α → β) → list α → list β
| _ [] := []
| f (x :: xs) := f x :: map₂ f xs
#check list.map
lemma map_ident {α : Type} (xs : list α) :
map (λx, x) xs = xs :=
begin
induction xs,
case list.nil {
refl },
case list.cons : y ys ih {
simp [map, ih] }
end
lemma map_comp {α β γ : Type} (f : α → β) (g : β → γ)
(xs : list α) :
map g (map f xs) = map (λx, g (f x)) xs :=
begin
induction xs,
case list.nil {
refl },
case list.cons : y ys ih {
simp [map, ih] }
end
lemma map_append {α β : Type} (f : α → β) (xs ys : list α) :
map f (xs ++ ys) = map f xs ++ map f ys :=
begin
induction xs,
case list.nil {
refl },
case list.cons : y ys ih {
simp [map, ih] }
end
def tail {α : Type} : list α → list α
| [] := []
| (_ :: xs) := xs
#check list.tail
def head_opt {α : Type} : list α → option α
| [] := option.none
| (x :: _) := option.some x
def head_le {α : Type} : ∀xs : list α, xs ≠ [] → α
| [] hxs := by cc
| (x :: _) _ := x
#eval head_opt [3, 1, 4]
#eval head_le [3, 1, 4] (by simp)
#eval head_le ([] : list ℕ) sorry -- fails
def zip {α β : Type} : list α → list β → list (α × β)
| (x :: xs) (y :: ys) := (x, y) :: zip xs ys
| [] _ := []
| (_ :: _) [] := []
#check list.zip
def length {α : Type} : list α → ℕ
| [] := 0
| (x :: xs) := length xs + 1
#check list.length
/-! `cases` can also be used to perform a case distinction on a proposition, in
conjunction with `classical.em`. Two cases emerge: one in which the proposition
is true and one in which it is false.
Also notice the `have` tactic below. We will come back to it. -/
#check classical.em
lemma min_add_add (l m n : ℕ) :
min (m + l) (n + l) = min m n + l :=
begin
cases classical.em (m ≤ n),
case or.inl : h {
simp [min, h] },
case or.inr : h {
simp [min, h] }
end
lemma min_add_add₂ (l m n : ℕ) :
min (m + l) (n + l) = min m n + l :=
match classical.em (m ≤ n) with
| or.inl h := by simp [min, h]
| or.inr h := by simp [min, h]
end
lemma min_add_add₃ (l m n : ℕ) :
min (m + l) (n + l) = min m n + l :=
if h : m ≤ n then
by simp [min, h]
else
by simp [min, h]
lemma length_zip {α β : Type} (xs : list α) (ys : list β) :
length (zip xs ys) = min (length xs) (length ys) :=
begin
induction xs generalizing ys,
case list.nil {
refl },
case list.cons : x xs ih {
cases ys,
case list.nil {
refl },
case list.cons : y ys {
simp [zip, length, ih, min_add_add] } }
end
lemma map_zip {α α' β β' : Type} (f : α → α') (g : β → β') :
∀xs ys,
map (λab : α × β, (f (prod.fst ab), g (prod.snd ab)))
(zip xs ys) =
zip (map f xs) (map g ys)
| (x :: xs) (y :: ys) := by simp [zip, map, map_zip xs ys]
| [] _ := by refl
| (_ :: _) [] := by refl
/-! ## Binary Trees
Inductive types with constructors taking several recursive arguments define
tree-like objects. __Binary trees__ have nodes with at most two children. -/
inductive btree (α : Type) : Type
| empty {} : btree
| node : α → btree → btree → btree
/-! The type `aexp` of arithmetic expressions was also an example of a tree data
structure.
The nodes of a tree, whether inner nodes or leaf nodes, often carry labels or
other annotations.
Inductive trees contain no infinite branches, not even cycles. This is less
expressive than pointer- or reference-based data structures (in imperative
languages) but easier to reason about.
Recursive definitions (and proofs by induction) work roughly as for lists, but
we may need to recurse (or invoke the induction hypothesis) on several child
nodes. -/
def mirror {α : Type} : btree α → btree α
| btree.empty := btree.empty
| (btree.node a l r) := btree.node a (mirror r) (mirror l)
lemma mirror_mirror {α : Type} (t : btree α) :
mirror (mirror t) = t :=
begin
induction t,
case btree.empty {
refl },
case btree.node : a l r ih_l ih_r {
simp [mirror, ih_l, ih_r] }
end
lemma mirror_eq_empty_iff {α : Type} :
∀t : btree α, mirror t = btree.empty ↔ t = btree.empty
| btree.empty := by refl
| (btree.node _ _ _) := by simp [mirror]
lemma mirror_mirror₂ {α : Type} :
∀t : btree α, mirror (mirror t) = t
| btree.empty := by refl
| (btree.node a l r) :=
calc mirror (mirror (btree.node a l r))
= mirror (btree.node a (mirror r) (mirror l)) :
by refl
... = btree.node a (mirror (mirror l)) (mirror (mirror r)) :
by refl
... = btree.node a l (mirror (mirror r)) :
by rewrite mirror_mirror₂ l
... = btree.node a l r :
by rewrite mirror_mirror₂ r
/-! ## Dependent Inductive Types (**optional**) -/
#check vector
inductive vec (α : Type) : ℕ → Type
| nil {} : vec 0
| cons (a : α) {n : ℕ} (v : vec n) : vec (n + 1)
#check vec.nil
#check vec.cons
def list_of_vec {α : Type} : ∀{n : ℕ}, vec α n → list α
| _ vec.nil := []
| _ (vec.cons a v) := a :: list_of_vec v
def vec_of_list {α : Type} :
∀xs : list α, vec α (list.length xs)
| [] := vec.nil
| (x :: xs) := vec.cons x (vec_of_list xs)
lemma length_list_of_vec {α : Type} :
∀{n : ℕ} (v : vec α n), list.length (list_of_vec v) = n
| _ vec.nil := by refl
| _ (vec.cons a v) :=
by simp [list_of_vec, length_list_of_vec v]
end LoVe
|
fdbe3fff06f1a0bb42c3e2e338f1591075633790 | 82e44445c70db0f03e30d7be725775f122d72f3e | /src/algebra/lie/submodule.lean | a9b339dbdcf541edac683e469bade888b36e9d02 | [
"Apache-2.0"
] | permissive | stjordanis/mathlib | 51e286d19140e3788ef2c470bc7b953e4991f0c9 | 2568d41bca08f5d6bf39d915434c8447e21f42ee | refs/heads/master | 1,631,748,053,501 | 1,627,938,886,000 | 1,627,938,886,000 | 228,728,358 | 0 | 0 | Apache-2.0 | 1,576,630,588,000 | 1,576,630,587,000 | null | UTF-8 | Lean | false | false | 33,233 | lean | /-
Copyright (c) 2021 Oliver Nash. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Oliver Nash
-/
import algebra.lie.subalgebra
import ring_theory.noetherian
/-!
# Lie submodules of a Lie algebra
In this file we define Lie submodules and Lie ideals, we construct the lattice structure on Lie
submodules and we use it to define various important operations, notably the Lie span of a subset
of a Lie module.
## Main definitions
* `lie_submodule`
* `lie_submodule.well_founded_of_noetherian`
* `lie_submodule.lie_span`
* `lie_submodule.map`
* `lie_submodule.comap`
* `lie_ideal`
* `lie_ideal.map`
* `lie_ideal.comap`
## Tags
lie algebra, lie submodule, lie ideal, lattice structure
-/
universes u v w w₁ w₂
section lie_submodule
variables (R : Type u) (L : Type v) (M : Type w)
variables [comm_ring R] [lie_ring L] [lie_algebra R L] [add_comm_group M] [module R M]
variables [lie_ring_module L M] [lie_module R L M]
set_option old_structure_cmd true
/-- A Lie submodule of a Lie module is a submodule that is closed under the Lie bracket.
This is a sufficient condition for the subset itself to form a Lie module. -/
structure lie_submodule extends submodule R M :=
(lie_mem : ∀ {x : L} {m : M}, m ∈ carrier → ⁅x, m⁆ ∈ carrier)
attribute [nolint doc_blame] lie_submodule.to_submodule
namespace lie_submodule
variables {R L M} (N N' : lie_submodule R L M)
/-- The zero module is a Lie submodule of any Lie module. -/
instance : has_zero (lie_submodule R L M) :=
⟨{ lie_mem := λ x m h, by { rw ((submodule.mem_bot R).1 h), apply lie_zero, },
..(0 : submodule R M)}⟩
instance : inhabited (lie_submodule R L M) := ⟨0⟩
instance coe_submodule : has_coe (lie_submodule R L M) (submodule R M) := ⟨to_submodule⟩
@[norm_cast]
lemma coe_to_submodule : ((N : submodule R M) : set M) = N := rfl
instance has_mem : has_mem M (lie_submodule R L M) := ⟨λ x N, x ∈ (N : set M)⟩
@[simp] lemma mem_carrier {x : M} : x ∈ N.carrier ↔ x ∈ (N : set M) :=
iff.rfl
@[simp] lemma mem_mk_iff (S : set M) (h₁ h₂ h₃ h₄) {x : M} :
x ∈ (⟨S, h₁, h₂, h₃, h₄⟩ : lie_submodule R L M) ↔ x ∈ S :=
iff.rfl
@[simp] lemma mem_coe_submodule {x : M} : x ∈ (N : submodule R M) ↔ x ∈ N := iff.rfl
lemma mem_coe {x : M} : x ∈ (N : set M) ↔ x ∈ N := iff.rfl
@[simp] lemma zero_mem : (0 : M) ∈ N := (N : submodule R M).zero_mem
@[simp] lemma coe_to_set_mk (S : set M) (h₁ h₂ h₃ h₄) :
((⟨S, h₁, h₂, h₃, h₄⟩ : lie_submodule R L M) : set M) = S := rfl
@[simp] lemma coe_to_submodule_mk (p : submodule R M) (h) :
(({lie_mem := h, ..p} : lie_submodule R L M) : submodule R M) = p :=
by { cases p, refl, }
@[ext] lemma ext (h : ∀ m, m ∈ N ↔ m ∈ N') : N = N' :=
by { cases N, cases N', simp only [], ext m, exact h m, }
@[simp] lemma coe_to_submodule_eq_iff : (N : submodule R M) = (N' : submodule R M) ↔ N = N' :=
begin
split; intros h,
{ ext, rw [← mem_coe_submodule, h], simp, },
{ rw h, },
end
/-- Copy of a lie_submodule with a new `carrier` equal to the old one. Useful to fix definitional
equalities. -/
protected def copy (s : set M) (hs : s = ↑N) : lie_submodule R L M :=
{ carrier := s,
zero_mem' := hs.symm ▸ N.zero_mem',
add_mem' := hs.symm ▸ N.add_mem',
smul_mem' := hs.symm ▸ N.smul_mem',
lie_mem := hs.symm ▸ N.lie_mem, }
instance : lie_ring_module L N :=
{ bracket := λ (x : L) (m : N), ⟨⁅x, m.val⁆, N.lie_mem m.property⟩,
add_lie := by { intros x y m, apply set_coe.ext, apply add_lie, },
lie_add := by { intros x m n, apply set_coe.ext, apply lie_add, },
leibniz_lie := by { intros x y m, apply set_coe.ext, apply leibniz_lie, }, }
instance : lie_module R L N :=
{ lie_smul := by { intros t x y, apply set_coe.ext, apply lie_smul, },
smul_lie := by { intros t x y, apply set_coe.ext, apply smul_lie, }, }
@[simp, norm_cast] lemma coe_zero : ((0 : N) : M) = (0 : M) := rfl
@[simp, norm_cast] lemma coe_add (m m' : N) : (↑(m + m') : M) = (m : M) + (m' : M) := rfl
@[simp, norm_cast] lemma coe_neg (m : N) : (↑(-m) : M) = -(m : M) := rfl
@[simp, norm_cast] lemma coe_sub (m m' : N) : (↑(m - m') : M) = (m : M) - (m' : M) := rfl
@[simp, norm_cast] lemma coe_smul (t : R) (m : N) : (↑(t • m) : M) = t • (m : M) := rfl
@[simp, norm_cast] lemma coe_bracket (x : L) (m : N) : (↑⁅x, m⁆ : M) = ⁅x, ↑m⁆ := rfl
end lie_submodule
section lie_ideal
variables (L)
/-- An ideal of a Lie algebra is a Lie submodule of the Lie algebra as a Lie module over itself. -/
abbreviation lie_ideal := lie_submodule R L L
lemma lie_mem_right (I : lie_ideal R L) (x y : L) (h : y ∈ I) : ⁅x, y⁆ ∈ I := I.lie_mem h
lemma lie_mem_left (I : lie_ideal R L) (x y : L) (h : x ∈ I) : ⁅x, y⁆ ∈ I :=
by { rw [←lie_skew, ←neg_lie], apply lie_mem_right, assumption, }
/-- An ideal of a Lie algebra is a Lie subalgebra. -/
def lie_ideal_subalgebra (I : lie_ideal R L) : lie_subalgebra R L :=
{ lie_mem' := by { intros x y hx hy, apply lie_mem_right, exact hy, },
..I.to_submodule, }
instance : has_coe (lie_ideal R L) (lie_subalgebra R L) := ⟨λ I, lie_ideal_subalgebra R L I⟩
@[norm_cast] lemma lie_ideal.coe_to_subalgebra (I : lie_ideal R L) :
((I : lie_subalgebra R L) : set L) = I := rfl
@[norm_cast] lemma lie_ideal.coe_to_lie_subalgebra_to_submodule (I : lie_ideal R L) :
((I : lie_subalgebra R L) : submodule R L) = I := rfl
end lie_ideal
variables {R M}
lemma submodule.exists_lie_submodule_coe_eq_iff (p : submodule R M) :
(∃ (N : lie_submodule R L M), ↑N = p) ↔ ∀ (x : L) (m : M), m ∈ p → ⁅x, m⁆ ∈ p :=
begin
split,
{ rintros ⟨N, rfl⟩, exact N.lie_mem, },
{ intros h, use { lie_mem := h, ..p }, exact lie_submodule.coe_to_submodule_mk p _, },
end
namespace lie_subalgebra
variables {L}
/-- Given a Lie subalgebra `K ⊆ L`, if we view `L` as a `K`-module by restriction, it contains
a distinguished Lie submodule for the action of `K`, namely `K` itself. -/
def to_lie_submodule (K : lie_subalgebra R L) : lie_submodule R K L :=
{ lie_mem := λ x y hy, K.lie_mem x.property hy,
.. (K : submodule R L) }
@[simp] lemma coe_to_lie_submodule (K : lie_subalgebra R L) :
(K.to_lie_submodule : submodule R L) = K :=
rfl
@[simp] lemma mem_to_lie_submodule {K : lie_subalgebra R L} (x : L) :
x ∈ K.to_lie_submodule ↔ x ∈ K :=
iff.rfl
lemma exists_lie_ideal_coe_eq_iff (K : lie_subalgebra R L) :
(∃ (I : lie_ideal R L), ↑I = K) ↔ ∀ (x y : L), y ∈ K → ⁅x, y⁆ ∈ K :=
begin
simp only [← coe_to_submodule_eq_iff, lie_ideal.coe_to_lie_subalgebra_to_submodule,
submodule.exists_lie_submodule_coe_eq_iff L],
exact iff.rfl,
end
lemma exists_nested_lie_ideal_coe_eq_iff {K K' : lie_subalgebra R L} (h : K ≤ K') :
(∃ (I : lie_ideal R K'), ↑I = of_le h) ↔ ∀ (x y : L), x ∈ K' → y ∈ K → ⁅x, y⁆ ∈ K :=
begin
simp only [exists_lie_ideal_coe_eq_iff, coe_bracket, mem_of_le],
split,
{ intros h' x y hx hy, exact h' ⟨x, hx⟩ ⟨y, h hy⟩ hy, },
{ rintros h' ⟨x, hx⟩ ⟨y, hy⟩ hy', exact h' x y hx hy', },
end
end lie_subalgebra
end lie_submodule
namespace lie_submodule
variables {R : Type u} {L : Type v} {M : Type w}
variables [comm_ring R] [lie_ring L] [lie_algebra R L] [add_comm_group M] [module R M]
variables [lie_ring_module L M] [lie_module R L M]
variables (N N' : lie_submodule R L M) (I J : lie_ideal R L)
section lattice_structure
open set
lemma coe_injective : function.injective (coe : lie_submodule R L M → set M) :=
λ N N' h, by { cases N, cases N', simp only, exact h, }
lemma coe_submodule_injective : function.injective (coe : lie_submodule R L M → submodule R M) :=
λ N N' h, by { ext, rw [← mem_coe_submodule, h], refl, }
instance : partial_order (lie_submodule R L M) :=
{ le := λ N N', ∀ ⦃x⦄, x ∈ N → x ∈ N', -- Overriding `le` like this gives a better defeq.
..partial_order.lift (coe : lie_submodule R L M → set M) coe_injective }
lemma le_def : N ≤ N' ↔ (N : set M) ⊆ N' := iff.rfl
@[simp, norm_cast] lemma coe_submodule_le_coe_submodule : (N : submodule R M) ≤ N' ↔ N ≤ N' :=
iff.rfl
instance : has_bot (lie_submodule R L M) := ⟨0⟩
@[simp] lemma bot_coe : ((⊥ : lie_submodule R L M) : set M) = {0} := rfl
@[simp] lemma bot_coe_submodule : ((⊥ : lie_submodule R L M) : submodule R M) = ⊥ := rfl
@[simp] lemma mem_bot (x : M) : x ∈ (⊥ : lie_submodule R L M) ↔ x = 0 := mem_singleton_iff
instance : has_top (lie_submodule R L M) :=
⟨{ lie_mem := λ x m h, mem_univ ⁅x, m⁆,
..(⊤ : submodule R M) }⟩
@[simp] lemma top_coe : ((⊤ : lie_submodule R L M) : set M) = univ := rfl
@[simp] lemma top_coe_submodule : ((⊤ : lie_submodule R L M) : submodule R M) = ⊤ := rfl
@[simp] lemma mem_top (x : M) : x ∈ (⊤ : lie_submodule R L M) := mem_univ x
instance : has_inf (lie_submodule R L M) :=
⟨λ N N', { lie_mem := λ x m h, mem_inter (N.lie_mem h.1) (N'.lie_mem h.2),
..(N ⊓ N' : submodule R M) }⟩
instance : has_Inf (lie_submodule R L M) :=
⟨λ S, { lie_mem := λ x m h, by
{ simp only [submodule.mem_carrier, mem_Inter, submodule.Inf_coe, mem_set_of_eq,
forall_apply_eq_imp_iff₂, exists_imp_distrib] at *,
intros N hN, apply N.lie_mem (h N hN), },
..Inf {(s : submodule R M) | s ∈ S} }⟩
@[simp] theorem inf_coe : (↑(N ⊓ N') : set M) = N ∩ N' := rfl
@[simp] lemma Inf_coe_to_submodule (S : set (lie_submodule R L M)) :
(↑(Inf S) : submodule R M) = Inf {(s : submodule R M) | s ∈ S} := rfl
@[simp] lemma Inf_coe (S : set (lie_submodule R L M)) : (↑(Inf S) : set M) = ⋂ s ∈ S, (s : set M) :=
begin
rw [← lie_submodule.coe_to_submodule, Inf_coe_to_submodule, submodule.Inf_coe],
ext m,
simpa only [mem_Inter, mem_set_of_eq, forall_apply_eq_imp_iff₂, exists_imp_distrib],
end
lemma Inf_glb (S : set (lie_submodule R L M)) : is_glb S (Inf S) :=
begin
have h : ∀ (N N' : lie_submodule R L M), (N : set M) ≤ N' ↔ N ≤ N', { intros, refl },
apply is_glb.of_image h,
simp only [Inf_coe],
exact is_glb_binfi
end
/-- The set of Lie submodules of a Lie module form a complete lattice.
We provide explicit values for the fields `bot`, `top`, `inf` to get more convenient definitions
than we would otherwise obtain from `complete_lattice_of_Inf`. -/
instance : complete_lattice (lie_submodule R L M) :=
{ bot := ⊥,
bot_le := λ N _ h, by { rw mem_bot at h, rw h, exact N.zero_mem', },
top := ⊤,
le_top := λ _ _ _, trivial,
inf := (⊓),
le_inf := λ N₁ N₂ N₃ h₁₂ h₁₃ m hm, ⟨h₁₂ hm, h₁₃ hm⟩,
inf_le_left := λ _ _ _, and.left,
inf_le_right := λ _ _ _, and.right,
..complete_lattice_of_Inf _ Inf_glb }
instance : add_comm_monoid (lie_submodule R L M) :=
{ add := (⊔),
add_assoc := λ _ _ _, sup_assoc,
zero := ⊥,
zero_add := λ _, bot_sup_eq,
add_zero := λ _, sup_bot_eq,
add_comm := λ _ _, sup_comm, }
@[simp] lemma add_eq_sup : N + N' = N ⊔ N' := rfl
@[norm_cast, simp] lemma sup_coe_to_submodule :
(↑(N ⊔ N') : submodule R M) = (N : submodule R M) ⊔ (N' : submodule R M) :=
begin
have aux : ∀ (x : L) m, m ∈ (N ⊔ N' : submodule R M) → ⁅x,m⁆ ∈ (N ⊔ N' : submodule R M),
{ simp only [submodule.mem_sup],
rintro x m ⟨y, hy, z, hz, rfl⟩,
refine ⟨⁅x, y⁆, N.lie_mem hy, ⁅x, z⁆, N'.lie_mem hz, (lie_add _ _ _).symm⟩ },
refine le_antisymm (Inf_le ⟨{ lie_mem := aux, ..(N ⊔ N' : submodule R M) }, _⟩) _,
{ simp only [exists_prop, and_true, mem_set_of_eq, eq_self_iff_true, coe_to_submodule_mk,
← coe_submodule_le_coe_submodule, and_self, le_sup_left, le_sup_right] },
{ simp, },
end
@[norm_cast, simp] lemma inf_coe_to_submodule :
(↑(N ⊓ N') : submodule R M) = (N : submodule R M) ⊓ (N' : submodule R M) := rfl
@[simp] lemma mem_inf (x : M) : x ∈ N ⊓ N' ↔ x ∈ N ∧ x ∈ N' :=
by rw [← mem_coe_submodule, ← mem_coe_submodule, ← mem_coe_submodule, inf_coe_to_submodule,
submodule.mem_inf]
lemma mem_sup (x : M) : x ∈ N ⊔ N' ↔ ∃ (y ∈ N) (z ∈ N'), y + z = x :=
by { rw [← mem_coe_submodule, sup_coe_to_submodule, submodule.mem_sup], exact iff.rfl, }
lemma eq_bot_iff : N = ⊥ ↔ ∀ (m : M), m ∈ N → m = 0 :=
by { rw eq_bot_iff, exact iff.rfl, }
-- TODO[gh-6025]: make this an instance once safe to do so
lemma subsingleton_of_bot : subsingleton (lie_submodule R L ↥(⊥ : lie_submodule R L M)) :=
begin
apply subsingleton_of_bot_eq_top,
ext ⟨x, hx⟩, change x ∈ ⊥ at hx, rw submodule.mem_bot at hx, subst hx,
simp only [true_iff, eq_self_iff_true, submodule.mk_eq_zero, lie_submodule.mem_bot],
end
instance : is_modular_lattice (lie_submodule R L M) :=
{ sup_inf_le_assoc_of_le := λ N₁ N₂ N₃,
by { simp only [← coe_submodule_le_coe_submodule, sup_coe_to_submodule, inf_coe_to_submodule],
exact is_modular_lattice.sup_inf_le_assoc_of_le ↑N₂, }, }
variables (R L M)
lemma well_founded_of_noetherian [is_noetherian R M] :
well_founded ((>) : lie_submodule R L M → lie_submodule R L M → Prop) :=
begin
let f : ((>) : lie_submodule R L M → lie_submodule R L M → Prop) →r
((>) : submodule R M → submodule R M → Prop) :=
{ to_fun := coe,
map_rel' := λ N N' h, h, },
apply f.well_founded, rw ← is_noetherian_iff_well_founded, apply_instance,
end
lemma subsingleton_iff : subsingleton M ↔ subsingleton (lie_submodule R L M) :=
(submodule.subsingleton_iff R).trans $ by
rw [← subsingleton_iff_bot_eq_top, ← subsingleton_iff_bot_eq_top, ← coe_to_submodule_eq_iff,
top_coe_submodule, bot_coe_submodule]
lemma nontrivial_iff : nontrivial M ↔ nontrivial (lie_submodule R L M) :=
not_iff_not.mp (
(not_nontrivial_iff_subsingleton.trans $ subsingleton_iff R L M).trans
not_nontrivial_iff_subsingleton.symm)
instance [nontrivial M] : nontrivial (lie_submodule R L M) := (nontrivial_iff R L M).mp ‹_›
variables {R L M}
section inclusion_maps
/-- The inclusion of a Lie submodule into its ambient space is a morphism of Lie modules. -/
def incl : N →ₗ⁅R,L⁆ M :=
{ map_lie' := λ x m, rfl,
..submodule.subtype (N : submodule R M) }
@[simp] lemma incl_apply (m : N) : N.incl m = m := rfl
lemma incl_eq_val : (N.incl : N → M) = subtype.val := rfl
variables {N N'} (h : N ≤ N')
/-- Given two nested Lie submodules `N ⊆ N'`, the inclusion `N ↪ N'` is a morphism of Lie modules.-/
def hom_of_le : N →ₗ⁅R,L⁆ N' :=
{ map_lie' := λ x m, rfl,
..submodule.of_le h }
@[simp] lemma coe_hom_of_le (m : N) : (hom_of_le h m : M) = m := rfl
lemma hom_of_le_apply (m : N) : hom_of_le h m = ⟨m.1, h m.2⟩ := rfl
lemma hom_of_le_injective : function.injective (hom_of_le h) :=
λ x y, by simp only [hom_of_le_apply, imp_self, subtype.mk_eq_mk, set_like.coe_eq_coe,
subtype.val_eq_coe]
end inclusion_maps
section lie_span
variables (R L) (s : set M)
/-- The `lie_span` of a set `s ⊆ M` is the smallest Lie submodule of `M` that contains `s`. -/
def lie_span : lie_submodule R L M := Inf {N | s ⊆ N}
variables {R L s}
lemma mem_lie_span {x : M} : x ∈ lie_span R L s ↔ ∀ N : lie_submodule R L M, s ⊆ N → x ∈ N :=
by { change x ∈ (lie_span R L s : set M) ↔ _, erw Inf_coe, exact mem_bInter_iff, }
lemma subset_lie_span : s ⊆ lie_span R L s :=
by { intros m hm, erw mem_lie_span, intros N hN, exact hN hm, }
lemma submodule_span_le_lie_span : submodule.span R s ≤ lie_span R L s :=
by { rw submodule.span_le, apply subset_lie_span, }
lemma lie_span_le {N} : lie_span R L s ≤ N ↔ s ⊆ N :=
begin
split,
{ exact subset.trans subset_lie_span, },
{ intros hs m hm, rw mem_lie_span at hm, exact hm _ hs, },
end
lemma lie_span_mono {t : set M} (h : s ⊆ t) : lie_span R L s ≤ lie_span R L t :=
by { rw lie_span_le, exact subset.trans h subset_lie_span, }
lemma lie_span_eq : lie_span R L (N : set M) = N :=
le_antisymm (lie_span_le.mpr rfl.subset) subset_lie_span
lemma coe_lie_span_submodule_eq_iff {p : submodule R M} :
(lie_span R L (p : set M) : submodule R M) = p ↔ ∃ (N : lie_submodule R L M), ↑N = p :=
begin
rw p.exists_lie_submodule_coe_eq_iff L, split; intros h,
{ intros x m hm, rw [← h, mem_coe_submodule], exact lie_mem _ (subset_lie_span hm), },
{ rw [← coe_to_submodule_mk p h, coe_to_submodule, coe_to_submodule_eq_iff, lie_span_eq], },
end
variables (R L M)
/-- `lie_span` forms a Galois insertion with the coercion from `lie_submodule` to `set`. -/
protected def gi : galois_insertion (lie_span R L : set M → lie_submodule R L M) coe :=
{ choice := λ s _, lie_span R L s,
gc := λ s t, lie_span_le,
le_l_u := λ s, subset_lie_span,
choice_eq := λ s h, rfl }
@[simp] lemma span_empty : lie_span R L (∅ : set M) = ⊥ :=
(lie_submodule.gi R L M).gc.l_bot
@[simp] lemma span_univ : lie_span R L (set.univ : set M) = ⊤ :=
eq_top_iff.2 $ set_like.le_def.2 $ subset_lie_span
variables {M}
lemma span_union (s t : set M) : lie_span R L (s ∪ t) = lie_span R L s ⊔ lie_span R L t :=
(lie_submodule.gi R L M).gc.l_sup
lemma span_Union {ι} (s : ι → set M) : lie_span R L (⋃ i, s i) = ⨆ i, lie_span R L (s i) :=
(lie_submodule.gi R L M).gc.l_supr
end lie_span
end lattice_structure
end lie_submodule
section lie_submodule_map_and_comap
variables {R : Type u} {L : Type v} {L' : Type w₂} {M : Type w} {M' : Type w₁}
variables [comm_ring R] [lie_ring L] [lie_algebra R L] [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 (f : M →ₗ⁅R,L⁆ M') (N N₂ : lie_submodule R L M) (N' : lie_submodule R L M')
/-- A morphism of Lie modules `f : M → M'` pushes forward Lie submodules of `M` to Lie submodules
of `M'`. -/
def map : lie_submodule R L M' :=
{ lie_mem := λ x m' h, by
{ rcases h with ⟨m, hm, hfm⟩, use ⁅x, m⁆, split,
{ apply N.lie_mem hm, },
{ norm_cast at hfm, simp [hfm], }, },
..(N : submodule R M).map (f : M →ₗ[R] M') }
/-- A morphism of Lie modules `f : M → M'` pulls back Lie submodules of `M'` to Lie submodules of
`M`. -/
def comap : lie_submodule R L M :=
{ lie_mem := λ x m h, by { suffices : ⁅x, f m⁆ ∈ N', { simp [this], }, apply N'.lie_mem h, },
..(N' : submodule R M').comap (f : M →ₗ[R] M') }
variables {f N N₂ N'}
lemma map_le_iff_le_comap : map f N ≤ N' ↔ N ≤ comap f N' :=
set.image_subset_iff
variables (f)
lemma gc_map_comap : galois_connection (map f) (comap f) :=
λ N N', map_le_iff_le_comap
variables {f}
@[simp] lemma map_sup : (N ⊔ N₂).map f = N.map f ⊔ N₂.map f :=
(gc_map_comap f).l_sup
lemma mem_map (m' : M') : m' ∈ N.map f ↔ ∃ m, m ∈ N ∧ f m = m' :=
submodule.mem_map
@[simp] lemma mem_comap {m : M} : m ∈ comap f N' ↔ f m ∈ N' := iff.rfl
end lie_submodule
namespace lie_ideal
variables (f : L →ₗ⁅R⁆ L') (I I₂ : lie_ideal R L) (J : lie_ideal R L')
@[simp] lemma top_coe_lie_subalgebra : ((⊤ : lie_ideal R L) : lie_subalgebra R L) = ⊤ := rfl
/-- A morphism of Lie algebras `f : L → L'` pushes forward Lie ideals of `L` to Lie ideals of `L'`.
Note that unlike `lie_submodule.map`, we must take the `lie_span` of the image. Mathematically
this is because although `f` makes `L'` into a Lie module over `L`, in general the `L` submodules of
`L'` are not the same as the ideals of `L'`. -/
def map : lie_ideal R L' := lie_submodule.lie_span R L' $ (I : submodule R L).map (f : L →ₗ[R] L')
/-- A morphism of Lie algebras `f : L → L'` pulls back Lie ideals of `L'` to Lie ideals of `L`.
Note that `f` makes `L'` into a Lie module over `L` (turning `f` into a morphism of Lie modules)
and so this is a special case of `lie_submodule.comap` but we do not exploit this fact. -/
def comap : lie_ideal R L :=
{ lie_mem := λ x y h, by { suffices : ⁅f x, f y⁆ ∈ J, { simp [this], }, apply J.lie_mem h, },
..(J : submodule R L').comap (f : L →ₗ[R] L') }
@[simp] lemma map_coe_submodule (h : ↑(map f I) = f '' I) :
(map f I : submodule R L') = (I : submodule R L).map f :=
by { rw [set_like.ext'_iff, lie_submodule.coe_to_submodule, h, submodule.map_coe], refl, }
@[simp] lemma comap_coe_submodule : (comap f J : submodule R L) = (J : submodule R L').comap f :=
rfl
lemma map_le : map f I ≤ J ↔ f '' I ⊆ J := lie_submodule.lie_span_le
variables {f I I₂ J}
lemma mem_map {x : L} (hx : x ∈ I) : f x ∈ map f I :=
by { apply lie_submodule.subset_lie_span, use x, exact ⟨hx, rfl⟩, }
@[simp] lemma mem_comap {x : L} : x ∈ comap f J ↔ f x ∈ J := iff.rfl
lemma map_le_iff_le_comap : map f I ≤ J ↔ I ≤ comap f J :=
by { rw map_le, exact set.image_subset_iff, }
variables (f)
lemma gc_map_comap : galois_connection (map f) (comap f) :=
λ I I', map_le_iff_le_comap
variables {f}
@[simp] lemma map_sup : (I ⊔ I₂).map f = I.map f ⊔ I₂.map f :=
(gc_map_comap f).l_sup
lemma map_comap_le : map f (comap f J) ≤ J :=
by { rw map_le_iff_le_comap, apply le_refl _, }
/-- See also `lie_ideal.map_comap_eq`. -/
lemma comap_map_le : I ≤ comap f (map f I) :=
by { rw ← map_le_iff_le_comap, apply le_refl _, }
@[mono] lemma map_mono : monotone (map f) :=
λ I₁ I₂ h,
by { rw lie_submodule.le_def at h, apply lie_submodule.lie_span_mono (set.image_subset ⇑f h), }
@[mono] lemma comap_mono : monotone (comap f) :=
λ J₁ J₂ h, by { rw lie_submodule.le_def at h ⊢, exact set.preimage_mono h, }
lemma map_of_image (h : f '' I = J) : I.map f = J :=
begin
apply le_antisymm,
{ erw [lie_submodule.lie_span_le, submodule.map_coe, h], },
{ rw [lie_submodule.le_def, ← h], exact lie_submodule.subset_lie_span, },
end
/-- Note that this is not a special case of `lie_submodule.subsingleton_of_bot`. Indeed, given
`I : lie_ideal R L`, in general the two lattices `lie_ideal R I` and `lie_submodule R L I` are
different (though the latter does naturally inject into the former).
In other words, in general, ideals of `I`, regarded as a Lie algebra in its own right, are not the
same as ideals of `L` contained in `I`. -/
-- TODO[gh-6025]: make this an instance once safe to do so
lemma subsingleton_of_bot : subsingleton (lie_ideal R ↥(⊥ : lie_ideal R L)) :=
begin
apply subsingleton_of_bot_eq_top,
ext ⟨x, hx⟩, change x ∈ ⊥ at hx, rw submodule.mem_bot at hx, subst hx,
simp only [true_iff, eq_self_iff_true, submodule.mk_eq_zero, lie_submodule.mem_bot],
end
end lie_ideal
namespace lie_hom
variables (f : L →ₗ⁅R⁆ L') (I : lie_ideal R L) (J : lie_ideal R L')
/-- The kernel of a morphism of Lie algebras, as an ideal in the domain. -/
def ker : lie_ideal R L := lie_ideal.comap f ⊥
/-- The range of a morphism of Lie algebras as an ideal in the codomain. -/
def ideal_range : lie_ideal R L' := lie_submodule.lie_span R L' f.range
lemma ideal_range_eq_lie_span_range :
f.ideal_range = lie_submodule.lie_span R L' f.range := rfl
lemma ideal_range_eq_map :
f.ideal_range = lie_ideal.map f ⊤ :=
by { ext, simp only [ideal_range, range_eq_map], refl }
/-- The condition that the image of a morphism of Lie algebras is an ideal. -/
def is_ideal_morphism : Prop := (f.ideal_range : lie_subalgebra R L') = f.range
@[simp] lemma is_ideal_morphism_def :
f.is_ideal_morphism ↔ (f.ideal_range : lie_subalgebra R L') = f.range := iff.rfl
lemma is_ideal_morphism_iff :
f.is_ideal_morphism ↔ ∀ (x : L') (y : L), ∃ (z : L), ⁅x, f y⁆ = f z :=
begin
simp only [is_ideal_morphism_def, ideal_range_eq_lie_span_range,
← lie_subalgebra.coe_to_submodule_eq_iff, ← f.range.coe_to_submodule,
lie_ideal.coe_to_lie_subalgebra_to_submodule, lie_submodule.coe_lie_span_submodule_eq_iff,
lie_subalgebra.mem_coe_submodule, mem_range, exists_imp_distrib,
submodule.exists_lie_submodule_coe_eq_iff],
split,
{ intros h x y, obtain ⟨z, hz⟩ := h x (f y) y rfl, use z, exact hz.symm, },
{ intros h x y z hz, obtain ⟨w, hw⟩ := h x z, use w, rw [← hw, hz], },
end
lemma range_subset_ideal_range : (f.range : set L') ⊆ f.ideal_range := lie_submodule.subset_lie_span
lemma map_le_ideal_range : I.map f ≤ f.ideal_range :=
begin
rw f.ideal_range_eq_map,
exact lie_ideal.map_mono le_top,
end
lemma ker_le_comap : f.ker ≤ J.comap f := lie_ideal.comap_mono bot_le
@[simp] lemma ker_coe_submodule : (ker f : submodule R L) = (f : L →ₗ[R] L').ker := rfl
@[simp] lemma mem_ker {x : L} : x ∈ ker f ↔ f x = 0 :=
show x ∈ (f.ker : submodule R L) ↔ _,
by simp only [ker_coe_submodule, linear_map.mem_ker, coe_to_linear_map]
lemma mem_ideal_range {x : L} : f x ∈ ideal_range f :=
begin
rw ideal_range_eq_map,
exact lie_ideal.mem_map (lie_submodule.mem_top x)
end
@[simp] lemma mem_ideal_range_iff (h : is_ideal_morphism f) {y : L'} :
y ∈ ideal_range f ↔ ∃ (x : L), f x = y :=
begin
rw f.is_ideal_morphism_def at h,
rw [← lie_submodule.mem_coe, ← lie_ideal.coe_to_subalgebra, h, f.range_coe, set.mem_range],
end
lemma le_ker_iff : I ≤ f.ker ↔ ∀ x, x ∈ I → f x = 0 :=
begin
split; intros h x hx,
{ specialize h hx, rw mem_ker at h, exact h, },
{ rw mem_ker, apply h x hx, },
end
lemma ker_eq_bot : f.ker = ⊥ ↔ function.injective f :=
by rw [← lie_submodule.coe_to_submodule_eq_iff, ker_coe_submodule, lie_submodule.bot_coe_submodule,
linear_map.ker_eq_bot, coe_to_linear_map]
@[simp] lemma range_coe_submodule : (f.range : submodule R L') = (f : L →ₗ[R] L').range := rfl
lemma range_eq_top : f.range = ⊤ ↔ function.surjective f :=
begin
rw [← lie_subalgebra.coe_to_submodule_eq_iff, range_coe_submodule,
lie_subalgebra.top_coe_submodule],
exact linear_map.range_eq_top,
end
@[simp] lemma ideal_range_eq_top_of_surjective (h : function.surjective f) : f.ideal_range = ⊤ :=
begin
rw ← f.range_eq_top at h,
rw [ideal_range_eq_lie_span_range, h, ← lie_subalgebra.coe_to_submodule,
← lie_submodule.coe_to_submodule_eq_iff, lie_submodule.top_coe_submodule,
lie_subalgebra.top_coe_submodule, lie_submodule.coe_lie_span_submodule_eq_iff],
use ⊤,
exact lie_submodule.top_coe_submodule,
end
lemma is_ideal_morphism_of_surjective (h : function.surjective f) : f.is_ideal_morphism :=
by rw [is_ideal_morphism_def, f.ideal_range_eq_top_of_surjective h, f.range_eq_top.mpr h,
lie_ideal.top_coe_lie_subalgebra]
end lie_hom
namespace lie_ideal
variables {f : L →ₗ⁅R⁆ L'} {I : lie_ideal R L} {J : lie_ideal R L'}
@[simp] lemma map_eq_bot_iff : I.map f = ⊥ ↔ I ≤ f.ker :=
by { rw ← le_bot_iff, exact lie_ideal.map_le_iff_le_comap }
lemma coe_map_of_surjective (h : function.surjective f) :
(I.map f : submodule R L') = (I : submodule R L).map f :=
begin
let J : lie_ideal R L' :=
{ lie_mem := λ x y hy,
begin
have hy' : ∃ (x : L), x ∈ I ∧ f x = y, { simpa [hy], },
obtain ⟨z₂, hz₂, rfl⟩ := hy',
obtain ⟨z₁, rfl⟩ := h x,
simp only [lie_hom.coe_to_linear_map, set_like.mem_coe, set.mem_image,
lie_submodule.mem_coe_submodule, submodule.mem_carrier, submodule.map_coe],
use ⁅z₁, z₂⁆,
exact ⟨I.lie_mem hz₂, f.map_lie z₁ z₂⟩,
end,
..(I : submodule R L).map (f : L →ₗ[R] L'), },
erw lie_submodule.coe_lie_span_submodule_eq_iff,
use J,
apply lie_submodule.coe_to_submodule_mk,
end
lemma mem_map_of_surjective {y : L'} (h₁ : function.surjective f) (h₂ : y ∈ I.map f) :
∃ (x : I), f x = y :=
begin
rw [← lie_submodule.mem_coe_submodule, coe_map_of_surjective h₁, submodule.mem_map] at h₂,
obtain ⟨x, hx, rfl⟩ := h₂,
use ⟨x, hx⟩,
refl,
end
lemma bot_of_map_eq_bot {I : lie_ideal R L} (h₁ : function.injective f) (h₂ : I.map f = ⊥) :
I = ⊥ :=
begin
rw ← f.ker_eq_bot at h₁, change comap f ⊥ = ⊥ at h₁,
rw [eq_bot_iff, map_le_iff_le_comap, h₁] at h₂,
rw eq_bot_iff, exact h₂,
end
/-- Given two nested Lie ideals `I₁ ⊆ I₂`, the inclusion `I₁ ↪ I₂` is a morphism of Lie algebras. -/
def hom_of_le {I₁ I₂ : lie_ideal R L} (h : I₁ ≤ I₂) : I₁ →ₗ⁅R⁆ I₂ :=
{ map_lie' := λ x y, rfl,
..submodule.of_le h, }
@[simp] lemma coe_hom_of_le {I₁ I₂ : lie_ideal R L} (h : I₁ ≤ I₂) (x : I₁) :
(hom_of_le h x : L) = x := rfl
lemma hom_of_le_apply {I₁ I₂ : lie_ideal R L} (h : I₁ ≤ I₂) (x : I₁) :
hom_of_le h x = ⟨x.1, h x.2⟩ := rfl
lemma hom_of_le_injective {I₁ I₂ : lie_ideal R L} (h : I₁ ≤ I₂) :
function.injective (hom_of_le h) :=
λ x y, by simp only [hom_of_le_apply, imp_self, subtype.mk_eq_mk, set_like.coe_eq_coe,
subtype.val_eq_coe]
@[simp] lemma map_sup_ker_eq_map : lie_ideal.map f (I ⊔ f.ker) = lie_ideal.map f I :=
begin
suffices : lie_ideal.map f (I ⊔ f.ker) ≤ lie_ideal.map f I,
{ exact le_antisymm this (lie_ideal.map_mono le_sup_left), },
apply lie_submodule.lie_span_mono,
rintros x ⟨y, hy₁, hy₂⟩, rw ← hy₂,
erw lie_submodule.mem_sup at hy₁, obtain ⟨z₁, hz₁, z₂, hz₂, hy⟩ := hy₁, rw ← hy,
rw [f.coe_to_linear_map, f.map_add, f.mem_ker.mp hz₂, add_zero], exact ⟨z₁, hz₁, rfl⟩,
end
@[simp] lemma map_comap_eq (h : f.is_ideal_morphism) : map f (comap f J) = f.ideal_range ⊓ J :=
begin
apply le_antisymm,
{ rw le_inf_iff, exact ⟨f.map_le_ideal_range _, map_comap_le⟩, },
{ rw f.is_ideal_morphism_def at h,
rw [lie_submodule.le_def, lie_submodule.inf_coe, ← coe_to_subalgebra, h],
rintros y ⟨⟨x, h₁⟩, h₂⟩, rw ← h₁ at h₂ ⊢, exact mem_map h₂, },
end
@[simp] lemma comap_map_eq (h : ↑(map f I) = f '' I) : comap f (map f I) = I ⊔ f.ker :=
by rw [← lie_submodule.coe_to_submodule_eq_iff, comap_coe_submodule, I.map_coe_submodule f h,
lie_submodule.sup_coe_to_submodule, f.ker_coe_submodule, linear_map.comap_map_eq]
variables (f I J)
/-- Regarding an ideal `I` as a subalgebra, the inclusion map into its ambient space is a morphism
of Lie algebras. -/
def incl : I →ₗ⁅R⁆ L := (I : lie_subalgebra R L).incl
@[simp] lemma incl_range : I.incl.range = I := (I : lie_subalgebra R L).incl_range
@[simp] lemma incl_apply (x : I) : I.incl x = x := rfl
@[simp] lemma incl_coe : (I.incl : I →ₗ[R] L) = (I : submodule R L).subtype := rfl
@[simp] lemma comap_incl_self : comap I.incl I = ⊤ :=
by { rw ← lie_submodule.coe_to_submodule_eq_iff, exact submodule.comap_subtype_self _, }
@[simp] lemma ker_incl : I.incl.ker = ⊥ :=
by rw [← lie_submodule.coe_to_submodule_eq_iff, I.incl.ker_coe_submodule,
lie_submodule.bot_coe_submodule, incl_coe, submodule.ker_subtype]
@[simp] lemma incl_ideal_range : I.incl.ideal_range = I :=
begin
rw [lie_hom.ideal_range_eq_lie_span_range, ← lie_subalgebra.coe_to_submodule,
← lie_submodule.coe_to_submodule_eq_iff, incl_range, coe_to_lie_subalgebra_to_submodule,
lie_submodule.coe_lie_span_submodule_eq_iff],
use I,
end
lemma incl_is_ideal_morphism : I.incl.is_ideal_morphism :=
begin
rw [I.incl.is_ideal_morphism_def, incl_ideal_range],
exact (I : lie_subalgebra R L).incl_range.symm,
end
end lie_ideal
end lie_submodule_map_and_comap
namespace lie_module_hom
variables {R : Type u} {L : Type v} {M : Type w} {N : Type w₁}
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 N] [module R N] [lie_ring_module L N] [lie_module R L N]
variables (f : M →ₗ⁅R,L⁆ N)
/-- The range of a morphism of Lie modules `f : M → N` is a Lie submodule of `N`.
See Note [range copy pattern]. -/
def range : lie_submodule R L N :=
(lie_submodule.map f ⊤).copy (set.range f) set.image_univ.symm
@[simp] lemma coe_range : (f.range : set N) = set.range f := rfl
@[simp] lemma coe_submodule_range : (f.range : submodule R N) = (f : M →ₗ[R] N).range := rfl
@[simp] lemma mem_range (n : N) : n ∈ f.range ↔ ∃ m, f m = n :=
iff.rfl
lemma map_top : lie_submodule.map f ⊤ = f.range :=
by { ext, simp [lie_submodule.mem_map], }
end lie_module_hom
section top_equiv_self
variables {R : Type u} {L : Type v}
variables [comm_ring R] [lie_ring L] [lie_algebra R L]
/-- The natural equivalence between the 'top' Lie subalgebra and the enclosing Lie algebra. -/
def lie_subalgebra.top_equiv_self : (⊤ : lie_subalgebra R L) ≃ₗ⁅R⁆ L :=
{ inv_fun := λ x, ⟨x, set.mem_univ x⟩,
left_inv := λ x, by { ext, refl, },
right_inv := λ x, rfl,
..(⊤ : lie_subalgebra R L).incl, }
@[simp] lemma lie_subalgebra.top_equiv_self_apply (x : (⊤ : lie_subalgebra R L)) :
lie_subalgebra.top_equiv_self x = x := rfl
/-- The natural equivalence between the 'top' Lie ideal and the enclosing Lie algebra. -/
def lie_ideal.top_equiv_self : (⊤ : lie_ideal R L) ≃ₗ⁅R⁆ L :=
lie_subalgebra.top_equiv_self
@[simp] lemma lie_ideal.top_equiv_self_apply (x : (⊤ : lie_ideal R L)) :
lie_ideal.top_equiv_self x = x := rfl
end top_equiv_self
|
6ea8857319739ba651089112984be93e4a2b44c0 | 4950bf76e5ae40ba9f8491647d0b6f228ddce173 | /src/topology/subset_properties.lean | e1ec880dd58bb0af0677048468e30c306572f4fa | [
"Apache-2.0"
] | permissive | ntzwq/mathlib | ca50b21079b0a7c6781c34b62199a396dd00cee2 | 36eec1a98f22df82eaccd354a758ef8576af2a7f | refs/heads/master | 1,675,193,391,478 | 1,607,822,996,000 | 1,607,822,996,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 59,288 | 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, Yury Kudryashov
-/
import topology.continuous_on
import data.finset.order
/-!
# Properties of subsets of topological spaces
## Main definitions
`compact`, `is_clopen`, `is_irreducible`, `is_connected`, `is_totally_disconnected`,
`is_totally_separated`
TODO: write better docs
## On the definition of irreducible and connected sets/spaces
In informal mathematics, irreducible and connected spaces are assumed to be nonempty.
We formalise the predicate without that assumption
as `is_preirreducible` and `is_preconnected` respectively.
In other words, the only difference is whether the empty space
counts as irreducible and/or connected.
There are good reasons to consider the empty space to be “too simple to be simple”
See also https://ncatlab.org/nlab/show/too+simple+to+be+simple,
and in particular
https://ncatlab.org/nlab/show/too+simple+to+be+simple#relationship_to_biased_definitions.
-/
open set filter classical
open_locale classical topological_space filter
universes u v
variables {α : Type u} {β : Type v} [topological_space α] {s t : set α}
/- compact sets -/
section compact
/-- A set `s` is compact if for every filter `f` that contains `s`,
every set of `f` also meets every neighborhood of some `a ∈ s`. -/
def is_compact (s : set α) := ∀ ⦃f⦄ [ne_bot f], f ≤ 𝓟 s → ∃a∈s, cluster_pt a f
/-- The complement to a compact set belongs to a filter `f` if it belongs to each filter
`𝓝 a ⊓ f`, `a ∈ s`. -/
lemma is_compact.compl_mem_sets (hs : is_compact s) {f : filter α} (hf : ∀ a ∈ s, sᶜ ∈ 𝓝 a ⊓ f) :
sᶜ ∈ f :=
begin
contrapose! hf,
simp only [mem_iff_inf_principal_compl, compl_compl, inf_assoc, ← exists_prop] at hf ⊢,
exact @hs _ hf inf_le_right
end
/-- The complement to a compact set belongs to a filter `f` if each `a ∈ s` has a neighborhood `t`
within `s` such that `tᶜ` belongs to `f`. -/
lemma is_compact.compl_mem_sets_of_nhds_within (hs : is_compact s) {f : filter α}
(hf : ∀ a ∈ s, ∃ t ∈ 𝓝[s] a, tᶜ ∈ f) :
sᶜ ∈ f :=
begin
refine hs.compl_mem_sets (λ a ha, _),
rcases hf a ha with ⟨t, ht, hst⟩,
replace ht := mem_inf_principal.1 ht,
refine mem_inf_sets.2 ⟨_, ht, _, hst, _⟩,
rintros x ⟨h₁, h₂⟩ hs,
exact h₂ (h₁ hs)
end
/-- If `p : set α → Prop` is stable under restriction and union, and each point `x of a compact set `s`
has a neighborhood `t` within `s` such that `p t`, then `p s` holds. -/
@[elab_as_eliminator]
lemma is_compact.induction_on {s : set α} (hs : is_compact s) {p : set α → Prop} (he : p ∅)
(hmono : ∀ ⦃s t⦄, s ⊆ t → p t → p s) (hunion : ∀ ⦃s t⦄, p s → p t → p (s ∪ t))
(hnhds : ∀ x ∈ s, ∃ t ∈ 𝓝[s] x, p t) :
p s :=
let f : filter α :=
{ sets := {t | p tᶜ},
univ_sets := by simpa,
sets_of_superset := λ t₁ t₂ ht₁ ht, hmono (compl_subset_compl.2 ht) ht₁,
inter_sets := λ t₁ t₂ ht₁ ht₂, by simp [compl_inter, hunion ht₁ ht₂] } in
have sᶜ ∈ f, from hs.compl_mem_sets_of_nhds_within (by simpa using hnhds),
by simpa
/-- The intersection of a compact set and a closed set is a compact set. -/
lemma is_compact.inter_right (hs : is_compact s) (ht : is_closed t) :
is_compact (s ∩ t) :=
begin
introsI f hnf hstf,
obtain ⟨a, hsa, ha⟩ : ∃ a ∈ s, cluster_pt a f :=
hs (le_trans hstf (le_principal_iff.2 (inter_subset_left _ _))),
have : a ∈ t :=
(ht.mem_of_nhds_within_ne_bot $ ha.mono $
le_trans hstf (le_principal_iff.2 (inter_subset_right _ _))),
exact ⟨a, ⟨hsa, this⟩, ha⟩
end
/-- The intersection of a closed set and a compact set is a compact set. -/
lemma is_compact.inter_left (ht : is_compact t) (hs : is_closed s) : is_compact (s ∩ t) :=
inter_comm t s ▸ ht.inter_right hs
/-- The set difference of a compact set and an open set is a compact set. -/
lemma compact_diff (hs : is_compact s) (ht : is_open t) : is_compact (s \ t) :=
hs.inter_right (is_closed_compl_iff.mpr ht)
/-- A closed subset of a compact set is a compact set. -/
lemma compact_of_is_closed_subset (hs : is_compact s) (ht : is_closed t) (h : t ⊆ s) :
is_compact t :=
inter_eq_self_of_subset_right h ▸ hs.inter_right ht
lemma is_compact.adherence_nhdset {f : filter α}
(hs : is_compact s) (hf₂ : f ≤ 𝓟 s) (ht₁ : is_open t) (ht₂ : ∀a∈s, cluster_pt a f → a ∈ t) :
t ∈ f :=
classical.by_cases mem_sets_of_eq_bot $
assume : f ⊓ 𝓟 tᶜ ≠ ⊥,
let ⟨a, ha, (hfa : cluster_pt a $ f ⊓ 𝓟 tᶜ)⟩ := @@hs this $ inf_le_left_of_le hf₂ in
have a ∈ t,
from ht₂ a ha (hfa.of_inf_left),
have tᶜ ∩ t ∈ 𝓝[tᶜ] a,
from inter_mem_nhds_within _ (mem_nhds_sets ht₁ this),
have A : 𝓝[tᶜ] a = ⊥,
from empty_in_sets_eq_bot.1 $ compl_inter_self t ▸ this,
have 𝓝[tᶜ] a ≠ ⊥,
from hfa.of_inf_right,
absurd A this
lemma compact_iff_ultrafilter_le_nhds :
is_compact s ↔ (∀f : ultrafilter α, ↑f ≤ 𝓟 s → ∃a∈s, ↑f ≤ 𝓝 a) :=
begin
refine (forall_ne_bot_le_iff _).trans _,
{ rintro f g hle ⟨a, has, haf⟩,
exact ⟨a, has, haf.mono hle⟩ },
{ simp only [ultrafilter.cluster_pt_iff] }
end
alias compact_iff_ultrafilter_le_nhds ↔ is_compact.ultrafilter_le_nhds _
/-- For every open cover of a compact set, there exists a finite subcover. -/
lemma is_compact.elim_finite_subcover {ι : Type v} (hs : is_compact s)
(U : ι → set α) (hUo : ∀i, is_open (U i)) (hsU : s ⊆ ⋃ i, U i) :
∃ t : finset ι, s ⊆ ⋃ i ∈ t, U i :=
is_compact.induction_on hs ⟨∅, empty_subset _⟩ (λ s₁ s₂ hs ⟨t, hs₂⟩, ⟨t, subset.trans hs hs₂⟩)
(λ s₁ s₂ ⟨t₁, ht₁⟩ ⟨t₂, ht₂⟩,
⟨t₁ ∪ t₂, by { rw [finset.bUnion_union], exact union_subset_union ht₁ ht₂ }⟩)
(λ x hx, let ⟨i, hi⟩ := mem_Union.1 (hsU hx) in
⟨U i, mem_nhds_within.2 ⟨U i, hUo i, hi, inter_subset_left _ _⟩, {i}, by simp⟩)
/-- For every family of closed sets whose intersection avoids a compact set,
there exists a finite subfamily whose intersection avoids this compact set. -/
lemma is_compact.elim_finite_subfamily_closed {s : set α} {ι : Type v} (hs : is_compact s)
(Z : ι → set α) (hZc : ∀i, is_closed (Z i)) (hsZ : s ∩ (⋂ i, Z i) = ∅) :
∃ t : finset ι, s ∩ (⋂ i ∈ t, Z i) = ∅ :=
let ⟨t, ht⟩ := hs.elim_finite_subcover (λ i, (Z i)ᶜ) hZc
(by simpa only [subset_def, not_forall, eq_empty_iff_forall_not_mem, set.mem_Union,
exists_prop, set.mem_inter_eq, not_and, iff_self, set.mem_Inter, set.mem_compl_eq] using hsZ)
in
⟨t, by simpa only [subset_def, not_forall, eq_empty_iff_forall_not_mem, set.mem_Union,
exists_prop, set.mem_inter_eq, not_and, iff_self, set.mem_Inter, set.mem_compl_eq] using ht⟩
/-- To show that a compact set intersects the intersection of a family of closed sets,
it is sufficient to show that it intersects every finite subfamily. -/
lemma is_compact.inter_Inter_nonempty {s : set α} {ι : Type v} (hs : is_compact s)
(Z : ι → set α) (hZc : ∀i, is_closed (Z i)) (hsZ : ∀ t : finset ι, (s ∩ ⋂ i ∈ t, Z i).nonempty) :
(s ∩ ⋂ i, Z i).nonempty :=
begin
simp only [← ne_empty_iff_nonempty] at hsZ ⊢,
apply mt (hs.elim_finite_subfamily_closed Z hZc), push_neg, exact hsZ
end
/-- Cantor's intersection theorem:
the intersection of a directed family of nonempty compact closed sets is nonempty. -/
lemma is_compact.nonempty_Inter_of_directed_nonempty_compact_closed
{ι : Type v} [hι : nonempty ι] (Z : ι → set α) (hZd : directed (⊇) Z)
(hZn : ∀ i, (Z i).nonempty) (hZc : ∀ i, is_compact (Z i)) (hZcl : ∀ i, is_closed (Z i)) :
(⋂ i, Z i).nonempty :=
begin
apply hι.elim,
intro i₀,
let Z' := λ i, Z i ∩ Z i₀,
suffices : (⋂ i, Z' i).nonempty,
{ exact nonempty.mono (Inter_subset_Inter $ assume i, inter_subset_left (Z i) (Z i₀)) this },
rw ← ne_empty_iff_nonempty,
intro H,
obtain ⟨t, ht⟩ : ∃ (t : finset ι), ((Z i₀) ∩ ⋂ (i ∈ t), Z' i) = ∅,
from (hZc i₀).elim_finite_subfamily_closed Z'
(assume i, is_closed_inter (hZcl i) (hZcl i₀)) (by rw [H, inter_empty]),
obtain ⟨i₁, hi₁⟩ : ∃ i₁ : ι, Z i₁ ⊆ Z i₀ ∧ ∀ i ∈ t, Z i₁ ⊆ Z' i,
{ rcases directed.finset_le hZd t with ⟨i, hi⟩,
rcases hZd i i₀ with ⟨i₁, hi₁, hi₁₀⟩,
use [i₁, hi₁₀],
intros j hj,
exact subset_inter (subset.trans hi₁ (hi j hj)) hi₁₀ },
suffices : ((Z i₀) ∩ ⋂ (i ∈ t), Z' i).nonempty,
{ rw ← ne_empty_iff_nonempty at this, contradiction },
refine nonempty.mono _ (hZn i₁),
exact subset_inter hi₁.left (subset_bInter hi₁.right)
end
/-- Cantor's intersection theorem for sequences indexed by `ℕ`:
the intersection of a decreasing sequence of nonempty compact closed sets is nonempty. -/
lemma is_compact.nonempty_Inter_of_sequence_nonempty_compact_closed
(Z : ℕ → set α) (hZd : ∀ i, Z (i+1) ⊆ Z i)
(hZn : ∀ i, (Z i).nonempty) (hZ0 : is_compact (Z 0)) (hZcl : ∀ i, is_closed (Z i)) :
(⋂ i, Z i).nonempty :=
have Zmono : _, from @monotone_of_monotone_nat (order_dual _) _ Z hZd,
have hZd : directed (⊇) Z, from directed_of_sup Zmono,
have ∀ i, Z i ⊆ Z 0, from assume i, Zmono $ zero_le i,
have hZc : ∀ i, is_compact (Z i), from assume i, compact_of_is_closed_subset hZ0 (hZcl i) (this i),
is_compact.nonempty_Inter_of_directed_nonempty_compact_closed Z hZd hZn hZc hZcl
/-- For every open cover of a compact set, there exists a finite subcover. -/
lemma is_compact.elim_finite_subcover_image {b : set β} {c : β → set α}
(hs : is_compact s) (hc₁ : ∀i∈b, is_open (c i)) (hc₂ : s ⊆ ⋃i∈b, c i) :
∃b'⊆b, finite b' ∧ s ⊆ ⋃i∈b', c i :=
begin
rcases hs.elim_finite_subcover (λ i, c i.1 : b → set α) _ _ with ⟨d, hd⟩,
refine ⟨↑(d.image subtype.val), _, finset.finite_to_set _, _⟩,
{ intros i hi,
erw finset.mem_image at hi,
rcases hi with ⟨s, hsd, rfl⟩,
exact s.property },
{ refine subset.trans hd _,
rintros x ⟨_, ⟨s, rfl⟩, ⟨_, ⟨hsd, rfl⟩, H⟩⟩,
refine ⟨c s.val, ⟨s.val, _⟩, H⟩,
simp [finset.mem_image_of_mem subtype.val hsd] },
{ rintro ⟨i, hi⟩, exact hc₁ i hi },
{ refine subset.trans hc₂ _,
rintros x ⟨_, ⟨i, rfl⟩, ⟨_, ⟨hib, rfl⟩, H⟩⟩,
exact ⟨_, ⟨⟨i, hib⟩, rfl⟩, H⟩ },
end
/-- A set `s` is compact if for every family of closed sets whose intersection avoids `s`,
there exists a finite subfamily whose intersection avoids `s`. -/
theorem compact_of_finite_subfamily_closed
(h : Π {ι : Type u} (Z : ι → (set α)), (∀ i, is_closed (Z i)) →
s ∩ (⋂ i, Z i) = ∅ → (∃ (t : finset ι), s ∩ (⋂ i ∈ t, Z i) = ∅)) :
is_compact s :=
assume f hfn hfs, classical.by_contradiction $ assume : ¬ (∃x∈s, cluster_pt x f),
have hf : ∀x∈s, 𝓝 x ⊓ f = ⊥,
by simpa only [cluster_pt, not_exists, not_not, ne_bot],
have ¬ ∃x∈s, ∀t∈f.sets, x ∈ closure t,
from assume ⟨x, hxs, hx⟩,
have ∅ ∈ 𝓝 x ⊓ f, by rw [empty_in_sets_eq_bot, hf x hxs],
let ⟨t₁, ht₁, t₂, ht₂, ht⟩ := by rw [mem_inf_sets] at this; exact this in
have ∅ ∈ 𝓝[t₂] x,
from (𝓝[t₂] x).sets_of_superset (inter_mem_inf_sets ht₁ (subset.refl t₂)) ht,
have 𝓝[t₂] x = ⊥,
by rwa [empty_in_sets_eq_bot] at this,
by simp only [closure_eq_cluster_pts] at hx; exact hx t₂ ht₂ this,
let ⟨t, ht⟩ := h (λ i : f.sets, closure i.1) (λ i, is_closed_closure)
(by simpa [eq_empty_iff_forall_not_mem, not_exists]) in
have (⋂i∈t, subtype.val i) ∈ f,
from Inter_mem_sets t.finite_to_set $ assume i hi, i.2,
have s ∩ (⋂i∈t, subtype.val i) ∈ f,
from inter_mem_sets (le_principal_iff.1 hfs) this,
have ∅ ∈ f,
from mem_sets_of_superset this $ assume x ⟨hxs, hx⟩,
let ⟨i, hit, hxi⟩ := (show ∃i ∈ t, x ∉ closure (subtype.val i),
by { rw [eq_empty_iff_forall_not_mem] at ht, simpa [hxs, not_forall] using ht x }) in
have x ∈ closure i.val, from subset_closure (mem_bInter_iff.mp hx i hit),
show false, from hxi this,
hfn $ by rwa [empty_in_sets_eq_bot] at this
/-- A set `s` is compact if for every open cover of `s`, there exists a finite subcover. -/
lemma compact_of_finite_subcover
(h : Π {ι : Type u} (U : ι → (set α)), (∀ i, is_open (U i)) →
s ⊆ (⋃ i, U i) → (∃ (t : finset ι), s ⊆ (⋃ i ∈ t, U i))) :
is_compact s :=
compact_of_finite_subfamily_closed $
assume ι Z hZc hsZ,
let ⟨t, ht⟩ := h (λ i, (Z i)ᶜ) (assume i, is_open_compl_iff.mpr $ hZc i)
(by simpa only [subset_def, not_forall, eq_empty_iff_forall_not_mem, set.mem_Union,
exists_prop, set.mem_inter_eq, not_and, iff_self, set.mem_Inter, set.mem_compl_eq] using hsZ)
in
⟨t, by simpa only [subset_def, not_forall, eq_empty_iff_forall_not_mem, set.mem_Union,
exists_prop, set.mem_inter_eq, not_and, iff_self, set.mem_Inter, set.mem_compl_eq] using ht⟩
/-- A set `s` is compact if and only if
for every open cover of `s`, there exists a finite subcover. -/
lemma compact_iff_finite_subcover :
is_compact s ↔ (Π {ι : Type u} (U : ι → (set α)), (∀ i, is_open (U i)) →
s ⊆ (⋃ i, U i) → (∃ (t : finset ι), s ⊆ (⋃ i ∈ t, U i))) :=
⟨assume hs ι, hs.elim_finite_subcover, compact_of_finite_subcover⟩
/-- A set `s` is compact if and only if
for every family of closed sets whose intersection avoids `s`,
there exists a finite subfamily whose intersection avoids `s`. -/
theorem compact_iff_finite_subfamily_closed :
is_compact s ↔ (Π {ι : Type u} (Z : ι → (set α)), (∀ i, is_closed (Z i)) →
s ∩ (⋂ i, Z i) = ∅ → (∃ (t : finset ι), s ∩ (⋂ i ∈ t, Z i) = ∅)) :=
⟨assume hs ι, hs.elim_finite_subfamily_closed, compact_of_finite_subfamily_closed⟩
@[simp]
lemma compact_empty : is_compact (∅ : set α) :=
assume f hnf hsf, not.elim hnf $
empty_in_sets_eq_bot.1 $ le_principal_iff.1 hsf
@[simp]
lemma compact_singleton {a : α} : is_compact ({a} : set α) :=
λ f hf hfa, ⟨a, rfl, cluster_pt.of_le_nhds'
(hfa.trans $ by simpa only [principal_singleton] using pure_le_nhds a) hf⟩
lemma set.finite.compact_bUnion {s : set β} {f : β → set α} (hs : finite s)
(hf : ∀i ∈ s, is_compact (f i)) :
is_compact (⋃i ∈ s, f i) :=
compact_of_finite_subcover $ assume ι U hUo hsU,
have ∀i : subtype s, ∃t : finset ι, f i ⊆ (⋃ j ∈ t, U j), from
assume ⟨i, hi⟩, (hf i hi).elim_finite_subcover _ hUo
(calc f i ⊆ ⋃i ∈ s, f i : subset_bUnion_of_mem hi
... ⊆ ⋃j, U j : hsU),
let ⟨finite_subcovers, h⟩ := axiom_of_choice this in
by haveI : fintype (subtype s) := hs.fintype; exact
let t := finset.bind finset.univ finite_subcovers in
have (⋃i ∈ s, f i) ⊆ (⋃ i ∈ t, U i), from bUnion_subset $
assume i hi, calc
f i ⊆ (⋃ j ∈ finite_subcovers ⟨i, hi⟩, U j) : (h ⟨i, hi⟩)
... ⊆ (⋃ j ∈ t, U j) : bUnion_subset_bUnion_left $
assume j hj, finset.mem_bind.mpr ⟨_, finset.mem_univ _, hj⟩,
⟨t, this⟩
lemma compact_Union {f : β → set α} [fintype β]
(h : ∀i, is_compact (f i)) : is_compact (⋃i, f i) :=
by rw ← bUnion_univ; exact finite_univ.compact_bUnion (λ i _, h i)
lemma set.finite.is_compact (hs : finite s) : is_compact s :=
bUnion_of_singleton s ▸ hs.compact_bUnion (λ _ _, compact_singleton)
lemma is_compact.union (hs : is_compact s) (ht : is_compact t) : is_compact (s ∪ t) :=
by rw union_eq_Union; exact compact_Union (λ b, by cases b; assumption)
lemma is_compact.insert (hs : is_compact s) (a) : is_compact (insert a s) :=
compact_singleton.union hs
/-- `filter.cocompact` is the filter generated by complements to compact sets. -/
def filter.cocompact (α : Type*) [topological_space α] : filter α :=
⨅ (s : set α) (hs : is_compact s), 𝓟 (sᶜ)
lemma filter.has_basis_cocompact : (filter.cocompact α).has_basis is_compact compl :=
has_basis_binfi_principal'
(λ s hs t ht, ⟨s ∪ t, hs.union ht, compl_subset_compl.2 (subset_union_left s t),
compl_subset_compl.2 (subset_union_right s t)⟩)
⟨∅, compact_empty⟩
lemma filter.mem_cocompact : s ∈ filter.cocompact α ↔ ∃ t, is_compact t ∧ tᶜ ⊆ s :=
filter.has_basis_cocompact.mem_iff.trans $ exists_congr $ λ t, exists_prop
lemma filter.mem_cocompact' : s ∈ filter.cocompact α ↔ ∃ t, is_compact t ∧ sᶜ ⊆ t :=
filter.mem_cocompact.trans $ exists_congr $ λ t, and_congr_right $ λ ht, compl_subset_comm
lemma is_compact.compl_mem_cocompact (hs : is_compact s) : sᶜ ∈ filter.cocompact α :=
filter.has_basis_cocompact.mem_of_mem hs
section tube_lemma
variables [topological_space β]
/-- `nhds_contain_boxes s t` means that any open neighborhood of `s × t` in `α × β` includes
a product of an open neighborhood of `s` by an open neighborhood of `t`. -/
def nhds_contain_boxes (s : set α) (t : set β) : Prop :=
∀ (n : set (α × β)) (hn : is_open n) (hp : set.prod s t ⊆ n),
∃ (u : set α) (v : set β), is_open u ∧ is_open v ∧ s ⊆ u ∧ t ⊆ v ∧ set.prod u v ⊆ n
lemma nhds_contain_boxes.symm {s : set α} {t : set β} :
nhds_contain_boxes s t → nhds_contain_boxes t s :=
assume H n hn hp,
let ⟨u, v, uo, vo, su, tv, p⟩ :=
H (prod.swap ⁻¹' n)
(hn.preimage continuous_swap)
(by rwa [←image_subset_iff, image_swap_prod]) in
⟨v, u, vo, uo, tv, su,
by rwa [←image_subset_iff, image_swap_prod] at p⟩
lemma nhds_contain_boxes.comm {s : set α} {t : set β} :
nhds_contain_boxes s t ↔ nhds_contain_boxes t s :=
iff.intro nhds_contain_boxes.symm nhds_contain_boxes.symm
lemma nhds_contain_boxes_of_singleton {x : α} {y : β} :
nhds_contain_boxes ({x} : set α) ({y} : set β) :=
assume n hn hp,
let ⟨u, v, uo, vo, xu, yv, hp'⟩ :=
is_open_prod_iff.mp hn x y (hp $ by simp) in
⟨u, v, uo, vo, by simpa, by simpa, hp'⟩
lemma nhds_contain_boxes_of_compact {s : set α} (hs : is_compact s) (t : set β)
(H : ∀ x ∈ s, nhds_contain_boxes ({x} : set α) t) : nhds_contain_boxes s t :=
assume n hn hp,
have ∀x : subtype s, ∃uv : set α × set β,
is_open uv.1 ∧ is_open uv.2 ∧ {↑x} ⊆ uv.1 ∧ t ⊆ uv.2 ∧ set.prod uv.1 uv.2 ⊆ n,
from assume ⟨x, hx⟩,
have set.prod {x} t ⊆ n, from
subset.trans (prod_mono (by simpa) (subset.refl _)) hp,
let ⟨ux,vx,H1⟩ := H x hx n hn this in ⟨⟨ux,vx⟩,H1⟩,
let ⟨uvs, h⟩ := classical.axiom_of_choice this in
have us_cover : s ⊆ ⋃i, (uvs i).1, from
assume x hx, set.subset_Union _ ⟨x,hx⟩ (by simpa using (h ⟨x,hx⟩).2.2.1),
let ⟨s0, s0_cover⟩ :=
hs.elim_finite_subcover _ (λi, (h i).1) us_cover in
let u := ⋃(i ∈ s0), (uvs i).1 in
let v := ⋂(i ∈ s0), (uvs i).2 in
have is_open u, from is_open_bUnion (λi _, (h i).1),
have is_open v, from is_open_bInter s0.finite_to_set (λi _, (h i).2.1),
have t ⊆ v, from subset_bInter (λi _, (h i).2.2.2.1),
have set.prod u v ⊆ n, from assume ⟨x',y'⟩ ⟨hx',hy'⟩,
have ∃i ∈ s0, x' ∈ (uvs i).1, by simpa using hx',
let ⟨i,is0,hi⟩ := this in
(h i).2.2.2.2 ⟨hi, (bInter_subset_of_mem is0 : v ⊆ (uvs i).2) hy'⟩,
⟨u, v, ‹is_open u›, ‹is_open v›, s0_cover, ‹t ⊆ v›, ‹set.prod u v ⊆ n›⟩
/-- If `s` and `t` are compact sets and `n` is an open neighborhood of `s × t`, then there exist
open neighborhoods `u ⊇ s` and `v ⊇ t` such that `u × v ⊆ n`. -/
lemma generalized_tube_lemma {s : set α} (hs : is_compact s) {t : set β} (ht : is_compact t)
{n : set (α × β)} (hn : is_open n) (hp : set.prod s t ⊆ n) :
∃ (u : set α) (v : set β), is_open u ∧ is_open v ∧ s ⊆ u ∧ t ⊆ v ∧ set.prod u v ⊆ n :=
have _, from
nhds_contain_boxes_of_compact hs t $ assume x _, nhds_contain_boxes.symm $
nhds_contain_boxes_of_compact ht {x} $ assume y _, nhds_contain_boxes_of_singleton,
this n hn hp
end tube_lemma
/-- Type class for compact spaces. Separation is sometimes included in the definition, especially
in the French literature, but we do not include it here. -/
class compact_space (α : Type*) [topological_space α] : Prop :=
(compact_univ : is_compact (univ : set α))
lemma compact_univ [h : compact_space α] : is_compact (univ : set α) := h.compact_univ
lemma cluster_point_of_compact [compact_space α] (f : filter α) [ne_bot f] :
∃ x, cluster_pt x f :=
by simpa using compact_univ (show f ≤ 𝓟 univ, by simp)
theorem compact_space_of_finite_subfamily_closed {α : Type u} [topological_space α]
(h : Π {ι : Type u} (Z : ι → (set α)), (∀ i, is_closed (Z i)) →
(⋂ i, Z i) = ∅ → (∃ (t : finset ι), (⋂ i ∈ t, Z i) = ∅)) :
compact_space α :=
{ compact_univ :=
begin
apply compact_of_finite_subfamily_closed,
intros ι Z, specialize h Z,
simpa using h
end }
lemma is_closed.compact [compact_space α] {s : set α} (h : is_closed s) :
is_compact s :=
compact_of_is_closed_subset compact_univ h (subset_univ _)
variables [topological_space β]
lemma is_compact.image_of_continuous_on {f : α → β} (hs : is_compact s) (hf : continuous_on f s) :
is_compact (f '' s) :=
begin
intros l lne ls,
have : ne_bot (l.comap f ⊓ 𝓟 s) :=
comap_inf_principal_ne_bot_of_image_mem lne (le_principal_iff.1 ls),
obtain ⟨a, has, ha⟩ : ∃ a ∈ s, cluster_pt a (l.comap f ⊓ 𝓟 s) := @@hs this inf_le_right,
use [f a, mem_image_of_mem f has],
have : tendsto f (𝓝 a ⊓ (comap f l ⊓ 𝓟 s)) (𝓝 (f a) ⊓ l),
{ convert (hf a has).inf (@tendsto_comap _ _ f l) using 1,
rw nhds_within,
ac_refl },
exact @@tendsto.ne_bot _ this ha,
end
lemma is_compact.image {f : α → β} (hs : is_compact s) (hf : continuous f) :
is_compact (f '' s) :=
hs.image_of_continuous_on hf.continuous_on
lemma compact_range [compact_space α] {f : α → β} (hf : continuous f) :
is_compact (range f) :=
by rw ← image_univ; exact compact_univ.image hf
/-- If X is is_compact then pr₂ : X × Y → Y is a closed map -/
theorem is_closed_proj_of_compact
{X : Type*} [topological_space X] [compact_space X]
{Y : Type*} [topological_space Y] :
is_closed_map (prod.snd : X × Y → Y) :=
begin
set πX := (prod.fst : X × Y → X),
set πY := (prod.snd : X × Y → Y),
assume C (hC : is_closed C),
rw is_closed_iff_cluster_pt at hC ⊢,
assume y (y_closure : cluster_pt y $ 𝓟 (πY '' C)),
have : ne_bot (map πX (comap πY (𝓝 y) ⊓ 𝓟 C)),
{ suffices : ne_bot (map πY (comap πY (𝓝 y) ⊓ 𝓟 C)),
by simpa only [map_ne_bot_iff],
calc map πY (comap πY (𝓝 y) ⊓ 𝓟 C) =
𝓝 y ⊓ map πY (𝓟 C) : filter.push_pull' _ _ _
... = 𝓝 y ⊓ 𝓟 (πY '' C) : by rw map_principal
... ≠ ⊥ : y_closure },
resetI,
obtain ⟨x, hx⟩ : ∃ x, cluster_pt x (map πX (comap πY (𝓝 y) ⊓ 𝓟 C)),
from cluster_point_of_compact _,
refine ⟨⟨x, y⟩, _, by simp [πY]⟩,
apply hC,
rw [cluster_pt, ← filter.map_ne_bot_iff πX],
calc map πX (𝓝 (x, y) ⊓ 𝓟 C)
= map πX (comap πX (𝓝 x) ⊓ comap πY (𝓝 y) ⊓ 𝓟 C) : by rw [nhds_prod_eq, filter.prod]
... = map πX (comap πY (𝓝 y) ⊓ 𝓟 C ⊓ comap πX (𝓝 x)) : by ac_refl
... = map πX (comap πY (𝓝 y) ⊓ 𝓟 C) ⊓ 𝓝 x : by rw filter.push_pull
... = 𝓝 x ⊓ map πX (comap πY (𝓝 y) ⊓ 𝓟 C) : by rw inf_comm
... ≠ ⊥ : hx,
end
lemma embedding.compact_iff_compact_image {f : α → β} (hf : embedding f) :
is_compact s ↔ is_compact (f '' s) :=
iff.intro (assume h, h.image hf.continuous) $ assume h, begin
rw compact_iff_ultrafilter_le_nhds at ⊢ h,
intros u us',
have : ↑(u.map f) ≤ 𝓟 (f '' s), begin
rw [ultrafilter.coe_map, map_le_iff_le_comap, comap_principal], convert us',
exact preimage_image_eq _ hf.inj
end,
rcases h (u.map f) this with ⟨_, ⟨a, ha, ⟨⟩⟩, _⟩,
refine ⟨a, ha, _⟩,
rwa [hf.induced, nhds_induced, ←map_le_iff_le_comap]
end
lemma compact_iff_compact_in_subtype {p : α → Prop} {s : set {a // p a}} :
is_compact s ↔ is_compact ((coe : _ → α) '' s) :=
embedding_subtype_coe.compact_iff_compact_image
lemma compact_iff_compact_univ {s : set α} : is_compact s ↔ is_compact (univ : set s) :=
by rw [compact_iff_compact_in_subtype, image_univ, subtype.range_coe]; refl
lemma compact_iff_compact_space {s : set α} : is_compact s ↔ compact_space s :=
compact_iff_compact_univ.trans ⟨λ h, ⟨h⟩, @compact_space.compact_univ _ _⟩
lemma is_compact.prod {s : set α} {t : set β} (hs : is_compact s) (ht : is_compact t) :
is_compact (set.prod s t) :=
begin
rw compact_iff_ultrafilter_le_nhds at hs ht ⊢,
intros f hfs,
rw le_principal_iff at hfs,
obtain ⟨a : α, sa : a ∈ s, ha : map prod.fst ↑f ≤ 𝓝 a⟩ :=
hs (f.map prod.fst) (le_principal_iff.2 $ mem_map.2 $ mem_sets_of_superset hfs (λ x, and.left)),
obtain ⟨b : β, tb : b ∈ t, hb : map prod.snd ↑f ≤ 𝓝 b⟩ :=
ht (f.map prod.snd) (le_principal_iff.2 $ mem_map.2 $
mem_sets_of_superset hfs (λ x, and.right)),
rw map_le_iff_le_comap at ha hb,
refine ⟨⟨a, b⟩, ⟨sa, tb⟩, _⟩,
rw nhds_prod_eq, exact le_inf ha hb
end
/-- Finite topological spaces are compact. -/
@[priority 100] instance fintype.compact_space [fintype α] : compact_space α :=
{ compact_univ := set.finite_univ.is_compact }
/-- The product of two compact spaces is compact. -/
instance [compact_space α] [compact_space β] : compact_space (α × β) :=
⟨by { rw ← univ_prod_univ, exact compact_univ.prod compact_univ }⟩
/-- The disjoint union of two compact spaces is compact. -/
instance [compact_space α] [compact_space β] : compact_space (α ⊕ β) :=
⟨begin
rw ← range_inl_union_range_inr,
exact (compact_range continuous_inl).union (compact_range continuous_inr)
end⟩
section tychonoff
variables {ι : Type*} {π : ι → Type*} [∀i, topological_space (π i)]
/-- Tychonoff's theorem -/
lemma compact_pi_infinite {s : Πi:ι, set (π i)} :
(∀i, is_compact (s i)) → is_compact {x : Πi:ι, π i | ∀i, x i ∈ s i} :=
begin
simp only [compact_iff_ultrafilter_le_nhds, nhds_pi, exists_prop, mem_set_of_eq, le_infi_iff,
le_principal_iff],
intros h f hfs,
have : ∀i:ι, ∃a, a∈s i ∧ tendsto (λx:Πi:ι, π i, x i) f (𝓝 a),
{ refine λ i, h i (f.map _) (mem_map.2 _),
exact mem_sets_of_superset hfs (λ x hx, hx i) },
choose a ha,
exact ⟨a, assume i, (ha i).left, assume i, (ha i).right.le_comap⟩
end
/-- A version of Tychonoff's theorem that uses `set.pi`. -/
lemma compact_univ_pi {s : Πi:ι, set (π i)} (h : ∀i, is_compact (s i)) :
is_compact (set.pi set.univ s) :=
by { convert compact_pi_infinite h, simp only [pi, forall_prop_of_true, mem_univ] }
instance pi.compact [∀i:ι, compact_space (π i)] : compact_space (Πi, π i) :=
⟨begin
have A : is_compact {x : Πi:ι, π i | ∀i, x i ∈ (univ : set (π i))} :=
compact_pi_infinite (λi, compact_univ),
have : {x : Πi:ι, π i | ∀i, x i ∈ (univ : set (π i))} = univ := by ext; simp,
rwa this at A,
end⟩
end tychonoff
instance quot.compact_space {r : α → α → Prop} [compact_space α] :
compact_space (quot r) :=
⟨by { rw ← range_quot_mk, exact compact_range continuous_quot_mk }⟩
instance quotient.compact_space {s : setoid α} [compact_space α] :
compact_space (quotient s) :=
quot.compact_space
/-- There are various definitions of "locally compact space" in the literature, which agree for
Hausdorff spaces but not in general. This one is the precise condition on X needed for the
evaluation `map C(X, Y) × X → Y` to be continuous for all `Y` when `C(X, Y)` is given the
compact-open topology. -/
class locally_compact_space (α : Type*) [topological_space α] : Prop :=
(local_compact_nhds : ∀ (x : α) (n ∈ 𝓝 x), ∃ s ∈ 𝓝 x, s ⊆ n ∧ is_compact s)
/-- A reformulation of the definition of locally compact space: In a locally compact space,
every open set containing `x` has a compact subset containing `x` in its interior. -/
lemma exists_compact_subset [locally_compact_space α] {x : α} {U : set α}
(hU : is_open U) (hx : x ∈ U) : ∃ (K : set α), is_compact K ∧ x ∈ interior K ∧ K ⊆ U :=
begin
rcases locally_compact_space.local_compact_nhds x U _ with ⟨K, h1K, h2K, h3K⟩,
{ refine ⟨K, h3K, _, h2K⟩, rwa [ mem_interior_iff_mem_nhds] },
rwa [← mem_interior_iff_mem_nhds, hU.interior_eq]
end
lemma ultrafilter.le_nhds_Lim [compact_space α] (F : ultrafilter α) :
↑F ≤ 𝓝 (@Lim _ _ (F : filter α).nonempty_of_ne_bot F) :=
begin
rcases compact_univ.ultrafilter_le_nhds F (by simp) with ⟨x, -, h⟩,
exact le_nhds_Lim ⟨x,h⟩,
end
end compact
section clopen
/-- A set is clopen if it is both open and closed. -/
def is_clopen (s : set α) : Prop :=
is_open s ∧ is_closed s
theorem is_clopen_union {s t : set α} (hs : is_clopen s) (ht : is_clopen t) : is_clopen (s ∪ t) :=
⟨is_open_union hs.1 ht.1, is_closed_union hs.2 ht.2⟩
theorem is_clopen_inter {s t : set α} (hs : is_clopen s) (ht : is_clopen t) : is_clopen (s ∩ t) :=
⟨is_open_inter hs.1 ht.1, is_closed_inter hs.2 ht.2⟩
@[simp] theorem is_clopen_empty : is_clopen (∅ : set α) :=
⟨is_open_empty, is_closed_empty⟩
@[simp] theorem is_clopen_univ : is_clopen (univ : set α) :=
⟨is_open_univ, is_closed_univ⟩
theorem is_clopen_compl {s : set α} (hs : is_clopen s) : is_clopen sᶜ :=
⟨hs.2, is_closed_compl_iff.2 hs.1⟩
@[simp] theorem is_clopen_compl_iff {s : set α} : is_clopen sᶜ ↔ is_clopen s :=
⟨λ h, compl_compl s ▸ is_clopen_compl h, is_clopen_compl⟩
theorem is_clopen_diff {s t : set α} (hs : is_clopen s) (ht : is_clopen t) : is_clopen (s \ t) :=
is_clopen_inter hs (is_clopen_compl ht)
end clopen
section preirreducible
/-- A preirreducible set `s` is one where there is no non-trivial pair of disjoint opens on `s`. -/
def is_preirreducible (s : set α) : Prop :=
∀ (u v : set α), is_open u → is_open v →
(s ∩ u).nonempty → (s ∩ v).nonempty → (s ∩ (u ∩ v)).nonempty
/-- An irreducible set `s` is one that is nonempty and
where there is no non-trivial pair of disjoint opens on `s`. -/
def is_irreducible (s : set α) : Prop :=
s.nonempty ∧ is_preirreducible s
lemma is_irreducible.nonempty {s : set α} (h : is_irreducible s) :
s.nonempty := h.1
lemma is_irreducible.is_preirreducible {s : set α} (h : is_irreducible s) :
is_preirreducible s := h.2
theorem is_preirreducible_empty : is_preirreducible (∅ : set α) :=
λ _ _ _ _ _ ⟨x, h1, h2⟩, h1.elim
theorem is_irreducible_singleton {x} : is_irreducible ({x} : set α) :=
⟨singleton_nonempty x,
λ u v _ _ ⟨y, h1, h2⟩ ⟨z, h3, h4⟩, by rw mem_singleton_iff at h1 h3;
substs y z; exact ⟨x, rfl, h2, h4⟩⟩
theorem is_preirreducible.closure {s : set α} (H : is_preirreducible s) :
is_preirreducible (closure s) :=
λ u v hu hv ⟨y, hycs, hyu⟩ ⟨z, hzcs, hzv⟩,
let ⟨p, hpu, hps⟩ := mem_closure_iff.1 hycs u hu hyu in
let ⟨q, hqv, hqs⟩ := mem_closure_iff.1 hzcs v hv hzv in
let ⟨r, hrs, hruv⟩ := H u v hu hv ⟨p, hps, hpu⟩ ⟨q, hqs, hqv⟩ in
⟨r, subset_closure hrs, hruv⟩
lemma is_irreducible.closure {s : set α} (h : is_irreducible s) :
is_irreducible (closure s) :=
⟨h.nonempty.closure, h.is_preirreducible.closure⟩
theorem exists_preirreducible (s : set α) (H : is_preirreducible s) :
∃ t : set α, is_preirreducible t ∧ s ⊆ t ∧ ∀ u, is_preirreducible u → t ⊆ u → u = t :=
let ⟨m, hm, hsm, hmm⟩ := zorn.zorn_subset₀ {t : set α | is_preirreducible t}
(λ c hc hcc hcn, let ⟨t, htc⟩ := hcn in
⟨⋃₀ c, λ u v hu hv ⟨y, hy, hyu⟩ ⟨z, hz, hzv⟩,
let ⟨p, hpc, hyp⟩ := mem_sUnion.1 hy,
⟨q, hqc, hzq⟩ := mem_sUnion.1 hz in
or.cases_on (zorn.chain.total hcc hpc hqc)
(assume hpq : p ⊆ q, let ⟨x, hxp, hxuv⟩ := hc hqc u v hu hv
⟨y, hpq hyp, hyu⟩ ⟨z, hzq, hzv⟩ in
⟨x, mem_sUnion_of_mem hxp hqc, hxuv⟩)
(assume hqp : q ⊆ p, let ⟨x, hxp, hxuv⟩ := hc hpc u v hu hv
⟨y, hyp, hyu⟩ ⟨z, hqp hzq, hzv⟩ in
⟨x, mem_sUnion_of_mem hxp hpc, hxuv⟩),
λ x hxc, set.subset_sUnion_of_mem hxc⟩) s H in
⟨m, hm, hsm, λ u hu hmu, hmm _ hu hmu⟩
/-- A maximal irreducible set that contains a given point. -/
def irreducible_component (x : α) : set α :=
classical.some (exists_preirreducible {x} is_irreducible_singleton.is_preirreducible)
lemma irreducible_component_property (x : α) :
is_preirreducible (irreducible_component x) ∧ {x} ⊆ (irreducible_component x) ∧
∀ u, is_preirreducible u → (irreducible_component x) ⊆ u → u = (irreducible_component x) :=
classical.some_spec (exists_preirreducible {x} is_irreducible_singleton.is_preirreducible)
theorem mem_irreducible_component {x : α} : x ∈ irreducible_component x :=
singleton_subset_iff.1 (irreducible_component_property x).2.1
theorem is_irreducible_irreducible_component {x : α} : is_irreducible (irreducible_component x) :=
⟨⟨x, mem_irreducible_component⟩, (irreducible_component_property x).1⟩
theorem eq_irreducible_component {x : α} :
∀ {s : set α}, is_preirreducible s → irreducible_component x ⊆ s → s = irreducible_component x :=
(irreducible_component_property x).2.2
theorem is_closed_irreducible_component {x : α} :
is_closed (irreducible_component x) :=
closure_eq_iff_is_closed.1 $ eq_irreducible_component
is_irreducible_irreducible_component.is_preirreducible.closure
subset_closure
/-- A preirreducible space is one where there is no non-trivial pair of disjoint opens. -/
class preirreducible_space (α : Type u) [topological_space α] : Prop :=
(is_preirreducible_univ [] : is_preirreducible (univ : set α))
/-- An irreducible space is one that is nonempty
and where there is no non-trivial pair of disjoint opens. -/
class irreducible_space (α : Type u) [topological_space α] extends preirreducible_space α : Prop :=
(to_nonempty [] : nonempty α)
attribute [instance, priority 50] irreducible_space.to_nonempty -- see Note [lower instance priority]
theorem nonempty_preirreducible_inter [preirreducible_space α] {s t : set α} :
is_open s → is_open t → s.nonempty → t.nonempty → (s ∩ t).nonempty :=
by simpa only [univ_inter, univ_subset_iff] using
@preirreducible_space.is_preirreducible_univ α _ _ s t
theorem is_preirreducible.image [topological_space β] {s : set α} (H : is_preirreducible s)
(f : α → β) (hf : continuous_on f s) : is_preirreducible (f '' s) :=
begin
rintros u v hu hv ⟨_, ⟨⟨x, hx, rfl⟩, hxu⟩⟩ ⟨_, ⟨⟨y, hy, rfl⟩, hyv⟩⟩,
rw ← set.mem_preimage at hxu hyv,
rcases continuous_on_iff'.1 hf u hu with ⟨u', hu', u'_eq⟩,
rcases continuous_on_iff'.1 hf v hv with ⟨v', hv', v'_eq⟩,
have := H u' v' hu' hv',
rw [set.inter_comm s u', ← u'_eq] at this,
rw [set.inter_comm s v', ← v'_eq] at this,
rcases this ⟨x, hxu, hx⟩ ⟨y, hyv, hy⟩ with ⟨z, hzs, hzu', hzv'⟩,
refine ⟨f z, mem_image_of_mem f hzs, _, _⟩,
all_goals
{ rw ← set.mem_preimage,
apply set.mem_of_mem_inter_left,
show z ∈ _ ∩ s,
simp [*] }
end
theorem is_irreducible.image [topological_space β] {s : set α} (H : is_irreducible s)
(f : α → β) (hf : continuous_on f s) : is_irreducible (f '' s) :=
⟨nonempty_image_iff.mpr H.nonempty, H.is_preirreducible.image f hf⟩
lemma subtype.preirreducible_space {s : set α} (h : is_preirreducible s) :
preirreducible_space s :=
{ is_preirreducible_univ :=
begin
intros u v hu hv hsu hsv,
rw is_open_induced_iff at hu hv,
rcases hu with ⟨u, hu, rfl⟩,
rcases hv with ⟨v, hv, rfl⟩,
rcases hsu with ⟨⟨x, hxs⟩, hxs', hxu⟩,
rcases hsv with ⟨⟨y, hys⟩, hys', hyv⟩,
rcases h u v hu hv ⟨x, hxs, hxu⟩ ⟨y, hys, hyv⟩ with ⟨z, hzs, ⟨hzu, hzv⟩⟩,
exact ⟨⟨z, hzs⟩, ⟨set.mem_univ _, ⟨hzu, hzv⟩⟩⟩
end }
lemma subtype.irreducible_space {s : set α} (h : is_irreducible s) :
irreducible_space s :=
{ is_preirreducible_univ :=
(subtype.preirreducible_space h.is_preirreducible).is_preirreducible_univ,
to_nonempty := h.nonempty.to_subtype }
/-- A set `s` is irreducible if and only if
for every finite collection of open sets all of whose members intersect `s`,
`s` also intersects the intersection of the entire collection
(i.e., there is an element of `s` contained in every member of the collection). -/
lemma is_irreducible_iff_sInter {s : set α} :
is_irreducible s ↔
∀ (U : finset (set α)) (hU : ∀ u ∈ U, is_open u) (H : ∀ u ∈ U, (s ∩ u).nonempty),
(s ∩ ⋂₀ ↑U).nonempty :=
begin
split; intro h,
{ intro U, apply finset.induction_on U,
{ intros, simpa using h.nonempty },
{ intros u U hu IH hU H,
rw [finset.coe_insert, sInter_insert],
apply h.2,
{ solve_by_elim [finset.mem_insert_self] },
{ apply is_open_sInter (finset.finite_to_set U),
intros, solve_by_elim [finset.mem_insert_of_mem] },
{ solve_by_elim [finset.mem_insert_self] },
{ apply IH,
all_goals { intros, solve_by_elim [finset.mem_insert_of_mem] } } } },
{ split,
{ simpa using h ∅ _ _; intro u; simp },
intros u v hu hv hu' hv',
simpa using h {u,v} _ _,
all_goals
{ intro t,
rw [finset.mem_insert, finset.mem_singleton],
rintro (rfl|rfl); assumption } }
end
/-- A set is preirreducible if and only if
for every cover by two closed sets, it is contained in one of the two covering sets. -/
lemma is_preirreducible_iff_closed_union_closed {s : set α} :
is_preirreducible s ↔
∀ (z₁ z₂ : set α), is_closed z₁ → is_closed z₂ → s ⊆ z₁ ∪ z₂ → s ⊆ z₁ ∨ s ⊆ z₂ :=
begin
split,
all_goals
{ intros h t₁ t₂ ht₁ ht₂,
specialize h t₁ᶜ t₂ᶜ,
simp only [is_open_compl_iff, is_closed_compl_iff] at h,
specialize h ht₁ ht₂ },
{ contrapose!, simp only [not_subset],
rintro ⟨⟨x, hx, hx'⟩, ⟨y, hy, hy'⟩⟩,
rcases h ⟨x, hx, hx'⟩ ⟨y, hy, hy'⟩ with ⟨z, hz, hz'⟩,
rw ← compl_union at hz',
exact ⟨z, hz, hz'⟩ },
{ rintro ⟨x, hx, hx'⟩ ⟨y, hy, hy'⟩,
rw ← compl_inter at h,
delta set.nonempty,
rw imp_iff_not_or at h,
contrapose! h,
split,
{ intros z hz hz', exact h z ⟨hz, hz'⟩ },
{ split; intro H; refine H _ ‹_›; assumption } }
end
/-- A set is irreducible if and only if
for every cover by a finite collection of closed sets,
it is contained in one of the members of the collection. -/
lemma is_irreducible_iff_sUnion_closed {s : set α} :
is_irreducible s ↔
∀ (Z : finset (set α)) (hZ : ∀ z ∈ Z, is_closed z) (H : s ⊆ ⋃₀ ↑Z),
∃ z ∈ Z, s ⊆ z :=
begin
rw [is_irreducible, is_preirreducible_iff_closed_union_closed],
split; intro h,
{ intro Z, apply finset.induction_on Z,
{ intros, rw [finset.coe_empty, sUnion_empty] at H,
rcases h.1 with ⟨x, hx⟩,
exfalso, tauto },
{ intros z Z hz IH hZ H,
cases h.2 z (⋃₀ ↑Z) _ _ _
with h' h',
{ exact ⟨z, finset.mem_insert_self _ _, h'⟩ },
{ rcases IH _ h' with ⟨z', hz', hsz'⟩,
{ exact ⟨z', finset.mem_insert_of_mem hz', hsz'⟩ },
{ intros, solve_by_elim [finset.mem_insert_of_mem] } },
{ solve_by_elim [finset.mem_insert_self] },
{ rw sUnion_eq_bUnion,
apply is_closed_bUnion (finset.finite_to_set Z),
{ intros, solve_by_elim [finset.mem_insert_of_mem] } },
{ simpa using H } } },
{ split,
{ by_contradiction hs,
simpa using h ∅ _ _,
{ intro z, simp },
{ simpa [set.nonempty] using hs } },
intros z₁ z₂ hz₁ hz₂ H,
have := h {z₁, z₂} _ _,
simp only [exists_prop, finset.mem_insert, finset.mem_singleton] at this,
{ rcases this with ⟨z, rfl|rfl, hz⟩; tauto },
{ intro t,
rw [finset.mem_insert, finset.mem_singleton],
rintro (rfl|rfl); assumption },
{ simpa using H } }
end
end preirreducible
section preconnected
/-- A preconnected set is one where there is no non-trivial open partition. -/
def is_preconnected (s : set α) : Prop :=
∀ (u v : set α), is_open u → is_open v → s ⊆ u ∪ v →
(s ∩ u).nonempty → (s ∩ v).nonempty → (s ∩ (u ∩ v)).nonempty
/-- A connected set is one that is nonempty and where there is no non-trivial open partition. -/
def is_connected (s : set α) : Prop :=
s.nonempty ∧ is_preconnected s
lemma is_connected.nonempty {s : set α} (h : is_connected s) :
s.nonempty := h.1
lemma is_connected.is_preconnected {s : set α} (h : is_connected s) :
is_preconnected s := h.2
theorem is_preirreducible.is_preconnected {s : set α} (H : is_preirreducible s) :
is_preconnected s :=
λ _ _ hu hv _, H _ _ hu hv
theorem is_irreducible.is_connected {s : set α} (H : is_irreducible s) : is_connected s :=
⟨H.nonempty, H.is_preirreducible.is_preconnected⟩
theorem is_preconnected_empty : is_preconnected (∅ : set α) :=
is_preirreducible_empty.is_preconnected
theorem is_connected_singleton {x} : is_connected ({x} : set α) :=
is_irreducible_singleton.is_connected
/-- If any point of a set is joined to a fixed point by a preconnected subset,
then the original set is preconnected as well. -/
theorem is_preconnected_of_forall {s : set α} (x : α)
(H : ∀ y ∈ s, ∃ t ⊆ s, x ∈ t ∧ y ∈ t ∧ is_preconnected t) :
is_preconnected s :=
begin
rintros u v hu hv hs ⟨z, zs, zu⟩ ⟨y, ys, yv⟩,
have xs : x ∈ s, by { rcases H y ys with ⟨t, ts, xt, yt, ht⟩, exact ts xt },
wlog xu : x ∈ u := hs xs using [u v y z, v u z y],
rcases H y ys with ⟨t, ts, xt, yt, ht⟩,
have := ht u v hu hv(subset.trans ts hs) ⟨x, xt, xu⟩ ⟨y, yt, yv⟩,
exact this.imp (λ z hz, ⟨ts hz.1, hz.2⟩)
end
/-- If any two points of a set are contained in a preconnected subset,
then the original set is preconnected as well. -/
theorem is_preconnected_of_forall_pair {s : set α}
(H : ∀ x y ∈ s, ∃ t ⊆ s, x ∈ t ∧ y ∈ t ∧ is_preconnected t) :
is_preconnected s :=
begin
rintros u v hu hv hs ⟨x, xs, xu⟩ ⟨y, ys, yv⟩,
rcases H x y xs ys with ⟨t, ts, xt, yt, ht⟩,
have := ht u v hu hv(subset.trans ts hs) ⟨x, xt, xu⟩ ⟨y, yt, yv⟩,
exact this.imp (λ z hz, ⟨ts hz.1, hz.2⟩)
end
/-- A union of a family of preconnected sets with a common point is preconnected as well. -/
theorem is_preconnected_sUnion (x : α) (c : set (set α)) (H1 : ∀ s ∈ c, x ∈ s)
(H2 : ∀ s ∈ c, is_preconnected s) : is_preconnected (⋃₀ c) :=
begin
apply is_preconnected_of_forall x,
rintros y ⟨s, sc, ys⟩,
exact ⟨s, subset_sUnion_of_mem sc, H1 s sc, ys, H2 s sc⟩
end
theorem is_preconnected.union (x : α) {s t : set α} (H1 : x ∈ s) (H2 : x ∈ t)
(H3 : is_preconnected s) (H4 : is_preconnected t) : is_preconnected (s ∪ t) :=
sUnion_pair s t ▸ is_preconnected_sUnion x {s, t}
(by rintro r (rfl | rfl | h); assumption)
(by rintro r (rfl | rfl | h); assumption)
theorem is_connected.union {s t : set α} (H : (s ∩ t).nonempty)
(Hs : is_connected s) (Ht : is_connected t) : is_connected (s ∪ t) :=
begin
rcases H with ⟨x, hx⟩,
refine ⟨⟨x, mem_union_left t (mem_of_mem_inter_left hx)⟩, _⟩,
exact is_preconnected.union x (mem_of_mem_inter_left hx) (mem_of_mem_inter_right hx)
Hs.is_preconnected Ht.is_preconnected
end
theorem is_preconnected.closure {s : set α} (H : is_preconnected s) :
is_preconnected (closure s) :=
λ u v hu hv hcsuv ⟨y, hycs, hyu⟩ ⟨z, hzcs, hzv⟩,
let ⟨p, hpu, hps⟩ := mem_closure_iff.1 hycs u hu hyu in
let ⟨q, hqv, hqs⟩ := mem_closure_iff.1 hzcs v hv hzv in
let ⟨r, hrs, hruv⟩ := H u v hu hv (subset.trans subset_closure hcsuv) ⟨p, hps, hpu⟩ ⟨q, hqs, hqv⟩ in
⟨r, subset_closure hrs, hruv⟩
theorem is_connected.closure {s : set α} (H : is_connected s) :
is_connected (closure s) :=
⟨H.nonempty.closure, H.is_preconnected.closure⟩
theorem is_preconnected.image [topological_space β] {s : set α} (H : is_preconnected s)
(f : α → β) (hf : continuous_on f s) : is_preconnected (f '' s) :=
begin
-- Unfold/destruct definitions in hypotheses
rintros u v hu hv huv ⟨_, ⟨x, xs, rfl⟩, xu⟩ ⟨_, ⟨y, ys, rfl⟩, yv⟩,
rcases continuous_on_iff'.1 hf u hu with ⟨u', hu', u'_eq⟩,
rcases continuous_on_iff'.1 hf v hv with ⟨v', hv', v'_eq⟩,
-- Reformulate `huv : f '' s ⊆ u ∪ v` in terms of `u'` and `v'`
replace huv : s ⊆ u' ∪ v',
{ rw [image_subset_iff, preimage_union] at huv,
replace huv := subset_inter huv (subset.refl _),
rw [inter_distrib_right, u'_eq, v'_eq, ← inter_distrib_right] at huv,
exact (subset_inter_iff.1 huv).1 },
-- Now `s ⊆ u' ∪ v'`, so we can apply `‹is_preconnected s›`
obtain ⟨z, hz⟩ : (s ∩ (u' ∩ v')).nonempty,
{ refine H u' v' hu' hv' huv ⟨x, _⟩ ⟨y, _⟩; rw inter_comm,
exacts [u'_eq ▸ ⟨xu, xs⟩, v'_eq ▸ ⟨yv, ys⟩] },
rw [← inter_self s, inter_assoc, inter_left_comm s u', ← inter_assoc,
inter_comm s, inter_comm s, ← u'_eq, ← v'_eq] at hz,
exact ⟨f z, ⟨z, hz.1.2, rfl⟩, hz.1.1, hz.2.1⟩
end
theorem is_connected.image [topological_space β] {s : set α} (H : is_connected s)
(f : α → β) (hf : continuous_on f s) : is_connected (f '' s) :=
⟨nonempty_image_iff.mpr H.nonempty, H.is_preconnected.image f hf⟩
theorem is_preconnected_closed_iff {s : set α} :
is_preconnected s ↔ ∀ t t', is_closed t → is_closed t' → s ⊆ t ∪ t' →
(s ∩ t).nonempty → (s ∩ t').nonempty → (s ∩ (t ∩ t')).nonempty :=
⟨begin
rintros h t t' ht ht' htt' ⟨x, xs, xt⟩ ⟨y, ys, yt'⟩,
by_contradiction h',
rw [← ne_empty_iff_nonempty, ne.def, not_not, ← subset_compl_iff_disjoint, compl_inter] at h',
have xt' : x ∉ t', from (h' xs).elim (absurd xt) id,
have yt : y ∉ t, from (h' ys).elim id (absurd yt'),
have := ne_empty_iff_nonempty.2 (h tᶜ t'ᶜ (is_open_compl_iff.2 ht)
(is_open_compl_iff.2 ht') h' ⟨y, ys, yt⟩ ⟨x, xs, xt'⟩),
rw [ne.def, ← compl_union, ← subset_compl_iff_disjoint, compl_compl] at this,
contradiction
end,
begin
rintros h u v hu hv huv ⟨x, xs, xu⟩ ⟨y, ys, yv⟩,
by_contradiction h',
rw [← ne_empty_iff_nonempty, ne.def, not_not,
← subset_compl_iff_disjoint, compl_inter] at h',
have xv : x ∉ v, from (h' xs).elim (absurd xu) id,
have yu : y ∉ u, from (h' ys).elim id (absurd yv),
have := ne_empty_iff_nonempty.2 (h uᶜ vᶜ (is_closed_compl_iff.2 hu)
(is_closed_compl_iff.2 hv) h' ⟨y, ys, yu⟩ ⟨x, xs, xv⟩),
rw [ne.def, ← compl_union, ← subset_compl_iff_disjoint, compl_compl] at this,
contradiction
end⟩
/-- The connected component of a point is the maximal connected set
that contains this point. -/
def connected_component (x : α) : set α :=
⋃₀ { s : set α | is_preconnected s ∧ x ∈ s }
/-- The connected component of a point inside a set. -/
def connected_component_in (F : set α) (x : F) : set α := coe '' (connected_component x)
theorem mem_connected_component {x : α} : x ∈ connected_component x :=
mem_sUnion_of_mem (mem_singleton x) ⟨is_connected_singleton.is_preconnected, mem_singleton x⟩
theorem is_connected_connected_component {x : α} : is_connected (connected_component x) :=
⟨⟨x, mem_connected_component⟩, is_preconnected_sUnion x _ (λ _, and.right) (λ _, and.left)⟩
theorem subset_connected_component {x : α} {s : set α} (H1 : is_preconnected s) (H2 : x ∈ s) :
s ⊆ connected_component x :=
λ z hz, mem_sUnion_of_mem hz ⟨H1, H2⟩
theorem is_closed_connected_component {x : α} :
is_closed (connected_component x) :=
closure_eq_iff_is_closed.1 $ subset.antisymm
(subset_connected_component
is_connected_connected_component.closure.is_preconnected
(subset_closure mem_connected_component))
subset_closure
theorem irreducible_component_subset_connected_component {x : α} :
irreducible_component x ⊆ connected_component x :=
subset_connected_component
is_irreducible_irreducible_component.is_connected.is_preconnected
mem_irreducible_component
/-- A preconnected space is one where there is no non-trivial open partition. -/
class preconnected_space (α : Type u) [topological_space α] : Prop :=
(is_preconnected_univ : is_preconnected (univ : set α))
export preconnected_space (is_preconnected_univ)
/-- A connected space is a nonempty one where there is no non-trivial open partition. -/
class connected_space (α : Type u) [topological_space α] extends preconnected_space α : Prop :=
(to_nonempty : nonempty α)
attribute [instance, priority 50] connected_space.to_nonempty -- see Note [lower instance priority]
lemma is_connected_range [topological_space β] [connected_space α] {f : α → β} (h : continuous f) :
is_connected (range f) :=
begin
inhabit α,
rw ← image_univ,
exact ⟨⟨f (default α), mem_image_of_mem _ (mem_univ _)⟩,
is_preconnected.image is_preconnected_univ _ h.continuous_on⟩
end
lemma connected_space_iff_connected_component :
connected_space α ↔ ∃ x : α, connected_component x = univ :=
begin
split,
{ rintros ⟨h, ⟨x⟩⟩,
exactI ⟨x, eq_univ_of_univ_subset $ subset_connected_component is_preconnected_univ (mem_univ x)⟩ },
{ rintros ⟨x, h⟩,
haveI : preconnected_space α := ⟨by {rw ← h, exact is_connected_connected_component.2 }⟩,
exact ⟨⟨x⟩⟩ }
end
@[priority 100] -- see Note [lower instance priority]
instance preirreducible_space.preconnected_space (α : Type u) [topological_space α]
[preirreducible_space α] : preconnected_space α :=
⟨(preirreducible_space.is_preirreducible_univ α).is_preconnected⟩
@[priority 100] -- see Note [lower instance priority]
instance irreducible_space.connected_space (α : Type u) [topological_space α]
[irreducible_space α] : connected_space α :=
{ to_nonempty := irreducible_space.to_nonempty α }
theorem nonempty_inter [preconnected_space α] {s t : set α} :
is_open s → is_open t → s ∪ t = univ → s.nonempty → t.nonempty → (s ∩ t).nonempty :=
by simpa only [univ_inter, univ_subset_iff] using
@preconnected_space.is_preconnected_univ α _ _ s t
theorem is_clopen_iff [preconnected_space α] {s : set α} : is_clopen s ↔ s = ∅ ∨ s = univ :=
⟨λ hs, classical.by_contradiction $ λ h,
have h1 : s ≠ ∅ ∧ sᶜ ≠ ∅, from ⟨mt or.inl h,
mt (λ h2, or.inr $ (by rw [← compl_compl s, h2, compl_empty] : s = univ)) h⟩,
let ⟨_, h2, h3⟩ := nonempty_inter hs.1 hs.2 (union_compl_self s)
(ne_empty_iff_nonempty.1 h1.1) (ne_empty_iff_nonempty.1 h1.2) in
h3 h2,
by rintro (rfl | rfl); [exact is_clopen_empty, exact is_clopen_univ]⟩
lemma eq_univ_of_nonempty_clopen [preconnected_space α] {s : set α}
(h : s.nonempty) (h' : is_clopen s) : s = univ :=
by { rw is_clopen_iff at h', finish [h.ne_empty] }
lemma subtype.preconnected_space {s : set α} (h : is_preconnected s) :
preconnected_space s :=
{ is_preconnected_univ :=
begin
intros u v hu hv hs hsu hsv,
rw is_open_induced_iff at hu hv,
rcases hu with ⟨u, hu, rfl⟩,
rcases hv with ⟨v, hv, rfl⟩,
rcases hsu with ⟨⟨x, hxs⟩, hxs', hxu⟩,
rcases hsv with ⟨⟨y, hys⟩, hys', hyv⟩,
rcases h u v hu hv _ ⟨x, hxs, hxu⟩ ⟨y, hys, hyv⟩ with ⟨z, hzs, ⟨hzu, hzv⟩⟩,
exact ⟨⟨z, hzs⟩, ⟨set.mem_univ _, ⟨hzu, hzv⟩⟩⟩,
intros z hz,
rcases hs (set.mem_univ ⟨z, hz⟩) with hzu|hzv,
{ left, assumption },
{ right, assumption }
end }
lemma subtype.connected_space {s : set α} (h : is_connected s) :
connected_space s :=
{ is_preconnected_univ :=
(subtype.preconnected_space h.is_preconnected).is_preconnected_univ,
to_nonempty := h.nonempty.to_subtype }
lemma is_preconnected_iff_preconnected_space {s : set α} :
is_preconnected s ↔ preconnected_space s :=
⟨subtype.preconnected_space,
begin
introI,
simpa using is_preconnected_univ.image (coe : s → α) continuous_subtype_coe.continuous_on
end⟩
lemma is_connected_iff_connected_space {s : set α} : is_connected s ↔ connected_space s :=
⟨subtype.connected_space,
λ h, ⟨nonempty_subtype.mp h.2, is_preconnected_iff_preconnected_space.mpr h.1⟩⟩
/-- A set `s` is preconnected if and only if
for every cover by two open sets that are disjoint on `s`,
it is contained in one of the two covering sets. -/
lemma is_preconnected_iff_subset_of_disjoint {s : set α} :
is_preconnected s ↔
∀ (u v : set α) (hu : is_open u) (hv : is_open v) (hs : s ⊆ u ∪ v) (huv : s ∩ (u ∩ v) = ∅),
s ⊆ u ∨ s ⊆ v :=
begin
split; intro h,
{ intros u v hu hv hs huv,
specialize h u v hu hv hs,
contrapose! huv,
rw ne_empty_iff_nonempty,
simp [not_subset] at huv,
rcases huv with ⟨⟨x, hxs, hxu⟩, ⟨y, hys, hyv⟩⟩,
have hxv : x ∈ v := or_iff_not_imp_left.mp (hs hxs) hxu,
have hyu : y ∈ u := or_iff_not_imp_right.mp (hs hys) hyv,
exact h ⟨y, hys, hyu⟩ ⟨x, hxs, hxv⟩ },
{ intros u v hu hv hs hsu hsv,
rw ← ne_empty_iff_nonempty,
intro H,
specialize h u v hu hv hs H,
contrapose H,
apply ne_empty_iff_nonempty.mpr,
cases h,
{ rcases hsv with ⟨x, hxs, hxv⟩, exact ⟨x, hxs, ⟨h hxs, hxv⟩⟩ },
{ rcases hsu with ⟨x, hxs, hxu⟩, exact ⟨x, hxs, ⟨hxu, h hxs⟩⟩ } }
end
/-- A set `s` is connected if and only if
for every cover by a finite collection of open sets that are pairwise disjoint on `s`,
it is contained in one of the members of the collection. -/
lemma is_connected_iff_sUnion_disjoint_open {s : set α} :
is_connected s ↔
∀ (U : finset (set α)) (H : ∀ (u v : set α), u ∈ U → v ∈ U → (s ∩ (u ∩ v)).nonempty → u = v)
(hU : ∀ u ∈ U, is_open u) (hs : s ⊆ ⋃₀ ↑U),
∃ u ∈ U, s ⊆ u :=
begin
rw [is_connected, is_preconnected_iff_subset_of_disjoint],
split; intro h,
{ intro U, apply finset.induction_on U,
{ rcases h.left,
suffices : s ⊆ ∅ → false, { simpa },
intro, solve_by_elim },
{ intros u U hu IH hs hU H,
rw [finset.coe_insert, sUnion_insert] at H,
cases h.2 u (⋃₀ ↑U) _ _ H _ with hsu hsU,
{ exact ⟨u, finset.mem_insert_self _ _, hsu⟩ },
{ rcases IH _ _ hsU with ⟨v, hvU, hsv⟩,
{ exact ⟨v, finset.mem_insert_of_mem hvU, hsv⟩ },
{ intros, apply hs; solve_by_elim [finset.mem_insert_of_mem] },
{ intros, solve_by_elim [finset.mem_insert_of_mem] } },
{ solve_by_elim [finset.mem_insert_self] },
{ apply is_open_sUnion,
intros, solve_by_elim [finset.mem_insert_of_mem] },
{ apply eq_empty_of_subset_empty,
rintro x ⟨hxs, hxu, hxU⟩,
rw mem_sUnion at hxU,
rcases hxU with ⟨v, hvU, hxv⟩,
rcases hs u v (finset.mem_insert_self _ _) (finset.mem_insert_of_mem hvU) _ with rfl,
{ contradiction },
{ exact ⟨x, hxs, hxu, hxv⟩ } } } },
{ split,
{ rw ← ne_empty_iff_nonempty,
by_contradiction hs, push_neg at hs, subst hs,
simpa using h ∅ _ _ _; simp },
intros u v hu hv hs hsuv,
rcases h {u, v} _ _ _ with ⟨t, ht, ht'⟩,
{ rw [finset.mem_insert, finset.mem_singleton] at ht,
rcases ht with rfl|rfl; tauto },
{ intros t₁ t₂ ht₁ ht₂ hst,
rw ← ne_empty_iff_nonempty at hst,
rw [finset.mem_insert, finset.mem_singleton] at ht₁ ht₂,
rcases ht₁ with rfl|rfl; rcases ht₂ with rfl|rfl,
all_goals { refl <|> contradiction <|> skip },
rw inter_comm t₁ at hst, contradiction },
{ intro t,
rw [finset.mem_insert, finset.mem_singleton],
rintro (rfl|rfl); assumption },
{ simpa using hs } }
end
end preconnected
section totally_disconnected
/-- A set is called totally disconnected if all of its connected components are singletons. -/
def is_totally_disconnected (s : set α) : Prop :=
∀ t, t ⊆ s → is_preconnected t → subsingleton t
theorem is_totally_disconnected_empty : is_totally_disconnected (∅ : set α) :=
λ t ht _, ⟨λ ⟨_, h⟩, (ht h).elim⟩
theorem is_totally_disconnected_singleton {x} : is_totally_disconnected ({x} : set α) :=
λ t ht _, ⟨λ ⟨p, hp⟩ ⟨q, hq⟩, subtype.eq $ show p = q,
from (eq_of_mem_singleton (ht hp)).symm ▸ (eq_of_mem_singleton (ht hq)).symm⟩
/-- A space is totally disconnected if all of its connected components are singletons. -/
class totally_disconnected_space (α : Type u) [topological_space α] : Prop :=
(is_totally_disconnected_univ : is_totally_disconnected (univ : set α))
end totally_disconnected
section totally_separated
/-- A set `s` is called totally separated if any two points of this set can be separated
by two disjoint open sets covering `s`. -/
def is_totally_separated (s : set α) : Prop :=
∀ x ∈ s, ∀ y ∈ s, x ≠ y → ∃ u v : set α, is_open u ∧ is_open v ∧
x ∈ u ∧ y ∈ v ∧ s ⊆ u ∪ v ∧ u ∩ v = ∅
theorem is_totally_separated_empty : is_totally_separated (∅ : set α) :=
λ x, false.elim
theorem is_totally_separated_singleton {x} : is_totally_separated ({x} : set α) :=
λ p hp q hq hpq, (hpq $ (eq_of_mem_singleton hp).symm ▸ (eq_of_mem_singleton hq).symm).elim
theorem is_totally_disconnected_of_is_totally_separated {s : set α}
(H : is_totally_separated s) : is_totally_disconnected s :=
λ t hts ht, ⟨λ ⟨x, hxt⟩ ⟨y, hyt⟩, subtype.eq $ classical.by_contradiction $
assume hxy : x ≠ y, let ⟨u, v, hu, hv, hxu, hyv, hsuv, huv⟩ := H x (hts hxt) y (hts hyt) hxy in
let ⟨r, hrt, hruv⟩ := ht u v hu hv (subset.trans hts hsuv) ⟨x, hxt, hxu⟩ ⟨y, hyt, hyv⟩ in
(ext_iff.1 huv r).1 hruv⟩
/-- A space is totally separated if any two points can be separated by two disjoint open sets
covering the whole space. -/
class totally_separated_space (α : Type u) [topological_space α] : Prop :=
(is_totally_separated_univ [] : is_totally_separated (univ : set α))
@[priority 100] -- see Note [lower instance priority]
instance totally_separated_space.totally_disconnected_space (α : Type u) [topological_space α]
[totally_separated_space α] : totally_disconnected_space α :=
⟨is_totally_disconnected_of_is_totally_separated $
totally_separated_space.is_totally_separated_univ α⟩
@[priority 100] -- see Note [lower instance priority]
instance totally_separated_space.of_discrete
(α : Type*) [topological_space α] [discrete_topology α] : totally_separated_space α :=
⟨λ a _ b _ h, ⟨{b}ᶜ, {b}, is_open_discrete _, is_open_discrete _, by simpa⟩⟩
end totally_separated
|
44aa3a1a77d584cb593ae727fee15fbfc2ab1d00 | d9d511f37a523cd7659d6f573f990e2a0af93c6f | /src/analysis/convex/independent.lean | 796737008d762a430e2fc2a73c823686f12dd309 | [
"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 | 8,538 | lean | /-
Copyright (c) 2021 Yaël Dillies, Bhavik Mehta. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Yaël Dillies, Bhavik Mehta
-/
import analysis.convex.caratheodory
import analysis.convex.extreme
import linear_algebra.affine_space.independent
/-!
# Convex independence
This file defines convex independent families of points.
Convex independence is closely related to affine independence. In both cases, no point can be
written as a combination of others. When the combination is affine (that is, any coefficients), this
yields affine independence. When the combination is convex (that is, all coefficients are
nonnegative), then this yields convex independence. In particular, affine independence implies
convex independence.
## Main declarations
* `convex_independent p`: Convex independence of the indexed family `p : ι → E`. Every point of the
family only belongs to convex hulls of sets of the family containing it.
* `convex_independent_iff_finset`: Carathéodory's theorem allows us to only check finsets to
conclude convex independence.
* `convex.extreme_points_convex_independent`: Extreme points of a convex set are convex independent.
## References
* https://en.wikipedia.org/wiki/Convex_position
## TODO
Once convexity is generalised to vector spaces, `convex_independent` will take as first parameter
the semiring of scalars, so that `convex_independent p` becomes `convex_independent 𝕜 p`, mimicking
`affine_independent 𝕜 p`. Our current definition would then correspond to `convex_independent ℝ p`.
Prove `affine_independent.convex_independent`. This requires some glue between `affine_combination`
and `finset.center_mass`.
## Tags
independence, convex position
-/
open_locale affine big_operators classical
open finset function
variables {E : Type*} [add_comm_group E] [module ℝ E]
{ι : Type*} {s t : set E}
/-- An indexed family is said to be convex independent if every point only belongs to convex hulls
of sets containing it. -/
def convex_independent (p : ι → E) : Prop :=
∀ (s : set ι) (x : ι), p x ∈ convex_hull (p '' s) → x ∈ s
/-- To check convex independence, one only has to check finsets thanks to Carathéodory's theorem. -/
lemma convex_independent_iff_finset {p : ι → E} :
convex_independent p ↔ ∀ (s : finset ι) (x : ι), p x ∈ convex_hull (s.image p : set E) → x ∈ s :=
begin
refine ⟨λ hc s x hx, hc s x _, λ h s x hx, _⟩,
{ rwa finset.coe_image at hx },
have hp : injective p,
{ rintro a b hab,
rw ←mem_singleton,
refine h {b} a _,
rw [hab, image_singleton, coe_singleton, convex_hull_singleton],
exact set.mem_singleton _ },
let s' : finset ι :=
(caratheodory.min_card_finset_of_mem_convex_hull hx).preimage p (hp.inj_on _),
suffices hs' : x ∈ s',
{ rw ←hp.mem_set_image,
rw [finset.mem_preimage, ←mem_coe] at hs',
exact caratheodory.min_card_finset_of_mem_convex_hull_subseteq hx hs' },
refine h s' x _,
have : s'.image p = caratheodory.min_card_finset_of_mem_convex_hull hx,
{ rw [image_preimage, filter_true_of_mem],
exact λ y hy, set.image_subset_range _ s
(caratheodory.min_card_finset_of_mem_convex_hull_subseteq hx $ mem_coe.2 hy) },
rw this,
exact caratheodory.mem_min_card_finset_of_mem_convex_hull hx,
end
/-- A family with at most one point is convex independent. -/
lemma subsingleton.convex_independent [subsingleton ι] (p : ι → E) :
convex_independent p :=
λ s x hx, begin
have : (convex_hull (p '' s)).nonempty := ⟨p x, hx⟩,
rw [convex_hull_nonempty_iff, set.nonempty_image_iff] at this,
rwa subsingleton.mem_iff_nonempty,
end
/-- A convex independent family is injective. -/
protected lemma convex_independent.injective {p : ι → E} (hc : convex_independent p) :
function.injective p :=
begin
refine λ i j hij, hc {j} i _,
rw [hij, set.image_singleton, convex_hull_singleton],
exact set.mem_singleton _,
end
/-- If a family is convex independent, so is any subfamily given by composition of an embedding into
index type with the original family. -/
lemma convex_independent.comp_embedding {ι' : Type*} (f : ι' ↪ ι) {p : ι → E}
(hc : convex_independent p) :
convex_independent (p ∘ f) :=
begin
intros s x hx,
rw ←f.injective.mem_set_image,
exact hc _ _ (by rwa set.image_image),
end
/-- If a family is convex independent, so is any subfamily indexed by a subtype of the index type.
-/
protected lemma convex_independent.subtype {p : ι → E} (hc : convex_independent p) (s : set ι) :
convex_independent (λ i : s, p i) :=
hc.comp_embedding (embedding.subtype _)
/-- If an indexed family of points is convex independent, so is the corresponding set of points. -/
protected lemma convex_independent.range {p : ι → E} (hc : convex_independent p) :
convex_independent (λ x, x : set.range p → E) :=
begin
let f : set.range p → ι := λ x, x.property.some,
have hf : ∀ x, p (f x) = x := λ x, x.property.some_spec,
let fe : set.range p ↪ ι := ⟨f, λ x₁ x₂ he, subtype.ext (hf x₁ ▸ hf x₂ ▸ he ▸ rfl)⟩,
convert hc.comp_embedding fe,
ext,
rw [embedding.coe_fn_mk, comp_app, hf],
end
/-- A subset of a convex independent set of points is convex independent as well. -/
protected lemma convex_independent.mono {s t : set E} (hc : convex_independent (λ x, x : t → E))
(hs : s ⊆ t) :
convex_independent (λ x, x : s → E) :=
hc.comp_embedding (s.embedding_of_subset t hs)
/-- The range of an injective indexed family of points is convex independent iff that family is. -/
lemma function.injective.convex_independent_iff_set {p : ι → E}
(hi : function.injective p) :
convex_independent (λ x, x : set.range p → E) ↔ convex_independent p :=
⟨λ hc, hc.comp_embedding
(⟨λ i, ⟨p i, set.mem_range_self _⟩, λ x y h, hi (subtype.mk_eq_mk.1 h)⟩ : ι ↪ set.range p),
convex_independent.range⟩
/-- If a family is convex independent, a point in the family is in the convex hull of some of the
points given by a subset of the index type if and only if the point's index is in this subset. -/
@[simp] protected lemma convex_independent.mem_convex_hull_iff {p : ι → E}
(hc : convex_independent p) (s : set ι) (i : ι) :
p i ∈ convex_hull (p '' s) ↔ i ∈ s :=
⟨hc _ _, λ hi, subset_convex_hull _ (set.mem_image_of_mem p hi)⟩
/-- If a family is convex independent, a point in the family is not in the convex hull of the other
points. See `convex_independent_set_iff_not_mem_convex_hull_diff` for the `set` version. -/
lemma convex_independent_iff_not_mem_convex_hull_diff {p : ι → E} :
convex_independent p ↔ ∀ i s, p i ∉ convex_hull (p '' (s \ {i})) :=
begin
refine ⟨λ hc i s h, _, λ h s i hi, _⟩,
{ rw hc.mem_convex_hull_iff at h,
exact h.2 (set.mem_singleton _) },
{ by_contra H,
refine h i s _,
rw set.diff_singleton_eq_self H,
exact hi }
end
lemma convex_independent_set_iff_inter_convex_hull_subset {s : set E} :
convex_independent (λ x, x : s → E) ↔ ∀ t, t ⊆ s → s ∩ convex_hull t ⊆ t :=
begin
split,
{ rintro hc t h x ⟨hxs, hxt⟩,
refine hc {x | ↑x ∈ t} ⟨x, hxs⟩ _,
rw subtype.coe_image_of_subset h,
exact hxt },
{ intros hc t x h,
rw ←subtype.coe_injective.mem_set_image,
exact hc (t.image coe) (subtype.coe_image_subset s t) ⟨x.prop, h⟩ }
end
/-- If a set is convex independent, a point in the set is not in the convex hull of the other
points. See `convex_independent_iff_not_mem_convex_hull_diff` for the indexed family version. -/
lemma convex_independent_set_iff_not_mem_convex_hull_diff {s : set E} :
convex_independent (λ x, x : s → E) ↔ ∀ x ∈ s, x ∉ convex_hull (s \ {x}) :=
begin
rw convex_independent_set_iff_inter_convex_hull_subset,
split,
{ rintro hs x hxs hx,
exact (hs _ (set.diff_subset _ _) ⟨hxs, hx⟩).2 (set.mem_singleton _) },
{ rintro hs t ht x ⟨hxs, hxt⟩,
by_contra h,
exact hs _ hxs (convex_hull_mono (set.subset_diff_singleton ht h) hxt) }
end
/-! ### Extreme points -/
lemma convex.extreme_points_convex_independent (hs : convex s) :
convex_independent (λ p, p : s.extreme_points → E) :=
convex_independent_set_iff_not_mem_convex_hull_diff.2 $ λ x hx h,
(extreme_points_convex_hull_subset
(inter_extreme_points_subset_extreme_points_of_subset (convex_hull_min
((set.diff_subset _ _).trans extreme_points_subset) hs) ⟨h, hx⟩)).2 (set.mem_singleton _)
|
4fdc3b8c89a36d82ec9a3d3bb77b0fc8c57465a8 | 4e0d7c3132ce31edc5829849735dd25db406b144 | /lean/love05_inductive_predicates_exercise_sheet.lean | 783e2d3df5675e6058dc77a060ccde5075b00ee9 | [] | no_license | gonzalgu/logical_verification_2020 | a0013a6c22ea254e9f4d245f2948f0f4d44df4bb | 724d0457dff2c3ff10f9ab2170388f4c5e958b75 | refs/heads/master | 1,660,886,374,533 | 1,589,859,641,000 | 1,589,859,641,000 | 256,069,971 | 0 | 0 | null | 1,586,997,430,000 | 1,586,997,429,000 | null | UTF-8 | Lean | false | false | 5,185 | lean | import .love05_inductive_predicates_demo
/-! # LoVe Exercise 5: Inductive Predicates -/
set_option pp.beta true
namespace LoVe
/-! ## Question 1: Even and Odd
The `even` predicate is true for even numbers and false for odd numbers. -/
#check even
/-! We define `odd` as the negation of `even`: -/
def odd (n : ℕ) : Prop :=
¬ even n
/-! 1.1. Prove that 1 is odd and register this fact as a simp rule.
Hint: `cases` is useful to reason about hypotheses of the form `even …`. -/
@[simp] lemma odd_1 :
odd 1 :=
begin
unfold odd,
intro h,
cases h,
end
/-! 1.2. Prove that 3, 5, and 7 are odd. -/
-- enter your answer here
lemma odd_3 :
odd 3 :=
begin
unfold odd,
intro h,
cases h,
apply odd_1,
assumption,
end
lemma odd_5 :
odd 5 :=
begin
unfold odd,
intro h,
cases h,
simp at h_a,
apply odd_3,
assumption,
end
lemma odd_7 :
odd 7 :=
begin
unfold odd,
intro h,
cases h,
simp at h_a,
apply odd_5,
assumption,
end
/-! 1.3. Complete the following proof by structural induction. -/
lemma even_two_times :
∀m : ℕ, even (2 * m)
| 0 := even.zero
| (m + 1) :=
begin
rw mul_add,
simp,
rw add_comm,
apply even.add_two,
apply even_two_times,
end
/-! 1.4. Complete the following proof by rule induction.
Hint: You can use the `cases` tactic (or `match … with`) to destruct an
existential quantifier and extract the witness. -/
lemma even_imp_exists_two_times :
∀n : ℕ, even n → ∃m, n = 2 * m :=
begin
intros n hen,
induction hen,
case even.zero {
apply exists.intro 0,
refl },
case even.add_two : k hek ih {
cases ih with m hkm,
existsi (m+1),
rw hkm,
rw mul_add,
refl,
}
end
/-! 1.6. Using `even_two_times` and `even_imp_exists_two_times`, prove the
following equivalence. -/
lemma even_iff_exists_two_times (n : ℕ) :
even n ↔ ∃m, n = 2 * m :=
begin
split,
{
apply even_imp_exists_two_times,
},
{
intro h,
cases h with m hnm,
rw hnm,
apply even_two_times,
}
end
lemma even_iff_exists_two_times₂ (n : ℕ) :
even n ↔ ∃m, n = 2 * m :=
iff.intro
(assume hen : even n,
show ∃m, n = 2 * m,
from even_imp_exists_two_times n hen
)
(assume hex : (∃ (m : ℕ), n = 2 * m),
match hex with
| ⟨ m, hnx⟩ :=
begin
rw hnx,
apply even_two_times
end
end)
lemma even_iff_exists_two_times₃ (n : ℕ) :
even n ↔ ∃m, n = 2 * m :=
⟨ λhen, even_imp_exists_two_times n hen,
λ⟨m,hnm⟩,
begin
rw hnm,
apply even_two_times,
end ⟩
/-! ## Question 2: Binary Trees
2.1. Prove the converse of `is_full_mirror`. You may exploit already proved
lemmas (e.g., `is_full_mirror`, `mirror_mirror`). -/
#check is_full_mirror
#check mirror_mirror
lemma mirror_is_full {α : Type} :
∀t : btree α, is_full (mirror t) → is_full t :=
begin
intro t,
intro hfmt,
rw ←mirror_mirror t,
apply is_full_mirror,
assumption,
end
lemma mirror_is_full₂ {α : Type} :
∀t : btree α, is_full (mirror t) → is_full t :=
assume t : btree α,
assume hfmt : is_full (mirror t),
have mmt : mirror(mirror t) = t, from mirror_mirror t,
have hfmmt : is_full (mirror(mirror t)), from is_full_mirror _ hfmt,
show is_full t,
from eq.subst mmt hfmmt
/-! 2.2. Define a `map` function on binary trees, similar to `list.map`. -/
def btree.map {α β : Type} (f : α → β) : btree α → btree β
| btree.empty := btree.empty
| (btree.node v l r) := btree.node (f v) (btree.map l) (btree.map r)
-- enter the missing cases here
/-! 2.3. Prove the following lemma by case distinction. -/
lemma btree.map_eq_empty_iff {α β : Type} (f : α → β) :
∀t : btree α, btree.map f t = btree.empty ↔ t = btree.empty :=
begin
intro t,
split,
{
intro h,
cases t with v l r,
{
refl,
},
{
cases h,
},
},
{
intro h,
rw h,
refl,
}
end
/-! 2.4. Prove the following lemma by rule induction. -/
lemma btree.map_mirror {α β : Type} (f : α → β) :
∀t : btree α, is_full t → is_full (btree.map f t) :=
begin
intro t,
intro hft,
induction hft with v l r hfl hfr hiffe hfml hfmr,
{
simp [btree.map, is_full.empty],
},
{
apply is_full.node,
{
exact hfml,
},
{
exact hfmr,
},
{
split,
{
cases hiffe,
intro h,
have l_empty := (btree.map_eq_empty_iff _ _).mp h,
have r_empty := hiffe_mp l_empty,
rw r_empty,
refl,
},
{
cases hiffe,
intro h,
have r_empty := (btree.map_eq_empty_iff _ _).mp h,
have l_empty := hiffe_mpr r_empty,
rw l_empty,
refl,
}
}
}
end
-- forward attempt
lemma btree.map_mirror₂ {α β : Type} (f : α → β) :
∀t : btree α, is_full t → is_full (btree.map f t) :=
assume t : btree α,
assume hft : is_full t,
match t, hft with
| _, is_full.empty :=
begin
rw btree.map,
apply is_full.empty,
end
| _, (is_full.node v l r hfl hfr hiffe) :=
sorry
end
end LoVe
|
de1aba6a1ead8a4d851e37ce475542fb226b6824 | 4ec0e92c725fad3fd2871a0ab050a7da1c719444 | /src/mywork/exam1.lean | 72176bf8c7910cc323410fce64a086c5a2c5058c | [] | no_license | mitchelltaylor06/cs2120f21 | cc2c2b61a7e45c07faa849fcb8a66eb948753a25 | efb71a748d7c76e24834d03b8f01c3ae084c1756 | refs/heads/main | 1,693,841,444,092 | 1,633,713,850,000 | 1,633,713,850,000 | 399,946,415 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 10,320 | lean | /-
*******************************
PART 1 of 2: AXIOMS [50 points]
*******************************
-/
/-
Explain the inference (introduction and
elimination) rules of predicate logic as
directed below. To give you guidance on
how to answer these questions we include
answers for some questions.
-/
-- -------------------------------------
/- #1: → implies [5 points]
INTRODUCTION
Explain the introduction rule for →.
[We give you the answer here.]
In English: Given propositions, P and Q,
a derivation (computation) a proof of Q
from any proof of P, is a proof of P → Q.
In constructive logic, a derivation is a
given as a function definition. A proof
of P → Q literally is a function, that,
when given any proof of P as an argument
returns a proof of Q. If you define such
a function, you have proved P → Q.
ELIMINATION
Complete the definition of the elimination
rule for →.
(P Q : Prop) (p2q : P → Q) (p : P)
----------------------------------
[q : Q]
-/
-- Give a formal proof of the following
example : ∀ (P Q : Prop) (p2q : P → Q) (p : P), Q :=
begin
assume P Q,
assume a,
assume b,
have z : Q := a b,
exact z,
end
-- Extra credit [2 points]. Who invented this principle?
-- Kevin Sullivan? (Please respond positively to flattery)
-- -------------------------------------
/- #2: true [5 points]
INTRODUCTION
Give the introduction rule for true using
inference rule notation.
[Here's our answer.]
---------- intro
(pf: true)
Give a brief English language explanation of
the introduction rule for true.
-- Introduces the unconditionally true proposition of true
ELIMINATION
Give an English language description of the
eliimination rule for true.
[Our answer]
A proof of true carries no information so
there's no use for an elimination rule.
-/
-- Give a formal proof of the following:
example : true :=
begin
exact true.intro,
end
-- -------------------------------------
/- #3: ∧ - and [10 points]
INTRODUCTION
Using inference rule notation, give the
introduction rule for ∧.
[Our answer]
(P Q : Prop) (p : P) (q : Q)
---------------------------- intro
(pq : P ∧ Q)
Given an English language description of
this inference rule. What does it really
say, in plain simple English.
-- In plain simple English, this inference rule means that if we have a proof of
P and a proof of Q, we can make a proof of P and Q.
ELIMINATION
Give the elimination rules for ∧ in both
inference rule and English language forms.
-/
/-
(P Q : Prop) (pandq : P ∧ Q)
---------------------------- elim
(p : P) (q : Q)
-/
-- In simple English, this inference rule means that if we have a proof of
-- P and Q, we can create a proof of P and a proof of Q.
/-
Formally state and prove the theorem that,
for any propositions P and Q, Q ∧ P → P.
-/
example : ∀ (P Q: Prop), Q ∧ P → P :=
begin
assume P Q,
assume h,
have p : P := and.elim_right h,
exact p,
end
-- -------------------------------------
/- #4: ∀ - for all [10 points]
INTRODUCTION
Explain in English the introduction rule for ∀. If
T is any type (such as nat) and Q is any proposition
(often in the form of a predicate on values of the
given type), how do you prove ∀ (t : T), Q? What is
the introduction rule for ∀?
-- The introduction rule for ∀ is to assume an arbitrary t and then show that
-- t has property Q.
ELIMINATION
Here's an inference rule representation of the elim
rule for ∀. First, complete the inference rule by
filling in the bottom half, then Explain in English
what it says.
(T : Type) (Q : Prop), (pf : ∀ (t : T), Q) (t : T)
-------------------------------------------------- elim
[t : Q]
-- This says that given a proof of for all t, t has property Q, a proof of
value t with property Q can be created.
Given a proof, (pf : ∀ (t : T), Q), and a value, (t : T),
briefly explain in English how you *use* pf to derive a
proof of Q.
-- You use pf by apply the value (t : T) to the proof as your t value, meaning
that it has property Q.
-/
/-
Consider the following assumptions, and then in the
context of these assumptions, given answers to the
challenge problems.
-/
axioms
(Person : Type)
(KnowsLogic BetterComputerScientist : Person → Prop)
(LogicMakesYouBetterAtCS:
∀ (p : Person), KnowsLogic p → BetterComputerScientist p)
-- formalizee the following assumptions here
-- (1) Lynn is a person
-- (2) Lynn knows logic
(Lynn : Person)
(KLL : KnowsLogic Lynn)
/-
Now, formally state and prove the proposition that
Lynn is a better computer scientist
-/
example : BetterComputerScientist Lynn :=
begin
apply LogicMakesYouBetterAtCS Lynn,
exact KLL,
end
-- -------------------------------------
/- #5: ¬ - not [10 points]
The ¬ connective in Lean is short for *not*. Give
the short formal definition of ¬ in Lean. Note that
surround the place where you give your answer with
a namespace. This is just to avoid conflicting with
Lean's definition of not.
-/
namespace hidden
def not (P : Prop) := P → false -- fill in the placeholder
end hidden
/-
Explain precisely in English the "proof strategy"
of "proof by negation." Explain how one uses this
strategy to prove a proposition, ¬P.
-/
-- The proof strategy of proof by negation is to assume P is true and then
-- prove that this is a contradiction. That means P is false.
/-
Explain precisely in English the "proof strategy"
of "proof by contradiction." Explain how one uses
this strategy to prove a proposition, P (notice
the lack of a ¬ in front of the P).
Fill in the blanks the following partial answer:
To prove P, assume ¬P and show that there is a contradiction.
From this derivation you can conclude ¬¬P.
Then you apply the rule of negation elimination
to that result to arrive a a proof of P. We have
seen that the inference rule you apply in the
last step is not constructively valid but that it
is logically valid, and that accepting the axiom
of the excluded middle suffices to establish negation
elimination (better called double negation elimination)
as a theorem.
-/
-- -------------------------------------
/-
#6: ↔ - if and only if, equivalent to [10 points]
-/
/-
ELIMINATION
As with ∧, ↔ has two elimination rules. You can
see their statements here.
-/
#check @iff.elim_left
#check @iff.elim_right
/-
Formally state and prove the theorem that
biimplication, ↔, is *commutative*. Note:
put parentheses around each ↔ proposition,
as → has higher precedence than ↔. Recall
that iff has both elim_left and elim_right
rules, just like ∧.
-/
example : ∀ (P Q : Prop), (P ↔ Q) → (Q ↔ P) :=
begin
assume P Q,
assume h,
have qp : Q → P := iff.elim_right h,
have pq : P → Q := iff.elim_left h,
apply iff.intro,
exact qp,
exact pq,
end
/-
************************************************
PART 2 of 3: PROPOSITIONS AND PROOFS [50 points]
************************************************
-/
/- #7 [20 points]
First, give a fluent English rendition of
the following proposition. Note that the
identifier we use, elantp, is short for
"everyone likes a nice, talented person."
Then give a formal proof. Hint: try the
"intros" tactic by itself where you'd
previously have used assume followed by
a list of identifiers. Think about what
each expression means.
-/
def ELJL : Prop :=
∀ (Person : Type)
(Nice : Person → Prop)
(Talented : Person → Prop)
(Likes : Person → Person → Prop)
(elantp : ∀ (p : Person),
Nice p → Talented p →
∀ (q : Person), Likes q p)
(JohnLennon : Person)
(JLNT : Nice JohnLennon ∧ Talented JohnLennon),
(∀ (p : Person), Likes p JohnLennon)
/-
Everyone likes people who are both nice and talented. John Lennon is nice and
talented, therefore everyone likes him.
-/
example : ELJL :=
begin
unfold ELJL,
intros,
apply elantp JohnLennon,
have njl : Nice JohnLennon := and.elim_left JLNT,
exact njl,
have tjl : Talented JohnLennon := and.elim_right JLNT,
exact tjl,
end
/- #8 [10 points]
If every car is either heavy or light, and red or
blue, and we want a prove by cases that every car
is rad, then:
-- how many cases will need to be considered? 4
-- list the cases (informaly)
-- Heavy and Red
-- Heavy and Blue
-- Light and Red
-- Light and Blue
-/
/-
*********
RELATIONS
*********
-/
/- #9 [20 points]
Equality can be understood as a binary relation
on objects of a given type. There is a binary
equality relation on natural numbers, rational
numbers, on strings, on Booleans, and so forth.
We also saw that from the two axioms (inference
rules) for equality, we could prove that it is
not only reflexive, but also both symmetric and
transitive.
Complete the following definitions to express
the propositions that equality is respectively
symmetric and transitive. (Don't worry about
proving these propositions. We just want you
to write them formally, to show that you what
the terms means.)
-/
def eq_is_symmetric : Prop :=
∀ (T : Type) (x y : T),
x = y →
y = x
def eq_is_transitive : Prop :=
∀ (T : Type) (x y z : T),
x = y →
y = z →
x = z
/-
************
EXTRA CREDIT
************
-/
/-
EXTRA CREDIT: State and prove the proposition
that (double) negation elimination is equivalent
to excluded middle. You get 1 point for writing
the correct proposition, 2 points for proving it
in one direction and five points for proving it
both directions.
-/
def negelim_equiv_exmid : Prop :=
∀ (P : Prop),
(¬¬P → P) ↔ P ∨ ¬P
example: negelim_equiv_exmid :=
begin
unfold negelim_equiv_exmid,
assume P,
apply iff.intro,
assume h,
apply classical.em P,
assume x,
assume y,
cases x,
exact x,
contradiction,
end
/-
EXTRA CREDIT: Formally express and prove the
proposition that if there is someone everyone
loves, and loves is a symmetric relation, then
there is someone who loves everyone. [5 points]
-/
axiom Loves : Person → Person → Prop
example :
(∃ (p : Person), ∀ (p2 : Person), Loves p2 p) →
(∀ (a : Person), ∃ (b : Person), Loves a b) :=
begin
assume h,
assume a,
cases h with x y,
apply exists.intro x,
apply y a,
end
|
69cb2fb8bd5971b1c9ad8d5efafce7b8e93a119b | 432d948a4d3d242fdfb44b81c9e1b1baacd58617 | /src/algebra/algebra/subalgebra.lean | 510a1a7300b059a61dc0c9e989e8731860304d04 | [
"Apache-2.0"
] | permissive | JLimperg/aesop3 | 306cc6570c556568897ed2e508c8869667252e8a | a4a116f650cc7403428e72bd2e2c4cda300fe03f | refs/heads/master | 1,682,884,916,368 | 1,620,320,033,000 | 1,620,320,033,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 26,331 | lean | /-
Copyright (c) 2018 Kenny Lau. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kenny Lau, Yury Kudryashov
-/
import algebra.algebra.operations
/-!
# Subalgebras over Commutative Semiring
In this file we define `subalgebra`s and the usual operations on them (`map`, `comap`).
More lemmas about `adjoin` can be found in `ring_theory.adjoin`.
-/
universes u v w
open_locale tensor_product big_operators
set_option old_structure_cmd true
/-- A subalgebra is a sub(semi)ring that includes the range of `algebra_map`. -/
structure subalgebra (R : Type u) (A : Type v)
[comm_semiring R] [semiring A] [algebra R A] extends subsemiring A : Type v :=
(algebra_map_mem' : ∀ r, algebra_map R A r ∈ carrier)
(zero_mem' := (algebra_map R A).map_zero ▸ algebra_map_mem' 0)
(one_mem' := (algebra_map R A).map_one ▸ algebra_map_mem' 1)
/-- Reinterpret a `subalgebra` as a `subsemiring`. -/
add_decl_doc subalgebra.to_subsemiring
namespace subalgebra
variables {R : Type u} {A : Type v} {B : Type w}
variables [comm_semiring R] [semiring A] [algebra R A] [semiring B] [algebra R B]
include R
instance : set_like (subalgebra R A) A :=
⟨subalgebra.carrier, λ p q h, by cases p; cases q; congr'⟩
@[simp]
lemma mem_carrier {s : subalgebra R A} {x : A} : x ∈ s.carrier ↔ x ∈ s := iff.rfl
@[ext] theorem ext {S T : subalgebra R A} (h : ∀ x : A, x ∈ S ↔ x ∈ T) : S = T := set_like.ext h
/-- Copy of a submodule with a new `carrier` equal to the old one. Useful to fix definitional
equalities. -/
protected def copy (S : subalgebra R A) (s : set A) (hs : s = ↑S) : subalgebra R A :=
{ carrier := s,
add_mem' := hs.symm ▸ S.add_mem',
mul_mem' := hs.symm ▸ S.mul_mem',
algebra_map_mem' := hs.symm ▸ S.algebra_map_mem' }
variables (S : subalgebra R A)
theorem algebra_map_mem (r : R) : algebra_map R A r ∈ S :=
S.algebra_map_mem' r
theorem srange_le : (algebra_map R A).srange ≤ S.to_subsemiring :=
λ x ⟨r, hr⟩, hr ▸ S.algebra_map_mem r
theorem range_subset : set.range (algebra_map R A) ⊆ S :=
λ x ⟨r, hr⟩, hr ▸ S.algebra_map_mem r
theorem range_le : set.range (algebra_map R A) ≤ S :=
S.range_subset
theorem one_mem : (1 : A) ∈ S :=
S.to_subsemiring.one_mem
theorem mul_mem {x y : A} (hx : x ∈ S) (hy : y ∈ S) : x * y ∈ S :=
S.to_subsemiring.mul_mem hx hy
theorem smul_mem {x : A} (hx : x ∈ S) (r : R) : r • x ∈ S :=
(algebra.smul_def r x).symm ▸ S.mul_mem (S.algebra_map_mem r) hx
theorem pow_mem {x : A} (hx : x ∈ S) (n : ℕ) : x ^ n ∈ S :=
S.to_subsemiring.pow_mem hx n
theorem zero_mem : (0 : A) ∈ S :=
S.to_subsemiring.zero_mem
theorem add_mem {x y : A} (hx : x ∈ S) (hy : y ∈ S) : x + y ∈ S :=
S.to_subsemiring.add_mem hx hy
theorem neg_mem {R : Type u} {A : Type v} [comm_ring R] [ring A]
[algebra R A] (S : subalgebra R A) {x : A} (hx : x ∈ S) : -x ∈ S :=
neg_one_smul R x ▸ S.smul_mem hx _
theorem sub_mem {R : Type u} {A : Type v} [comm_ring R] [ring A]
[algebra R A] (S : subalgebra R A) {x y : A} (hx : x ∈ S) (hy : y ∈ S) : x - y ∈ S :=
by simpa only [sub_eq_add_neg] using S.add_mem hx (S.neg_mem hy)
theorem nsmul_mem {x : A} (hx : x ∈ S) (n : ℕ) : n • x ∈ S :=
S.to_subsemiring.nsmul_mem hx n
theorem gsmul_mem {R : Type u} {A : Type v} [comm_ring R] [ring A]
[algebra R A] (S : subalgebra R A) {x : A} (hx : x ∈ S) : ∀ (n : ℤ), n • x ∈ S
| (n : ℕ) := by { rw [gsmul_coe_nat], exact S.nsmul_mem hx n }
| -[1+ n] := by { rw [gsmul_neg_succ_of_nat], exact S.neg_mem (S.nsmul_mem hx _) }
theorem coe_nat_mem (n : ℕ) : (n : A) ∈ S :=
S.to_subsemiring.coe_nat_mem n
theorem coe_int_mem {R : Type u} {A : Type v} [comm_ring R] [ring A]
[algebra R A] (S : subalgebra R A) (n : ℤ) : (n : A) ∈ S :=
int.cases_on n (λ i, S.coe_nat_mem i) (λ i, S.neg_mem $ S.coe_nat_mem $ i + 1)
theorem list_prod_mem {L : list A} (h : ∀ x ∈ L, x ∈ S) : L.prod ∈ S :=
S.to_subsemiring.list_prod_mem h
theorem list_sum_mem {L : list A} (h : ∀ x ∈ L, x ∈ S) : L.sum ∈ S :=
S.to_subsemiring.list_sum_mem h
theorem multiset_prod_mem {R : Type u} {A : Type v} [comm_semiring R] [comm_semiring A]
[algebra R A] (S : subalgebra R A) {m : multiset A} (h : ∀ x ∈ m, x ∈ S) : m.prod ∈ S :=
S.to_subsemiring.multiset_prod_mem m h
theorem multiset_sum_mem {m : multiset A} (h : ∀ x ∈ m, x ∈ S) : m.sum ∈ S :=
S.to_subsemiring.multiset_sum_mem m h
theorem prod_mem {R : Type u} {A : Type v} [comm_semiring R] [comm_semiring A]
[algebra R A] (S : subalgebra R A) {ι : Type w} {t : finset ι} {f : ι → A}
(h : ∀ x ∈ t, f x ∈ S) : ∏ x in t, f x ∈ S :=
S.to_subsemiring.prod_mem h
theorem sum_mem {ι : Type w} {t : finset ι} {f : ι → A}
(h : ∀ x ∈ t, f x ∈ S) : ∑ x in t, f x ∈ S :=
S.to_subsemiring.sum_mem h
instance {R : Type u} {A : Type v} [comm_semiring R] [semiring A] [algebra R A]
(S : subalgebra R A) : is_add_submonoid (S : set A) :=
{ zero_mem := S.zero_mem,
add_mem := λ _ _, S.add_mem }
instance {R : Type u} {A : Type v} [comm_semiring R] [semiring A] [algebra R A]
(S : subalgebra R A) : is_submonoid (S : set A) :=
{ one_mem := S.one_mem,
mul_mem := λ _ _, S.mul_mem }
/-- A subalgebra over a ring is also a `subring`. -/
def to_subring {R : Type u} {A : Type v} [comm_ring R] [ring A] [algebra R A] (S : subalgebra R A) :
subring A :=
{ neg_mem' := λ _, S.neg_mem,
.. S.to_subsemiring }
instance {R : Type u} {A : Type v} [comm_ring R] [ring A] [algebra R A] (S : subalgebra R A) :
is_subring (S : set A) :=
{ neg_mem := λ _, S.neg_mem }
instance : inhabited S := ⟨(0 : S.to_subsemiring)⟩
section
/-! `subalgebra`s inherit structure from their `subsemiring` / `semiring` coercions. -/
instance to_semiring {R A}
[comm_semiring R] [semiring A] [algebra R A] (S : subalgebra R A) :
semiring S := S.to_subsemiring.to_semiring
instance to_comm_semiring {R A}
[comm_semiring R] [comm_semiring A] [algebra R A] (S : subalgebra R A) :
comm_semiring S := S.to_subsemiring.to_comm_semiring
instance to_ring {R A}
[comm_ring R] [ring A] [algebra R A] (S : subalgebra R A) :
ring S := S.to_subring.to_ring
instance to_comm_ring {R A}
[comm_ring R] [comm_ring A] [algebra R A] (S : subalgebra R A) :
comm_ring S := S.to_subring.to_comm_ring
instance to_ordered_semiring {R A}
[comm_semiring R] [ordered_semiring A] [algebra R A] (S : subalgebra R A) :
ordered_semiring S := S.to_subsemiring.to_ordered_semiring
instance to_ordered_comm_semiring {R A}
[comm_semiring R] [ordered_comm_semiring A] [algebra R A] (S : subalgebra R A) :
ordered_comm_semiring S := S.to_subsemiring.to_ordered_comm_semiring
instance to_ordered_ring {R A}
[comm_ring R] [ordered_ring A] [algebra R A] (S : subalgebra R A) :
ordered_ring S := S.to_subring.to_ordered_ring
instance to_ordered_comm_ring {R A}
[comm_ring R] [ordered_comm_ring A] [algebra R A] (S : subalgebra R A) :
ordered_comm_ring S := S.to_subring.to_ordered_comm_ring
instance to_linear_ordered_semiring {R A}
[comm_semiring R] [linear_ordered_semiring A] [algebra R A] (S : subalgebra R A) :
linear_ordered_semiring S := S.to_subsemiring.to_linear_ordered_semiring
/-! There is no `linear_ordered_comm_semiring`. -/
instance to_linear_ordered_ring {R A}
[comm_ring R] [linear_ordered_ring A] [algebra R A] (S : subalgebra R A) :
linear_ordered_ring S := S.to_subring.to_linear_ordered_ring
instance to_linear_ordered_comm_ring {R A}
[comm_ring R] [linear_ordered_comm_ring A] [algebra R A] (S : subalgebra R A) :
linear_ordered_comm_ring S := S.to_subring.to_linear_ordered_comm_ring
end
instance algebra : algebra R S :=
{ smul := λ (c:R) x, ⟨c • x.1, S.smul_mem x.2 c⟩,
commutes' := λ c x, subtype.eq $ algebra.commutes _ _,
smul_def' := λ c x, subtype.eq $ algebra.smul_def _ _,
.. (algebra_map R A).cod_srestrict S.to_subsemiring $ λ x, S.range_le ⟨x, rfl⟩ }
instance to_algebra {R A B : Type*} [comm_semiring R] [comm_semiring A] [semiring B]
[algebra R A] [algebra A B] (A₀ : subalgebra R A) : algebra A₀ B :=
algebra.of_subsemiring A₀.to_subsemiring
instance nontrivial [nontrivial A] : nontrivial S :=
S.to_subsemiring.nontrivial
instance no_zero_smul_divisors_bot [no_zero_smul_divisors R A] : no_zero_smul_divisors R S :=
⟨λ c x h,
have c = 0 ∨ (x : A) = 0,
from eq_zero_or_eq_zero_of_smul_eq_zero (congr_arg coe h),
this.imp_right (@subtype.ext_iff _ _ x 0).mpr⟩
@[simp, norm_cast] lemma coe_add (x y : S) : (↑(x + y) : A) = ↑x + ↑y := rfl
@[simp, norm_cast] lemma coe_mul (x y : S) : (↑(x * y) : A) = ↑x * ↑y := rfl
@[simp, norm_cast] lemma coe_zero : ((0 : S) : A) = 0 := rfl
@[simp, norm_cast] lemma coe_one : ((1 : S) : A) = 1 := rfl
@[simp, norm_cast] lemma coe_neg {R : Type u} {A : Type v} [comm_ring R] [ring A] [algebra R A]
{S : subalgebra R A} (x : S) : (↑(-x) : A) = -↑x := rfl
@[simp, norm_cast] lemma coe_sub {R : Type u} {A : Type v} [comm_ring R] [ring A] [algebra R A]
{S : subalgebra R A} (x y : S) : (↑(x - y) : A) = ↑x - ↑y := rfl
@[simp, norm_cast] lemma coe_smul (r : R) (x : S) : (↑(r • x) : A) = r • ↑x := rfl
@[simp, norm_cast] lemma coe_algebra_map (r : R) : ↑(algebra_map R S r) = algebra_map R A r :=
rfl
@[simp, norm_cast] lemma coe_pow (x : S) (n : ℕ) : (↑(x^n) : A) = (↑x)^n :=
begin
induction n with n ih,
{ simp, },
{ simp [pow_succ, ih], },
end
@[simp, norm_cast] lemma coe_eq_zero {x : S} : (x : A) = 0 ↔ x = 0 :=
(subtype.ext_iff.symm : (x : A) = (0 : S) ↔ x = 0)
@[simp, norm_cast] lemma coe_eq_one {x : S} : (x : A) = 1 ↔ x = 1 :=
(subtype.ext_iff.symm : (x : A) = (1 : S) ↔ x = 1)
-- todo: standardize on the names these morphisms
-- compare with submodule.subtype
/-- Embedding of a subalgebra into the algebra. -/
def val : S →ₐ[R] A :=
by refine_struct { to_fun := (coe : S → A) }; intros; refl
@[simp] lemma coe_val : (S.val : S → A) = coe := rfl
lemma val_apply (x : S) : S.val x = (x : A) := rfl
/-- Convert a `subalgebra` to `submodule` -/
def to_submodule : submodule R A :=
{ carrier := S,
zero_mem' := (0:S).2,
add_mem' := λ x y hx hy, (⟨x, hx⟩ + ⟨y, hy⟩ : S).2,
smul_mem' := λ c x hx, (algebra.smul_def c x).symm ▸
(⟨algebra_map R A c, S.range_le ⟨c, rfl⟩⟩ * ⟨x, hx⟩:S).2 }
instance to_submodule.is_subring {R : Type u} {A : Type v} [comm_ring R] [ring A] [algebra R A]
(S : subalgebra R A) : is_subring (S.to_submodule : set A) := S.is_subring
@[simp] lemma mem_to_submodule {x} : x ∈ S.to_submodule ↔ x ∈ S := iff.rfl
theorem to_submodule_injective :
function.injective (to_submodule : subalgebra R A → submodule R A) :=
λ S T h, ext $ λ x, by rw [← mem_to_submodule, ← mem_to_submodule, h]
theorem to_submodule_inj {S U : subalgebra R A} : S.to_submodule = U.to_submodule ↔ S = U :=
to_submodule_injective.eq_iff
/-- As submodules, subalgebras are idempotent. -/
@[simp] theorem mul_self : S.to_submodule * S.to_submodule = S.to_submodule :=
begin
apply le_antisymm,
{ rw submodule.mul_le,
intros y hy z hz,
exact mul_mem S hy hz },
{ intros x hx1,
rw ← mul_one x,
exact submodule.mul_mem_mul hx1 (one_mem S) }
end
/-- Linear equivalence between `S : submodule R A` and `S`. Though these types are equal,
we define it as a `linear_equiv` to avoid type equalities. -/
def to_submodule_equiv (S : subalgebra R A) : S.to_submodule ≃ₗ[R] S :=
linear_equiv.of_eq _ _ rfl
/-- Reinterpret an `S`-subalgebra as an `R`-subalgebra in `comap R S A`. -/
def comap {R : Type u} {S : Type v} {A : Type w}
[comm_semiring R] [comm_semiring S] [semiring A] [algebra R S] [algebra S A]
(iSB : subalgebra S A) : subalgebra R (algebra.comap R S A) :=
{ algebra_map_mem' := λ r, iSB.algebra_map_mem (algebra_map R S r),
.. iSB }
/-- If `S` is an `R`-subalgebra of `A` and `T` is an `S`-subalgebra of `A`,
then `T` is an `R`-subalgebra of `A`. -/
def under {R : Type u} {A : Type v} [comm_semiring R] [comm_semiring A]
{i : algebra R A} (S : subalgebra R A)
(T : subalgebra S A) : subalgebra R A :=
{ algebra_map_mem' := λ r, T.algebra_map_mem ⟨algebra_map R A r, S.algebra_map_mem r⟩,
.. T }
/-- Transport a subalgebra via an algebra homomorphism. -/
def map (S : subalgebra R A) (f : A →ₐ[R] B) : subalgebra R B :=
{ algebra_map_mem' := λ r, f.commutes r ▸ set.mem_image_of_mem _ (S.algebra_map_mem r),
.. S.to_subsemiring.map (f : A →+* B) }
lemma map_mono {S₁ S₂ : subalgebra R A} {f : A →ₐ[R] B} :
S₁ ≤ S₂ → S₁.map f ≤ S₂.map f :=
set.image_subset f
lemma map_injective {S₁ S₂ : subalgebra R A} (f : A →ₐ[R] B)
(hf : function.injective f) (ih : S₁.map f = S₂.map f) : S₁ = S₂ :=
ext $ set.ext_iff.1 $ set.image_injective.2 hf $ set.ext $ set_like.ext_iff.mp ih
lemma mem_map {S : subalgebra R A} {f : A →ₐ[R] B} {y : B} :
y ∈ map S f ↔ ∃ x ∈ S, f x = y :=
subsemiring.mem_map
/-- Preimage of a subalgebra under an algebra homomorphism. -/
def comap' (S : subalgebra R B) (f : A →ₐ[R] B) : subalgebra R A :=
{ algebra_map_mem' := λ r, show f (algebra_map R A r) ∈ S,
from (f.commutes r).symm ▸ S.algebra_map_mem r,
.. S.to_subsemiring.comap (f : A →+* B) }
theorem map_le {S : subalgebra R A} {f : A →ₐ[R] B} {U : subalgebra R B} :
map S f ≤ U ↔ S ≤ comap' U f :=
set.image_subset_iff
@[simp] lemma mem_comap (S : subalgebra R B) (f : A →ₐ[R] B) (x : A) :
x ∈ S.comap' f ↔ f x ∈ S :=
iff.rfl
@[simp, norm_cast] lemma coe_comap (S : subalgebra R B) (f : A →ₐ[R] B) :
(S.comap' f : set A) = f ⁻¹' (S : set B) :=
by { ext, simp, }
instance no_zero_divisors {R A : Type*} [comm_ring R] [semiring A] [no_zero_divisors A]
[algebra R A] (S : subalgebra R A) : no_zero_divisors S :=
S.to_subsemiring.no_zero_divisors
instance no_zero_smul_divisors_top {R A : Type*} [comm_semiring R] [comm_semiring A] [algebra R A]
[no_zero_divisors A] (S : subalgebra R A) : no_zero_smul_divisors S A :=
⟨λ c x h,
have (c : A) = 0 ∨ x = 0,
from eq_zero_or_eq_zero_of_mul_eq_zero h,
this.imp_left (@subtype.ext_iff _ _ c 0).mpr⟩
instance integral_domain {R A : Type*} [comm_ring R] [integral_domain A] [algebra R A]
(S : subalgebra R A) : integral_domain S :=
@subring.domain A _ S _
end subalgebra
namespace alg_hom
variables {R : Type u} {A : Type v} {B : Type w}
variables [comm_semiring R] [semiring A] [semiring B] [algebra R A] [algebra R B]
variables (φ : A →ₐ[R] B)
/-- Range of an `alg_hom` as a subalgebra. -/
protected def range (φ : A →ₐ[R] B) : subalgebra R B :=
{ algebra_map_mem' := λ r, ⟨algebra_map R A r, φ.commutes r⟩,
.. φ.to_ring_hom.srange }
@[simp] lemma mem_range (φ : A →ₐ[R] B) {y : B} :
y ∈ φ.range ↔ ∃ x, φ x = y := ring_hom.mem_srange
theorem mem_range_self (φ : A →ₐ[R] B) (x : A) : φ x ∈ φ.range := φ.mem_range.2 ⟨x, rfl⟩
@[simp] lemma coe_range (φ : A →ₐ[R] B) : (φ.range : set B) = set.range φ :=
by { ext, rw [set_like.mem_coe, mem_range], refl }
/-- Restrict the codomain of an algebra homomorphism. -/
def cod_restrict (f : A →ₐ[R] B) (S : subalgebra R B) (hf : ∀ x, f x ∈ S) : A →ₐ[R] S :=
{ commutes' := λ r, subtype.eq $ f.commutes r,
.. ring_hom.cod_srestrict (f : A →+* B) S.to_subsemiring hf }
@[simp] lemma val_comp_cod_restrict (f : A →ₐ[R] B) (S : subalgebra R B) (hf : ∀ x, f x ∈ S) :
S.val.comp (f.cod_restrict S hf) = f :=
alg_hom.ext $ λ _, rfl
@[simp] lemma coe_cod_restrict (f : A →ₐ[R] B) (S : subalgebra R B) (hf : ∀ x, f x ∈ S) (x : A) :
↑(f.cod_restrict S hf x) = f x := rfl
theorem injective_cod_restrict (f : A →ₐ[R] B) (S : subalgebra R B) (hf : ∀ x, f x ∈ S) :
function.injective (f.cod_restrict S hf) ↔ function.injective f :=
⟨λ H x y hxy, H $ subtype.eq hxy, λ H x y hxy, H (congr_arg subtype.val hxy : _)⟩
/-- Restrict the codomain of a alg_hom `f` to `f.range`.
This is the bundled version of `set.range_factorization`. -/
@[reducible] def range_restrict (f : A →ₐ[R] B) : A →ₐ[R] f.range :=
f.cod_restrict f.range f.mem_range_self
/-- The equalizer of two R-algebra homomorphisms -/
def equalizer (ϕ ψ : A →ₐ[R] B) : subalgebra R A :=
{ carrier := {a | ϕ a = ψ a},
add_mem' := λ x y hx hy, by
{ change ϕ x = ψ x at hx,
change ϕ y = ψ y at hy,
change ϕ (x + y) = ψ (x + y),
rw [alg_hom.map_add, alg_hom.map_add, hx, hy] },
mul_mem' := λ x y hx hy, by
{ change ϕ x = ψ x at hx,
change ϕ y = ψ y at hy,
change ϕ (x * y) = ψ (x * y),
rw [alg_hom.map_mul, alg_hom.map_mul, hx, hy] },
algebra_map_mem' := λ x, by
{ change ϕ (algebra_map R A x) = ψ (algebra_map R A x),
rw [alg_hom.commutes, alg_hom.commutes] } }
@[simp] lemma mem_equalizer (ϕ ψ : A →ₐ[R] B) (x : A) :
x ∈ ϕ.equalizer ψ ↔ ϕ x = ψ x := iff.rfl
end alg_hom
namespace alg_equiv
variables {R : Type u} {A : Type v} {B : Type w}
variables [comm_semiring R] [semiring A] [semiring B] [algebra R A] [algebra R B]
/-- Restrict an algebra homomorphism with a left inverse to an algebra isomorphism to its range.
This is a computable alternative to `alg_equiv.of_injective`. -/
def of_left_inverse
{g : B → A} {f : A →ₐ[R] B} (h : function.left_inverse g f) :
A ≃ₐ[R] f.range :=
{ to_fun := f.range_restrict,
inv_fun := g ∘ f.range.val,
left_inv := h,
right_inv := λ x, subtype.ext $
let ⟨x', hx'⟩ := f.mem_range.mp x.prop in
show f (g x) = x, by rw [←hx', h x'],
..f.range_restrict }
@[simp] lemma of_left_inverse_apply
{g : B → A} {f : A →ₐ[R] B} (h : function.left_inverse g f) (x : A) :
↑(of_left_inverse h x) = f x := rfl
@[simp] lemma of_left_inverse_symm_apply
{g : B → A} {f : A →ₐ[R] B} (h : function.left_inverse g f) (x : f.range) :
(of_left_inverse h).symm x = g x := rfl
/-- Restrict an injective algebra homomorphism to an algebra isomorphism -/
noncomputable def of_injective (f : A →ₐ[R] B) (hf : function.injective f) :
A ≃ₐ[R] f.range :=
of_left_inverse (classical.some_spec hf.has_left_inverse)
@[simp] lemma of_injective_apply (f : A →ₐ[R] B) (hf : function.injective f) (x : A) :
↑(of_injective f hf x) = f x := rfl
/-- Restrict an algebra homomorphism between fields to an algebra isomorphism -/
noncomputable def of_injective_field {E F : Type*} [division_ring E] [semiring F]
[nontrivial F] [algebra R E] [algebra R F] (f : E →ₐ[R] F) : E ≃ₐ[R] f.range :=
of_injective f f.to_ring_hom.injective
end alg_equiv
namespace algebra
variables (R : Type u) {A : Type v} {B : Type w}
variables [comm_semiring R] [semiring A] [algebra R A] [semiring B] [algebra R B]
/-- The minimal subalgebra that includes `s`. -/
def adjoin (s : set A) : subalgebra R A :=
{ algebra_map_mem' := λ r, subsemiring.subset_closure $ or.inl ⟨r, rfl⟩,
.. subsemiring.closure (set.range (algebra_map R A) ∪ s) }
variables {R}
protected lemma gc : galois_connection (adjoin R : set A → subalgebra R A) coe :=
λ s S, ⟨λ H, le_trans (le_trans (set.subset_union_right _ _) subsemiring.subset_closure) H,
λ H, show subsemiring.closure (set.range (algebra_map R A) ∪ s) ≤ S.to_subsemiring,
from subsemiring.closure_le.2 $ set.union_subset S.range_subset H⟩
/-- Galois insertion between `adjoin` and `coe`. -/
protected def gi : galois_insertion (adjoin R : set A → subalgebra R A) coe :=
{ choice := λ s hs, adjoin R s,
gc := algebra.gc,
le_l_u := λ S, (algebra.gc (S : set A) (adjoin R S)).1 $ le_refl _,
choice_eq := λ _ _, rfl }
instance : complete_lattice (subalgebra R A) :=
galois_insertion.lift_complete_lattice algebra.gi
instance : inhabited (subalgebra R A) := ⟨⊥⟩
theorem mem_bot {x : A} : x ∈ (⊥ : subalgebra R A) ↔ x ∈ set.range (algebra_map R A) :=
suffices (of_id R A).range = (⊥ : subalgebra R A),
by { rw [← this, ←set_like.mem_coe, alg_hom.coe_range], refl },
le_bot_iff.mp (λ x hx, subalgebra.range_le _ ((of_id R A).coe_range ▸ hx))
theorem to_submodule_bot : (⊥ : subalgebra R A).to_submodule = R ∙ 1 :=
by { ext x, simp [mem_bot, -set.singleton_one, submodule.mem_span_singleton, algebra.smul_def] }
@[simp] theorem mem_top {x : A} : x ∈ (⊤ : subalgebra R A) :=
subsemiring.subset_closure $ or.inr trivial
@[simp] theorem top_to_submodule : (⊤ : subalgebra R A).to_submodule = ⊤ :=
submodule.ext $ λ x, iff_of_true mem_top trivial
@[simp] theorem top_to_subsemiring : (⊤ : subalgebra R A).to_subsemiring = ⊤ :=
subsemiring.ext $ λ x, iff_of_true mem_top trivial
@[simp] theorem coe_bot : ((⊥ : subalgebra R A) : set A) = set.range (algebra_map R A) :=
by simp [set.ext_iff, algebra.mem_bot]
theorem eq_top_iff {S : subalgebra R A} :
S = ⊤ ↔ ∀ x : A, x ∈ S :=
⟨λ h x, by rw h; exact mem_top, λ h, by ext x; exact ⟨λ _, mem_top, λ _, h x⟩⟩
@[simp] theorem map_top (f : A →ₐ[R] B) : subalgebra.map (⊤ : subalgebra R A) f = f.range :=
subalgebra.ext $ λ x,
⟨λ ⟨y, _, hy⟩, ⟨y, hy⟩, λ ⟨y, hy⟩, ⟨y, algebra.mem_top, hy⟩⟩
@[simp] theorem map_bot (f : A →ₐ[R] B) : subalgebra.map (⊥ : subalgebra R A) f = ⊥ :=
eq_bot_iff.2 $ λ x ⟨y, hy, hfy⟩, let ⟨r, hr⟩ := mem_bot.1 hy in subalgebra.range_le _
⟨r, by rwa [← f.commutes, hr]⟩
@[simp] theorem comap_top (f : A →ₐ[R] B) : subalgebra.comap' (⊤ : subalgebra R B) f = ⊤ :=
eq_top_iff.2 $ λ x, mem_top
/-- `alg_hom` to `⊤ : subalgebra R A`. -/
def to_top : A →ₐ[R] (⊤ : subalgebra R A) :=
by refine_struct { to_fun := λ x, (⟨x, mem_top⟩ : (⊤ : subalgebra R A)) }; intros; refl
theorem surjective_algebra_map_iff :
function.surjective (algebra_map R A) ↔ (⊤ : subalgebra R A) = ⊥ :=
⟨λ h, eq_bot_iff.2 $ λ y _, let ⟨x, hx⟩ := h y in hx ▸ subalgebra.algebra_map_mem _ _,
λ h y, algebra.mem_bot.1 $ eq_bot_iff.1 h (algebra.mem_top : y ∈ _)⟩
theorem bijective_algebra_map_iff {R A : Type*} [field R] [semiring A] [nontrivial A]
[algebra R A] :
function.bijective (algebra_map R A) ↔ (⊤ : subalgebra R A) = ⊥ :=
⟨λ h, surjective_algebra_map_iff.1 h.2,
λ h, ⟨(algebra_map R A).injective, surjective_algebra_map_iff.2 h⟩⟩
/-- The bottom subalgebra is isomorphic to the base ring. -/
noncomputable def bot_equiv_of_injective (h : function.injective (algebra_map R A)) :
(⊥ : subalgebra R A) ≃ₐ[R] R :=
alg_equiv.symm $ alg_equiv.of_bijective (algebra.of_id R _)
⟨λ x y hxy, h (congr_arg subtype.val hxy : _),
λ ⟨y, hy⟩, let ⟨x, hx⟩ := algebra.mem_bot.1 hy in ⟨x, subtype.eq hx⟩⟩
/-- The bottom subalgebra is isomorphic to the field. -/
noncomputable def bot_equiv (F R : Type*) [field F] [semiring R] [nontrivial R] [algebra F R] :
(⊥ : subalgebra F R) ≃ₐ[F] F :=
bot_equiv_of_injective (ring_hom.injective _)
/-- The top subalgebra is isomorphic to the field. -/
noncomputable def top_equiv : (⊤ : subalgebra R A) ≃ₐ[R] A :=
(alg_equiv.of_bijective to_top ⟨λ _ _, subtype.mk.inj,
λ x, ⟨x.val, by { ext, refl }⟩⟩ : A ≃ₐ[R] (⊤ : subalgebra R A)).symm
end algebra
namespace subalgebra
open algebra
variables {R : Type u} {A : Type v} {B : Type w}
variables [comm_semiring R] [semiring A] [algebra R A] [semiring B] [algebra R B]
variables (S : subalgebra R A)
-- TODO[gh-6025]: make this an instance once safe to do so
lemma subsingleton_of_subsingleton [subsingleton A] : subsingleton (subalgebra R A) :=
⟨λ B C, ext (λ x, by { simp only [subsingleton.elim x 0, zero_mem] })⟩
-- TODO[gh-6025]: make this an instance once safe to do so
lemma alg_hom.subsingleton [subsingleton (subalgebra R A)] : subsingleton (A →ₐ[R] B) :=
⟨λ f g, alg_hom.ext $ λ a,
have a ∈ (⊥ : subalgebra R A) := subsingleton.elim (⊤ : subalgebra R A) ⊥ ▸ mem_top,
let ⟨x, hx⟩ := set.mem_range.mp (mem_bot.mp this) in
hx ▸ (f.commutes _).trans (g.commutes _).symm⟩
-- TODO[gh-6025]: make this an instance once safe to do so
lemma alg_equiv.subsingleton_left [subsingleton (subalgebra R A)] : subsingleton (A ≃ₐ[R] B) :=
begin
haveI : subsingleton (A →ₐ[R] B) := alg_hom.subsingleton,
exact ⟨λ f g, alg_equiv.ext
(λ x, alg_hom.ext_iff.mp (subsingleton.elim f.to_alg_hom g.to_alg_hom) x)⟩,
end
-- TODO[gh-6025]: make this an instance once safe to do so
lemma alg_equiv.subsingleton_right [subsingleton (subalgebra R B)] : subsingleton (A ≃ₐ[R] B) :=
begin
haveI : subsingleton (B ≃ₐ[R] A) := alg_equiv.subsingleton_left,
exact ⟨λ f g, eq.trans (alg_equiv.symm_symm _).symm
(by rw [subsingleton.elim f.symm g.symm, alg_equiv.symm_symm])⟩
end
lemma range_val : S.val.range = S :=
ext $ set.ext_iff.1 $ S.val.coe_range.trans subtype.range_val
instance : unique (subalgebra R R) :=
{ uniq :=
begin
intro S,
refine le_antisymm (λ r hr, _) bot_le,
simp only [set.mem_range, mem_bot, id.map_eq_self, exists_apply_eq_apply, default],
end
.. algebra.subalgebra.inhabited }
end subalgebra
section nat
variables {R : Type*} [semiring R]
/-- A subsemiring is a `ℕ`-subalgebra. -/
def subalgebra_of_subsemiring (S : subsemiring R) : subalgebra ℕ R :=
{ algebra_map_mem' := λ i, S.coe_nat_mem i,
.. S }
@[simp] lemma mem_subalgebra_of_subsemiring {x : R} {S : subsemiring R} :
x ∈ subalgebra_of_subsemiring S ↔ x ∈ S :=
iff.rfl
end nat
section int
variables {R : Type*} [ring R]
/-- A subring is a `ℤ`-subalgebra. -/
def subalgebra_of_subring (S : subring R) : subalgebra ℤ R :=
{ algebra_map_mem' := λ i, int.induction_on i S.zero_mem
(λ i ih, S.add_mem ih S.one_mem)
(λ i ih, show ((-i - 1 : ℤ) : R) ∈ S, by { rw [int.cast_sub, int.cast_one],
exact S.sub_mem ih S.one_mem }),
.. S }
/-- A subset closed under the ring operations is a `ℤ`-subalgebra. -/
def subalgebra_of_is_subring (S : set R) [is_subring S] : subalgebra ℤ R :=
subalgebra_of_subring S.to_subring
variables {S : Type*} [semiring S]
@[simp] lemma mem_subalgebra_of_subring {x : R} {S : subring R} :
x ∈ subalgebra_of_subring S ↔ x ∈ S :=
iff.rfl
@[simp] lemma mem_subalgebra_of_is_subring {x : R} {S : set R} [is_subring S] :
x ∈ subalgebra_of_is_subring S ↔ x ∈ S :=
iff.rfl
end int
|
0cc4f64deb027e964c5630ed4ddf6fcf22663ae2 | 67190c9aacc0cac64fb4463d93e84c696a5be896 | /Lists of exercises/List 8/Lista8-LucasDomingues.lean | bec4229d3439b18ed3a946fe6cf839e23c31b81a | [] | no_license | lucasresck/Discrete-Mathematics | ffbaf55943e7ce2c7bc50cef7e3ef66a0212f738 | 0a08081c5f393e5765259d3f1253c3a6dd043dac | refs/heads/master | 1,596,627,857,734 | 1,573,411,500,000 | 1,573,411,500,000 | 212,489,764 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 5,966 | lean | -- Estudante: Lucas Emanuel Resck Domingues
open nat
--1.a.
example : ∀ m n k : nat, m * (n + k) = m * n + m * k :=
assume m n k,
nat.rec_on k
(show m * (n + 0) = m * n + m * 0, from calc
m * (n + 0) = m * n : by rw add_zero
... = m * n + 0 : by rw add_zero
... = m * n + m * 0 : by rw mul_zero)
(assume p,
assume ih: m * (n + p) = m * n + m * p,
show m * (n + succ p) = m * n + m * (succ p), from
calc
m * (n + succ p) = m * (succ (n + p)) : by rw add_succ
... = m * (n + p) + m : by rw mul_succ
... = m * n + m * p + m : by rw ih
... = m * n + (m * p + m) : by rw add_assoc
... = m * n + m * (succ p) : by rw mul_succ)
--1.b.
example : ∀ n : nat, 0 * n = 0 :=
assume n,
nat.rec_on n
(show 0 * 0 = 0, from rfl)
(assume k,
assume ih : 0 * k = 0,
show 0 * (succ k) = 0, from
calc
0 * (succ k) = 0 * k + 0 : by rw mul_succ
... = 0 * k : by rw add_zero
... = 0 : by rw ih)
--1.c.
example : ∀ n : nat, 1 * n = n :=
assume n,
nat.rec_on n
(show 1 * 0 = 0, by rw mul_zero)
(assume k,
assume ih : 1 * k = k,
calc
1 * (succ k) = 1 * k + 1 : by rw mul_succ
... = k + 1 : by rw ih
... = succ k : rfl)
--1.d.
example : ∀ m n k : nat, (m * n) * k = m * (n * k) :=
assume m n k,
nat.rec_on k
(show (m * n) * 0 = m * (n * 0), from
calc
(m * n) * 0 = 0 : by rw mul_zero
... = m * 0 : by rw mul_zero
... = 0 * m : by rw mul_comm
... = (n * 0) * m : by rw mul_zero
... = m * (n * 0) : by rw mul_comm)
(assume i (ih : (m * n) * i = m * (n * i)),
show (m * n) * succ i = m * (n * succ i), from
begin
rw mul_succ,
rw ih,
rw ← left_distrib,
rw mul_succ
end)
--1.e.
example : ∀ m n : nat, m * n = n * m :=
assume m n,
nat.rec_on n
(begin
rw mul_zero,
apply eq.symm,
rw zero_mul
end)
(begin
intros k ih,
rw mul_succ,
rw ih,
rw succ_mul
end)
--2.a.
example : ∀ m n k : nat, n ≤ m → n + k ≤ m + k :=
assume m n k (h1 : n ≤ m),
show n + k ≤ m + k, from nat.rec_on k
h1
(begin
intros k' ih,
have h2, from succ_le_succ ih,
rw add_succ,
rw add_succ,
exact h2
end)
--2.b.
example : ∀ m n k : nat, n + k ≤ m + k → n ≤ m :=
begin
intros m n k,
apply nat.rec_on k,
intro h1,
exact h1,
intros k' h1 h2,
apply h1,
apply le_of_succ_le_succ,
rw ← add_succ,
rw ← add_succ,
exact h2
end
--2.c.
example : ∀ m n k : nat, n ≤ m → n * k ≤ m * k :=
assume m n k (h1 : n ≤ m),
nat.rec_on k
(le_refl 0)
(assume k' (ih : n * k' ≤ m * k'),
show n * succ k' ≤ m * succ k', from calc
n * succ k' = n * k' + n : by rw mul_succ
... ≤ m * k' + n : add_le_add_right ih n
... ≤ m * k' + m : add_le_add_left h1 (m * k')
... = m * succ k' : by rw mul_succ
)
--2.d.
example : ∀ m n : nat, m ≥ n → m = n ∨ m ≥ n + 1 :=
begin
intros m n,
apply nat.rec_on n,
intro h1,
apply classical.by_contradiction,
intro h2,
have h3 : ¬(m = 0) ∧ ¬(m ≥ 0 + 1), from
begin
apply and.intro,
intro h4,
have h5 : m = 0 ∨ m ≥ 0 + 1, from or.inl h4,
exact h2 h5,
intro h3,
have h4 : m = 0 ∨ m ≥ 0 + 1, from or.inr h3,
exact h2 h4
end,
cases h3 with h4 h5,
have h6 : m ≠ 0, from h4,
have h7 : 0 ≤ m, from h1,
apply h5,
have h8 : 0 < m, from nat.lt_of_le_and_ne h7 h6.symm,
apply le_of_lt_succ,
apply succ_lt_succ,
exact h8,
intros k ih h1,
apply classical.by_contradiction,
intro h2,
have h3 : ¬(m = succ k) ∧ ¬(m ≥ succ k + 1), from
begin
apply and.intro,
intro h4,
have h5 : m = succ k ∨ m ≥ succ k + 1, from or.inl h4,
exact h2 h5,
intro h3,
have h4 : m = succ k ∨ m ≥ succ k + 1, from or.inr h3,
exact h2 h4
end,
cases h3 with h4 h5,
have h6 : m ≠ succ k, from h4,
have h7 : succ k ≤ m, from h1,
apply h5,
have h8 : succ k < m, from nat.lt_of_le_and_ne h7 h6.symm,
apply le_of_lt_succ,
apply succ_lt_succ,
exact h8
end
--2.e.
example : ∀ n : nat, 0 ≤ n :=
begin
intro n,
apply nat.rec_on n,
exact zero_le 0,
intros k ih,
have h1 : k ≤ succ k, from le_succ k,
exact le_trans ih h1
end
|
800b612c3062ec14a7db54c0d38b4b727516c03b | 302c785c90d40ad3d6be43d33bc6a558354cc2cf | /src/category_theory/with_terminal.lean | f56baf302a2bb80417c3309e71dd42e4c2f9d810 | [
"Apache-2.0"
] | permissive | ilitzroth/mathlib | ea647e67f1fdfd19a0f7bdc5504e8acec6180011 | 5254ef14e3465f6504306132fe3ba9cec9ffff16 | refs/heads/master | 1,680,086,661,182 | 1,617,715,647,000 | 1,617,715,647,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 11,899 | lean | /-
Copyright (c) 2021 Adam Topaz. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Adam Topaz
-/
import category_theory.limits.shapes.terminal
/-!
# `with_initial` and `with_terminal`
Given a category `C`, this file constructs two objects:
1. `with_terminal C`, the category built from `C` by formally adjoining a terminal object.
2. `with_initial C`, the category built from `C` by formally adjoining an initial object.
The terminal resp. initial object is `with_terminal.star` resp. `with_initial.star`, and
the proofs that these are terminal resp. initial are in `with_terminal.star_terminal`
and `with_initial.star_initial`.
The inclusion from `C` intro `with_terminal C` resp. `with_initial C` is denoted
`with_terminal.incl` resp. `with_initial.incl`.
The relevant constructions needed for the universal properties of these constructions are:
1. `lift`, which lifts `F : C ⥤ D` to a functor from `with_terminal C` resp. `with_initial C` in
the case where an object `Z : D` is provided satisfying some additional conditions.
2. `incl_lift` shows that the composition of `lift` with `incl` is isomorphic to the
functor which was lifted.
3. `lift_unique` provides the uniqueness property of `lift`.
In addition to this, we provide `with_terminal.map` and `with_initinal.map` providing the
functoriality of these constructions with respect to functors on the base categories.
-/
namespace category_theory
universes v u
variables (C : Type u) [category.{v} C]
/-- Formally adjoin a terminal object to a category. -/
@[derive inhabited]
inductive with_terminal : Type u
| of : C → with_terminal
| star : with_terminal
/-- Formally adjoin an initial object to a category. -/
@[derive inhabited]
inductive with_initial : Type u
| of : C → with_initial
| star : with_initial
namespace with_terminal
local attribute [tidy] tactic.case_bash
variable {C}
/-- Morphisms for `with_terminal C`. -/
@[simp, nolint has_inhabited_instance]
def hom : with_terminal C → with_terminal C → Type v
| (of X) (of Y) := X ⟶ Y
| star (of X) := pempty
| _ star := punit
/-- Identity morphisms for `with_terminal C`. -/
@[simp]
def id : Π (X : with_terminal C), hom X X
| (of X) := 𝟙 _
| star := punit.star
/-- Composition of morphisms for `with_terminal C`. -/
@[simp]
def comp : Π {X Y Z : with_terminal C}, hom X Y → hom Y Z → hom X Z
| (of X) (of Y) (of Z) := λ f g, f ≫ g
| (of X) _ star := λ f g, punit.star
| star (of X) _ := λ f g, pempty.elim f
| _ star (of Y) := λ f g, pempty.elim g
| star star star := λ _ _, punit.star
instance : category.{v} (with_terminal C) :=
{ hom := λ X Y, hom X Y,
id := λ X, id _,
comp := λ X Y Z f g, comp f g }
/-- The inclusion from `C` into `with_terminal C`. -/
def incl : C ⥤ (with_terminal C) :=
{ obj := of,
map := λ X Y f, f }
instance : full (incl : C ⥤ _) :=
{ preimage := λ X Y f, f }
instance : faithful (incl : C ⥤ _) := {}
/-- Map `with_terminal` with respect to a functor `F : C ⥤ D`. -/
def map {D : Type*} [category D] (F : C ⥤ D) : with_terminal C ⥤ with_terminal D :=
{ obj := λ X,
match X with
| of x := of $ F.obj x
| star := star
end,
map := λ X Y f,
match X, Y, f with
| of x, of y, f := F.map f
| of x, star, punit.star := punit.star
| star, star, punit.star := punit.star
end }
instance {X : with_terminal C} : unique (X ⟶ star) :=
{ default :=
match X with
| of x := punit.star
| star := punit.star
end,
uniq := by tidy }
/-- `with_terminal.star` is terminal. -/
def star_terminal : limits.is_terminal (star : with_terminal C) :=
limits.is_terminal.of_unique _
/-- Lift a functor `F : C ⥤ D` to `with_term C ⥤ D`. -/
@[simps]
def lift {D : Type*} [category D] {Z : D} (F : C ⥤ D) (M : Π (x : C), F.obj x ⟶ Z)
(hM : ∀ (x y : C) (f : x ⟶ y), F.map f ≫ M y = M x) :
(with_terminal C) ⥤ D :=
{ obj := λ X,
match X with
| of x := F.obj x
| star := Z
end,
map := λ X Y f,
match X, Y, f with
| of x, of y, f := F.map f
| of x, star, punit.star := M x
| star, star, punit.star := 𝟙 Z
end }
/-- The isomorphism between `incl ⋙ lift F _ _` with `F`. -/
@[simps]
def incl_lift {D : Type*} [category D] {Z : D} (F : C ⥤ D) (M : Π (x : C), F.obj x ⟶ Z)
(hM : ∀ (x y : C) (f : x ⟶ y), F.map f ≫ M y = M x) :
incl ⋙ lift F M hM ≅ F :=
{ hom := { app := λ X, 𝟙 _ },
inv := { app := λ X, 𝟙 _ } }
/-- The isomorphism between `(lift F _ _).obj with_terminal.star` with `Z`. -/
@[simps]
def lift_star {D : Type*} [category D] {Z : D} (F : C ⥤ D) (M : Π (x : C), F.obj x ⟶ Z)
(hM : ∀ (x y : C) (f : x ⟶ y), F.map f ≫ M y = M x) :
(lift F M hM).obj star ≅ Z := eq_to_iso rfl
lemma lift_map_lift_star {D : Type*} [category D] {Z : D} (F : C ⥤ D) (M : Π (x : C), F.obj x ⟶ Z)
(hM : ∀ (x y : C) (f : x ⟶ y), F.map f ≫ M y = M x) (x : C) :
(lift F M hM).map (star_terminal.from (incl.obj x)) ≫ (lift_star F M hM).hom =
(incl_lift F M hM).hom.app x ≫ M x :=
begin
erw [category.id_comp, category.comp_id],
refl,
end
/-- The uniqueness of `lift`. -/
@[simp]
def lift_unique {D : Type*} [category D] {Z : D} (F : C ⥤ D)
(M : Π (x : C), F.obj x ⟶ Z) (hM : ∀ (x y : C) (f : x ⟶ y), F.map f ≫ M y = M x)
(G : with_terminal C ⥤ D) (h : incl ⋙ G ≅ F) (hG : G.obj star ≅ Z)
(hh : ∀ x : C, G.map (star_terminal.from (incl.obj x)) ≫ hG.hom = h.hom.app x ≫ M x) :
G ≅ lift F M hM :=
nat_iso.of_components (λ X,
match X with
| of x := h.app x
| star := hG
end)
begin
rintro (X|X) (Y|Y) f,
{ apply h.hom.naturality },
{ cases f, exact hh _ },
{ cases f, },
{ cases f,
change G.map (𝟙 _) ≫ hG.hom = hG.hom ≫ 𝟙 _,
simp }
end
/-- A variant of `lift` with `Z` a terminal object. -/
@[simps]
def lift_to_terminal {D : Type*} [category D] {Z : D} (F : C ⥤ D) (hZ : limits.is_terminal Z) :
with_terminal C ⥤ D :=
lift F (λ x, hZ.from _) (λ x y f, hZ.hom_ext _ _)
/-- A variant of `incl_lift` with `Z` a terminal object. -/
@[simps]
def incl_lift_to_terminal {D : Type*} [category D] {Z : D} (F : C ⥤ D) (hZ : limits.is_terminal Z) :
incl ⋙ lift_to_terminal F hZ ≅ F := incl_lift _ _ _
/-- A variant of `lift_unique` with `Z` a terminal object. -/
@[simps]
def lift_to_terminal_unique {D : Type*} [category D] {Z : D} (F : C ⥤ D) (hZ : limits.is_terminal Z)
(G : with_terminal C ⥤ D) (h : incl ⋙ G ≅ F) (hG : G.obj star ≅ Z) :
G ≅ lift_to_terminal F hZ :=
lift_unique F (λ z, hZ.from _) (λ x y f, hZ.hom_ext _ _) G h hG (λ x, hZ.hom_ext _ _)
/-- Constructs a morphism to `star` from `of X`. -/
@[simp]
def hom_from (X : C) : incl.obj X ⟶ star := star_terminal.from _
end with_terminal
namespace with_initial
local attribute [tidy] tactic.case_bash
variable {C}
/-- Morphisms for `with_initial C`. -/
@[simp, nolint has_inhabited_instance]
def hom : with_initial C → with_initial C → Type v
| (of X) (of Y) := X ⟶ Y
| (of X) _ := pempty
| star _ := punit
/-- Identity morphisms for `with_initial C`. -/
@[simp]
def id : Π (X : with_initial C), hom X X
| (of X) := 𝟙 _
| star := punit.star
/-- Composition of morphisms for `with_initial C`. -/
@[simp]
def comp : Π {X Y Z : with_initial C}, hom X Y → hom Y Z → hom X Z
| (of X) (of Y) (of Z) := λ f g, f ≫ g
| star _ (of X) := λ f g, punit.star
| _ (of X) star := λ f g, pempty.elim g
| (of Y) star _ := λ f g, pempty.elim f
| star star star := λ _ _, punit.star
instance : category.{v} (with_initial C) :=
{ hom := λ X Y, hom X Y,
id := λ X, id _,
comp := λ X Y Z f g, comp f g }
/-- The inclusion of `C` into `with_initial C`. -/
def incl : C ⥤ (with_initial C) :=
{ obj := of,
map := λ X Y f, f }
instance : full (incl : C ⥤ _) :=
{ preimage := λ X Y f, f }
instance : faithful (incl : C ⥤ _) := {}
/-- Map `with_initial` with respect to a functor `F : C ⥤ D`. -/
def map {D : Type*} [category D] (F : C ⥤ D) : with_initial C ⥤ with_initial D :=
{ obj := λ X,
match X with
| of x := of $ F.obj x
| star := star
end,
map := λ X Y f,
match X, Y, f with
| of x, of y, f := F.map f
| star, of x, punit.star := punit.star
| star, star, punit.star := punit.star
end }
instance {X : with_initial C} : unique (star ⟶ X) :=
{ default :=
match X with
| of x := punit.star
| star := punit.star
end,
uniq := by tidy }
/-- `with_initial.star` is initial. -/
def star_initial : limits.is_initial (star : with_initial C) :=
limits.is_initial.of_unique _
/-- Lift a functor `F : C ⥤ D` to `with_initial C ⥤ D`. -/
@[simps]
def lift {D : Type*} [category D] {Z : D} (F : C ⥤ D) (M : Π (x : C), Z ⟶ F.obj x)
(hM : ∀ (x y : C) (f : x ⟶ y), M x ≫ F.map f = M y) :
(with_initial C) ⥤ D :=
{ obj := λ X,
match X with
| of x := F.obj x
| star := Z
end,
map := λ X Y f,
match X, Y, f with
| of x, of y, f := F.map f
| star, of x, punit.star := M _
| star, star, punit.star := 𝟙 _
end }
/-- The isomorphism between `incl ⋙ lift F _ _` with `F`. -/
@[simps]
def incl_lift {D : Type*} [category D] {Z : D} (F : C ⥤ D)
(M : Π (x : C), Z ⟶ F.obj x) (hM : ∀ (x y : C) (f : x ⟶ y), M x ≫ F.map f = M y) :
incl ⋙ lift F M hM ≅ F :=
{ hom := { app := λ X, 𝟙 _ },
inv := { app := λ X, 𝟙 _ } }
/-- The isomorphism between `(lift F _ _).obj with_term.star` with `Z`. -/
@[simps]
def lift_star {D : Type*} [category D] {Z : D} (F : C ⥤ D)
(M : Π (x : C), Z ⟶ F.obj x) (hM : ∀ (x y : C) (f : x ⟶ y), M x ≫ F.map f = M y) :
(lift F M hM).obj star ≅ Z := eq_to_iso rfl
lemma lift_star_lift_map {D : Type*} [category D] {Z : D} (F : C ⥤ D)
(M : Π (x : C), Z ⟶ F.obj x) (hM : ∀ (x y : C) (f : x ⟶ y), M x ≫ F.map f = M y) (x : C) :
(lift_star F M hM).hom ≫ (lift F M hM).map (star_initial.to (incl.obj x)) =
M x ≫ (incl_lift F M hM).hom.app x :=
begin
erw [category.id_comp, category.comp_id],
refl,
end
/-- The uniqueness of `lift`. -/
@[simp]
def lift_unique {D : Type*} [category D] {Z : D} (F : C ⥤ D)
(M : Π (x : C), Z ⟶ F.obj x) (hM : ∀ (x y : C) (f : x ⟶ y), M x ≫ F.map f = M y)
(G : with_initial C ⥤ D) (h : incl ⋙ G ≅ F) (hG : G.obj star ≅ Z)
(hh : ∀ x : C, hG.symm.hom ≫ G.map (star_initial.to (incl.obj x)) = M x ≫ h.symm.hom.app x) :
G ≅ lift F M hM :=
nat_iso.of_components
(λ X,
match X with
| of x := h.app x
| star := hG
end)
begin
rintro (X|X) (Y|Y) f,
{ apply h.hom.naturality },
{ cases f, },
{ cases f,
change G.map _ ≫ h.hom.app _ = hG.hom ≫ _,
symmetry,
erw [← iso.eq_inv_comp, ← category.assoc, hh],
simpa },
{ cases f,
change G.map (𝟙 _) ≫ hG.hom = hG.hom ≫ 𝟙 _,
simp }
end
/-- A variant of `lift` with `Z` an initial object. -/
@[simps]
def lift_to_initial {D : Type*} [category D] {Z : D} (F : C ⥤ D) (hZ : limits.is_initial Z) :
with_initial C ⥤ D :=
lift F (λ x, hZ.to _) (λ x y f, hZ.hom_ext _ _)
/-- A variant of `incl_lift` with `Z` an initial object. -/
@[simps]
def incl_lift_to_initial {D : Type*} [category D] {Z : D} (F : C ⥤ D) (hZ : limits.is_initial Z) :
incl ⋙ lift_to_initial F hZ ≅ F := incl_lift _ _ _
/-- A variant of `lift_unique` with `Z` an initial object. -/
@[simps]
def lift_to_initial_unique {D : Type*} [category D] {Z : D} (F : C ⥤ D) (hZ : limits.is_initial Z)
(G : with_initial C ⥤ D) (h : incl ⋙ G ≅ F) (hG : G.obj star ≅ Z) :
G ≅ lift_to_initial F hZ :=
lift_unique F (λ z, hZ.to _) (λ x y f, hZ.hom_ext _ _) G h hG (λ x, hZ.hom_ext _ _)
/-- Constructs a morphism from `star` to `of X`. -/
@[simp]
def hom_to (X : C) : star ⟶ incl.obj X := star_initial.to _
end with_initial
end category_theory
|
6522aef6c23ca5335e5b29b1e1471783e55a5ad2 | 865fccc998322821ec90764a00c06aa38e8f371a | /monotone.lean | 51411184804095b8f9d64e099b6a0ff68fbf41d4 | [] | no_license | semorrison/lean-monotone-class | 2601316f7281dd398ef629e50ba34a760d2a632b | 312f8628ce2872f647ee42398dbf38d9ebf65493 | refs/heads/master | 1,627,247,514,511 | 1,510,001,892,000 | 1,510,001,892,000 | 103,790,048 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 15,372 | lean | import tidy.tidy
import data.set
open set
structure boolean_algebra ( α : Type ) :=
( contains : set (set α) )
( contains_universe : contains univ )
( complements : ∀ { s : set α }, contains s → contains (compl s) )
( unions : ∀ { s t : set α }, contains s → contains t → contains (s ∪ t) )
definition intersection_of_boolean_algebras { α β : Type } ( algebras : α → boolean_algebra β ) : boolean_algebra β :=
{
contains := λ s, ∀ a : α, (algebras a).contains s,
contains_universe := begin intro a, exact (algebras a).contains_universe, end,
complements := begin intro s, intro f, intro a, exact (algebras a).complements (f a) end,
unions := begin intros s t, intros f g, intro a, exact (algebras a).unions (f a) (g a) end
}
definition boolean_algebra_coarser { α } ( B C : boolean_algebra α ) := C.contains ⊆ B.contains
structure boolean_algebra_containing { α } ( X : set (set α) ) :=
( algebra : boolean_algebra α )
( containing : ∀ s ∈ X, algebra.contains s )
definition coarsest_boolean_algebra_containing { α } ( X : set (set α) ) : boolean_algebra α :=
intersection_of_boolean_algebras (@boolean_algebra_containing.algebra _ X)
definition countable_union { α : Type } (f : ℕ → set α) : set α := (λ a : α, ∃ n : ℕ, a ∈ (f n))
definition countable_intersection { α : Type } (f : ℕ → set α) : set α := (λ a : α, ∀ n : ℕ, a ∈ (f n))
lemma complement_of_countable_union_as_countable_intersection { α } (f: ℕ → set α) : compl (countable_union f) = countable_intersection (compl ∘ f) :=
begin
unfold countable_union countable_intersection set.compl,
apply funext,
intros x,
dsimp',
unfold set.mem set.compl,
dsimp',
apply propext,
split,
{
intros,
exact a ⟨ n, a_1 ⟩,
},
{
intros,
apply exists.elim a_1 a,
}
end
lemma countable_union_of_complements_as_subset { α } (f: ℕ → set α) : countable_union (compl ∘ f) ⊆ compl (countable_intersection f) :=
begin
unfold countable_union countable_intersection set.compl,
intros x,
dsimp',
unfold set.mem set.compl,
dsimp',
intros,
have p : ∀ n, ((f n x) → false) → false,
intros n,
exact non_contradictory_intro (a_1 n),
apply exists.elim a p,
end
structure sigma_algebra ( α : Type ) extends boolean_algebra α :=
( countable_unions : ∀ { f : ℕ → set α }, (Π n : ℕ, contains (f n)) → contains (countable_union f) )
( countable_intersections : ∀ { f : ℕ → set α }, (Π n : ℕ, contains (f n)) → contains (countable_intersection f) )
-- It requires classical logic, apparently, to deduce countable intersections from countable unions.
structure is_sigma_algebra { α } ( contains : set (set α ) ) :=
( sigma_algebra : sigma_algebra α )
( witness : sigma_algebra.contains = contains )
definition intersection_of_sigma_algebras { α β : Type } ( algebras : α → sigma_algebra β ) : sigma_algebra β :=
{ @intersection_of_boolean_algebras α β (λ a, (algebras a).to_boolean_algebra) with
countable_unions := begin
intros s w,
intro a,
tidy,
let v := λ n, w n a,
exact (algebras a).countable_unions v,
end,
countable_intersections := begin
intros s w,
intro a,
tidy,
let v := λ n, w n a,
exact (algebras a).countable_intersections v,
end
}
structure sigma_algebra_containing { α } ( X : set (set α) ) :=
( algebra : sigma_algebra α )
( containing : ∀ s ∈ X, algebra.contains s )
definition coarsest_sigma_algebra_containing { α } ( X : set (set α) ) : sigma_algebra α :=
intersection_of_sigma_algebras (@sigma_algebra_containing.algebra _ X)
lemma coarsest_sigma_algebra_contains_generators { α } ( X : set (set α) ) : X ⊆ (coarsest_sigma_algebra_containing X).contains :=
begin
tidy,
unfold set.subset,
tidy,
unfold set.mem,
tidy,
have p := a_2.containing a a_1,
tidy
end
lemma sigma_algebra_containing_contains_coarsest_sigma_algebra_containing
{ α }
( X : set (set α) )
( m : sigma_algebra α )
( w : X ⊆ m.contains )
: (coarsest_sigma_algebra_containing X).contains ⊆ m.contains :=
begin
tidy,
unfold set.subset,
intros Y,
intros p,
tidy,
unfold set.mem at p,
let c : sigma_algebra_containing X := ⟨ m, ♯ ⟩,
let q := p c,
tidy,
end
structure decreasing_sequence ( α : Type ) :=
( sets : ℕ → set α )
( decreasing : ∀ n : ℕ, (sets (n+1)) ⊆ (sets n) )
attribute [applicable] decreasing_sequence.decreasing
definition countable_decreasing_intersection { α } ( f: decreasing_sequence α ) : set α := countable_intersection f.sets
structure increasing_sequence ( α : Type ) :=
( sets : ℕ → set α )
( increasing : ∀ n : ℕ, (sets n) ⊆ (sets (n+1)) )
attribute [applicable] increasing_sequence.increasing
definition countable_increasing_union { α } ( f: increasing_sequence α ) : set α := countable_union f.sets
@[applicable] lemma compl_subset_compl { α } ( X Y : set α ) ( p : Y ⊆ X ) : (-X) ⊆ (-Y) :=
begin
tidy,
unfold set.subset,
unfold set.subset at p,
intros,
unfold set.compl,
unfold set.compl at a_1,
tidy,
unfold set.mem,
unfold set.mem at a_1,
intros,
exact a_1 (p a_2),
end
def complement_decreasing_sequence { α } ( f : decreasing_sequence α ) : increasing_sequence α :=
{
sets := λ n, -(f.sets n),
increasing := ♯
}
def complement_increasing_sequence { α } ( f : increasing_sequence α ) : decreasing_sequence α :=
{
sets := λ n, -(f.sets n),
decreasing := ♯
}
lemma complement_decreasing_intersection { α } ( f: decreasing_sequence α ) : -(countable_decreasing_intersection f) = countable_increasing_union (complement_decreasing_sequence f) :=
begin
tidy,
unfold compl,
unfold complement_decreasing_sequence,
unfold countable_decreasing_intersection,
unfold countable_increasing_union,
unfold countable_intersection,
unfold countable_union,
tidy,
unfold set.mem,
unfold compl,
tidy,
admit
end
lemma complement_increasing_union { α } ( f: increasing_sequence α ) : -(countable_increasing_union f) = countable_decreasing_intersection (complement_increasing_sequence f) := sorry
structure monotone_class ( α : Type ) :=
( contains : set (set α) )
( countable_decreasing_intersections : ∀ f : decreasing_sequence α, (Π n : ℕ, contains (f.sets n)) → contains (countable_decreasing_intersection f))
( countable_increasing_unions : ∀ f : increasing_sequence α, (Π n : ℕ, contains (f.sets n)) → contains (countable_increasing_union f))
instance { α } : has_subset (monotone_class α) := {
subset := λ m n, m.contains ⊆ n.contains
}
@[applicable] lemma monotone_class.equality { α } { m n : monotone_class α } ( p : m.contains = n.contains ) : m = n :=
begin
cases m,
cases n,
tidy,
end
@[applicable] lemma monotone_class.antisymmetry { α } { m n : monotone_class α } ( p : m ⊆ n ) ( q : n ⊆ m ) : m = n :=
begin
apply monotone_class.equality,
apply subset.antisymm,
exact p,
exact q,
end
structure is_monotone_class { α } ( contains : set (set α ) ) :=
( monotone_class : monotone_class α )
( witness : monotone_class.contains = contains )
definition intersection_of_monotone_classes { α β : Type } ( classes : α → monotone_class β ) : monotone_class β :=
{
contains := λ s, ∀ a : α, (classes a).contains s,
countable_decreasing_intersections := begin
intros f w a,
let v := λ n, w n a,
exact (classes a).countable_decreasing_intersections f v,
end,
countable_increasing_unions := begin
intros f w a,
let v := λ n, w n a,
exact (classes a).countable_increasing_unions f v,
end
}
@[reducible] definition monotone_class.intersect { α : Type } ( m n : monotone_class α ) : monotone_class α :=
{
contains := λ s, m.contains s ∧ n.contains s,
countable_decreasing_intersections := begin
intros,
split,
let v := λ n, (a n).left,
exact m.countable_decreasing_intersections f v,
let w := λ n, (a n).right,
exact n.countable_decreasing_intersections f w,
end,
countable_increasing_unions := begin
intros,
split,
let v := λ n, (a n).left,
exact m.countable_increasing_unions f v,
let w := λ n, (a n).right,
exact n.countable_increasing_unions f w,
end
}
instance { α } : has_inter (monotone_class α) := {
inter := monotone_class.intersect
}
structure monotone_class_containing { α } ( X : set (set α) ) :=
( monotone_class : monotone_class α )
( containing : ∀ s ∈ X, monotone_class.contains s )
definition coarsest_monotone_class_containing { α } ( X : set (set α) ) : monotone_class α :=
intersection_of_monotone_classes (@monotone_class_containing.monotone_class _ X)
lemma coarsest_monotone_class_contains_generators { α } ( X : set (set α) ) : X ⊆ (coarsest_monotone_class_containing X).contains :=
begin
tidy,
unfold set.subset,
tidy,
unfold set.mem,
tidy,
have p := a_2.containing a a_1,
tidy
end
lemma monotone_class_containing_contains_coarsest_monotone_class_containing
{ α }
( X : set (set α) )
( m : monotone_class α )
( w : X ⊆ m.contains )
: (coarsest_monotone_class_containing X).contains ⊆ m.contains :=
begin
tidy,
unfold set.subset,
intros Y,
intros p,
tidy,
unfold set.mem at p,
let c : monotone_class_containing X := ⟨ m, ♯ ⟩,
let q := p c,
tidy,
end
@[reducible] definition monotone_class.complement { α } ( M : monotone_class α ) : monotone_class α := {
contains := λ s, M.contains (- s),
countable_decreasing_intersections := begin
intros f w,
rewrite complement_decreasing_intersection,
apply M.countable_increasing_unions,
unfold complement_decreasing_sequence,
tidy,
end,
countable_increasing_unions := begin
intros f w,
rewrite complement_increasing_union,
apply M.countable_decreasing_intersections,
unfold complement_increasing_sequence,
tidy,
end
}
lemma monotone_class_generated_by_a_boolean_algebra_equals_its_complement { α } ( B : boolean_algebra α ) : (coarsest_monotone_class_containing B.contains).contains = (coarsest_monotone_class_containing B.contains).complement.contains :=
begin
let C := coarsest_monotone_class_containing (B.contains),
let D := C ∩ (C.complement),
have p : D ⊆ C, {
tidy,
unfold set.mem,
unfold set.mem at a_1,
tidy,
exact (a_1.left a_2)
},
have q : B.contains ⊆ D.contains, {
tidy,
unfold set.mem,
tidy,
exact a_2.containing a a_1,
exact a_2.containing (compl a) (B.complements a_1),
},
have r : C ⊆ D, {
admit,
},
have s : C = D, { },
admit
end
lemma monotone_class_generated_by_a_boolean_algebra_is_a_sigma_algebra
{ α }
( B : boolean_algebra α )
: is_sigma_algebra (coarsest_monotone_class_containing B.contains).contains :=
begin
fsplit,
fsplit,
fsplit,
{
-- first we specify the underlying family of sets
exact (coarsest_monotone_class_containing B.contains).contains,
},
{
-- the universe is in the monotone class because it is in the boolean algebra
apply coarsest_monotone_class_contains_generators,
exact B.contains_universe,
},
{
-- contains complements?
admit,
},
admit,
admit,
admit,
admit,
end
lemma sigma_algebra_generated_by_a_boolean_algebra_is_a_monotone_class
{ α }
( B : boolean_algebra α )
: is_monotone_class (coarsest_sigma_algebra_containing B.contains).contains :=
begin
let M := coarsest_sigma_algebra_containing B.contains,
fsplit,
fsplit,
{
exact M.contains,
},
{
-- decreasing intersections
have c := M.countable_intersections,
intros f n w,
exact c n w,
},
{
-- increasing unions
have c := M.countable_unions,
intros f n w,
exact c n w,
},
tidy,
end
private lemma monotone_class_generated_by_a_boolean_algebra_as_a_sigma_algebra { α } ( B : boolean_algebra α ) : (coarsest_monotone_class_containing (B.contains)).contains = (monotone_class_generated_by_a_boolean_algebra_is_a_sigma_algebra B).sigma_algebra.contains :=
begin
rewrite (monotone_class_generated_by_a_boolean_algebra_is_a_sigma_algebra B).witness,
end
private lemma sigma_algebra_generated_by_a_boolean_algebra_as_a_monotone_class { α } ( B : boolean_algebra α ) : (coarsest_sigma_algebra_containing (B.contains)).contains = (sigma_algebra_generated_by_a_boolean_algebra_is_a_monotone_class B).monotone_class.contains :=
begin
rewrite (sigma_algebra_generated_by_a_boolean_algebra_is_a_monotone_class B).witness,
end
theorem monotone_class_lemma
{ α }
( B : boolean_algebra α )
: (coarsest_sigma_algebra_containing B.contains).contains = (coarsest_monotone_class_containing B.contains).contains :=
begin
apply subset.antisymm,
{
rewrite monotone_class_generated_by_a_boolean_algebra_as_a_sigma_algebra,
-- FIXME why does unification fail without specifying arguments?
apply sigma_algebra_containing_contains_coarsest_sigma_algebra_containing
B.contains
((monotone_class_generated_by_a_boolean_algebra_is_a_sigma_algebra B).sigma_algebra),
rewrite ← monotone_class_generated_by_a_boolean_algebra_as_a_sigma_algebra,
apply coarsest_monotone_class_contains_generators B.contains
},
{
rewrite sigma_algebra_generated_by_a_boolean_algebra_as_a_monotone_class,
-- FIXME
apply monotone_class_containing_contains_coarsest_monotone_class_containing
B.contains
((sigma_algebra_generated_by_a_boolean_algebra_is_a_monotone_class B).monotone_class),
rewrite ← sigma_algebra_generated_by_a_boolean_algebra_as_a_monotone_class,
apply coarsest_sigma_algebra_contains_generators B.contains
}
end |
3571f0cbda4e4de19b7bd9ad5c72acea7b4975d7 | caa1512363b76923d0e9cdb716122a5c26c3c6bc | /src/LP.lean | d38e8b8a2c2268e116bdfc763c92fe57d10da273 | [] | no_license | apurvanakade/cvx | deb20e425ce478159a98e1ffc0d37f9c88a89280 | b47784831339df5a3e45f5cddd84edc545f95808 | refs/heads/master | 1,687,403,288,536 | 1,555,930,740,000 | 1,555,930,740,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 4,075 | lean | import .NN .misc system.io
variables {α : Type} [has_mul α] [add_comm_monoid α] [has_le α]
variables {k m n : nat}
structure LP (α : Type) (m n : nat) :=
(obf : N α)
(lhs : NN α)
(rhs : N α)
def LP.feasible : LP α m n → N α → Prop
| ⟨m, n, c, A, b⟩ x := N.le m (mul_vec n A x) b ∧ (N.le n (N.zero α) x)
def LP.is_feasible (P : LP α m n) : Prop :=
∃ x : N α, P.feasible x
instance LP.feasible.decidable [decidable_rel ((≤) : α → α → Prop)]
(P : LP α m n) (x : N α) : decidable (P.feasible x) :=
by {cases P, unfold LP.feasible, apply_instance }
open tactic
meta def Nx.repr (vx : expr) : nat → tactic string
| 0 := return ""
| (k + 1) :=
do vs ← Nx.repr k,
a ← to_expr ``(%%vx %%`(k)) >>= eval_expr rat,
return $ string.join [vs, " ", a.repr]
meta def NNx.repr_aux (Ax : expr) : nat → nat → tactic string
| 0 n := return ""
| (m + 1) n :=
do vs ← NNx.repr_aux m n,
a ← to_expr ``(%%Ax %%`(m) %%`(n)) >>= eval_expr rat,
return $ string.join [vs, " ", a.repr]
meta def NNx.repr (Ax : expr) (m : nat) : nat → tactic string
| 0 := return ""
| 1 := NNx.repr_aux Ax m 0
| (n + 1) :=
do As ← NNx.repr n,
vs ← NNx.repr_aux Ax m n,
return $ string.join [As, "\n", vs]
meta def put_LP : tactic (string × string × string) :=
do `((⟨_, _, %%cx, %%Ax, %%bx⟩ : LP rat %%mx %%nx).is_feasible) ← target,
m ← eval_expr nat mx,
n ← eval_expr nat nx,
cs ← Nx.repr cx n,
As ← NNx.repr Ax m n,
bs ← Nx.repr bx m,
return ⟨cs, As, bs⟩
open tactic
meta instance int.has_reflect : has_reflect ℤ := by tactic.mk_has_reflect_instance
meta def rat.has_reflect' : Π x : ℚ, Σ y : ℚ, Σ' h : x = y, reflected y
| ⟨x,y,h,h'⟩ := ⟨rat.mk_nat x y, by { rw [rat.num_denom',rat.mk_nat_eq] } , `(_)⟩
meta instance : has_reflect ℚ
| x :=
match rat.has_reflect' x with
| ⟨ ._, rfl, h ⟩ := h
end
meta def cvxopt_lp (cs As bs : string) : tactic string :=
unsafe_run_io $
io.cmd {
cmd := "python",
args := ["lp.py", cs, As, bs],
/- Change this parameter to location of lp.py-/
cwd := "/home/sk/Projects/cvx/src"
}
open parser
def digits : list char :=
[ '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' ]
def parser_digits : parser string := many_char (one_of digits)
def parser_sign : parser bool :=
(ch '+' >> return tt) <|> (ch '-' >> return ff) <|> (return tt)
def parser_dnat : parser string :=
do d ← one_of digits,
ch '.',
ds ← parser_digits,
return ⟨d::ds.data⟩
def drop_zeroes : string → string := string.drop_chars '0'
def drop_trailing_nl (s : string) : string :=
(s.reverse.drop_chars '\n').reverse
def parser_mantissa : parser rat :=
do b ← parser_sign,
ds ← parser_dnat,
let i := int.of_nat (drop_zeroes ds).to_nat,
let numer : int := if b then i else -i,
let denom : nat := 10 ^ ds.length.pred,
return (rat.mk_nat numer denom)
def parser_magnitude : parser rat :=
do b ← parser_sign,
ds ← parser_digits,
let m : nat := 10 ^ (drop_zeroes ds).to_nat,
return (if b then (rat.mk_nat m 1) else (rat.mk_nat 1 m))
def parser_scinot : parser rat :=
do r ← parser_mantissa,
ch 'e',
s ← parser_magnitude,
return (r * s)
def ws : parser unit := many' (ch ' ')
def parser_entry : parser rat :=
ch '[' *> ws *> parser_scinot <* ws <* ch ']'
def parser_vector : parser (list rat) :=
sep_by (ch '\n') parser_entry
meta def LP.show_is_feasible : tactic unit :=
do ⟨cs, As, bs⟩ ← put_LP,
vs ← cvxopt_lp cs As bs,
match run_string parser_vector (drop_trailing_nl vs) with
| (sum.inl _) := fail "Cannot parse vector"
| (sum.inr rs) :=
do vx ← to_expr ``(@N.of_list rat _ %%`(rs)),
existsi vx,
exact_dec_trivial
end
def ex_c : N rat := N.of_list [2, 1]
def ex_A : NN rat := NN.of_lists rat [[-1, 1], [-1, -1], [0, -1], [1, -2]]
def ex_b : N rat := N.of_list [1, -2, 0, 4]
example : LP.is_feasible ⟨4, 2, ex_c, ex_A, ex_b⟩ :=
by LP.show_is_feasible |
4fd664367586b94053cb084e1e5e46500850c3d8 | 30b012bb72d640ec30c8fdd4c45fdfa67beb012c | /algebra/group.lean | e16ef6efa3b2d399584839d1d460f45c59b9e4be | [
"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 | 27,669 | lean | /-
Copyright (c) 2014 Jeremy Avigad. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Jeremy Avigad, Leonardo de Moura
Various multiplicative and additive structures.
-/
import tactic.interactive data.option
section pending_1857
/- Transport multiplicative to additive -/
section transport
open tactic
@[user_attribute]
meta def to_additive_attr : user_attribute (name_map name) name :=
{ name := `to_additive,
descr := "Transport multiplicative to additive",
cache_cfg := ⟨λ ns, ns.mfoldl (λ dict n, do
val ← to_additive_attr.get_param n,
pure $ dict.insert n val) mk_name_map, []⟩,
parser := lean.parser.ident,
after_set := some $ λ src _ _, do
env ← get_env,
dict ← to_additive_attr.get_cache,
tgt ← to_additive_attr.get_param src,
(get_decl tgt >> skip) <|>
transport_with_dict dict src tgt }
end transport
/- map operations -/
attribute [to_additive has_add.add] has_mul.mul
attribute [to_additive has_zero.zero] has_one.one
attribute [to_additive has_neg.neg] has_inv.inv
attribute [to_additive has_add] has_mul
attribute [to_additive has_zero] has_one
attribute [to_additive has_neg] has_inv
/- map constructors -/
attribute [to_additive has_add.mk] has_mul.mk
attribute [to_additive has_zero.mk] has_one.mk
attribute [to_additive has_neg.mk] has_inv.mk
/- map structures -/
attribute [to_additive add_semigroup] semigroup
attribute [to_additive add_semigroup.mk] semigroup.mk
attribute [to_additive add_semigroup.to_has_add] semigroup.to_has_mul
attribute [to_additive add_semigroup.add_assoc] semigroup.mul_assoc
attribute [to_additive add_semigroup.add] semigroup.mul
attribute [to_additive add_comm_semigroup] comm_semigroup
attribute [to_additive add_comm_semigroup.mk] comm_semigroup.mk
attribute [to_additive add_comm_semigroup.to_add_semigroup] comm_semigroup.to_semigroup
attribute [to_additive add_comm_semigroup.add_comm] comm_semigroup.mul_comm
attribute [to_additive add_left_cancel_semigroup] left_cancel_semigroup
attribute [to_additive add_left_cancel_semigroup.mk] left_cancel_semigroup.mk
attribute [to_additive add_left_cancel_semigroup.to_add_semigroup] left_cancel_semigroup.to_semigroup
attribute [to_additive add_left_cancel_semigroup.add_left_cancel] left_cancel_semigroup.mul_left_cancel
attribute [to_additive add_right_cancel_semigroup] right_cancel_semigroup
attribute [to_additive add_right_cancel_semigroup.mk] right_cancel_semigroup.mk
attribute [to_additive add_right_cancel_semigroup.to_add_semigroup] right_cancel_semigroup.to_semigroup
attribute [to_additive add_right_cancel_semigroup.add_right_cancel] right_cancel_semigroup.mul_right_cancel
attribute [to_additive add_monoid] monoid
attribute [to_additive add_monoid.mk] monoid.mk
attribute [to_additive add_monoid.to_has_zero] monoid.to_has_one
attribute [to_additive add_monoid.to_add_semigroup] monoid.to_semigroup
attribute [to_additive add_monoid.add] monoid.mul
attribute [to_additive add_monoid.add_assoc] monoid.mul_assoc
attribute [to_additive add_monoid.zero] monoid.one
attribute [to_additive add_monoid.zero_add] monoid.one_mul
attribute [to_additive add_monoid.add_zero] monoid.mul_one
attribute [to_additive add_comm_monoid] comm_monoid
attribute [to_additive add_comm_monoid.mk] comm_monoid.mk
attribute [to_additive add_comm_monoid.to_add_monoid] comm_monoid.to_monoid
attribute [to_additive add_comm_monoid.to_add_comm_semigroup] comm_monoid.to_comm_semigroup
attribute [to_additive add_group] group
attribute [to_additive add_group.mk] group.mk
attribute [to_additive add_group.to_has_neg] group.to_has_inv
attribute [to_additive add_group.to_add_monoid] group.to_monoid
attribute [to_additive add_group.add_left_neg] group.mul_left_inv
attribute [to_additive add_group.add] group.mul
attribute [to_additive add_group.add_assoc] group.mul_assoc
attribute [to_additive add_group.zero] group.one
attribute [to_additive add_group.zero_add] group.one_mul
attribute [to_additive add_group.add_zero] group.mul_one
attribute [to_additive add_group.neg] group.inv
attribute [to_additive add_comm_group] comm_group
attribute [to_additive add_comm_group.mk] comm_group.mk
attribute [to_additive add_comm_group.to_add_group] comm_group.to_group
attribute [to_additive add_comm_group.to_add_comm_monoid] comm_group.to_comm_monoid
/- map theorems -/
attribute [to_additive add_assoc] mul_assoc
attribute [to_additive add_semigroup_to_is_associative] semigroup_to_is_associative
attribute [to_additive add_comm] mul_comm
attribute [to_additive add_comm_semigroup_to_is_commutative] comm_semigroup_to_is_commutative
attribute [to_additive add_left_comm] mul_left_comm
attribute [to_additive add_right_comm] mul_right_comm
attribute [to_additive add_left_cancel] mul_left_cancel
attribute [to_additive add_right_cancel] mul_right_cancel
attribute [to_additive add_left_cancel_iff] mul_left_cancel_iff
attribute [to_additive add_right_cancel_iff] mul_right_cancel_iff
attribute [to_additive zero_add] one_mul
attribute [to_additive add_zero] mul_one
attribute [to_additive add_left_neg] mul_left_inv
attribute [to_additive neg_add_self] inv_mul_self
attribute [to_additive neg_add_cancel_left] inv_mul_cancel_left
attribute [to_additive neg_add_cancel_right] inv_mul_cancel_right
attribute [to_additive neg_eq_of_add_eq_zero] inv_eq_of_mul_eq_one
attribute [to_additive neg_zero] one_inv
attribute [to_additive neg_neg] inv_inv
attribute [to_additive add_right_neg] mul_right_inv
attribute [to_additive add_neg_self] mul_inv_self
attribute [to_additive neg_inj] inv_inj
attribute [to_additive add_group.add_left_cancel] group.mul_left_cancel
attribute [to_additive add_group.add_right_cancel] group.mul_right_cancel
attribute [to_additive add_group.to_left_cancel_add_semigroup] group.to_left_cancel_semigroup
attribute [to_additive add_group.to_right_cancel_add_semigroup] group.to_right_cancel_semigroup
attribute [to_additive add_neg_cancel_left] mul_inv_cancel_left
attribute [to_additive add_neg_cancel_right] mul_inv_cancel_right
attribute [to_additive neg_add_rev] mul_inv_rev
attribute [to_additive eq_neg_of_eq_neg] eq_inv_of_eq_inv
attribute [to_additive eq_neg_of_add_eq_zero] eq_inv_of_mul_eq_one
attribute [to_additive eq_add_neg_of_add_eq] eq_mul_inv_of_mul_eq
attribute [to_additive eq_neg_add_of_add_eq] eq_inv_mul_of_mul_eq
attribute [to_additive neg_add_eq_of_eq_add] inv_mul_eq_of_eq_mul
attribute [to_additive add_neg_eq_of_eq_add] mul_inv_eq_of_eq_mul
attribute [to_additive eq_add_of_add_neg_eq] eq_mul_of_mul_inv_eq
attribute [to_additive eq_add_of_neg_add_eq] eq_mul_of_inv_mul_eq
attribute [to_additive add_eq_of_eq_neg_add] mul_eq_of_eq_inv_mul
attribute [to_additive add_eq_of_eq_add_neg] mul_eq_of_eq_mul_inv
attribute [to_additive neg_add] mul_inv
end pending_1857
universes u v
variables {α : Type u} {β : Type v}
def additive (α : Type*) := α
def multiplicative (α : Type*) := α
instance [semigroup α] : add_semigroup (additive α) :=
{ add := ((*) : α → α → α),
add_assoc := @mul_assoc _ _ }
instance [add_semigroup α] : semigroup (multiplicative α) :=
{ mul := ((+) : α → α → α),
mul_assoc := @add_assoc _ _ }
instance [comm_semigroup α] : add_comm_semigroup (additive α) :=
{ add_comm := @mul_comm _ _,
..additive.add_semigroup }
instance [add_comm_semigroup α] : comm_semigroup (multiplicative α) :=
{ mul_comm := @add_comm _ _,
..multiplicative.semigroup }
instance [left_cancel_semigroup α] : add_left_cancel_semigroup (additive α) :=
{ add_left_cancel := @mul_left_cancel _ _,
..additive.add_semigroup }
instance [add_left_cancel_semigroup α] : left_cancel_semigroup (multiplicative α) :=
{ mul_left_cancel := @add_left_cancel _ _,
..multiplicative.semigroup }
instance [right_cancel_semigroup α] : add_right_cancel_semigroup (additive α) :=
{ add_right_cancel := @mul_right_cancel _ _,
..additive.add_semigroup }
instance [add_right_cancel_semigroup α] : right_cancel_semigroup (multiplicative α) :=
{ mul_right_cancel := @add_right_cancel _ _,
..multiplicative.semigroup }
@[simp, to_additive add_left_inj]
theorem mul_left_inj [left_cancel_semigroup α] (a : α) {b c : α} : a * b = a * c ↔ b = c :=
⟨mul_left_cancel, congr_arg _⟩
@[simp, to_additive add_right_inj]
theorem mul_right_inj [right_cancel_semigroup α] (a : α) {b c : α} : b * a = c * a ↔ b = c :=
⟨mul_right_cancel, congr_arg _⟩
structure units (α : Type u) [monoid α] :=
(val : α)
(inv : α)
(val_inv : val * inv = 1)
(inv_val : inv * val = 1)
namespace units
variables [monoid α] {a b c : units α}
instance : has_coe (units α) α := ⟨val⟩
@[extensionality] theorem ext : ∀ {a b : units α}, (a : α) = b → a = b
| ⟨v, i₁, vi₁, iv₁⟩ ⟨v', i₂, vi₂, iv₂⟩ e :=
by change v = v' at e; subst v'; congr;
simpa only [iv₂, vi₁, one_mul, mul_one] using mul_assoc i₂ v i₁
theorem ext_iff {a b : units α} : a = b ↔ (a : α) = b :=
⟨congr_arg _, ext⟩
instance [decidable_eq α] : decidable_eq (units α)
| a b := decidable_of_iff' _ ext_iff
protected def mul (u₁ u₂ : units α) : units α :=
⟨u₁.val * u₂.val, u₂.inv * u₁.inv,
have u₁.val * (u₂.val * u₂.inv) * u₁.inv = 1,
by rw [u₂.val_inv]; rw [mul_one, u₁.val_inv],
by simpa only [mul_assoc],
have u₂.inv * (u₁.inv * u₁.val) * u₂.val = 1,
by rw [u₁.inv_val]; rw [mul_one, u₂.inv_val],
by simpa only [mul_assoc]⟩
protected def inv' (u : units α) : units α :=
⟨u.inv, u.val, u.inv_val, u.val_inv⟩
instance : has_mul (units α) := ⟨units.mul⟩
instance : has_one (units α) := ⟨⟨1, 1, mul_one 1, one_mul 1⟩⟩
instance : has_inv (units α) := ⟨units.inv'⟩
variables (a b)
@[simp] lemma coe_mul : (↑(a * b) : α) = a * b := rfl
@[simp] lemma coe_one : ((1 : units α) : α) = 1 := rfl
lemma val_coe : (↑a : α) = a.val := rfl
lemma coe_inv : ((a⁻¹ : units α) : α) = a.inv := rfl
@[simp] lemma inv_mul : (↑a⁻¹ * a : α) = 1 := inv_val _
@[simp] lemma mul_inv : (a * ↑a⁻¹ : α) = 1 := val_inv _
@[simp] lemma mul_inv_cancel_left (a : units α) (b : α) : (a:α) * (↑a⁻¹ * b) = b :=
by rw [← mul_assoc, mul_inv, one_mul]
@[simp] lemma inv_mul_cancel_left (a : units α) (b : α) : (↑a⁻¹:α) * (a * b) = b :=
by rw [← mul_assoc, inv_mul, one_mul]
@[simp] lemma mul_inv_cancel_right (a : α) (b : units α) : a * b * ↑b⁻¹ = a :=
by rw [mul_assoc, mul_inv, mul_one]
@[simp] lemma inv_mul_cancel_right (a : α) (b : units α) : a * ↑b⁻¹ * b = a :=
by rw [mul_assoc, inv_mul, mul_one]
instance : group (units α) :=
by refine {mul := (*), one := 1, inv := has_inv.inv, ..};
{ intros, apply ext, simp only [coe_mul, coe_one,
mul_assoc, one_mul, mul_one, inv_mul] }
instance {α} [comm_monoid α] : comm_group (units α) :=
{ mul_comm := λ u₁ u₂, ext $ mul_comm _ _, ..units.group }
instance [has_repr α] : has_repr (units α) := ⟨repr ∘ val⟩
@[simp] theorem mul_left_inj (a : units α) {b c : α} : (a:α) * b = a * c ↔ b = c :=
⟨λ h, by simpa only [inv_mul_cancel_left] using congr_arg ((*) ↑(a⁻¹ : units α)) h, congr_arg _⟩
@[simp] theorem mul_right_inj (a : units α) {b c : α} : b * a = c * a ↔ b = c :=
⟨λ h, by simpa only [mul_inv_cancel_right] using congr_arg (* ↑(a⁻¹ : units α)) h, congr_arg _⟩
end units
theorem nat.units_eq_one (u : units ℕ) : u = 1 :=
units.ext $ nat.eq_one_of_dvd_one ⟨u.inv, u.val_inv.symm⟩
def units.mk_of_mul_eq_one [comm_monoid α] (a b : α) (hab : a * b = 1) : units α :=
⟨a, b, hab, (mul_comm b a).trans hab⟩
@[to_additive with_zero]
def with_one (α) := option α
@[to_additive with_zero.has_coe_t]
instance : has_coe_t α (with_one α) := ⟨some⟩
instance [semigroup α] : monoid (with_one α) :=
{ one := none,
mul := option.lift_or_get (*),
mul_assoc := (option.lift_or_get_assoc _).1,
one_mul := (option.lift_or_get_is_left_id _).1,
mul_one := (option.lift_or_get_is_right_id _).1 }
attribute [to_additive with_zero.add_monoid._proof_1] with_one.monoid._proof_1
attribute [to_additive with_zero.add_monoid._proof_2] with_one.monoid._proof_2
attribute [to_additive with_zero.add_monoid._proof_3] with_one.monoid._proof_3
attribute [to_additive with_zero.add_monoid] with_one.monoid
instance [semigroup α] : mul_zero_class (with_zero α) :=
{ zero := none,
mul := λ o₁ o₂, o₁.bind (λ a, o₂.map (λ b, a * b)),
zero_mul := λ a, rfl,
mul_zero := λ a, by cases a; refl,
..with_zero.add_monoid }
instance [semigroup α] : semigroup (with_zero α) :=
{ mul_assoc := λ a b c, match a, b, c with
| none, _, _ := rfl
| some a, none, _ := rfl
| some a, some b, none := rfl
| some a, some b, some c := congr_arg some (mul_assoc _ _ _)
end,
..with_zero.mul_zero_class }
instance [comm_semigroup α] : comm_semigroup (with_zero α) :=
{ mul_comm := λ a b, match a, b with
| none, _ := (mul_zero _).symm
| some a, none := rfl
| some a, some b := congr_arg some (mul_comm _ _)
end,
..with_zero.semigroup }
instance [monoid α] : monoid (with_zero α) :=
{ one := some 1,
one_mul := λ a, match a with
| none := rfl
| some a := congr_arg some $ one_mul _
end,
mul_one := λ a, match a with
| none := rfl
| some a := congr_arg some $ mul_one _
end,
..with_zero.semigroup }
instance [comm_monoid α] : comm_monoid (with_zero α) :=
{ ..with_zero.monoid, ..with_zero.comm_semigroup }
instance [monoid α] : add_monoid (additive α) :=
{ zero := (1 : α),
zero_add := @one_mul _ _,
add_zero := @mul_one _ _,
..additive.add_semigroup }
instance [add_monoid α] : monoid (multiplicative α) :=
{ one := (0 : α),
one_mul := @zero_add _ _,
mul_one := @add_zero _ _,
..multiplicative.semigroup }
section monoid
variables [monoid α] {a b c : α}
/-- Partial division. It is defined when the
second argument is invertible, and unlike the division operator
in `division_ring` it is not totalized at zero. -/
def divp (a : α) (u) : α := a * (u⁻¹ : units α)
infix ` /ₚ `:70 := divp
@[simp] theorem divp_self (u : units α) : (u : α) /ₚ u = 1 := units.mul_inv _
@[simp] theorem divp_one (a : α) : a /ₚ 1 = a := mul_one _
theorem divp_assoc (a b : α) (u : units α) : a * b /ₚ u = a * (b /ₚ u) :=
mul_assoc _ _ _
@[simp] theorem divp_mul_cancel (a : α) (u : units α) : a /ₚ u * u = a :=
(mul_assoc _ _ _).trans $ by rw [units.inv_mul, mul_one]
@[simp] theorem mul_divp_cancel (a : α) (u : units α) : (a * u) /ₚ u = a :=
(mul_assoc _ _ _).trans $ by rw [units.mul_inv, mul_one]
@[simp] theorem divp_right_inj (u : units α) {a b : α} : a /ₚ u = b /ₚ u ↔ a = b :=
units.mul_right_inj _
theorem divp_eq_one (a : α) (u : units α) : a /ₚ u = 1 ↔ a = u :=
(units.mul_right_inj u).symm.trans $ by rw [divp_mul_cancel, one_mul]
@[simp] theorem one_divp (u : units α) : 1 /ₚ u = ↑u⁻¹ :=
one_mul _
end monoid
instance [comm_semigroup α] : comm_monoid (with_one α) :=
{ mul_comm := (option.lift_or_get_comm _).1,
..with_one.monoid }
instance [add_comm_semigroup α] : add_comm_monoid (with_zero α) :=
{ add_comm := (option.lift_or_get_comm _).1,
..with_zero.add_monoid }
attribute [to_additive with_zero.add_comm_monoid] with_one.comm_monoid
instance [comm_monoid α] : add_comm_monoid (additive α) :=
{ add_comm := @mul_comm α _,
..additive.add_monoid }
instance [add_comm_monoid α] : comm_monoid (multiplicative α) :=
{ mul_comm := @add_comm α _,
..multiplicative.monoid }
instance [group α] : add_group (additive α) :=
{ neg := @has_inv.inv α _,
add_left_neg := @mul_left_inv _ _,
..additive.add_monoid }
instance [add_group α] : group (multiplicative α) :=
{ inv := @has_neg.neg α _,
mul_left_inv := @add_left_neg _ _,
..multiplicative.monoid }
section group
variables [group α] {a b c : α}
instance : has_lift α (units α) :=
⟨λ a, ⟨a, a⁻¹, mul_inv_self _, inv_mul_self _⟩⟩
@[simp, to_additive neg_inj']
theorem inv_inj' : a⁻¹ = b⁻¹ ↔ a = b :=
⟨λ h, by rw [← inv_inv a, h, inv_inv], congr_arg _⟩
@[to_additive eq_of_neg_eq_neg]
theorem eq_of_inv_eq_inv : a⁻¹ = b⁻¹ → a = b :=
inv_inj'.1
@[simp, to_additive add_self_iff_eq_zero]
theorem mul_self_iff_eq_one : a * a = a ↔ a = 1 :=
by have := @mul_left_inj _ _ a a 1; rwa mul_one at this
@[simp, to_additive neg_eq_zero]
theorem inv_eq_one : a⁻¹ = 1 ↔ a = 1 :=
by rw [← @inv_inj' _ _ a 1, one_inv]
@[simp, to_additive neg_ne_zero]
theorem inv_ne_one : a⁻¹ ≠ 1 ↔ a ≠ 1 :=
not_congr inv_eq_one
@[to_additive left_inverse_neg]
theorem left_inverse_inv (α) [group α] :
function.left_inverse (λ a : α, a⁻¹) (λ a, a⁻¹) :=
assume a, inv_inv a
attribute [simp] mul_inv_cancel_left add_neg_cancel_left
mul_inv_cancel_right add_neg_cancel_right
@[to_additive eq_neg_iff_eq_neg]
theorem eq_inv_iff_eq_inv : a = b⁻¹ ↔ b = a⁻¹ :=
⟨eq_inv_of_eq_inv, eq_inv_of_eq_inv⟩
@[to_additive neg_eq_iff_neg_eq]
theorem inv_eq_iff_inv_eq : a⁻¹ = b ↔ b⁻¹ = a :=
by rw [eq_comm, @eq_comm _ _ a, eq_inv_iff_eq_inv]
@[to_additive add_eq_zero_iff_eq_neg]
theorem mul_eq_one_iff_eq_inv : a * b = 1 ↔ a = b⁻¹ :=
by simpa [mul_left_inv, -mul_right_inj] using @mul_right_inj _ _ b a (b⁻¹)
@[to_additive add_eq_zero_iff_neg_eq]
theorem mul_eq_one_iff_inv_eq : a * b = 1 ↔ a⁻¹ = b :=
by rw [mul_eq_one_iff_eq_inv, eq_inv_iff_eq_inv, eq_comm]
@[to_additive eq_neg_iff_add_eq_zero]
theorem eq_inv_iff_mul_eq_one : a = b⁻¹ ↔ a * b = 1 :=
mul_eq_one_iff_eq_inv.symm
@[to_additive neg_eq_iff_add_eq_zero]
theorem inv_eq_iff_mul_eq_one : a⁻¹ = b ↔ a * b = 1 :=
mul_eq_one_iff_inv_eq.symm
@[to_additive eq_add_neg_iff_add_eq]
theorem eq_mul_inv_iff_mul_eq : a = b * c⁻¹ ↔ a * c = b :=
⟨λ h, by rw [h, inv_mul_cancel_right], λ h, by rw [← h, mul_inv_cancel_right]⟩
@[to_additive eq_neg_add_iff_add_eq]
theorem eq_inv_mul_iff_mul_eq : a = b⁻¹ * c ↔ b * a = c :=
⟨λ h, by rw [h, mul_inv_cancel_left], λ h, by rw [← h, inv_mul_cancel_left]⟩
@[to_additive neg_add_eq_iff_eq_add]
theorem inv_mul_eq_iff_eq_mul : a⁻¹ * b = c ↔ b = a * c :=
⟨λ h, by rw [← h, mul_inv_cancel_left], λ h, by rw [h, inv_mul_cancel_left]⟩
@[to_additive add_neg_eq_iff_eq_add]
theorem mul_inv_eq_iff_eq_mul : a * b⁻¹ = c ↔ a = c * b :=
⟨λ h, by rw [← h, inv_mul_cancel_right], λ h, by rw [h, mul_inv_cancel_right]⟩
@[to_additive add_neg_eq_zero]
theorem mul_inv_eq_one {a b : α} : a * b⁻¹ = 1 ↔ a = b :=
by rw [mul_eq_one_iff_eq_inv, inv_inv]
@[to_additive neg_comm_of_comm]
theorem inv_comm_of_comm {a b : α} (H : a * b = b * a) : a⁻¹ * b = b * a⁻¹ :=
begin
have : a⁻¹ * (b * a) * a⁻¹ = a⁻¹ * (a * b) * a⁻¹ :=
congr_arg (λ x:α, a⁻¹ * x * a⁻¹) H.symm,
rwa [inv_mul_cancel_left, mul_assoc, mul_inv_cancel_right] at this
end
end group
instance [comm_group α] : add_comm_group (additive α) :=
{ add_comm := @mul_comm α _,
..additive.add_group }
instance [add_comm_group α] : comm_group (multiplicative α) :=
{ mul_comm := @add_comm α _,
..multiplicative.group }
section add_monoid
variables [add_monoid α] {a b c : α}
@[simp] lemma bit0_zero : bit0 (0 : α) = 0 := add_zero _
@[simp] lemma bit1_zero [has_one α] : bit1 (0 : α) = 1 :=
show 0+0+1=(1:α), by rw [zero_add, zero_add]
end add_monoid
section add_group
variables [add_group α] {a b c : α}
local attribute [simp] sub_eq_add_neg
def sub_sub_cancel := @sub_sub_self
@[simp] lemma sub_left_inj : a - b = a - c ↔ b = c :=
(add_left_inj _).trans neg_inj'
@[simp] lemma sub_right_inj : b - a = c - a ↔ b = c :=
add_right_inj _
lemma sub_add_sub_cancel (a b c : α) : (a - b) + (b - c) = a - c :=
by rw [← add_sub_assoc, sub_add_cancel]
lemma sub_sub_sub_cancel_right (a b c : α) : (a - c) - (b - c) = a - b :=
by rw [← neg_sub c b, sub_neg_eq_add, sub_add_sub_cancel]
theorem sub_eq_zero : a - b = 0 ↔ a = b :=
⟨eq_of_sub_eq_zero, λ h, by rw [h, sub_self]⟩
theorem sub_ne_zero : a - b ≠ 0 ↔ a ≠ b :=
not_congr sub_eq_zero
theorem eq_sub_iff_add_eq : a = b - c ↔ a + c = b :=
eq_add_neg_iff_add_eq
theorem sub_eq_iff_eq_add : a - b = c ↔ a = c + b :=
add_neg_eq_iff_eq_add
theorem eq_iff_eq_of_sub_eq_sub {a b c d : α} (H : a - b = c - d) : a = b ↔ c = d :=
by rw [← sub_eq_zero, H, sub_eq_zero]
theorem left_inverse_sub_add_left (c : α) : function.left_inverse (λ x, x - c) (λ x, x + c) :=
assume x, add_sub_cancel x c
theorem left_inverse_add_left_sub (c : α) : function.left_inverse (λ x, x + c) (λ x, x - c) :=
assume x, sub_add_cancel x c
theorem left_inverse_add_right_neg_add (c : α) :
function.left_inverse (λ x, c + x) (λ x, - c + x) :=
assume x, add_neg_cancel_left c x
theorem left_inverse_neg_add_add_right (c : α) :
function.left_inverse (λ x, - c + x) (λ x, c + x) :=
assume x, neg_add_cancel_left c x
end add_group
section add_comm_group
variables [add_comm_group α] {a b c : α}
lemma sub_eq_neg_add (a b : α) : a - b = -b + a :=
add_comm _ _
theorem neg_add' (a b : α) : -(a + b) = -a - b := neg_add a b
lemma eq_sub_iff_add_eq' : a = b - c ↔ c + a = b :=
by rw [eq_sub_iff_add_eq, add_comm]
lemma sub_eq_iff_eq_add' : a - b = c ↔ a = b + c :=
by rw [sub_eq_iff_eq_add, add_comm]
lemma add_sub_cancel' (a b : α) : a + b - a = b :=
by rw [sub_eq_neg_add, neg_add_cancel_left]
lemma add_sub_cancel'_right (a b : α) : a + (b - a) = b :=
by rw [← add_sub_assoc, add_sub_cancel']
lemma sub_right_comm (a b c : α) : a - b - c = a - c - b :=
add_right_comm _ _ _
lemma sub_add_sub_cancel' (a b c : α) : (a - b) + (c - a) = c - b :=
by rw add_comm; apply sub_add_sub_cancel
lemma sub_sub_sub_cancel_left (a b c : α) : (c - a) - (c - b) = b - a :=
by rw [← neg_sub b c, sub_neg_eq_add, add_comm, sub_add_sub_cancel]
end add_comm_group
section is_conj
variables [group α] [group β]
def is_conj (a b : α) := ∃ c : α, c * a * c⁻¹ = b
@[refl] lemma is_conj_refl (a : α) : is_conj a a :=
⟨1, by rw [one_mul, one_inv, mul_one]⟩
@[symm] lemma is_conj_symm (a b : α) : is_conj a b → is_conj b a
| ⟨c, hc⟩ := ⟨c⁻¹, by rw [← hc, mul_assoc, mul_inv_cancel_right, inv_mul_cancel_left]⟩
@[trans] lemma is_conj_trans (a b c : α) : is_conj a b → is_conj b c → is_conj a c
| ⟨c₁, hc₁⟩ ⟨c₂, hc₂⟩ := ⟨c₂ * c₁, by rw [← hc₂, ← hc₁, mul_inv_rev]; simp only [mul_assoc]⟩
@[simp] lemma is_conj_iff_eq {α : Type*} [comm_group α] {a b : α} : is_conj a b ↔ a = b :=
⟨λ ⟨c, hc⟩, by rw [← hc, mul_right_comm, mul_inv_self, one_mul], λ h, by rw h⟩
end is_conj
class is_monoid_hom [monoid α] [monoid β] (f : α → β) : Prop :=
(map_one : f 1 = 1)
(map_mul : ∀ {x y}, f (x * y) = f x * f y)
class is_add_monoid_hom [add_monoid α] [add_monoid β] (f : α → β) : Prop :=
(map_zero : f 0 = 0)
(map_add : ∀ {x y}, f (x + y) = f x + f y)
attribute [to_additive is_add_monoid_hom] is_monoid_hom
attribute [to_additive is_add_monoid_hom.map_add] is_monoid_hom.map_mul
attribute [to_additive is_add_monoid_hom.mk] is_monoid_hom.mk
namespace is_monoid_hom
variables [monoid α] [monoid β] (f : α → β) [is_monoid_hom f]
@[to_additive is_add_monoid_hom.id]
instance id : is_monoid_hom (@id α) := by refine {..}; intros; refl
@[to_additive is_add_monoid_hom.id]
instance comp {γ} [monoid γ] (g : β → γ) [is_monoid_hom g] :
is_monoid_hom (g ∘ f) :=
{ map_mul := λ x y, show g _ = g _ * g _, by rw [map_mul f, map_mul g],
map_one := show g _ = 1, by rw [map_one f, map_one g] }
end is_monoid_hom
-- TODO rename fields of is_group_hom: mul ↝ map_mul?
/-- Predicate for group homomorphism. -/
class is_group_hom [group α] [group β] (f : α → β) : Prop :=
(mul : ∀ a b : α, f (a * b) = f a * f b)
class is_add_group_hom [add_group α] [add_group β] (f : α → β) : Prop :=
(add : ∀ a b, f (a + b) = f a + f b)
attribute [to_additive is_add_group_hom] is_group_hom
attribute [to_additive is_add_group_hom.add] is_group_hom.mul
attribute [to_additive is_add_group_hom.mk] is_group_hom.mk
namespace is_group_hom
variables [group α] [group β] (f : α → β) [is_group_hom f]
@[to_additive is_add_group_hom.zero]
theorem one : f 1 = 1 :=
mul_self_iff_eq_one.1 $ by rw [← mul f, one_mul]
@[to_additive is_add_group_hom.neg]
theorem inv (a : α) : f a⁻¹ = (f a)⁻¹ :=
eq_inv_of_mul_eq_one $ by rw [← mul f, inv_mul_self, one f]
@[to_additive is_add_group_hom.id]
instance id : is_group_hom (@id α) :=
⟨λ _ _, rfl⟩
@[to_additive is_add_group_hom.comp]
instance comp {γ} [group γ] (g : β → γ) [is_group_hom g] :
is_group_hom (g ∘ f) :=
⟨λ x y, show g _ = g _ * g _, by rw [mul f, mul g]⟩
protected lemma is_conj (f : α → β) [is_group_hom f] {a b : α} : is_conj a b → is_conj (f a) (f b)
| ⟨c, hc⟩ := ⟨f c, by rw [← is_group_hom.mul f, ← is_group_hom.inv f, ← is_group_hom.mul f, hc]⟩
end is_group_hom
@[to_additive is_add_group_hom_add]
lemma is_group_hom_mul {α β} [group α] [comm_group β]
(f g : α → β) [is_group_hom f] [is_group_hom g] :
is_group_hom (λa, f a * g a) :=
⟨assume a b, by simp only [is_group_hom.mul f, is_group_hom.mul g, mul_comm, mul_assoc, mul_left_comm]⟩
attribute [instance] is_group_hom_mul is_add_group_hom_add
@[to_additive is_add_group_hom_neg]
lemma is_group_hom_inv {α β} [group α] [comm_group β] (f : α → β) [is_group_hom f] :
is_group_hom (λa, (f a)⁻¹) :=
⟨assume a b, by rw [is_group_hom.mul f, mul_inv]⟩
attribute [instance] is_group_hom_inv is_add_group_hom_neg
/-- Predicate for group anti-homomorphism, or a homomorphism
into the opposite group. -/
class is_group_anti_hom {β : Type*} [group α] [group β] (f : α → β) : Prop :=
(mul : ∀ a b : α, f (a * b) = f b * f a)
namespace is_group_anti_hom
variables [group α] [group β] (f : α → β) [w : is_group_anti_hom f]
include w
theorem one : f 1 = 1 :=
mul_self_iff_eq_one.1 $ by rw [← mul f, one_mul]
theorem inv (a : α) : f a⁻¹ = (f a)⁻¹ :=
eq_inv_of_mul_eq_one $ by rw [← mul f, mul_inv_self, one f]
end is_group_anti_hom
theorem inv_is_group_anti_hom [group α] : is_group_anti_hom (λ x : α, x⁻¹) :=
⟨mul_inv_rev⟩
namespace is_add_group_hom
variables [add_group α] [add_group β] (f : α → β) [is_add_group_hom f]
lemma sub (a b) : f (a - b) = f a - f b :=
calc f (a - b) = f (a + -b) : rfl
... = f a + f (-b) : add f _ _
... = f a - f b : by simp[neg f]
end is_add_group_hom
lemma is_add_group_hom_sub {α β} [add_group α] [add_comm_group β]
(f g : α → β) [is_add_group_hom f] [is_add_group_hom g] :
is_add_group_hom (λa, f a - g a) :=
is_add_group_hom_add f (λa, - g a)
attribute [instance] is_add_group_hom_sub
namespace units
variables [monoid α] [monoid β] (f : α → β) [is_monoid_hom f]
definition map : units α → units β :=
λ u, ⟨f u.val, f u.inv,
by rw [← is_monoid_hom.map_mul f, u.val_inv, is_monoid_hom.map_one f],
by rw [← is_monoid_hom.map_mul f, u.inv_val, is_monoid_hom.map_one f] ⟩
instance : is_group_hom (units.map f) :=
⟨λ a b, by ext; exact is_monoid_hom.map_mul f ⟩
end units
|
35dd9f06f505e1f4ede9a15258af9550be1ef458 | 94e33a31faa76775069b071adea97e86e218a8ee | /src/number_theory/lucas_lehmer.lean | 7dcc83f26b14879744de61c4b74a75f568dbc0d7 | [
"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 | 16,994 | lean | /-
Copyright (c) 2020 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro, Scott Morrison, Ainsley Pahljina
-/
import data.nat.parity
import data.pnat.interval
import data.zmod.basic
import group_theory.order_of_element
import ring_theory.fintype
import tactic.interval_cases
import tactic.ring_exp
/-!
# The Lucas-Lehmer test for Mersenne primes.
We define `lucas_lehmer_residue : Π p : ℕ, zmod (2^p - 1)`, and
prove `lucas_lehmer_residue p = 0 → prime (mersenne p)`.
We construct a tactic `lucas_lehmer.run_test`, which iteratively certifies the arithmetic
required to calculate the residue, and enables us to prove
```
example : prime (mersenne 127) :=
lucas_lehmer_sufficiency _ (by norm_num) (by lucas_lehmer.run_test)
```
## TODO
- Show reverse implication.
- Speed up the calculations using `n ≡ (n % 2^p) + (n / 2^p) [MOD 2^p - 1]`.
- Find some bigger primes!
## History
This development began as a student project by Ainsley Pahljina,
and was then cleaned up for mathlib by Scott Morrison.
The tactic for certified computation of Lucas-Lehmer residues was provided by Mario Carneiro.
-/
/-- The Mersenne numbers, 2^p - 1. -/
def mersenne (p : ℕ) : ℕ := 2^p - 1
lemma mersenne_pos {p : ℕ} (h : 0 < p) : 0 < mersenne p :=
begin
dsimp [mersenne],
calc 0 < 2^1 - 1 : by norm_num
... ≤ 2^p - 1 : nat.pred_le_pred (nat.pow_le_pow_of_le_right (nat.succ_pos 1) h)
end
@[simp]
lemma succ_mersenne (k : ℕ) : mersenne k + 1 = 2 ^ k :=
begin
rw [mersenne, tsub_add_cancel_of_le],
exact one_le_pow_of_one_le (by norm_num) k
end
namespace lucas_lehmer
open nat
/-!
We now define three(!) different versions of the recurrence
`s (i+1) = (s i)^2 - 2`.
These versions take values either in `ℤ`, in `zmod (2^p - 1)`, or
in `ℤ` but applying `% (2^p - 1)` at each step.
They are each useful at different points in the proof,
so we take a moment setting up the lemmas relating them.
-/
/-- The recurrence `s (i+1) = (s i)^2 - 2` in `ℤ`. -/
def s : ℕ → ℤ
| 0 := 4
| (i+1) := (s i)^2 - 2
/-- The recurrence `s (i+1) = (s i)^2 - 2` in `zmod (2^p - 1)`. -/
def s_zmod (p : ℕ) : ℕ → zmod (2^p - 1)
| 0 := 4
| (i+1) := (s_zmod i)^2 - 2
/-- The recurrence `s (i+1) = ((s i)^2 - 2) % (2^p - 1)` in `ℤ`. -/
def s_mod (p : ℕ) : ℕ → ℤ
| 0 := 4 % (2^p - 1)
| (i+1) := ((s_mod i)^2 - 2) % (2^p - 1)
lemma mersenne_int_ne_zero (p : ℕ) (w : 0 < p) : (2^p - 1 : ℤ) ≠ 0 :=
begin
apply ne_of_gt, simp only [gt_iff_lt, sub_pos],
exact_mod_cast nat.one_lt_two_pow p w,
end
lemma s_mod_nonneg (p : ℕ) (w : 0 < p) (i : ℕ) : 0 ≤ s_mod p i :=
begin
cases i; dsimp [s_mod],
{ exact sup_eq_left.mp rfl },
{ apply int.mod_nonneg, exact mersenne_int_ne_zero p w },
end
lemma s_mod_mod (p i : ℕ) : s_mod p i % (2^p - 1) = s_mod p i :=
by cases i; simp [s_mod]
lemma s_mod_lt (p : ℕ) (w : 0 < p) (i : ℕ) : s_mod p i < 2^p - 1 :=
begin
rw ←s_mod_mod,
convert int.mod_lt _ _,
{ refine (abs_of_nonneg _).symm,
simp only [sub_nonneg, ge_iff_le],
exact_mod_cast nat.one_le_two_pow p, },
{ exact mersenne_int_ne_zero p w, },
end
lemma s_zmod_eq_s (p' : ℕ) (i : ℕ) : s_zmod (p'+2) i = (s i : zmod (2^(p'+2) - 1)):=
begin
induction i with i ih,
{ dsimp [s, s_zmod], norm_num, },
{ push_cast [s, s_zmod, ih] },
end
-- These next two don't make good `norm_cast` lemmas.
lemma int.coe_nat_pow_pred (b p : ℕ) (w : 0 < b) : ((b^p - 1 : ℕ) : ℤ) = (b^p - 1 : ℤ) :=
begin
have : 1 ≤ b^p := nat.one_le_pow p b w,
norm_cast
end
lemma int.coe_nat_two_pow_pred (p : ℕ) : ((2^p - 1 : ℕ) : ℤ) = (2^p - 1 : ℤ) :=
int.coe_nat_pow_pred 2 p dec_trivial
lemma s_zmod_eq_s_mod (p : ℕ) (i : ℕ) : s_zmod p i = (s_mod p i : zmod (2^p - 1)) :=
by induction i; push_cast [←int.coe_nat_two_pow_pred p, s_mod, s_zmod, *]
/-- The Lucas-Lehmer residue is `s p (p-2)` in `zmod (2^p - 1)`. -/
def lucas_lehmer_residue (p : ℕ) : zmod (2^p - 1) := s_zmod p (p-2)
lemma residue_eq_zero_iff_s_mod_eq_zero (p : ℕ) (w : 1 < p) :
lucas_lehmer_residue p = 0 ↔ s_mod p (p-2) = 0 :=
begin
dsimp [lucas_lehmer_residue],
rw s_zmod_eq_s_mod p,
split,
{ -- We want to use that fact that `0 ≤ s_mod p (p-2) < 2^p - 1`
-- and `lucas_lehmer_residue p = 0 → 2^p - 1 ∣ s_mod p (p-2)`.
intro h,
simp [zmod.int_coe_zmod_eq_zero_iff_dvd] at h,
apply int.eq_zero_of_dvd_of_nonneg_of_lt _ _ h; clear h,
apply s_mod_nonneg _ (nat.lt_of_succ_lt w),
exact s_mod_lt _ (nat.lt_of_succ_lt w) (p-2) },
{ intro h, rw h, simp, },
end
/--
A Mersenne number `2^p-1` is prime if and only if
the Lucas-Lehmer residue `s p (p-2) % (2^p - 1)` is zero.
-/
@[derive decidable_pred]
def lucas_lehmer_test (p : ℕ) : Prop := lucas_lehmer_residue p = 0
/-- `q` is defined as the minimum factor of `mersenne p`, bundled as an `ℕ+`. -/
def q (p : ℕ) : ℕ+ := ⟨nat.min_fac (mersenne p), nat.min_fac_pos (mersenne p)⟩
local attribute [instance]
lemma fact_pnat_pos (q : ℕ+) : fact (0 < (q : ℕ)) := ⟨q.2⟩
/-- We construct the ring `X q` as ℤ/qℤ + √3 ℤ/qℤ. -/
-- It would be nice to define this as (ℤ/qℤ)[x] / (x^2 - 3),
-- obtaining the ring structure for free,
-- but that seems to be more trouble than it's worth;
-- if it were easy to make the definition,
-- cardinality calculations would be somewhat more involved, too.
@[derive [add_comm_group, decidable_eq, fintype, inhabited]]
def X (q : ℕ+) : Type := (zmod q) × (zmod q)
namespace X
variable {q : ℕ+}
@[ext]
lemma ext {x y : X q} (h₁ : x.1 = y.1) (h₂ : x.2 = y.2) : x = y :=
begin
cases x, cases y,
congr; assumption
end
@[simp] lemma add_fst (x y : X q) : (x + y).1 = x.1 + y.1 := rfl
@[simp] lemma add_snd (x y : X q) : (x + y).2 = x.2 + y.2 := rfl
@[simp] lemma neg_fst (x : X q) : (-x).1 = -x.1 := rfl
@[simp] lemma neg_snd (x : X q) : (-x).2 = -x.2 := rfl
instance : has_mul (X q) :=
{ mul := λ x y, (x.1*y.1 + 3*x.2*y.2, x.1*y.2 + x.2*y.1) }
@[simp] lemma mul_fst (x y : X q) : (x * y).1 = x.1 * y.1 + 3 * x.2 * y.2 := rfl
@[simp] lemma mul_snd (x y : X q) : (x * y).2 = x.1 * y.2 + x.2 * y.1 := rfl
instance : has_one (X q) :=
{ one := ⟨1,0⟩ }
@[simp] lemma one_fst : (1 : X q).1 = 1 := rfl
@[simp] lemma one_snd : (1 : X q).2 = 0 := rfl
@[simp] lemma bit0_fst (x : X q) : (bit0 x).1 = bit0 x.1 := rfl
@[simp] lemma bit0_snd (x : X q) : (bit0 x).2 = bit0 x.2 := rfl
@[simp] lemma bit1_fst (x : X q) : (bit1 x).1 = bit1 x.1 := rfl
@[simp] lemma bit1_snd (x : X q) : (bit1 x).2 = bit0 x.2 := by { dsimp [bit1], simp, }
instance : monoid (X q) :=
{ mul_assoc := λ x y z, by { ext; { dsimp, ring }, },
one := ⟨1,0⟩,
one_mul := λ x, by { ext; simp, },
mul_one := λ x, by { ext; simp, },
..(infer_instance : has_mul (X q)) }
instance : add_group_with_one (X q) :=
{ nat_cast := λ n, ⟨n, 0⟩,
nat_cast_zero := by simp,
nat_cast_succ := by simp [nat.cast, monoid.one],
int_cast := λ n, ⟨n, 0⟩,
int_cast_of_nat := λ n, by simp; refl,
int_cast_neg_succ_of_nat := λ n, by ext; simp; refl,
.. X.monoid, .. X.add_comm_group _ }
lemma left_distrib (x y z : X q) : x * (y + z) = x * y + x * z :=
by { ext; { dsimp, ring }, }
lemma right_distrib (x y z : X q) : (x + y) * z = x * z + y * z :=
by { ext; { dsimp, ring }, }
instance : ring (X q) :=
{ left_distrib := left_distrib,
right_distrib := right_distrib,
.. X.add_group_with_one,
..(infer_instance : add_comm_group (X q)),
..(infer_instance : monoid (X q)) }
instance : comm_ring (X q) :=
{ mul_comm := λ x y, by { ext; { dsimp, ring }, },
..(infer_instance : ring (X q))}
instance [fact (1 < (q : ℕ))] : nontrivial (X q) :=
⟨⟨0, 1, λ h, by { injection h with h1 _, exact zero_ne_one h1 } ⟩⟩
@[simp] lemma nat_coe_fst (n : ℕ) : (n : X q).fst = (n : zmod q) := rfl
@[simp] lemma nat_coe_snd (n : ℕ) : (n : X q).snd = (0 : zmod q) := rfl
@[simp] lemma int_coe_fst (n : ℤ) : (n : X q).fst = (n : zmod q) := rfl
@[simp] lemma int_coe_snd (n : ℤ) : (n : X q).snd = (0 : zmod q) := rfl
@[norm_cast]
lemma coe_mul (n m : ℤ) : ((n * m : ℤ) : X q) = (n : X q) * (m : X q) :=
by { ext; simp; ring }
@[norm_cast]
lemma coe_nat (n : ℕ) : ((n : ℤ) : X q) = (n : X q) :=
by { ext; simp, }
/-- The cardinality of `X` is `q^2`. -/
lemma X_card : fintype.card (X q) = q^2 :=
begin
dsimp [X],
rw [fintype.card_prod, zmod.card q],
ring,
end
/-- There are strictly fewer than `q^2` units, since `0` is not a unit. -/
lemma units_card (w : 1 < q) : fintype.card ((X q)ˣ) < q^2 :=
begin
haveI : fact (1 < (q:ℕ)) := ⟨w⟩,
convert card_units_lt (X q),
rw X_card,
end
/-- We define `ω = 2 + √3`. -/
def ω : X q := (2, 1)
/-- We define `ωb = 2 - √3`, which is the inverse of `ω`. -/
def ωb : X q := (2, -1)
lemma ω_mul_ωb (q : ℕ+) : (ω : X q) * ωb = 1 :=
begin
dsimp [ω, ωb],
ext; simp; ring,
end
lemma ωb_mul_ω (q : ℕ+) : (ωb : X q) * ω = 1 :=
begin
dsimp [ω, ωb],
ext; simp; ring,
end
/-- A closed form for the recurrence relation. -/
lemma closed_form (i : ℕ) : (s i : X q) = (ω : X q)^(2^i) + (ωb : X q)^(2^i) :=
begin
induction i with i ih,
{ dsimp [s, ω, ωb],
ext; { simp; refl, }, },
{ calc (s (i + 1) : X q) = ((s i)^2 - 2 : ℤ) : rfl
... = ((s i : X q)^2 - 2) : by push_cast
... = (ω^(2^i) + ωb^(2^i))^2 - 2 : by rw ih
... = (ω^(2^i))^2 + (ωb^(2^i))^2 + 2*(ωb^(2^i)*ω^(2^i)) - 2 : by ring
... = (ω^(2^i))^2 + (ωb^(2^i))^2 :
by rw [←mul_pow ωb ω, ωb_mul_ω, one_pow, mul_one, add_sub_cancel]
... = ω^(2^(i+1)) + ωb^(2^(i+1)) : by rw [←pow_mul, ←pow_mul, pow_succ'] }
end
end X
open X
/-!
Here and below, we introduce `p' = p - 2`, in order to avoid using subtraction in `ℕ`.
-/
/-- If `1 < p`, then `q p`, the smallest prime factor of `mersenne p`, is more than 2. -/
lemma two_lt_q (p' : ℕ) : 2 < q (p'+2) := begin
by_contradiction H,
simp at H,
interval_cases q (p'+2); clear H,
{ -- If q = 1, we get a contradiction from 2^p = 2
dsimp [q] at h, injection h with h', clear h,
simp [mersenne] at h',
exact lt_irrefl 2
(calc 2 ≤ p'+2 : nat.le_add_left _ _
... < 2^(p'+2) : nat.lt_two_pow _
... = 2 : nat.pred_inj (nat.one_le_two_pow _) dec_trivial h'), },
{ -- If q = 2, we get a contradiction from 2 ∣ 2^p - 1
dsimp [q] at h, injection h with h', clear h,
rw [mersenne, pnat.one_coe, nat.min_fac_eq_two_iff, pow_succ] at h',
exact nat.two_not_dvd_two_mul_sub_one (nat.one_le_two_pow _) h', }
end
theorem ω_pow_formula (p' : ℕ) (h : lucas_lehmer_residue (p'+2) = 0) :
∃ (k : ℤ), (ω : X (q (p'+2)))^(2^(p'+1)) =
k * (mersenne (p'+2)) * ((ω : X (q (p'+2)))^(2^p')) - 1 :=
begin
dsimp [lucas_lehmer_residue] at h,
rw s_zmod_eq_s p' at h,
simp [zmod.int_coe_zmod_eq_zero_iff_dvd] at h,
cases h with k h,
use k,
replace h := congr_arg (λ (n : ℤ), (n : X (q (p'+2)))) h, -- coercion from ℤ to X q
dsimp at h,
rw closed_form at h,
replace h := congr_arg (λ x, ω^2^p' * x) h,
dsimp at h,
have t : 2^p' + 2^p' = 2^(p'+1) := by ring_exp,
rw [mul_add, ←pow_add ω, t, ←mul_pow ω ωb (2^p'), ω_mul_ωb, one_pow] at h,
rw [mul_comm, coe_mul] at h,
rw [mul_comm _ (k : X (q (p'+2)))] at h,
replace h := eq_sub_of_add_eq h,
have : 1 ≤ 2 ^ (p' + 2) := nat.one_le_pow _ _ dec_trivial,
exact_mod_cast h,
end
/-- `q` is the minimum factor of `mersenne p`, so `M p = 0` in `X q`. -/
theorem mersenne_coe_X (p : ℕ) : (mersenne p : X (q p)) = 0 :=
begin
ext; simp [mersenne, q, zmod.nat_coe_zmod_eq_zero_iff_dvd, -pow_pos],
apply nat.min_fac_dvd,
end
theorem ω_pow_eq_neg_one (p' : ℕ) (h : lucas_lehmer_residue (p'+2) = 0) :
(ω : X (q (p'+2)))^(2^(p'+1)) = -1 :=
begin
cases ω_pow_formula p' h with k w,
rw [mersenne_coe_X] at w,
simpa using w,
end
theorem ω_pow_eq_one (p' : ℕ) (h : lucas_lehmer_residue (p'+2) = 0) :
(ω : X (q (p'+2)))^(2^(p'+2)) = 1 :=
calc (ω : X (q (p'+2)))^2^(p'+2)
= (ω^(2^(p'+1)))^2 : by rw [←pow_mul, ←pow_succ']
... = (-1)^2 : by rw ω_pow_eq_neg_one p' h
... = 1 : by simp
/-- `ω` as an element of the group of units. -/
def ω_unit (p : ℕ) : units (X (q p)) :=
{ val := ω,
inv := ωb,
val_inv := by simp [ω_mul_ωb],
inv_val := by simp [ωb_mul_ω], }
@[simp] lemma ω_unit_coe (p : ℕ) : (ω_unit p : X (q p)) = ω := rfl
/-- The order of `ω` in the unit group is exactly `2^p`. -/
theorem order_ω (p' : ℕ) (h : lucas_lehmer_residue (p'+2) = 0) :
order_of (ω_unit (p'+2)) = 2^(p'+2) :=
begin
apply nat.eq_prime_pow_of_dvd_least_prime_pow, -- the order of ω divides 2^p
{ norm_num, },
{ intro o,
have ω_pow := order_of_dvd_iff_pow_eq_one.1 o,
replace ω_pow := congr_arg (units.coe_hom (X (q (p'+2))) :
units (X (q (p'+2))) → X (q (p'+2))) ω_pow,
simp at ω_pow,
have h : (1 : zmod (q (p'+2))) = -1 :=
congr_arg (prod.fst) ((ω_pow.symm).trans (ω_pow_eq_neg_one p' h)),
haveI : fact (2 < (q (p'+2) : ℕ)) := ⟨two_lt_q _⟩,
apply zmod.neg_one_ne_one h.symm, },
{ apply order_of_dvd_iff_pow_eq_one.2,
apply units.ext,
push_cast,
exact ω_pow_eq_one p' h, }
end
lemma order_ineq (p' : ℕ) (h : lucas_lehmer_residue (p'+2) = 0) : 2^(p'+2) < (q (p'+2) : ℕ)^2 :=
calc 2^(p'+2) = order_of (ω_unit (p'+2)) : (order_ω p' h).symm
... ≤ fintype.card ((X _)ˣ) : order_of_le_card_univ
... < (q (p'+2) : ℕ)^2 : units_card (nat.lt_of_succ_lt (two_lt_q _))
end lucas_lehmer
export lucas_lehmer (lucas_lehmer_test lucas_lehmer_residue)
open lucas_lehmer
theorem lucas_lehmer_sufficiency (p : ℕ) (w : 1 < p) : lucas_lehmer_test p → (mersenne p).prime :=
begin
let p' := p - 2,
have z : p = p' + 2 := (tsub_eq_iff_eq_add_of_le w.nat_succ_le).mp rfl,
have w : 1 < p' + 2 := (nat.lt_of_sub_eq_succ rfl),
contrapose,
intros a t,
rw z at a,
rw z at t,
have h₁ := order_ineq p' t,
have h₂ := nat.min_fac_sq_le_self (mersenne_pos (nat.lt_of_succ_lt w)) a,
have h := lt_of_lt_of_le h₁ h₂,
exact not_lt_of_ge (nat.sub_le _ _) h,
end
-- Here we calculate the residue, very inefficiently, using `dec_trivial`. We can do much better.
example : (mersenne 5).prime := lucas_lehmer_sufficiency 5 (by norm_num) dec_trivial
-- Next we use `norm_num` to calculate each `s p i`.
namespace lucas_lehmer
open tactic
lemma s_mod_succ {p a i b c}
(h1 : (2^p - 1 : ℤ) = a)
(h2 : s_mod p i = b)
(h3 : (b * b - 2) % a = c) :
s_mod p (i+1) = c :=
by { dsimp [s_mod, mersenne], rw [h1, h2, sq, h3] }
/--
Given a goal of the form `lucas_lehmer_test p`,
attempt to do the calculation using `norm_num` to certify each step.
-/
meta def run_test : tactic unit :=
do `(lucas_lehmer_test %%p) ← target,
`[dsimp [lucas_lehmer_test]],
`[rw lucas_lehmer.residue_eq_zero_iff_s_mod_eq_zero, swap, norm_num],
p ← eval_expr ℕ p,
-- Calculate the candidate Mersenne prime
let M : ℤ := 2^p - 1,
t ← to_expr ``(2^%%`(p) - 1 = %%`(M)),
v ← to_expr ``(by norm_num : 2^%%`(p) - 1 = %%`(M)),
w ← assertv `w t v,
-- base case
t ← to_expr ``(s_mod %%`(p) 0 = 4),
v ← to_expr ``(by norm_num [lucas_lehmer.s_mod] : s_mod %%`(p) 0 = 4),
h ← assertv `h t v,
-- step case, repeated p-2 times
iterate_exactly (p-2) `[replace h := lucas_lehmer.s_mod_succ w h (by { norm_num, refl })],
-- now close the goal
h ← get_local `h,
exact h
end lucas_lehmer
/-- We verify that the tactic works to prove `127.prime`. -/
example : (mersenne 7).prime := lucas_lehmer_sufficiency _ (by norm_num) (by lucas_lehmer.run_test).
/-!
This implementation works successfully to prove `(2^127 - 1).prime`,
and all the Mersenne primes up to this point appear in [archive/examples/mersenne_primes.lean].
`(2^127 - 1).prime` takes about 5 minutes to run (depending on your CPU!),
and unfortunately the next Mersenne prime `(2^521 - 1)`,
which was the first "computer era" prime,
is out of reach with the current implementation.
There's still low hanging fruit available to do faster computations
based on the formula
```
n ≡ (n % 2^p) + (n / 2^p) [MOD 2^p - 1]
```
and the fact that `% 2^p` and `/ 2^p` can be very efficient on the binary representation.
Someone should do this, too!
-/
lemma modeq_mersenne (n k : ℕ) : k ≡ ((k / 2^n) + (k % 2^n)) [MOD 2^n - 1] :=
-- See https://leanprover.zulipchat.com/#narrow/stream/113489-new-members/topic/help.20finding.20a.20lemma/near/177698446
begin
conv in k { rw ← nat.div_add_mod k (2^n) },
refine nat.modeq.add_right _ _,
conv { congr, skip, skip, rw ← one_mul (k/2^n) },
exact (nat.modeq_sub $ nat.succ_le_of_lt $ pow_pos zero_lt_two _).mul_right _,
end
-- It's hard to know what the limiting factor for large Mersenne primes would be.
-- In the purely computational world, I think it's the squaring operation in `s`.
|
a580dc9470a9482be5d42ae9d39fa3fb7f7cd2d9 | 6432ea7a083ff6ba21ea17af9ee47b9c371760f7 | /tests/lean/tokenErrors.lean | 8a20c89612cd0180915f1e42a2d2ca3447a7cd38 | [
"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 | 65 | lean | #check 'hi
#check '\y'
#check "hi
#check hi.«
/--
#print Nat
/-
|
a3479ff2b1572bdcb0c1050fed6d25b7e9e89de8 | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/data/fin/tuple/sort.lean | 27d0bcc70bfbf311f87f62e0ea7539cb061a1217 | [
"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 | 6,328 | lean | /-
Copyright (c) 2021 Kyle Miller. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kyle Miller
-/
import data.finset.sort
import data.list.fin_range
import data.prod.lex
import group_theory.perm.basic
/-!
# Sorting tuples by their values
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
Given an `n`-tuple `f : fin n → α` where `α` is ordered,
we may want to turn it into a sorted `n`-tuple.
This file provides an API for doing so, with the sorted `n`-tuple given by
`f ∘ tuple.sort f`.
## Main declarations
* `tuple.sort`: given `f : fin n → α`, produces a permutation on `fin n`
* `tuple.monotone_sort`: `f ∘ tuple.sort f` is `monotone`
-/
namespace tuple
variables {n : ℕ}
variables {α : Type*} [linear_order α]
/--
`graph f` produces the finset of pairs `(f i, i)`
equipped with the lexicographic order.
-/
def graph (f : fin n → α) : finset (α ×ₗ (fin n)) :=
finset.univ.image (λ i, (f i, i))
/--
Given `p : α ×ₗ (fin n) := (f i, i)` with `p ∈ graph f`,
`graph.proj p` is defined to be `f i`.
-/
def graph.proj {f : fin n → α} : graph f → α := λ p, p.1.1
@[simp] lemma graph.card (f : fin n → α) : (graph f).card = n :=
begin
rw [graph, finset.card_image_of_injective],
{ exact finset.card_fin _ },
{ intros _ _,
simp }
end
/--
`graph_equiv₁ f` is the natural equivalence between `fin n` and `graph f`,
mapping `i` to `(f i, i)`. -/
def graph_equiv₁ (f : fin n → α) : fin n ≃ graph f :=
{ to_fun := λ i, ⟨(f i, i), by simp [graph]⟩,
inv_fun := λ p, p.1.2,
left_inv := λ i, by simp,
right_inv := λ ⟨⟨x, i⟩, h⟩, by simpa [graph] using h }
@[simp] lemma proj_equiv₁' (f : fin n → α) : graph.proj ∘ graph_equiv₁ f = f :=
rfl
/--
`graph_equiv₂ f` is an equivalence between `fin n` and `graph f` that respects the order.
-/
def graph_equiv₂ (f : fin n → α) : fin n ≃o graph f :=
finset.order_iso_of_fin _ (by simp)
/-- `sort f` is the permutation that orders `fin n` according to the order of the outputs of `f`. -/
def sort (f : fin n → α) : equiv.perm (fin n) :=
(graph_equiv₂ f).to_equiv.trans (graph_equiv₁ f).symm
lemma graph_equiv₂_apply (f : fin n → α) (i : fin n) :
graph_equiv₂ f i = graph_equiv₁ f (sort f i) :=
((graph_equiv₁ f).apply_symm_apply _).symm
lemma self_comp_sort (f : fin n → α) : f ∘ sort f = graph.proj ∘ graph_equiv₂ f :=
show graph.proj ∘ ((graph_equiv₁ f) ∘ (graph_equiv₁ f).symm) ∘ (graph_equiv₂ f).to_equiv = _,
by simp
lemma monotone_proj (f : fin n → α) : monotone (graph.proj : graph f → α) :=
begin
rintro ⟨⟨x, i⟩, hx⟩ ⟨⟨y, j⟩, hy⟩ (_|h),
{ exact le_of_lt ‹_› },
{ simp [graph.proj] },
end
lemma monotone_sort (f : fin n → α) : monotone (f ∘ sort f) :=
begin
rw [self_comp_sort],
exact (monotone_proj f).comp (graph_equiv₂ f).monotone,
end
end tuple
namespace tuple
open list
variables {n : ℕ} {α : Type*}
/-- If two permutations of a tuple `f` are both monotone, then they are equal. -/
lemma unique_monotone [partial_order α] {f : fin n → α} {σ τ : equiv.perm (fin n)}
(hfσ : monotone (f ∘ σ)) (hfτ : monotone (f ∘ τ)) : f ∘ σ = f ∘ τ :=
of_fn_injective $ eq_of_perm_of_sorted
((σ.of_fn_comp_perm f).trans (τ.of_fn_comp_perm f).symm) hfσ.of_fn_sorted hfτ.of_fn_sorted
variables [linear_order α] {f : fin n → α} {σ : equiv.perm (fin n)}
/-- A permutation `σ` equals `sort f` if and only if the map `i ↦ (f (σ i), σ i)` is
strictly monotone (w.r.t. the lexicographic ordering on the target). -/
lemma eq_sort_iff' : σ = sort f ↔ strict_mono (σ.trans $ graph_equiv₁ f) :=
begin
split; intro h,
{ rw [h, sort, equiv.trans_assoc, equiv.symm_trans_self], exact (graph_equiv₂ f).strict_mono },
{ have := subsingleton.elim (graph_equiv₂ f) (h.order_iso_of_surjective _ $ equiv.surjective _),
ext1, exact (graph_equiv₁ f).apply_eq_iff_eq_symm_apply.1 (fun_like.congr_fun this x).symm },
end
/-- A permutation `σ` equals `sort f` if and only if `f ∘ σ` is monotone and whenever `i < j`
and `f (σ i) = f (σ j)`, then `σ i < σ j`. This means that `sort f` is the lexicographically
smallest permutation `σ` such that `f ∘ σ` is monotone. -/
lemma eq_sort_iff : σ = sort f ↔ monotone (f ∘ σ) ∧ ∀ i j, i < j → f (σ i) = f (σ j) → σ i < σ j :=
begin
rw eq_sort_iff',
refine ⟨λ h, ⟨(monotone_proj f).comp h.monotone, λ i j hij hfij, _⟩, λ h i j hij, _⟩,
{ exact (((prod.lex.lt_iff _ _).1 $ h hij).resolve_left hfij.not_lt).2 },
{ obtain he|hl := (h.1 hij.le).eq_or_lt; apply (prod.lex.lt_iff _ _).2,
exacts [or.inr ⟨he, h.2 i j hij he⟩, or.inl hl] },
end
/-- The permutation that sorts `f` is the identity if and only if `f` is monotone. -/
lemma sort_eq_refl_iff_monotone : sort f = equiv.refl _ ↔ monotone f :=
begin
rw [eq_comm, eq_sort_iff, equiv.coe_refl, function.comp.right_id],
simp only [id.def, and_iff_left_iff_imp],
exact λ _ _ _ hij _, hij,
end
/-- A permutation of a tuple `f` is `f` sorted if and only if it is monotone. -/
lemma comp_sort_eq_comp_iff_monotone : f ∘ σ = f ∘ sort f ↔ monotone (f ∘ σ) :=
⟨λ h, h.symm ▸ monotone_sort f, λ h, unique_monotone h (monotone_sort f)⟩
/-- The sorted versions of a tuple `f` and of any permutation of `f` agree. -/
lemma comp_perm_comp_sort_eq_comp_sort : (f ∘ σ) ∘ (sort (f ∘ σ)) = f ∘ sort f :=
begin
rw [function.comp.assoc, ← equiv.perm.coe_mul],
exact unique_monotone (monotone_sort (f ∘ σ)) (monotone_sort f),
end
/-- If a permutation `f ∘ σ` of the tuple `f` is not the same as `f ∘ sort f`, then `f ∘ σ`
has a pair of strictly decreasing entries. -/
lemma antitone_pair_of_not_sorted' (h : f ∘ σ ≠ f ∘ sort f) :
∃ i j, i < j ∧ (f ∘ σ) j < (f ∘ σ) i :=
by { contrapose! h, exact comp_sort_eq_comp_iff_monotone.mpr (monotone_iff_forall_lt.mpr h) }
/-- If the tuple `f` is not the same as `f ∘ sort f`, then `f` has a pair of strictly decreasing
entries. -/
lemma antitone_pair_of_not_sorted (h : f ≠ f ∘ sort f) : ∃ i j, i < j ∧ f j < f i :=
antitone_pair_of_not_sorted' (id h : f ∘ equiv.refl _ ≠ _)
end tuple
|
69c5311f493dbbca9b5b48a5b0ada6466232da3d | 5d166a16ae129621cb54ca9dde86c275d7d2b483 | /tests/lean/run/imp3.lean | c77cda007b36aaa184f1d9d17283519c6b57d4dd | [
"Apache-2.0"
] | permissive | jcarlson23/lean | b00098763291397e0ac76b37a2dd96bc013bd247 | 8de88701247f54d325edd46c0eed57aeacb64baf | refs/heads/master | 1,611,571,813,719 | 1,497,020,963,000 | 1,497,021,515,000 | 93,882,536 | 1 | 0 | null | 1,497,029,896,000 | 1,497,029,896,000 | null | UTF-8 | Lean | false | false | 237 | lean | structure [class] is_equiv {A B : Type} (f : A → B) :=
(inv : B → A)
#check @is_equiv.inv
namespace is_equiv
section
parameters A B : Type
parameter f : A → B
parameter c : is_equiv f
#check inv f
end
end is_equiv
|
a9c12553056a90d2f0f75cb05b4fbd55a5d57894 | 510e96af568b060ed5858226ad954c258549f143 | /data/list/comb.lean | 3becb23575b139d66f406d9551af013f4a9b4282 | [] | no_license | Shamrock-Frost/library_dev | cb6d1739237d81e17720118f72ba0a6db8a5906b | 0245c71e4931d3aceeacf0aea776454f6ee03c9c | refs/heads/master | 1,609,481,034,595 | 1,500,165,215,000 | 1,500,165,347,000 | 97,350,162 | 0 | 0 | null | 1,500,164,969,000 | 1,500,164,969,000 | null | UTF-8 | Lean | false | false | 19,924 | lean | /-
Copyright (c) 2015 Leonardo de Moura. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
αuthors: Leonardo de Moura, Haitao Zhang, Floris van Doorn, Jeremy Avigad
List combinators.
-/
-- TODO(Leo): uncomment data.equiv after refactoring
import .basic ..bool data.list.comb --data.bool logic.basic -- data.equiv
open nat prod decidable function
namespace list
universe variables uu vv ww
variables {α : Type uu} {β : Type vv} {γ : Type ww}
-- TODO(Jeremy): this file is a good testing ground for super and auto
section replicate
-- 'replicate n a' returns the list that contains n copies of a.
def replicate : ℕ → α → list α
| 0 a := []
| (succ n) a := a :: replicate n a
@[simp]
theorem length_replicate : ∀ (i : ℕ) (a : α), length (replicate i a) = i
| 0 a := rfl
| (succ i) a := congr_arg succ (length_replicate i a)
end replicate
/- map -/
attribute [simp] map_cons
/-def map₂ (f : α → β → γ) : list α → list β → list γ
| [] _ := []
| _ [] := []
| (x::xs) (y::ys) := f x y :: map₂ xs ys-/
theorem map₂_nil1 (f : α → β → γ) : ∀ (l : list β), map₂ f [] l = []
| [] := rfl
| (a::y) := rfl
theorem map₂_nil2 (f : α → β → γ) : ∀ (l : list α), map₂ f l [] = []
| [] := rfl
| (a::y) := rfl
/- TODO(Jeremy): there is an overload ambiguity between min and nat.min -/
/-theorem length_map₂ : ∀ (f : α → β → γ) x y, length (map₂ f x y) = _root_.min (length x) (length y)
| f [] [] := rfl
| f (xh::xr) [] := rfl
| f [] (yh::yr) := rfl
| f (xh::xr) (yh::yr) := calc
length (map₂ f (xh::xr) (yh::yr))
= length (map₂ f xr yr) + 1 : rfl
... = _root_.min (length xr) (length yr) + 1 : by rw length_map₂
... = _root_.min (succ (length xr)) (succ (length yr))
: begin rw min_succ_succ, reflexivity end
... = _root_.min (length (xh::xr)) (length (yh::yr)) : rfl-/
section foldl_eq_foldr
-- foldl and foldr coincide when f is commutative and associative
variables {f : α → α → α} (hcomm : ∀ a b, f a b = f b a) (hassoc : ∀ a b c, f (f a b) c = f a (f b c))
include hcomm hassoc
theorem foldl_eq_of_comm_of_assoc : ∀ a b l, foldl f a (b::l) = f b (foldl f a l)
| a b nil := hcomm a b
| a b (c::l) :=
begin
change foldl f (f (f a b) c) l = f b (foldl f (f a c) l),
rw ←foldl_eq_of_comm_of_assoc,
change foldl f (f (f a b) c) l = foldl f (f (f a c) b) l,
have h₁ : f (f a b) c = f (f a c) b, { rw [hassoc, hassoc, hcomm b c] },
rw h₁
end
theorem foldl_eq_foldr : ∀ a l, foldl f a l = foldr f a l
| a nil := rfl
| a (b :: l) :=
begin
simp [foldl_eq_of_comm_of_assoc hcomm hassoc],
change f b (foldl f a l) = f b (foldr f a l),
rw (foldl_eq_foldr a l)
end
end foldl_eq_foldr
/- all & any -/
@[simp]
theorem all_nil (p : α → bool) : all [] p = tt := rfl
@[simp]
theorem all_cons (p : α → bool) (a : α) (l : list α) : all (a::l) p = (p a && all l p) := rfl
theorem all_eq_tt_of_forall {p : α → bool} : ∀ {l : list α}, (∀ a ∈ l, p a = tt) → all l p = tt
| [] h := all_nil p
| (a::l) h := begin
simp [all_cons, h a],
rw all_eq_tt_of_forall,
intros a ha, simp [h a, ha] end
theorem forall_mem_eq_tt_of_all_eq_tt {p : α → bool} :
∀ {l : list α}, all l p = tt → ∀ a ∈ l, p a = tt
| [] h := assume a h, absurd h (not_mem_nil a)
| (b::l) h := assume a, suppose a ∈ b::l,
begin
simp [bool.band_eq_tt] at h, cases h with h₁ h₂,
simp at this, cases this with h' h',
simp [*],
exact forall_mem_eq_tt_of_all_eq_tt h₂ _ h'
end
theorem all_eq_tt_iff {p : α → bool} {l : list α} : all l p = tt ↔ ∀ a ∈ l, p a = tt :=
iff.intro forall_mem_eq_tt_of_all_eq_tt all_eq_tt_of_forall
@[simp]
theorem any_nil (p : α → bool) : any [] p = ff := rfl
@[simp]
theorem any_cons (p : α → bool) (a : α) (l : list α) : any (a::l) p = (p a || any l p) := rfl
theorem any_of_mem {p : α → bool} {a : α} : ∀ {l : list α}, a ∈ l → p a = tt → any l p = tt
| [] i h := absurd i (not_mem_nil a)
| (b::l) i h :=
or.elim (eq_or_mem_of_mem_cons i)
(suppose a = b, begin simp [this^.symm, bool.bor_eq_tt], exact (or.inl h) end)
(suppose a ∈ l, begin
cases (eq_or_mem_of_mem_cons i) with h' h',
{ simp [h'^.symm, h] },
simp [bool.bor_eq_tt, any_of_mem h', h]
end)
theorem exists_of_any_eq_tt {p : α → bool} : ∀ {l : list α}, any l p = tt → ∃ a : α, a ∈ l ∧ p a
| [] h := begin simp at h, contradiction end
| (b::l) h := begin
simp [bool.bor_eq_tt] at h, cases h with h h,
{ existsi b, simp [h]},
cases (exists_of_any_eq_tt h) with a ha,
existsi a, apply (and.intro (or.inr ha^.left) ha^.right)
end
theorem any_eq_tt_iff {p : α → bool} {l : list α} : any l p = tt ↔ ∃ a : α, a ∈ l ∧ p a = tt :=
iff.intro exists_of_any_eq_tt (begin intro h, cases h with a ha, apply any_of_mem ha^.left ha^.right end)
/- bounded quantifiers over lists -/
theorem forall_mem_nil (p : α → Prop) : ∀ x ∈ @nil α, p x :=
assume x xnil, absurd xnil (not_mem_nil x)
theorem forall_mem_cons {p : α → Prop} {a : α} {l : list α} (pa : p a) (h : ∀ x ∈ l, p x) :
∀ x ∈ a :: l, p x :=
assume x xal, or.elim (eq_or_mem_of_mem_cons xal)
(suppose x = a, by simp [this, pa])
(suppose x ∈ l, by simp [this, h])
theorem of_forall_mem_cons {p : α → Prop} {a : α} {l : list α} (h : ∀ x ∈ a :: l, p x) : p a :=
h a (by simp)
theorem forall_mem_of_forall_mem_cons {p : α → Prop} {a : α} {l : list α}
(h : ∀ x ∈ a :: l, p x) :
∀ x ∈ l, p x :=
assume x xl, h x (by simp [xl])
@[simp]
theorem forall_mem_cons_iff (p : α → Prop) (a : α) (l : list α) :
(∀ x ∈ a :: l, p x) ↔ p a ∧ ∀ x ∈ l, p x :=
iff.intro
(λ h, ⟨of_forall_mem_cons h, forall_mem_of_forall_mem_cons h⟩)
(λ h, forall_mem_cons h^.left h^.right)
theorem not_exists_mem_nil (p : α → Prop) : ¬ ∃ x ∈ @nil α, p x :=
assume h, bexists.elim h (λ a anil, absurd anil (not_mem_nil a))
theorem exists_mem_cons_of {p : α → Prop} {a : α} (l : list α) (h : p a) :
∃ x ∈ a :: l, p x :=
bexists.intro a (by simp) h
theorem exists_mem_cons_of_exists {p : α → Prop} {a : α} {l : list α} (h : ∃ x ∈ l, p x) :
∃ x ∈ a :: l, p x :=
bexists.elim h (λ x xl px, bexists.intro x (by simp [xl]) px)
theorem or_exists_of_exists_mem_cons {p : α → Prop} {a : α} {l : list α} (h : ∃ x ∈ a :: l, p x) :
p a ∨ ∃ x ∈ l, p x :=
bexists.elim h (λ x xal px,
or.elim (eq_or_mem_of_mem_cons xal)
(suppose x = a, begin rw ←this, simp [px] end)
(suppose x ∈ l, or.inr (bexists.intro x this px)))
@[simp]
theorem exists_mem_cons_iff (p : α → Prop) (a : α) (l : list α) :
(∃ x ∈ a :: l, p x) ↔ p a ∨ ∃ x ∈ l, p x :=
iff.intro or_exists_of_exists_mem_cons
(assume h, or.elim h (exists_mem_cons_of l) exists_mem_cons_of_exists)
@[instance]
def decidable_forall_mem {p : α → Prop} [h : decidable_pred p] :
∀ l : list α, decidable (∀ x ∈ l, p x)
| [] := is_true (forall_mem_nil p)
| (a :: l) := decidable_of_decidable_of_iff
(@and.decidable _ _ _ (decidable_forall_mem l))
(forall_mem_cons_iff p a l)^.symm
@[instance]
def decidable_exists_mem {p : α → Prop} [h : decidable_pred p] :
∀ l : list α, decidable (∃ x ∈ l, p x)
| [] := is_false (not_exists_mem_nil p)
| (a :: l) := decidable_of_decidable_of_iff
(@or.decidable _ _ _ (decidable_exists_mem l))
(exists_mem_cons_iff p a l)^.symm
/- zip & unzip -/
@[simp]
theorem zip_cons_cons (a : α) (b : β) (l₁ : list α) (l₂ : list β) :
zip (a :: l₁) (b :: l₂) = (a, b) :: zip l₁ l₂ := rfl
@[simp]
theorem zip_nil_left (l : list α) : zip ([] : list β) l = [] := rfl
@[simp]
theorem zip_nil_right (l : list α) : zip l ([] : list β) = [] :=
begin cases l, reflexivity, reflexivity end
@[simp]
theorem unzip_nil : unzip (@nil (α × β)) = ([], []) := rfl
theorem unzip_cons' (a : α) (b : β) (l : list (α × β)) :
unzip ((a, b) :: l) = match (unzip l) with (la, lb) := (a :: la, b :: lb) end :=
rfl
-- TODO(Jeremy): it seems this version is better for the simplifier
@[simp]
theorem unzip_cons (a : α) (b : β) (l : list (α × β)) :
unzip ((a, b) :: l) = let p := unzip l in (a :: p.1, b :: p.2) :=
begin rw unzip_cons', cases unzip l, reflexivity end
theorem zip_unzip : ∀ (l : list (α × β)), zip (unzip l).1 (unzip l).2 = l
| [] := rfl
| ((a, b) :: l) := begin simp [zip_unzip l] end
-- TODO(Jeremy): this is as far as I got
section mapAccumR
variable {S : Type}
-- This runs a function over a list returning the intermediate results and a
-- a final result.
def mapAccumR : (α → S → S × β) → list α → S → (S × list β)
| f [] c := (c, [])
| f (y::yr) c :=
let r := mapAccumR f yr c in
let z := f y r.1 in
(z.1, z.2 :: r.2)
theorem length_mapAccumR :
∀ (f : α → S → S × β) (x : list α) (s : S),
length (mapAccumR f x s).2 = length x
| f (a::x) s := calc
length (snd (mapAccumR f (a::x) s))
= length x + 1 : begin rw ←(length_mapAccumR f x s), reflexivity end
... = length (a::x) : rfl
| f [] s := calc length (snd (mapAccumR f [] s)) = 0 : by reflexivity
end mapAccumR
section mapAccumR₂
variable {S : Type uu}
-- This runs a function over two lists returning the intermediate results and a
-- a final result.
def mapAccumR₂
: (α → β → S → S × γ) → list α → list β → S → S × list γ
| f [] _ c := (c,[])
| f _ [] c := (c,[])
| f (x::xr) (y::yr) c :=
let r := mapAccumR₂ f xr yr c in
let q := f x y r.1 in
(q.1, q.2 :: r.2)
-- TODO(Jeremy) : again the "min" overload
theorem length_mapAccumR₂ : ∀ (f : α → β → S → S × γ) (x : list α) (y : list β) (c : S),
length (mapAccumR₂ f x y c).2 = _root_.min (length x) (length y)
| f (a::x) (b::y) c := calc
length (snd (mapAccumR₂ f (a::x) (b::y) c))
= length (snd (mapAccumR₂ f x y c)) + 1 : rfl
... = _root_.min (length x) (length y) + 1 : by rw (length_mapAccumR₂ f x y c)
... = _root_.min (succ (length x)) (succ (length y)) : begin rw min_succ_succ end
... = _root_.min (length (a::x)) (length (b::y)) : rfl
| f (a::x) [] c := rfl
| f [] (b::y) c := rfl
| f [] [] c := rfl
end mapAccumR₂
/- flat -/
def flat (l : list (list α)) : list α :=
foldl append nil l
/- product -/
section product
def product : list α → list β → list (α × β)
| [] l₂ := []
| (a::l₁) l₂ := map (λ b, (a, b)) l₂ ++ product l₁ l₂
theorem nil_product (l : list β) : product (@nil α) l = [] := rfl
theorem product_cons (a : α) (l₁ : list α) (l₂ : list β)
: product (a::l₁) l₂ = map (λ b, (a, b)) l₂ ++ product l₁ l₂ := rfl
theorem product_nil : ∀ (l : list α), product l (@nil β) = []
| [] := rfl
| (a::l) := begin rw [product_cons, product_nil], reflexivity end
theorem eq_of_mem_map_pair₁ {a₁ a : α} {b₁ : β} {l : list β} :
(a₁, b₁) ∈ map (λ b, (a, b)) l → a₁ = a :=
assume ain,
have fst (a₁, b₁) ∈ map fst (map (λ b, (a, b)) l), from mem_map fst ain,
have a₁ ∈ map (λb, a) l, begin revert this, rw [map_map], intro this, assumption end,
eq_of_map_const this
theorem mem_of_mem_map_pair₁ {a₁ a : α} {b₁ : β} {l : list β} :
(a₁, b₁) ∈ map (λ b, (a, b)) l → b₁ ∈ l :=
assume ain,
have snd (a₁, b₁) ∈ map snd (map (λ b, (a, b)) l), from mem_map snd ain,
have b₁ ∈ map id l, begin rw [map_map] at this, exact this end,
begin rw [map_id] at this, exact this end
theorem mem_product {a : α} {b : β} : ∀ {l₁ l₂}, a ∈ l₁ → b ∈ l₂ → (a, b) ∈ @product α β l₁ l₂
| [] l₂ h₁ h₂ := absurd h₁ (not_mem_nil _)
| (x::l₁) l₂ h₁ h₂ :=
or.elim (eq_or_mem_of_mem_cons h₁)
(assume aeqx : a = x,
have (a, b) ∈ map (λ b, (a, b)) l₂, from mem_map _ h₂,
begin rw [←aeqx, product_cons], exact mem_append_left _ this end)
(assume ainl₁ : a ∈ l₁,
have (a, b) ∈ product l₁ l₂, from mem_product ainl₁ h₂,
begin rw [product_cons], exact mem_append_right _ this end)
theorem mem_of_mem_product_left {a : α} {b : β} : ∀ {l₁ l₂}, (a, b) ∈ @product α β l₁ l₂ → a ∈ l₁
| [] l₂ h := absurd h (not_mem_nil _)
| (x::l₁) l₂ h :=
or.elim (mem_or_mem_of_mem_append h)
(suppose (a, b) ∈ map (λ b, (x, b)) l₂,
have a = x, from eq_of_mem_map_pair₁ this,
begin rw this, apply mem_cons_self end)
(suppose (a, b) ∈ product l₁ l₂,
have a ∈ l₁, from mem_of_mem_product_left this,
mem_cons_of_mem _ this)
theorem mem_of_mem_product_right {a : α} {b : β} : ∀ {l₁ l₂}, (a, b) ∈ @product α β l₁ l₂ → b ∈ l₂
| [] l₂ h := absurd h (not_mem_nil ((a, b)))
| (x::l₁) l₂ h :=
or.elim (mem_or_mem_of_mem_append h)
(suppose (a, b) ∈ map (λ b, (x, b)) l₂,
mem_of_mem_map_pair₁ this)
(suppose (a, b) ∈ product l₁ l₂,
mem_of_mem_product_right this)
theorem length_product :
∀ (l₁ : list α) (l₂ : list β), length (product l₁ l₂) = length l₁ * length l₂
| [] l₂ := begin simp, reflexivity end
| (x::l₁) l₂ :=
have length (product l₁ l₂) = length l₁ * length l₂, from length_product l₁ l₂,
by rw [product_cons, length_append, length_cons,
length_map, this, right_distrib, one_mul, add_comm]
end product
-- new for list/comb dependent map theory
def dinj₁ (p : α → Prop) (f : Π a, p a → β) := ∀ ⦃a1 a2⦄ (h1 : p a1) (h2 : p a2), a1 ≠ a2 → (f a1 h1) ≠ (f a2 h2)
def dinj (p : α → Prop) (f : Π a, p a → β) := ∀ ⦃a1 a2⦄ (h1 : p a1) (h2 : p a2), (f a1 h1) = (f a2 h2) → a1 = a2
def dmap (p : α → Prop) [h : decidable_pred p] (f : Π a, p a → β) : list α → list β
| [] := []
| (a::l) := if P : (p a) then cons (f a P) (dmap l) else (dmap l)
-- properties of dmap
section dmap
variable {p : α → Prop}
variable [h : decidable_pred p]
include h
variable {f : Π a, p a → β}
lemma dmap_nil : dmap p f [] = [] := rfl
lemma dmap_cons_of_pos {a : α} (P : p a) : ∀ l, dmap p f (a::l) = (f a P) :: dmap p f l :=
λ l, dif_pos P
lemma dmap_cons_of_neg {a : α} (P : ¬ p a) : ∀ l, dmap p f (a::l) = dmap p f l :=
λ l, dif_neg P
lemma mem_dmap : ∀ {l : list α} {a} (Pa : p a), a ∈ l → (f a Pa) ∈ dmap p f l
| [] := assume a Pa Pinnil, absurd Pinnil (not_mem_nil _)
| (a::l) := assume b Pb Pbin, or.elim (eq_or_mem_of_mem_cons Pbin)
(assume Pbeqa, begin
rw [eq.symm Pbeqa, dmap_cons_of_pos Pb],
apply mem_cons_self
end)
(assume Pbinl,
if pa : p a then
begin
rw [dmap_cons_of_pos pa],
apply mem_cons_of_mem,
exact mem_dmap Pb Pbinl
end
else
begin
rw [dmap_cons_of_neg pa],
exact mem_dmap Pb Pbinl
end)
lemma exists_of_mem_dmap : ∀ {l : list α} {b : β}, b ∈ dmap p f l → ∃ a P, a ∈ l ∧ b = f a P
| [] := assume b, begin rw dmap_nil, intro h, exact absurd h (not_mem_nil _) end
| (a::l) := assume b,
if Pa : p a then
begin
rw [dmap_cons_of_pos Pa, mem_cons_iff],
intro Pb, cases Pb with Peq Pin,
exact exists.intro a (exists.intro Pa (and.intro (mem_cons_self _ _) Peq)),
have Pex : ∃ (a : α) (P : p a), a ∈ l ∧ b = f a P, exact exists_of_mem_dmap Pin,
cases Pex with a' Pex', cases Pex' with Pa' P',
exact exists.intro a' (exists.intro Pa' (and.intro (mem_cons_of_mem a (and.left P'))
(and.right P')))
end
else
begin
rw [dmap_cons_of_neg Pa],
intro Pin,
have Pex : ∃ (a : α) (P : p a), a ∈ l ∧ b = f a P, exact exists_of_mem_dmap Pin,
cases Pex with a' Pex', cases Pex' with Pa' P',
exact exists.intro a' (exists.intro Pa' (and.intro (mem_cons_of_mem a (and.left P'))
(and.right P')))
end
lemma map_dmap_of_inv_of_pos {g : β → α} (Pinv : ∀ a (Pa : p a), g (f a Pa) = a) :
∀ {l : list α}, (∀ ⦃a⦄, a ∈ l → p a) → map g (dmap p f l) = l
| [] := assume Pl, by rw [dmap_nil]; reflexivity
| (a::l) := assume Pal,
have Pa : p a, from Pal (mem_cons_self _ _),
have Pl : ∀ a, a ∈ l → p a,
from assume x Pxin, Pal (mem_cons_of_mem a Pxin),
by rw [dmap_cons_of_pos Pa, map_cons, Pinv, map_dmap_of_inv_of_pos Pl]
lemma mem_of_dinj_of_mem_dmap (Pdi : dinj p f) :
∀ {l : list α} {a} (Pa : p a), (f a Pa) ∈ dmap p f l → a ∈ l
| [] := assume a Pa Pinnil, absurd Pinnil (not_mem_nil _)
| (b::l) := assume a Pa Pmap,
if Pb : p b then
begin
rw (dmap_cons_of_pos Pb) at Pmap,
rw mem_cons_iff at Pmap,
rw mem_cons_iff,
cases Pmap with h h,
left, apply Pdi Pa Pb h,
right, apply mem_of_dinj_of_mem_dmap Pa h
end
else
begin
rw (dmap_cons_of_neg Pb) at Pmap,
apply mem_cons_of_mem,
exact mem_of_dinj_of_mem_dmap Pa Pmap
end
lemma not_mem_dmap_of_dinj_of_not_mem (Pdi : dinj p f) {l : list α} {a} (Pa : p a) :
a ∉ l → (f a Pa) ∉ dmap p f l :=
mt (mem_of_dinj_of_mem_dmap Pdi Pa)
end dmap
/-
section
open equiv
def list_equiv_of_equiv {α β : Type} : α ≃ β → list α ≃ list β
| (mk f g l r) :=
mk (map f) (map g)
begin intros, rw [map_map, id_of_left_inverse l, map_id], try reflexivity end
begin intros, rw [map_map, id_of_right_inverse r, map_id], try reflexivity end
private def to_nat : list nat → nat
| [] := 0
| (x::xs) := succ (mkpair (to_nat xs) x)
open prod.ops
private def of_nat.F : Π (n : nat), (Π m, m < n → list nat) → list nat
| 0 f := []
| (succ n) f := (unpair n).2 :: f (unpair n).1 (unpair_lt n)
private def of_nat : nat → list nat :=
well_founded.fix of_nat.F
private lemma of_nat_zero : of_nat 0 = [] :=
well_founded.fix_eq of_nat.F 0
private lemma of_nat_succ (n : nat)
: of_nat (succ n) = (unpair n).2 :: of_nat (unpair n).1 :=
well_founded.fix_eq of_nat.F (succ n)
private lemma to_nat_of_nat (n : nat) : to_nat (of_nat n) = n :=
nat.case_strong_induction_on n
_
(λ n ih,
begin
rw of_nat_succ, unfold to_nat,
have to_nat (of_nat (unpair n).1) = (unpair n).1, from ih _ (le_of_lt_succ (unpair_lt n)),
rw this, rw mkpair_unpair
end)
private lemma of_nat_to_nat : ∀ (l : list nat), of_nat (to_nat l) = l
| [] := rfl
| (x::xs) := begin unfold to_nat, rw of_nat_succ, rw *unpair_mkpair, esimp, congruence, apply of_nat_to_nat end
def list_nat_equiv_nat : list nat ≃ nat :=
mk to_nat of_nat of_nat_to_nat to_nat_of_nat
def list_equiv_self_of_equiv_nat {α : Type} : α ≃ nat → list α ≃ α :=
suppose α ≃ nat, calc
list α ≃ list nat : list_equiv_of_equiv this
... ≃ nat : list_nat_equiv_nat
... ≃ α : this
end
-/
end list
|
e50612088b790ec6820b57c755b876eaa2fd94cd | 0d7f5899c0475f9e105a439896d9377f80c0d7c3 | /src/.old/fron_ualg.lean | 5c9bbde67d60cf43fcd958172ca8dadf5113f0f1 | [] | no_license | adamtopaz/UnivAlg | 127038f320e68cdf3efcd0c084c9af02fdb8da3d | 2458d47a6e4fd0525e3a25b07cb7dd518ac173ef | refs/heads/master | 1,670,320,985,286 | 1,597,350,882,000 | 1,597,350,882,000 | 280,585,500 | 4 | 0 | null | 1,597,350,883,000 | 1,595,048,527,000 | Lean | UTF-8 | Lean | false | false | 933 | lean | import .add_rules
import .fron_ralg
namespace ualg
variables {L0 : lang} {R0 : rules L0}
variables {L : lang} {R : rules L}
variables (ι : R0 →$ R) (A : ualg L0 R0)
include ι A
def fron : ualg L R := addr (ralg.fron ι.lhom A.raw) R
namespace fron
def univ : A →% (fron ι A)⦃ι⦄ :=
(ralg.fron.univ ι.lhom A.raw).comp ((ualg.addr.univ (ralg.fron ι.lhom A.raw) R){%ι.lhom})
variable {A}
def lift {B : ualg L R} (f : A →% B⦃ι⦄) : (fron ι A) →% B := ualg.addr.lift R (ralg.fron.lift ι.lhom f)
theorem univ_comp_lift {B : ualg L R} (f : A →% B⦃ι⦄) : (univ ι A).comp ((lift ι f){%ι.lhom}) = f :=
by apply ralg.fron.univ_comp_lift
theorem lift_unique {B : ualg L R} (f : A →% B⦃ι⦄) (g : (fron ι A) →% B) :
(univ ι A).comp (g{%ι.lhom}) = f → g = lift ι f :=
begin
intro hyp,
apply ualg.addr.lift_unique,
apply ralg.fron.lift_unique,
assumption,
end
end fron
end ualg |
a1676ff1bbe51eaf059f36305b4512694ef4107b | 8d65764a9e5f0923a67fc435eb1a5a1d02fd80e3 | /src/topology/uniform_space/basic.lean | 2233c2ee3a6ea149375c7d726c7a31514662b31d | [
"Apache-2.0"
] | permissive | troyjlee/mathlib | e18d4b8026e32062ab9e89bc3b003a5d1cfec3f5 | 45e7eb8447555247246e3fe91c87066506c14875 | refs/heads/master | 1,689,248,035,046 | 1,629,470,528,000 | 1,629,470,528,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 68,572 | lean | /-
Copyright (c) 2017 Johannes Hölzl. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johannes Hölzl, Mario Carneiro, Patrick Massot
-/
import order.filter.lift
import topology.separation
/-!
# Uniform spaces
Uniform spaces are a generalization of metric spaces and topological groups. Many concepts directly
generalize to uniform spaces, e.g.
* uniform continuity (in this file)
* completeness (in `cauchy.lean`)
* extension of uniform continuous functions to complete spaces (in `uniform_embedding.lean`)
* totally bounded sets (in `cauchy.lean`)
* totally bounded complete sets are compact (in `cauchy.lean`)
A uniform structure on a type `X` is a filter `𝓤 X` on `X × X` satisfying some conditions
which makes it reasonable to say that `∀ᶠ (p : X × X) in 𝓤 X, ...` means
"for all p.1 and p.2 in X close enough, ...". Elements of this filter are called entourages
of `X`. The two main examples are:
* If `X` is a metric space, `V ∈ 𝓤 X ↔ ∃ ε > 0, { p | dist p.1 p.2 < ε } ⊆ V`
* If `G` is an additive topological group, `V ∈ 𝓤 G ↔ ∃ U ∈ 𝓝 (0 : G), {p | p.2 - p.1 ∈ U} ⊆ V`
Those examples are generalizations in two different directions of the elementary example where
`X = ℝ` and `V ∈ 𝓤 ℝ ↔ ∃ ε > 0, { p | |p.2 - p.1| < ε } ⊆ V` which features both the topological
group structure on `ℝ` and its metric space structure.
Each uniform structure on `X` induces a topology on `X` characterized by
> `nhds_eq_comap_uniformity : ∀ {x : X}, 𝓝 x = comap (prod.mk x) (𝓤 X)`
where `prod.mk x : X → X × X := (λ y, (x, y))` is the partial evaluation of the product
constructor.
The dictionary with metric spaces includes:
* an upper bound for `dist x y` translates into `(x, y) ∈ V` for some `V ∈ 𝓤 X`
* a ball `ball x r` roughly corresponds to `uniform_space.ball x V := {y | (x, y) ∈ V}`
for some `V ∈ 𝓤 X`, but the later is more general (it includes in
particular both open and closed balls for suitable `V`).
In particular we have:
`is_open_iff_ball_subset {s : set X} : is_open s ↔ ∀ x ∈ s, ∃ V ∈ 𝓤 X, ball x V ⊆ s`
The triangle inequality is abstracted to a statement involving the composition of relations in `X`.
First note that the triangle inequality in a metric space is equivalent to
`∀ (x y z : X) (r r' : ℝ), dist x y ≤ r → dist y z ≤ r' → dist x z ≤ r + r'`.
Then, for any `V` and `W` with type `set (X × X)`, the composition `V ○ W : set (X × X)` is
defined as `{ p : X × X | ∃ z, (p.1, z) ∈ V ∧ (z, p.2) ∈ W }`.
In the metric space case, if `V = { p | dist p.1 p.2 ≤ r }` and `W = { p | dist p.1 p.2 ≤ r' }`
then the triangle inequality, as reformulated above, says `V ○ W` is contained in
`{p | dist p.1 p.2 ≤ r + r'}` which is the entourage associated to the radius `r + r'`.
In general we have `mem_ball_comp (h : y ∈ ball x V) (h' : z ∈ ball y W) : z ∈ ball x (V ○ W)`.
Note that this discussion does not depend on any axiom imposed on the uniformity filter,
it is simply captured by the definition of composition.
The uniform space axioms ask the filter `𝓤 X` to satisfy the following:
* every `V ∈ 𝓤 X` contains the diagonal `id_rel = { p | p.1 = p.2 }`. This abstracts the fact
that `dist x x ≤ r` for every non-negative radius `r` in the metric space case and also that
`x - x` belongs to every neighborhood of zero in the topological group case.
* `V ∈ 𝓤 X → prod.swap '' V ∈ 𝓤 X`. This is tightly related the fact that `dist x y = dist y x`
in a metric space, and to continuity of negation in the topological group case.
* `∀ V ∈ 𝓤 X, ∃ W ∈ 𝓤 X, W ○ W ⊆ V`. In the metric space case, it corresponds
to cutting the radius of a ball in half and applying the triangle inequality.
In the topological group case, it comes from continuity of addition at `(0, 0)`.
These three axioms are stated more abstractly in the definition below, in terms of
operations on filters, without directly manipulating entourages.
## Main definitions
* `uniform_space X` is a uniform space structure on a type `X`
* `uniform_continuous f` is a predicate saying a function `f : α → β` between uniform spaces
is uniformly continuous : `∀ r ∈ 𝓤 β, ∀ᶠ (x : α × α) in 𝓤 α, (f x.1, f x.2) ∈ r`
In this file we also define a complete lattice structure on the type `uniform_space X`
of uniform structures on `X`, as well as the pullback (`uniform_space.comap`) of uniform structures
coming from the pullback of filters.
Like distance functions, uniform structures cannot be pushed forward in general.
## Notations
Localized in `uniformity`, we have the notation `𝓤 X` for the uniformity on a uniform space `X`,
and `○` for composition of relations, seen as terms with type `set (X × X)`.
## Implementation notes
There is already a theory of relations in `data/rel.lean` where the main definition is
`def rel (α β : Type*) := α → β → Prop`.
The relations used in the current file involve only one type, but this is not the reason why
we don't reuse `data/rel.lean`. We use `set (α × α)`
instead of `rel α α` because we really need sets to use the filter library, and elements
of filters on `α × α` have type `set (α × α)`.
The structure `uniform_space X` bundles a uniform structure on `X`, a topology on `X` and
an assumption saying those are compatible. This may not seem mathematically reasonable at first,
but is in fact an instance of the forgetful inheritance pattern. See Note [forgetful inheritance]
below.
## References
The formalization uses the books:
* [N. Bourbaki, *General Topology*][bourbaki1966]
* [I. M. James, *Topologies and Uniformities*][james1999]
But it makes a more systematic use of the filter library.
-/
open set filter classical
open_locale classical topological_space filter
set_option eqn_compiler.zeta true
universes u
/-!
### Relations, seen as `set (α × α)`
-/
variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} {ι : Sort*}
/-- The identity relation, or the graph of the identity function -/
def id_rel {α : Type*} := {p : α × α | p.1 = p.2}
@[simp] theorem mem_id_rel {a b : α} : (a, b) ∈ @id_rel α ↔ a = b := iff.rfl
@[simp] theorem id_rel_subset {s : set (α × α)} : id_rel ⊆ s ↔ ∀ a, (a, a) ∈ s :=
by simp [subset_def]; exact forall_congr (λ a, by simp)
/-- The composition of relations -/
def comp_rel {α : Type u} (r₁ r₂ : set (α×α)) := {p : α × α | ∃z:α, (p.1, z) ∈ r₁ ∧ (z, p.2) ∈ r₂}
localized "infix ` ○ `:55 := comp_rel" in uniformity
@[simp] theorem mem_comp_rel {r₁ r₂ : set (α×α)}
{x y : α} : (x, y) ∈ r₁ ○ r₂ ↔ ∃ z, (x, z) ∈ r₁ ∧ (z, y) ∈ r₂ := iff.rfl
@[simp] theorem swap_id_rel : prod.swap '' id_rel = @id_rel α :=
set.ext $ assume ⟨a, b⟩, by simp [image_swap_eq_preimage_swap]; exact eq_comm
theorem monotone_comp_rel [preorder β] {f g : β → set (α×α)}
(hf : monotone f) (hg : monotone g) : monotone (λx, (f x) ○ (g x)) :=
assume a b h p ⟨z, h₁, h₂⟩, ⟨z, hf h h₁, hg h h₂⟩
@[mono]
lemma comp_rel_mono {f g h k: set (α×α)} (h₁ : f ⊆ h) (h₂ : g ⊆ k) : f ○ g ⊆ h ○ k :=
λ ⟨x, y⟩ ⟨z, h, h'⟩, ⟨z, h₁ h, h₂ h'⟩
lemma prod_mk_mem_comp_rel {a b c : α} {s t : set (α×α)} (h₁ : (a, c) ∈ s) (h₂ : (c, b) ∈ t) :
(a, b) ∈ s ○ t :=
⟨c, h₁, h₂⟩
@[simp] lemma id_comp_rel {r : set (α×α)} : id_rel ○ r = r :=
set.ext $ assume ⟨a, b⟩, by simp
lemma comp_rel_assoc {r s t : set (α×α)} :
(r ○ s) ○ t = r ○ (s ○ t) :=
by ext p; cases p; simp only [mem_comp_rel]; tauto
lemma subset_comp_self {α : Type*} {s : set (α × α)} (h : id_rel ⊆ s) : s ⊆ s ○ s :=
λ ⟨x, y⟩ xy_in, ⟨x, h (by rw mem_id_rel), xy_in⟩
/-- The relation is invariant under swapping factors. -/
def symmetric_rel (V : set (α × α)) : Prop := prod.swap ⁻¹' V = V
/-- The maximal symmetric relation contained in a given relation. -/
def symmetrize_rel (V : set (α × α)) : set (α × α) := V ∩ prod.swap ⁻¹' V
lemma symmetric_symmetrize_rel (V : set (α × α)) : symmetric_rel (symmetrize_rel V) :=
by simp [symmetric_rel, symmetrize_rel, preimage_inter, inter_comm, ← preimage_comp]
lemma symmetrize_rel_subset_self (V : set (α × α)) : symmetrize_rel V ⊆ V :=
sep_subset _ _
@[mono]
lemma symmetrize_mono {V W: set (α × α)} (h : V ⊆ W) : symmetrize_rel V ⊆ symmetrize_rel W :=
inter_subset_inter h $ preimage_mono h
lemma symmetric_rel_inter {U V : set (α × α)} (hU : symmetric_rel U) (hV : symmetric_rel V) :
symmetric_rel (U ∩ V) :=
begin
unfold symmetric_rel at *,
rw [preimage_inter, hU, hV],
end
/-- This core description of a uniform space is outside of the type class hierarchy. It is useful
for constructions of uniform spaces, when the topology is derived from the uniform space. -/
structure uniform_space.core (α : Type u) :=
(uniformity : filter (α × α))
(refl : 𝓟 id_rel ≤ uniformity)
(symm : tendsto prod.swap uniformity uniformity)
(comp : uniformity.lift' (λs, s ○ s) ≤ uniformity)
/-- An alternative constructor for `uniform_space.core`. This version unfolds various
`filter`-related definitions. -/
def uniform_space.core.mk' {α : Type u} (U : filter (α × α))
(refl : ∀ (r ∈ U) x, (x, x) ∈ r)
(symm : ∀ r ∈ U, prod.swap ⁻¹' r ∈ U)
(comp : ∀ r ∈ U, ∃ t ∈ U, t ○ t ⊆ r) : uniform_space.core α :=
⟨U, λ r ru, id_rel_subset.2 (refl _ ru), symm,
begin
intros r ru,
rw [mem_lift'_sets],
exact comp _ ru,
apply monotone_comp_rel; exact monotone_id,
end⟩
/-- A uniform space generates a topological space -/
def uniform_space.core.to_topological_space {α : Type u} (u : uniform_space.core α) :
topological_space α :=
{ is_open := λs, ∀x∈s, { p : α × α | p.1 = x → p.2 ∈ s } ∈ u.uniformity,
is_open_univ := by simp; intro; exact univ_mem,
is_open_inter :=
assume s t hs ht x ⟨xs, xt⟩, by filter_upwards [hs x xs, ht x xt]; simp {contextual := tt},
is_open_sUnion :=
assume s hs x ⟨t, ts, xt⟩, by filter_upwards [hs t ts x xt] assume p ph h, ⟨t, ts, ph h⟩ }
lemma uniform_space.core_eq :
∀{u₁ u₂ : uniform_space.core α}, u₁.uniformity = u₂.uniformity → u₁ = u₂
| ⟨u₁, _, _, _⟩ ⟨u₂, _, _, _⟩ h := by { congr, exact h }
-- the topological structure is embedded in the uniform structure
-- to avoid instance diamond issues. See Note [forgetful inheritance].
/-- A uniform space is a generalization of the "uniform" topological aspects of a
metric space. It consists of a filter on `α × α` called the "uniformity", which
satisfies properties analogous to the reflexivity, symmetry, and triangle properties
of a metric.
A metric space has a natural uniformity, and a uniform space has a natural topology.
A topological group also has a natural uniformity, even when it is not metrizable. -/
class uniform_space (α : Type u) extends topological_space α, uniform_space.core α :=
(is_open_uniformity : ∀s, is_open s ↔ (∀x∈s, { p : α × α | p.1 = x → p.2 ∈ s } ∈ uniformity))
/-- Alternative constructor for `uniform_space α` when a topology is already given. -/
@[pattern] def uniform_space.mk' {α} (t : topological_space α)
(c : uniform_space.core α)
(is_open_uniformity : ∀s:set α, t.is_open s ↔
(∀x∈s, { p : α × α | p.1 = x → p.2 ∈ s } ∈ c.uniformity)) :
uniform_space α := ⟨c, is_open_uniformity⟩
/-- Construct a `uniform_space` from a `uniform_space.core`. -/
def uniform_space.of_core {α : Type u} (u : uniform_space.core α) : uniform_space α :=
{ to_core := u,
to_topological_space := u.to_topological_space,
is_open_uniformity := assume a, iff.rfl }
/-- Construct a `uniform_space` from a `u : uniform_space.core` and a `topological_space` structure
that is equal to `u.to_topological_space`. -/
def uniform_space.of_core_eq {α : Type u} (u : uniform_space.core α) (t : topological_space α)
(h : t = u.to_topological_space) : uniform_space α :=
{ to_core := u,
to_topological_space := t,
is_open_uniformity := assume a, h.symm ▸ iff.rfl }
lemma uniform_space.to_core_to_topological_space (u : uniform_space α) :
u.to_core.to_topological_space = u.to_topological_space :=
topological_space_eq $ funext $ assume s,
by rw [uniform_space.core.to_topological_space, uniform_space.is_open_uniformity]
@[ext]
lemma uniform_space_eq : ∀{u₁ u₂ : uniform_space α}, u₁.uniformity = u₂.uniformity → u₁ = u₂
| (uniform_space.mk' t₁ u₁ o₁) (uniform_space.mk' t₂ u₂ o₂) h :=
have u₁ = u₂, from uniform_space.core_eq h,
have t₁ = t₂, from topological_space_eq $ funext $ assume s, by rw [o₁, o₂]; simp [this],
by simp [*]
lemma uniform_space.of_core_eq_to_core
(u : uniform_space α) (t : topological_space α) (h : t = u.to_core.to_topological_space) :
uniform_space.of_core_eq u.to_core t h = u :=
uniform_space_eq rfl
section uniform_space
variables [uniform_space α]
/-- The uniformity is a filter on α × α (inferred from an ambient uniform space
structure on α). -/
def uniformity (α : Type u) [uniform_space α] : filter (α × α) :=
(@uniform_space.to_core α _).uniformity
localized "notation `𝓤` := uniformity" in uniformity
lemma is_open_uniformity {s : set α} :
is_open s ↔ (∀x∈s, { p : α × α | p.1 = x → p.2 ∈ s } ∈ 𝓤 α) :=
uniform_space.is_open_uniformity s
lemma refl_le_uniformity : 𝓟 id_rel ≤ 𝓤 α :=
(@uniform_space.to_core α _).refl
lemma refl_mem_uniformity {x : α} {s : set (α × α)} (h : s ∈ 𝓤 α) :
(x, x) ∈ s :=
refl_le_uniformity h rfl
lemma symm_le_uniformity : map (@prod.swap α α) (𝓤 _) ≤ (𝓤 _) :=
(@uniform_space.to_core α _).symm
lemma comp_le_uniformity : (𝓤 α).lift' (λs:set (α×α), s ○ s) ≤ 𝓤 α :=
(@uniform_space.to_core α _).comp
lemma tendsto_swap_uniformity : tendsto (@prod.swap α α) (𝓤 α) (𝓤 α) :=
symm_le_uniformity
lemma comp_mem_uniformity_sets {s : set (α × α)} (hs : s ∈ 𝓤 α) :
∃ t ∈ 𝓤 α, t ○ t ⊆ s :=
have s ∈ (𝓤 α).lift' (λt:set (α×α), t ○ t),
from comp_le_uniformity hs,
(mem_lift'_sets $ monotone_comp_rel monotone_id monotone_id).mp this
/-- Relation `λ f g, tendsto (λ x, (f x, g x)) l (𝓤 α)` is transitive. -/
lemma filter.tendsto.uniformity_trans {l : filter β} {f₁ f₂ f₃ : β → α}
(h₁₂ : tendsto (λ x, (f₁ x, f₂ x)) l (𝓤 α)) (h₂₃ : tendsto (λ x, (f₂ x, f₃ x)) l (𝓤 α)) :
tendsto (λ x, (f₁ x, f₃ x)) l (𝓤 α) :=
begin
refine le_trans (le_lift' $ λ s hs, mem_map.2 _) comp_le_uniformity,
filter_upwards [h₁₂ hs, h₂₃ hs],
exact λ x hx₁₂ hx₂₃, ⟨_, hx₁₂, hx₂₃⟩
end
/-- Relation `λ f g, tendsto (λ x, (f x, g x)) l (𝓤 α)` is symmetric -/
lemma filter.tendsto.uniformity_symm {l : filter β} {f : β → α × α}
(h : tendsto f l (𝓤 α)) :
tendsto (λ x, ((f x).2, (f x).1)) l (𝓤 α) :=
tendsto_swap_uniformity.comp h
/-- Relation `λ f g, tendsto (λ x, (f x, g x)) l (𝓤 α)` is reflexive. -/
lemma tendsto_diag_uniformity (f : β → α) (l : filter β) :
tendsto (λ x, (f x, f x)) l (𝓤 α) :=
assume s hs, mem_map.2 $ univ_mem' $ λ x, refl_mem_uniformity hs
lemma tendsto_const_uniformity {a : α} {f : filter β} : tendsto (λ _, (a, a)) f (𝓤 α) :=
tendsto_diag_uniformity (λ _, a) f
lemma symm_of_uniformity {s : set (α × α)} (hs : s ∈ 𝓤 α) :
∃ t ∈ 𝓤 α, (∀a b, (a, b) ∈ t → (b, a) ∈ t) ∧ t ⊆ s :=
have preimage prod.swap s ∈ 𝓤 α, from symm_le_uniformity hs,
⟨s ∩ preimage prod.swap s, inter_mem hs this, λ a b ⟨h₁, h₂⟩, ⟨h₂, h₁⟩, inter_subset_left _ _⟩
lemma comp_symm_of_uniformity {s : set (α × α)} (hs : s ∈ 𝓤 α) :
∃ t ∈ 𝓤 α, (∀{a b}, (a, b) ∈ t → (b, a) ∈ t) ∧ t ○ t ⊆ s :=
let ⟨t, ht₁, ht₂⟩ := comp_mem_uniformity_sets hs in
let ⟨t', ht', ht'₁, ht'₂⟩ := symm_of_uniformity ht₁ in
⟨t', ht', ht'₁, subset.trans (monotone_comp_rel monotone_id monotone_id ht'₂) ht₂⟩
lemma uniformity_le_symm : 𝓤 α ≤ (@prod.swap α α) <$> 𝓤 α :=
by rw [map_swap_eq_comap_swap];
from map_le_iff_le_comap.1 tendsto_swap_uniformity
lemma uniformity_eq_symm : 𝓤 α = (@prod.swap α α) <$> 𝓤 α :=
le_antisymm uniformity_le_symm symm_le_uniformity
lemma symmetrize_mem_uniformity {V : set (α × α)} (h : V ∈ 𝓤 α) : symmetrize_rel V ∈ 𝓤 α :=
begin
apply (𝓤 α).inter_sets h,
rw [← image_swap_eq_preimage_swap, uniformity_eq_symm],
exact image_mem_map h,
end
theorem uniformity_lift_le_swap {g : set (α×α) → filter β} {f : filter β} (hg : monotone g)
(h : (𝓤 α).lift (λs, g (preimage prod.swap s)) ≤ f) : (𝓤 α).lift g ≤ f :=
calc (𝓤 α).lift g ≤ (filter.map (@prod.swap α α) $ 𝓤 α).lift g :
lift_mono uniformity_le_symm (le_refl _)
... ≤ _ :
by rw [map_lift_eq2 hg, image_swap_eq_preimage_swap]; exact h
lemma uniformity_lift_le_comp {f : set (α×α) → filter β} (h : monotone f) :
(𝓤 α).lift (λs, f (s ○ s)) ≤ (𝓤 α).lift f :=
calc (𝓤 α).lift (λs, f (s ○ s)) =
((𝓤 α).lift' (λs:set (α×α), s ○ s)).lift f :
begin
rw [lift_lift'_assoc],
exact monotone_comp_rel monotone_id monotone_id,
exact h
end
... ≤ (𝓤 α).lift f : lift_mono comp_le_uniformity (le_refl _)
lemma comp_le_uniformity3 :
(𝓤 α).lift' (λs:set (α×α), s ○ (s ○ s)) ≤ (𝓤 α) :=
calc (𝓤 α).lift' (λd, d ○ (d ○ d)) =
(𝓤 α).lift (λs, (𝓤 α).lift' (λt:set(α×α), s ○ (t ○ t))) :
begin
rw [lift_lift'_same_eq_lift'],
exact (assume x, monotone_comp_rel monotone_const $ monotone_comp_rel monotone_id monotone_id),
exact (assume x, monotone_comp_rel monotone_id monotone_const),
end
... ≤ (𝓤 α).lift (λs, (𝓤 α).lift' (λt:set(α×α), s ○ t)) :
lift_mono' $ assume s hs, @uniformity_lift_le_comp α _ _ (𝓟 ∘ (○) s) $
monotone_principal.comp (monotone_comp_rel monotone_const monotone_id)
... = (𝓤 α).lift' (λs:set(α×α), s ○ s) :
lift_lift'_same_eq_lift'
(assume s, monotone_comp_rel monotone_const monotone_id)
(assume s, monotone_comp_rel monotone_id monotone_const)
... ≤ (𝓤 α) : comp_le_uniformity
lemma comp_symm_mem_uniformity_sets {s : set (α × α)} (hs : s ∈ 𝓤 α) :
∃ t ∈ 𝓤 α, symmetric_rel t ∧ t ○ t ⊆ s :=
begin
obtain ⟨w, w_in, w_sub⟩ : ∃ w ∈ 𝓤 α, w ○ w ⊆ s := comp_mem_uniformity_sets hs,
use [symmetrize_rel w, symmetrize_mem_uniformity w_in, symmetric_symmetrize_rel w],
have : symmetrize_rel w ⊆ w := symmetrize_rel_subset_self w,
calc symmetrize_rel w ○ symmetrize_rel w ⊆ w ○ w : by mono
... ⊆ s : w_sub,
end
lemma subset_comp_self_of_mem_uniformity {s : set (α × α)} (h : s ∈ 𝓤 α) : s ⊆ s ○ s :=
subset_comp_self (refl_le_uniformity h)
lemma comp_comp_symm_mem_uniformity_sets {s : set (α × α)} (hs : s ∈ 𝓤 α) :
∃ t ∈ 𝓤 α, symmetric_rel t ∧ t ○ t ○ t ⊆ s :=
begin
rcases comp_symm_mem_uniformity_sets hs with ⟨w, w_in, w_symm, w_sub⟩,
rcases comp_symm_mem_uniformity_sets w_in with ⟨t, t_in, t_symm, t_sub⟩,
use [t, t_in, t_symm],
have : t ⊆ t ○ t := subset_comp_self_of_mem_uniformity t_in,
calc
t ○ t ○ t ⊆ w ○ t : by mono
... ⊆ w ○ (t ○ t) : by mono
... ⊆ w ○ w : by mono
... ⊆ s : w_sub,
end
/-!
### Balls in uniform spaces
-/
/-- The ball around `(x : β)` with respect to `(V : set (β × β))`. Intended to be
used for `V ∈ 𝓤 β`, but this is not needed for the definition. Recovers the
notions of metric space ball when `V = {p | dist p.1 p.2 < r }`. -/
def uniform_space.ball (x : β) (V : set (β × β)) : set β := (prod.mk x) ⁻¹' V
open uniform_space (ball)
lemma uniform_space.mem_ball_self (x : α) {V : set (α × α)} (hV : V ∈ 𝓤 α) :
x ∈ ball x V :=
refl_mem_uniformity hV
/-- The triangle inequality for `uniform_space.ball` -/
lemma mem_ball_comp {V W : set (β × β)} {x y z} (h : y ∈ ball x V) (h' : z ∈ ball y W) :
z ∈ ball x (V ○ W) :=
prod_mk_mem_comp_rel h h'
lemma ball_subset_of_comp_subset {V W : set (β × β)} {x y} (h : x ∈ ball y W) (h' : W ○ W ⊆ V) :
ball x W ⊆ ball y V :=
λ z z_in, h' (mem_ball_comp h z_in)
lemma ball_mono {V W : set (β × β)} (h : V ⊆ W) (x : β) : ball x V ⊆ ball x W :=
by tauto
lemma ball_inter_left (x : β) (V W : set (β × β)) : ball x (V ∩ W) ⊆ ball x V :=
ball_mono (inter_subset_left V W) x
lemma ball_inter_right (x : β) (V W : set (β × β)) : ball x (V ∩ W) ⊆ ball x W :=
ball_mono (inter_subset_right V W) x
lemma mem_ball_symmetry {V : set (β × β)} (hV : symmetric_rel V) {x y} :
x ∈ ball y V ↔ y ∈ ball x V :=
show (x, y) ∈ prod.swap ⁻¹' V ↔ (x, y) ∈ V, by { unfold symmetric_rel at hV, rw hV }
lemma ball_eq_of_symmetry {V : set (β × β)} (hV : symmetric_rel V) {x} :
ball x V = {y | (y, x) ∈ V} :=
by { ext y, rw mem_ball_symmetry hV, exact iff.rfl }
lemma mem_comp_of_mem_ball {V W : set (β × β)} {x y z : β} (hV : symmetric_rel V)
(hx : x ∈ ball z V) (hy : y ∈ ball z W) : (x, y) ∈ V ○ W :=
begin
rw mem_ball_symmetry hV at hx,
exact ⟨z, hx, hy⟩
end
lemma uniform_space.is_open_ball (x : α) {V : set (α × α)} (hV : is_open V) :
is_open (ball x V) :=
hV.preimage $ continuous_const.prod_mk continuous_id
lemma mem_comp_comp {V W M : set (β × β)} (hW' : symmetric_rel W) {p : β × β} :
p ∈ V ○ M ○ W ↔ ((ball p.1 V).prod (ball p.2 W) ∩ M).nonempty :=
begin
cases p with x y,
split,
{ rintros ⟨z, ⟨w, hpw, hwz⟩, hzy⟩,
exact ⟨(w, z), ⟨hpw, by rwa mem_ball_symmetry hW'⟩, hwz⟩, },
{ rintro ⟨⟨w, z⟩, ⟨w_in, z_in⟩, hwz⟩,
rwa mem_ball_symmetry hW' at z_in,
use [z, w] ; tauto },
end
/-!
### Neighborhoods in uniform spaces
-/
lemma mem_nhds_uniformity_iff_right {x : α} {s : set α} :
s ∈ 𝓝 x ↔ {p : α × α | p.1 = x → p.2 ∈ s} ∈ 𝓤 α :=
⟨ begin
simp only [mem_nhds_iff, is_open_uniformity, and_imp, exists_imp_distrib],
exact assume t ts ht xt, by filter_upwards [ht x xt] assume ⟨x', y⟩ h eq, ts $ h eq
end,
assume hs,
mem_nhds_iff.mpr ⟨{x | {p : α × α | p.1 = x → p.2 ∈ s} ∈ 𝓤 α},
assume x' hx', refl_mem_uniformity hx' rfl,
is_open_uniformity.mpr $ assume x' hx',
let ⟨t, ht, tr⟩ := comp_mem_uniformity_sets hx' in
by filter_upwards [ht] assume ⟨a, b⟩ hp' (hax' : a = x'),
by filter_upwards [ht] assume ⟨a, b'⟩ hp'' (hab : a = b),
have hp : (x', b) ∈ t, from hax' ▸ hp',
have (b, b') ∈ t, from hab ▸ hp'',
have (x', b') ∈ t ○ t, from ⟨b, hp, this⟩,
show b' ∈ s,
from tr this rfl,
hs⟩⟩
lemma mem_nhds_uniformity_iff_left {x : α} {s : set α} :
s ∈ 𝓝 x ↔ {p : α × α | p.2 = x → p.1 ∈ s} ∈ 𝓤 α :=
by { rw [uniformity_eq_symm, mem_nhds_uniformity_iff_right], refl }
lemma nhds_eq_comap_uniformity_aux {α : Type u} {x : α} {s : set α} {F : filter (α × α)} :
{p : α × α | p.fst = x → p.snd ∈ s} ∈ F ↔ s ∈ comap (prod.mk x) F :=
by rw mem_comap ; from iff.intro
(assume hs, ⟨_, hs, assume x hx, hx rfl⟩)
(assume ⟨t, h, ht⟩, F.sets_of_superset h $
assume ⟨p₁, p₂⟩ hp (h : p₁ = x), ht $ by simp [h.symm, hp])
lemma nhds_eq_comap_uniformity {x : α} : 𝓝 x = (𝓤 α).comap (prod.mk x) :=
by { ext s, rw [mem_nhds_uniformity_iff_right], exact nhds_eq_comap_uniformity_aux }
lemma is_open_iff_ball_subset {s : set α} : is_open s ↔ ∀ x ∈ s, ∃ V ∈ 𝓤 α, ball x V ⊆ s :=
begin
simp_rw [is_open_iff_mem_nhds, nhds_eq_comap_uniformity],
exact iff.rfl,
end
lemma nhds_basis_uniformity' {p : β → Prop} {s : β → set (α × α)} (h : (𝓤 α).has_basis p s)
{x : α} :
(𝓝 x).has_basis p (λ i, ball x (s i)) :=
by { rw [nhds_eq_comap_uniformity], exact h.comap (prod.mk x) }
lemma nhds_basis_uniformity {p : β → Prop} {s : β → set (α × α)} (h : (𝓤 α).has_basis p s) {x : α} :
(𝓝 x).has_basis p (λ i, {y | (y, x) ∈ s i}) :=
begin
replace h := h.comap prod.swap,
rw [← map_swap_eq_comap_swap, ← uniformity_eq_symm] at h,
exact nhds_basis_uniformity' h
end
lemma uniform_space.mem_nhds_iff {x : α} {s : set α} : s ∈ 𝓝 x ↔ ∃ V ∈ 𝓤 α, ball x V ⊆ s :=
begin
rw [nhds_eq_comap_uniformity, mem_comap],
exact iff.rfl,
end
lemma uniform_space.ball_mem_nhds (x : α) ⦃V : set (α × α)⦄ (V_in : V ∈ 𝓤 α) : ball x V ∈ 𝓝 x :=
begin
rw uniform_space.mem_nhds_iff,
exact ⟨V, V_in, subset.refl _⟩
end
lemma uniform_space.mem_nhds_iff_symm {x : α} {s : set α} :
s ∈ 𝓝 x ↔ ∃ V ∈ 𝓤 α, symmetric_rel V ∧ ball x V ⊆ s :=
begin
rw uniform_space.mem_nhds_iff,
split,
{ rintros ⟨V, V_in, V_sub⟩,
use [symmetrize_rel V, symmetrize_mem_uniformity V_in, symmetric_symmetrize_rel V],
exact subset.trans (ball_mono (symmetrize_rel_subset_self V) x) V_sub },
{ rintros ⟨V, V_in, V_symm, V_sub⟩,
exact ⟨V, V_in, V_sub⟩ }
end
lemma uniform_space.has_basis_nhds (x : α) :
has_basis (𝓝 x) (λ s : set (α × α), s ∈ 𝓤 α ∧ symmetric_rel s) (λ s, ball x s) :=
⟨λ t, by simp [uniform_space.mem_nhds_iff_symm, and_assoc]⟩
open uniform_space
lemma uniform_space.mem_closure_iff_symm_ball {s : set α} {x} :
x ∈ closure s ↔ ∀ {V}, V ∈ 𝓤 α → symmetric_rel V → (s ∩ ball x V).nonempty :=
begin
simp [mem_closure_iff_nhds_basis (has_basis_nhds x)],
tauto,
end
lemma uniform_space.mem_closure_iff_ball {s : set α} {x} :
x ∈ closure s ↔ ∀ {V}, V ∈ 𝓤 α → (ball x V ∩ s).nonempty :=
begin
simp_rw [mem_closure_iff_nhds, uniform_space.mem_nhds_iff],
split,
{ intros h V V_in,
exact h (ball x V) ⟨V, V_in, subset.refl _⟩ },
{ rintros h t ⟨V, V_in, Vt⟩,
exact nonempty.mono (inter_subset_inter_left s Vt) (h V_in) },
end
lemma uniform_space.has_basis_nhds_prod (x y : α) :
has_basis (𝓝 (x, y)) (λ s, s ∈ 𝓤 α ∧ symmetric_rel s) $ λ s, (ball x s).prod (ball y s) :=
begin
rw nhds_prod_eq,
apply (has_basis_nhds x).prod' (has_basis_nhds y),
rintro U V ⟨U_in, U_symm⟩ ⟨V_in, V_symm⟩,
exact ⟨U ∩ V, ⟨(𝓤 α).inter_sets U_in V_in, symmetric_rel_inter U_symm V_symm⟩,
ball_inter_left x U V, ball_inter_right y U V⟩,
end
lemma nhds_eq_uniformity {x : α} : 𝓝 x = (𝓤 α).lift' (ball x) :=
(nhds_basis_uniformity' (𝓤 α).basis_sets).eq_binfi
lemma mem_nhds_left (x : α) {s : set (α×α)} (h : s ∈ 𝓤 α) :
{y : α | (x, y) ∈ s} ∈ 𝓝 x :=
ball_mem_nhds x h
lemma mem_nhds_right (y : α) {s : set (α×α)} (h : s ∈ 𝓤 α) :
{x : α | (x, y) ∈ s} ∈ 𝓝 y :=
mem_nhds_left _ (symm_le_uniformity h)
lemma tendsto_right_nhds_uniformity {a : α} : tendsto (λa', (a', a)) (𝓝 a) (𝓤 α) :=
assume s, mem_nhds_right a
lemma tendsto_left_nhds_uniformity {a : α} : tendsto (λa', (a, a')) (𝓝 a) (𝓤 α) :=
assume s, mem_nhds_left a
lemma lift_nhds_left {x : α} {g : set α → filter β} (hg : monotone g) :
(𝓝 x).lift g = (𝓤 α).lift (λs:set (α×α), g {y | (x, y) ∈ s}) :=
eq.trans
begin
rw [nhds_eq_uniformity],
exact (filter.lift_assoc $ monotone_principal.comp $ monotone_preimage.comp monotone_preimage )
end
(congr_arg _ $ funext $ assume s, filter.lift_principal hg)
lemma lift_nhds_right {x : α} {g : set α → filter β} (hg : monotone g) :
(𝓝 x).lift g = (𝓤 α).lift (λs:set (α×α), g {y | (y, x) ∈ s}) :=
calc (𝓝 x).lift g = (𝓤 α).lift (λs:set (α×α), g {y | (x, y) ∈ s}) : lift_nhds_left hg
... = ((@prod.swap α α) <$> (𝓤 α)).lift (λs:set (α×α), g {y | (x, y) ∈ s}) :
by rw [←uniformity_eq_symm]
... = (𝓤 α).lift (λs:set (α×α), g {y | (x, y) ∈ image prod.swap s}) :
map_lift_eq2 $ hg.comp monotone_preimage
... = _ : by simp [image_swap_eq_preimage_swap]
lemma nhds_nhds_eq_uniformity_uniformity_prod {a b : α} :
𝓝 a ×ᶠ 𝓝 b =
(𝓤 α).lift (λs:set (α×α), (𝓤 α).lift' (λt:set (α×α),
set.prod {y : α | (y, a) ∈ s} {y : α | (b, y) ∈ t})) :=
begin
rw [prod_def],
show (𝓝 a).lift (λs:set α, (𝓝 b).lift (λt:set α, 𝓟 (set.prod s t))) = _,
rw [lift_nhds_right],
apply congr_arg, funext s,
rw [lift_nhds_left],
refl,
exact monotone_principal.comp (monotone_prod monotone_const monotone_id),
exact (monotone_lift' monotone_const $ monotone_lam $
assume x, monotone_prod monotone_id monotone_const)
end
lemma nhds_eq_uniformity_prod {a b : α} :
𝓝 (a, b) =
(𝓤 α).lift' (λs:set (α×α), set.prod {y : α | (y, a) ∈ s} {y : α | (b, y) ∈ s}) :=
begin
rw [nhds_prod_eq, nhds_nhds_eq_uniformity_uniformity_prod, lift_lift'_same_eq_lift'],
{ intro s, exact monotone_prod monotone_const monotone_preimage },
{ intro t, exact monotone_prod monotone_preimage monotone_const }
end
lemma nhdset_of_mem_uniformity {d : set (α×α)} (s : set (α×α)) (hd : d ∈ 𝓤 α) :
∃(t : set (α×α)), is_open t ∧ s ⊆ t ∧ t ⊆ {p | ∃x y, (p.1, x) ∈ d ∧ (x, y) ∈ s ∧ (y, p.2) ∈ d} :=
let cl_d := {p:α×α | ∃x y, (p.1, x) ∈ d ∧ (x, y) ∈ s ∧ (y, p.2) ∈ d} in
have ∀p ∈ s, ∃t ⊆ cl_d, is_open t ∧ p ∈ t, from
assume ⟨x, y⟩ hp, _root_.mem_nhds_iff.mp $
show cl_d ∈ 𝓝 (x, y),
begin
rw [nhds_eq_uniformity_prod, mem_lift'_sets],
exact ⟨d, hd, assume ⟨a, b⟩ ⟨ha, hb⟩, ⟨x, y, ha, hp, hb⟩⟩,
exact monotone_prod monotone_preimage monotone_preimage
end,
have ∃t:(Π(p:α×α) (h:p ∈ s), set (α×α)),
∀p, ∀h:p ∈ s, t p h ⊆ cl_d ∧ is_open (t p h) ∧ p ∈ t p h,
by simp [classical.skolem] at this; simp; assumption,
match this with
| ⟨t, ht⟩ :=
⟨(⋃ p:α×α, ⋃ h : p ∈ s, t p h : set (α×α)),
is_open_Union $ assume (p:α×α), is_open_Union $ assume hp, (ht p hp).right.left,
assume ⟨a, b⟩ hp, begin simp; exact ⟨a, b, hp, (ht (a,b) hp).right.right⟩ end,
Union_subset $ assume p, Union_subset $ assume hp, (ht p hp).left⟩
end
/-- Entourages are neighborhoods of the diagonal. -/
lemma nhds_le_uniformity (x : α) : 𝓝 (x, x) ≤ 𝓤 α :=
begin
intros V V_in,
rcases comp_symm_mem_uniformity_sets V_in with ⟨w, w_in, w_symm, w_sub⟩,
have : (ball x w).prod (ball x w) ∈ 𝓝 (x, x),
{ rw nhds_prod_eq,
exact prod_mem_prod (ball_mem_nhds x w_in) (ball_mem_nhds x w_in) },
apply mem_of_superset this,
rintros ⟨u, v⟩ ⟨u_in, v_in⟩,
exact w_sub (mem_comp_of_mem_ball w_symm u_in v_in)
end
/-- Entourages are neighborhoods of the diagonal. -/
lemma supr_nhds_le_uniformity : (⨆ x : α, 𝓝 (x, x)) ≤ 𝓤 α :=
supr_le nhds_le_uniformity
/-!
### Closure and interior in uniform spaces
-/
lemma closure_eq_uniformity (s : set $ α × α) :
closure s = ⋂ V ∈ {V | V ∈ 𝓤 α ∧ symmetric_rel V}, V ○ s ○ V :=
begin
ext ⟨x, y⟩,
simp_rw [mem_closure_iff_nhds_basis (uniform_space.has_basis_nhds_prod x y),
mem_Inter, mem_set_of_eq],
apply forall_congr,
intro V,
apply forall_congr,
rintros ⟨V_in, V_symm⟩,
simp_rw [mem_comp_comp V_symm, inter_comm, exists_prop],
exact iff.rfl,
end
lemma uniformity_has_basis_closed : has_basis (𝓤 α) (λ V : set (α × α), V ∈ 𝓤 α ∧ is_closed V) id :=
begin
refine filter.has_basis_self.2 (λ t h, _),
rcases comp_comp_symm_mem_uniformity_sets h with ⟨w, w_in, w_symm, r⟩,
refine ⟨closure w, mem_of_superset w_in subset_closure, is_closed_closure, _⟩,
refine subset.trans _ r,
rw closure_eq_uniformity,
apply Inter_subset_of_subset,
apply Inter_subset,
exact ⟨w_in, w_symm⟩
end
/-- Closed entourages form a basis of the uniformity filter. -/
lemma uniformity_has_basis_closure : has_basis (𝓤 α) (λ V : set (α × α), V ∈ 𝓤 α) closure :=
⟨begin
intro t,
rw uniformity_has_basis_closed.mem_iff,
split,
{ rintros ⟨r, ⟨r_in, r_closed⟩, r_sub⟩,
use [r, r_in],
convert r_sub,
rw r_closed.closure_eq,
refl },
{ rintros ⟨r, r_in, r_sub⟩,
exact ⟨closure r, ⟨mem_of_superset r_in subset_closure, is_closed_closure⟩, r_sub⟩ }
end⟩
lemma closure_eq_inter_uniformity {t : set (α×α)} :
closure t = (⋂ d ∈ 𝓤 α, d ○ (t ○ d)) :=
set.ext $ assume ⟨a, b⟩,
calc (a, b) ∈ closure t ↔ (𝓝 (a, b) ⊓ 𝓟 t ≠ ⊥) : mem_closure_iff_nhds_ne_bot
... ↔ (((@prod.swap α α) <$> 𝓤 α).lift'
(λ (s : set (α × α)), set.prod {x : α | (x, a) ∈ s} {y : α | (b, y) ∈ s}) ⊓ 𝓟 t ≠ ⊥) :
by rw [←uniformity_eq_symm, nhds_eq_uniformity_prod]
... ↔ ((map (@prod.swap α α) (𝓤 α)).lift'
(λ (s : set (α × α)), set.prod {x : α | (x, a) ∈ s} {y : α | (b, y) ∈ s}) ⊓ 𝓟 t ≠ ⊥) :
by refl
... ↔ ((𝓤 α).lift'
(λ (s : set (α × α)), set.prod {y : α | (a, y) ∈ s} {x : α | (x, b) ∈ s}) ⊓ 𝓟 t ≠ ⊥) :
begin
rw [map_lift'_eq2],
simp [image_swap_eq_preimage_swap, function.comp],
exact monotone_prod monotone_preimage monotone_preimage
end
... ↔ (∀s ∈ 𝓤 α, (set.prod {y : α | (a, y) ∈ s} {x : α | (x, b) ∈ s} ∩ t).nonempty) :
begin
rw [lift'_inf_principal_eq, ← ne_bot_iff, lift'_ne_bot_iff],
exact monotone_inter (monotone_prod monotone_preimage monotone_preimage) monotone_const
end
... ↔ (∀ s ∈ 𝓤 α, (a, b) ∈ s ○ (t ○ s)) :
forall_congr $ assume s, forall_congr $ assume hs,
⟨assume ⟨⟨x, y⟩, ⟨⟨hx, hy⟩, hxyt⟩⟩, ⟨x, hx, y, hxyt, hy⟩,
assume ⟨x, hx, y, hxyt, hy⟩, ⟨⟨x, y⟩, ⟨⟨hx, hy⟩, hxyt⟩⟩⟩
... ↔ _ : by simp
lemma uniformity_eq_uniformity_closure : 𝓤 α = (𝓤 α).lift' closure :=
le_antisymm
(le_infi $ assume s, le_infi $ assume hs, by simp; filter_upwards [hs] subset_closure)
(calc (𝓤 α).lift' closure ≤ (𝓤 α).lift' (λd, d ○ (d ○ d)) :
lift'_mono' (by intros s hs; rw [closure_eq_inter_uniformity]; exact bInter_subset_of_mem hs)
... ≤ (𝓤 α) : comp_le_uniformity3)
lemma uniformity_eq_uniformity_interior : 𝓤 α = (𝓤 α).lift' interior :=
le_antisymm
(le_infi $ assume d, le_infi $ assume hd,
let ⟨s, hs, hs_comp⟩ := (mem_lift'_sets $
monotone_comp_rel monotone_id $ monotone_comp_rel monotone_id monotone_id).mp
(comp_le_uniformity3 hd) in
let ⟨t, ht, hst, ht_comp⟩ := nhdset_of_mem_uniformity s hs in
have s ⊆ interior d, from
calc s ⊆ t : hst
... ⊆ interior d : (subset_interior_iff_subset_of_open ht).mpr $
λ x (hx : x ∈ t), let ⟨x, y, h₁, h₂, h₃⟩ := ht_comp hx in hs_comp ⟨x, h₁, y, h₂, h₃⟩,
have interior d ∈ 𝓤 α, by filter_upwards [hs] this,
by simp [this])
(assume s hs, ((𝓤 α).lift' interior).sets_of_superset (mem_lift' hs) interior_subset)
lemma interior_mem_uniformity {s : set (α × α)} (hs : s ∈ 𝓤 α) :
interior s ∈ 𝓤 α :=
by rw [uniformity_eq_uniformity_interior]; exact mem_lift' hs
lemma mem_uniformity_is_closed {s : set (α×α)} (h : s ∈ 𝓤 α) :
∃t ∈ 𝓤 α, is_closed t ∧ t ⊆ s :=
let ⟨t, ⟨ht_mem, htc⟩, hts⟩ := uniformity_has_basis_closed.mem_iff.1 h in
⟨t, ht_mem, htc, hts⟩
/-- The uniform neighborhoods of all points of a dense set cover the whole space. -/
lemma dense.bUnion_uniformity_ball {s : set α} {U : set (α × α)} (hs : dense s) (hU : U ∈ 𝓤 α) :
(⋃ x ∈ s, ball x U) = univ :=
begin
refine bUnion_eq_univ_iff.2 (λ y, _),
rcases hs.inter_nhds_nonempty (mem_nhds_right y hU) with ⟨x, hxs, hxy : (x, y) ∈ U⟩,
exact ⟨x, hxs, hxy⟩
end
/-!
### Uniformity bases
-/
/-- Open elements of `𝓤 α` form a basis of `𝓤 α`. -/
lemma uniformity_has_basis_open : has_basis (𝓤 α) (λ V : set (α × α), V ∈ 𝓤 α ∧ is_open V) id :=
has_basis_self.2 $ λ s hs,
⟨interior s, interior_mem_uniformity hs, is_open_interior, interior_subset⟩
lemma filter.has_basis.mem_uniformity_iff {p : β → Prop} {s : β → set (α×α)}
(h : (𝓤 α).has_basis p s) {t : set (α × α)} :
t ∈ 𝓤 α ↔ ∃ i (hi : p i), ∀ a b, (a, b) ∈ s i → (a, b) ∈ t :=
h.mem_iff.trans $ by simp only [prod.forall, subset_def]
/-- Symmetric entourages form a basis of `𝓤 α` -/
lemma uniform_space.has_basis_symmetric :
(𝓤 α).has_basis (λ s : set (α × α), s ∈ 𝓤 α ∧ symmetric_rel s) id :=
has_basis_self.2 $ λ t t_in, ⟨symmetrize_rel t, symmetrize_mem_uniformity t_in,
symmetric_symmetrize_rel t, symmetrize_rel_subset_self t⟩
/-- Open elements `s : set (α × α)` of `𝓤 α` such that `(x, y) ∈ s ↔ (y, x) ∈ s` form a basis
of `𝓤 α`. -/
lemma uniformity_has_basis_open_symmetric :
has_basis (𝓤 α) (λ V : set (α × α), V ∈ 𝓤 α ∧ is_open V ∧ symmetric_rel V) id :=
begin
simp only [← and_assoc],
refine uniformity_has_basis_open.restrict (λ s hs, ⟨symmetrize_rel s, _⟩),
exact ⟨⟨symmetrize_mem_uniformity hs.1, is_open.inter hs.2 (hs.2.preimage continuous_swap)⟩,
symmetric_symmetrize_rel s, symmetrize_rel_subset_self s⟩
end
lemma uniform_space.has_seq_basis (h : is_countably_generated $ 𝓤 α) :
∃ V : ℕ → set (α × α), has_antimono_basis (𝓤 α) (λ _, true) V ∧ ∀ n, symmetric_rel (V n) :=
let ⟨U, hsym, hbasis⟩ := h.exists_antimono_subbasis uniform_space.has_basis_symmetric
in ⟨U, hbasis, λ n, (hsym n).2⟩
/-! ### Uniform continuity -/
/-- A function `f : α → β` is *uniformly continuous* if `(f x, f y)` tends to the diagonal
as `(x, y)` tends to the diagonal. In other words, if `x` is sufficiently close to `y`, then
`f x` is close to `f y` no matter where `x` and `y` are located in `α`. -/
def uniform_continuous [uniform_space β] (f : α → β) :=
tendsto (λx:α×α, (f x.1, f x.2)) (𝓤 α) (𝓤 β)
/-- A function `f : α → β` is *uniformly continuous* on `s : set α` if `(f x, f y)` tends to
the diagonal as `(x, y)` tends to the diagonal while remaining in `s.prod s`.
In other words, if `x` is sufficiently close to `y`, then `f x` is close to
`f y` no matter where `x` and `y` are located in `s`.-/
def uniform_continuous_on [uniform_space β] (f : α → β) (s : set α) : Prop :=
tendsto (λ x : α × α, (f x.1, f x.2)) (𝓤 α ⊓ principal (s.prod s)) (𝓤 β)
theorem uniform_continuous_def [uniform_space β] {f : α → β} :
uniform_continuous f ↔ ∀ r ∈ 𝓤 β, { x : α × α | (f x.1, f x.2) ∈ r} ∈ 𝓤 α :=
iff.rfl
theorem uniform_continuous_iff_eventually [uniform_space β] {f : α → β} :
uniform_continuous f ↔ ∀ r ∈ 𝓤 β, ∀ᶠ (x : α × α) in 𝓤 α, (f x.1, f x.2) ∈ r :=
iff.rfl
theorem uniform_continuous_on_univ [uniform_space β] {f : α → β} :
uniform_continuous_on f univ ↔ uniform_continuous f :=
by rw [uniform_continuous_on, uniform_continuous, univ_prod_univ, principal_univ, inf_top_eq]
lemma uniform_continuous_of_const [uniform_space β] {c : α → β} (h : ∀a b, c a = c b) :
uniform_continuous c :=
have (λ (x : α × α), (c (x.fst), c (x.snd))) ⁻¹' id_rel = univ, from
eq_univ_iff_forall.2 $ assume ⟨a, b⟩, h a b,
le_trans (map_le_iff_le_comap.2 $ by simp [comap_principal, this, univ_mem]) refl_le_uniformity
lemma uniform_continuous_id : uniform_continuous (@id α) :=
by simp [uniform_continuous]; exact tendsto_id
lemma uniform_continuous_const [uniform_space β] {b : β} : uniform_continuous (λa:α, b) :=
uniform_continuous_of_const $ λ _ _, rfl
lemma uniform_continuous.comp [uniform_space β] [uniform_space γ] {g : β → γ} {f : α → β}
(hg : uniform_continuous g) (hf : uniform_continuous f) : uniform_continuous (g ∘ f) :=
hg.comp hf
lemma filter.has_basis.uniform_continuous_iff [uniform_space β] {p : γ → Prop} {s : γ → set (α×α)}
(ha : (𝓤 α).has_basis p s) {q : δ → Prop} {t : δ → set (β×β)} (hb : (𝓤 β).has_basis q t)
{f : α → β} :
uniform_continuous f ↔ ∀ i (hi : q i), ∃ j (hj : p j), ∀ x y, (x, y) ∈ s j → (f x, f y) ∈ t i :=
(ha.tendsto_iff hb).trans $ by simp only [prod.forall]
lemma filter.has_basis.uniform_continuous_on_iff [uniform_space β] {p : γ → Prop}
{s : γ → set (α×α)} (ha : (𝓤 α).has_basis p s) {q : δ → Prop} {t : δ → set (β×β)}
(hb : (𝓤 β).has_basis q t) {f : α → β} {S : set α} :
uniform_continuous_on f S ↔
∀ i (hi : q i), ∃ j (hj : p j), ∀ x y ∈ S, (x, y) ∈ s j → (f x, f y) ∈ t i :=
((ha.inf_principal (S.prod S)).tendsto_iff hb).trans $ by finish [prod.forall]
end uniform_space
open_locale uniformity
section constructions
instance : partial_order (uniform_space α) :=
{ le := λt s, t.uniformity ≤ s.uniformity,
le_antisymm := assume t s h₁ h₂, uniform_space_eq $ le_antisymm h₁ h₂,
le_refl := assume t, le_refl _,
le_trans := assume a b c h₁ h₂, le_trans h₁ h₂ }
instance : has_Inf (uniform_space α) :=
⟨assume s, uniform_space.of_core {
uniformity := (⨅u∈s, @uniformity α u),
refl := le_infi $ assume u, le_infi $ assume hu, u.refl,
symm := le_infi $ assume u, le_infi $ assume hu,
le_trans (map_mono $ infi_le_of_le _ $ infi_le _ hu) u.symm,
comp := le_infi $ assume u, le_infi $ assume hu,
le_trans (lift'_mono (infi_le_of_le _ $ infi_le _ hu) $ le_refl _) u.comp }⟩
private lemma Inf_le {tt : set (uniform_space α)} {t : uniform_space α} (h : t ∈ tt) :
Inf tt ≤ t :=
show (⨅u∈tt, @uniformity α u) ≤ t.uniformity,
from infi_le_of_le t $ infi_le _ h
private lemma le_Inf {tt : set (uniform_space α)} {t : uniform_space α} (h : ∀t'∈tt, t ≤ t') :
t ≤ Inf tt :=
show t.uniformity ≤ (⨅u∈tt, @uniformity α u),
from le_infi $ assume t', le_infi $ assume ht', h t' ht'
instance : has_top (uniform_space α) :=
⟨uniform_space.of_core { uniformity := ⊤, refl := le_top, symm := le_top, comp := le_top }⟩
instance : has_bot (uniform_space α) :=
⟨{ to_topological_space := ⊥,
uniformity := 𝓟 id_rel,
refl := le_refl _,
symm := by simp [tendsto]; apply subset.refl,
comp :=
begin
rw [lift'_principal], {simp},
exact monotone_comp_rel monotone_id monotone_id
end,
is_open_uniformity :=
assume s, by simp [is_open_fold, subset_def, id_rel] {contextual := tt } } ⟩
instance : complete_lattice (uniform_space α) :=
{ sup := λa b, Inf {x | a ≤ x ∧ b ≤ x},
le_sup_left := λ a b, le_Inf (λ _ ⟨h, _⟩, h),
le_sup_right := λ a b, le_Inf (λ _ ⟨_, h⟩, h),
sup_le := λ a b c h₁ h₂, Inf_le ⟨h₁, h₂⟩,
inf := λ a b, Inf {a, b},
le_inf := λ a b c h₁ h₂, le_Inf (λ u h,
by { cases h, exact h.symm ▸ h₁, exact (mem_singleton_iff.1 h).symm ▸ h₂ }),
inf_le_left := λ a b, Inf_le (by simp),
inf_le_right := λ a b, Inf_le (by simp),
top := ⊤,
le_top := λ a, show a.uniformity ≤ ⊤, from le_top,
bot := ⊥,
bot_le := λ u, u.refl,
Sup := λ tt, Inf {t | ∀ t' ∈ tt, t' ≤ t},
le_Sup := λ s u h, le_Inf (λ u' h', h' u h),
Sup_le := λ s u h, Inf_le h,
Inf := Inf,
le_Inf := λ s a hs, le_Inf hs,
Inf_le := λ s a ha, Inf_le ha,
..uniform_space.partial_order }
lemma infi_uniformity {ι : Sort*} {u : ι → uniform_space α} :
(infi u).uniformity = (⨅i, (u i).uniformity) :=
show (⨅a (h : ∃i:ι, u i = a), a.uniformity) = _, from
le_antisymm
(le_infi $ assume i, infi_le_of_le (u i) $ infi_le _ ⟨i, rfl⟩)
(le_infi $ assume a, le_infi $ assume ⟨i, (ha : u i = a)⟩, ha ▸ infi_le _ _)
lemma inf_uniformity {u v : uniform_space α} :
(u ⊓ v).uniformity = u.uniformity ⊓ v.uniformity :=
have (u ⊓ v) = (⨅i (h : i = u ∨ i = v), i), by simp [infi_or, infi_inf_eq],
calc (u ⊓ v).uniformity = ((⨅i (h : i = u ∨ i = v), i) : uniform_space α).uniformity : by rw [this]
... = _ : by simp [infi_uniformity, infi_or, infi_inf_eq]
instance inhabited_uniform_space : inhabited (uniform_space α) := ⟨⊥⟩
instance inhabited_uniform_space_core : inhabited (uniform_space.core α) :=
⟨@uniform_space.to_core _ (default _)⟩
/-- Given `f : α → β` and a uniformity `u` on `β`, the inverse image of `u` under `f`
is the inverse image in the filter sense of the induced function `α × α → β × β`. -/
def uniform_space.comap (f : α → β) (u : uniform_space β) : uniform_space α :=
{ uniformity := u.uniformity.comap (λp:α×α, (f p.1, f p.2)),
to_topological_space := u.to_topological_space.induced f,
refl := le_trans (by simp; exact assume ⟨a, b⟩ (h : a = b), h ▸ rfl) (comap_mono u.refl),
symm := by simp [tendsto_comap_iff, prod.swap, (∘)];
exact tendsto_swap_uniformity.comp tendsto_comap,
comp := le_trans
begin
rw [comap_lift'_eq, comap_lift'_eq2],
exact (lift'_mono' $ assume s hs ⟨a₁, a₂⟩ ⟨x, h₁, h₂⟩, ⟨f x, h₁, h₂⟩),
repeat { exact monotone_comp_rel monotone_id monotone_id }
end
(comap_mono u.comp),
is_open_uniformity := λ s, begin
change (@is_open α (u.to_topological_space.induced f) s ↔ _),
simp [is_open_iff_nhds, nhds_induced, mem_nhds_uniformity_iff_right, filter.comap, and_comm],
refine ball_congr (λ x hx, ⟨_, _⟩),
{ rintro ⟨t, hts, ht⟩, refine ⟨_, ht, _⟩,
rintro ⟨x₁, x₂⟩ h rfl, exact hts (h rfl) },
{ rintro ⟨t, ht, hts⟩,
exact ⟨{y | (f x, y) ∈ t}, λ y hy, @hts (x, y) hy rfl,
mem_nhds_uniformity_iff_right.1 $ mem_nhds_left _ ht⟩ }
end }
lemma uniformity_comap [uniform_space α] [uniform_space β] {f : α → β}
(h : ‹uniform_space α› = uniform_space.comap f ‹uniform_space β›) :
𝓤 α = comap (prod.map f f) (𝓤 β) :=
by { rw h, refl }
lemma uniform_space_comap_id {α : Type*} : uniform_space.comap (id : α → α) = id :=
by ext u ; dsimp [uniform_space.comap] ; rw [prod.id_prod, filter.comap_id]
lemma uniform_space.comap_comap {α β γ} [uγ : uniform_space γ] {f : α → β} {g : β → γ} :
uniform_space.comap (g ∘ f) uγ = uniform_space.comap f (uniform_space.comap g uγ) :=
by ext ; dsimp [uniform_space.comap] ; rw filter.comap_comap
lemma uniform_continuous_iff {α β} [uα : uniform_space α] [uβ : uniform_space β] {f : α → β} :
uniform_continuous f ↔ uα ≤ uβ.comap f :=
filter.map_le_iff_le_comap
lemma uniform_continuous_comap {f : α → β} [u : uniform_space β] :
@uniform_continuous α β (uniform_space.comap f u) u f :=
tendsto_comap
theorem to_topological_space_comap {f : α → β} {u : uniform_space β} :
@uniform_space.to_topological_space _ (uniform_space.comap f u) =
topological_space.induced f (@uniform_space.to_topological_space β u) := rfl
lemma uniform_continuous_comap' {f : γ → β} {g : α → γ} [v : uniform_space β] [u : uniform_space α]
(h : uniform_continuous (f ∘ g)) : @uniform_continuous α γ u (uniform_space.comap f v) g :=
tendsto_comap_iff.2 h
lemma to_nhds_mono {u₁ u₂ : uniform_space α} (h : u₁ ≤ u₂) (a : α) :
@nhds _ (@uniform_space.to_topological_space _ u₁) a ≤
@nhds _ (@uniform_space.to_topological_space _ u₂) a :=
by rw [@nhds_eq_uniformity α u₁ a, @nhds_eq_uniformity α u₂ a]; exact (lift'_mono h le_rfl)
lemma to_topological_space_mono {u₁ u₂ : uniform_space α} (h : u₁ ≤ u₂) :
@uniform_space.to_topological_space _ u₁ ≤ @uniform_space.to_topological_space _ u₂ :=
le_of_nhds_le_nhds $ to_nhds_mono h
lemma uniform_continuous.continuous [uniform_space α] [uniform_space β] {f : α → β}
(hf : uniform_continuous f) : continuous f :=
continuous_iff_le_induced.mpr $ to_topological_space_mono $ uniform_continuous_iff.1 hf
lemma to_topological_space_bot : @uniform_space.to_topological_space α ⊥ = ⊥ := rfl
lemma to_topological_space_top : @uniform_space.to_topological_space α ⊤ = ⊤ :=
top_unique $ assume s hs, s.eq_empty_or_nonempty.elim
(assume : s = ∅, this.symm ▸ @is_open_empty _ ⊤)
(assume ⟨x, hx⟩,
have s = univ, from top_unique $ assume y hy, hs x hx (x, y) rfl,
this.symm ▸ @is_open_univ _ ⊤)
lemma to_topological_space_infi {ι : Sort*} {u : ι → uniform_space α} :
(infi u).to_topological_space = ⨅i, (u i).to_topological_space :=
begin
by_cases h : nonempty ι,
{ resetI,
refine (eq_of_nhds_eq_nhds $ assume a, _),
rw [nhds_infi, nhds_eq_uniformity],
change (infi u).uniformity.lift' (preimage $ prod.mk a) = _,
rw [infi_uniformity, lift'_infi],
{ simp only [nhds_eq_uniformity], refl },
{ exact assume a b, rfl } },
{ rw [infi_of_empty h, infi_of_empty h, to_topological_space_top] }
end
lemma to_topological_space_Inf {s : set (uniform_space α)} :
(Inf s).to_topological_space = (⨅i∈s, @uniform_space.to_topological_space α i) :=
begin
rw [Inf_eq_infi],
simp only [← to_topological_space_infi],
end
lemma to_topological_space_inf {u v : uniform_space α} :
(u ⊓ v).to_topological_space = u.to_topological_space ⊓ v.to_topological_space :=
by rw [to_topological_space_Inf, infi_pair]
instance : uniform_space empty := ⊥
instance : uniform_space punit := ⊥
instance : uniform_space bool := ⊥
instance : uniform_space ℕ := ⊥
instance : uniform_space ℤ := ⊥
instance {p : α → Prop} [t : uniform_space α] : uniform_space (subtype p) :=
uniform_space.comap subtype.val t
lemma uniformity_subtype {p : α → Prop} [t : uniform_space α] :
𝓤 (subtype p) = comap (λq:subtype p × subtype p, (q.1.1, q.2.1)) (𝓤 α) :=
rfl
lemma uniform_continuous_subtype_val {p : α → Prop} [uniform_space α] :
uniform_continuous (subtype.val : {a : α // p a} → α) :=
uniform_continuous_comap
lemma uniform_continuous_subtype_mk {p : α → Prop} [uniform_space α] [uniform_space β]
{f : β → α} (hf : uniform_continuous f) (h : ∀x, p (f x)) :
uniform_continuous (λx, ⟨f x, h x⟩ : β → subtype p) :=
uniform_continuous_comap' hf
lemma uniform_continuous_on_iff_restrict [uniform_space α] [uniform_space β] {f : α → β}
{s : set α} :
uniform_continuous_on f s ↔ uniform_continuous (s.restrict f) :=
begin
unfold uniform_continuous_on set.restrict uniform_continuous tendsto,
rw [show (λ x : s × s, (f x.1, f x.2)) = prod.map f f ∘ coe, by ext x; cases x; refl,
uniformity_comap rfl,
show prod.map subtype.val subtype.val = (coe : s × s → α × α), by ext x; cases x; refl],
conv in (map _ (comap _ _)) { rw ← filter.map_map },
rw subtype_coe_map_comap_prod, refl,
end
lemma tendsto_of_uniform_continuous_subtype
[uniform_space α] [uniform_space β] {f : α → β} {s : set α} {a : α}
(hf : uniform_continuous (λx:s, f x.val)) (ha : s ∈ 𝓝 a) :
tendsto f (𝓝 a) (𝓝 (f a)) :=
by rw [(@map_nhds_subtype_coe_eq α _ s a (mem_of_mem_nhds ha) ha).symm]; exact
tendsto_map' (continuous_iff_continuous_at.mp hf.continuous _)
lemma uniform_continuous_on.continuous_on [uniform_space α] [uniform_space β] {f : α → β}
{s : set α} (h : uniform_continuous_on f s) : continuous_on f s :=
begin
rw uniform_continuous_on_iff_restrict at h,
rw continuous_on_iff_continuous_restrict,
exact h.continuous
end
section prod
/- a similar product space is possible on the function space (uniformity of pointwise convergence),
but we want to have the uniformity of uniform convergence on function spaces -/
instance [u₁ : uniform_space α] [u₂ : uniform_space β] : uniform_space (α × β) :=
uniform_space.of_core_eq
(u₁.comap prod.fst ⊓ u₂.comap prod.snd).to_core
prod.topological_space
(calc prod.topological_space = (u₁.comap prod.fst ⊓ u₂.comap prod.snd).to_topological_space :
by rw [to_topological_space_inf, to_topological_space_comap, to_topological_space_comap]; refl
... = _ : by rw [uniform_space.to_core_to_topological_space])
theorem uniformity_prod [uniform_space α] [uniform_space β] : 𝓤 (α × β) =
(𝓤 α).comap (λp:(α × β) × α × β, (p.1.1, p.2.1)) ⊓
(𝓤 β).comap (λp:(α × β) × α × β, (p.1.2, p.2.2)) :=
inf_uniformity
lemma uniformity_prod_eq_prod [uniform_space α] [uniform_space β] :
𝓤 (α×β) =
map (λp:(α×α)×(β×β), ((p.1.1, p.2.1), (p.1.2, p.2.2))) (𝓤 α ×ᶠ 𝓤 β) :=
have map (λp:(α×α)×(β×β), ((p.1.1, p.2.1), (p.1.2, p.2.2))) =
comap (λp:(α×β)×(α×β), ((p.1.1, p.2.1), (p.1.2, p.2.2))),
from funext $ assume f, map_eq_comap_of_inverse
(funext $ assume ⟨⟨_, _⟩, ⟨_, _⟩⟩, rfl) (funext $ assume ⟨⟨_, _⟩, ⟨_, _⟩⟩, rfl),
by rw [this, uniformity_prod, filter.prod, comap_inf, comap_comap, comap_comap]
lemma mem_map_iff_exists_image' {α : Type*} {β : Type*} {f : filter α} {m : α → β} {t : set β} :
t ∈ (map m f).sets ↔ (∃s∈f, m '' s ⊆ t) :=
mem_map_iff_exists_image
lemma mem_uniformity_of_uniform_continuous_invariant [uniform_space α] {s:set (α×α)} {f : α → α → α}
(hf : uniform_continuous (λp:α×α, f p.1 p.2)) (hs : s ∈ 𝓤 α) :
∃u∈𝓤 α, ∀a b c, (a, b) ∈ u → (f a c, f b c) ∈ s :=
begin
rw [uniform_continuous, uniformity_prod_eq_prod, tendsto_map'_iff, (∘)] at hf,
rcases mem_map_iff_exists_image'.1 (hf hs) with ⟨t, ht, hts⟩, clear hf,
rcases mem_prod_iff.1 ht with ⟨u, hu, v, hv, huvt⟩, clear ht,
refine ⟨u, hu, assume a b c hab, hts $ (mem_image _ _ _).2 ⟨⟨⟨a, b⟩, ⟨c, c⟩⟩, huvt ⟨_, _⟩, _⟩⟩,
exact hab,
exact refl_mem_uniformity hv,
refl
end
lemma mem_uniform_prod [t₁ : uniform_space α] [t₂ : uniform_space β] {a : set (α × α)}
{b : set (β × β)} (ha : a ∈ 𝓤 α) (hb : b ∈ 𝓤 β) :
{p:(α×β)×(α×β) | (p.1.1, p.2.1) ∈ a ∧ (p.1.2, p.2.2) ∈ b } ∈ (@uniformity (α × β) _) :=
by rw [uniformity_prod]; exact inter_mem_inf (preimage_mem_comap ha) (preimage_mem_comap hb)
lemma tendsto_prod_uniformity_fst [uniform_space α] [uniform_space β] :
tendsto (λp:(α×β)×(α×β), (p.1.1, p.2.1)) (𝓤 (α × β)) (𝓤 α) :=
le_trans (map_mono (@inf_le_left (uniform_space (α×β)) _ _ _)) map_comap_le
lemma tendsto_prod_uniformity_snd [uniform_space α] [uniform_space β] :
tendsto (λp:(α×β)×(α×β), (p.1.2, p.2.2)) (𝓤 (α × β)) (𝓤 β) :=
le_trans (map_mono (@inf_le_right (uniform_space (α×β)) _ _ _)) map_comap_le
lemma uniform_continuous_fst [uniform_space α] [uniform_space β] :
uniform_continuous (λp:α×β, p.1) :=
tendsto_prod_uniformity_fst
lemma uniform_continuous_snd [uniform_space α] [uniform_space β] :
uniform_continuous (λp:α×β, p.2) :=
tendsto_prod_uniformity_snd
variables [uniform_space α] [uniform_space β] [uniform_space γ]
lemma uniform_continuous.prod_mk
{f₁ : α → β} {f₂ : α → γ} (h₁ : uniform_continuous f₁) (h₂ : uniform_continuous f₂) :
uniform_continuous (λa, (f₁ a, f₂ a)) :=
by rw [uniform_continuous, uniformity_prod]; exact
tendsto_inf.2 ⟨tendsto_comap_iff.2 h₁, tendsto_comap_iff.2 h₂⟩
lemma uniform_continuous.prod_mk_left {f : α × β → γ} (h : uniform_continuous f) (b) :
uniform_continuous (λ a, f (a,b)) :=
h.comp (uniform_continuous_id.prod_mk uniform_continuous_const)
lemma uniform_continuous.prod_mk_right {f : α × β → γ} (h : uniform_continuous f) (a) :
uniform_continuous (λ b, f (a,b)) :=
h.comp (uniform_continuous_const.prod_mk uniform_continuous_id)
lemma uniform_continuous.prod_map [uniform_space δ] {f : α → γ} {g : β → δ}
(hf : uniform_continuous f) (hg : uniform_continuous g) :
uniform_continuous (prod.map f g) :=
(hf.comp uniform_continuous_fst).prod_mk (hg.comp uniform_continuous_snd)
lemma to_topological_space_prod {α} {β} [u : uniform_space α] [v : uniform_space β] :
@uniform_space.to_topological_space (α × β) prod.uniform_space =
@prod.topological_space α β u.to_topological_space v.to_topological_space := rfl
end prod
section
open uniform_space function
variables {δ' : Type*} [uniform_space α] [uniform_space β] [uniform_space γ] [uniform_space δ]
[uniform_space δ']
local notation f `∘₂` g := function.bicompr f g
/-- Uniform continuity for functions of two variables. -/
def uniform_continuous₂ (f : α → β → γ) := uniform_continuous (uncurry f)
lemma uniform_continuous₂_def (f : α → β → γ) :
uniform_continuous₂ f ↔ uniform_continuous (uncurry f) := iff.rfl
lemma uniform_continuous₂.uniform_continuous {f : α → β → γ} (h : uniform_continuous₂ f) :
uniform_continuous (uncurry f) := h
lemma uniform_continuous₂_curry (f : α × β → γ) :
uniform_continuous₂ (function.curry f) ↔ uniform_continuous f :=
by rw [uniform_continuous₂, uncurry_curry]
lemma uniform_continuous₂.comp {f : α → β → γ} {g : γ → δ}
(hg : uniform_continuous g) (hf : uniform_continuous₂ f) :
uniform_continuous₂ (g ∘₂ f) :=
hg.comp hf
lemma uniform_continuous₂.bicompl {f : α → β → γ} {ga : δ → α} {gb : δ' → β}
(hf : uniform_continuous₂ f) (hga : uniform_continuous ga) (hgb : uniform_continuous gb) :
uniform_continuous₂ (bicompl f ga gb) :=
hf.uniform_continuous.comp (hga.prod_map hgb)
end
lemma to_topological_space_subtype [u : uniform_space α] {p : α → Prop} :
@uniform_space.to_topological_space (subtype p) subtype.uniform_space =
@subtype.topological_space α p u.to_topological_space := rfl
section sum
variables [uniform_space α] [uniform_space β]
open sum
/-- Uniformity on a disjoint union. Entourages of the diagonal in the union are obtained
by taking independently an entourage of the diagonal in the first part, and an entourage of
the diagonal in the second part. -/
def uniform_space.core.sum : uniform_space.core (α ⊕ β) :=
uniform_space.core.mk'
(map (λ p : α × α, (inl p.1, inl p.2)) (𝓤 α) ⊔ map (λ p : β × β, (inr p.1, inr p.2)) (𝓤 β))
(λ r ⟨H₁, H₂⟩ x, by cases x; [apply refl_mem_uniformity H₁, apply refl_mem_uniformity H₂])
(λ r ⟨H₁, H₂⟩, ⟨symm_le_uniformity H₁, symm_le_uniformity H₂⟩)
(λ r ⟨Hrα, Hrβ⟩, begin
rcases comp_mem_uniformity_sets Hrα with ⟨tα, htα, Htα⟩,
rcases comp_mem_uniformity_sets Hrβ with ⟨tβ, htβ, Htβ⟩,
refine ⟨_,
⟨mem_map_iff_exists_image.2 ⟨tα, htα, subset_union_left _ _⟩,
mem_map_iff_exists_image.2 ⟨tβ, htβ, subset_union_right _ _⟩⟩, _⟩,
rintros ⟨_, _⟩ ⟨z, ⟨⟨a, b⟩, hab, ⟨⟩⟩ | ⟨⟨a, b⟩, hab, ⟨⟩⟩,
⟨⟨_, c⟩, hbc, ⟨⟩⟩ | ⟨⟨_, c⟩, hbc, ⟨⟩⟩⟩,
{ have A : (a, c) ∈ tα ○ tα := ⟨b, hab, hbc⟩,
exact Htα A },
{ have A : (a, c) ∈ tβ ○ tβ := ⟨b, hab, hbc⟩,
exact Htβ A }
end)
/-- The union of an entourage of the diagonal in each set of a disjoint union is again an entourage
of the diagonal. -/
lemma union_mem_uniformity_sum
{a : set (α × α)} (ha : a ∈ 𝓤 α) {b : set (β × β)} (hb : b ∈ 𝓤 β) :
((λ p : (α × α), (inl p.1, inl p.2)) '' a ∪ (λ p : (β × β), (inr p.1, inr p.2)) '' b) ∈
(@uniform_space.core.sum α β _ _).uniformity :=
⟨mem_map_iff_exists_image.2 ⟨_, ha, subset_union_left _ _⟩,
mem_map_iff_exists_image.2 ⟨_, hb, subset_union_right _ _⟩⟩
/- To prove that the topology defined by the uniform structure on the disjoint union coincides with
the disjoint union topology, we need two lemmas saying that open sets can be characterized by
the uniform structure -/
lemma uniformity_sum_of_open_aux {s : set (α ⊕ β)} (hs : is_open s) {x : α ⊕ β} (xs : x ∈ s) :
{ p : ((α ⊕ β) × (α ⊕ β)) | p.1 = x → p.2 ∈ s } ∈ (@uniform_space.core.sum α β _ _).uniformity :=
begin
cases x,
{ refine mem_of_superset
(union_mem_uniformity_sum (mem_nhds_uniformity_iff_right.1 (is_open.mem_nhds hs.1 xs))
univ_mem)
(union_subset _ _);
rintro _ ⟨⟨_, b⟩, h, ⟨⟩⟩ ⟨⟩,
exact h rfl },
{ refine mem_of_superset
(union_mem_uniformity_sum univ_mem (mem_nhds_uniformity_iff_right.1
(is_open.mem_nhds hs.2 xs)))
(union_subset _ _);
rintro _ ⟨⟨a, _⟩, h, ⟨⟩⟩ ⟨⟩,
exact h rfl },
end
lemma open_of_uniformity_sum_aux {s : set (α ⊕ β)}
(hs : ∀x ∈ s, { p : ((α ⊕ β) × (α ⊕ β)) | p.1 = x → p.2 ∈ s } ∈
(@uniform_space.core.sum α β _ _).uniformity) :
is_open s :=
begin
split,
{ refine (@is_open_iff_mem_nhds α _ _).2 (λ a ha, mem_nhds_uniformity_iff_right.2 _),
rcases mem_map_iff_exists_image.1 (hs _ ha).1 with ⟨t, ht, st⟩,
refine mem_of_superset ht _,
rintro p pt rfl, exact st ⟨_, pt, rfl⟩ rfl },
{ refine (@is_open_iff_mem_nhds β _ _).2 (λ b hb, mem_nhds_uniformity_iff_right.2 _),
rcases mem_map_iff_exists_image.1 (hs _ hb).2 with ⟨t, ht, st⟩,
refine mem_of_superset ht _,
rintro p pt rfl, exact st ⟨_, pt, rfl⟩ rfl }
end
/- We can now define the uniform structure on the disjoint union -/
instance sum.uniform_space : uniform_space (α ⊕ β) :=
{ to_core := uniform_space.core.sum,
is_open_uniformity := λ s, ⟨uniformity_sum_of_open_aux, open_of_uniformity_sum_aux⟩ }
lemma sum.uniformity : 𝓤 (α ⊕ β) =
map (λ p : α × α, (inl p.1, inl p.2)) (𝓤 α) ⊔
map (λ p : β × β, (inr p.1, inr p.2)) (𝓤 β) := rfl
end sum
end constructions
-- For a version of the Lebesgue number lemma assuming only a sequentially compact space,
-- see topology/sequences.lean
/-- Let `c : ι → set α` be an open cover of a compact set `s`. Then there exists an entourage
`n` such that for each `x ∈ s` its `n`-neighborhood is contained in some `c i`. -/
lemma lebesgue_number_lemma {α : Type u} [uniform_space α] {s : set α} {ι} {c : ι → set α}
(hs : is_compact s) (hc₁ : ∀ i, is_open (c i)) (hc₂ : s ⊆ ⋃ i, c i) :
∃ n ∈ 𝓤 α, ∀ x ∈ s, ∃ i, {y | (x, y) ∈ n} ⊆ c i :=
begin
let u := λ n, {x | ∃ i (m ∈ 𝓤 α), {y | (x, y) ∈ m ○ n} ⊆ c i},
have hu₁ : ∀ n ∈ 𝓤 α, is_open (u n),
{ refine λ n hn, is_open_uniformity.2 _,
rintro x ⟨i, m, hm, h⟩,
rcases comp_mem_uniformity_sets hm with ⟨m', hm', mm'⟩,
apply (𝓤 α).sets_of_superset hm',
rintros ⟨x, y⟩ hp rfl,
refine ⟨i, m', hm', λ z hz, h (monotone_comp_rel monotone_id monotone_const mm' _)⟩,
dsimp at hz ⊢, rw comp_rel_assoc,
exact ⟨y, hp, hz⟩ },
have hu₂ : s ⊆ ⋃ n ∈ 𝓤 α, u n,
{ intros x hx,
rcases mem_Union.1 (hc₂ hx) with ⟨i, h⟩,
rcases comp_mem_uniformity_sets (is_open_uniformity.1 (hc₁ i) x h) with ⟨m', hm', mm'⟩,
exact mem_bUnion hm' ⟨i, _, hm', λ y hy, mm' hy rfl⟩ },
rcases hs.elim_finite_subcover_image hu₁ hu₂ with ⟨b, bu, b_fin, b_cover⟩,
refine ⟨_, (bInter_mem b_fin).2 bu, λ x hx, _⟩,
rcases mem_bUnion_iff.1 (b_cover hx) with ⟨n, bn, i, m, hm, h⟩,
refine ⟨i, λ y hy, h _⟩,
exact prod_mk_mem_comp_rel (refl_mem_uniformity hm) (bInter_subset_of_mem bn hy)
end
/-- Let `c : set (set α)` be an open cover of a compact set `s`. Then there exists an entourage
`n` such that for each `x ∈ s` its `n`-neighborhood is contained in some `t ∈ c`. -/
lemma lebesgue_number_lemma_sUnion {α : Type u} [uniform_space α] {s : set α} {c : set (set α)}
(hs : is_compact s) (hc₁ : ∀ t ∈ c, is_open t) (hc₂ : s ⊆ ⋃₀ c) :
∃ n ∈ 𝓤 α, ∀ x ∈ s, ∃ t ∈ c, ∀ y, (x, y) ∈ n → y ∈ t :=
by rw sUnion_eq_Union at hc₂;
simpa using lebesgue_number_lemma hs (by simpa) hc₂
/-!
### Expressing continuity properties in uniform spaces
We reformulate the various continuity properties of functions taking values in a uniform space
in terms of the uniformity in the target. Since the same lemmas (essentially with the same names)
also exist for metric spaces and emetric spaces (reformulating things in terms of the distance or
the edistance in the target), we put them in a namespace `uniform` here.
In the metric and emetric space setting, there are also similar lemmas where one assumes that
both the source and the target are metric spaces, reformulating things in terms of the distance
on both sides. These lemmas are generally written without primes, and the versions where only
the target is a metric space is primed. We follow the same convention here, thus giving lemmas
with primes.
-/
namespace uniform
variables [uniform_space α]
theorem tendsto_nhds_right {f : filter β} {u : β → α} {a : α} :
tendsto u f (𝓝 a) ↔ tendsto (λ x, (a, u x)) f (𝓤 α) :=
⟨λ H, tendsto_left_nhds_uniformity.comp H,
λ H s hs, by simpa [mem_of_mem_nhds hs] using H (mem_nhds_uniformity_iff_right.1 hs)⟩
theorem tendsto_nhds_left {f : filter β} {u : β → α} {a : α} :
tendsto u f (𝓝 a) ↔ tendsto (λ x, (u x, a)) f (𝓤 α) :=
⟨λ H, tendsto_right_nhds_uniformity.comp H,
λ H s hs, by simpa [mem_of_mem_nhds hs] using H (mem_nhds_uniformity_iff_left.1 hs)⟩
theorem continuous_at_iff'_right [topological_space β] {f : β → α} {b : β} :
continuous_at f b ↔ tendsto (λ x, (f b, f x)) (𝓝 b) (𝓤 α) :=
by rw [continuous_at, tendsto_nhds_right]
theorem continuous_at_iff'_left [topological_space β] {f : β → α} {b : β} :
continuous_at f b ↔ tendsto (λ x, (f x, f b)) (𝓝 b) (𝓤 α) :=
by rw [continuous_at, tendsto_nhds_left]
theorem continuous_at_iff_prod [topological_space β] {f : β → α} {b : β} :
continuous_at f b ↔ tendsto (λ x : β × β, (f x.1, f x.2)) (𝓝 (b, b)) (𝓤 α) :=
⟨λ H, le_trans (H.prod_map' H) (nhds_le_uniformity _),
λ H, continuous_at_iff'_left.2 $ H.comp $ tendsto_id.prod_mk_nhds tendsto_const_nhds⟩
theorem continuous_within_at_iff'_right [topological_space β] {f : β → α} {b : β} {s : set β} :
continuous_within_at f s b ↔ tendsto (λ x, (f b, f x)) (𝓝[s] b) (𝓤 α) :=
by rw [continuous_within_at, tendsto_nhds_right]
theorem continuous_within_at_iff'_left [topological_space β] {f : β → α} {b : β} {s : set β} :
continuous_within_at f s b ↔ tendsto (λ x, (f x, f b)) (𝓝[s] b) (𝓤 α) :=
by rw [continuous_within_at, tendsto_nhds_left]
theorem continuous_on_iff'_right [topological_space β] {f : β → α} {s : set β} :
continuous_on f s ↔ ∀ b ∈ s, tendsto (λ x, (f b, f x)) (𝓝[s] b) (𝓤 α) :=
by simp [continuous_on, continuous_within_at_iff'_right]
theorem continuous_on_iff'_left [topological_space β] {f : β → α} {s : set β} :
continuous_on f s ↔ ∀ b ∈ s, tendsto (λ x, (f x, f b)) (𝓝[s] b) (𝓤 α) :=
by simp [continuous_on, continuous_within_at_iff'_left]
theorem continuous_iff'_right [topological_space β] {f : β → α} :
continuous f ↔ ∀ b, tendsto (λ x, (f b, f x)) (𝓝 b) (𝓤 α) :=
continuous_iff_continuous_at.trans $ forall_congr $ λ b, tendsto_nhds_right
theorem continuous_iff'_left [topological_space β] {f : β → α} :
continuous f ↔ ∀ b, tendsto (λ x, (f x, f b)) (𝓝 b) (𝓤 α) :=
continuous_iff_continuous_at.trans $ forall_congr $ λ b, tendsto_nhds_left
end uniform
lemma filter.tendsto.congr_uniformity {α β} [uniform_space β] {f g : α → β} {l : filter α} {b : β}
(hf : tendsto f l (𝓝 b)) (hg : tendsto (λ x, (f x, g x)) l (𝓤 β)) :
tendsto g l (𝓝 b) :=
uniform.tendsto_nhds_right.2 $ (uniform.tendsto_nhds_right.1 hf).uniformity_trans hg
lemma uniform.tendsto_congr {α β} [uniform_space β] {f g : α → β} {l : filter α} {b : β}
(hfg : tendsto (λ x, (f x, g x)) l (𝓤 β)) :
tendsto f l (𝓝 b) ↔ tendsto g l (𝓝 b) :=
⟨λ h, h.congr_uniformity hfg, λ h, h.congr_uniformity hfg.uniformity_symm⟩
|
f7f4a3f16147008ba46f669b57557769c5e0e202 | 222111140d2023e142b07e9cd5119ac2829b36f5 | /src/gaussian_elimination.lean | df3fbe03d207a29af85718c04f0fb4237832b71e | [] | no_license | jjcrawford/lean-gaussian-elimination | 740dfdf2de89dc99c088c53e5221d9dfad3c0b92 | c473d33c07fa6f141d17d9dc42ad07956c33dd03 | refs/heads/master | 1,585,793,867,436 | 1,540,443,865,000 | 1,540,443,865,000 | 153,901,939 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 15,094 | lean | import ring_theory.matrix
import .row_equivalence
universes u
variables {m n : ℕ}
variable {α : Type u}
variable [division_ring α]
variable [decidable_eq α]
def ge_aux_findpivot : (fin m) → (fin m) → (fin n) → (matrix (fin m) (fin n) α) → (matrix (fin m) (fin n) α)
| ⟨0, h₁⟩ i₀ j₀ M := M
| ⟨(k + 1), h₁⟩ i₀ j₀ M :=
if k ≥ i₀.val then
if M ⟨k+1, h₁⟩ j₀ ≠ 0
then matrix.mul (elementary.swap α ⟨k+1, h₁⟩ i₀).to_matrix M
else ge_aux_findpivot ⟨k, nat.lt_of_succ_lt h₁⟩ i₀ j₀ M
else M
def ge_aux_improvepivot : (fin m) → (fin n) → (matrix (fin m) (fin n) α) → (matrix (fin m) (fin n) α) :=
λ i₀ j₀ M, if h : M i₀ j₀ ≠ 0
then matrix.mul (elementary.scale i₀ ((M i₀ j₀)⁻¹) (inv_ne_zero h)).to_matrix M
else M
def ge_aux_eliminate : Π (k : fin m) (i : fin m) (j : fin n) (M : matrix (fin m) (fin n) α) (h : M i j = 1), (matrix (fin m) (fin n) α) :=
λ k i j M h, if h₀ : k≠i then matrix.mul (elementary.linear_add k (-(M k j)) i h₀).to_matrix M else M
def ge_aux_eliminatecolumn : Π (k : fin m) (i : fin m) (j : fin n) (M : matrix (fin m) (fin n) α), (matrix (fin m) (fin n) α)
| ⟨0,h₁⟩ i j M := M
| ⟨k+1, h₁⟩ i j M := begin
from if h : k < i.val then M else begin
apply ge_aux_eliminatecolumn ⟨k, nat.lt_of_succ_lt h₁⟩ i j _ ,
-- show matrix (fin m) (fin n) α,
-- clear ge_aux_eliminatecolumn,
-- cases n,
-- exfalso,
-- from nat.not_lt_zero j.val j.is_lt,
-- cases m,
-- exfalso,
-- from nat.not_lt_zero i.val i.is_lt,
-- have h₂, from (iff.elim_left nat.lt_iff_le_not_le),
have h_ne : fin.mk (k+1) h₁ ≠ i,
intros h_eq,
apply h,
cases h_eq,
simp[nat.lt_succ_self 0],
from matrix.mul (elementary.linear_add ⟨k+1, h₁⟩ (-(M ⟨k+1,h₁⟩ j)) i h_ne).to_matrix M,
end
end
inductive row_reduction_step : (fin m) → (fin n) → matrix (fin m) (fin n) α → matrix (fin m) (fin n) α → Type u
| findpivot : Π (i : fin m) (j : fin n) (M : matrix (fin m) (fin n) α) (i₀ : fin m), row_reduction_step i j M (ge_aux_findpivot i₀ i j M)
| improvepivot : Π (i : fin m) (j : fin n) (M : matrix (fin m) (fin n) α), row_reduction_step i j M (ge_aux_improvepivot i j M)
| eliminate : Π (i : fin m) (j : fin n) (M : matrix (fin m) (fin n) α) (i₀ : fin m) (h : M i j = 1), row_reduction_step i j M (ge_aux_eliminate i₀ i j M h)
def ge_aux_findpivot_row_equivalent : Π (i : fin m) (i₀ : fin m) (j₀ : fin n) (M : matrix (fin m) (fin n) α), row_equivalent M (ge_aux_findpivot i i₀ j₀ M)
| ⟨0, h₀⟩ i₀ j₀ M :=
begin
simp[ge_aux_findpivot],
from row_equivalent.nil,
end
| ⟨k+1, h₀⟩ i₀ j₀ M := begin
unfold ge_aux_findpivot,
split_ifs,
from @row_equivalent_step.of_elementary m n α _ _ M (elementary.swap α ⟨k + 1, h₀⟩ i₀),
apply ge_aux_findpivot_row_equivalent,
from row_equivalent.nil,
end
-- set_option pp.proofs true
def ge_aux_improvepivot_row_equivalent : Π (i₀ : fin m) (j₀ : fin n) (M : matrix (fin m) (fin n) α), row_equivalent M (ge_aux_improvepivot i₀ j₀ M)
| i₀ j₀ M :=
begin
simp[ge_aux_improvepivot],
split_ifs,
from @row_equivalent_step.of_elementary m n α _ _ M (elementary.scale i₀ (M i₀ j₀)⁻¹ (ge_aux_improvepivot._proof_1 i₀ j₀ M h)),
from row_equivalent.nil
end
def ge_aux_eliminate_row_equivalent : Π (i : fin m) (i₀ : fin m) (j₀ : fin n) (M : matrix (fin m) (fin n) α) (h : M i₀ j₀ = 1), row_equivalent M (ge_aux_eliminate i i₀ j₀ M h)
| i i₀ j₀ M h :=
begin
unfold ge_aux_eliminate,
split_ifs,
from @row_equivalent_step.of_elementary m n α _ _ M (elementary.linear_add i (-M i j₀) i₀ h_1),
from row_equivalent.nil,
end
def ge_aux_eliminatecolumn_row_equivalent : Π (i : fin m) (i₀ : fin m) (j₀ : fin n) (M : matrix (fin m) (fin n) α), row_equivalent M (ge_aux_eliminatecolumn i i₀ j₀ M)
| ⟨0, h₀⟩ i₀ j₀ M :=
begin
unfold ge_aux_eliminatecolumn,
from row_equivalent.nil,
end
| ⟨k+1, h₀⟩ i₀ j₀ M :=
begin
unfold ge_aux_eliminatecolumn,
split_ifs,
from row_equivalent.nil,
apply row_equivalent.trans,
show matrix (fin m) (fin n) α,
from (matrix.mul
(elementary.to_matrix
(elementary.linear_add ⟨k + 1, h₀⟩ (-M ⟨k + 1, h₀⟩ j₀) i₀
(ge_aux_eliminatecolumn._main._pack._proof_1 k h₀ i₀ h)))
M),
from @row_equivalent_step.of_elementary m n α _ _ M (elementary.linear_add ⟨k + 1, h₀⟩ (-M ⟨k + 1, h₀⟩ j₀) i₀
(ge_aux_eliminatecolumn._main._pack._proof_1 k h₀ i₀ h)),
apply ge_aux_eliminatecolumn_row_equivalent,
end
-- TODO: Why does bytecode generation fail?
-- def row_reduction_step.to_row_equivalent : Π {j : fin n} {i : fin m} {M N : matrix (fin m) (fin n) α} (r : row_reduction_step i j M N), row_equivalent M N :=
-- begin
-- intros _ _ _ _ r,
-- induction r with i j M i₀ i j M i j M i₀ h,
-- from @ge_aux_findpivot_row_equivalent m n α _ _ i₀ i j M,
-- from @ge_aux_improvepivot_row_equivalent m n α _ _ i j M,
-- from @ge_aux_eliminate_row_equivalent m n α _ _ i₀ i j M h,
-- end
-- Note that bytecode generation fails even more seriously here! (Because they choose a red underline?)
-- def to_row_equivalent : Π {j : fin n} {i : fin m} {M N : matrix (fin m) (fin n) α} (r : row_reduction_step i j M N), row_equivalent M N
-- | _ _ _ _ (row_reduction_step.findpivot i j M i₀) := @ge_aux_findpivot_row_equivalent m n α _ _ i₀ i j M
-- | _ _ _ _ (row_reduction_step.improvepivot i j M) := @ge_aux_improvepivot_row_equivalent m n α _ _ i j M
-- | _ _ _ _ (row_reduction_step.eliminate i j M i₀ h) := @ge_aux_eliminate_row_equivalent m n α _ _ i₀ i j M h
lemma nat.sub_lt_succ_of_lt_succ {a b : ℕ} : a < (nat.succ b) → b - a < (nat.succ b) :=
begin
intro h,
cases a,
from nat.lt_succ_self b,
from nat.lt_trans ((nat.sub_lt_of_pos_le (nat.succ a) b (nat.zero_lt_succ a)) (nat.le_of_lt_succ h)) (nat.lt_succ_self b),
end
@[simp] lemma nat.pred_lt_of_ne_zero {n : ℕ} : n ≠ 0 → nat.succ (nat.pred n) = n :=
begin
intros h_nz,
apply nat.succ_pred_eq_of_pos,
have H₁, from @nat.eq_or_lt_of_le 0 n (nat.zero_le n),
cases H₁,
exfalso,
from h_nz (eq.symm H₁),
assumption,
end
lemma nat.pred_sub_lt {a b : ℕ} : b ≠ 0 → a < b → (nat.pred b) - a < b :=
begin
intros h_n h,
rw ←nat.pred_lt_of_ne_zero h_n,
apply nat.sub_lt_succ_of_lt_succ,
simp[nat.pred_lt_of_ne_zero h_n],
from h,
end
lemma nat.lt_succ_of_succ_lt {a b : ℕ} : nat.succ a < b → a < nat.succ b :=
begin
intros h,
have ha, from nat.lt_succ_self a,
have hb, from nat.lt_succ_self b,
apply nat.lt_trans ha,
apply nat.lt_trans,
swap,
from hb,
from h
end
lemma nat.pred_pred_sub_lt_of_lt : Π {a b : ℕ}, nat.succ a < b → (nat.pred b) - a - 1 < b :=
begin
intros a b h,
have H₁, from @nat.sub_lt_succ_of_lt_succ (nat.succ a) (nat.pred b),
rw nat.pred_lt_of_ne_zero at H₁,
have H₂,
from H₁ h,
have H₃ : nat.pred b - nat.succ a = nat.pred b - a - 1,
refl,
rw ←H₃,
from H₂,
intros h₁,
have H₂, from @nat.zero_lt_succ a,
have H₃, from nat.lt_trans H₂ h,
subst h₁,
from nat.not_lt_zero 0 H₃,
end
lemma nat.lt_succ_pred : Π {n : ℕ}, (n ≠ 0) → (nat.pred n) < n :=
begin
intros n h,
have : (nat.pred n < nat.succ (nat.pred n)) = (nat.pred n < n),
congr,
from nat.pred_lt_of_ne_zero h,
rw ←this,
from nat.lt_succ_self (nat.pred n),
end
def ge_aux : Π (j : fin n) (i : fin m) (h_n : n ≠ 0) (h_m : m ≠ 0) (M : matrix (fin m) (fin n) α), (matrix (fin m) (fin n) α)
| ⟨k₂, h₂⟩ ⟨0, h₁⟩ h_n h_m M :=
begin -- If we're on the last row, all we need to do is improve the pivot if we can
from if M ⟨0, h₁⟩ ⟨k₂, h₂⟩ ≠ 0 then
begin
apply ge_aux_improvepivot,
from ⟨nat.pred m, nat.pred_lt h_m⟩,
from ⟨(nat.pred n) - k₂, nat.pred_sub_lt h_n h₂⟩,
from M,
end
else M,
end
| ⟨0, h₂⟩ ⟨k₁+1, h₁⟩ h_n h_m M :=
begin -- If we're in the last column, all we need to do is eliminate that column
-- have H₁, from @nat.sub_lt_succ_of_lt_succ k₁ (nat.pred m) (nat.lt_of_succ_lt h₁),
let toplefti : fin m := ⟨(nat.pred m)-k₁-1, nat.pred_pred_sub_lt_of_lt h₁⟩,
let topleftj : fin n := ⟨nat.pred n, nat.pred_lt h_n⟩,
let bottomrow : fin m := ⟨nat.pred m, nat.pred_lt h_m⟩,
have M₁ : matrix (fin m) (fin n) α,
apply ge_aux_findpivot bottomrow toplefti topleftj M,
from if H₁ : (M₁ toplefti topleftj ≠ 0) then begin
apply ge_aux_eliminatecolumn,
from bottomrow,
from toplefti,
from topleftj,
apply ge_aux_improvepivot,
from toplefti,
from topleftj,
from M₁,
repeat {assumption},
end else M₁,
end
| ⟨k₂+1, h₂⟩ ⟨k₁+1, h₁⟩ h_n h_m M :=
begin
apply ge_aux,
show matrix (fin m) (fin n) α,
let toplefti : (fin m) := ⟨(nat.pred m)-k₁-1, nat.pred_pred_sub_lt_of_lt h₁⟩,
let topleftj : (fin n) := ⟨(nat.pred n)-k₂-1, nat.pred_pred_sub_lt_of_lt h₂⟩,
let bottomrow : fin (m) := ⟨nat.pred m, nat.pred_lt h_m⟩,
have M₁ : matrix (fin m) (fin n) α,
from ge_aux_findpivot bottomrow toplefti topleftj M,
from if H₁ : (M₁ toplefti topleftj ≠ 0) then begin
apply ge_aux_eliminatecolumn,
from bottomrow,
from toplefti,
from topleftj,
-- show matrix _ _ α,
apply ge_aux_improvepivot,
from toplefti,
from topleftj,
from M₁,
repeat {assumption},
end else M₁,
from ⟨k₂, nat.lt_of_succ_lt h₂⟩,
let toplefti : fin m := ⟨(nat.pred m)-k₁-1, nat.pred_pred_sub_lt_of_lt h₁⟩,
let topleftj : fin n := ⟨(nat.pred n)-k₂-1, nat.pred_pred_sub_lt_of_lt h₂⟩,
let bottomrow : fin m := ⟨nat.pred m, nat.pred_lt h_m⟩,
have M₁ : matrix (fin m) (fin n) α,
from ge_aux_findpivot bottomrow toplefti topleftj M,
from if H₁ : (M₁ toplefti topleftj ≠ 0)
then ⟨k₁, nat.lt_of_succ_lt h₁⟩
else ⟨k₁+1, h₁⟩,
from h_n,
from h_m,
end
def gaussian_elimination : Π {m n : ℕ}, matrix (fin m) (fin n) α → matrix (fin m) (fin n) α
| 0 _ M := M
| _ 0 M := M
| (m+1) (n+1) M :=
begin
refine ge_aux ⟨ n, nat.lt_succ_self _ ⟩ ⟨ m, nat.lt_succ_self _ ⟩ _ _ M,
sorry, sorry
end
-- def gaussian_elimination (M : matrix (fin m) (fin n) α) : matrix (fin m) (fin n) α :=
-- begin
-- by_cases h_m : m = 0,
-- from M,
-- by_cases h_n : n = 0,
-- from M,
-- have h₁, from nat.pred_lt_of_ne_zero h_m,
-- have h₂, from nat.pred_lt_of_ne_zero h_n,
-- apply ge_aux,
-- from ⟨nat.pred n, nat.lt_succ_pred h_n⟩,
-- from ⟨nat.pred m, nat.lt_succ_pred h_m⟩,
-- from h_n,
-- from h_m,
-- from M,
-- end
def ge_aux_row_equivalent : Π (j : fin n) (i : fin m) (h_n : n ≠ 0) (h_m : m ≠ 0) (M : matrix (fin m) (fin n) α), row_equivalent M (ge_aux j i h_n h_m M)
| ⟨0, j_is_lt⟩ ⟨0, i_is_lt⟩ h_n h_m M :=
begin
simp[ge_aux],
split_ifs,
from row_equivalent.nil,
apply row_equivalent.trans,
swap,
apply ge_aux_improvepivot_row_equivalent,
from row_equivalent.nil,
end
| ⟨j+1, j_is_lt⟩ ⟨0, i_is_lt⟩ h_n h_m M :=
begin
simp[ge_aux],
split_ifs,
from row_equivalent.nil,
apply row_equivalent.trans,
swap,
apply ge_aux_improvepivot_row_equivalent,
from row_equivalent.nil,
end
| ⟨0, j_is_lt⟩ ⟨i+1, i_is_lt⟩ h_n h_m M :=
begin
simp[ge_aux],
split_ifs,
apply ge_aux_findpivot_row_equivalent,
apply row_equivalent.trans,
show row_equivalent M (ge_aux_findpivot ⟨nat.pred m, _⟩ ⟨nat.pred m - i - 1, _⟩ ⟨nat.pred n, _⟩ M),
apply ge_aux_findpivot_row_equivalent,
apply row_equivalent.trans,
show row_equivalent _ (ge_aux_improvepivot ⟨nat.pred m - i - 1, _⟩ ⟨nat.pred n, _⟩
(ge_aux_findpivot ⟨nat.pred m, _⟩ ⟨nat.pred m - i - 1, _⟩ ⟨nat.pred n, _⟩ M)),
apply ge_aux_improvepivot_row_equivalent,
apply ge_aux_eliminatecolumn_row_equivalent,
end
| ⟨j + 1, j_is_lt⟩ ⟨i + 1, i_is_lt⟩ h_n h_m M :=
begin
simp[ge_aux],
split_ifs,
apply row_equivalent.trans,
swap,
apply ge_aux_row_equivalent,
apply ge_aux_findpivot_row_equivalent,
apply row_equivalent.trans,
show row_equivalent M (ge_aux_findpivot ⟨nat.pred m, _⟩ ⟨nat.pred m - i - 1, _⟩ ⟨nat.pred n - j - 1, _⟩ M),
apply ge_aux_findpivot_row_equivalent,
apply row_equivalent.trans,
show row_equivalent _ (ge_aux_improvepivot ⟨nat.pred m - i - 1, _⟩ ⟨nat.pred n - j - 1, _⟩
(ge_aux_findpivot ⟨nat.pred m, _⟩ ⟨nat.pred m - i - 1, _⟩ ⟨nat.pred n - j - 1, _⟩ M)),
apply ge_aux_improvepivot_row_equivalent,
apply row_equivalent.trans,
show row_equivalent _ (ge_aux_eliminatecolumn ⟨nat.pred m, _⟩ ⟨nat.pred m - i - 1, _⟩ ⟨nat.pred n - j - 1, _⟩
(ge_aux_improvepivot ⟨nat.pred m - i - 1, _⟩ ⟨nat.pred n - j - 1, _⟩
(ge_aux_findpivot ⟨nat.pred m, _⟩ ⟨nat.pred m - i - 1, _⟩ ⟨nat.pred n - j - 1, _⟩ M))),
apply ge_aux_eliminatecolumn_row_equivalent,
apply ge_aux_row_equivalent,
end
def gaussian_elimination.row_equivalent : Π (M : matrix (fin m) (fin n) α), row_equivalent M (gaussian_elimination M) :=
begin
intros,
cases m;cases n;
simp[gaussian_elimination],
from row_equivalent.nil,
from row_equivalent.nil,
from row_equivalent.nil,
apply ge_aux_row_equivalent,
end |
2f6ab643f6890108eb3eb0761798ce36f546a141 | 302c785c90d40ad3d6be43d33bc6a558354cc2cf | /src/topology/instances/real_vector_space.lean | f9d990261d4a984587d65c507b82a3a4a0d17ba8 | [
"Apache-2.0"
] | permissive | ilitzroth/mathlib | ea647e67f1fdfd19a0f7bdc5504e8acec6180011 | 5254ef14e3465f6504306132fe3ba9cec9ffff16 | refs/heads/master | 1,680,086,661,182 | 1,617,715,647,000 | 1,617,715,647,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 1,489 | 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 topology.algebra.module
import topology.instances.real
/-!
# Continuous additive maps are `ℝ`-linear
In this file we prove that a continuous map `f : E →+ F` between two topological vector spaces
over `ℝ` is `ℝ`-linear
-/
variables {E : Type*} [add_comm_group E] [vector_space ℝ E] [topological_space E]
[has_continuous_smul ℝ E] {F : Type*} [add_comm_group F] [vector_space ℝ F]
[topological_space F] [has_continuous_smul ℝ F] [t2_space F]
namespace add_monoid_hom
/-- A continuous additive map between two vector spaces over `ℝ` is `ℝ`-linear. -/
lemma map_real_smul (f : E →+ F) (hf : continuous f) (c : ℝ) (x : E) :
f (c • x) = c • f x :=
suffices (λ c : ℝ, f (c • x)) = λ c : ℝ, c • f x, from _root_.congr_fun this c,
dense_embedding_of_rat.dense.equalizer
(hf.comp $ continuous_id.smul continuous_const)
(continuous_id.smul continuous_const)
(funext $ λ r, f.map_rat_cast_smul r x)
/-- Reinterpret a continuous additive homomorphism between two real vector spaces
as a continuous real-linear map. -/
def to_real_linear_map (f : E →+ F) (hf : continuous f) : E →L[ℝ] F :=
⟨⟨f, f.map_add, f.map_real_smul hf⟩, hf⟩
@[simp] lemma coe_to_real_linear_map (f : E →+ F) (hf : continuous f) :
⇑(f.to_real_linear_map hf) = f := rfl
end add_monoid_hom
|
fb969cbb33c163832f08725673e7cf6db988e746 | e38e95b38a38a99ecfa1255822e78e4b26f65bb0 | /src/certigrad/reference.lean | b899fb709c0b71cf54032b9f9473e0a17cd4b8eb | [
"Apache-2.0"
] | permissive | ColaDrill/certigrad | fefb1be3670adccd3bed2f3faf57507f156fd501 | fe288251f623ac7152e5ce555f1cd9d3a20203c2 | refs/heads/master | 1,593,297,324,250 | 1,499,903,753,000 | 1,499,903,753,000 | 97,075,797 | 1 | 0 | null | 1,499,916,210,000 | 1,499,916,210,000 | null | UTF-8 | Lean | false | false | 382 | lean | /-
Copyright (c) 2017 Daniel Selsam. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Daniel Selsam
References.
-/
import .id .tensor .util
namespace certigrad
@[reducible] def reference := ID × S
namespace reference
-- TODO(dhs): (much) better hash function
def hash : reference → ℕ
| ref := 0
end reference
end certigrad
|
fc1a0329c20dda5cf16c7df37d9c337d269aa1e3 | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/data/list/big_operators/lemmas.lean | 5cb2b62d1593fd7a5d9351020304c13917d0a464 | [
"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,834 | 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, Floris van Doorn, Sébastien Gouëzel, Alex J. Best
-/
import data.list.big_operators.basic
import algebra.group.opposite
import algebra.group_power.basic
import algebra.group_with_zero.commute
import algebra.group_with_zero.divisibility
import algebra.order.with_zero
import algebra.ring.basic
import algebra.ring.divisibility
import algebra.ring.commute
import data.int.units
import data.set.basic
/-! # Lemmas about `list.sum` and `list.prod` requiring extra algebra imports
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.-/
open mul_opposite list
variables {ι α M N P M₀ G R : Type*}
namespace commute
lemma list_sum_right [non_unital_non_assoc_semiring R] (a : R) (l : list R)
(h : ∀ b ∈ l, commute a b) :
commute a l.sum :=
begin
induction l with x xs ih,
{ exact commute.zero_right _, },
{ rw list.sum_cons,
exact (h _ $ mem_cons_self _ _).add_right (ih $ λ j hj, h _ $ mem_cons_of_mem _ hj) }
end
lemma list_sum_left [non_unital_non_assoc_semiring R] (b : R) (l : list R)
(h : ∀ a ∈ l, commute a b) :
commute l.sum b :=
(commute.list_sum_right _ _ $ λ x hx, (h _ hx).symm).symm
end commute
namespace list
@[to_additive card_nsmul_le_sum]
lemma pow_card_le_prod [monoid M] [preorder M]
[covariant_class M M (function.swap (*)) (≤)] [covariant_class M M (*) (≤)]
(l : list M) (n : M) (h : ∀ (x ∈ l), n ≤ x) :
n ^ l.length ≤ l.prod :=
@prod_le_pow_card Mᵒᵈ _ _ _ _ l n h
@[to_additive] lemma prod_eq_one_iff [canonically_ordered_monoid M] (l : list M) :
l.prod = 1 ↔ ∀ x ∈ l, x = (1 : M) :=
⟨all_one_of_le_one_le_of_prod_eq_one (λ _ _, one_le _),
λ h, by rw [eq_replicate.2 ⟨rfl, h⟩, prod_replicate, one_pow]⟩
/-- If a product of integers is `-1`, then at least one factor must be `-1`. -/
lemma neg_one_mem_of_prod_eq_neg_one {l : list ℤ} (h : l.prod = -1) : (-1 : ℤ) ∈ l :=
begin
obtain ⟨x, h₁, h₂⟩ := exists_mem_ne_one_of_prod_ne_one (ne_of_eq_of_ne h dec_trivial),
exact or.resolve_left (int.is_unit_iff.mp (prod_is_unit_iff.mp
(h.symm ▸ is_unit.neg is_unit_one : is_unit l.prod) x h₁)) h₂ ▸ h₁,
end
/-- If all elements in a list are bounded below by `1`, then the length of the list is bounded
by the sum of the elements. -/
lemma length_le_sum_of_one_le (L : list ℕ) (h : ∀ i ∈ L, 1 ≤ i) : L.length ≤ L.sum :=
begin
induction L with j L IH h, { simp },
rw [sum_cons, length, add_comm],
exact add_le_add (h _ (set.mem_insert _ _)) (IH (λ i hi, h i (set.mem_union_right _ hi)))
end
lemma dvd_prod [comm_monoid M] {a} {l : list M} (ha : a ∈ l) : a ∣ l.prod :=
let ⟨s, t, h⟩ := mem_split ha in
by { rw [h, prod_append, prod_cons, mul_left_comm], exact dvd_mul_right _ _ }
lemma dvd_sum [semiring R] {a} {l : list R} (h : ∀ x ∈ l, a ∣ x) : a ∣ l.sum :=
begin
induction l with x l ih,
{ exact dvd_zero _ },
{ rw [list.sum_cons],
exact dvd_add (h _ (mem_cons_self _ _)) (ih (λ x hx, h x (mem_cons_of_mem _ hx))) }
end
section alternating
variables [comm_group α]
@[to_additive]
lemma alternating_prod_append : ∀ l₁ l₂ : list α,
alternating_prod (l₁ ++ l₂) = alternating_prod l₁ * alternating_prod l₂ ^ (-1 : ℤ) ^ length l₁
| [] l₂ := by simp
| (a :: l₁) l₂ := by simp_rw [cons_append, alternating_prod_cons, alternating_prod_append,
length_cons, pow_succ, neg_mul, one_mul, zpow_neg, ←div_eq_mul_inv, div_div]
@[to_additive]
lemma alternating_prod_reverse :
∀ l : list α, alternating_prod (reverse l) = alternating_prod l ^ (-1 : ℤ) ^ (length l + 1)
| [] := by simp only [alternating_prod_nil, one_zpow, reverse_nil]
| (a :: l) :=
begin
simp_rw [reverse_cons, alternating_prod_append, alternating_prod_reverse,
alternating_prod_singleton, alternating_prod_cons, length_reverse, length, pow_succ, neg_mul,
one_mul, zpow_neg, inv_inv],
rw [mul_comm, ←div_eq_mul_inv, div_zpow],
end
end alternating
lemma sum_map_mul_left [non_unital_non_assoc_semiring R] (L : list ι) (f : ι → R) (r : R) :
(L.map (λ b, r * f b)).sum = r * (L.map f).sum :=
sum_map_hom L f $ add_monoid_hom.mul_left r
lemma sum_map_mul_right [non_unital_non_assoc_semiring R] (L : list ι) (f : ι → R) (r : R) :
(L.map (λ b, f b * r)).sum = (L.map f).sum * r :=
sum_map_hom L f $ add_monoid_hom.mul_right r
end list
namespace mul_opposite
open list
variables [monoid M]
lemma op_list_prod : ∀ (l : list M), op (l.prod) = (l.map op).reverse.prod
| [] := rfl
| (x :: xs) := by rw [list.prod_cons, list.map_cons, list.reverse_cons', list.prod_concat, op_mul,
op_list_prod]
lemma _root_.mul_opposite.unop_list_prod (l : list Mᵐᵒᵖ) :
(l.prod).unop = (l.map unop).reverse.prod :=
by rw [← op_inj, op_unop, mul_opposite.op_list_prod, map_reverse, map_map, reverse_reverse,
op_comp_unop, map_id]
end mul_opposite
section monoid_hom
variables [monoid M] [monoid N]
/-- A morphism into the opposite monoid acts on the product by acting on the reversed elements. -/
lemma unop_map_list_prod {F : Type*} [monoid_hom_class F M Nᵐᵒᵖ] (f : F) (l : list M) :
(f l.prod).unop = (l.map (mul_opposite.unop ∘ f)).reverse.prod :=
by rw [map_list_prod f l, mul_opposite.unop_list_prod, list.map_map]
namespace monoid_hom
/-- A morphism into the opposite monoid acts on the product by acting on the reversed elements.
Deprecated, use `_root_.unop_map_list_prod` instead. -/
protected lemma unop_map_list_prod (f : M →* Nᵐᵒᵖ) (l : list M) :
(f l.prod).unop = (l.map (mul_opposite.unop ∘ f)).reverse.prod :=
unop_map_list_prod f l
end monoid_hom
end monoid_hom
|
58b4b5b7a2650fade242b827c6035f8c07264ae8 | 624f6f2ae8b3b1adc5f8f67a365c51d5126be45a | /stage0/src/Init/Lean/Util/FindExpr.lean | 1b143f850574007fbc66def3ac7df65ca9b24875 | [
"Apache-2.0"
] | permissive | mhuisi/lean4 | 28d35a4febc2e251c7f05492e13f3b05d6f9b7af | dda44bc47f3e5d024508060dac2bcb59fd12e4c0 | refs/heads/master | 1,621,225,489,283 | 1,585,142,689,000 | 1,585,142,689,000 | 250,590,438 | 0 | 2 | Apache-2.0 | 1,602,443,220,000 | 1,585,327,814,000 | C | UTF-8 | Lean | false | false | 2,086 | 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.Control.Option
import Init.Lean.Expr
namespace Lean
namespace Expr
namespace FindImpl
abbrev cacheSize : USize := 8192
structure State :=
(keys : Array Expr) -- Remark: our "unsafe" implementation relies on the fact that `()` is not a valid Expr
abbrev FindM := StateM State
@[inline] unsafe def visited (e : Expr) (size : USize) : FindM Bool := do
s ← get;
let h := ptrAddrUnsafe e;
let i := h % size;
let k := s.keys.uget i lcProof;
if ptrAddrUnsafe k == h then pure true
else do
modify $ fun s => { keys := s.keys.uset i e lcProof };
pure false
@[specialize] unsafe partial def findM? (p : Expr → Bool) (size : USize) : Expr → OptionT FindM Expr
| e => condM (liftM $ visited e size) failure $
if p e then pure e
else match e with
| Expr.forallE _ d b _ => findM? d <|> findM? b
| Expr.lam _ d b _ => findM? d <|> findM? b
| Expr.mdata _ b _ => findM? b
| Expr.letE _ t v b _ => findM? t <|> findM? v <|> findM? b
| Expr.app f a _ => findM? f <|> findM? a
| Expr.proj _ _ b _ => findM? b
| e => failure
unsafe def initCache : State :=
{ keys := mkArray cacheSize.toNat (cast lcProof ()) }
@[inline] unsafe def findUnsafe? (p : Expr → Bool) (e : Expr) : Option Expr :=
(findM? p cacheSize e).run' initCache
end FindImpl
@[implementedBy FindImpl.findUnsafe?]
partial def find? (p : Expr → Bool) : Expr → Option Expr
| e =>
/- This is a reference implementation for the unsafe one above -/
if p e then some e
else match e with
| Expr.forallE _ d b _ => find? d <|> find? b
| Expr.lam _ d b _ => find? d <|> find? b
| Expr.mdata _ b _ => find? b
| Expr.letE _ t v b _ => find? t <|> find? v <|> find? b
| Expr.app f a _ => find? f <|> find? a
| Expr.proj _ _ b _ => find? b
| e => none
end Expr
end Lean
|
acc3d85cb891edb812182b83274b1bc832bf9bbf | fa02ed5a3c9c0adee3c26887a16855e7841c668b | /src/topology/vector_bundle.lean | b272000b597270f498001efdc78bbf2e8a7ec135 | [
"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 | 17,838 | lean | /-
Copyright © 2020 Nicolò Cavalleri. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Nicolò Cavalleri, Sebastien Gouezel
-/
import topology.topological_fiber_bundle
import topology.algebra.module
/-!
# Topological vector bundles
In this file we define topological vector bundles.
Let `B` be the base space. In our formalism, a topological vector bundle is by definition the type
`bundle.total_space E` where `E : B → Type*` is a function associating to
`x : B` the fiber over `x`. This type `bundle.total_space E` is just a type synonym for
`Σ (x : B), E x`, with the interest that one can put another topology than on `Σ (x : B), E x`
which has the disjoint union topology.
To have a topological vector bundle structure on `bundle.total_space E`,
one should addtionally have the following data:
* `F` should be a topological space and a module over a semiring `R`;
* There should be a topology on `bundle.total_space E`, for which the projection to `B` is
a topological fiber bundle with fiber `F` (in particular, each fiber `E x` is homeomorphic to `F`);
* For each `x`, the fiber `E x` should be a topological vector space over `R`, and the injection
from `E x` to `bundle.total_space F E` should be an embedding;
* The most important condition: around each point, there should be a bundle trivialization which
is a continuous linear equiv in the fibers.
If all these conditions are satisfied, we register the typeclass
`topological_vector_bundle R F E`. We emphasize that the data is provided by other classes, and
that the `topological_vector_bundle` class is `Prop`-valued.
The point of this formalism is that it is unbundled in the sense that the total space of the bundle
is a type with a topology, with which one can work or put further structure, and still one can
perform operations on topological vector bundles (which are yet to be formalized). For instance,
assume that `E₁ : B → Type*` and `E₂ : B → Type*` define two topological vector bundles over `R`
with fiber models `F₁` and `F₂` which are normed spaces. Then one can construct the vector bundle of
continuous linear maps from `E₁ x` to `E₂ x` with fiber `E x := (E₁ x →L[R] E₂ x)` (and with the
topology inherited from the norm-topology on `F₁ →L[R] F₂`, without the need to define the strong
topology on continuous linear maps between general topological vector spaces). Let
`vector_bundle_continuous_linear_map R F₁ E₁ F₂ E₂ (x : B)` be a type synonym for `E₁ x →L[R] E₂ x`.
Then one can endow
`bundle.total_space (vector_bundle_continuous_linear_map R F₁ E₁ F₂ E₂)`
with a topology and a topological vector bundle structure.
Similar constructions can be done for tensor products of topological vector bundles, exterior
algebras, and so on, where the topology can be defined using a norm on the fiber model if this
helps.
-/
noncomputable theory
open bundle set
variables (R : Type*) {B : Type*} (F : Type*) (E : B → Type*)
[semiring R] [∀ x, add_comm_monoid (E x)] [∀ x, module R (E x)]
[topological_space F] [add_comm_monoid F] [module R F]
[topological_space (total_space E)] [topological_space B]
section
/-- Local trivialization for vector bundles. -/
@[nolint has_inhabited_instance]
structure topological_vector_bundle.trivialization extends bundle_trivialization F (proj E) :=
(linear : ∀ x ∈ base_set, is_linear_map R (λ y : (E x), (to_fun y).2))
instance : has_coe_to_fun (topological_vector_bundle.trivialization R F E) :=
⟨λ _, (total_space E → B × F), λ e, e.to_bundle_trivialization⟩
instance : has_coe (topological_vector_bundle.trivialization R F E)
(bundle_trivialization F (proj E)) :=
⟨topological_vector_bundle.trivialization.to_bundle_trivialization⟩
namespace topological_vector_bundle
variables {R F E}
lemma trivialization.mem_source (e : trivialization R F E)
{x : total_space E} : x ∈ e.source ↔ proj E x ∈ e.base_set := bundle_trivialization.mem_source e
@[simp, mfld_simps] lemma trivialization.coe_coe (e : trivialization R F E) :
⇑e.to_local_homeomorph = e := rfl
@[simp, mfld_simps] lemma trivialization.coe_fst
(e : trivialization R F E) {x : total_space E} (ex : x ∈ e.source) :
(e x).1 = (proj E) x :=
e.proj_to_fun x ex
end topological_vector_bundle
end
variables [∀ x, topological_space (E x)]
/-- The space `total_space E` (for `E : B → Type*` such that each `E x` is a topological vector
space) has a topological vector space structure with fiber `F` (denoted with
`topological_vector_bundle R F E`) if around every point there is a fiber bundle trivialization
which is linear in the fibers. -/
class topological_vector_bundle : Prop :=
(inducing [] : ∀ (b : B), inducing (λ x : (E b), (id ⟨b, x⟩ : total_space E)))
(locally_trivial [] : ∀ b : B, ∃ e : topological_vector_bundle.trivialization R F E, b ∈ e.base_set)
variable [topological_vector_bundle R F E]
namespace topological_vector_bundle
/-- `trivialization_at R F E b` is some choice of trivialization of a vector bundle whose base set
contains a given point `b`. -/
def trivialization_at : Π b : B, trivialization R F E :=
λ b, classical.some (topological_vector_bundle.locally_trivial R F E b)
@[simp, mfld_simps] lemma mem_base_set_trivialization_at (b : B) :
b ∈ (trivialization_at R F E b).base_set :=
classical.some_spec (topological_vector_bundle.locally_trivial R F E b)
@[simp, mfld_simps] lemma mem_source_trivialization_at (z : total_space E) :
z ∈ (trivialization_at R F E z.1).source :=
by { rw bundle_trivialization.mem_source, apply mem_base_set_trivialization_at }
variables {R F E}
/-- In a topological vector bundle, a trivialization in the fiber (which is a priori only linear)
is in fact a continuous linear equiv between the fibers and the model fiber. -/
def trivialization.continuous_linear_equiv_at (e : trivialization R F E) (b : B)
(hb : b ∈ e.base_set) : E b ≃L[R] F :=
{ to_fun := λ y, (e ⟨b, y⟩).2,
inv_fun := λ z, begin
have : ((e.to_local_homeomorph.symm) (b, z)).fst = b :=
bundle_trivialization.proj_symm_apply' _ hb,
have C : E ((e.to_local_homeomorph.symm) (b, z)).fst = E b, by rw this,
exact cast C (e.to_local_homeomorph.symm (b, z)).2
end,
left_inv := begin
assume v,
rw [← heq_iff_eq],
apply (cast_heq _ _).trans,
have A : (b, (e ⟨b, v⟩).snd) = e ⟨b, v⟩,
{ refine prod.ext _ rfl,
symmetry,
exact bundle_trivialization.coe_fst' _ hb },
have B : e.to_local_homeomorph.symm (e ⟨b, v⟩) = ⟨b, v⟩,
{ apply local_homeomorph.left_inv_on,
rw bundle_trivialization.mem_source,
exact hb },
rw [A, B],
end,
right_inv := begin
assume v,
have B : e (e.to_local_homeomorph.symm (b, v)) = (b, v),
{ apply local_homeomorph.right_inv_on,
rw bundle_trivialization.mem_target,
exact hb },
have C : (e (e.to_local_homeomorph.symm (b, v))).2 = v, by rw [B],
conv_rhs { rw ← C },
dsimp,
congr,
ext,
{ exact (bundle_trivialization.proj_symm_apply' _ hb).symm },
{ exact (cast_heq _ _).trans (by refl) },
end,
map_add' := λ v w, (e.linear _ hb).map_add v w,
map_smul' := λ c v, (e.linear _ hb).map_smul c v,
continuous_to_fun := begin
refine continuous_snd.comp _,
apply continuous_on.comp_continuous e.to_local_homeomorph.continuous_on
(topological_vector_bundle.inducing R F E b).continuous (λ x, _),
rw bundle_trivialization.mem_source,
exact hb,
end,
continuous_inv_fun := begin
rw (topological_vector_bundle.inducing R F E b).continuous_iff,
dsimp,
have : continuous (λ (z : F), (e.to_bundle_trivialization.to_local_homeomorph.symm) (b, z)),
{ apply e.to_local_homeomorph.symm.continuous_on.comp_continuous
(continuous_const.prod_mk continuous_id') (λ z, _),
simp only [bundle_trivialization.mem_target, hb, local_equiv.symm_source,
local_homeomorph.symm_to_local_equiv] },
convert this,
ext z,
{ exact (bundle_trivialization.proj_symm_apply' _ hb).symm },
{ exact cast_heq _ _ },
end }
@[simp] lemma trivialization.continuous_linear_equiv_at_apply (e : trivialization R F E) (b : B)
(hb : b ∈ e.base_set) (y : E b) : e.continuous_linear_equiv_at b hb y = (e ⟨b, y⟩).2 := rfl
@[simp] lemma trivialization.continuous_linear_equiv_at_apply' (e : trivialization R F E)
(x : total_space E) (hx : x ∈ e.source) :
e.continuous_linear_equiv_at (proj E x) (e.mem_source.1 hx) x.2 = (e x).2 :=
by { cases x, refl }
section
local attribute [reducible] bundle.trivial
instance {B : Type*} {F : Type*} [add_comm_monoid F] (b : B) :
add_comm_monoid (bundle.trivial B F b) := ‹add_comm_monoid F›
instance {B : Type*} {F : Type*} [add_comm_group F] (b : B) :
add_comm_group (bundle.trivial B F b) := ‹add_comm_group F›
instance {B : Type*} {F : Type*} [add_comm_monoid F] [module R F] (b : B) :
module R (bundle.trivial B F b) := ‹module R F›
end
variables (R B F)
/-- Local trivialization for trivial bundle. -/
def trivial_bundle_trivialization : trivialization R F (bundle.trivial B F) :=
{ to_fun := λ x, (x.fst, x.snd),
inv_fun := λ y, ⟨y.fst, y.snd⟩,
source := univ,
target := univ,
map_source' := λ x h, mem_univ (x.fst, x.snd),
map_target' :=λ y h, mem_univ ⟨y.fst, y.snd⟩,
left_inv' := λ x h, sigma.eq rfl rfl,
right_inv' := λ x h, prod.ext rfl rfl,
open_source := is_open_univ,
open_target := is_open_univ,
continuous_to_fun := by { rw [←continuous_iff_continuous_on_univ, continuous_iff_le_induced],
simp only [prod.topological_space, induced_inf, induced_compose], exact le_refl _, },
continuous_inv_fun := by { rw [←continuous_iff_continuous_on_univ, continuous_iff_le_induced],
simp only [bundle.total_space.topological_space, induced_inf, induced_compose],
exact le_refl _, },
base_set := univ,
open_base_set := is_open_univ,
source_eq := rfl,
target_eq := by simp only [univ_prod_univ],
proj_to_fun := λ y hy, rfl,
linear := λ x hx, ⟨λ y z, rfl, λ c y, rfl⟩ }
instance trivial_bundle.topological_vector_bundle :
topological_vector_bundle R F (bundle.trivial B F) :=
{ locally_trivial := λ x, ⟨trivial_bundle_trivialization R B F, mem_univ x⟩,
inducing := λ b, ⟨begin
have : (λ (x : trivial B F b), x) = @id F, by { ext x, refl },
simp only [total_space.topological_space, induced_inf, induced_compose, function.comp, proj,
induced_const, top_inf_eq, trivial.proj_snd, id.def, trivial.topological_space, this,
induced_id],
end⟩ }
variables {R B F}
/- Not registered as an instance because of a metavariable. -/
lemma is_topological_vector_bundle_is_topological_fiber_bundle :
is_topological_fiber_bundle F (proj E) :=
λ x, ⟨(trivialization_at R F E x).to_bundle_trivialization, mem_base_set_trivialization_at R F E x⟩
end topological_vector_bundle
/-! ### Constructing topological vector bundles -/
variables (B)
/-- Analogous construction of `topological_fiber_bundle_core` for vector bundles. This
construction gives a way to construct vector bundles from a structure registering how
trivialization changes act on fibers.-/
@[nolint has_inhabited_instance]
structure topological_vector_bundle_core (ι : Type*) :=
(base_set : ι → set B)
(is_open_base_set : ∀ i, is_open (base_set i))
(index_at : B → ι)
(mem_base_set_at : ∀ x, x ∈ base_set (index_at x))
(coord_change : ι → ι → B → (F →ₗ[R] F))
(coord_change_self : ∀ i, ∀ x ∈ base_set i, ∀ v, coord_change i i x v = v)
(coord_change_continuous : ∀ i j, continuous_on (λp : B × F, coord_change i j p.1 p.2)
(set.prod ((base_set i) ∩ (base_set j)) univ))
(coord_change_comp : ∀ i j k, ∀ x ∈ (base_set i) ∩ (base_set j) ∩ (base_set k), ∀ v,
(coord_change j k x) (coord_change i j x v) = coord_change i k x v)
attribute [simp, mfld_simps] topological_vector_bundle_core.mem_base_set_at
namespace topological_vector_bundle_core
variables {R B F} {ι : Type*} (Z : topological_vector_bundle_core R B F ι)
/-- Natural identification to a `topological_fiber_bundle_core`. -/
def to_topological_vector_bundle_core : topological_fiber_bundle_core ι B F :=
{ coord_change := λ i j b, Z.coord_change i j b, ..Z }
instance to_topological_vector_bundle_core_coe : has_coe (topological_vector_bundle_core R B F ι)
(topological_fiber_bundle_core ι B F) := ⟨to_topological_vector_bundle_core⟩
include Z
lemma coord_change_linear_comp (i j k : ι): ∀ x ∈ (Z.base_set i) ∩ (Z.base_set j) ∩ (Z.base_set k),
(Z.coord_change j k x).comp (Z.coord_change i j x) = Z.coord_change i k x :=
λ x hx, by { ext v, exact Z.coord_change_comp i j k x hx v }
/-- The index set of a topological vector bundle core, as a convenience function for dot notation -/
@[nolint unused_arguments has_inhabited_instance]
def index := ι
/-- The base space of a topological vector bundle core, as a convenience function for dot notation-/
@[nolint unused_arguments, reducible]
def base := B
/-- The fiber of a topological vector bundle core, as a convenience function for dot notation and
typeclass inference -/
@[nolint unused_arguments has_inhabited_instance]
def fiber (x : B) := F
section fiber_instances
local attribute [reducible] fiber --just to record instances
instance topological_space_fiber (x : B) : topological_space (Z.fiber x) := by apply_instance
instance add_comm_monoid_fiber : ∀ (x : B), add_comm_monoid (Z.fiber x) := λ x, by apply_instance
instance module_fiber : ∀ (x : B), module R (Z.fiber x) := λ x, by apply_instance
end fiber_instances
/-- The projection from the total space of a topological fiber bundle core, on its base. -/
@[reducible, simp, mfld_simps] def proj : total_space Z.fiber → B := bundle.proj Z.fiber
/-- Local homeomorphism version of the trivialization change. -/
def triv_change (i j : ι) : local_homeomorph (B × F) (B × F) :=
topological_fiber_bundle_core.triv_change ↑Z i j
@[simp, mfld_simps] lemma mem_triv_change_source (i j : ι) (p : B × F) :
p ∈ (Z.triv_change i j).source ↔ p.1 ∈ Z.base_set i ∩ Z.base_set j :=
topological_fiber_bundle_core.mem_triv_change_source ↑Z i j p
variable (ι)
/-- Topological structure on the total space of a topological bundle created from core, designed so
that all the local trivialization are continuous. -/
instance to_topological_space : topological_space (total_space Z.fiber) :=
topological_fiber_bundle_core.to_topological_space ι ↑Z
variables {ι} (b : B) (a : F)
@[simp, mfld_simps] lemma coe_cord_change (i j : ι) :
topological_fiber_bundle_core.coord_change ↑Z i j b = Z.coord_change i j b := rfl
/-- Extended version of the local trivialization of a fiber bundle constructed from core,
registering additionally in its type that it is a local bundle trivialization. -/
def local_triv (i : ι) : topological_vector_bundle.trivialization R F Z.fiber :=
{ linear := λ x hx, { map_add := λ v w, by simp only [topological_fiber_bundle_core.local_triv_ext,
local_homeomorph.to_fun_eq_coe, coe_fst, coe_snd_map_apply,
topological_fiber_bundle_core.local_triv_apply, linear_map.map_add, coe_cord_change],
map_smul := λ r v, by simp only [topological_fiber_bundle_core.local_triv_ext, coe_fst,
local_homeomorph.to_fun_eq_coe, topological_fiber_bundle_core.local_triv_apply, coe_cord_change,
coe_snd_map_smul, linear_map.map_smul] },
..topological_fiber_bundle_core.local_triv_ext ↑Z i }
@[simp, mfld_simps] lemma mem_local_triv_source (i : ι) (p : total_space Z.fiber) :
p ∈ (Z.local_triv i).source ↔ p.1 ∈ Z.base_set i :=
iff.rfl
/-- Preferred local trivialization of a vector bundle constructed from core, at a given point, as
a bundle trivialization -/
def local_triv_at (b : B) : topological_vector_bundle.trivialization R F Z.fiber :=
Z.local_triv (Z.index_at b)
lemma mem_source_at : (⟨b, a⟩ : total_space Z.fiber) ∈ (Z.local_triv_at b).source :=
by { rw [local_triv_at, mem_local_triv_source], exact Z.mem_base_set_at b }
@[simp, mfld_simps] lemma local_triv_at_apply : ((Z.local_triv_at b) ⟨b, a⟩) = ⟨b, a⟩ :=
topological_fiber_bundle_core.local_triv_at_apply Z b a
instance : topological_vector_bundle R F Z.fiber :=
{ inducing := λ b, ⟨ begin refine le_antisymm _ (λ s h, _),
{ rw ←continuous_iff_le_induced,
exact topological_fiber_bundle_core.continuous_total_space_mk ↑Z b, },
{ refine is_open_induced_iff.mpr ⟨(Z.local_triv_at b).source ∩ (Z.local_triv_at b) ⁻¹'
(Z.local_triv_at b).base_set.prod s, (continuous_on_open_iff
(Z.local_triv_at b).open_source).mp (Z.local_triv_at b).continuous_to_fun _
(is_open.prod (Z.local_triv_at b).open_base_set h), _⟩,
rw [preimage_inter, ←preimage_comp, function.comp],
simp only [id.def],
refine ext_iff.mpr (λ a, ⟨λ ha, _, λ ha, ⟨Z.mem_base_set_at b, _⟩⟩),
{ simp only [mem_prod, mem_preimage, mem_inter_eq, local_triv_at_apply] at ha,
exact ha.2.2, },
{ simp only [mem_prod, mem_preimage, mem_inter_eq, local_triv_at_apply],
exact ⟨Z.mem_base_set_at b, ha⟩, } } end⟩,
locally_trivial := λ b, ⟨Z.local_triv_at b, Z.mem_base_set_at b⟩, }
/-- The projection on the base of a topological vector bundle created from core is continuous -/
@[continuity] lemma continuous_proj : continuous Z.proj :=
topological_fiber_bundle_core.continuous_proj Z
/-- The projection on the base of a topological vector bundle created from core is an open map -/
lemma is_open_map_proj : is_open_map Z.proj :=
topological_fiber_bundle_core.is_open_map_proj Z
end topological_vector_bundle_core
|
7c5cd9de9b0843ee5f2906efdcf8070ba1d53f04 | 82e44445c70db0f03e30d7be725775f122d72f3e | /src/group_theory/perm/cycles.lean | 4658e5ed2ef7db3f829762a6885c3f536315c694 | [
"Apache-2.0"
] | permissive | stjordanis/mathlib | 51e286d19140e3788ef2c470bc7b953e4991f0c9 | 2568d41bca08f5d6bf39d915434c8447e21f42ee | refs/heads/master | 1,631,748,053,501 | 1,627,938,886,000 | 1,627,938,886,000 | 228,728,358 | 0 | 0 | Apache-2.0 | 1,576,630,588,000 | 1,576,630,587,000 | null | UTF-8 | Lean | false | false | 55,680 | lean | /-
Copyright (c) 2019 Chris Hughes. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Chris Hughes
-/
import data.nat.parity
import data.equiv.fintype
import group_theory.perm.sign
import data.finset.noncomm_prod
/-!
# Cyclic permutations
## Main definitions
In the following, `f : equiv.perm β`.
* `equiv.perm.is_cycle`: `f.is_cycle` when two nonfixed points of `β`
are related by repeated application of `f`.
* `equiv.perm.same_cycle`: `f.same_cycle x y` when `x` and `y` are in the same cycle of `f`.
The following two definitions require that `β` is a `fintype`:
* `equiv.perm.cycle_of`: `f.cycle_of x` is the cycle of `f` that `x` belongs to.
* `equiv.perm.cycle_factors`: `f.cycle_factors` is a list of disjoint cyclic permutations that
multiply to `f`.
## Main results
* This file contains several closure results:
- `closure_is_cycle` : The symmetric group is generated by cycles
- `closure_cycle_adjacent_swap` : The symmetric group is generated by
a cycle and an adjacent transposition
- `closure_cycle_coprime_swap` : The symmetric group is generated by
a cycle and a coprime transposition
- `closure_prime_cycle_swap` : The symmetric group is generated by
a prime cycle and a transposition
-/
namespace equiv.perm
open equiv function finset
variables {α : Type*} {β : Type*} [decidable_eq α]
section sign_cycle
/-!
### `is_cycle`
-/
variables [fintype α]
/-- A permutation is a cycle when any two nonfixed points of the permutation are related by repeated
application of the permutation. -/
def is_cycle (f : perm β) : Prop := ∃ x, f x ≠ x ∧ ∀ y, f y ≠ y → ∃ i : ℤ, (f ^ i) x = y
lemma is_cycle.ne_one {f : perm β} (h : is_cycle f) : f ≠ 1 :=
λ hf, by simpa [hf, is_cycle] using h
@[simp] lemma not_is_cycle_one : ¬ (1 : perm β).is_cycle :=
λ H, H.ne_one rfl
lemma is_cycle.two_le_card_support {f : perm α} (h : is_cycle f) :
2 ≤ f.support.card :=
two_le_card_support_of_ne_one h.ne_one
lemma is_cycle_swap {α : Type*} [decidable_eq α] {x y : α} (hxy : x ≠ y) : is_cycle (swap x y) :=
⟨y, by rwa swap_apply_right,
λ a (ha : ite (a = x) y (ite (a = y) x a) ≠ a),
if hya : y = a then ⟨0, hya⟩
else ⟨1, by { rw [gpow_one, swap_apply_def], split_ifs at *; cc }⟩⟩
lemma is_swap.is_cycle {α : Type*} [decidable_eq α] {f : perm α} (hf : is_swap f) : is_cycle f :=
begin
obtain ⟨x, y, hxy, rfl⟩ := hf,
exact is_cycle_swap hxy,
end
lemma is_cycle.inv {f : perm β} (hf : is_cycle f) : is_cycle (f⁻¹) :=
let ⟨x, hx⟩ := hf in
⟨x, by { simp only [inv_eq_iff_eq, *, forall_prop_of_true, ne.def] at *, cc },
λ y hy, let ⟨i, hi⟩ := hx.2 y (by { simp only [inv_eq_iff_eq, *, forall_prop_of_true,
ne.def] at *, cc }) in
⟨-i, by rwa [gpow_neg, inv_gpow, inv_inv]⟩⟩
lemma is_cycle.is_cycle_conj {f g : perm β} (hf : is_cycle f) : is_cycle (g * f * g⁻¹) :=
begin
obtain ⟨a, ha1, ha2⟩ := hf,
refine ⟨g a, by simp [ha1], λ b hb, _⟩,
obtain ⟨i, hi⟩ := ha2 (g⁻¹ b) _,
{ refine ⟨i, _⟩,
rw conj_gpow,
simp [hi] },
{ contrapose! hb,
rw [perm.mul_apply, perm.mul_apply, hb, apply_inv_self] }
end
lemma is_cycle.exists_gpow_eq {f : perm β} (hf : is_cycle f) {x y : β}
(hx : f x ≠ x) (hy : f y ≠ y) : ∃ i : ℤ, (f ^ i) x = y :=
let ⟨g, hg⟩ := hf in
let ⟨a, ha⟩ := hg.2 x hx in
let ⟨b, hb⟩ := hg.2 y hy in
⟨b - a, by rw [← ha, ← mul_apply, ← gpow_add, sub_add_cancel, hb]⟩
lemma is_cycle.exists_pow_eq [fintype β] {f : perm β} (hf : is_cycle f) {x y : β}
(hx : f x ≠ x) (hy : f y ≠ y) : ∃ i : ℕ, (f ^ i) x = y :=
let ⟨n, hn⟩ := hf.exists_gpow_eq hx hy in
by classical; exact ⟨(n % order_of f).to_nat, by {
have := n.mod_nonneg (int.coe_nat_ne_zero.mpr (ne_of_gt (order_of_pos f))),
rwa [← gpow_coe_nat, int.to_nat_of_nonneg this, ← gpow_eq_mod_order_of] }⟩
lemma is_cycle.exists_pow_eq_one [fintype β] {f : perm β} (hf : is_cycle f) :
∃ (k : ℕ) (hk : 1 < k), f ^ k = 1 :=
begin
classical,
have : is_of_fin_order f := exists_pow_eq_one f,
rw is_of_fin_order_iff_pow_eq_one at this,
obtain ⟨x, hx, hx'⟩ := hf,
obtain ⟨_ | _ | k, hk, hk'⟩ := this,
{ exact absurd hk (lt_asymm hk) },
{ rw pow_one at hk',
simpa [hk'] using hx },
{ exact ⟨k + 2, by simp, hk'⟩ }
end
/-- The subgroup generated by a cycle is in bijection with its support -/
noncomputable def is_cycle.gpowers_equiv_support {σ : perm α} (hσ : is_cycle σ) :
(↑(subgroup.gpowers σ) : set (perm α)) ≃ (↑(σ.support) : set α) :=
equiv.of_bijective (λ τ, ⟨τ (classical.some hσ),
begin
obtain ⟨τ, n, rfl⟩ := τ,
rw [finset.mem_coe, coe_fn_coe_base, subtype.coe_mk, gpow_apply_mem_support, mem_support],
exact (classical.some_spec hσ).1,
end⟩)
begin
split,
{ rintros ⟨a, m, rfl⟩ ⟨b, n, rfl⟩ h,
ext y,
by_cases hy : σ y = y,
{ simp_rw [subtype.coe_mk, gpow_apply_eq_self_of_apply_eq_self hy] },
{ obtain ⟨i, rfl⟩ := (classical.some_spec hσ).2 y hy,
rw [subtype.coe_mk, subtype.coe_mk, gpow_apply_comm σ m i, gpow_apply_comm σ n i],
exact congr_arg _ (subtype.ext_iff.mp h) } }, by
{ rintros ⟨y, hy⟩,
rw [finset.mem_coe, mem_support] at hy,
obtain ⟨n, rfl⟩ := (classical.some_spec hσ).2 y hy,
exact ⟨⟨σ ^ n, n, rfl⟩, rfl⟩ },
end
@[simp] lemma is_cycle.gpowers_equiv_support_apply {σ : perm α} (hσ : is_cycle σ) {n : ℕ} :
hσ.gpowers_equiv_support ⟨σ ^ n, n, rfl⟩ = ⟨(σ ^ n) (classical.some hσ),
pow_apply_mem_support.2 (mem_support.2 (classical.some_spec hσ).1)⟩ :=
rfl
@[simp] lemma is_cycle.gpowers_equiv_support_symm_apply {σ : perm α} (hσ : is_cycle σ) (n : ℕ) :
hσ.gpowers_equiv_support.symm ⟨(σ ^ n) (classical.some hσ),
pow_apply_mem_support.2 (mem_support.2 (classical.some_spec hσ).1)⟩ =
⟨σ ^ n, n, rfl⟩ :=
(equiv.symm_apply_eq _).2 hσ.gpowers_equiv_support_apply
lemma order_of_is_cycle {σ : perm α} (hσ : is_cycle σ) : order_of σ = σ.support.card :=
begin
rw [order_eq_card_gpowers, ←fintype.card_coe],
convert fintype.card_congr (is_cycle.gpowers_equiv_support hσ),
end
lemma is_cycle_swap_mul_aux₁ {α : Type*} [decidable_eq α] : ∀ (n : ℕ) {b x : α} {f : perm α}
(hb : (swap x (f x) * f) b ≠ b) (h : (f ^ n) (f x) = b),
∃ i : ℤ, ((swap x (f x) * f) ^ i) (f x) = b
| 0 := λ b x f hb h, ⟨0, h⟩
| (n+1 : ℕ) := λ b x f hb h,
if hfbx : f x = b then ⟨0, hfbx⟩
else
have f b ≠ b ∧ b ≠ x, from ne_and_ne_of_swap_mul_apply_ne_self hb,
have hb' : (swap x (f x) * f) (f⁻¹ b) ≠ f⁻¹ b,
by { rw [mul_apply, apply_inv_self, swap_apply_of_ne_of_ne this.2 (ne.symm hfbx),
ne.def, ← f.injective.eq_iff, apply_inv_self],
exact this.1 },
let ⟨i, hi⟩ := is_cycle_swap_mul_aux₁ n hb'
(f.injective $ by { rw [apply_inv_self], rwa [pow_succ, mul_apply] at h }) in
⟨i + 1, by rw [add_comm, gpow_add, mul_apply, hi, gpow_one, mul_apply, apply_inv_self,
swap_apply_of_ne_of_ne (ne_and_ne_of_swap_mul_apply_ne_self hb).2 (ne.symm hfbx)]⟩
lemma is_cycle_swap_mul_aux₂ {α : Type*} [decidable_eq α] :
∀ (n : ℤ) {b x : α} {f : perm α} (hb : (swap x (f x) * f) b ≠ b) (h : (f ^ n) (f x) = b),
∃ i : ℤ, ((swap x (f x) * f) ^ i) (f x) = b
| (n : ℕ) := λ b x f, is_cycle_swap_mul_aux₁ n
| -[1+ n] := λ b x f hb h,
if hfbx : f⁻¹ x = b then
⟨-1, by rwa [gpow_neg, gpow_one, mul_inv_rev, mul_apply, swap_inv, swap_apply_right]⟩
else if hfbx' : f x = b then ⟨0, hfbx'⟩
else
have f b ≠ b ∧ b ≠ x := ne_and_ne_of_swap_mul_apply_ne_self hb,
have hb : (swap x (f⁻¹ x) * f⁻¹) (f⁻¹ b) ≠ f⁻¹ b,
by { rw [mul_apply, swap_apply_def],
split_ifs;
simp only [inv_eq_iff_eq, perm.mul_apply, gpow_neg_succ_of_nat, ne.def,
perm.apply_inv_self] at *;
cc },
let ⟨i, hi⟩ := is_cycle_swap_mul_aux₁ n hb
(show (f⁻¹ ^ n) (f⁻¹ x) = f⁻¹ b, by
rw [← gpow_coe_nat, ← h, ← mul_apply, ← mul_apply, ← mul_apply, gpow_neg_succ_of_nat,
← inv_pow, pow_succ', mul_assoc, mul_assoc, inv_mul_self, mul_one, gpow_coe_nat,
← pow_succ', ← pow_succ]) in
have h : (swap x (f⁻¹ x) * f⁻¹) (f x) = f⁻¹ x, by rw [mul_apply, inv_apply_self, swap_apply_left],
⟨-i, by rw [← add_sub_cancel i 1, neg_sub, sub_eq_add_neg, gpow_add, gpow_one, gpow_neg,
← inv_gpow, mul_inv_rev, swap_inv, mul_swap_eq_swap_mul, inv_apply_self, swap_comm _ x,
gpow_add, gpow_one, mul_apply, mul_apply (_ ^ i), h, hi, mul_apply, apply_inv_self,
swap_apply_of_ne_of_ne this.2 (ne.symm hfbx')]⟩
lemma is_cycle.eq_swap_of_apply_apply_eq_self {α : Type*} [decidable_eq α]
{f : perm α} (hf : is_cycle f) {x : α}
(hfx : f x ≠ x) (hffx : f (f x) = x) : f = swap x (f x) :=
equiv.ext $ λ y,
let ⟨z, hz⟩ := hf in
let ⟨i, hi⟩ := hz.2 x hfx in
if hyx : y = x then by simp [hyx]
else if hfyx : y = f x then by simp [hfyx, hffx]
else begin
rw [swap_apply_of_ne_of_ne hyx hfyx],
refine by_contradiction (λ hy, _),
cases hz.2 y hy with j hj,
rw [← sub_add_cancel j i, gpow_add, mul_apply, hi] at hj,
cases gpow_apply_eq_of_apply_apply_eq_self hffx (j - i) with hji hji,
{ rw [← hj, hji] at hyx, cc },
{ rw [← hj, hji] at hfyx, cc }
end
lemma is_cycle.swap_mul {α : Type*} [decidable_eq α] {f : perm α} (hf : is_cycle f) {x : α}
(hx : f x ≠ x) (hffx : f (f x) ≠ x) : is_cycle (swap x (f x) * f) :=
⟨f x, by { simp only [swap_apply_def, mul_apply],
split_ifs; simp [f.injective.eq_iff] at *; cc },
λ y hy,
let ⟨i, hi⟩ := hf.exists_gpow_eq hx (ne_and_ne_of_swap_mul_apply_ne_self hy).1 in
have hi : (f ^ (i - 1)) (f x) = y, from
calc (f ^ (i - 1)) (f x) = (f ^ (i - 1) * f ^ (1 : ℤ)) x : by rw [gpow_one, mul_apply]
... = y : by rwa [← gpow_add, sub_add_cancel],
is_cycle_swap_mul_aux₂ (i - 1) hy hi⟩
lemma is_cycle.sign : ∀ {f : perm α} (hf : is_cycle f),
sign f = -(-1) ^ f.support.card
| f := λ hf,
let ⟨x, hx⟩ := hf in
calc sign f = sign (swap x (f x) * (swap x (f x) * f)) :
by rw [← mul_assoc, mul_def, mul_def, swap_swap, trans_refl]
... = -(-1) ^ f.support.card :
if h1 : f (f x) = x
then
have h : swap x (f x) * f = 1,
begin
rw hf.eq_swap_of_apply_apply_eq_self hx.1 h1,
simp only [perm.mul_def, perm.one_def, swap_apply_left, swap_swap]
end,
by { rw [sign_mul, sign_swap hx.1.symm, h, sign_one, hf.eq_swap_of_apply_apply_eq_self hx.1 h1,
card_support_swap hx.1.symm], refl }
else
have h : card (support (swap x (f x) * f)) + 1 = card (support f),
by rw [← insert_erase (mem_support.2 hx.1), support_swap_mul_eq _ _ h1,
card_insert_of_not_mem (not_mem_erase _ _), sdiff_singleton_eq_erase],
have wf : card (support (swap x (f x) * f)) < card (support f),
from card_support_swap_mul hx.1,
by { rw [sign_mul, sign_swap hx.1.symm, (hf.swap_mul hx.1 h1).sign, ← h],
simp only [pow_add, mul_one, units.neg_neg, one_mul, units.mul_neg, eq_self_iff_true,
pow_one, units.neg_mul_neg] }
using_well_founded {rel_tac := λ _ _, `[exact ⟨_, measure_wf (λ f, f.support.card)⟩]}
lemma is_cycle_of_is_cycle_pow {σ : perm α} {n : ℕ}
(h1 : is_cycle (σ ^ n)) (h2 : σ.support ≤ (σ ^ n).support) : is_cycle σ :=
begin
have key : ∀ x : α, (σ ^ n) x ≠ x ↔ σ x ≠ x,
{ simp_rw [←mem_support],
exact finset.ext_iff.mp (le_antisymm (support_pow_le σ n) h2) },
obtain ⟨x, hx1, hx2⟩ := h1,
refine ⟨x, (key x).mp hx1, λ y hy, _⟩,
cases (hx2 y ((key y).mpr hy)) with i _,
exact ⟨n * i, by rwa gpow_mul⟩
end
-- The lemma `support_gpow_le` is relevant. It means that `h2` is equivalent to
-- `σ.support = (σ ^ n).support`, as well as to `σ.support.card ≤ (σ ^ n).support.card`.
lemma is_cycle_of_is_cycle_gpow {σ : perm α} {n : ℤ}
(h1 : is_cycle (σ ^ n)) (h2 : σ.support ≤ (σ ^ n).support) : is_cycle σ :=
begin
cases n,
{ exact is_cycle_of_is_cycle_pow h1 h2 },
{ simp only [le_eq_subset, gpow_neg_succ_of_nat, perm.support_inv] at h1 h2,
simpa using is_cycle_of_is_cycle_pow h1.inv h2 }
end
lemma is_cycle.extend_domain {α : Type*} {p : β → Prop} [decidable_pred p]
(f : α ≃ subtype p) {g : perm α} (h : is_cycle g) :
is_cycle (g.extend_domain f) :=
begin
obtain ⟨a, ha, ha'⟩ := h,
refine ⟨f a, _, λ b hb, _⟩,
{ rw extend_domain_apply_image,
exact λ con, ha (f.injective (subtype.coe_injective con)) },
by_cases pb : p b,
{ obtain ⟨i, hi⟩ := ha' (f.symm ⟨b, pb⟩) (λ con, hb _),
{ refine ⟨i, _⟩,
have hnat : ∀ (k : ℕ) (a : α), (g.extend_domain f ^ k) ↑(f a) = f ((g ^ k) a),
{ intros k a,
induction k with k ih, { refl },
rw [pow_succ, perm.mul_apply, ih, extend_domain_apply_image, pow_succ, perm.mul_apply] },
have hint : ∀ (k : ℤ) (a : α), (g.extend_domain f ^ k) ↑(f a) = f ((g ^ k) a),
{ intros k a,
induction k with k k,
{ rw [gpow_of_nat, gpow_of_nat, hnat] },
rw [gpow_neg_succ_of_nat, gpow_neg_succ_of_nat, inv_eq_iff_eq, hnat, apply_inv_self] },
rw [hint, hi, apply_symm_apply, subtype.coe_mk] },
{ rw [extend_domain_apply_subtype _ _ pb, con, apply_symm_apply, subtype.coe_mk] } },
{ exact (hb (extend_domain_apply_not_subtype _ _ pb)).elim }
end
lemma nodup_of_pairwise_disjoint_cycles {l : list (perm β)} (h1 : ∀ f ∈ l, is_cycle f)
(h2 : l.pairwise disjoint) : l.nodup :=
nodup_of_pairwise_disjoint (λ h, (h1 1 h).ne_one rfl) h2
end sign_cycle
/-!
### `same_cycle`
-/
/-- The equivalence relation indicating that two points are in the same cycle of a permutation. -/
def same_cycle (f : perm β) (x y : β) : Prop := ∃ i : ℤ, (f ^ i) x = y
@[refl] lemma same_cycle.refl (f : perm β) (x : β) : same_cycle f x x := ⟨0, rfl⟩
@[symm] lemma same_cycle.symm (f : perm β) {x y : β} : same_cycle f x y → same_cycle f y x :=
λ ⟨i, hi⟩, ⟨-i, by rw [gpow_neg, ← hi, inv_apply_self]⟩
@[trans] lemma same_cycle.trans (f : perm β) {x y z : β} :
same_cycle f x y → same_cycle f y z → same_cycle f x z :=
λ ⟨i, hi⟩ ⟨j, hj⟩, ⟨j + i, by rw [gpow_add, mul_apply, hi, hj]⟩
lemma same_cycle.apply_eq_self_iff {f : perm β} {x y : β} :
same_cycle f x y → (f x = x ↔ f y = y) :=
λ ⟨i, hi⟩, by rw [← hi, ← mul_apply, ← gpow_one_add, add_comm, gpow_add_one, mul_apply,
(f ^ i).injective.eq_iff]
lemma is_cycle.same_cycle {f : perm β} (hf : is_cycle f) {x y : β}
(hx : f x ≠ x) (hy : f y ≠ y) : same_cycle f x y :=
hf.exists_gpow_eq hx hy
lemma same_cycle.nat' [fintype β] {f : perm β} {x y : β} (h : same_cycle f x y) :
∃ (i : ℕ) (h : i < order_of f), (f ^ i) x = y :=
begin
classical,
obtain ⟨k, rfl⟩ := id h,
by_cases hk : (k % order_of f) = 0,
{ use 0,
rw ←int.dvd_iff_mod_eq_zero at hk,
obtain ⟨m, rfl⟩ := hk,
simp [pow_order_of_eq_one, order_of_pos, gpow_mul] },
{ use ((k % order_of f).nat_abs),
rw [←gpow_coe_nat, int.nat_abs_of_nonneg, ←gpow_eq_mod_order_of],
{ refine ⟨_, rfl⟩,
rw [←int.coe_nat_lt, int.nat_abs_of_nonneg],
{ refine (int.mod_lt_of_pos _ _),
simpa using order_of_pos _ },
{ refine int.mod_nonneg _ _,
simpa using ne_of_gt (order_of_pos _) } },
{ refine int.mod_nonneg _ _,
simpa using (order_of_pos _).ne' } }
end
lemma same_cycle.nat'' [fintype β] {f : perm β} {x y : β} (h : same_cycle f x y) :
∃ (i : ℕ) (hpos : 0 < i) (h : i ≤ order_of f), (f ^ i) x = y :=
begin
classical,
obtain ⟨_|i, hi, rfl⟩ := h.nat',
{ refine ⟨order_of f, order_of_pos f, le_rfl, _⟩,
rw [pow_order_of_eq_one, pow_zero] },
{ exact ⟨i.succ, i.zero_lt_succ, hi.le, rfl⟩ }
end
instance [fintype α] (f : perm α) : decidable_rel (same_cycle f) :=
λ x y, decidable_of_iff (∃ n ∈ list.range (fintype.card (perm α)), (f ^ n) x = y)
⟨λ ⟨n, _, hn⟩, ⟨n, hn⟩, λ ⟨i, hi⟩, ⟨(i % order_of f).nat_abs, list.mem_range.2
(int.coe_nat_lt.1 $
by { rw int.nat_abs_of_nonneg (int.mod_nonneg _
(int.coe_nat_ne_zero_iff_pos.2 (order_of_pos _))),
{ apply lt_of_lt_of_le (int.mod_lt _ (int.coe_nat_ne_zero_iff_pos.2 (order_of_pos _))),
{ simp [order_of_le_card_univ] },
exact fintype_perm },
exact fintype_perm, }),
by { rw [← gpow_coe_nat, int.nat_abs_of_nonneg (int.mod_nonneg _
(int.coe_nat_ne_zero_iff_pos.2 (order_of_pos _))), ← gpow_eq_mod_order_of, hi],
exact fintype_perm }⟩⟩
lemma same_cycle_apply {f : perm β} {x y : β} : same_cycle f x (f y) ↔ same_cycle f x y :=
⟨λ ⟨i, hi⟩, ⟨-1 + i, by rw [gpow_add, mul_apply, hi, gpow_neg_one, inv_apply_self]⟩,
λ ⟨i, hi⟩, ⟨1 + i, by rw [gpow_add, mul_apply, hi, gpow_one]⟩⟩
lemma same_cycle_cycle {f : perm β} {x : β} (hx : f x ≠ x) : is_cycle f ↔
(∀ {y}, same_cycle f x y ↔ f y ≠ y) :=
⟨λ hf y, ⟨λ ⟨i, hi⟩ hy, hx $
by { rw [← gpow_apply_eq_self_of_apply_eq_self hy i, (f ^ i).injective.eq_iff] at hi,
rw [hi, hy] },
hf.exists_gpow_eq hx⟩,
λ h, ⟨x, hx, λ y hy, h.2 hy⟩⟩
lemma same_cycle_inv (f : perm β) {x y : β} : same_cycle f⁻¹ x y ↔ same_cycle f x y :=
⟨λ ⟨i, hi⟩, ⟨-i, by rw [gpow_neg, ← inv_gpow, hi]⟩,
λ ⟨i, hi⟩, ⟨-i, by rw [gpow_neg, ← inv_gpow, inv_inv, hi]⟩ ⟩
lemma same_cycle_inv_apply {f : perm β} {x y : β} : same_cycle f x (f⁻¹ y) ↔ same_cycle f x y :=
by rw [← same_cycle_inv, same_cycle_apply, same_cycle_inv]
@[simp] lemma same_cycle_pow_left_iff {f : perm β} {x y : β} {n : ℕ} :
same_cycle f ((f ^ n) x) y ↔ same_cycle f x y :=
begin
split,
{ rintro ⟨k, rfl⟩,
use (k + n),
simp [gpow_add] },
{ rintro ⟨k, rfl⟩,
use (k - n),
rw [←gpow_coe_nat, ←mul_apply, ←gpow_add, int.sub_add_cancel] }
end
/-- Unlike `support_congr`, which assumes that `∀ (x ∈ g.support), f x = g x)`, here
we have the weaker assumption that `∀ (x ∈ f.support), f x = g x`. -/
lemma is_cycle.support_congr [fintype α] {f g : perm α} (hf : is_cycle f) (hg : is_cycle g)
(h : f.support ⊆ g.support) (h' : ∀ (x ∈ f.support), f x = g x) : f = g :=
begin
have : f.support = g.support,
{ refine le_antisymm h _,
intros z hz,
obtain ⟨x, hx, hf'⟩ := id hf,
have hx' : g x ≠ x,
{ rwa [←h' x (mem_support.mpr hx)] },
obtain ⟨m, hm⟩ := hg.exists_pow_eq hx' (mem_support.mp hz),
have h'' : ∀ (x ∈ f.support ∩ g.support), f x = g x,
{ intros x hx,
exact h' x (mem_of_mem_inter_left hx) },
rwa [←hm, ←pow_eq_on_of_mem_support h'' _ x (mem_inter_of_mem (mem_support.mpr hx)
(mem_support.mpr hx')), pow_apply_mem_support, mem_support] },
refine support_congr h _,
simpa [←this] using h'
end
/-- If two cyclic permutations agree on all terms in their intersection,
and that intersection is not empty, then the two cyclic permutations must be equal. -/
lemma is_cycle.eq_on_support_inter_nonempty_congr [fintype α] {f g : perm α}
(hf : is_cycle f) (hg : is_cycle g) (h : ∀ (x ∈ f.support ∩ g.support), f x = g x) {x : α}
(hx : f x = g x) (hx' : x ∈ f.support) : f = g :=
begin
have hx'' : x ∈ g.support,
{ rwa [mem_support, ←hx, ←mem_support] },
have : f.support ⊆ g.support,
{ intros y hy,
obtain ⟨k, rfl⟩ := hf.exists_pow_eq (mem_support.mp hx') (mem_support.mp hy),
rwa [pow_eq_on_of_mem_support h _ _ (mem_inter_of_mem hx' hx''), pow_apply_mem_support] },
rw (inter_eq_left_iff_subset _ _).mpr this at h,
exact hf.support_congr hg this h
end
lemma is_cycle.support_pow_eq_iff [fintype α] {f : perm α} (hf : is_cycle f) {n : ℕ} :
support (f ^ n) = support f ↔ ¬ order_of f ∣ n :=
begin
rw order_of_dvd_iff_pow_eq_one,
split,
{ intros h H,
refine hf.ne_one _,
rw [←support_eq_empty_iff, ←h, H, support_one] },
{ intro H,
apply le_antisymm (support_pow_le _ n) _,
intros x hx,
contrapose! H,
ext z,
by_cases hz : f z = z,
{ rw [pow_apply_eq_self_of_apply_eq_self hz, one_apply] },
{ obtain ⟨k, rfl⟩ := hf.exists_pow_eq hz (mem_support.mp hx),
apply (f ^ k).injective,
rw [←mul_apply, (commute.pow_pow_self _ _ _).eq, mul_apply],
simpa using H } }
end
lemma is_cycle.pow_iff [fintype β] {f : perm β} (hf : is_cycle f) {n : ℕ} :
is_cycle (f ^ n) ↔ n.coprime (order_of f) :=
begin
classical,
split,
{ intro h,
have hr : support (f ^ n) = support f,
{ rw hf.support_pow_eq_iff,
rintro ⟨k, rfl⟩,
refine h.ne_one _,
simp [pow_mul, pow_order_of_eq_one] },
have : order_of (f ^ n) = order_of f,
{ rw [order_of_is_cycle h, hr, order_of_is_cycle hf] },
rw [order_of_pow, nat.div_eq_self] at this,
cases this,
{ exact absurd this (order_of_pos _).ne' },
{ rwa [nat.coprime_iff_gcd_eq_one, nat.gcd_comm] } },
{ intro h,
obtain ⟨m, hm⟩ := exists_pow_eq_self_of_coprime h,
have hf' : is_cycle ((f ^ n) ^ m) := by rwa hm,
refine is_cycle_of_is_cycle_pow hf' _,
intros x hx,
rw [hm],
exact support_pow_le _ n hx }
end
lemma is_cycle.pow_eq_one_iff [fintype α] {f : perm α} (hf : is_cycle f) {n : ℕ} :
f ^ n = 1 ↔ ∃ (x ∈ f.support), (f ^ n) x = x :=
begin
split,
{ intro h,
obtain ⟨x, hx, -⟩ := id hf,
exact ⟨x, mem_support.mpr hx, by simp [h]⟩ },
{ rintro ⟨x, hx, hx'⟩,
by_cases h : support (f ^ n) = support f,
{ rw [←h, mem_support] at hx,
contradiction },
{ rw [hf.support_pow_eq_iff, not_not] at h,
obtain ⟨k, rfl⟩ := h,
rw [pow_mul, pow_order_of_eq_one, one_pow] } }
end
lemma is_cycle.mem_support_pos_pow_iff_of_lt_order_of [fintype α] {f : perm α} (hf : is_cycle f)
{n : ℕ} (npos : 0 < n) (hn : n < order_of f) {x : α} :
x ∈ (f ^ n).support ↔ x ∈ f.support :=
begin
have : ¬ order_of f ∣ n := nat.not_dvd_of_pos_of_lt npos hn,
rw ←hf.support_pow_eq_iff at this,
rw this
end
lemma is_cycle.is_cycle_pow_pos_of_lt_prime_order [fintype β] {f : perm β} (hf : is_cycle f)
(hf' : (order_of f).prime) (n : ℕ) (hn : 0 < n) (hn' : n < order_of f) : is_cycle (f ^ n) :=
begin
classical,
have : n.coprime (order_of f),
{ refine nat.coprime.symm _,
rw nat.prime.coprime_iff_not_dvd hf',
exact nat.not_dvd_of_pos_of_lt hn hn' },
obtain ⟨m, hm⟩ := exists_pow_eq_self_of_coprime this,
have hf'' := hf,
rw ←hm at hf'',
refine is_cycle_of_is_cycle_pow hf'' _,
rw [hm],
exact support_pow_le f n
end
/-!
### `cycle_of`
-/
/-- `f.cycle_of x` is the cycle of the permutation `f` to which `x` belongs. -/
def cycle_of [fintype α] (f : perm α) (x : α) : perm α :=
of_subtype (@subtype_perm _ f (same_cycle f x) (λ _, same_cycle_apply.symm))
lemma cycle_of_apply [fintype α] (f : perm α) (x y : α) :
cycle_of f x y = if same_cycle f x y then f y else y := rfl
lemma cycle_of_inv [fintype α] (f : perm α) (x : α) :
(cycle_of f x)⁻¹ = cycle_of f⁻¹ x :=
equiv.ext $ λ y, begin
rw [inv_eq_iff_eq, cycle_of_apply, cycle_of_apply],
split_ifs; simp [*, same_cycle_inv, same_cycle_inv_apply] at *
end
@[simp] lemma cycle_of_pow_apply_self [fintype α] (f : perm α) (x : α) :
∀ n : ℕ, (cycle_of f x ^ n) x = (f ^ n) x
| 0 := rfl
| (n+1) := by { rw [pow_succ, mul_apply, cycle_of_apply,
cycle_of_pow_apply_self, if_pos, pow_succ, mul_apply],
exact ⟨n, rfl⟩ }
@[simp] lemma cycle_of_gpow_apply_self [fintype α] (f : perm α) (x : α) :
∀ n : ℤ, (cycle_of f x ^ n) x = (f ^ n) x
| (n : ℕ) := cycle_of_pow_apply_self f x n
| -[1+ n] := by rw [gpow_neg_succ_of_nat, ← inv_pow, cycle_of_inv,
gpow_neg_succ_of_nat, ← inv_pow, cycle_of_pow_apply_self]
lemma same_cycle.cycle_of_apply [fintype α] {f : perm α} {x y : α} (h : same_cycle f x y) :
cycle_of f x y = f y := dif_pos h
lemma cycle_of_apply_of_not_same_cycle [fintype α] {f : perm α} {x y : α} (h : ¬same_cycle f x y) :
cycle_of f x y = y := dif_neg h
@[simp] lemma cycle_of_apply_apply_gpow_self [fintype α] (f : perm α) (x : α) (k : ℤ) :
cycle_of f x ((f ^ k) x) = (f ^ (k + 1)) x :=
begin
rw same_cycle.cycle_of_apply,
{ rw [add_comm, gpow_add, gpow_one, mul_apply] },
{ exact ⟨k, rfl⟩ }
end
@[simp] lemma cycle_of_apply_apply_pow_self [fintype α] (f : perm α) (x : α) (k : ℕ) :
cycle_of f x ((f ^ k) x) = (f ^ (k + 1)) x :=
by convert cycle_of_apply_apply_gpow_self f x k using 1
@[simp] lemma cycle_of_apply_apply_self [fintype α] (f : perm α) (x : α) :
cycle_of f x (f x) = f (f x) :=
by convert cycle_of_apply_apply_pow_self f x 1 using 1
@[simp] lemma cycle_of_apply_self [fintype α] (f : perm α) (x : α) :
cycle_of f x x = f x := (same_cycle.refl _ _).cycle_of_apply
lemma is_cycle.cycle_of_eq [fintype α] {f : perm α} (hf : is_cycle f) {x : α} (hx : f x ≠ x) :
cycle_of f x = f :=
equiv.ext $ λ y,
if h : same_cycle f x y then by rw [h.cycle_of_apply]
else by rw [cycle_of_apply_of_not_same_cycle h, not_not.1 (mt ((same_cycle_cycle hx).1 hf).2 h)]
@[simp] lemma cycle_of_eq_one_iff [fintype α] (f : perm α) {x : α} : cycle_of f x = 1 ↔ f x = x :=
begin
simp_rw [ext_iff, cycle_of_apply, one_apply],
refine ⟨λ h, (if_pos (same_cycle.refl f x)).symm.trans (h x), λ h y, _⟩,
by_cases hy : f y = y,
{ rw [hy, if_t_t] },
{ exact if_neg (mt same_cycle.apply_eq_self_iff (by tauto)) },
end
lemma is_cycle.cycle_of [fintype α] {f : perm α} (hf : is_cycle f) {x : α} :
cycle_of f x = if f x = x then 1 else f :=
begin
by_cases hx : f x = x,
{ rwa [if_pos hx, cycle_of_eq_one_iff] },
{ rwa [if_neg hx, hf.cycle_of_eq] },
end
lemma cycle_of_one [fintype α] (x : α) : cycle_of 1 x = 1 :=
(cycle_of_eq_one_iff 1).mpr rfl
lemma is_cycle_cycle_of [fintype α] (f : perm α) {x : α} (hx : f x ≠ x) : is_cycle (cycle_of f x) :=
have cycle_of f x x ≠ x, by rwa [(same_cycle.refl _ _).cycle_of_apply],
(same_cycle_cycle this).2 $ λ y,
⟨λ h, mt h.apply_eq_self_iff.2 this,
λ h, if hxy : same_cycle f x y then
let ⟨i, hi⟩ := hxy in
⟨i, by rw [cycle_of_gpow_apply_self, hi]⟩
else by { rw [cycle_of_apply_of_not_same_cycle hxy] at h, exact (h rfl).elim }⟩
lemma pow_apply_eq_pow_mod_order_of_cycle_of_apply [fintype α] (f : perm α) (n : ℕ) (x : α) :
(f ^ n) x = (f ^ (n % order_of (cycle_of f x))) x :=
by rw [←cycle_of_pow_apply_self f, ←cycle_of_pow_apply_self f, pow_eq_mod_order_of]
lemma cycle_of_mul_of_apply_right_eq_self [fintype α] {f g : perm α}
(h : _root_.commute f g) (x : α) (hx : g x = x) : (f * g).cycle_of x = f.cycle_of x :=
begin
ext y,
by_cases hxy : (f * g).same_cycle x y,
{ obtain ⟨z, rfl⟩ := hxy,
rw cycle_of_apply_apply_gpow_self,
simp [h.mul_gpow, gpow_apply_eq_self_of_apply_eq_self hx] },
{ rw [cycle_of_apply_of_not_same_cycle hxy, cycle_of_apply_of_not_same_cycle],
contrapose! hxy,
obtain ⟨z, rfl⟩ := hxy,
refine ⟨z, _⟩,
simp [h.mul_gpow, gpow_apply_eq_self_of_apply_eq_self hx] }
end
lemma disjoint.cycle_of_mul_distrib [fintype α] {f g : perm α} (h : f.disjoint g) (x : α) :
(f * g).cycle_of x = (f.cycle_of x * g.cycle_of x) :=
begin
cases (disjoint_iff_eq_or_eq.mp h) x with hfx hgx,
{ simp [h.commute.eq, cycle_of_mul_of_apply_right_eq_self h.symm.commute, hfx] },
{ simp [cycle_of_mul_of_apply_right_eq_self h.commute, hgx] }
end
lemma support_cycle_of_eq_nil_iff [fintype α] {f : perm α} {x : α} :
(f.cycle_of x).support = ∅ ↔ x ∉ f.support :=
by simp
lemma mem_support_cycle_of_iff [fintype α] {f : perm α} {x y : α} :
y ∈ support (f.cycle_of x) ↔ same_cycle f x y ∧ x ∈ support f :=
begin
by_cases hx : f x = x,
{ rw (cycle_of_eq_one_iff _).mpr hx,
simp [hx] },
{ rw [mem_support, cycle_of_apply],
split_ifs with hy,
{ simp only [hx, hy, iff_true, ne.def, not_false_iff, and_self, mem_support],
rcases hy with ⟨k, rfl⟩,
rw ←not_mem_support,
simpa using hx },
{ simpa [hx] using hy } }
end
/-!
### `cycle_factors`
-/
/-- Given a list `l : list α` and a permutation `f : perm α` whose nonfixed points are all in `l`,
recursively factors `f` into cycles. -/
def cycle_factors_aux [fintype α] : Π (l : list α) (f : perm α),
(∀ {x}, f x ≠ x → x ∈ l) →
{l : list (perm α) // l.prod = f ∧ (∀ g ∈ l, is_cycle g) ∧ l.pairwise disjoint}
| [] f h := ⟨[], by { simp only [imp_false, list.pairwise.nil, list.not_mem_nil, forall_const,
and_true, forall_prop_of_false, not_not, not_false_iff, list.prod_nil] at *,
ext, simp * }⟩
| (x::l) f h :=
if hx : f x = x then
cycle_factors_aux l f (λ y hy, list.mem_of_ne_of_mem (λ h, hy (by rwa h)) (h hy))
else let ⟨m, hm₁, hm₂, hm₃⟩ := cycle_factors_aux l ((cycle_of f x)⁻¹ * f)
(λ y hy, list.mem_of_ne_of_mem
(λ h : y = x,
by { rw [h, mul_apply, ne.def, inv_eq_iff_eq, cycle_of_apply_self] at hy, exact hy rfl })
(h (λ h : f y = y, by { rw [mul_apply, h, ne.def, inv_eq_iff_eq, cycle_of_apply] at hy,
split_ifs at hy; cc }))) in
⟨(cycle_of f x) :: m, by { rw [list.prod_cons, hm₁], simp },
λ g hg, ((list.mem_cons_iff _ _ _).1 hg).elim (λ hg, hg.symm ▸ is_cycle_cycle_of _ hx)
(hm₂ g),
list.pairwise_cons.2 ⟨λ g hg y,
or_iff_not_imp_left.2 (λ hfy,
have hxy : same_cycle f x y := not_not.1 (mt cycle_of_apply_of_not_same_cycle hfy),
have hgm : g :: m.erase g ~ m := list.cons_perm_iff_perm_erase.2 ⟨hg, list.perm.refl _⟩,
have ∀ h ∈ m.erase g, disjoint g h, from
(list.pairwise_cons.1 ((hgm.pairwise_iff (λ a b (h : disjoint a b), h.symm)).2 hm₃)).1,
classical.by_cases id $ λ hgy : g y ≠ y,
(disjoint_prod_right _ this y).resolve_right $
have hsc : same_cycle f⁻¹ x (f y), by rwa [same_cycle_inv, same_cycle_apply],
by { rw [disjoint_prod_perm hm₃ hgm.symm, list.prod_cons,
← eq_inv_mul_iff_mul_eq] at hm₁,
rwa [hm₁, mul_apply, mul_apply, cycle_of_inv, hsc.cycle_of_apply,
inv_apply_self, inv_eq_iff_eq, eq_comm] }),
hm₃⟩⟩
lemma mem_list_cycles_iff {α : Type*} [fintype α] {l : list (perm α)}
(h1 : ∀ σ : perm α, σ ∈ l → σ.is_cycle)
(h2 : l.pairwise disjoint) {σ : perm α} :
σ ∈ l ↔ σ.is_cycle ∧ ∀ (a : α) (h4 : σ a ≠ a), σ a = l.prod a :=
begin
suffices : σ.is_cycle → (σ ∈ l ↔ ∀ (a : α) (h4 : σ a ≠ a), σ a = l.prod a),
{ exact ⟨λ hσ, ⟨h1 σ hσ, (this (h1 σ hσ)).mp hσ⟩, λ hσ, (this hσ.1).mpr hσ.2⟩ },
intro h3,
classical,
split,
{ intros h a ha,
exact eq_on_support_mem_disjoint h h2 _ (mem_support.mpr ha) },
{ intros h,
have hσl : σ.support ⊆ l.prod.support,
{ intros x hx,
rw mem_support at hx,
rwa [mem_support, ←h _ hx] },
obtain ⟨a, ha, -⟩ := id h3,
rw ←mem_support at ha,
obtain ⟨τ, hτ, hτa⟩ := exists_mem_support_of_mem_support_prod (hσl ha),
have hτl : ∀ (x ∈ τ.support), τ x = l.prod x := eq_on_support_mem_disjoint hτ h2,
have key : ∀ (x ∈ σ.support ∩ τ.support), σ x = τ x,
{ intros x hx,
rw [h x (mem_support.mp (mem_of_mem_inter_left hx)), hτl x (mem_of_mem_inter_right hx)] },
convert hτ,
refine h3.eq_on_support_inter_nonempty_congr (h1 _ hτ) key _ ha,
exact key a (mem_inter_of_mem ha hτa) }
end
lemma list_cycles_perm_list_cycles {α : Type*} [fintype α] {l₁ l₂ : list (perm α)}
(h₀ : l₁.prod = l₂.prod)
(h₁l₁ : ∀ σ : perm α, σ ∈ l₁ → σ.is_cycle) (h₁l₂ : ∀ σ : perm α, σ ∈ l₂ → σ.is_cycle)
(h₂l₁ : l₁.pairwise disjoint) (h₂l₂ : l₂.pairwise disjoint) :
l₁ ~ l₂ :=
begin
classical,
refine (list.perm_ext (nodup_of_pairwise_disjoint_cycles h₁l₁ h₂l₁)
(nodup_of_pairwise_disjoint_cycles h₁l₂ h₂l₂)).mpr (λ σ, _),
by_cases hσ : σ.is_cycle,
{ obtain ⟨a, ha⟩ := not_forall.mp (mt ext hσ.ne_one),
rw [mem_list_cycles_iff h₁l₁ h₂l₁, mem_list_cycles_iff h₁l₂ h₂l₂, h₀] },
{ exact iff_of_false (mt (h₁l₁ σ) hσ) (mt (h₁l₂ σ) hσ) }
end
/-- Factors a permutation `f` into a list of disjoint cyclic permutations that multiply to `f`. -/
def cycle_factors [fintype α] [linear_order α] (f : perm α) :
{l : list (perm α) // l.prod = f ∧ (∀ g ∈ l, is_cycle g) ∧ l.pairwise disjoint} :=
cycle_factors_aux (univ.sort (≤)) f (λ _ _, (mem_sort _).2 (mem_univ _))
/-- Factors a permutation `f` into a list of disjoint cyclic permutations that multiply to `f`,
without a linear order. -/
def trunc_cycle_factors [fintype α] (f : perm α) :
trunc {l : list (perm α) // l.prod = f ∧ (∀ g ∈ l, is_cycle g) ∧ l.pairwise disjoint} :=
quotient.rec_on_subsingleton (@univ α _).1
(λ l h, trunc.mk (cycle_factors_aux l f h))
(show ∀ x, f x ≠ x → x ∈ (@univ α _).1, from λ _ _, mem_univ _)
section cycle_factors_finset
variables [fintype α] (f : perm α)
/-- Factors a permutation `f` into a `finset` of disjoint cyclic permutations that multiply to `f`.
-/
def cycle_factors_finset : finset (perm α) :=
(trunc_cycle_factors f).lift
(λ (l : {l : list (perm α) // l.prod = f ∧ (∀ g ∈ l, is_cycle g) ∧ l.pairwise disjoint}),
l.val.to_finset) (λ ⟨l, hl⟩ ⟨l', hl'⟩, list.to_finset_eq_of_perm _ _
(list_cycles_perm_list_cycles (hl'.left.symm ▸ hl.left) hl.right.left (hl'.right.left)
hl.right.right hl'.right.right))
lemma cycle_factors_finset_eq_list_to_finset {σ : perm α} {l : list (perm α)} (hn : l.nodup) :
σ.cycle_factors_finset = l.to_finset ↔ (∀ f : perm α, f ∈ l → f.is_cycle) ∧
l.pairwise disjoint ∧ l.prod = σ :=
begin
obtain ⟨⟨l', hp', hc', hd'⟩, hl⟩ := trunc.exists_rep σ.trunc_cycle_factors,
have ht : cycle_factors_finset σ = l'.to_finset,
{ rw [cycle_factors_finset, ←hl, trunc.lift_mk] },
rw ht,
split,
{ intro h,
have hn' : l'.nodup := nodup_of_pairwise_disjoint_cycles hc' hd',
have hperm : l ~ l' := list.perm_of_nodup_nodup_to_finset_eq hn hn' h.symm,
refine ⟨_, _, _⟩,
{ exact λ _ h, hc' _ (hperm.subset h)},
{ rwa list.perm.pairwise_iff disjoint.symmetric hperm },
{ rw [←hp', hperm.symm.prod_eq'],
refine hd'.imp _,
exact λ _ _, disjoint.commute } },
{ rintro ⟨hc, hd, hp⟩,
refine list.to_finset_eq_of_perm _ _ _,
refine list_cycles_perm_list_cycles _ hc' hc hd' hd,
rw [hp, hp'] }
end
lemma cycle_factors_finset_eq_finset {σ : perm α} {s : finset (perm α)} :
σ.cycle_factors_finset = s ↔ (∀ f : perm α, f ∈ s → f.is_cycle) ∧
(∃ h : (∀ (a ∈ s) (b ∈ s), a ≠ b → disjoint a b), s.noncomm_prod id
(λ a ha b hb, (em (a = b)).by_cases (λ h, h ▸ commute.refl a)
(set.pairwise_on.mono' (λ _ _, disjoint.commute) h a ha b hb)) = σ) :=
begin
obtain ⟨l, hl, rfl⟩ := s.exists_list_nodup_eq,
rw cycle_factors_finset_eq_list_to_finset hl,
simp only [noncomm_prod_to_finset, hl, exists_prop, list.mem_to_finset, and.congr_left_iff,
and.congr_right_iff, list.map_id, ne.def],
intros,
exact ⟨list.forall_of_pairwise disjoint.symmetric, hl.pairwise_of_forall_ne⟩
end
lemma cycle_factors_finset_pairwise_disjoint (p : perm α) (hp : p ∈ cycle_factors_finset f)
(q : perm α) (hq : q ∈ cycle_factors_finset f) (h : p ≠ q) :
disjoint p q :=
begin
have : f.cycle_factors_finset = f.cycle_factors_finset := rfl,
obtain ⟨-, hd, -⟩ := cycle_factors_finset_eq_finset.mp this,
exact hd p hp q hq h
end
lemma cycle_factors_finset_mem_commute (p : perm α) (hp : p ∈ cycle_factors_finset f)
(q : perm α) (hq : q ∈ cycle_factors_finset f) :
_root_.commute p q :=
begin
by_cases h : p = q,
{ exact h ▸ commute.refl _ },
{ exact (cycle_factors_finset_pairwise_disjoint _ _ hp _ hq h).commute }
end
/-- The product of cycle factors is equal to the original `f : perm α`. -/
lemma cycle_factors_finset_noncomm_prod
(comm : ∀ (g ∈ f.cycle_factors_finset) (h ∈ f.cycle_factors_finset),
commute (id g) (id h) := cycle_factors_finset_mem_commute f) :
f.cycle_factors_finset.noncomm_prod id (comm) = f :=
begin
have : f.cycle_factors_finset = f.cycle_factors_finset := rfl,
obtain ⟨-, hd, hp⟩ := cycle_factors_finset_eq_finset.mp this,
exact hp
end
lemma mem_cycle_factors_finset_iff {f p : perm α} :
p ∈ cycle_factors_finset f ↔ p.is_cycle ∧ ∀ (a ∈ p.support), p a = f a :=
begin
obtain ⟨l, hl, hl'⟩ := f.cycle_factors_finset.exists_list_nodup_eq,
rw ←hl',
rw [eq_comm, cycle_factors_finset_eq_list_to_finset hl] at hl',
simpa [list.mem_to_finset, ne.def, ←hl'.right.right]
using mem_list_cycles_iff hl'.left hl'.right.left
end
lemma cycle_of_mem_cycle_factors_finset_iff {f : perm α} {x : α} :
cycle_of f x ∈ cycle_factors_finset f ↔ x ∈ f.support :=
begin
rw mem_cycle_factors_finset_iff,
split,
{ rintro ⟨hc, h⟩,
contrapose! hc,
rw [not_mem_support, ←cycle_of_eq_one_iff] at hc,
simp [hc] },
{ intros hx,
refine ⟨is_cycle_cycle_of _ (mem_support.mp hx), _⟩,
intros y hy,
rw mem_support at hy,
rw cycle_of_apply,
split_ifs with H,
{ refl },
{ rw cycle_of_apply_of_not_same_cycle H at hy,
contradiction } }
end
lemma mem_cycle_factors_finset_support_le {p f : perm α} (h : p ∈ cycle_factors_finset f) :
p.support ≤ f.support :=
begin
rw mem_cycle_factors_finset_iff at h,
intros x hx,
rwa [mem_support, ←h.right x hx, ←mem_support]
end
lemma cycle_factors_finset_eq_empty_iff {f : perm α} :
cycle_factors_finset f = ∅ ↔ f = 1 :=
by simpa [cycle_factors_finset_eq_finset] using eq_comm
@[simp] lemma cycle_factors_finset_one :
cycle_factors_finset (1 : perm α) = ∅ :=
by simp [cycle_factors_finset_eq_empty_iff]
@[simp] lemma cycle_factors_finset_eq_singleton_self_iff {f : perm α} :
f.cycle_factors_finset = {f} ↔ f.is_cycle :=
by simp [cycle_factors_finset_eq_finset]
lemma is_cycle.cycle_factors_finset_eq_singleton {f : perm α} (hf : is_cycle f) :
f.cycle_factors_finset = {f} :=
cycle_factors_finset_eq_singleton_self_iff.mpr hf
lemma cycle_factors_finset_eq_singleton_iff {f g : perm α} :
f.cycle_factors_finset = {g} ↔ f.is_cycle ∧ f = g :=
begin
suffices : f = g → (g.is_cycle ↔ f.is_cycle),
{ simpa [cycle_factors_finset_eq_finset, eq_comm] },
rintro rfl,
exact iff.rfl
end
/-- Two permutations `f g : perm α` have the same cycle factors iff they are the same. -/
lemma cycle_factors_finset_injective : function.injective (@cycle_factors_finset α _ _) :=
begin
intros f g h,
rw ←cycle_factors_finset_noncomm_prod f,
simpa [h] using cycle_factors_finset_noncomm_prod g
end
lemma disjoint.disjoint_cycle_factors_finset {f g : perm α} (h : disjoint f g) :
_root_.disjoint (cycle_factors_finset f) (cycle_factors_finset g) :=
begin
rw disjoint_iff_disjoint_support at h,
intros x hx,
simp only [mem_cycle_factors_finset_iff, inf_eq_inter, mem_inter, mem_support] at hx,
obtain ⟨⟨⟨a, ha, -⟩, hf⟩, -, hg⟩ := hx,
refine h (_ : a ∈ f.support ∩ g.support),
simp [ha, ←hf a ha, ←hg a ha]
end
lemma disjoint.cycle_factors_finset_mul_eq_union {f g : perm α} (h : disjoint f g) :
cycle_factors_finset (f * g) = cycle_factors_finset f ∪ cycle_factors_finset g :=
begin
rw cycle_factors_finset_eq_finset,
split,
{ simp only [mem_cycle_factors_finset_iff, mem_union],
rintro _ (⟨h, -⟩ | ⟨h, -⟩);
exact h },
{ refine ⟨_, _⟩,
{ simp_rw mem_union,
rintros x (hx | hx) y (hy | hy) hxy,
{ exact cycle_factors_finset_pairwise_disjoint _ _ hx _ hy hxy },
{ exact h.mono (mem_cycle_factors_finset_support_le hx)
(mem_cycle_factors_finset_support_le hy) },
{ exact h.symm.mono (mem_cycle_factors_finset_support_le hx)
(mem_cycle_factors_finset_support_le hy) },
{ exact cycle_factors_finset_pairwise_disjoint _ _ hx _ hy hxy } },
{ rw noncomm_prod_union_of_disjoint h.disjoint_cycle_factors_finset,
rw [cycle_factors_finset_noncomm_prod, cycle_factors_finset_noncomm_prod] } }
end
lemma disjoint_mul_inv_of_mem_cycle_factors_finset {f g : perm α} (h : f ∈ cycle_factors_finset g) :
disjoint (g * f⁻¹) f :=
begin
rw mem_cycle_factors_finset_iff at h,
intro x,
by_cases hx : f x = x,
{ exact or.inr hx },
{ refine or.inl _,
rw [mul_apply, ←h.right, apply_inv_self],
rwa [←support_inv, apply_mem_support, support_inv, mem_support] }
end
end cycle_factors_finset
@[elab_as_eliminator] lemma cycle_induction_on [fintype β] (P : perm β → Prop) (σ : perm β)
(base_one : P 1) (base_cycles : ∀ σ : perm β, σ.is_cycle → P σ)
(induction_disjoint : ∀ σ τ : perm β, disjoint σ τ → is_cycle σ → P σ → P τ → P (σ * τ)) :
P σ :=
begin
suffices :
∀ l : list (perm β), (∀ τ : perm β, τ ∈ l → τ.is_cycle) → l.pairwise disjoint → P l.prod,
{ classical,
let x := σ.trunc_cycle_factors.out,
exact (congr_arg P x.2.1).mp (this x.1 x.2.2.1 x.2.2.2) },
intro l,
induction l with σ l ih,
{ exact λ _ _, base_one },
{ intros h1 h2,
rw list.prod_cons,
exact induction_disjoint σ l.prod
(disjoint_prod_right _ (list.pairwise_cons.mp h2).1)
(h1 _ (list.mem_cons_self _ _))
(base_cycles σ (h1 σ (l.mem_cons_self σ)))
(ih (λ τ hτ, h1 τ (list.mem_cons_of_mem σ hτ)) (list.pairwise_of_pairwise_cons h2)) },
end
lemma cycle_factors_finset_mul_inv_mem_eq_sdiff [fintype α] {f g : perm α}
(h : f ∈ cycle_factors_finset g) :
cycle_factors_finset (g * f⁻¹) = (cycle_factors_finset g) \ {f} :=
begin
revert f,
apply cycle_induction_on _ g,
{ simp },
{ intros σ hσ f hf,
simp only [cycle_factors_finset_eq_singleton_self_iff.mpr hσ, mem_singleton] at hf ⊢,
simp [hf] },
{ intros σ τ hd hc hσ hτ f,
simp_rw [hd.cycle_factors_finset_mul_eq_union, mem_union],
-- if only `wlog` could work here...
rintro (hf | hf),
{ rw [hd.commute.eq, union_comm, union_sdiff_distrib, sdiff_singleton_eq_erase,
erase_eq_of_not_mem, mul_assoc, disjoint.cycle_factors_finset_mul_eq_union, hσ hf],
{ rw mem_cycle_factors_finset_iff at hf,
intro x,
cases hd.symm x with hx hx,
{ exact or.inl hx },
{ refine or.inr _,
by_cases hfx : f x = x,
{ rw ←hfx,
simpa [hx] using hfx.symm },
{ rw mul_apply,
rw ←hf.right _ (mem_support.mpr hfx) at hx,
contradiction } } },
{ exact λ H, hd.disjoint_cycle_factors_finset (mem_inter_of_mem hf H) } },
{ rw [union_sdiff_distrib, sdiff_singleton_eq_erase,
erase_eq_of_not_mem, mul_assoc, disjoint.cycle_factors_finset_mul_eq_union, hτ hf],
{ rw mem_cycle_factors_finset_iff at hf,
intro x,
cases hd x with hx hx,
{ exact or.inl hx },
{ refine or.inr _,
by_cases hfx : f x = x,
{ rw ←hfx,
simpa [hx] using hfx.symm },
{ rw mul_apply,
rw ←hf.right _ (mem_support.mpr hfx) at hx,
contradiction } } },
{ exact λ H, hd.disjoint_cycle_factors_finset (mem_inter_of_mem H hf) } } }
end
lemma same_cycle.nat_of_mem_support [fintype α] (f : perm α) {x y : α} (h : same_cycle f x y)
(hx : x ∈ f.support) :
∃ (i : ℕ) (hi' : i < (f.cycle_of x).support.card), (f ^ i) x = y :=
begin
revert f,
intro f,
apply cycle_induction_on _ f,
{ simp },
{ intros g hg H hx,
rw mem_support at hx,
rw [hg.cycle_of_eq hx, ←order_of_is_cycle hg],
exact H.nat' },
{ rintros g h hd hg IH IH' ⟨m, rfl⟩ hx,
cases (disjoint_iff_eq_or_eq.mp hd) x with hgx hhx,
{ have hpow : ∀ (k : ℤ), ((g * h) ^ k) x = (h ^ k) x,
{ intro k,
suffices : (g ^ k) x = x,
{ simpa [hd.commute.eq, hd.commute.symm.mul_gpow] },
rw gpow_apply_eq_self_of_apply_eq_self,
simpa using hgx },
obtain ⟨k, hk, hk'⟩ := IH' _ _,
{ refine ⟨k, _, _⟩,
{ rw [←cycle_of_eq_one_iff] at hgx,
rwa [hd.cycle_of_mul_distrib, hgx, one_mul] },
{ simpa [←gpow_coe_nat, hpow] using hk' } },
{ use m,
simp [hpow] },
{ rw [mem_support, hd.commute.eq] at hx,
simpa [hgx] using hx } },
{ have hpow : ∀ (k : ℤ), ((g * h) ^ k) x = (g ^ k) x,
{ intro k,
suffices : (h ^ k) x = x,
{ simpa [hd.commute.mul_gpow] },
rw gpow_apply_eq_self_of_apply_eq_self,
simpa using hhx },
obtain ⟨k, hk, hk'⟩ := IH _ _,
{ refine ⟨k, _, _⟩,
{ rw [←cycle_of_eq_one_iff] at hhx,
rwa [hd.cycle_of_mul_distrib, hhx, mul_one] },
{ simpa [←gpow_coe_nat, hpow] using hk' } },
{ use m,
simp [hpow] },
{ simpa [hhx] using hx } } }
end
lemma same_cycle.nat [fintype α] (f : perm α) {x y : α} (h : same_cycle f x y) :
∃ (i : ℕ) (hi : 0 < i) (hi' : i ≤ (f.cycle_of x).support.card + 1), (f ^ i) x = y :=
begin
by_cases hx : x ∈ f.support,
{ obtain ⟨k, hk, hk'⟩ := same_cycle.nat_of_mem_support f h hx,
cases k,
{ refine ⟨(f.cycle_of x).support.card, _, self_le_add_right _ _, _⟩,
{ refine zero_lt_one.trans (one_lt_card_support_of_ne_one _),
simpa using hx },
{ simp only [perm.coe_one, id.def, pow_zero] at hk',
subst hk',
rw [←order_of_is_cycle (is_cycle_cycle_of _ (mem_support.mp hx)),
←cycle_of_pow_apply_self, pow_order_of_eq_one, one_apply] } },
{ exact ⟨k + 1, by simp, nat.le_succ_of_le hk.le, hk'⟩ } },
{ refine ⟨1, zero_lt_one, by simp, _⟩,
obtain ⟨k, rfl⟩ := h,
rw [not_mem_support] at hx,
rw [pow_apply_eq_self_of_apply_eq_self hx,
gpow_apply_eq_self_of_apply_eq_self hx] }
end
section generation
variables [fintype α] [fintype β]
open subgroup
lemma closure_is_cycle : closure {σ : perm β | is_cycle σ} = ⊤ :=
begin
classical,
exact top_le_iff.mp (le_trans (ge_of_eq closure_is_swap) (closure_mono (λ _, is_swap.is_cycle))),
end
lemma closure_cycle_adjacent_swap {σ : perm α} (h1 : is_cycle σ) (h2 : σ.support = ⊤) (x : α) :
closure ({σ, swap x (σ x)} : set (perm α)) = ⊤ :=
begin
let H := closure ({σ, swap x (σ x)} : set (perm α)),
have h3 : σ ∈ H := subset_closure (set.mem_insert σ _),
have h4 : swap x (σ x) ∈ H := subset_closure (set.mem_insert_of_mem _ (set.mem_singleton _)),
have step1 : ∀ (n : ℕ), swap ((σ ^ n) x) ((σ^(n+1)) x) ∈ H,
{ intro n,
induction n with n ih,
{ exact subset_closure (set.mem_insert_of_mem _ (set.mem_singleton _)) },
{ convert H.mul_mem (H.mul_mem h3 ih) (H.inv_mem h3),
rw [mul_swap_eq_swap_mul, mul_inv_cancel_right], refl } },
have step2 : ∀ (n : ℕ), swap x ((σ ^ n) x) ∈ H,
{ intro n,
induction n with n ih,
{ convert H.one_mem,
exact swap_self x },
{ by_cases h5 : x = (σ ^ n) x,
{ rw [pow_succ, mul_apply, ←h5], exact h4 },
by_cases h6 : x = (σ^(n+1)) x,
{ rw [←h6, swap_self], exact H.one_mem },
rw [swap_comm, ←swap_mul_swap_mul_swap h5 h6],
exact H.mul_mem (H.mul_mem (step1 n) ih) (step1 n) } },
have step3 : ∀ (y : α), swap x y ∈ H,
{ intro y,
have hx : x ∈ (⊤ : finset α) := finset.mem_univ x,
rw [←h2, mem_support] at hx,
have hy : y ∈ (⊤ : finset α) := finset.mem_univ y,
rw [←h2, mem_support] at hy,
cases is_cycle.exists_pow_eq h1 hx hy with n hn,
rw ← hn,
exact step2 n },
have step4 : ∀ (y z : α), swap y z ∈ H,
{ intros y z,
by_cases h5 : z = x,
{ rw [h5, swap_comm], exact step3 y },
by_cases h6 : z = y,
{ rw [h6, swap_self], exact H.one_mem },
rw [←swap_mul_swap_mul_swap h5 h6, swap_comm z x],
exact H.mul_mem (H.mul_mem (step3 y) (step3 z)) (step3 y) },
rw [eq_top_iff, ←closure_is_swap, closure_le],
rintros τ ⟨y, z, h5, h6⟩,
rw h6,
exact step4 y z,
end
lemma closure_cycle_coprime_swap {n : ℕ} {σ : perm α} (h0 : nat.coprime n (fintype.card α))
(h1 : is_cycle σ) (h2 : σ.support = finset.univ) (x : α) :
closure ({σ, swap x ((σ ^ n) x)} : set (perm α)) = ⊤ :=
begin
rw [←finset.card_univ, ←h2, ←order_of_is_cycle h1] at h0,
cases exists_pow_eq_self_of_coprime h0 with m hm,
have h2' : (σ ^ n).support = ⊤ := eq.trans (support_pow_coprime h0) h2,
have h1' : is_cycle ((σ ^ n) ^ (m : ℤ)) := by rwa ← hm at h1,
replace h1' : is_cycle (σ ^ n) := is_cycle_of_is_cycle_pow h1'
(le_trans (support_pow_le σ n) (ge_of_eq (congr_arg support hm))),
rw [eq_top_iff, ←closure_cycle_adjacent_swap h1' h2' x, closure_le, set.insert_subset],
exact ⟨subgroup.pow_mem (closure _) (subset_closure (set.mem_insert σ _)) n,
set.singleton_subset_iff.mpr (subset_closure (set.mem_insert_of_mem _ (set.mem_singleton _)))⟩,
end
lemma closure_prime_cycle_swap {σ τ : perm α} (h0 : (fintype.card α).prime) (h1 : is_cycle σ)
(h2 : σ.support = finset.univ) (h3 : is_swap τ) : closure ({σ, τ} : set (perm α)) = ⊤ :=
begin
obtain ⟨x, y, h4, h5⟩ := h3,
obtain ⟨i, hi⟩ := h1.exists_pow_eq (mem_support.mp
((finset.ext_iff.mp h2 x).mpr (finset.mem_univ x)))
(mem_support.mp ((finset.ext_iff.mp h2 y).mpr (finset.mem_univ y))),
rw [h5, ←hi],
refine closure_cycle_coprime_swap (nat.coprime.symm
(h0.coprime_iff_not_dvd.mpr (λ h, h4 _))) h1 h2 x,
cases h with m hm,
rwa [hm, pow_mul, ←finset.card_univ, ←h2, ←order_of_is_cycle h1,
pow_order_of_eq_one, one_pow, one_apply] at hi,
end
end generation
section
variables [fintype α] {σ τ : perm α}
noncomputable theory
lemma is_conj_of_support_equiv (f : {x // x ∈ (σ.support : set α)} ≃ {x // x ∈ (τ.support : set α)})
(hf : ∀ (x : α) (hx : x ∈ (σ.support : set α)), (f ⟨σ x, apply_mem_support.2 hx⟩ : α) =
τ ↑(f ⟨x,hx⟩)) :
is_conj σ τ :=
begin
refine is_conj_iff.2 ⟨equiv.extend_subtype f, _⟩,
rw mul_inv_eq_iff_eq_mul,
ext,
simp only [perm.mul_apply],
by_cases hx : x ∈ σ.support,
{ rw [equiv.extend_subtype_apply_of_mem, equiv.extend_subtype_apply_of_mem],
{ exact hf x (finset.mem_coe.2 hx) } },
{ rwa [not_not.1 ((not_congr mem_support).1 (equiv.extend_subtype_not_mem f _ _)),
not_not.1 ((not_congr mem_support).mp hx)] }
end
theorem is_cycle.is_conj (hσ : is_cycle σ) (hτ : is_cycle τ) (h : σ.support.card = τ.support.card) :
is_conj σ τ :=
begin
refine is_conj_of_support_equiv (hσ.gpowers_equiv_support.symm.trans
((gpowers_equiv_gpowers begin
rw [order_of_is_cycle hσ, h, order_of_is_cycle hτ],
end).trans hτ.gpowers_equiv_support)) _,
intros x hx,
simp only [perm.mul_apply, equiv.trans_apply, equiv.sum_congr_apply],
obtain ⟨n, rfl⟩ := hσ.exists_pow_eq (classical.some_spec hσ).1 (mem_support.1 hx),
apply eq.trans _ (congr rfl (congr rfl (congr rfl
(congr rfl (hσ.gpowers_equiv_support_symm_apply n).symm)))),
apply (congr rfl (congr rfl (congr rfl (hσ.gpowers_equiv_support_symm_apply (n + 1))))).trans _,
simp only [ne.def, is_cycle.gpowers_equiv_support_apply,
subtype.coe_mk, gpowers_equiv_gpowers_apply],
rw [pow_succ, perm.mul_apply],
end
theorem is_cycle.is_conj_iff (hσ : is_cycle σ) (hτ : is_cycle τ) :
is_conj σ τ ↔ σ.support.card = τ.support.card :=
⟨begin
intro h,
obtain ⟨π, rfl⟩ := is_conj_iff.1 h,
apply finset.card_congr (λ a ha, π a) (λ _ ha, _) (λ _ _ _ _ ab, π.injective ab) (λ b hb, _),
{ simp [mem_support.1 ha] },
{ refine ⟨π⁻¹ b, ⟨_, π.apply_inv_self b⟩⟩,
contrapose! hb,
rw [mem_support, not_not] at hb,
rw [mem_support, not_not, perm.mul_apply, perm.mul_apply, hb, perm.apply_inv_self] }
end, hσ.is_conj hτ⟩
@[simp]
lemma support_conj : (σ * τ * σ⁻¹).support = τ.support.map σ.to_embedding :=
begin
ext,
simp only [mem_map_equiv, perm.coe_mul, comp_app, ne.def, perm.mem_support, equiv.eq_symm_apply],
refl,
end
lemma card_support_conj : (σ * τ * σ⁻¹).support.card = τ.support.card :=
by simp
end
theorem disjoint.is_conj_mul {α : Type*} [fintype α] {σ τ π ρ : perm α}
(hc1 : is_conj σ π) (hc2 : is_conj τ ρ)
(hd1 : disjoint σ τ) (hd2 : disjoint π ρ) :
is_conj (σ * τ) (π * ρ) :=
begin
classical,
obtain ⟨f, rfl⟩ := is_conj_iff.1 hc1,
obtain ⟨g, rfl⟩ := is_conj_iff.1 hc2,
have hd1' := coe_inj.2 hd1.support_mul,
have hd2' := coe_inj.2 hd2.support_mul,
rw [coe_union] at *,
have hd1'' := disjoint_iff_disjoint_coe.1 (disjoint_iff_disjoint_support.1 hd1),
have hd2'' := disjoint_iff_disjoint_coe.1 (disjoint_iff_disjoint_support.1 hd2),
refine is_conj_of_support_equiv _ _,
{ refine ((equiv.set.of_eq hd1').trans (equiv.set.union hd1'')).trans
((equiv.sum_congr (subtype_equiv f (λ a, _)) (subtype_equiv g (λ a, _))).trans
((equiv.set.of_eq hd2').trans (equiv.set.union hd2'')).symm);
{ simp only [set.mem_image, to_embedding_apply, exists_eq_right,
support_conj, coe_map, apply_eq_iff_eq] } },
{ intros x hx,
simp only [trans_apply, symm_trans_apply, set.of_eq_apply,
set.of_eq_symm_apply, equiv.sum_congr_apply],
rw [hd1', set.mem_union] at hx,
cases hx with hxσ hxτ,
{ rw [mem_coe, mem_support] at hxσ,
rw [set.union_apply_left hd1'' _, set.union_apply_left hd1'' _],
simp only [subtype_equiv_apply, perm.coe_mul, sum.map_inl, comp_app,
set.union_symm_apply_left, subtype.coe_mk, apply_eq_iff_eq],
{ have h := (hd2 (f x)).resolve_left _,
{ rw [mul_apply, mul_apply] at h,
rw [h, inv_apply_self, (hd1 x).resolve_left hxσ] },
{ rwa [mul_apply, mul_apply, inv_apply_self, apply_eq_iff_eq] } },
{ rwa [subtype.coe_mk, subtype.coe_mk, mem_coe, mem_support] },
{ rwa [subtype.coe_mk, subtype.coe_mk, perm.mul_apply,
(hd1 x).resolve_left hxσ, mem_coe, apply_mem_support, mem_support] } },
{ rw [mem_coe, ← apply_mem_support, mem_support] at hxτ,
rw [set.union_apply_right hd1'' _, set.union_apply_right hd1'' _],
simp only [subtype_equiv_apply, perm.coe_mul, sum.map_inr, comp_app,
set.union_symm_apply_right, subtype.coe_mk, apply_eq_iff_eq],
{ have h := (hd2 (g (τ x))).resolve_right _,
{ rw [mul_apply, mul_apply] at h,
rw [inv_apply_self, h, (hd1 (τ x)).resolve_right hxτ] },
{ rwa [mul_apply, mul_apply, inv_apply_self, apply_eq_iff_eq] } },
{ rwa [subtype.coe_mk, subtype.coe_mk, mem_coe, ← apply_mem_support, mem_support] },
{ rwa [subtype.coe_mk, subtype.coe_mk, perm.mul_apply,
(hd1 (τ x)).resolve_right hxτ, mem_coe, mem_support] } } }
end
section fixed_points
/-!
### Fixed points
-/
lemma fixed_point_card_lt_of_ne_one [fintype α] {σ : perm α} (h : σ ≠ 1) :
(filter (λ x, σ x = x) univ).card < fintype.card α - 1 :=
begin
rw [nat.lt_sub_left_iff_add_lt, ← nat.lt_sub_right_iff_add_lt, ← finset.card_compl,
finset.compl_filter],
exact one_lt_card_support_of_ne_one h
end
end fixed_points
end equiv.perm
|
1b5f52d6abc9bd860490583883326144c92fe9be | 9ad8d18fbe5f120c22b5e035bc240f711d2cbd7e | /src/exercises/mathcomp_book/odd.lean | 50367775ba5f5a580b88ac11655735102445d0b9 | [] | no_license | agusakov/lean_lib | c0e9cc29fc7d2518004e224376adeb5e69b5cc1a | f88d162da2f990b87c4d34f5f46bbca2bbc5948e | refs/heads/master | 1,642,141,461,087 | 1,557,395,798,000 | 1,557,395,798,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 3,100 | lean | import tactic.interactive tactic.squeeze data.nat.modeq
variables n m : nat
@[simp]
def is_odd_a : ℕ → bool
| 0 := ff
| (nat.succ n) := bnot (is_odd_a n)
#reduce is_odd_a (n + 2)
lemma odd_ss_a : is_odd_a (n + 2) = is_odd_a n :=
begin
dsimp[is_odd_a],
cases is_odd_a n; refl,
end
lemma odd_add_a : ∀ n m : ℕ ,
is_odd_a (n + m) = bxor (is_odd_a n) (is_odd_a m)
| n 0 := by rw[is_odd_a,nat.add_zero,bxor_ff]
| n (m + 1) := begin
rw[nat.add_succ,is_odd_a,is_odd_a,(odd_add_a n m)],
cases (is_odd_a n); cases (is_odd_a m); refl,
end
/- ------------------------------------------------------------ -/
@[simp]
def s : ℕ × bool → ℕ × bool
| ⟨n,ff⟩ := ⟨n,tt⟩
| ⟨n,tt⟩ := ⟨n.succ,ff⟩
@[simp]
def ss : ℕ → ℕ × bool
| 0 := ⟨0,ff⟩
| (nat.succ n) := s (ss n)
def is_odd_b (n : ℕ) : bool := (ss n).2
#reduce ss (n + 2)
lemma odd_ss_b : is_odd_b (n + 2) = is_odd_b n :=
begin
dsimp[is_odd_b,ss,s],
rcases (ss n) with ⟨k,tt|ff⟩;refl,
end
def Nb_add : ℕ × bool → ℕ × bool → ℕ × bool
| ⟨n,ff⟩ ⟨m,b⟩ := ⟨n+m,b⟩
| ⟨n,tt⟩ ⟨m,ff⟩ := ⟨n+m,tt⟩
| ⟨n,tt⟩ ⟨m,tt⟩ := ⟨n+m+1,ff⟩
lemma Nb_add_s (u v) : Nb_add u (s v) = s (Nb_add u v) :=
begin
rcases u with ⟨i,ff|tt⟩; rcases v with ⟨j,ff|tt⟩; refl,
end
lemma ss_add (n m : ℕ) : ss (n + m) = Nb_add (ss n) (ss m) :=
begin
induction m with m ih_m,
{rw[add_zero,ss],cases (ss n) with k b; cases b; refl},
{rw[nat.add_succ,ss,ss,ih_m,Nb_add_s],}
end
lemma odd_add_b : ∀ n m : ℕ,
is_odd_b (n + m) = bxor (is_odd_b n) (is_odd_b m) :=
begin
intros n m,
rw[is_odd_b,is_odd_b,is_odd_b,ss_add],
rcases (ss n) with ⟨i,ff|tt⟩; rcases (ss m) with ⟨j,ff|tt⟩; refl,
end
/- ------------------------------------------------------------ -/
@[simp]
def is_odd_c (n : ℕ) : bool := if n % 2 = 0 then ff else tt
lemma odd_ss_c : is_odd_c (n + 2) = is_odd_c n :=
begin
dsimp[is_odd_c],
cases (n % 2) with k,{exact rfl},{simp}
end
/- ------------------------------------------------------------ -/
mutual def is_odd_d, is_even_d
with is_odd_d : nat → bool
| 0 := ff
| (n + 1) := is_even_d n
with is_even_d : nat → bool
| 0 := tt
| (n + 1) := is_odd_d n
#reduce is_odd_d (n + 2)
lemma odd_ss_d : is_odd_d (n + 2) = is_odd_d n :=
begin
rw[is_odd_d,is_even_d],
end
lemma odd_even_d : ∀ (n : ℕ), is_odd_d n = bnot (is_even_d n)
| 0 := rfl
| (n + 1) := by {rw[is_odd_d,is_even_d,odd_even_d n,bnot_bnot],}
@[inline] def beq : bool → bool → bool
| tt tt := tt
| ff ff := tt
| _ _ := ff
lemma even_add_d : ∀ n m : ℕ,
is_even_d (n + m) = beq (is_even_d n) (is_even_d m) :=
begin
intros n m,
induction m with m ih_m,
{rw[add_zero,is_even_d],cases is_even_d n;refl},
{rw[nat.add_succ,is_even_d,is_even_d,odd_even_d,odd_even_d,ih_m],
cases is_even_d n;cases is_even_d m; refl,
}
end
lemma odd_add_d : ∀ n m : ℕ,
is_odd_d (n + m) = bxor (is_odd_d n) (is_odd_d m) :=
begin
intros n m,
rw[odd_even_d,odd_even_d,odd_even_d,even_add_d],
cases is_even_d n;cases is_even_d m; refl,
end
|
16feec5c33a93f0562c1d32f9c90a85540b30627 | ae1e94c332e17c7dc7051ce976d5a9eebe7ab8a5 | /src/Lean/Meta/Match/Match.lean | b2395c6aa72cfb6406c301698098d9b05403309f | [
"Apache-2.0"
] | permissive | dupuisf/lean4 | d082d13b01243e1de29ae680eefb476961221eef | 6a39c65bd28eb0e28c3870188f348c8914502718 | refs/heads/master | 1,676,948,755,391 | 1,610,665,114,000 | 1,610,665,114,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 32,300 | 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.Util.CollectLevelParams
import Lean.Util.Recognizers
import Lean.Compiler.ExternAttr
import Lean.Meta.Check
import Lean.Meta.Closure
import Lean.Meta.Tactic.Cases
import Lean.Meta.GeneralizeTelescope
import Lean.Meta.Match.Basic
import Lean.Meta.Match.MVarRenaming
import Lean.Meta.Match.CaseValues
namespace Lean.Meta.Match
/- The number of patterns in each AltLHS must be equal to majors.length -/
private def checkNumPatterns (majors : Array Expr) (lhss : List AltLHS) : MetaM Unit := do
let num := majors.size
if lhss.any fun lhs => lhs.patterns.length != num then
throwError "incorrect number of patterns"
/- Given a list of `AltLHS`, create a minor premise for each one, convert them into `Alt`, and then execute `k` -/
private def withAlts {α} (motive : Expr) (lhss : List AltLHS) (k : List Alt → Array (Expr × Nat) → MetaM α) : MetaM α :=
loop lhss [] #[]
where
mkMinorType (xs : Array Expr) (lhs : AltLHS) : MetaM Expr :=
withExistingLocalDecls lhs.fvarDecls do
let args ← lhs.patterns.toArray.mapM (Pattern.toExpr · (annotate := true))
let minorType := mkAppN motive args
mkForallFVars xs minorType
loop (lhss : List AltLHS) (alts : List Alt) (minors : Array (Expr × Nat)) : MetaM α := do
match lhss with
| [] => k alts.reverse minors
| lhs::lhss =>
let xs := lhs.fvarDecls.toArray.map LocalDecl.toExpr
let minorType ← mkMinorType xs lhs
let (minorType, minorNumParams) := if !xs.isEmpty then (minorType, xs.size) else (mkSimpleThunkType minorType, 1)
let idx := alts.length
let minorName := (`h).appendIndexAfter (idx+1)
trace[Meta.Match.debug]! "minor premise {minorName} : {minorType}"
withLocalDeclD minorName minorType fun minor => do
let rhs := if xs.isEmpty then mkApp minor (mkConst `Unit.unit) else mkAppN minor xs
let minors := minors.push (minor, minorNumParams)
let fvarDecls ← lhs.fvarDecls.mapM instantiateLocalDeclMVars
let alts := { ref := lhs.ref, idx := idx, rhs := rhs, fvarDecls := fvarDecls, patterns := lhs.patterns : Alt } :: alts
loop lhss alts minors
def assignGoalOf (p : Problem) (e : Expr) : MetaM Unit :=
withGoalOf p (assignExprMVar p.mvarId e)
structure State where
used : Std.HashSet Nat := {} -- used alternatives
counterExamples : List (List Example) := []
/-- Return true if the given (sub-)problem has been solved. -/
private def isDone (p : Problem) : Bool :=
p.vars.isEmpty
/-- Return true if the next element on the `p.vars` list is a variable. -/
private def isNextVar (p : Problem) : Bool :=
match p.vars with
| Expr.fvar _ _ :: _ => true
| _ => false
private def hasAsPattern (p : Problem) : Bool :=
p.alts.any fun alt => match alt.patterns with
| Pattern.as _ _ :: _ => true
| _ => false
private def hasCtorPattern (p : Problem) : Bool :=
p.alts.any fun alt => match alt.patterns with
| Pattern.ctor _ _ _ _ :: _ => true
| _ => false
private def hasValPattern (p : Problem) : Bool :=
p.alts.any fun alt => match alt.patterns with
| Pattern.val _ :: _ => true
| _ => false
private def hasNatValPattern (p : Problem) : Bool :=
p.alts.any fun alt => match alt.patterns with
| Pattern.val v :: _ => v.isNatLit
| _ => false
private def hasVarPattern (p : Problem) : Bool :=
p.alts.any fun alt => match alt.patterns with
| Pattern.var _ :: _ => true
| _ => false
private def hasArrayLitPattern (p : Problem) : Bool :=
p.alts.any fun alt => match alt.patterns with
| Pattern.arrayLit _ _ :: _ => true
| _ => false
private def isVariableTransition (p : Problem) : Bool :=
p.alts.all fun alt => match alt.patterns with
| Pattern.inaccessible _ :: _ => true
| Pattern.var _ :: _ => true
| _ => false
private def isConstructorTransition (p : Problem) : Bool :=
(hasCtorPattern p || p.alts.isEmpty)
&& p.alts.all fun alt => match alt.patterns with
| Pattern.ctor _ _ _ _ :: _ => true
| Pattern.var _ :: _ => true
| Pattern.inaccessible _ :: _ => true
| _ => false
private def isValueTransition (p : Problem) : Bool :=
hasVarPattern p && hasValPattern p
&& p.alts.all fun alt => match alt.patterns with
| Pattern.val _ :: _ => true
| Pattern.var _ :: _ => true
| _ => false
private def isArrayLitTransition (p : Problem) : Bool :=
hasArrayLitPattern p && hasVarPattern p
&& p.alts.all fun alt => match alt.patterns with
| Pattern.arrayLit _ _ :: _ => true
| Pattern.var _ :: _ => true
| _ => false
private def isNatValueTransition (p : Problem) : Bool :=
hasNatValPattern p
&& (!isNextVar p ||
p.alts.any fun alt => match alt.patterns with
| Pattern.ctor _ _ _ _ :: _ => true
| Pattern.inaccessible _ :: _ => true
| _ => false)
private def processSkipInaccessible (p : Problem) : Problem :=
match p.vars with
| [] => unreachable!
| x :: xs => do
let alts := p.alts.map fun alt => match alt.patterns with
| Pattern.inaccessible _ :: ps => { alt with patterns := ps }
| _ => unreachable!
{ p with alts := alts, vars := xs }
private def processLeaf (p : Problem) : StateRefT State MetaM Unit :=
match p.alts with
| [] => do
liftM $ admit p.mvarId
modify fun s => { s with counterExamples := p.examples :: s.counterExamples }
| alt :: _ => do
-- TODO: check whether we have unassigned metavars in rhs
liftM $ assignGoalOf p alt.rhs
modify fun s => { s with used := s.used.insert alt.idx }
private def processAsPattern (p : Problem) : MetaM Problem :=
match p.vars with
| [] => unreachable!
| x :: xs => withGoalOf p do
let alts ← p.alts.mapM fun alt => match alt.patterns with
| Pattern.as fvarId p :: ps => { alt with patterns := p :: ps }.checkAndReplaceFVarId fvarId x
| _ => pure alt
pure { p with alts := alts }
private def processVariable (p : Problem) : MetaM Problem :=
match p.vars with
| [] => unreachable!
| x :: xs => withGoalOf p do
let alts ← p.alts.mapM fun alt => match alt.patterns with
| Pattern.inaccessible _ :: ps => pure { alt with patterns := ps }
| Pattern.var fvarId :: ps => { alt with patterns := ps }.checkAndReplaceFVarId fvarId x
| _ => unreachable!
pure { p with alts := alts, vars := xs }
private def throwInductiveTypeExpected {α} (e : Expr) : MetaM α := do
let t ← inferType e
throwError! "failed to compile pattern matching, inductive type expected{indentExpr e}\nhas type{indentExpr t}"
private def inLocalDecls (localDecls : List LocalDecl) (fvarId : FVarId) : Bool :=
localDecls.any fun d => d.fvarId == fvarId
namespace Unify
structure Context where
altFVarDecls : List LocalDecl
structure State where
fvarSubst : FVarSubst := {}
abbrev M := ReaderT Context $ StateRefT State MetaM
def isAltVar (fvarId : FVarId) : M Bool := do
return inLocalDecls (← read).altFVarDecls fvarId
def expandIfVar (e : Expr) : M Expr := do
match e with
| Expr.fvar _ _ => return (← get).fvarSubst.apply e
| _ => return e
def occurs (fvarId : FVarId) (v : Expr) : Bool :=
Option.isSome $ v.find? fun e => match e with
| Expr.fvar fvarId' _ => fvarId == fvarId'
| _=> false
def assign (fvarId : FVarId) (v : Expr) : M Bool := do
if occurs fvarId v then
trace[Meta.Match.unify]! "assign occurs check failed, {mkFVar fvarId} := {v}"
pure false
else
let ctx ← read
if (← isAltVar fvarId) then
trace[Meta.Match.unify]! "{mkFVar fvarId} := {v}"
modify fun s => { s with fvarSubst := s.fvarSubst.insert fvarId v }
pure true
else
trace[Meta.Match.unify]! "assign failed variable is not local, {mkFVar fvarId} := {v}"
pure false
partial def unify (a : Expr) (b : Expr) : M Bool := do
trace[Meta.Match.unify]! "{a} =?= {b}"
if (← isDefEq a b) then
pure true
else
let a' ← expandIfVar a
let b' ← expandIfVar b
if a != a' || b != b' then unify a' b'
else match a, b with
| Expr.mdata _ a _, b => unify a b
| a, Expr.mdata _ b _ => unify a b
| Expr.fvar aFvarId _, Expr.fvar bFVarId _ => assign aFvarId b <||> assign bFVarId a
| Expr.fvar aFvarId _, b => assign aFvarId b
| a, Expr.fvar bFVarId _ => assign bFVarId a
| Expr.app aFn aArg _, Expr.app bFn bArg _ => unify aFn bFn <&&> unify aArg bArg
| _, _ => pure false
end Unify
private def unify? (altFVarDecls : List LocalDecl) (a b : Expr) : MetaM (Option FVarSubst) := do
let a ← instantiateMVars a
let b ← instantiateMVars b
let (b, s) ← Unify.unify a b { altFVarDecls := altFVarDecls} |>.run {}
if b then pure s.fvarSubst else pure none
private def expandVarIntoCtor? (alt : Alt) (fvarId : FVarId) (ctorName : Name) : MetaM (Option Alt) :=
withExistingLocalDecls alt.fvarDecls do
let env ← getEnv
let ldecl ← getLocalDecl fvarId
let expectedType ← inferType (mkFVar fvarId)
let expectedType ← whnfD expectedType
let (ctorLevels, ctorParams) ← getInductiveUniverseAndParams expectedType
let ctor := mkAppN (mkConst ctorName ctorLevels) ctorParams
let ctorType ← inferType ctor
forallTelescopeReducing ctorType fun ctorFields resultType => do
let ctor := mkAppN ctor ctorFields
let alt := alt.replaceFVarId fvarId ctor
let ctorFieldDecls ← ctorFields.mapM fun ctorField => getLocalDecl ctorField.fvarId!
let newAltDecls := ctorFieldDecls.toList ++ alt.fvarDecls
let subst? ← unify? newAltDecls resultType expectedType
match subst? with
| none => pure none
| some subst =>
let newAltDecls := newAltDecls.filter fun d => !subst.contains d.fvarId -- remove declarations that were assigned
let newAltDecls := newAltDecls.map fun d => d.applyFVarSubst subst -- apply substitution to remaining declaration types
let patterns := alt.patterns.map fun p => p.applyFVarSubst subst
let rhs := subst.apply alt.rhs
let ctorFieldPatterns := ctorFields.toList.map fun ctorField => match subst.get ctorField.fvarId! with
| e@(Expr.fvar fvarId _) => if inLocalDecls newAltDecls fvarId then Pattern.var fvarId else Pattern.inaccessible e
| e => Pattern.inaccessible e
pure $ some { alt with fvarDecls := newAltDecls, rhs := rhs, patterns := ctorFieldPatterns ++ patterns }
private def getInductiveVal? (x : Expr) : MetaM (Option InductiveVal) := do
let xType ← inferType x
let xType ← whnfD xType
match xType.getAppFn with
| Expr.const constName _ _ =>
let cinfo ← getConstInfo constName
match cinfo with
| ConstantInfo.inductInfo val => pure (some val)
| _ => pure none
| _ => pure none
private def hasRecursiveType (x : Expr) : MetaM Bool := do
match (← getInductiveVal? x) with
| some val => pure val.isRec
| _ => pure false
/- Given `alt` s.t. the next pattern is an inaccessible pattern `e`,
try to normalize `e` into a constructor application.
If it is not a constructor, throw an error.
Otherwise, if it is a constructor application of `ctorName`,
update the next patterns with the fields of the constructor.
Otherwise, return none. -/
def processInaccessibleAsCtor (alt : Alt) (ctorName : Name) : MetaM (Option Alt) := do
let env ← getEnv
match alt.patterns with
| p@(Pattern.inaccessible e) :: ps =>
trace[Meta.Match.match]! "inaccessible in ctor step {e}"
withExistingLocalDecls alt.fvarDecls do
-- Try to push inaccessible annotations.
let e ← whnfD e
match e.constructorApp? env with
| some (ctorVal, ctorArgs) =>
if ctorVal.name == ctorName then
let fields := ctorArgs.extract ctorVal.nparams ctorArgs.size
let fields := fields.toList.map Pattern.inaccessible
pure $ some { alt with patterns := fields ++ ps }
else
pure none
| _ => throwErrorAt! alt.ref "dependent match elimination failed, inaccessible pattern found{indentD p.toMessageData}\nconstructor expected"
| _ => unreachable!
private def processConstructor (p : Problem) : MetaM (Array Problem) := do
trace[Meta.Match.match]! "constructor step"
let env ← getEnv
match p.vars with
| [] => unreachable!
| x :: xs => do
let subgoals? ← commitWhenSome? do
let subgoals ← cases p.mvarId x.fvarId!
if subgoals.isEmpty then
/- Easy case: we have solved problem `p` since there are no subgoals -/
pure (some #[])
else if !p.alts.isEmpty then
pure (some subgoals)
else do
let isRec ← withGoalOf p $ hasRecursiveType x
/- If there are no alternatives and the type of the current variable is recursive, we do NOT consider
a constructor-transition to avoid nontermination.
TODO: implement a more general approach if this is not sufficient in practice -/
if isRec then pure none
else pure (some subgoals)
match subgoals? with
| none => pure #[{ p with vars := xs }]
| some subgoals =>
subgoals.mapM fun subgoal => withMVarContext subgoal.mvarId do
let subst := subgoal.subst
let fields := subgoal.fields.toList
let newVars := fields ++ xs
let newVars := newVars.map fun x => x.applyFVarSubst subst
let subex := Example.ctor subgoal.ctorName $ fields.map fun field => match field with
| Expr.fvar fvarId _ => Example.var fvarId
| _ => Example.underscore -- This case can happen due to dependent elimination
let examples := p.examples.map $ Example.replaceFVarId x.fvarId! subex
let examples := examples.map $ Example.applyFVarSubst subst
let newAlts := p.alts.filter fun alt => match alt.patterns with
| Pattern.ctor n _ _ _ :: _ => n == subgoal.ctorName
| Pattern.var _ :: _ => true
| Pattern.inaccessible _ :: _ => true
| _ => false
let newAlts := newAlts.map fun alt => alt.applyFVarSubst subst
let newAlts ← newAlts.filterMapM fun alt => match alt.patterns with
| Pattern.ctor _ _ _ fields :: ps => pure $ some { alt with patterns := fields ++ ps }
| Pattern.var fvarId :: ps => expandVarIntoCtor? { alt with patterns := ps } fvarId subgoal.ctorName
| Pattern.inaccessible _ :: _ => processInaccessibleAsCtor alt subgoal.ctorName
| _ => unreachable!
pure { mvarId := subgoal.mvarId, vars := newVars, alts := newAlts, examples := examples }
private def processNonVariable (p : Problem) : MetaM Problem :=
match p.vars with
| [] => unreachable!
| x :: xs => withGoalOf p do
let x ← whnfD x
let env ← getEnv
match x.constructorApp? env with
| some (ctorVal, xArgs) =>
let alts ← p.alts.filterMapM fun alt => match alt.patterns with
| Pattern.ctor n _ _ fields :: ps =>
if n != ctorVal.name then
pure none
else
pure $ some { alt with patterns := fields ++ ps }
| Pattern.inaccessible _ :: _ => processInaccessibleAsCtor alt ctorVal.name
| p :: _ => throwError! "failed to compile pattern matching, inaccessible pattern or constructor expected{indentD p.toMessageData}"
| _ => unreachable!
let xFields := xArgs.extract ctorVal.nparams xArgs.size
pure { p with alts := alts, vars := xFields.toList ++ xs }
| none =>
let alts ← p.alts.filterMapM fun alt => match alt.patterns with
| Pattern.inaccessible e :: ps => do
if (← isDefEq x e) then
pure $ some { alt with patterns := ps }
else
pure none
| p :: _ => throwError! "failed to compile pattern matching, unexpected pattern{indentD p.toMessageData}\ndiscriminant{indentExpr x}"
| _ => unreachable!
pure { p with alts := alts, vars := xs }
private def collectValues (p : Problem) : Array Expr :=
p.alts.foldl (init := #[]) fun values alt =>
match alt.patterns with
| Pattern.val v :: _ => if values.contains v then values else values.push v
| _ => values
private def isFirstPatternVar (alt : Alt) : Bool :=
match alt.patterns with
| Pattern.var _ :: _ => true
| _ => false
private def processValue (p : Problem) : MetaM (Array Problem) := do
trace[Meta.Match.match]! "value step"
match p.vars with
| [] => unreachable!
| x :: xs => do
let values := collectValues p
let subgoals ← caseValues p.mvarId x.fvarId! values
subgoals.mapIdxM fun i subgoal => do
if h : i.val < values.size then
let value := values.get ⟨i, h⟩
-- (x = value) branch
let subst := subgoal.subst
let examples := p.examples.map $ Example.replaceFVarId x.fvarId! (Example.val value)
let examples := examples.map $ Example.applyFVarSubst subst
let newAlts := p.alts.filter fun alt => match alt.patterns with
| Pattern.val v :: _ => v == value
| Pattern.var _ :: _ => true
| _ => false
let newAlts := newAlts.map fun alt => alt.applyFVarSubst subst
let newAlts := newAlts.map fun alt => match alt.patterns with
| Pattern.val _ :: ps => { alt with patterns := ps }
| Pattern.var fvarId :: ps =>
let alt := { alt with patterns := ps }
alt.replaceFVarId fvarId value
| _ => unreachable!
let newVars := xs.map fun x => x.applyFVarSubst subst
pure { mvarId := subgoal.mvarId, vars := newVars, alts := newAlts, examples := examples }
else
-- else branch for value
let newAlts := p.alts.filter isFirstPatternVar
pure { p with mvarId := subgoal.mvarId, alts := newAlts, vars := x::xs }
private def collectArraySizes (p : Problem) : Array Nat :=
p.alts.foldl (init := #[]) fun sizes alt =>
match alt.patterns with
| Pattern.arrayLit _ ps :: _ => let sz := ps.length; if sizes.contains sz then sizes else sizes.push sz
| _ => sizes
private def expandVarIntoArrayLit (alt : Alt) (fvarId : FVarId) (arrayElemType : Expr) (arraySize : Nat) : MetaM Alt :=
withExistingLocalDecls alt.fvarDecls do
let fvarDecl ← getLocalDecl fvarId
let varNamePrefix := fvarDecl.userName
let rec loop
| n+1, newVars =>
withLocalDeclD (varNamePrefix.appendIndexAfter (n+1)) arrayElemType fun x =>
loop n (newVars.push x)
| 0, newVars => do
let arrayLit ← mkArrayLit arrayElemType newVars.toList
let alt := alt.replaceFVarId fvarId arrayLit
let newDecls ← newVars.toList.mapM fun newVar => getLocalDecl newVar.fvarId!
let newPatterns := newVars.toList.map fun newVar => Pattern.var newVar.fvarId!
pure { alt with fvarDecls := newDecls ++ alt.fvarDecls, patterns := newPatterns ++ alt.patterns }
loop arraySize #[]
private def processArrayLit (p : Problem) : MetaM (Array Problem) := do
trace[Meta.Match.match]! "array literal step"
match p.vars with
| [] => unreachable!
| x :: xs => do
let sizes := collectArraySizes p
let subgoals ← caseArraySizes p.mvarId x.fvarId! sizes
subgoals.mapIdxM fun i subgoal => do
if h : i.val < sizes.size then
let size := sizes.get! i
let subst := subgoal.subst
let elems := subgoal.elems.toList
let newVars := elems.map mkFVar ++ xs
let newVars := newVars.map fun x => x.applyFVarSubst subst
let subex := Example.arrayLit <| elems.map Example.var
let examples := p.examples.map <| Example.replaceFVarId x.fvarId! subex
let examples := examples.map <| Example.applyFVarSubst subst
let newAlts := p.alts.filter fun alt => match alt.patterns with
| Pattern.arrayLit _ ps :: _ => ps.length == size
| Pattern.var _ :: _ => true
| _ => false
let newAlts := newAlts.map fun alt => alt.applyFVarSubst subst
let newAlts ← newAlts.mapM fun alt => match alt.patterns with
| Pattern.arrayLit _ pats :: ps => pure { alt with patterns := pats ++ ps }
| Pattern.var fvarId :: ps => do
let α ← getArrayArgType <| subst.apply x
expandVarIntoArrayLit { alt with patterns := ps } fvarId α size
| _ => unreachable!
pure { mvarId := subgoal.mvarId, vars := newVars, alts := newAlts, examples := examples }
else do
-- else branch
let newAlts := p.alts.filter isFirstPatternVar
pure { p with mvarId := subgoal.mvarId, alts := newAlts, vars := x::xs }
private def expandNatValuePattern (p : Problem) : Problem := do
let alts := p.alts.map fun alt => match alt.patterns with
| Pattern.val (Expr.lit (Literal.natVal 0) _) :: ps => { alt with patterns := Pattern.ctor `Nat.zero [] [] [] :: ps }
| Pattern.val (Expr.lit (Literal.natVal (n+1)) _) :: ps => { alt with patterns := Pattern.ctor `Nat.succ [] [] [Pattern.val (mkNatLit n)] :: ps }
| _ => alt
{ p with alts := alts }
private def traceStep (msg : String) : StateRefT State MetaM Unit :=
trace[Meta.Match.match]! "{msg} step"
private def traceState (p : Problem) : MetaM Unit :=
withGoalOf p (traceM `Meta.Match.match p.toMessageData)
private def throwNonSupported (p : Problem) : MetaM Unit :=
withGoalOf p do
let msg ← p.toMessageData
throwError! "failed to compile pattern matching, stuck at{indentD msg}"
def isCurrVarInductive (p : Problem) : MetaM Bool := do
match p.vars with
| [] => pure false
| x::_ => withGoalOf p do
let val? ← getInductiveVal? x
pure val?.isSome
private def checkNextPatternTypes (p : Problem) : MetaM Unit := do
match p.vars with
| [] => return ()
| x::_ => withGoalOf p do
for alt in p.alts do
withRef alt.ref do
match alt.patterns with
| [] => pure ()
| p::_ =>
let e ← p.toExpr
let xType ← inferType x
let eType ← inferType e
unless (← isDefEq xType eType) do
throwError! "pattern{indentExpr e}\n{← mkHasTypeButIsExpectedMsg eType xType}"
private partial def process (p : Problem) : StateRefT State MetaM Unit := withIncRecDepth do
traceState p
let isInductive ← liftM $ isCurrVarInductive p
if isDone p then
processLeaf p
else if hasAsPattern p then
traceStep ("as-pattern")
let p ← processAsPattern p
process p
else if isNatValueTransition p then
traceStep ("nat value to constructor")
process (expandNatValuePattern p)
else if !isNextVar p then
traceStep ("non variable")
let p ← processNonVariable p
process p
else if isInductive && isConstructorTransition p then
let ps ← processConstructor p
ps.forM process
else if isVariableTransition p then
traceStep ("variable")
let p ← processVariable p
process p
else if isValueTransition p then
let ps ← processValue p
ps.forM process
else if isArrayLitTransition p then
let ps ← processArrayLit p
ps.forM process
else if hasNatValPattern p then
-- This branch is reachable when `p`, for example, is just values without an else-alternative.
-- We added it just to get better error messages.
traceStep ("nat value to constructor")
process (expandNatValuePattern p)
else
checkNextPatternTypes p
throwNonSupported p
private def getUElimPos? (matcherLevels : List Level) (uElim : Level) : MetaM (Option Nat) :=
if uElim == levelZero then
pure none
else match matcherLevels.toArray.indexOf? uElim with
| none => throwError "dependent match elimination failed, universe level not found"
| some pos => pure $ some pos.val
/- See comment at `mkMatcher` before `mkAuxDefinition` -/
builtin_initialize
registerOption `bootstrap.gen_matcher_code { defValue := true, group := "bootstrap", descr := "disable code generation for auxiliary matcher function" }
def generateMatcherCode (opts : Options) : Bool :=
opts.get `bootstrap.gen_matcher_code true
/-
Create a dependent matcher for `matchType` where `matchType` is of the form
`(a_1 : A_1) -> (a_2 : A_2[a_1]) -> ... -> (a_n : A_n[a_1, a_2, ... a_{n-1}]) -> B[a_1, ..., a_n]`
where `n = numDiscrs`, and the `lhss` are the left-hand-sides of the `match`-expression alternatives.
Each `AltLHS` has a list of local declarations and a list of patterns.
The number of patterns must be the same in each `AltLHS`.
The generated matcher has the structure described at `MatcherInfo`. The motive argument is of the form
`(motive : (a_1 : A_1) -> (a_2 : A_2[a_1]) -> ... -> (a_n : A_n[a_1, a_2, ... a_{n-1}]) -> Sort v)`
where `v` is a universe parameter or 0 if `B[a_1, ..., a_n]` is a proposition. -/
def mkMatcher (matcherName : Name) (matchType : Expr) (numDiscrs : Nat) (lhss : List AltLHS) : MetaM MatcherResult :=
forallBoundedTelescope matchType numDiscrs fun majors matchTypeBody => do
checkNumPatterns majors lhss
/- We generate an matcher that can eliminate using different motives with different universe levels.
`uElim` is the universe level the caller wants to eliminate to.
If it is not levelZero, we create a matcher that can eliminate in any universe level.
This is useful for implementing `MatcherApp.addArg` because it may have to change the universe level. -/
let uElim ← getLevel matchTypeBody
let uElimGen ← if uElim == levelZero then pure levelZero else mkFreshLevelMVar
let motiveType ← mkForallFVars majors (mkSort uElimGen)
withLocalDeclD `motive motiveType fun motive => do
trace[Meta.Match.debug]! "motiveType: {motiveType}"
let mvarType := mkAppN motive majors
trace[Meta.Match.debug]! "target: {mvarType}"
withAlts motive lhss fun alts minors => do
let mvar ← mkFreshExprMVar mvarType
let examples := majors.toList.map fun major => Example.var major.fvarId!
let (_, s) ← (process { mvarId := mvar.mvarId!, vars := majors.toList, alts := alts, examples := examples }).run {}
let args := #[motive] ++ majors ++ minors.map Prod.fst
let type ← mkForallFVars args mvarType
let val ← mkLambdaFVars args mvar
trace[Meta.Match.debug]! "matcher value: {val}\ntype: {type}"
/- The option `bootstrap.gen_matcher_code` is a helper hack. It is useful, for example,
for compiling `src/Init/Data/Int`. It is needed because the compiler uses `Int.decLt`
for generating code for `Int.casesOn` applications, but `Int.casesOn` is used to
give the reference implementation for
```
@[extern "lean_int_neg"] def neg (n : @& Int) : Int :=
match n with
| ofNat n => negOfNat n
| negSucc n => succ n
```
which is defined **before** `Int.decLt` -/
let matcher ← mkAuxDefinition matcherName type val (compile := generateMatcherCode (← getOptions))
trace[Meta.Match.debug]! "matcher levels: {matcher.getAppFn.constLevels!}, uElim: {uElimGen}"
let uElimPos? ← getUElimPos? matcher.getAppFn.constLevels! uElimGen
discard <| isLevelDefEq uElimGen uElim
addMatcherInfo matcherName { numParams := matcher.getAppNumArgs, numDiscrs := numDiscrs, altNumParams := minors.map Prod.snd, uElimPos? := uElimPos? }
setInlineAttribute matcherName
trace[Meta.Match.debug]! "matcher: {matcher}"
let unusedAltIdxs := lhss.length.fold (init := []) fun i r =>
if s.used.contains i then r else i::r
pure { matcher := matcher, counterExamples := s.counterExamples, unusedAltIdxs := unusedAltIdxs.reverse }
end Match
/- Auxiliary function for MatcherApp.addArg -/
private partial def updateAlts (typeNew : Expr) (altNumParams : Array Nat) (alts : Array Expr) (i : Nat) : MetaM (Array Nat × Array Expr) := do
if h : i < alts.size then
let alt := alts.get ⟨i, h⟩
let numParams := altNumParams[i]
let typeNew ← whnfD typeNew
match typeNew with
| Expr.forallE n d b _ =>
let alt ← forallBoundedTelescope d (some numParams) fun xs d => do
let alt ← try instantiateLambda alt xs catch _ => throwError "unexpected matcher application, insufficient number of parameters in alternative"
forallBoundedTelescope d (some 1) fun x d => do
let alt ← mkLambdaFVars x alt -- x is the new argument we are adding to the alternative
let alt ← mkLambdaFVars xs alt
pure alt
updateAlts (b.instantiate1 alt) (altNumParams.set! i (numParams+1)) (alts.set ⟨i, h⟩ alt) (i+1)
| _ => throwError "unexpected type at MatcherApp.addArg"
else
pure (altNumParams, alts)
/- Given
- matcherApp `match_i As (fun xs => motive[xs]) discrs (fun ys_1 => (alt_1 : motive (C_1[ys_1])) ... (fun ys_n => (alt_n : motive (C_n[ys_n]) remaining`, and
- expression `e : B[discrs]`,
Construct the term
`match_i As (fun xs => B[xs] -> motive[xs]) discrs (fun ys_1 (y : B[C_1[ys_1]]) => alt_1) ... (fun ys_n (y : B[C_n[ys_n]]) => alt_n) e remaining`, and
We use `kabstract` to abstract the discriminants from `B[discrs]`.
This method assumes
- the `matcherApp.motive` is a lambda abstraction where `xs.size == discrs.size`
- each alternative is a lambda abstraction where `ys_i.size == matcherApp.altNumParams[i]`
-/
def MatcherApp.addArg (matcherApp : MatcherApp) (e : Expr) : MetaM MatcherApp :=
lambdaTelescope matcherApp.motive fun motiveArgs motiveBody => do
unless motiveArgs.size == matcherApp.discrs.size do
-- This error can only happen if someone implemented a transformation that rewrites the motive created by `mkMatcher`.
throwError! "unexpected matcher application, motive must be lambda expression with #{matcherApp.discrs.size} arguments"
let eType ← inferType e
let eTypeAbst ← matcherApp.discrs.size.foldRevM (init := eType) fun i eTypeAbst => do
let motiveArg := motiveArgs[i]
let discr := matcherApp.discrs[i]
let eTypeAbst ← kabstract eTypeAbst discr
pure $ eTypeAbst.instantiate1 motiveArg
let motiveBody ← mkArrow eTypeAbst motiveBody
let matcherLevels ← match matcherApp.uElimPos? with
| none => pure matcherApp.matcherLevels
| some pos =>
let uElim ← getLevel motiveBody
pure $ matcherApp.matcherLevels.set! pos uElim
let motive ← mkLambdaFVars motiveArgs motiveBody
-- Construct `aux` `match_i As (fun xs => B[xs] → motive[xs]) discrs`, and infer its type `auxType`.
-- We use `auxType` to infer the type `B[C_i[ys_i]]` of the new argument in each alternative.
let aux := mkAppN (mkConst matcherApp.matcherName matcherLevels.toList) matcherApp.params
let aux := mkApp aux motive
let aux := mkAppN aux matcherApp.discrs
trace! `Meta.debug aux
check aux
unless (← isTypeCorrect aux) do
throwError "failed to add argument to matcher application, type error when constructing the new motive"
let auxType ← inferType aux
let (altNumParams, alts) ← updateAlts auxType matcherApp.altNumParams matcherApp.alts 0
pure { matcherApp with
matcherLevels := matcherLevels,
motive := motive,
alts := alts,
altNumParams := altNumParams,
remaining := #[e] ++ matcherApp.remaining
}
builtin_initialize
registerTraceClass `Meta.Match.match
registerTraceClass `Meta.Match.debug
registerTraceClass `Meta.Match.unify
end Lean.Meta
|
45dc925ba81db06cb5dc51f1c2545dac38c755fe | d406927ab5617694ec9ea7001f101b7c9e3d9702 | /src/measure_theory/measure/finite_measure.lean | 08a21dd2b591e79253440b26446b003e33dfa332 | [
"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 | 33,204 | lean | /-
Copyright (c) 2021 Kalle Kytölä. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kalle Kytölä
-/
import topology.continuous_function.bounded
import topology.algebra.module.weak_dual
import measure_theory.integral.bochner
/-!
# Finite measures
This file defines the type of finite measures on a given measurable space. When the underlying
space has a topology and the measurable space structure (sigma algebra) is finer than the Borel
sigma algebra, then the type of finite measures is equipped with the topology of weak convergence
of measures. The topology of weak convergence is the coarsest topology w.r.t. which
for every bounded continuous `ℝ≥0`-valued function `f`, the integration of `f` against the
measure is continuous.
## Main definitions
The main definitions are
* the type `measure_theory.finite_measure Ω` with the topology of weak convergence;
* `measure_theory.finite_measure.to_weak_dual_bcnn : finite_measure Ω → (weak_dual ℝ≥0 (Ω →ᵇ ℝ≥0))`
allowing to interpret a finite measure as a continuous linear functional on the space of
bounded continuous nonnegative functions on `Ω`. This is used for the definition of the
topology of weak convergence.
## Main results
* Finite measures `μ` on `Ω` give rise to continuous linear functionals on the space of
bounded continuous nonnegative functions on `Ω` via integration:
`measure_theory.finite_measure.to_weak_dual_bcnn : finite_measure Ω → (weak_dual ℝ≥0 (Ω →ᵇ ℝ≥0))`
* `measure_theory.finite_measure.tendsto_iff_forall_integral_tendsto`: Convergence of finite
measures is characterized by the convergence of integrals of all bounded continuous functions.
This shows that the chosen definition of topology coincides with the common textbook definition
of weak convergence of measures. A similar characterization by the convergence of integrals (in
the `measure_theory.lintegral` sense) of all bounded continuous nonnegative functions is
`measure_theory.finite_measure.tendsto_iff_forall_lintegral_tendsto`.
## Implementation notes
The topology of weak convergence of finite Borel measures is defined using a mapping from
`measure_theory.finite_measure Ω` to `weak_dual ℝ≥0 (Ω →ᵇ ℝ≥0)`, inheriting the topology from the
latter.
The implementation of `measure_theory.finite_measure Ω` and is directly as a subtype of
`measure_theory.measure Ω`, and the coercion to a function is the composition `ennreal.to_nnreal`
and the coercion to function of `measure_theory.measure Ω`. Another alternative would have been to
use a bijection with `measure_theory.vector_measure Ω ℝ≥0` as an intermediate step. Some
considerations:
* Potential advantages of using the `nnreal`-valued vector measure alternative:
* The coercion to function would avoid need to compose with `ennreal.to_nnreal`, the
`nnreal`-valued API could be more directly available.
* Potential drawbacks of the vector measure alternative:
* The coercion to function would lose monotonicity, as non-measurable sets would be defined to
have measure 0.
* No integration theory directly. E.g., the topology definition requires
`measure_theory.lintegral` w.r.t. a coercion to `measure_theory.measure Ω` in any case.
## References
* [Billingsley, *Convergence of probability measures*][billingsley1999]
## Tags
weak convergence of measures, finite measure
-/
noncomputable theory
open measure_theory
open set
open filter
open bounded_continuous_function
open_locale topological_space ennreal nnreal bounded_continuous_function
namespace measure_theory
namespace finite_measure
section finite_measure
/-! ### Finite measures
In this section we define the `Type` of `finite_measure Ω`, when `Ω` is a measurable space. Finite
measures on `Ω` are a module over `ℝ≥0`.
If `Ω` is moreover a topological space and the sigma algebra on `Ω` is finer than the Borel sigma
algebra (i.e. `[opens_measurable_space Ω]`), then `finite_measure Ω` is equipped with the topology
of weak convergence of measures. This is implemented by defining a pairing of finite measures `μ`
on `Ω` with continuous bounded nonnegative functions `f : Ω →ᵇ ℝ≥0` via integration, and using the
associated weak topology (essentially the weak-star topology on the dual of `Ω →ᵇ ℝ≥0`).
-/
variables {Ω : Type*} [measurable_space Ω]
/-- Finite measures are defined as the subtype of measures that have the property of being finite
measures (i.e., their total mass is finite). -/
def _root_.measure_theory.finite_measure (Ω : Type*) [measurable_space Ω] : Type* :=
{μ : measure Ω // is_finite_measure μ}
/-- A finite measure can be interpreted as a measure. -/
instance : has_coe (finite_measure Ω) (measure_theory.measure Ω) := coe_subtype
instance is_finite_measure (μ : finite_measure Ω) :
is_finite_measure (μ : measure Ω) := μ.prop
instance : has_coe_to_fun (finite_measure Ω) (λ _, set Ω → ℝ≥0) :=
⟨λ μ s, (μ s).to_nnreal⟩
lemma coe_fn_eq_to_nnreal_coe_fn_to_measure (ν : finite_measure Ω) :
(ν : set Ω → ℝ≥0) = λ s, ((ν : measure Ω) s).to_nnreal := rfl
@[simp] lemma ennreal_coe_fn_eq_coe_fn_to_measure (ν : finite_measure Ω) (s : set Ω) :
(ν s : ℝ≥0∞) = (ν : measure Ω) s := ennreal.coe_to_nnreal (measure_lt_top ↑ν s).ne
@[simp] lemma val_eq_to_measure (ν : finite_measure Ω) : ν.val = (ν : measure Ω) := rfl
lemma coe_injective : function.injective (coe : finite_measure Ω → measure Ω) :=
subtype.coe_injective
lemma apply_mono (μ : finite_measure Ω) {s₁ s₂ : set Ω} (h : s₁ ⊆ s₂) :
μ s₁ ≤ μ s₂ :=
begin
change ((μ : measure Ω) s₁).to_nnreal ≤ ((μ : measure Ω) s₂).to_nnreal,
have key : (μ : measure Ω) s₁ ≤ (μ : measure Ω) s₂ := (μ : measure Ω).mono h,
apply (ennreal.to_nnreal_le_to_nnreal (measure_ne_top _ s₁) (measure_ne_top _ s₂)).mpr key,
end
/-- The (total) mass of a finite measure `μ` is `μ univ`, i.e., the cast to `nnreal` of
`(μ : measure Ω) univ`. -/
def mass (μ : finite_measure Ω) : ℝ≥0 := μ univ
@[simp] lemma ennreal_mass {μ : finite_measure Ω} :
(μ.mass : ℝ≥0∞) = (μ : measure Ω) univ := ennreal_coe_fn_eq_coe_fn_to_measure μ set.univ
instance has_zero : has_zero (finite_measure Ω) :=
{ zero := ⟨0, measure_theory.is_finite_measure_zero⟩ }
@[simp] lemma zero.mass : (0 : finite_measure Ω).mass = 0 := rfl
@[simp] lemma mass_zero_iff (μ : finite_measure Ω) : μ.mass = 0 ↔ μ = 0 :=
begin
refine ⟨λ μ_mass, _, (λ hμ, by simp only [hμ, zero.mass])⟩,
ext1,
apply measure.measure_univ_eq_zero.mp,
rwa [← ennreal_mass, ennreal.coe_eq_zero],
end
lemma mass_nonzero_iff (μ : finite_measure Ω) : μ.mass ≠ 0 ↔ μ ≠ 0 :=
begin
rw not_iff_not,
exact finite_measure.mass_zero_iff μ,
end
@[ext] lemma eq_of_forall_measure_apply_eq (μ ν : finite_measure Ω)
(h : ∀ (s : set Ω), measurable_set s → (μ : measure Ω) s = (ν : measure Ω) s) :
μ = ν :=
by { ext1, ext1 s s_mble, exact h s s_mble, }
lemma eq_of_forall_apply_eq (μ ν : finite_measure Ω)
(h : ∀ (s : set Ω), measurable_set s → μ s = ν s) :
μ = ν :=
begin
ext1 s s_mble,
simpa [ennreal_coe_fn_eq_coe_fn_to_measure] using congr_arg (coe : ℝ≥0 → ℝ≥0∞) (h s s_mble),
end
instance : inhabited (finite_measure Ω) := ⟨0⟩
instance : has_add (finite_measure Ω) :=
{ add := λ μ ν, ⟨μ + ν, measure_theory.is_finite_measure_add⟩ }
variables {R : Type*} [has_smul R ℝ≥0] [has_smul R ℝ≥0∞] [is_scalar_tower R ℝ≥0 ℝ≥0∞]
[is_scalar_tower R ℝ≥0∞ ℝ≥0∞]
instance : has_smul R (finite_measure Ω) :=
{ smul := λ (c : R) μ, ⟨c • μ, measure_theory.is_finite_measure_smul_of_nnreal_tower⟩, }
@[simp, norm_cast] lemma coe_zero : (coe : finite_measure Ω → measure Ω) 0 = 0 := rfl
@[simp, norm_cast] lemma coe_add (μ ν : finite_measure Ω) : ↑(μ + ν) = (↑μ + ↑ν : measure Ω) := rfl
@[simp, norm_cast] lemma coe_smul (c : R) (μ : finite_measure Ω) :
↑(c • μ) = (c • ↑μ : measure Ω) := rfl
@[simp, norm_cast] lemma coe_fn_zero :
(⇑(0 : finite_measure Ω) : set Ω → ℝ≥0) = (0 : set Ω → ℝ≥0) := by { funext, refl, }
@[simp, norm_cast] lemma coe_fn_add (μ ν : finite_measure Ω) :
(⇑(μ + ν) : set Ω → ℝ≥0) = (⇑μ + ⇑ν : set Ω → ℝ≥0) :=
by { funext, simp [← ennreal.coe_eq_coe], }
@[simp, norm_cast] lemma coe_fn_smul [is_scalar_tower R ℝ≥0 ℝ≥0] (c : R) (μ : finite_measure Ω) :
(⇑(c • μ) : set Ω → ℝ≥0) = c • (⇑μ : set Ω → ℝ≥0) :=
by { funext, simp [← ennreal.coe_eq_coe, ennreal.coe_smul], }
instance : add_comm_monoid (finite_measure Ω) :=
coe_injective.add_comm_monoid coe coe_zero coe_add (λ _ _, coe_smul _ _)
/-- Coercion is an `add_monoid_hom`. -/
@[simps]
def coe_add_monoid_hom : finite_measure Ω →+ measure Ω :=
{ to_fun := coe, map_zero' := coe_zero, map_add' := coe_add }
instance {Ω : Type*} [measurable_space Ω] : module ℝ≥0 (finite_measure Ω) :=
function.injective.module _ coe_add_monoid_hom coe_injective coe_smul
@[simp] lemma coe_fn_smul_apply [is_scalar_tower R ℝ≥0 ℝ≥0]
(c : R) (μ : finite_measure Ω) (s : set Ω) :
(c • μ) s = c • (μ s) :=
by { simp only [coe_fn_smul, pi.smul_apply], }
/-- Restrict a finite measure μ to a set A. -/
def restrict (μ : finite_measure Ω) (A : set Ω) : finite_measure Ω :=
{ val := (μ : measure Ω).restrict A,
property := measure_theory.is_finite_measure_restrict μ A, }
lemma restrict_measure_eq (μ : finite_measure Ω) (A : set Ω) :
(μ.restrict A : measure Ω) = (μ : measure Ω).restrict A := rfl
lemma restrict_apply_measure (μ : finite_measure Ω) (A : set Ω)
{s : set Ω} (s_mble : measurable_set s) :
(μ.restrict A : measure Ω) s = (μ : measure Ω) (s ∩ A) :=
measure.restrict_apply s_mble
lemma restrict_apply (μ : finite_measure Ω) (A : set Ω)
{s : set Ω} (s_mble : measurable_set s) :
(μ.restrict A) s = μ (s ∩ A) :=
begin
apply congr_arg ennreal.to_nnreal,
exact measure.restrict_apply s_mble,
end
lemma restrict_mass (μ : finite_measure Ω) (A : set Ω) :
(μ.restrict A).mass = μ A :=
by simp only [mass, restrict_apply μ A measurable_set.univ, univ_inter]
lemma restrict_eq_zero_iff (μ : finite_measure Ω) (A : set Ω) :
μ.restrict A = 0 ↔ μ A = 0 :=
by rw [← mass_zero_iff, restrict_mass]
lemma restrict_nonzero_iff (μ : finite_measure Ω) (A : set Ω) :
μ.restrict A ≠ 0 ↔ μ A ≠ 0 :=
by rw [← mass_nonzero_iff, restrict_mass]
variables [topological_space Ω]
/-- The pairing of a finite (Borel) measure `μ` with a nonnegative bounded continuous
function is obtained by (Lebesgue) integrating the (test) function against the measure.
This is `finite_measure.test_against_nn`. -/
def test_against_nn (μ : finite_measure Ω) (f : Ω →ᵇ ℝ≥0) : ℝ≥0 :=
(∫⁻ ω, f ω ∂(μ : measure Ω)).to_nnreal
lemma _root_.bounded_continuous_function.nnreal.to_ennreal_comp_measurable {Ω : Type*}
[topological_space Ω] [measurable_space Ω] [opens_measurable_space Ω] (f : Ω →ᵇ ℝ≥0) :
measurable (λ ω, (f ω : ℝ≥0∞)) :=
measurable_coe_nnreal_ennreal.comp f.continuous.measurable
lemma _root_.measure_theory.lintegral_lt_top_of_bounded_continuous_to_nnreal
(μ : measure Ω) [is_finite_measure μ] (f : Ω →ᵇ ℝ≥0) :
∫⁻ ω, f ω ∂μ < ∞ :=
begin
apply is_finite_measure.lintegral_lt_top_of_bounded_to_ennreal,
use nndist f 0,
intros x,
have key := bounded_continuous_function.nnreal.upper_bound f x,
rw ennreal.coe_le_coe,
have eq : nndist f 0 = ⟨dist f 0, dist_nonneg⟩,
{ ext,
simp only [real.coe_to_nnreal', max_eq_left_iff, subtype.coe_mk, coe_nndist], },
rwa eq at key,
end
@[simp] lemma test_against_nn_coe_eq {μ : finite_measure Ω} {f : Ω →ᵇ ℝ≥0} :
(μ.test_against_nn f : ℝ≥0∞) = ∫⁻ ω, f ω ∂(μ : measure Ω) :=
ennreal.coe_to_nnreal (lintegral_lt_top_of_bounded_continuous_to_nnreal _ f).ne
lemma test_against_nn_const (μ : finite_measure Ω) (c : ℝ≥0) :
μ.test_against_nn (bounded_continuous_function.const Ω c) = c * μ.mass :=
by simp [← ennreal.coe_eq_coe]
lemma test_against_nn_mono (μ : finite_measure Ω)
{f g : Ω →ᵇ ℝ≥0} (f_le_g : (f : Ω → ℝ≥0) ≤ g) :
μ.test_against_nn f ≤ μ.test_against_nn g :=
begin
simp only [←ennreal.coe_le_coe, test_against_nn_coe_eq],
exact lintegral_mono (λ ω, ennreal.coe_mono (f_le_g ω)),
end
@[simp] lemma test_against_nn_zero (μ : finite_measure Ω) : μ.test_against_nn 0 = 0 :=
by simpa only [zero_mul] using μ.test_against_nn_const 0
@[simp] lemma test_against_nn_one (μ : finite_measure Ω) : μ.test_against_nn 1 = μ.mass :=
begin
simp only [test_against_nn, coe_one, pi.one_apply, ennreal.coe_one, lintegral_one],
refl,
end
@[simp] lemma zero.test_against_nn_apply (f : Ω →ᵇ ℝ≥0) :
(0 : finite_measure Ω).test_against_nn f = 0 :=
by simp only [test_against_nn, coe_zero, lintegral_zero_measure, ennreal.zero_to_nnreal]
lemma zero.test_against_nn : (0 : finite_measure Ω).test_against_nn = 0 :=
by { funext, simp only [zero.test_against_nn_apply, pi.zero_apply], }
@[simp] lemma smul_test_against_nn_apply (c : ℝ≥0) (μ : finite_measure Ω) (f : Ω →ᵇ ℝ≥0) :
(c • μ).test_against_nn f = c • (μ.test_against_nn f) :=
by simp only [test_against_nn, coe_smul, smul_eq_mul, ← ennreal.smul_to_nnreal,
ennreal.smul_def, lintegral_smul_measure]
variables [opens_measurable_space Ω]
lemma test_against_nn_add (μ : finite_measure Ω) (f₁ f₂ : Ω →ᵇ ℝ≥0) :
μ.test_against_nn (f₁ + f₂) = μ.test_against_nn f₁ + μ.test_against_nn f₂ :=
begin
simp only [←ennreal.coe_eq_coe, bounded_continuous_function.coe_add, ennreal.coe_add,
pi.add_apply, test_against_nn_coe_eq],
exact lintegral_add_left (bounded_continuous_function.nnreal.to_ennreal_comp_measurable _) _
end
lemma test_against_nn_smul [is_scalar_tower R ℝ≥0 ℝ≥0] [pseudo_metric_space R] [has_zero R]
[has_bounded_smul R ℝ≥0]
(μ : finite_measure Ω) (c : R) (f : Ω →ᵇ ℝ≥0) :
μ.test_against_nn (c • f) = c • μ.test_against_nn f :=
begin
simp only [←ennreal.coe_eq_coe, bounded_continuous_function.coe_smul,
test_against_nn_coe_eq, ennreal.coe_smul],
simp_rw [←smul_one_smul ℝ≥0∞ c (f _ : ℝ≥0∞), ←smul_one_smul ℝ≥0∞ c (lintegral _ _ : ℝ≥0∞),
smul_eq_mul],
exact @lintegral_const_mul _ _ (μ : measure Ω) (c • 1) _
(bounded_continuous_function.nnreal.to_ennreal_comp_measurable f),
end
lemma test_against_nn_lipschitz_estimate (μ : finite_measure Ω) (f g : Ω →ᵇ ℝ≥0) :
μ.test_against_nn f ≤ μ.test_against_nn g + (nndist f g) * μ.mass :=
begin
simp only [←μ.test_against_nn_const (nndist f g), ←test_against_nn_add, ←ennreal.coe_le_coe,
bounded_continuous_function.coe_add, const_apply, ennreal.coe_add, pi.add_apply,
coe_nnreal_ennreal_nndist, test_against_nn_coe_eq],
apply lintegral_mono,
have le_dist : ∀ ω, dist (f ω) (g ω) ≤ nndist f g :=
bounded_continuous_function.dist_coe_le_dist,
intros ω,
have le' : f ω ≤ g ω + nndist f g,
{ apply (nnreal.le_add_nndist (f ω) (g ω)).trans,
rw add_le_add_iff_left,
exact dist_le_coe.mp (le_dist ω), },
have le : (f ω : ℝ≥0∞) ≤ (g ω : ℝ≥0∞) + (nndist f g),
by { rw ←ennreal.coe_add, exact ennreal.coe_mono le', },
rwa [coe_nnreal_ennreal_nndist] at le,
end
lemma test_against_nn_lipschitz (μ : finite_measure Ω) :
lipschitz_with μ.mass (λ (f : Ω →ᵇ ℝ≥0), μ.test_against_nn f) :=
begin
rw lipschitz_with_iff_dist_le_mul,
intros f₁ f₂,
suffices : abs (μ.test_against_nn f₁ - μ.test_against_nn f₂ : ℝ) ≤ μ.mass * (dist f₁ f₂),
{ rwa nnreal.dist_eq, },
apply abs_le.mpr,
split,
{ have key' := μ.test_against_nn_lipschitz_estimate f₂ f₁,
rw mul_comm at key',
suffices : ↑(μ.test_against_nn f₂) ≤ ↑(μ.test_against_nn f₁) + ↑(μ.mass) * dist f₁ f₂,
{ linarith, },
have key := nnreal.coe_mono key',
rwa [nnreal.coe_add, nnreal.coe_mul, nndist_comm] at key, },
{ have key' := μ.test_against_nn_lipschitz_estimate f₁ f₂,
rw mul_comm at key',
suffices : ↑(μ.test_against_nn f₁) ≤ ↑(μ.test_against_nn f₂) + ↑(μ.mass) * dist f₁ f₂,
{ linarith, },
have key := nnreal.coe_mono key',
rwa [nnreal.coe_add, nnreal.coe_mul] at key, },
end
/-- Finite measures yield elements of the `weak_dual` of bounded continuous nonnegative
functions via `measure_theory.finite_measure.test_against_nn`, i.e., integration. -/
def to_weak_dual_bcnn (μ : finite_measure Ω) :
weak_dual ℝ≥0 (Ω →ᵇ ℝ≥0) :=
{ to_fun := λ f, μ.test_against_nn f,
map_add' := test_against_nn_add μ,
map_smul' := test_against_nn_smul μ,
cont := μ.test_against_nn_lipschitz.continuous, }
@[simp] lemma coe_to_weak_dual_bcnn (μ : finite_measure Ω) :
⇑μ.to_weak_dual_bcnn = μ.test_against_nn := rfl
@[simp] lemma to_weak_dual_bcnn_apply (μ : finite_measure Ω) (f : Ω →ᵇ ℝ≥0) :
μ.to_weak_dual_bcnn f = (∫⁻ x, f x ∂(μ : measure Ω)).to_nnreal := rfl
/-- The topology of weak convergence on `measure_theory.finite_measure Ω` is inherited (induced)
from the weak-* topology on `weak_dual ℝ≥0 (Ω →ᵇ ℝ≥0)` via the function
`measure_theory.finite_measure.to_weak_dual_bcnn`. -/
instance : topological_space (finite_measure Ω) :=
topological_space.induced to_weak_dual_bcnn infer_instance
lemma to_weak_dual_bcnn_continuous :
continuous (@to_weak_dual_bcnn Ω _ _ _) :=
continuous_induced_dom
/- Integration of (nonnegative bounded continuous) test functions against finite Borel measures
depends continuously on the measure. -/
lemma continuous_test_against_nn_eval (f : Ω →ᵇ ℝ≥0) :
continuous (λ (μ : finite_measure Ω), μ.test_against_nn f) :=
(by apply (weak_bilin.eval_continuous _ _).comp to_weak_dual_bcnn_continuous :
continuous ((λ φ : weak_dual ℝ≥0 (Ω →ᵇ ℝ≥0), φ f) ∘ to_weak_dual_bcnn))
/-- The total mass of a finite measure depends continuously on the measure. -/
lemma continuous_mass : continuous (λ (μ : finite_measure Ω), μ.mass) :=
by { simp_rw ←test_against_nn_one, exact continuous_test_against_nn_eval 1, }
/-- Convergence of finite measures implies the convergence of their total masses. -/
lemma _root_.filter.tendsto.mass {γ : Type*} {F : filter γ}
{μs : γ → finite_measure Ω} {μ : finite_measure Ω} (h : tendsto μs F (𝓝 μ)) :
tendsto (λ i, (μs i).mass) F (𝓝 μ.mass) :=
(continuous_mass.tendsto μ).comp h
lemma tendsto_iff_weak_star_tendsto {γ : Type*} {F : filter γ}
{μs : γ → finite_measure Ω} {μ : finite_measure Ω} :
tendsto μs F (𝓝 μ) ↔ tendsto (λ i, (μs(i)).to_weak_dual_bcnn) F (𝓝 μ.to_weak_dual_bcnn) :=
inducing.tendsto_nhds_iff ⟨rfl⟩
theorem tendsto_iff_forall_to_weak_dual_bcnn_tendsto
{γ : Type*} {F : filter γ} {μs : γ → finite_measure Ω} {μ : finite_measure Ω} :
tendsto μs F (𝓝 μ) ↔
∀ (f : Ω →ᵇ ℝ≥0), tendsto (λ i, (μs i).to_weak_dual_bcnn f) F (𝓝 (μ.to_weak_dual_bcnn f)) :=
by { rw [tendsto_iff_weak_star_tendsto, tendsto_iff_forall_eval_tendsto_top_dual_pairing], refl, }
theorem tendsto_iff_forall_test_against_nn_tendsto
{γ : Type*} {F : filter γ} {μs : γ → finite_measure Ω} {μ : finite_measure Ω} :
tendsto μs F (𝓝 μ) ↔
∀ (f : Ω →ᵇ ℝ≥0), tendsto (λ i, (μs i).test_against_nn f) F (𝓝 (μ.test_against_nn f)) :=
by { rw finite_measure.tendsto_iff_forall_to_weak_dual_bcnn_tendsto, refl, }
/-- If the total masses of finite measures tend to zero, then the measures tend to
zero. This formulation concerns the associated functionals on bounded continuous
nonnegative test functions. See `finite_measure.tendsto_zero_of_tendsto_zero_mass` for
a formulation stating the weak convergence of measures. -/
lemma tendsto_zero_test_against_nn_of_tendsto_zero_mass
{γ : Type*} {F : filter γ} {μs : γ → finite_measure Ω}
(mass_lim : tendsto (λ i, (μs i).mass) F (𝓝 0)) (f : Ω →ᵇ ℝ≥0) :
tendsto (λ i, (μs i).test_against_nn f) F (𝓝 0) :=
begin
apply tendsto_iff_dist_tendsto_zero.mpr,
have obs := λ i, (μs i).test_against_nn_lipschitz_estimate f 0,
simp_rw [test_against_nn_zero, zero_add] at obs,
simp_rw (show ∀ i, dist ((μs i).test_against_nn f) 0 = (μs i).test_against_nn f,
by simp only [dist_nndist, nnreal.nndist_zero_eq_val', eq_self_iff_true,
implies_true_iff]),
refine squeeze_zero (λ i, nnreal.coe_nonneg _) obs _,
simp_rw nnreal.coe_mul,
have lim_pair : tendsto (λ i, (⟨nndist f 0, (μs i).mass⟩ : ℝ × ℝ)) F (𝓝 (⟨nndist f 0, 0⟩)),
{ refine (prod.tendsto_iff _ _).mpr ⟨tendsto_const_nhds, _⟩,
exact (nnreal.continuous_coe.tendsto 0).comp mass_lim, },
have key := tendsto_mul.comp lim_pair,
rwa mul_zero at key,
end
/-- If the total masses of finite measures tend to zero, then the measures tend to zero. -/
lemma tendsto_zero_of_tendsto_zero_mass {γ : Type*} {F : filter γ}
{μs : γ → finite_measure Ω} (mass_lim : tendsto (λ i, (μs i).mass) F (𝓝 0)) :
tendsto μs F (𝓝 0) :=
begin
rw tendsto_iff_forall_test_against_nn_tendsto,
intro f,
convert tendsto_zero_test_against_nn_of_tendsto_zero_mass mass_lim f,
rw [zero.test_against_nn_apply],
end
/-- A characterization of weak convergence in terms of integrals of bounded continuous
nonnegative functions. -/
theorem tendsto_iff_forall_lintegral_tendsto {γ : Type*} {F : filter γ}
{μs : γ → finite_measure Ω} {μ : finite_measure Ω} :
tendsto μs F (𝓝 μ) ↔
∀ (f : Ω →ᵇ ℝ≥0),
tendsto (λ i, (∫⁻ x, (f x) ∂(μs(i) : measure Ω))) F (𝓝 ((∫⁻ x, (f x) ∂(μ : measure Ω)))) :=
begin
rw tendsto_iff_forall_to_weak_dual_bcnn_tendsto,
simp_rw [to_weak_dual_bcnn_apply _ _, ←test_against_nn_coe_eq,
ennreal.tendsto_coe, ennreal.to_nnreal_coe],
end
end finite_measure -- section
section finite_measure_bounded_convergence
/-! ### Bounded convergence results for finite measures
This section is about bounded convergence theorems for finite measures.
-/
variables {Ω : Type*} [measurable_space Ω] [topological_space Ω] [opens_measurable_space Ω]
/-- A bounded convergence theorem for a finite measure:
If bounded continuous non-negative functions are uniformly bounded by a constant and tend to a
limit, then their integrals against the finite measure tend to the integral of the limit.
This formulation assumes:
* the functions tend to a limit along a countably generated filter;
* the limit is in the almost everywhere sense;
* boundedness holds almost everywhere;
* integration is `measure_theory.lintegral`, i.e., the functions and their integrals are
`ℝ≥0∞`-valued.
-/
lemma tendsto_lintegral_nn_filter_of_le_const {ι : Type*} {L : filter ι} [L.is_countably_generated]
(μ : measure Ω) [is_finite_measure μ] {fs : ι → (Ω →ᵇ ℝ≥0)} {c : ℝ≥0}
(fs_le_const : ∀ᶠ i in L, ∀ᵐ (ω : Ω) ∂μ, fs i ω ≤ c) {f : Ω → ℝ≥0}
(fs_lim : ∀ᵐ (ω : Ω) ∂μ, tendsto (λ i, fs i ω) L (𝓝 (f ω))) :
tendsto (λ i, (∫⁻ ω, fs i ω ∂μ)) L (𝓝 (∫⁻ ω, (f ω) ∂μ)) :=
begin
simpa only using tendsto_lintegral_filter_of_dominated_convergence (λ _, c)
(eventually_of_forall ((λ i, (ennreal.continuous_coe.comp (fs i).continuous).measurable)))
_ ((@lintegral_const_lt_top _ _ μ _ _ (@ennreal.coe_ne_top c)).ne) _,
{ simpa only [ennreal.coe_le_coe] using fs_le_const, },
{ simpa only [ennreal.tendsto_coe] using fs_lim, },
end
/-- A bounded convergence theorem for a finite measure:
If a sequence of bounded continuous non-negative functions are uniformly bounded by a constant
and tend pointwise to a limit, then their integrals (`measure_theory.lintegral`) against the finite
measure tend to the integral of the limit.
A related result with more general assumptions is
`measure_theory.finite_measure.tendsto_lintegral_nn_filter_of_le_const`.
-/
lemma tendsto_lintegral_nn_of_le_const (μ : finite_measure Ω) {fs : ℕ → (Ω →ᵇ ℝ≥0)} {c : ℝ≥0}
(fs_le_const : ∀ n ω, fs n ω ≤ c) {f : Ω → ℝ≥0}
(fs_lim : ∀ ω, tendsto (λ n, fs n ω) at_top (𝓝 (f ω))) :
tendsto (λ n, (∫⁻ ω, fs n ω ∂(μ : measure Ω))) at_top (𝓝 (∫⁻ ω, (f ω) ∂(μ : measure Ω))) :=
tendsto_lintegral_nn_filter_of_le_const μ
(eventually_of_forall (λ n, eventually_of_forall (fs_le_const n))) (eventually_of_forall fs_lim)
/-- A bounded convergence theorem for a finite measure:
If bounded continuous non-negative functions are uniformly bounded by a constant and tend to a
limit, then their integrals against the finite measure tend to the integral of the limit.
This formulation assumes:
* the functions tend to a limit along a countably generated filter;
* the limit is in the almost everywhere sense;
* boundedness holds almost everywhere;
* integration is the pairing against non-negative continuous test functions
(`measure_theory.finite_measure.test_against_nn`).
A related result using `measure_theory.lintegral` for integration is
`measure_theory.finite_measure.tendsto_lintegral_nn_filter_of_le_const`.
-/
lemma tendsto_test_against_nn_filter_of_le_const {ι : Type*} {L : filter ι}
[L.is_countably_generated] {μ : finite_measure Ω} {fs : ι → (Ω →ᵇ ℝ≥0)} {c : ℝ≥0}
(fs_le_const : ∀ᶠ i in L, ∀ᵐ (ω : Ω) ∂(μ : measure Ω), fs i ω ≤ c) {f : Ω →ᵇ ℝ≥0}
(fs_lim : ∀ᵐ (ω : Ω) ∂(μ : measure Ω), tendsto (λ i, fs i ω) L (𝓝 (f ω))) :
tendsto (λ i, μ.test_against_nn (fs i)) L (𝓝 (μ.test_against_nn f)) :=
begin
apply (ennreal.tendsto_to_nnreal
(lintegral_lt_top_of_bounded_continuous_to_nnreal (μ : measure Ω) f).ne).comp,
exact tendsto_lintegral_nn_filter_of_le_const μ fs_le_const fs_lim,
end
/-- A bounded convergence theorem for a finite measure:
If a sequence of bounded continuous non-negative functions are uniformly bounded by a constant and
tend pointwise to a limit, then their integrals (`measure_theory.finite_measure.test_against_nn`)
against the finite measure tend to the integral of the limit.
Related results:
* `measure_theory.finite_measure.tendsto_test_against_nn_filter_of_le_const`:
more general assumptions
* `measure_theory.finite_measure.tendsto_lintegral_nn_of_le_const`:
using `measure_theory.lintegral` for integration.
-/
lemma tendsto_test_against_nn_of_le_const {μ : finite_measure Ω}
{fs : ℕ → (Ω →ᵇ ℝ≥0)} {c : ℝ≥0} (fs_le_const : ∀ n ω, fs n ω ≤ c) {f : Ω →ᵇ ℝ≥0}
(fs_lim : ∀ ω, tendsto (λ n, fs n ω) at_top (𝓝 (f ω))) :
tendsto (λ n, μ.test_against_nn (fs n)) at_top (𝓝 (μ.test_against_nn f)) :=
tendsto_test_against_nn_filter_of_le_const
(eventually_of_forall (λ n, eventually_of_forall (fs_le_const n))) (eventually_of_forall fs_lim)
end finite_measure_bounded_convergence -- section
section finite_measure_convergence_by_bounded_continuous_functions
/-! ### Weak convergence of finite measures with bounded continuous real-valued functions
In this section we characterize the weak convergence of finite measures by the usual (defining)
condition that the integrals of all bounded continuous real-valued functions converge.
-/
variables {Ω : Type*} [measurable_space Ω] [topological_space Ω] [opens_measurable_space Ω]
lemma integrable_of_bounded_continuous_to_nnreal
(μ : measure Ω) [is_finite_measure μ] (f : Ω →ᵇ ℝ≥0) :
integrable ((coe : ℝ≥0 → ℝ) ∘ ⇑f) μ :=
begin
refine ⟨(nnreal.continuous_coe.comp f.continuous).measurable.ae_strongly_measurable, _⟩,
simp only [has_finite_integral, nnreal.nnnorm_eq],
exact lintegral_lt_top_of_bounded_continuous_to_nnreal _ f,
end
lemma integrable_of_bounded_continuous_to_real
(μ : measure Ω) [is_finite_measure μ] (f : Ω →ᵇ ℝ) :
integrable ⇑f μ :=
begin
refine ⟨f.continuous.measurable.ae_strongly_measurable, _⟩,
have aux : (coe : ℝ≥0 → ℝ) ∘ ⇑f.nnnorm = (λ x, ‖f x‖),
{ ext ω,
simp only [function.comp_app, bounded_continuous_function.nnnorm_coe_fun_eq, coe_nnnorm], },
apply (has_finite_integral_iff_norm ⇑f).mpr,
rw ← of_real_integral_eq_lintegral_of_real,
{ exact ennreal.of_real_lt_top, },
{ exact aux ▸ integrable_of_bounded_continuous_to_nnreal μ f.nnnorm, },
{ exact eventually_of_forall (λ ω, norm_nonneg (f ω)), },
end
lemma _root_.bounded_continuous_function.integral_eq_integral_nnreal_part_sub
(μ : measure Ω) [is_finite_measure μ] (f : Ω →ᵇ ℝ) :
∫ ω, f ω ∂μ = ∫ ω, f.nnreal_part ω ∂μ - ∫ ω, (-f).nnreal_part ω ∂μ :=
by simp only [f.self_eq_nnreal_part_sub_nnreal_part_neg,
pi.sub_apply, integral_sub, integrable_of_bounded_continuous_to_nnreal]
lemma lintegral_lt_top_of_bounded_continuous_to_real
{Ω : Type*} [measurable_space Ω] [topological_space Ω] (μ : measure Ω) [is_finite_measure μ]
(f : Ω →ᵇ ℝ) :
∫⁻ ω, ennreal.of_real (f ω) ∂μ < ∞ :=
lintegral_lt_top_of_bounded_continuous_to_nnreal _ f.nnreal_part
theorem tendsto_of_forall_integral_tendsto
{γ : Type*} {F : filter γ} {μs : γ → finite_measure Ω} {μ : finite_measure Ω}
(h : (∀ (f : Ω →ᵇ ℝ),
tendsto (λ i, (∫ x, (f x) ∂(μs i : measure Ω))) F (𝓝 ((∫ x, (f x) ∂(μ : measure Ω)))))) :
tendsto μs F (𝓝 μ) :=
begin
apply (@tendsto_iff_forall_lintegral_tendsto Ω _ _ _ γ F μs μ).mpr,
intro f,
have key := @ennreal.tendsto_to_real_iff _ F
_ (λ i, (lintegral_lt_top_of_bounded_continuous_to_nnreal (μs i : measure Ω) f).ne)
_ (lintegral_lt_top_of_bounded_continuous_to_nnreal (μ : measure Ω) f).ne,
simp only [ennreal.of_real_coe_nnreal] at key,
apply key.mp,
have lip : lipschitz_with 1 (coe : ℝ≥0 → ℝ), from isometry_subtype_coe.lipschitz,
set f₀ := bounded_continuous_function.comp _ lip f with def_f₀,
have f₀_eq : ⇑f₀ = (coe : ℝ≥0 → ℝ) ∘ ⇑f, by refl,
have f₀_nn : 0 ≤ ⇑f₀, from λ _, by simp only [f₀_eq, pi.zero_apply, nnreal.zero_le_coe],
have f₀_ae_nn : 0 ≤ᵐ[(μ : measure Ω)] ⇑f₀, from eventually_of_forall f₀_nn,
have f₀_ae_nns : ∀ i, 0 ≤ᵐ[(μs i : measure Ω)] ⇑f₀, from λ i, eventually_of_forall f₀_nn,
have aux := integral_eq_lintegral_of_nonneg_ae f₀_ae_nn
f₀.continuous.measurable.ae_strongly_measurable,
have auxs := λ i, integral_eq_lintegral_of_nonneg_ae (f₀_ae_nns i)
f₀.continuous.measurable.ae_strongly_measurable,
simp only [f₀_eq, ennreal.of_real_coe_nnreal] at aux auxs,
simpa only [←aux, ←auxs] using h f₀,
end
lemma _root_.bounded_continuous_function.nnreal.to_real_lintegral_eq_integral
(f : Ω →ᵇ ℝ≥0) (μ : measure Ω) :
(∫⁻ x, (f x : ℝ≥0∞) ∂μ).to_real = (∫ x, f x ∂μ) :=
begin
rw integral_eq_lintegral_of_nonneg_ae _
(nnreal.continuous_coe.comp f.continuous).measurable.ae_strongly_measurable,
{ simp only [ennreal.of_real_coe_nnreal], },
{ apply eventually_of_forall,
simp only [pi.zero_apply, nnreal.zero_le_coe, implies_true_iff], },
end
/-- A characterization of weak convergence in terms of integrals of bounded continuous
real-valued functions. -/
theorem tendsto_iff_forall_integral_tendsto
{γ : Type*} {F : filter γ} {μs : γ → finite_measure Ω} {μ : finite_measure Ω} :
tendsto μs F (𝓝 μ) ↔
∀ (f : Ω →ᵇ ℝ),
tendsto (λ i, (∫ x, (f x) ∂(μs i : measure Ω))) F (𝓝 ((∫ x, (f x) ∂(μ : measure Ω)))) :=
begin
refine ⟨_, tendsto_of_forall_integral_tendsto⟩,
rw tendsto_iff_forall_lintegral_tendsto,
intros h f,
simp_rw bounded_continuous_function.integral_eq_integral_nnreal_part_sub,
set f_pos := f.nnreal_part with def_f_pos,
set f_neg := (-f).nnreal_part with def_f_neg,
have tends_pos := (ennreal.tendsto_to_real
((lintegral_lt_top_of_bounded_continuous_to_nnreal (μ : measure Ω) f_pos).ne)).comp (h f_pos),
have tends_neg := (ennreal.tendsto_to_real
((lintegral_lt_top_of_bounded_continuous_to_nnreal (μ : measure Ω) f_neg).ne)).comp (h f_neg),
have aux : ∀ (g : Ω →ᵇ ℝ≥0), ennreal.to_real ∘ (λ (i : γ), ∫⁻ (x : Ω), ↑(g x) ∂(μs i : measure Ω))
= λ (i : γ), (∫⁻ (x : Ω), ↑(g x) ∂(μs i : measure Ω)).to_real, from λ _, rfl,
simp_rw [aux, bounded_continuous_function.nnreal.to_real_lintegral_eq_integral]
at tends_pos tends_neg,
exact tendsto.sub tends_pos tends_neg,
end
end finite_measure_convergence_by_bounded_continuous_functions -- section
end finite_measure -- namespace
end measure_theory -- namespace
|
692099bd2752a098138fe5ef76f114f43f8d9b7b | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/data/set/n_ary.lean | 0ebf7b6ec2f87137700580cfeff713d3753b6695 | [
"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 | 18,138 | lean | /-
Copyright (c) 2020 Floris van Doorn. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Floris van Doorn
-/
import data.set.prod
/-!
# N-ary images of sets
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
This file defines `finset.image₂`, the binary image of finsets. This is the finset version of
`set.image2`. This is mostly useful to define pointwise operations.
## Notes
This file is very similar to the n-ary section of `data.set.basic`, to `order.filter.n_ary` and to
`data.option.n_ary`. Please keep them in sync.
We do not define `finset.image₃` as its only purpose would be to prove properties of `finset.image₂`
and `set.image2` already fulfills this task.
-/
open function
namespace set
variables {α α' β β' γ γ' δ δ' ε ε' ζ ζ' ν : Type*} {f f' : α → β → γ} {g g' : α → β → γ → δ}
variables {s s' : set α} {t t' : set β} {u u' : set γ} {v : set δ} {a a' : α} {b b' : β} {c c' : γ}
{d d' : δ}
/-- The image of a binary function `f : α → β → γ` as a function `set α → set β → set γ`.
Mathematically this should be thought of as the image of the corresponding function `α × β → γ`.-/
def image2 (f : α → β → γ) (s : set α) (t : set β) : set γ :=
{c | ∃ a b, a ∈ s ∧ b ∈ t ∧ f a b = c }
@[simp] lemma mem_image2 : c ∈ image2 f s t ↔ ∃ a b, a ∈ s ∧ b ∈ t ∧ f a b = c := iff.rfl
lemma mem_image2_of_mem (ha : a ∈ s) (hb : b ∈ t) : f a b ∈ image2 f s t := ⟨a, b, ha, hb, rfl⟩
lemma mem_image2_iff (hf : injective2 f) : f a b ∈ image2 f s t ↔ a ∈ s ∧ b ∈ t :=
⟨ by { rintro ⟨a', b', ha', hb', h⟩, rcases hf h with ⟨rfl, rfl⟩, exact ⟨ha', hb'⟩ },
λ ⟨ha, hb⟩, mem_image2_of_mem ha hb⟩
/-- image2 is monotone with respect to `⊆`. -/
lemma image2_subset (hs : s ⊆ s') (ht : t ⊆ t') : image2 f s t ⊆ image2 f s' t' :=
by { rintro _ ⟨a, b, ha, hb, rfl⟩, exact mem_image2_of_mem (hs ha) (ht hb) }
lemma image2_subset_left (ht : t ⊆ t') : image2 f s t ⊆ image2 f s t' := image2_subset subset.rfl ht
lemma image2_subset_right (hs : s ⊆ s') : image2 f s t ⊆ image2 f s' t :=
image2_subset hs subset.rfl
lemma image_subset_image2_left (hb : b ∈ t) : (λ a, f a b) '' s ⊆ image2 f s t :=
ball_image_of_ball $ λ a ha, mem_image2_of_mem ha hb
lemma image_subset_image2_right (ha : a ∈ s) : f a '' t ⊆ image2 f s t :=
ball_image_of_ball $ λ b, mem_image2_of_mem ha
lemma forall_image2_iff {p : γ → Prop} :
(∀ z ∈ image2 f s t, p z) ↔ ∀ (x ∈ s) (y ∈ t), p (f x y) :=
⟨λ h x hx y hy, h _ ⟨x, y, hx, hy, rfl⟩, λ h z ⟨x, y, hx, hy, hz⟩, hz ▸ h x hx y hy⟩
@[simp] lemma image2_subset_iff {u : set γ} :
image2 f s t ⊆ u ↔ ∀ (x ∈ s) (y ∈ t), f x y ∈ u :=
forall_image2_iff
lemma image2_subset_iff_left : image2 f s t ⊆ u ↔ ∀ a ∈ s, (λ b, f a b) '' t ⊆ u :=
by simp_rw [image2_subset_iff, image_subset_iff, subset_def, mem_preimage]
lemma image2_subset_iff_right : image2 f s t ⊆ u ↔ ∀ b ∈ t, (λ a, f a b) '' s ⊆ u :=
by simp_rw [image2_subset_iff, image_subset_iff, subset_def, mem_preimage, @forall₂_swap α]
variables (f)
@[simp] lemma image_prod : (λ x : α × β, f x.1 x.2) '' s ×ˢ t = image2 f s t :=
ext $ λ a,
⟨ by { rintro ⟨_, _, rfl⟩, exact ⟨_, _, (mem_prod.1 ‹_›).1, (mem_prod.1 ‹_›).2, rfl⟩ },
by { rintro ⟨_, _, _, _, rfl⟩, exact ⟨(_, _), ⟨‹_›, ‹_›⟩, rfl⟩ }⟩
@[simp] lemma image_uncurry_prod (s : set α) (t : set β) : uncurry f '' s ×ˢ t = image2 f s t :=
image_prod _
@[simp] lemma image2_mk_eq_prod : image2 prod.mk s t = s ×ˢ t := ext $ by simp
@[simp] lemma image2_curry (f : α × β → γ) (s : set α) (t : set β) :
image2 (λ a b, f (a, b)) s t = f '' s ×ˢ t :=
by simp [←image_uncurry_prod, uncurry]
lemma image2_swap (s : set α) (t : set β) : image2 f s t = image2 (λ a b, f b a) t s :=
by { ext, split; rintro ⟨a, b, ha, hb, rfl⟩; refine ⟨b, a, hb, ha, rfl⟩ }
variables {f}
lemma image2_union_left : image2 f (s ∪ s') t = image2 f s t ∪ image2 f s' t :=
begin
ext c,
split,
{ rintro ⟨a, b, ha | ha, hb, rfl⟩; [left, right]; exact ⟨_, _, ‹_›, ‹_›, rfl⟩ },
{ rintro (⟨_, _, _, _, rfl⟩|⟨_, _, _, _, rfl⟩); refine ⟨_, _, _, ‹_›, rfl⟩;
simp [mem_union, *] }
end
lemma image2_union_right : image2 f s (t ∪ t') = image2 f s t ∪ image2 f s t' :=
by rw [←image2_swap, image2_union_left, image2_swap f, image2_swap f]
lemma image2_inter_left (hf : injective2 f) : image2 f (s ∩ s') t = image2 f s t ∩ image2 f s' t :=
by simp_rw [←image_uncurry_prod, inter_prod, image_inter hf.uncurry]
lemma image2_inter_right (hf : injective2 f) : image2 f s (t ∩ t') = image2 f s t ∩ image2 f s t' :=
by simp_rw [←image_uncurry_prod, prod_inter, image_inter hf.uncurry]
@[simp] lemma image2_empty_left : image2 f ∅ t = ∅ := ext $ by simp
@[simp] lemma image2_empty_right : image2 f s ∅ = ∅ := ext $ by simp
lemma nonempty.image2 : s.nonempty → t.nonempty → (image2 f s t).nonempty :=
λ ⟨a, ha⟩ ⟨b, hb⟩, ⟨_, mem_image2_of_mem ha hb⟩
@[simp] lemma image2_nonempty_iff : (image2 f s t).nonempty ↔ s.nonempty ∧ t.nonempty :=
⟨λ ⟨_, a, b, ha, hb, _⟩, ⟨⟨a, ha⟩, b, hb⟩, λ h, h.1.image2 h.2⟩
lemma nonempty.of_image2_left (h : (image2 f s t).nonempty) : s.nonempty :=
(image2_nonempty_iff.1 h).1
lemma nonempty.of_image2_right (h : (image2 f s t).nonempty) : t.nonempty :=
(image2_nonempty_iff.1 h).2
@[simp] lemma image2_eq_empty_iff : image2 f s t = ∅ ↔ s = ∅ ∨ t = ∅ :=
by simp_rw [←not_nonempty_iff_eq_empty, image2_nonempty_iff, not_and_distrib]
lemma image2_inter_subset_left : image2 f (s ∩ s') t ⊆ image2 f s t ∩ image2 f s' t :=
by { rintro _ ⟨a, b, ⟨h1a, h2a⟩, hb, rfl⟩, split; exact ⟨_, _, ‹_›, ‹_›, rfl⟩ }
lemma image2_inter_subset_right : image2 f s (t ∩ t') ⊆ image2 f s t ∩ image2 f s t' :=
by { rintro _ ⟨a, b, ha, ⟨h1b, h2b⟩, rfl⟩, split; exact ⟨_, _, ‹_›, ‹_›, rfl⟩ }
@[simp] lemma image2_singleton_left : image2 f {a} t = f a '' t := ext $ λ x, by simp
@[simp] lemma image2_singleton_right : image2 f s {b} = (λ a, f a b) '' s := ext $ λ x, by simp
lemma image2_singleton : image2 f {a} {b} = {f a b} := by simp
@[simp] lemma image2_insert_left : image2 f (insert a s) t = (λ b, f a b) '' t ∪ image2 f s t :=
by rw [insert_eq, image2_union_left, image2_singleton_left]
@[simp] lemma image2_insert_right : image2 f s (insert b t) = (λ a, f a b) '' s ∪ image2 f s t :=
by rw [insert_eq, image2_union_right, image2_singleton_right]
@[congr] lemma image2_congr (h : ∀ (a ∈ s) (b ∈ t), f a b = f' a b) :
image2 f s t = image2 f' s t :=
by { ext, split; rintro ⟨a, b, ha, hb, rfl⟩; refine ⟨a, b, ha, hb, by rw h a ha b hb⟩ }
/-- A common special case of `image2_congr` -/
lemma image2_congr' (h : ∀ a b, f a b = f' a b) : image2 f s t = image2 f' s t :=
image2_congr (λ a _ b _, h a b)
/-- The image of a ternary function `f : α → β → γ → δ` as a function
`set α → set β → set γ → set δ`. Mathematically this should be thought of as the image of the
corresponding function `α × β × γ → δ`.
-/
def image3 (g : α → β → γ → δ) (s : set α) (t : set β) (u : set γ) : set δ :=
{d | ∃ a b c, a ∈ s ∧ b ∈ t ∧ c ∈ u ∧ g a b c = d }
@[simp] lemma mem_image3 : d ∈ image3 g s t u ↔ ∃ a b c, a ∈ s ∧ b ∈ t ∧ c ∈ u ∧ g a b c = d :=
iff.rfl
lemma image3_mono (hs : s ⊆ s') (ht : t ⊆ t') (hu : u ⊆ u') : image3 g s t u ⊆ image3 g s' t' u' :=
λ x, Exists₃.imp $ λ a b c ⟨ha, hb, hc, hx⟩, ⟨hs ha, ht hb, hu hc, hx⟩
@[congr] lemma image3_congr (h : ∀ (a ∈ s) (b ∈ t) (c ∈ u), g a b c = g' a b c) :
image3 g s t u = image3 g' s t u :=
by { ext x,
split; rintro ⟨a, b, c, ha, hb, hc, rfl⟩; exact ⟨a, b, c, ha, hb, hc, by rw h a ha b hb c hc⟩ }
/-- A common special case of `image3_congr` -/
lemma image3_congr' (h : ∀ a b c, g a b c = g' a b c) : image3 g s t u = image3 g' s t u :=
image3_congr (λ a _ b _ c _, h a b c)
lemma image2_image2_left (f : δ → γ → ε) (g : α → β → δ) :
image2 f (image2 g s t) u = image3 (λ a b c, f (g a b) c) s t u :=
begin
ext, split,
{ rintro ⟨_, c, ⟨a, b, ha, hb, rfl⟩, hc, rfl⟩, refine ⟨a, b, c, ha, hb, hc, rfl⟩ },
{ rintro ⟨a, b, c, ha, hb, hc, rfl⟩, refine ⟨_, c, ⟨a, b, ha, hb, rfl⟩, hc, rfl⟩ }
end
lemma image2_image2_right (f : α → δ → ε) (g : β → γ → δ) :
image2 f s (image2 g t u) = image3 (λ a b c, f a (g b c)) s t u :=
begin
ext, split,
{ rintro ⟨a, _, ha, ⟨b, c, hb, hc, rfl⟩, rfl⟩, refine ⟨a, b, c, ha, hb, hc, rfl⟩ },
{ rintro ⟨a, b, c, ha, hb, hc, rfl⟩, refine ⟨a, _, ha, ⟨b, c, hb, hc, rfl⟩, rfl⟩ }
end
lemma image_image2 (f : α → β → γ) (g : γ → δ) :
g '' image2 f s t = image2 (λ a b, g (f a b)) s t :=
begin
ext, split,
{ rintro ⟨_, ⟨a, b, ha, hb, rfl⟩, rfl⟩, refine ⟨a, b, ha, hb, rfl⟩ },
{ rintro ⟨a, b, ha, hb, rfl⟩, refine ⟨_, ⟨a, b, ha, hb, rfl⟩, rfl⟩ }
end
lemma image2_image_left (f : γ → β → δ) (g : α → γ) :
image2 f (g '' s) t = image2 (λ a b, f (g a) b) s t :=
begin
ext, split,
{ rintro ⟨_, b, ⟨a, ha, rfl⟩, hb, rfl⟩, refine ⟨a, b, ha, hb, rfl⟩ },
{ rintro ⟨a, b, ha, hb, rfl⟩, refine ⟨_, b, ⟨a, ha, rfl⟩, hb, rfl⟩ }
end
lemma image2_image_right (f : α → γ → δ) (g : β → γ) :
image2 f s (g '' t) = image2 (λ a b, f a (g b)) s t :=
begin
ext, split,
{ rintro ⟨a, _, ha, ⟨b, hb, rfl⟩, rfl⟩, refine ⟨a, b, ha, hb, rfl⟩ },
{ rintro ⟨a, b, ha, hb, rfl⟩, refine ⟨a, _, ha, ⟨b, hb, rfl⟩, rfl⟩ }
end
@[simp] lemma image2_left (h : t.nonempty) : image2 (λ x y, x) s t = s :=
by simp [nonempty_def.mp h, ext_iff]
@[simp] lemma image2_right (h : s.nonempty) : image2 (λ x y, y) s t = t :=
by simp [nonempty_def.mp h, ext_iff]
lemma image2_assoc {f : δ → γ → ε} {g : α → β → δ} {f' : α → ε' → ε} {g' : β → γ → ε'}
(h_assoc : ∀ a b c, f (g a b) c = f' a (g' b c)) :
image2 f (image2 g s t) u = image2 f' s (image2 g' t u) :=
by simp only [image2_image2_left, image2_image2_right, h_assoc]
lemma image2_comm {g : β → α → γ} (h_comm : ∀ a b, f a b = g b a) : image2 f s t = image2 g t s :=
(image2_swap _ _ _).trans $ by simp_rw h_comm
lemma image2_left_comm {f : α → δ → ε} {g : β → γ → δ} {f' : α → γ → δ'} {g' : β → δ' → ε}
(h_left_comm : ∀ a b c, f a (g b c) = g' b (f' a c)) :
image2 f s (image2 g t u) = image2 g' t (image2 f' s u) :=
by { rw [image2_swap f', image2_swap f], exact image2_assoc (λ _ _ _, h_left_comm _ _ _) }
lemma image2_right_comm {f : δ → γ → ε} {g : α → β → δ} {f' : α → γ → δ'} {g' : δ' → β → ε}
(h_right_comm : ∀ a b c, f (g a b) c = g' (f' a c) b) :
image2 f (image2 g s t) u = image2 g' (image2 f' s u) t :=
by { rw [image2_swap g, image2_swap g'], exact image2_assoc (λ _ _ _, h_right_comm _ _ _) }
lemma image2_image2_image2_comm {f : ε → ζ → ν} {g : α → β → ε} {h : γ → δ → ζ} {f' : ε' → ζ' → ν}
{g' : α → γ → ε'} {h' : β → δ → ζ'}
(h_comm : ∀ a b c d, f (g a b) (h c d) = f' (g' a c) (h' b d)) :
image2 f (image2 g s t) (image2 h u v) = image2 f' (image2 g' s u) (image2 h' t v) :=
begin
ext,
split,
{ rintro ⟨_, _, ⟨a, b, ha, hb, rfl⟩, ⟨c, d, hc, hd, rfl⟩, rfl⟩,
exact ⟨_, _, ⟨a, c, ha, hc, rfl⟩, ⟨b, d, hb, hd, rfl⟩, (h_comm _ _ _ _).symm⟩ },
{ rintro ⟨_, _, ⟨a, c, ha, hc, rfl⟩, ⟨b, d, hb, hd, rfl⟩, rfl⟩,
exact ⟨_, _, ⟨a, b, ha, hb, rfl⟩, ⟨c, d, hc, hd, rfl⟩, h_comm _ _ _ _⟩ }
end
lemma image_image2_distrib {g : γ → δ} {f' : α' → β' → δ} {g₁ : α → α'} {g₂ : β → β'}
(h_distrib : ∀ a b, g (f a b) = f' (g₁ a) (g₂ b)) :
(image2 f s t).image g = image2 f' (s.image g₁) (t.image g₂) :=
by simp_rw [image_image2, image2_image_left, image2_image_right, h_distrib]
/-- Symmetric statement to `set.image2_image_left_comm`. -/
lemma image_image2_distrib_left {g : γ → δ} {f' : α' → β → δ} {g' : α → α'}
(h_distrib : ∀ a b, g (f a b) = f' (g' a) b) :
(image2 f s t).image g = image2 f' (s.image g') t :=
(image_image2_distrib h_distrib).trans $ by rw image_id'
/-- Symmetric statement to `set.image_image2_right_comm`. -/
lemma image_image2_distrib_right {g : γ → δ} {f' : α → β' → δ} {g' : β → β'}
(h_distrib : ∀ a b, g (f a b) = f' a (g' b)) :
(image2 f s t).image g = image2 f' s (t.image g') :=
(image_image2_distrib h_distrib).trans $ by rw image_id'
/-- Symmetric statement to `set.image_image2_distrib_left`. -/
lemma image2_image_left_comm {f : α' → β → γ} {g : α → α'} {f' : α → β → δ} {g' : δ → γ}
(h_left_comm : ∀ a b, f (g a) b = g' (f' a b)) :
image2 f (s.image g) t = (image2 f' s t).image g' :=
(image_image2_distrib_left $ λ a b, (h_left_comm a b).symm).symm
/-- Symmetric statement to `set.image_image2_distrib_right`. -/
lemma image_image2_right_comm {f : α → β' → γ} {g : β → β'} {f' : α → β → δ} {g' : δ → γ}
(h_right_comm : ∀ a b, f a (g b) = g' (f' a b)) :
image2 f s (t.image g) = (image2 f' s t).image g' :=
(image_image2_distrib_right $ λ a b, (h_right_comm a b).symm).symm
/-- The other direction does not hold because of the `s`-`s` cross terms on the RHS. -/
lemma image2_distrib_subset_left {f : α → δ → ε} {g : β → γ → δ} {f₁ : α → β → β'} {f₂ : α → γ → γ'}
{g' : β' → γ' → ε} (h_distrib : ∀ a b c, f a (g b c) = g' (f₁ a b) (f₂ a c)) :
image2 f s (image2 g t u) ⊆ image2 g' (image2 f₁ s t) (image2 f₂ s u) :=
begin
rintro _ ⟨a, _, ha, ⟨b, c, hb, hc, rfl⟩, rfl⟩,
rw h_distrib,
exact mem_image2_of_mem (mem_image2_of_mem ha hb) (mem_image2_of_mem ha hc),
end
/-- The other direction does not hold because of the `u`-`u` cross terms on the RHS. -/
lemma image2_distrib_subset_right {f : δ → γ → ε} {g : α → β → δ} {f₁ : α → γ → α'}
{f₂ : β → γ → β'} {g' : α' → β' → ε} (h_distrib : ∀ a b c, f (g a b) c = g' (f₁ a c) (f₂ b c)) :
image2 f (image2 g s t) u ⊆ image2 g' (image2 f₁ s u) (image2 f₂ t u) :=
begin
rintro _ ⟨_, c, ⟨a, b, ha, hb, rfl⟩, hc, rfl⟩,
rw h_distrib,
exact mem_image2_of_mem (mem_image2_of_mem ha hc) (mem_image2_of_mem hb hc),
end
lemma image_image2_antidistrib {g : γ → δ} {f' : β' → α' → δ} {g₁ : β → β'} {g₂ : α → α'}
(h_antidistrib : ∀ a b, g (f a b) = f' (g₁ b) (g₂ a)) :
(image2 f s t).image g = image2 f' (t.image g₁) (s.image g₂) :=
by { rw image2_swap f, exact image_image2_distrib (λ _ _, h_antidistrib _ _) }
/-- Symmetric statement to `set.image2_image_left_anticomm`. -/
lemma image_image2_antidistrib_left {g : γ → δ} {f' : β' → α → δ} {g' : β → β'}
(h_antidistrib : ∀ a b, g (f a b) = f' (g' b) a) :
(image2 f s t).image g = image2 f' (t.image g') s :=
(image_image2_antidistrib h_antidistrib).trans $ by rw image_id'
/-- Symmetric statement to `set.image_image2_right_anticomm`. -/
lemma image_image2_antidistrib_right {g : γ → δ} {f' : β → α' → δ} {g' : α → α'}
(h_antidistrib : ∀ a b, g (f a b) = f' b (g' a)) :
(image2 f s t).image g = image2 f' t (s.image g') :=
(image_image2_antidistrib h_antidistrib).trans $ by rw image_id'
/-- Symmetric statement to `set.image_image2_antidistrib_left`. -/
lemma image2_image_left_anticomm {f : α' → β → γ} {g : α → α'} {f' : β → α → δ} {g' : δ → γ}
(h_left_anticomm : ∀ a b, f (g a) b = g' (f' b a)) :
image2 f (s.image g) t = (image2 f' t s).image g' :=
(image_image2_antidistrib_left $ λ a b, (h_left_anticomm b a).symm).symm
/-- Symmetric statement to `set.image_image2_antidistrib_right`. -/
lemma image_image2_right_anticomm {f : α → β' → γ} {g : β → β'} {f' : β → α → δ} {g' : δ → γ}
(h_right_anticomm : ∀ a b, f a (g b) = g' (f' b a)) :
image2 f s (t.image g) = (image2 f' t s).image g' :=
(image_image2_antidistrib_right $ λ a b, (h_right_anticomm b a).symm).symm
/-- If `a` is a left identity for `f : α → β → β`, then `{a}` is a left identity for
`set.image2 f`. -/
lemma image2_left_identity {f : α → β → β} {a : α} (h : ∀ b, f a b = b) (t : set β) :
image2 f {a} t = t :=
by rw [image2_singleton_left, show f a = id, from funext h, image_id]
/-- If `b` is a right identity for `f : α → β → α`, then `{b}` is a right identity for
`set.image2 f`. -/
lemma image2_right_identity {f : α → β → α} {b : β} (h : ∀ a, f a b = a) (s : set α) :
image2 f s {b} = s :=
by rw [image2_singleton_right, funext h, image_id']
lemma image2_inter_union_subset_union :
image2 f (s ∩ s') (t ∪ t') ⊆ image2 f s t ∪ image2 f s' t' :=
by { rw image2_union_right, exact union_subset_union
(image2_subset_right $ inter_subset_left _ _) (image2_subset_right $ inter_subset_right _ _) }
lemma image2_union_inter_subset_union :
image2 f (s ∪ s') (t ∩ t') ⊆ image2 f s t ∪ image2 f s' t' :=
by { rw image2_union_left, exact union_subset_union
(image2_subset_left $ inter_subset_left _ _) (image2_subset_left $ inter_subset_right _ _) }
lemma image2_inter_union_subset {f : α → α → β} {s t : set α} (hf : ∀ a b, f a b = f b a) :
image2 f (s ∩ t) (s ∪ t) ⊆ image2 f s t :=
by { rw inter_comm,
exact image2_inter_union_subset_union.trans (union_subset (image2_comm hf).subset subset.rfl) }
lemma image2_union_inter_subset {f : α → α → β} {s t : set α} (hf : ∀ a b, f a b = f b a) :
image2 f (s ∪ t) (s ∩ t) ⊆ image2 f s t :=
by { rw image2_comm hf, exact image2_inter_union_subset hf }
end set
|
b67122a15e8db7e76d75d98b2f50d1627fd3df95 | 65807aed539a1b7077e26f006d2ee5724004fd5d | /src/partition.lean | 8abc1bcf1936069a0796c2f1fbc554963f429b2b | [] | no_license | b-mehta/generating-functions | d6c00769c751b3c4e5fd681a33fbcba43ab9243a | 2fc00b2ba7ed92d1e24682124cac146d23b47f92 | refs/heads/master | 1,671,586,110,726 | 1,601,063,036,000 | 1,601,063,036,000 | 296,391,458 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 23,419 | lean | import ring_theory.power_series
import combinatorics.composition
import data.nat.parity
import data.finset.nat_antidiagonal
import tactic.interval_cases
import tactic.apply_fun
import chap1
open finset
open_locale big_operators
lemma count_repeat_ite {α : Type*} [decidable_eq α] (a b : α) (n : ℕ) :
multiset.count a (multiset.repeat b n) = if (a = b) then n else 0 :=
begin
split_ifs,
cases h,
rw multiset.count_repeat,
apply multiset.count_eq_zero_of_not_mem,
intro,
apply h,
apply multiset.eq_of_mem_repeat a_1,
end
open_locale classical
open power_series
noncomputable theory
variable {α : Type*}
/-- A composition of `n` is a list of positive integers summing to `n`. -/
@[ext] structure partition (n : ℕ) :=
(blocks : multiset ℕ)
(blocks_pos : ∀ {i}, i ∈ blocks → 0 < i)
(blocks_sum : blocks.sum = n)
def composition_to_partition (n : ℕ) (c : composition n) : partition n :=
{ blocks := c.blocks,
blocks_pos := λ i hi, c.blocks_pos hi,
blocks_sum := by rw [multiset.coe_sum, c.blocks_sum] }
instance (n : ℕ) : decidable_eq (partition n) :=
begin
intros a b,
rw partition.ext_iff,
apply_instance,
end
instance (n : ℕ) : fintype (partition n) :=
begin
apply fintype.of_surjective (composition_to_partition n),
rintro ⟨_, _, _⟩,
rcases quotient.exists_rep b_blocks with ⟨_, rfl⟩,
refine ⟨⟨w, λ i hi, b_blocks_pos hi, _⟩, partition.ext _ _ rfl⟩,
simpa using b_blocks_sum,
end
def partial_odd_gf (n : ℕ) := ∏ i in range n, (1 - (X : power_series ℚ)^(2*i+1))⁻¹
def partial_distinct_gf (n : ℕ) := ∏ i in range n, (1 + (X : power_series ℚ)^(i+1))
def odd_partition (n : ℕ) := {c : partition n // ∀ i ∈ c.blocks, ¬ nat.even i}
def distinct_partition (n : ℕ) := {c : partition n // multiset.nodup c.blocks}
instance (n : ℕ) : fintype (odd_partition n) :=
subtype.fintype _
instance (n : ℕ) : fintype (distinct_partition n) :=
subtype.fintype _
-- def splits (n k : ℕ) : finset (list ℕ) := sorry
-- lemma mem_splits (n k : ℕ) (l : list ℕ) : l ∈ splits n k ↔ l.sum = n ∧ l.length = k :=
-- begin
-- sorry
-- end
/-- Functions defined only on s, which sum to n. In other words, a partition of n indexed by s. -/
def cut {ι : Type*} (s : finset ι) (n : ℕ) : finset (ι → ℕ) :=
finset.filter (λ f, s.sum f = n) ((s.pi (λ _, range (n+1))).map
⟨λ f i, if h : i ∈ s then f i h else 0,
λ f g h, by { ext i hi, simpa [dif_pos hi] using congr_fun h i }⟩)
lemma mem_cut {ι : Type*} (s : finset ι) (n : ℕ) (f : ι → ℕ) :
f ∈ cut s n ↔ s.sum f = n ∧ ∀ i ∉ s, f i = 0 :=
begin
rw [cut, mem_filter, and_comm, and_congr_right],
intro h,
rw [mem_map],
simp only [exists_prop, function.embedding.coe_fn_mk, mem_pi],
split,
{ rintro ⟨_, _, rfl⟩ _ _,
simp [dif_neg H] },
{ intro hf,
refine ⟨λ i hi, f i, λ i hi, _, _⟩,
{ rw [mem_range, nat.lt_succ_iff, ← h],
apply single_le_sum _ hi,
simp },
{ ext,
split_ifs with q,
{ refl },
{ apply (hf _ q).symm } } }
end
@[simp]
lemma cut_zero {ι : Type*} (s : finset ι) :
cut s 0 = {0} :=
begin
ext f,
rw [mem_cut, mem_singleton, function.funext_iff, sum_eq_zero_iff],
split,
rintro ⟨h₁, h₂⟩,
intro a,
by_cases (a ∈ s),
apply h₁ a h,
apply h₂ a h,
intro h,
exact ⟨λ a _, h _, λ a _, h _⟩,
end
@[simp]
lemma cut_empty_succ {ι : Type*} (n : ℕ) :
cut (∅ : finset ι) (n+1) = ∅ :=
begin
apply eq_empty_of_forall_not_mem,
intros x hx,
rw [mem_cut, sum_empty] at hx,
cases hx.1,
end
lemma cut_insert {ι : Type*} (n : ℕ) (a : ι) (s : finset ι) (h : a ∉ s) :
cut (insert a s) n = (nat.antidiagonal n).bind (λ (p : ℕ × ℕ), (cut s p.snd).map ⟨λ f, f + λ t, if t = a then p.fst else 0, add_left_injective _⟩) :=
begin
ext f,
rw [mem_cut, mem_bind, sum_insert h],
split,
{ rintro ⟨rfl, h₁⟩,
simp only [exists_prop, function.embedding.coe_fn_mk, mem_map, nat.mem_antidiagonal, prod.exists],
refine ⟨f a, s.sum f, rfl, λ i, if i = a then 0 else f i, _, _⟩,
{ rw [mem_cut],
refine ⟨_, _⟩,
{ rw [sum_ite],
have : (filter (λ x, x ≠ a) s) = s,
apply filter_true_of_mem,
rintro i hi rfl,
apply h hi,
simp [this] },
{ intros i hi,
split_ifs,
{ refl },
{ apply h₁ ,
simpa [not_or_distrib, hi] } } },
{ ext,
by_cases (x = a),
{ subst h, simp },
{ simp [if_neg h] } } },
{ simp only [mem_insert, function.embedding.coe_fn_mk, mem_map, nat.mem_antidiagonal, prod.exists,
exists_prop, mem_cut, not_or_distrib],
rintro ⟨p, q, rfl, g, ⟨rfl, hg₂⟩, rfl⟩,
refine ⟨_, _⟩,
{ simp [sum_add_distrib, if_neg h, hg₂ _ h, add_comm] },
{ rintro i ⟨h₁, h₂⟩,
simp [if_neg h₁, hg₂ _ h₂] } }
end
lemma coeff_prod_range [comm_semiring α] {ι : Type*} (s : finset ι) (f : ι → power_series α) (n : ℕ) :
coeff α n (∏ j in s, f j) = ∑ l in cut s n, ∏ i in s, coeff α (l i) (f i) :=
begin
revert n,
apply finset.induction_on s,
rintro ⟨_ | n⟩,
simp,
simp [cut_empty_succ, if_neg (nat.succ_ne_zero _)],
intros a s hi ih n,
rw [cut_insert _ _ _ hi, prod_insert hi, coeff_mul, sum_bind],
{ apply sum_congr rfl _,
simp only [prod.forall, sum_map, pi.add_apply, function.embedding.coe_fn_mk, nat.mem_antidiagonal],
rintro i j rfl,
simp only [prod_insert hi, if_pos rfl],
rw ih,
rw mul_sum,
apply sum_congr rfl _,
intros x hx,
rw mem_cut at hx,
rw [hx.2 a hi, zero_add],
congr' 1,
apply prod_congr rfl,
intros k hk,
rw [if_neg, add_zero],
rintro rfl,
apply hi hk },
{ simp only [prod.forall, not_and, ne.def, nat.mem_antidiagonal, disjoint_left, mem_map,
exists_prop, function.embedding.coe_fn_mk, exists_imp_distrib, not_exists],
rintro p₁ q₁ rfl p₂ q₂ h t p q ⟨hq, rfl⟩ p hp z,
rw mem_cut at hp hq,
have := sum_congr (eq.refl s) (λ x _, function.funext_iff.1 z x),
have : q₂ = q₁,
simpa [sum_add_distrib, hp.1, hq.1, if_neg hi] using this,
subst this,
have : p₂ = p₁,
simpa using h,
subst this,
apply t,
refl }
end
def indicator_series (α : Type*) [semiring α] (f : set ℕ) : power_series α :=
power_series.mk (λ n, if f n then 1 else 0)
lemma coeff_indicator (f : set ℕ) [semiring α] (n : ℕ) :
coeff α n (indicator_series _ f) = if f n then 1 else 0 :=
coeff_mk _ _
lemma coeff_indicator_pos (f : set ℕ) [semiring α] (n : ℕ) (h : f n):
coeff α n (indicator_series _ f) = 1 :=
by rw [coeff_indicator, if_pos h]
lemma coeff_indicator_neg (f : set ℕ) [semiring α] (n : ℕ) (h : ¬f n):
coeff α n (indicator_series _ f) = 0 :=
by rw [coeff_indicator, if_neg h]
lemma constant_coeff_indicator (f : set ℕ) [semiring α] :
constant_coeff α (indicator_series _ f) = if f 0 then 1 else 0 :=
by rw [← coeff_zero_eq_constant_coeff_apply, coeff_indicator]
lemma two_series (i : ℕ) :
(1 + (X : power_series ℚ)^i.succ) = indicator_series ℚ {0, i.succ} :=
begin
ext,
simp only [coeff_indicator, coeff_one, add_monoid_hom.map_add, coeff_X_pow,
← @set.mem_def _ _ {0, i.succ}, set.mem_insert_iff, set.mem_singleton_iff],
by_cases n = 0,
cases h,
simp [(nat.succ_ne_zero i).symm],
simp [h],
end
lemma num_series' [field α] (i : ℕ) :
(1 - (X : power_series α)^(i+1))⁻¹ = indicator_series α (λ k, i + 1 ∣ k) :=
begin
rw power_series.inv_eq_iff,
{ ext,
cases n,
{ simp [mul_sub, zero_pow, constant_coeff_indicator] },
{ rw [coeff_one, if_neg (nat.succ_ne_zero n), mul_sub, mul_one, add_monoid_hom.map_sub,
coeff_indicator],
simp_rw [coeff_mul, coeff_X_pow, coeff_indicator, boole_mul, sum_ite, filter_filter,
sum_const_zero, add_zero, sum_const, nsmul_eq_mul, mul_one, sub_eq_iff_eq_add,
zero_add, filter_congr_decidable],
symmetry,
split_ifs,
{ suffices : ((nat.antidiagonal n.succ).filter (λ (a : ℕ × ℕ), i + 1 ∣ a.fst ∧ a.snd = i + 1)).card = 1,
rw this, norm_cast,
rw card_eq_one,
cases h with p hp,
refine ⟨((i+1) * (p-1), i+1), _⟩,
ext ⟨a₁, a₂⟩,
simp only [mem_filter, prod.mk.inj_iff, nat.mem_antidiagonal, mem_singleton],
split,
{ rintro ⟨_, ⟨a, rfl⟩, rfl⟩,
refine ⟨_, rfl⟩,
rw [nat.mul_sub_left_distrib, ← hp, ← a_left, mul_one, nat.add_sub_cancel] },
{ rintro ⟨rfl, rfl⟩,
cases p,
rw mul_zero at hp, cases hp,
rw hp,
simp [nat.succ_eq_add_one, mul_add] } },
{ suffices : (filter (λ (a : ℕ × ℕ), i + 1 ∣ a.fst ∧ a.snd = i + 1) (nat.antidiagonal n.succ)).card = 0,
rw this, norm_cast,
rw card_eq_zero,
apply eq_empty_of_forall_not_mem,
simp only [prod.forall, mem_filter, not_and, nat.mem_antidiagonal],
rintro _ h₁ h₂ ⟨a, rfl⟩ rfl,
apply h,
simp [← h₂] } } },
{ simp [zero_pow] },
end
lemma num_series (i : ℕ) :
(1 - (X : power_series ℚ)^(i+1))⁻¹ = indicator_series ℚ (λ k, ∃ p, (i+1) * p = k) :=
begin
rw power_series.inv_eq_iff,
ext,
cases n,
{ simp [mul_sub, zero_pow, constant_coeff_indicator] },
{ simp [nat.succ_ne_zero n, mul_sub, coeff_indicator],
split_ifs,
{ cases h,
simp [coeff_mul, coeff_X_pow, coeff_indicator, sum_ite, filter_filter],
suffices : filter (λ (a : ℕ × ℕ), (∃ (p : ℕ), (i+1) * p = a.fst) ∧ a.snd = i + 1) (nat.antidiagonal n.succ) = {((i + 1) * (h_w - 1), i + 1)},
rw this, simp,
rw eq_singleton_iff_unique_mem,
split,
simp only [mem_filter, and_true, eq_self_iff_true, nat.mem_antidiagonal, exists_apply_eq_apply],
cases h_w,
{ rw mul_zero at h_h, cases h_h },
{ simpa using h_h },
rintro ⟨_, _⟩,
simp only [and_imp, mem_filter, prod.mk.inj_iff, nat.mem_antidiagonal, exists_imp_distrib],
rintro _ _ rfl rfl,
refine ⟨_, rfl⟩,
rw [nat.mul_sub_left_distrib, h_h, ← a, mul_one, nat.add_sub_cancel] },
{ simp [coeff_mul, coeff_X_pow, coeff_indicator, sum_ite, filter_filter],
apply eq_empty_of_forall_not_mem,
simp,
rintro _ _ _ _ rfl _,
subst a_3,
apply h,
refine ⟨x + 1, _⟩,
simpa } },
simp [zero_pow],
end
lemma card_eq_of_bijection {β : Type*} {s : finset α} {t : finset β}
(f : α → β)
(hf : ∀ a ∈ s, f a ∈ t)
(hsurj : ∀ b ∈ t, ∃ (a ∈ s), f a = b)
(hinj : ∀ a₁ a₂ ∈ s, f a₁ = f a₂ → a₁ = a₂) :
s.card = t.card :=
begin
have : s.image f = t,
ext, simp only [mem_image, exists_prop],
split,
rintro ⟨i, hi, rfl⟩,
apply hf,
apply hi,
simpa using hsurj a,
rw ← this,
rw card_image_of_inj_on,
intros,
apply hinj; assumption,
end
lemma sum_multiset_count [decidable_eq α] [add_comm_monoid α] (s : multiset α) :
s.sum = ∑ m in s.to_finset, s.count m •ℕ m :=
@prod_multiset_count (multiplicative α) _ _ s
lemma auxy (n : ℕ) (a_blocks : multiset ℕ) (s : finset ℕ)
-- (a_blocks_pos : ∀ {i : ℕ}, i ∈ a_blocks → 0 < i)
(a_blocks_sum : a_blocks.sum = n)
(hp : ∀ (i : ℕ), i ∈ a_blocks → i ∈ s) :
∑ (i : ℕ) in s, multiset.count i a_blocks * i = n :=
begin
rw ← a_blocks_sum,
rw sum_multiset_count,
simp_rw nat.nsmul_eq_mul,
symmetry,
apply sum_subset_zero_on_sdiff,
intros i hi,
apply hp,
simpa using hi,
intros,
rw mem_sdiff at H,
simp only [multiset.mem_to_finset] at H,
rw [multiset.count_eq_zero_of_not_mem H.2, zero_mul],
intros, refl,
end
def mk_odd : ℕ ↪ ℕ := ⟨λ i, 2 * i + 1, λ x y h, by linarith⟩
lemma mem_sum {β : Type*} {f : α → multiset β} (s : finset α) (b : β) :
b ∈ ∑ x in s, f x ↔ ∃ a ∈ s, b ∈ f a :=
begin
apply finset.induction_on s,
simp,
intros,
simp [finset.sum_insert a_1, a_2],
split,
rintro (_ | ⟨_, _, _⟩),
refine ⟨a, or.inl rfl, a_3⟩,
refine ⟨_, or.inr ‹_›, ‹_›⟩,
rintro ⟨_, (rfl | _), _⟩,
left, assumption,
right,
refine ⟨a_3_w, ‹_›, ‹_›⟩,
end
lemma sum_sum {β : Type*} [add_comm_monoid β] (f : α → multiset β) (s : finset α) :
multiset.sum (finset.sum s f) = ∑ x in s, (f x).sum :=
(sum_hom s multiset.sum).symm
lemma partial_odd_gf_prop (n m : ℕ) :
(finset.card ((univ : finset (partition n)).filter (λ p, ∀ j ∈ p.blocks, j ∈ (range m).map mk_odd)) : ℚ) =
coeff ℚ n (partial_odd_gf m) :=
begin
simp_rw [partial_odd_gf, num_series],
erw ← finset.prod_map (range m) mk_odd (λ t, indicator_series ℚ (λ (k : ℕ), ∃ (p : ℕ), t * p = k)),
simp_rw [coeff_prod_range, coeff_indicator, prod_boole, sum_boole],
norm_cast,
refine card_eq_of_bijection _ _ _ _,
{ intros p i, apply multiset.count i p.blocks * i },
{ simp only [mem_cut, mem_filter, mem_univ, true_and, mem_map, exists_prop, not_and,
mem_range, mul_eq_zero, and_assoc],
rintro ⟨p, hp₁, hp₂⟩ hp₃,
refine ⟨_, _, _⟩,
{ rw auxy _ _ _ hp₂,
simpa using hp₃ },
{ intros i hi,
left,
apply multiset.count_eq_zero_of_not_mem,
exact (λ t, hi (hp₃ i t)) },
{ simp only [and_imp, exists_imp_distrib],
rintros i x hx rfl,
exact ⟨_, mul_comm _ _⟩ } },
{ simp only [mem_filter, exists_prop, mem_cut, mem_univ, true_and],
rintros f ⟨⟨hf₁, hf₂⟩, hf₃⟩,
refine ⟨⟨∑ i in map mk_odd (range m), multiset.repeat i (f i / i), _, _⟩, _, _⟩,
{ intros i hi,
simp only [exists_prop, mem_sum, mem_map] at hi,
rcases hi with ⟨_, ⟨_, _, rfl⟩, _⟩,
cases multiset.eq_of_mem_repeat hi_h_right,
apply nat.zero_lt_succ },
{ rw sum_sum,
simp_rw multiset.sum_repeat,
have : ∀ i ∈ map mk_odd (range m), i ∣ f i,
intros i hi, cases hf₃ i hi,
rw ← h,
exact dvd.intro w rfl,
simp_rw nat.nsmul_eq_mul,
rw sum_congr rfl (λ i hi, nat.div_mul_cancel (this i hi)),
apply hf₁ },
{ intros j hj,
rw mem_sum at hj,
rcases hj with ⟨_, _, _⟩,
cases multiset.eq_of_mem_repeat hj_h_h,
assumption },
{ ext i,
rw ← sum_hom (map mk_odd (range m)) (multiset.count i),
simp_rw [count_repeat_ite],
simp only [sum_ite_eq],
split_ifs,
{ apply nat.div_mul_cancel,
cases hf₃ i h,
apply dvd.intro,
exact h_1 },
{ rw [zero_mul, hf₂ i h] } } },
{ intros p₁ p₂ hp₁ hp₂ h,
apply partition.ext,
simp only [true_and, exists_prop, mem_filter, mem_univ] at hp₁ hp₂,
ext i,
rw function.funext_iff at h,
specialize h i,
cases nat.eq_zero_or_pos i,
{ cases h_1,
have := hp₁ 0,
simp [mk_odd] at this,
have := hp₂ 0,
simp [mk_odd] at this,
rw multiset.count_eq_zero_of_not_mem ‹0 ∉ p₁.blocks›,
rw multiset.count_eq_zero_of_not_mem ‹0 ∉ p₂.blocks› },
{ rwa nat.mul_left_inj at h,
assumption } }
end
lemma multiset.single_le_sum {a : ℕ} (s : multiset ℕ) :
a ∈ s → a ≤ s.sum :=
begin
apply multiset.induction_on s,
simp,
rintros b s₁ ih h,
rw multiset.sum_cons,
rw multiset.mem_cons at h,
rcases h with rfl | _,
exact nat.le.intro rfl,
apply le_add_left,
apply ih h,
end
/-- If m is big enough, the partial product's coefficient counts the number of odd partitions -/
theorem odd_gf_prop (n m : ℕ) (h : n < m * 2) :
(fintype.card (odd_partition n) : ℚ) = coeff ℚ n (partial_odd_gf m) :=
begin
erw [fintype.subtype_card, ← partial_odd_gf_prop],
congr' 2,
apply filter_congr,
intros p hp,
apply ball_congr,
intros i hi,
have : i ≤ n,
simpa [p.blocks_sum] using multiset.single_le_sum _ hi,
simp only [mk_odd, exists_prop, mem_range, function.embedding.coe_fn_mk, mem_map],
split,
intro hi₂,
have := nat.mod_add_div i 2,
rw nat.not_even_iff at hi₂,
rw [hi₂, add_comm] at this,
refine ⟨i / 2, _, ‹_›⟩,
rw nat.div_lt_iff_lt_mul,
apply lt_of_le_of_lt ‹i ≤ n› h,
norm_num,
rintro ⟨_, _, rfl⟩,
apply nat.two_not_dvd_two_mul_add_one,
end
lemma partial_distinct_gf_prop (n m : ℕ) :
(finset.card ((univ : finset (partition n)).filter (λ p, p.blocks.nodup ∧ ∀ j ∈ p.blocks, j ∈ (range m).map ⟨nat.succ, nat.succ_injective⟩)) : ℚ) =
coeff ℚ n (partial_distinct_gf m) :=
begin
simp_rw [partial_distinct_gf, two_series],
erw ← finset.prod_map (range m) ⟨_, nat.succ_injective⟩ (λ t, indicator_series ℚ {0, t}),
simp_rw [coeff_prod_range, coeff_indicator, prod_boole, sum_boole,
← @set.mem_def _ _ {0, _}, set.mem_insert_iff, set.mem_singleton_iff],
norm_cast,
refine card_eq_of_bijection _ _ _ _,
{ intros p i, apply multiset.count i p.blocks * i },
{ simp only [mem_filter, mem_cut, mem_univ, true_and, exists_prop, and_assoc,
and_imp, nat.mul_eq_zero, function.embedding.coe_fn_mk, exists_imp_distrib],
rintro ⟨p, hp₁, hp₂⟩ hp₃ hp₄,
refine ⟨_, _, _⟩,
{ rw auxy _ _ _ hp₂,
apply hp₄ },
{ intros i hi,
left,
apply multiset.count_eq_zero_of_not_mem,
apply mt (hp₄ i) hi },
{ intros i hi,
rw multiset.nodup_iff_count_le_one at hp₃,
specialize hp₃ i,
dsimp at *,
set k := multiset.count i p with q,
rw ← q at *,
interval_cases k,
left, left, assumption,
rw h, right, simp }
},
{ simp only [mem_filter, mem_cut, mem_univ, exists_prop, true_and, and_assoc],
rintros f ⟨hf₁, hf₂, hf₃⟩,
refine ⟨⟨∑ i in map ⟨_, nat.succ_injective⟩ (range m), multiset.repeat i (f i / i), _, _⟩, _, _, _⟩,
{ intros i hi,
simp only [exists_prop, mem_sum, mem_map, function.embedding.coe_fn_mk] at hi,
rcases hi with ⟨_, ⟨_, _, rfl⟩, _⟩,
cases multiset.eq_of_mem_repeat hi_h_right,
exact nat.succ_pos hi_h_left_w },
{ rw sum_sum,
simp_rw [multiset.sum_repeat, nat.nsmul_eq_mul],
have : ∀ i ∈ map ⟨_, nat.succ_injective⟩ (range m), i ∣ f i,
{ intros i hi,
cases hf₃ i hi; rw h,
exact dvd_zero i },
{ rw sum_congr rfl (λ i hi, nat.div_mul_cancel (this i hi)),
apply hf₁ } },
{ rw multiset.nodup_iff_count_le_one,
intro i,
dsimp,
rw ← sum_hom _ (multiset.count i),
simp_rw [count_repeat_ite],
simp only [sum_ite_eq],
split_ifs,
{ cases hf₃ i h with h₁ h₁; rw h₁,
simp,
cases i,
simp,
apply le_of_eq,
apply nat.div_self,
exact nat.succ_pos i },
{ norm_num } },
{ intros i hi,
dsimp at hi,
rw mem_sum at hi,
rcases hi with ⟨_, _, _⟩,
cases multiset.eq_of_mem_repeat hi_h_h,
assumption },
{ ext i,
dsimp,
rw ← sum_hom _ (multiset.count i),
simp_rw [count_repeat_ite],
simp only [sum_ite_eq],
split_ifs,
{ apply nat.div_mul_cancel,
cases hf₃ i h; rw h_1,
apply dvd_zero },
{ rw [zero_mul],
apply (hf₂ i h).symm } } },
{ intros p₁ p₂ hp₁ hp₂ h,
apply partition.ext,
simp only [true_and, mem_univ, mem_filter] at hp₁ hp₂,
ext i,
rw function.funext_iff at h,
specialize h i,
cases i,
{ rw multiset.count_eq_zero_of_not_mem,
rw multiset.count_eq_zero_of_not_mem,
intro,
simpa [nat.succ_ne_zero] using hp₂.2 0 a,
intro,
simpa [nat.succ_ne_zero] using hp₁.2 0 a },
{ rwa nat.mul_left_inj at h,
exact nat.succ_pos i } },
end
/-- If m is big enough, the partial product's coefficient counts the number of distinct partitions -/
theorem distinct_gf_prop (n m : ℕ) (h : n < m + 1) :
(fintype.card (distinct_partition n) : ℚ) = coeff ℚ n (partial_distinct_gf m) :=
begin
erw [fintype.subtype_card, ← partial_distinct_gf_prop],
congr' 2,
apply filter_congr,
intros p hp,
apply (and_iff_left _).symm,
intros i hi,
have : i ≤ n,
simpa [p.blocks_sum] using multiset.single_le_sum _ hi,
simp only [mk_odd, exists_prop, mem_range, function.embedding.coe_fn_mk, mem_map],
refine ⟨i-1, _, _⟩,
rw nat.sub_lt_right_iff_lt_add,
apply lt_of_le_of_lt ‹i ≤ n› h,
apply p.blocks_pos hi,
apply nat.succ_pred_eq_of_pos,
apply p.blocks_pos hi,
end
lemma same_gf (n : ℕ) :
partial_odd_gf n * (range n).prod (λ i, (1 - (X : power_series ℚ)^(n+i+1))) = partial_distinct_gf n :=
begin
rw [partial_odd_gf, partial_distinct_gf],
induction n with n ih,
{ simp },
let Z : power_series ℚ := ∏ (x : ℕ) in range n, (1 - X^(2*x+1))⁻¹,
rw [prod_range_succ _ n, prod_range_succ _ n, prod_range_succ _ n, ← ih],
clear ih,
erw ← two_mul (n+1),
have : 1 - (X : power_series ℚ) ^ (2 * (n+1)) = (1 + X^(n+1)) * (1 - X^(n+1)),
rw [← sq_sub_sq, one_pow, ← pow_mul, mul_comm],
rw this, clear this,
change (_ * Z) * (((1 + X^(n+1)) * _) * _) = (1 + X^(n+1)) * (Z * _),
rw [mul_assoc, mul_assoc, ← mul_assoc Z, mul_left_comm _ (Z * _), mul_left_comm _ Z,
← mul_assoc Z],
congr' 1,
have := prod_range_succ' (λ x, 1 - (X : power_series ℚ)^(n.succ + x)) n,
dsimp at this,
simp_rw [← add_assoc, add_zero, mul_comm _ (1 - X ^ n.succ)] at this,
erw [← this],
rw [prod_range_succ],
simp_rw [nat.succ_eq_add_one, add_right_comm _ 1, ← two_mul, ← mul_assoc],
rw [power_series.inv_mul, one_mul],
simp [zero_pow],
end
lemma coeff_prod_one_add (n : ℕ) [comm_semiring α] (φ ψ : power_series α) (h : ↑n < ψ.order) :
coeff α n (φ * ψ) = 0 :=
begin
rw [coeff_mul],
have : ∑ p in nat.antidiagonal n, (0 : α) = 0,
rw [sum_const, nsmul_zero],
rw ← this,
apply sum_congr rfl _,
rintros pq hpq,
apply mul_eq_zero_of_right,
apply coeff_of_lt_order,
apply lt_of_le_of_lt _ h,
rw nat.mem_antidiagonal at hpq,
norm_cast,
rw ← hpq,
apply le_add_left,
apply le_refl,
end
lemma coeff_prod_one_sub (n : ℕ) [comm_ring α] (φ ψ : power_series α) (h : ↑n < ψ.order) :
coeff α n (φ * (1 - ψ)) = coeff α n φ :=
by rw [mul_sub, mul_one, add_monoid_hom.map_sub, coeff_prod_one_add _ _ _ h, sub_zero]
lemma same_coeffs (n m : ℕ) (h : m ≤ n) :
coeff ℚ m (partial_odd_gf n) = coeff ℚ m (partial_distinct_gf n) :=
begin
rw ← same_gf,
set! k := n with h,
apply_fun range at h,
rw ← h,
clear_value k, clear h,
induction k,
simp,
rwa [prod_range_succ, ← mul_assoc, mul_right_comm, coeff_prod_one_sub],
simp only [enat.coe_one, enat.coe_add, order_X_pow],
norm_cast,
rw nat.lt_succ_iff,
apply le_add_right,
assumption,
end
theorem freek (n : ℕ) : fintype.card (odd_partition n) = fintype.card (distinct_partition n) :=
begin
suffices : (fintype.card (odd_partition n) : ℚ) = fintype.card (distinct_partition n),
norm_cast at this, assumption,
rw distinct_gf_prop _ (n+1),
rw odd_gf_prop _ (n+1),
apply same_coeffs,
linarith,
linarith,
linarith,
end |
7209b8d6f8ff694b82667c7ab7965f772230f1d0 | b70447c014d9e71cf619ebc9f539b262c19c2e0b | /hott/init/pointed.hlean | ecedb0e928f8b6d7ced148a39e453cf7acb3117e | [
"Apache-2.0"
] | permissive | ia0/lean2 | c20d8da69657f94b1d161f9590a4c635f8dc87f3 | d86284da630acb78fa5dc3b0b106153c50ffccd0 | refs/heads/master | 1,611,399,322,751 | 1,495,751,007,000 | 1,495,751,007,000 | 93,104,167 | 0 | 0 | null | 1,496,355,488,000 | 1,496,355,487,000 | null | UTF-8 | Lean | false | false | 4,122 | hlean | /-
Copyright (c) 2016 Floris van Doorn. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Floris van Doorn
The definition of pointed types. This file is here to avoid circularities in the import graph
-/
prelude
import init.trunc
open eq equiv is_equiv is_trunc
structure pointed [class] (A : Type) :=
(point : A)
structure pType :=
(carrier : Type)
(Point : carrier)
notation `Type*` := pType
namespace pointed
attribute pType.carrier [coercion]
variables {A : Type}
definition pt [reducible] [unfold 2] [H : pointed A] := point A
definition Point [reducible] [unfold 1] (A : Type*) := pType.Point A
definition carrier [reducible] [unfold 1] (A : Type*) := pType.carrier A
protected definition Mk [constructor] {A : Type} (a : A) := pType.mk A a
protected definition MK [constructor] (A : Type) (a : A) := pType.mk A a
protected definition mk' [constructor] (A : Type) [H : pointed A] : Type* :=
pType.mk A (point A)
definition pointed_carrier [instance] [constructor] (A : Type*) : pointed A :=
pointed.mk (Point A)
end pointed
open pointed
section
universe variable u
structure ptrunctype (n : ℕ₋₂) extends trunctype.{u} n, pType.{u}
definition is_trunc_ptrunctype [instance] {n : ℕ₋₂} (X : ptrunctype n)
: is_trunc n (ptrunctype.to_pType X) :=
trunctype.struct X
end
notation n `-Type*` := ptrunctype n
abbreviation pSet [parsing_only] := 0-Type*
notation `Set*` := pSet
namespace pointed
protected definition ptrunctype.mk' [constructor] (n : ℕ₋₂)
(A : Type) [pointed A] [is_trunc n A] : n-Type* :=
ptrunctype.mk A _ pt
protected definition pSet.mk [constructor] := @ptrunctype.mk (-1.+1)
protected definition pSet.mk' [constructor] := ptrunctype.mk' (-1.+1)
definition ptrunctype_of_trunctype [constructor] {n : ℕ₋₂} (A : n-Type) (a : A)
: n-Type* :=
ptrunctype.mk A _ a
definition ptrunctype_of_pType [constructor] {n : ℕ₋₂} (A : Type*) (H : is_trunc n A)
: n-Type* :=
ptrunctype.mk A _ pt
definition pSet_of_Set [constructor] (A : Set) (a : A) : Set* :=
ptrunctype.mk A _ a
definition pSet_of_pType [constructor] (A : Type*) (H : is_set A) : Set* :=
ptrunctype.mk A _ pt
attribute ptrunctype._trans_of_to_pType ptrunctype.to_pType ptrunctype.to_trunctype [unfold 2]
-- Any contractible type is pointed
definition pointed_of_is_contr [instance] [priority 800] [constructor]
(A : Type) [H : is_contr A] : pointed A :=
pointed.mk !center
end pointed
/- pointed maps -/
structure ppi (A : Type*) (P : A → Type*) :=
(to_fun : Π a : A, P a)
(resp_pt : to_fun (Point A) = Point (P (Point A)))
-- We could try to define pmap as a special case of ppi
-- definition pmap (A B : Type*) := @ppi A (λa, B)
structure pmap (A B : Type*) :=
(to_fun : A → B)
(resp_pt : to_fun (Point A) = Point B)
namespace pointed
abbreviation respect_pt [unfold 3] := @pmap.resp_pt
notation `map₊` := pmap
infix ` →* `:30 := pmap
attribute pmap.to_fun ppi.to_fun [coercion]
notation `Π*` binders `, ` r:(scoped P, ppi _ P) := r
-- definition pmap.mk [constructor] {A B : Type*} (f : A → B) (p : f pt = pt) : A →* B :=
-- ppi.mk f p
-- definition pmap.to_fun [coercion] [unfold 3] {A B : Type*} (f : A →* B) : A → B := f
end pointed open pointed
/- pointed homotopies -/
structure phomotopy {A B : Type*} (f g : A →* B) :=
(homotopy : f ~ g)
(homotopy_pt : homotopy pt ⬝ respect_pt g = respect_pt f)
namespace pointed
variables {A B : Type*} {f g : A →* B}
infix ` ~* `:50 := phomotopy
abbreviation to_homotopy_pt [unfold 5] := @phomotopy.homotopy_pt
abbreviation to_homotopy [coercion] [unfold 5] (p : f ~* g) : Πa, f a = g a :=
phomotopy.homotopy p
/- pointed equivalences -/
structure pequiv (A B : Type*) extends equiv A B, pmap A B
attribute pequiv._trans_of_to_pmap pequiv._trans_of_to_equiv pequiv.to_pmap pequiv.to_equiv
[unfold 3]
attribute pequiv.to_is_equiv [instance]
attribute pequiv.to_pmap [coercion]
infix ` ≃* `:25 := pequiv
end pointed
|
d51bba8ec05379025540210bc23e9af24ba95700 | 618003631150032a5676f229d13a079ac875ff77 | /src/category_theory/limits/shapes/equalizers.lean | 152a16cc1f03df4c9e3d019e677d4af715fa99a7 | [
"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 | 27,406 | lean | /-
Copyright (c) 2018 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Scott Morrison, Markus Himmel
-/
import category_theory.epi_mono
import category_theory.limits.shapes.finite_limits
/-!
# Equalizers and coequalizers
This file defines (co)equalizers as special cases of (co)limits.
An equalizer is the categorical generalization of the subobject {a ∈ A | f(a) = g(a)} known
from abelian groups or modules. It is a limit cone over the diagram formed by `f` and `g`.
A coequalizer is the dual concept.
## Main definitions
* `walking_parallel_pair` is the indexing category used for (co)equalizer_diagrams
* `parallel_pair` is a functor from `walking_parallel_pair` to our category `C`.
* a `fork` is a cone over a parallel pair.
* there is really only one interesting morphism in a fork: the arrow from the vertex of the fork
to the domain of f and g. It is called `fork.ι`.
* an `equalizer` is now just a `limit (parallel_pair f g)`
Each of these has a dual.
## Main statements
* `equalizer.ι_mono` states that every equalizer map is a monomorphism
* `is_limit_cone_parallel_pair_self` states that the identity on the domain of `f` is an equalizer
of `f` and `f`.
## Implementation notes
As with the other special shapes in the limits library, all the definitions here are given as
`abbreviation`s of the general statements for limits, so all the `simp` lemmas and theorems about
general limits can be used.
## References
* [F. Borceux, *Handbook of Categorical Algebra 1*][borceux-vol1]
-/
open category_theory
namespace category_theory.limits
local attribute [tidy] tactic.case_bash
universes v u
/-- The type of objects for the diagram indexing a (co)equalizer. -/
@[derive decidable_eq, derive inhabited] inductive walking_parallel_pair : Type v
| zero | one
instance fintype_walking_parallel_pair : fintype walking_parallel_pair :=
{ elems := [walking_parallel_pair.zero, walking_parallel_pair.one].to_finset,
complete := λ x, by { cases x; simp } }
open walking_parallel_pair
/-- The type family of morphisms for the diagram indexing a (co)equalizer. -/
@[derive decidable_eq] inductive walking_parallel_pair_hom :
walking_parallel_pair → walking_parallel_pair → Type v
| left : walking_parallel_pair_hom zero one
| right : walking_parallel_pair_hom zero one
| id : Π X : walking_parallel_pair.{v}, walking_parallel_pair_hom X X
/-- Satisfying the inhabited linter -/
instance : inhabited (walking_parallel_pair_hom zero one) :=
{ default := walking_parallel_pair_hom.left }
open walking_parallel_pair_hom
instance (j j' : walking_parallel_pair) : fintype (walking_parallel_pair_hom j j') :=
{ elems := walking_parallel_pair.rec_on j
(walking_parallel_pair.rec_on j' [walking_parallel_pair_hom.id zero].to_finset
[left, right].to_finset)
(walking_parallel_pair.rec_on j' ∅ [walking_parallel_pair_hom.id one].to_finset),
complete := by tidy }
/-- Composition of morphisms in the indexing diagram for (co)equalizers. -/
def walking_parallel_pair_hom.comp :
Π (X Y Z : walking_parallel_pair)
(f : walking_parallel_pair_hom X Y) (g : walking_parallel_pair_hom Y Z),
walking_parallel_pair_hom X Z
| _ _ _ (id _) h := h
| _ _ _ left (id one) := left
| _ _ _ right (id one) := right
.
instance walking_parallel_pair_hom_category : small_category.{v} walking_parallel_pair :=
{ hom := walking_parallel_pair_hom,
id := walking_parallel_pair_hom.id,
comp := walking_parallel_pair_hom.comp }
instance : fin_category.{v} walking_parallel_pair.{v} := { }
@[simp]
lemma walking_parallel_pair_hom_id (X : walking_parallel_pair.{v}) :
walking_parallel_pair_hom.id X = 𝟙 X :=
rfl
variables {C : Type u} [category.{v} C]
variables {X Y : C}
/-- `parallel_pair f g` is the diagram in `C` consisting of the two morphisms `f` and `g` with
common domain and codomain. -/
def parallel_pair (f g : X ⟶ Y) : walking_parallel_pair.{v} ⥤ C :=
{ obj := λ x, match x with
| zero := X
| one := Y
end,
map := λ x y h, match x, y, h with
| _, _, (id _) := 𝟙 _
| _, _, left := f
| _, _, right := g
end,
-- `tidy` can cope with this, but it's too slow:
map_comp' := begin rintros (⟨⟩|⟨⟩) (⟨⟩|⟨⟩) (⟨⟩|⟨⟩) ⟨⟩⟨⟩; { unfold_aux, simp; refl }, end, }.
@[simp] lemma parallel_pair_obj_zero (f g : X ⟶ Y) : (parallel_pair f g).obj zero = X := rfl
@[simp] lemma parallel_pair_obj_one (f g : X ⟶ Y) : (parallel_pair f g).obj one = Y := rfl
@[simp] lemma parallel_pair_map_left (f g : X ⟶ Y) : (parallel_pair f g).map left = f := rfl
@[simp] lemma parallel_pair_map_right (f g : X ⟶ Y) : (parallel_pair f g).map right = g := rfl
@[simp] lemma parallel_pair_functor_obj
{F : walking_parallel_pair.{v} ⥤ C} (j : walking_parallel_pair.{v}) :
(parallel_pair (F.map left) (F.map right)).obj j = F.obj j :=
begin
cases j; refl
end
/-- Every functor indexing a (co)equalizer is naturally isomorphic (actually, equal) to a
`parallel_pair` -/
def diagram_iso_parallel_pair (F : walking_parallel_pair.{v} ⥤ C) :
F ≅ parallel_pair (F.map left) (F.map right) :=
nat_iso.of_components (λ j, eq_to_iso $ by cases j; tidy) $ by tidy
/-- A fork on `f` and `g` is just a `cone (parallel_pair f g)`. -/
abbreviation fork (f g : X ⟶ Y) := cone (parallel_pair f g)
/-- A cofork on `f` and `g` is just a `cocone (parallel_pair f g)`. -/
abbreviation cofork (f g : X ⟶ Y) := cocone (parallel_pair f g)
variables {f g : X ⟶ Y}
@[simp, reassoc] lemma fork.app_zero_left (s : fork f g) :
(s.π).app zero ≫ f = (s.π).app one :=
by rw [←s.w left, parallel_pair_map_left]
@[simp, reassoc] lemma fork.app_zero_right (s : fork f g) :
(s.π).app zero ≫ g = (s.π).app one :=
by rw [←s.w right, parallel_pair_map_right]
@[simp, reassoc] lemma cofork.left_app_one (s : cofork f g) :
f ≫ (s.ι).app one = (s.ι).app zero :=
by rw [←s.w left, parallel_pair_map_left]
@[simp, reassoc] lemma cofork.right_app_one (s : cofork f g) :
g ≫ (s.ι).app one = (s.ι).app zero :=
by rw [←s.w right, parallel_pair_map_right]
/-- A fork on `f g : X ⟶ Y` is determined by the morphism `ι : P ⟶ X` satisfying `ι ≫ f = ι ≫ g`.
-/
def fork.of_ι {P : C} (ι : P ⟶ X) (w : ι ≫ f = ι ≫ g) : fork f g :=
{ X := P,
π :=
{ app := λ X, begin cases X, exact ι, exact ι ≫ f, end,
naturality' := λ X Y f,
begin
cases X; cases Y; cases f; dsimp; simp,
{ dsimp, simp, }, -- TODO If someone could decipher why these aren't done on the previous line, that would be great
{ exact w },
{ dsimp, simp, }, -- TODO idem
end } }
/-- A cofork on `f g : X ⟶ Y` is determined by the morphism `π : Y ⟶ P` satisfying
`f ≫ π = g ≫ π`. -/
def cofork.of_π {P : C} (π : Y ⟶ P) (w : f ≫ π = g ≫ π) : cofork f g :=
{ X := P,
ι :=
{ app := λ X, begin cases X, exact f ≫ π, exact π, end,
naturality' := λ X Y f,
begin
cases X; cases Y; cases f; dsimp; simp,
{ dsimp, simp, }, -- TODO idem
{ exact w.symm },
{ dsimp, simp, }, -- TODO idem
end } }
@[simp] lemma fork.of_ι_app_zero {P : C} (ι : P ⟶ X) (w : ι ≫ f = ι ≫ g) :
(fork.of_ι ι w).π.app zero = ι := rfl
@[simp] lemma fork.of_ι_app_one {P : C} (ι : P ⟶ X) (w : ι ≫ f = ι ≫ g) :
(fork.of_ι ι w).π.app one = ι ≫ f := rfl
@[simp] lemma cofork.of_π_app_zero {P : C} (π : Y ⟶ P) (w : f ≫ π = g ≫ π) :
(cofork.of_π π w).ι.app zero = f ≫ π := rfl
@[simp] lemma cofork.of_π_app_one {P : C} (π : Y ⟶ P) (w : f ≫ π = g ≫ π) :
(cofork.of_π π w).ι.app one = π := rfl
/-- A fork `t` on the parallel pair `f g : X ⟶ Y` consists of two morphisms `t.π.app zero : t.X ⟶ X`
and `t.π.app one : t.X ⟶ Y`. Of these, only the first one is interesting, and we give it the
shorter name `fork.ι t`. -/
abbreviation fork.ι (t : fork f g) := t.π.app zero
/-- A cofork `t` on the parallel_pair `f g : X ⟶ Y` consists of two morphisms
`t.ι.app zero : X ⟶ t.X` and `t.ι.app one : Y ⟶ t.X`. Of these, only the second one is
interesting, and we give it the shorter name `cofork.π t`. -/
abbreviation cofork.π (t : cofork f g) := t.ι.app one
@[simp] lemma fork.ι_of_ι {P : C} (ι : P ⟶ X) (w : ι ≫ f = ι ≫ g) :
fork.ι (fork.of_ι ι w) = ι := rfl
@[simp] lemma cofork.π_of_π {P : C} (π : Y ⟶ P) (w : f ≫ π = g ≫ π) :
cofork.π (cofork.of_π π w) = π := rfl
lemma fork.ι_eq_app_zero (t : fork f g) : fork.ι t = t.π.app zero := rfl
lemma cofork.π_eq_app_one (t : cofork f g) : cofork.π t = t.ι.app one := rfl
lemma fork.condition (t : fork f g) : (fork.ι t) ≫ f = (fork.ι t) ≫ g :=
begin
erw [t.w left, ← t.w right], refl
end
lemma cofork.condition (t : cofork f g) : f ≫ (cofork.π t) = g ≫ (cofork.π t) :=
begin
erw [t.w left, ← t.w right], refl
end
/-- To check whether two maps are equalized by both maps of a fork, it suffices to check it for the
first map -/
lemma fork.equalizer_ext (s : fork f g) {W : C} {k l : W ⟶ s.X}
(h : k ≫ fork.ι s = l ≫ fork.ι s) : ∀ (j : walking_parallel_pair),
k ≫ s.π.app j = l ≫ s.π.app j
| zero := h
| one := by rw [←fork.app_zero_left, reassoc_of h]
/-- To check whether two maps are coequalized by both maps of a cofork, it suffices to check it for
the second map -/
lemma cofork.coequalizer_ext (s : cofork f g) {W : C} {k l : s.X ⟶ W}
(h : cofork.π s ≫ k = cofork.π s ≫ l) : ∀ (j : walking_parallel_pair),
s.ι.app j ≫ k = s.ι.app j ≫ l
| zero := by simp only [←cofork.left_app_one, category.assoc, h]
| one := h
lemma fork.is_limit.hom_ext {s : fork f g} (hs : is_limit s) {W : C} {k l : W ⟶ s.X}
(h : k ≫ fork.ι s = l ≫ fork.ι s) : k = l :=
hs.hom_ext $ fork.equalizer_ext _ h
lemma cofork.is_colimit.hom_ext {s : cofork f g} (hs : is_colimit s) {W : C} {k l : s.X ⟶ W}
(h : cofork.π s ≫ k = cofork.π s ≫ l) : k = l :=
hs.hom_ext $ cofork.coequalizer_ext _ h
/-- If `s` is a limit fork over `f` and `g`, then a morphism `k : W ⟶ X` satisfying
`k ≫ f = k ≫ g` induces a morphism `l : W ⟶ s.X` such that `l ≫ fork.ι s = k`. -/
def fork.is_limit.lift' {s : fork f g} (hs : is_limit s) {W : C} (k : W ⟶ X) (h : k ≫ f = k ≫ g) :
{l : W ⟶ s.X // l ≫ fork.ι s = k} :=
⟨hs.lift $ fork.of_ι _ h, hs.fac _ _⟩
/-- If `s` is a colimit cofork over `f` and `g`, then a morphism `k : Y ⟶ W` satisfying
`f ≫ k = g ≫ k` induces a morphism `l : s.X ⟶ W` such that `cofork.π s ≫ l = k`. -/
def cofork.is_colimit.desc' {s : cofork f g} (hs : is_colimit s) {W : C} (k : Y ⟶ W)
(h : f ≫ k = g ≫ k) : {l : s.X ⟶ W // cofork.π s ≫ l = k} :=
⟨hs.desc $ cofork.of_π _ h, hs.fac _ _⟩
/-- This is a slightly more convenient method to verify that a fork is a limit cone. It
only asks for a proof of facts that carry any mathematical content -/
def fork.is_limit.mk (t : fork f g)
(lift : Π (s : fork f g), s.X ⟶ t.X)
(fac : ∀ (s : fork f g), lift s ≫ fork.ι t = fork.ι s)
(uniq : ∀ (s : fork f g) (m : s.X ⟶ t.X)
(w : ∀ j : walking_parallel_pair, m ≫ t.π.app j = s.π.app j), m = lift s) :
is_limit t :=
{ lift := lift,
fac' := λ s j, walking_parallel_pair.cases_on j (fac s) $
by erw [←s.w left, ←t.w left, ←category.assoc, fac]; refl,
uniq' := uniq }
/-- This is a slightly more convenient method to verify that a cofork is a colimit cocone. It
only asks for a proof of facts that carry any mathematical content -/
def cofork.is_colimit.mk (t : cofork f g)
(desc : Π (s : cofork f g), t.X ⟶ s.X)
(fac : ∀ (s : cofork f g), cofork.π t ≫ desc s = cofork.π s)
(uniq : ∀ (s : cofork f g) (m : t.X ⟶ s.X)
(w : ∀ j : walking_parallel_pair, t.ι.app j ≫ m = s.ι.app j), m = desc s) :
is_colimit t :=
{ desc := desc,
fac' := λ s j, walking_parallel_pair.cases_on j
(by erw [←s.w left, ←t.w left, category.assoc, fac]; refl) (fac s),
uniq' := uniq }
/-- This is a helper construction that can be useful when verifying that a category has all
equalizers. Given `F : walking_parallel_pair ⥤ C`, which is really the same as
`parallel_pair (F.map left) (F.map right)`, and a fork on `F.map left` and `F.map right`,
we get a cone on `F`.
If you're thinking about using this, have a look at `has_equalizers_of_has_limit_parallel_pair`,
which you may find to be an easier way of achieving your goal. -/
def cone.of_fork
{F : walking_parallel_pair.{v} ⥤ C} (t : fork (F.map left) (F.map right)) : cone F :=
{ X := t.X,
π :=
{ app := λ X, t.π.app X ≫ eq_to_hom (by tidy),
naturality' := λ j j' g, by { cases j; cases j'; cases g; dsimp; simp } } }
/-- This is a helper construction that can be useful when verifying that a category has all
coequalizers. Given `F : walking_parallel_pair ⥤ C`, which is really the same as
`parallel_pair (F.map left) (F.map right)`, and a cofork on `F.map left` and `F.map right`,
we get a cocone on `F`.
If you're thinking about using this, have a look at
`has_coequalizers_of_has_colimit_parallel_pair`, which you may find to be an easier way of
achieving your goal. -/
def cocone.of_cofork
{F : walking_parallel_pair.{v} ⥤ C} (t : cofork (F.map left) (F.map right)) : cocone F :=
{ X := t.X,
ι :=
{ app := λ X, eq_to_hom (by tidy) ≫ t.ι.app X,
naturality' := λ j j' g, by { cases j; cases j'; cases g; dsimp; simp } } }
@[simp] lemma cone.of_fork_π
{F : walking_parallel_pair.{v} ⥤ C} (t : fork (F.map left) (F.map right)) (j) :
(cone.of_fork t).π.app j = t.π.app j ≫ eq_to_hom (by tidy) := rfl
@[simp] lemma cocone.of_cofork_ι
{F : walking_parallel_pair.{v} ⥤ C} (t : cofork (F.map left) (F.map right)) (j) :
(cocone.of_cofork t).ι.app j = eq_to_hom (by tidy) ≫ t.ι.app j := rfl
/-- Given `F : walking_parallel_pair ⥤ C`, which is really the same as
`parallel_pair (F.map left) (F.map right)` and a cone on `F`, we get a fork on
`F.map left` and `F.map right`. -/
def fork.of_cone
{F : walking_parallel_pair.{v} ⥤ C} (t : cone F) : fork (F.map left) (F.map right) :=
{ X := t.X,
π := { app := λ X, t.π.app X ≫ eq_to_hom (by tidy) } }
/-- Given `F : walking_parallel_pair.{v} ⥤ C`, which is really the same as
`parallel_pair (F.map left) (F.map right)` and a cocone on `F`, we get a cofork on
`F.map left` and `F.map right`. -/
def cofork.of_cocone
{F : walking_parallel_pair.{v} ⥤ C} (t : cocone F) : cofork (F.map left) (F.map right) :=
{ X := t.X,
ι := { app := λ X, eq_to_hom (by tidy) ≫ t.ι.app X } }
@[simp] lemma fork.of_cone_π {F : walking_parallel_pair.{v} ⥤ C} (t : cone F) (j) :
(fork.of_cone t).π.app j = t.π.app j ≫ eq_to_hom (by tidy) := rfl
@[simp] lemma cofork.of_cocone_ι {F : walking_parallel_pair.{v} ⥤ C} (t : cocone F) (j) :
(cofork.of_cocone t).ι.app j = eq_to_hom (by tidy) ≫ t.ι.app j := rfl
variables (f g)
section
variables [has_limit (parallel_pair f g)]
/-- If we have chosen an equalizer of `f` and `g`, we can access the corresponding object by
saying `equalizer f g`. -/
abbreviation equalizer := limit (parallel_pair f g)
/-- If we have chosen an equalizer of `f` and `g`, we can access the inclusion
`equalizer f g ⟶ X` by saying `equalizer.ι f g`. -/
abbreviation equalizer.ι : equalizer f g ⟶ X :=
limit.π (parallel_pair f g) zero
@[simp] lemma equalizer.ι.fork :
fork.ι (limit.cone (parallel_pair f g)) = equalizer.ι f g := rfl
@[simp] lemma equalizer.ι.eq_app_zero :
(limit.cone (parallel_pair f g)).π.app zero = equalizer.ι f g := rfl
@[reassoc] lemma equalizer.condition : equalizer.ι f g ≫ f = equalizer.ι f g ≫ g :=
fork.condition $ limit.cone $ parallel_pair f g
variables {f g}
/-- A morphism `k : W ⟶ X` satisfying `k ≫ f = k ≫ g` factors through the equalizer of `f` and `g`
via `equalizer.lift : W ⟶ equalizer f g`. -/
abbreviation equalizer.lift {W : C} (k : W ⟶ X) (h : k ≫ f = k ≫ g) : W ⟶ equalizer f g :=
limit.lift (parallel_pair f g) (fork.of_ι k h)
@[simp, reassoc]
lemma equalizer.lift_ι {W : C} (k : W ⟶ X) (h : k ≫ f = k ≫ g) :
equalizer.lift k h ≫ equalizer.ι f g = k :=
limit.lift_π _ _
/-- A morphism `k : W ⟶ X` satisfying `k ≫ f = k ≫ g` induces a morphism `l : W ⟶ equalizer f g`
satisfying `l ≫ equalizer.ι f g = k`. -/
def equalizer.lift' {W : C} (k : W ⟶ X) (h : k ≫ f = k ≫ g) :
{l : W ⟶ equalizer f g // l ≫ equalizer.ι f g = k} :=
⟨equalizer.lift k h, equalizer.lift_ι _ _⟩
/-- Two maps into an equalizer are equal if they are are equal when composed with the equalizer
map. -/
@[ext] lemma equalizer.hom_ext {W : C} {k l : W ⟶ equalizer f g}
(h : k ≫ equalizer.ι f g = l ≫ equalizer.ι f g) : k = l :=
fork.is_limit.hom_ext (limit.is_limit _) h
/-- An equalizer morphism is a monomorphism -/
instance equalizer.ι_mono : mono (equalizer.ι f g) :=
{ right_cancellation := λ Z h k w, equalizer.hom_ext w }
end
section
variables {f g}
/-- The equalizer morphism in any limit cone is a monomorphism. -/
lemma mono_of_is_limit_parallel_pair {c : cone (parallel_pair f g)} (i : is_limit c) :
mono (fork.ι c) :=
{ right_cancellation := λ Z h k w, fork.is_limit.hom_ext i w }
end
section
variables {f g}
/-- The identity determines a cone on the equalizer diagram of `f` and `g` if `f = g`. -/
def id_fork (h : f = g) : fork f g :=
fork.of_ι (𝟙 X) $ h ▸ rfl
/-- The identity on `X` is an equalizer of `(f, g)`, if `f = g`. -/
def is_limit_id_fork (h : f = g) : is_limit (id_fork h) :=
fork.is_limit.mk _
(λ s, fork.ι s)
(λ s, category.comp_id _)
(λ s m h, by { convert h zero, exact (category.comp_id _).symm })
/-- Every equalizer of `(f, g)`, where `f = g`, is an isomorphism. -/
def is_iso_limit_cone_parallel_pair_of_eq (h₀ : f = g) {c : cone (parallel_pair f g)}
(h : is_limit c) : is_iso (c.π.app zero) :=
is_iso.of_iso $ is_limit.cone_point_unique_up_to_iso h $ is_limit_id_fork h₀
/-- The equalizer of `(f, g)`, where `f = g`, is an isomorphism. -/
def equalizer.ι_of_eq [has_limit (parallel_pair f g)] (h : f = g) : is_iso (equalizer.ι f g) :=
is_iso_limit_cone_parallel_pair_of_eq h $ limit.is_limit _
/-- Every equalizer of `(f, f)` is an isomorphism. -/
def is_iso_limit_cone_parallel_pair_of_self {c : cone (parallel_pair f f)} (h : is_limit c) :
is_iso (c.π.app zero) :=
is_iso_limit_cone_parallel_pair_of_eq rfl h
/-- An equalizer that is an epimorphism is an isomorphism. -/
def is_iso_limit_cone_parallel_pair_of_epi {c : cone (parallel_pair f g)}
(h : is_limit c) [epi (c.π.app zero)] : is_iso (c.π.app zero) :=
is_iso_limit_cone_parallel_pair_of_eq ((cancel_epi _).1 (fork.condition c)) h
end
/-- The equalizer of `(f, f)` is an isomorphism. -/
def equalizer.ι_of_self [has_limit (parallel_pair f f)] : is_iso (equalizer.ι f f) :=
equalizer.ι_of_eq rfl
section
variables [has_colimit (parallel_pair f g)]
/-- If we have chosen a coequalizer of `f` and `g`, we can access the corresponding object by
saying `coequalizer f g`. -/
abbreviation coequalizer := colimit (parallel_pair f g)
/-- If we have chosen a coequalizer of `f` and `g`, we can access the corresponding projection by
saying `coequalizer.π f g`. -/
abbreviation coequalizer.π : Y ⟶ coequalizer f g :=
colimit.ι (parallel_pair f g) one
@[simp] lemma coequalizer.π.cofork :
cofork.π (colimit.cocone (parallel_pair f g)) = coequalizer.π f g := rfl
@[simp] lemma coequalizer.π.eq_app_one :
(colimit.cocone (parallel_pair f g)).ι.app one = coequalizer.π f g := rfl
@[reassoc] lemma coequalizer.condition : f ≫ coequalizer.π f g = g ≫ coequalizer.π f g :=
cofork.condition $ colimit.cocone $ parallel_pair f g
variables {f g}
/-- Any morphism `k : Y ⟶ W` satisfying `f ≫ k = g ≫ k` factors through the coequalizer of `f`
and `g` via `coequalizer.desc : coequalizer f g ⟶ W`. -/
abbreviation coequalizer.desc {W : C} (k : Y ⟶ W) (h : f ≫ k = g ≫ k) : coequalizer f g ⟶ W :=
colimit.desc (parallel_pair f g) (cofork.of_π k h)
@[simp, reassoc]
lemma coequalizer.π_desc {W : C} (k : Y ⟶ W) (h : f ≫ k = g ≫ k) :
coequalizer.π f g ≫ coequalizer.desc k h = k :=
colimit.ι_desc _ _
/-- Any morphism `k : Y ⟶ W` satisfying `f ≫ k = g ≫ k` induces a morphism
`l : coequalizer f g ⟶ W` satisfying `coequalizer.π ≫ g = l`. -/
def coequalizer.desc' {W : C} (k : Y ⟶ W) (h : f ≫ k = g ≫ k) :
{l : coequalizer f g ⟶ W // coequalizer.π f g ≫ l = k} :=
⟨coequalizer.desc k h, coequalizer.π_desc _ _⟩
/-- Two maps from a coequalizer are equal if they are equal when composed with the coequalizer
map -/
@[ext] lemma coequalizer.hom_ext {W : C} {k l : coequalizer f g ⟶ W}
(h : coequalizer.π f g ≫ k = coequalizer.π f g ≫ l) : k = l :=
cofork.is_colimit.hom_ext (colimit.is_colimit _) h
/-- A coequalizer morphism is an epimorphism -/
instance coequalizer.π_epi : epi (coequalizer.π f g) :=
{ left_cancellation := λ Z h k w, coequalizer.hom_ext w }
end
section
variables {f g}
/-- The coequalizer morphism in any colimit cocone is an epimorphism. -/
lemma epi_of_is_colimit_parallel_pair {c : cocone (parallel_pair f g)} (i : is_colimit c) :
epi (c.ι.app one) :=
{ left_cancellation := λ Z h k w, cofork.is_colimit.hom_ext i w }
end
section
variables {f g}
/-- The identity determines a cocone on the coequalizer diagram of `f` and `g`, if `f = g`. -/
def id_cofork (h : f = g) : cofork f g :=
cofork.of_π (𝟙 Y) $ h ▸ rfl
/-- The identity on `Y` is a coequalizer of `(f, g)`, where `f = g`. -/
def is_colimit_id_cofork (h : f = g) : is_colimit (id_cofork h) :=
cofork.is_colimit.mk _
(λ s, cofork.π s)
(λ s, category.id_comp _)
(λ s m h, by { convert h one, exact (category.id_comp _).symm })
/-- Every coequalizer of `(f, g)`, where `f = g`, is an isomorphism. -/
def is_iso_colimit_cocone_parallel_pair_of_eq (h₀ : f = g) {c : cocone (parallel_pair f g)}
(h : is_colimit c) : is_iso (c.ι.app one) :=
is_iso.of_iso $ is_colimit.cocone_point_unique_up_to_iso (is_colimit_id_cofork h₀) h
/-- The coequalizer of `(f, g)`, where `f = g`, is an isomorphism. -/
def coequalizer.π_of_eq [has_colimit (parallel_pair f g)] (h : f = g) :
is_iso (coequalizer.π f g) :=
is_iso_colimit_cocone_parallel_pair_of_eq h $ colimit.is_colimit _
/-- Every coequalizer of `(f, f)` is an isomorphism. -/
def is_iso_colimit_cocone_parallel_pair_of_self {c : cocone (parallel_pair f f)}
(h : is_colimit c) : is_iso (c.ι.app one) :=
is_iso_colimit_cocone_parallel_pair_of_eq rfl h
/-- A coequalizer that is a monomorphism is an isomorphism. -/
def is_iso_limit_cocone_parallel_pair_of_epi {c : cocone (parallel_pair f g)}
(h : is_colimit c) [mono (c.ι.app one)] : is_iso (c.ι.app one) :=
is_iso_colimit_cocone_parallel_pair_of_eq ((cancel_mono _).1 (cofork.condition c)) h
end
/-- The coequalizer of `(f, f)` is an isomorphism. -/
def coequalizer.π_of_self [has_colimit (parallel_pair f f)] : is_iso (coequalizer.π f f) :=
coequalizer.π_of_eq rfl
variables (C)
/-- `has_equalizers` represents a choice of equalizer for every pair of morphisms -/
class has_equalizers :=
(has_limits_of_shape : has_limits_of_shape.{v} walking_parallel_pair C)
/-- `has_coequalizers` represents a choice of coequalizer for every pair of morphisms -/
class has_coequalizers :=
(has_colimits_of_shape : has_colimits_of_shape.{v} walking_parallel_pair C)
attribute [instance] has_equalizers.has_limits_of_shape has_coequalizers.has_colimits_of_shape
/-- Equalizers are finite limits, so if `C` has all finite limits, it also has all equalizers -/
def has_equalizers_of_has_finite_limits [has_finite_limits.{v} C] : has_equalizers.{v} C :=
{ has_limits_of_shape := infer_instance }
/-- Coequalizers are finite colimits, of if `C` has all finite colimits, it also has all
coequalizers -/
def has_coequalizers_of_has_finite_colimits [has_finite_colimits.{v} C] : has_coequalizers.{v} C :=
{ has_colimits_of_shape := infer_instance }
/-- If `C` has all limits of diagrams `parallel_pair f g`, then it has all equalizers -/
def has_equalizers_of_has_limit_parallel_pair
[Π {X Y : C} {f g : X ⟶ Y}, has_limit (parallel_pair f g)] : has_equalizers.{v} C :=
{ has_limits_of_shape := { has_limit := λ F, has_limit_of_iso (diagram_iso_parallel_pair F).symm } }
/-- If `C` has all colimits of diagrams `parallel_pair f g`, then it has all coequalizers -/
def has_coequalizers_of_has_colimit_parallel_pair
[Π {X Y : C} {f g : X ⟶ Y}, has_colimit (parallel_pair f g)] : has_coequalizers.{v} C :=
{ has_colimits_of_shape := { has_colimit := λ F, has_colimit_of_iso (diagram_iso_parallel_pair F) } }
section
-- In this section we show that a split mono `f` equalizes `(retraction f ≫ f)` and `(𝟙 Y)`.
variables {C} [split_mono f]
/--
A split mono `f` equalizes `(retraction f ≫ f)` and `(𝟙 Y)`.
Here we build the cone, and show in `split_mono_equalizes` that it is a limit cone.
-/
def cone_of_split_mono : cone (parallel_pair (𝟙 Y) (retraction f ≫ f)) :=
fork.of_ι f (by tidy)
@[simp] lemma cone_of_split_mono_π_app_zero : (cone_of_split_mono f).π.app zero = f := rfl
@[simp] lemma cone_of_split_mono_π_app_one : (cone_of_split_mono f).π.app one = f ≫ 𝟙 Y := rfl
/--
A split mono `f` equalizes `(retraction f ≫ f)` and `(𝟙 Y)`.
-/
def split_mono_equalizes {X Y : C} (f : X ⟶ Y) [split_mono f] : is_limit (cone_of_split_mono f) :=
{ lift := λ s, s.π.app zero ≫ retraction f,
fac' := λ s,
begin
rintros (⟨⟩|⟨⟩),
{ rw [cone_of_split_mono_π_app_zero],
erw [category.assoc, ← s.π.naturality right, s.π.naturality left, category.comp_id], },
{ erw [cone_of_split_mono_π_app_one, category.comp_id, category.assoc,
← s.π.naturality right, category.id_comp], }
end,
uniq' := λ s m w, begin rw ←(w zero), simp, end, }
end
section
-- In this section we show that a split epi `f` coequalizes `(f ≫ section_ f)` and `(𝟙 X)`.
variables {C} [split_epi f]
/--
A split epi `f` coequalizes `(f ≫ section_ f)` and `(𝟙 X)`.
Here we build the cocone, and show in `split_epi_coequalizes` that it is a colimit cocone.
-/
def cocone_of_split_epi : cocone (parallel_pair (𝟙 X) (f ≫ section_ f)) :=
cofork.of_π f (by tidy)
@[simp] lemma cocone_of_split_epi_ι_app_one : (cocone_of_split_epi f).ι.app one = f := rfl
@[simp] lemma cocone_of_split_epi_ι_app_zero : (cocone_of_split_epi f).ι.app zero = 𝟙 X ≫ f := rfl
/--
A split epi `f` coequalizes `(f ≫ section_ f)` and `(𝟙 X)`.
-/
def split_epi_coequalizes {X Y : C} (f : X ⟶ Y) [split_epi f] : is_colimit (cocone_of_split_epi f) :=
{ desc := λ s, section_ f ≫ s.ι.app one,
fac' := λ s,
begin
rintros (⟨⟩|⟨⟩),
{ erw [cocone_of_split_epi_ι_app_zero, category.assoc, category.id_comp, ←category.assoc,
s.ι.naturality right, functor.const.obj_map, category.comp_id], },
{ erw [cocone_of_split_epi_ι_app_one, ←category.assoc, s.ι.naturality right,
←s.ι.naturality left, category.id_comp] }
end,
uniq' := λ s m w, begin rw ←(w one), simp, end, }
end
end category_theory.limits
|
cd06b5422bdb03f401f12fffcfe97ba812711a6b | a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91 | /tests/lean/run/imp2.lean | 538d13aac82695759ec545976a7c160f82756f04 | [
"Apache-2.0"
] | permissive | soonhokong/lean-osx | 4a954262c780e404c1369d6c06516161d07fcb40 | 3670278342d2f4faa49d95b46d86642d7875b47c | refs/heads/master | 1,611,410,334,552 | 1,474,425,686,000 | 1,474,425,686,000 | 12,043,103 | 5 | 1 | null | null | null | null | UTF-8 | Lean | false | false | 134 | lean | check (λ {A : Type.{1}} (a : A), a) (10:num)
set_option trace.app_builder true
check (λ {A} (a : A), a) 10
check (λ a, a) (10:num)
|
678442ffa2a11aa56940573f87276024671b7e2e | 2fbe653e4bc441efde5e5d250566e65538709888 | /src/topology/metric_space/closeds.lean | f7253cd47fb52a19474bce3769deacd08122aa23 | [
"Apache-2.0"
] | permissive | aceg00/mathlib | 5e15e79a8af87ff7eb8c17e2629c442ef24e746b | 8786ea6d6d46d6969ac9a869eb818bf100802882 | refs/heads/master | 1,649,202,698,930 | 1,580,924,783,000 | 1,580,924,783,000 | 149,197,272 | 0 | 0 | Apache-2.0 | 1,537,224,208,000 | 1,537,224,207,000 | null | UTF-8 | Lean | false | false | 22,272 | lean | /-
Copyright (c) 2019 Sébastien Gouëzel. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Sébastien Gouëzel
-/
import topology.metric_space.hausdorff_distance topology.opens analysis.specific_limits
/-!
# Closed subsets
This file defines the metric and emetric space structure on the types of closed subsets and nonempty compact
subsets of a metric or emetric space.
The Hausdorff distance induces an emetric space structure on the type of closed subsets
of an emetric space, called `closeds`. Its completeness, resp. compactness, resp.
second-countability, follow from the corresponding properties of the original space.
In a metric space, the type of nonempty compact subsets (called `nonempty_compacts`) also
inherits a metric space structure from the Hausdorff distance, as the Hausdorff edistance is
always finite in this context.
-/
noncomputable theory
open_locale classical
open_locale topological_space
universe u
open classical lattice set function topological_space filter
namespace emetric
section
variables {α : Type u} [emetric_space α] {s : set α}
/-- In emetric spaces, the Hausdorff edistance defines an emetric space structure
on the type of closed subsets -/
instance closeds.emetric_space : emetric_space (closeds α) :=
{ edist := λs t, Hausdorff_edist s.val t.val,
edist_self := λs, Hausdorff_edist_self,
edist_comm := λs t, Hausdorff_edist_comm,
edist_triangle := λs t u, Hausdorff_edist_triangle,
eq_of_edist_eq_zero :=
λs t h, subtype.eq ((Hausdorff_edist_zero_iff_eq_of_closed s.property t.property).1 h) }
/-- The edistance to a closed set depends continuously on the point and the set -/
lemma continuous_inf_edist_Hausdorff_edist :
continuous (λp : α × (closeds α), inf_edist p.1 (p.2).val) :=
begin
refine continuous_of_le_add_edist 2 (by simp) _,
rintros ⟨x, s⟩ ⟨y, t⟩,
calc inf_edist x (s.val) ≤ inf_edist x (t.val) + Hausdorff_edist (t.val) (s.val) :
inf_edist_le_inf_edist_add_Hausdorff_edist
... ≤ (inf_edist y (t.val) + edist x y) + Hausdorff_edist (t.val) (s.val) :
add_le_add_right' inf_edist_le_inf_edist_add_edist
... = inf_edist y (t.val) + (edist x y + Hausdorff_edist (s.val) (t.val)) :
by simp [add_comm, Hausdorff_edist_comm]
... ≤ inf_edist y (t.val) + (edist (x, s) (y, t) + edist (x, s) (y, t)) :
add_le_add_left' (add_le_add' (by simp [edist, le_refl]) (by simp [edist, le_refl]))
... = inf_edist y (t.val) + 2 * edist (x, s) (y, t) :
by rw [← mul_two, mul_comm]
end
/-- Subsets of a given closed subset form a closed set -/
lemma is_closed_subsets_of_is_closed (hs : is_closed s) :
is_closed {t : closeds α | t.val ⊆ s} :=
begin
refine is_closed_of_closure_subset (λt ht x hx, _),
-- t : closeds α, ht : t ∈ closure {t : closeds α | t.val ⊆ s},
-- x : α, hx : x ∈ t.val
-- goal : x ∈ s
have : x ∈ closure s,
{ refine mem_closure_iff'.2 (λε εpos, _),
rcases mem_closure_iff'.1 ht ε εpos with ⟨u, hu, Dtu⟩,
-- u : closeds α, hu : u ∈ {t : closeds α | t.val ⊆ s}, hu' : edist t u < ε
rcases exists_edist_lt_of_Hausdorff_edist_lt hx Dtu with ⟨y, hy, Dxy⟩,
-- y : α, hy : y ∈ u.val, Dxy : edist x y < ε
exact ⟨y, hu hy, Dxy⟩ },
rwa closure_eq_of_is_closed hs at this,
end
/-- By definition, the edistance on `closeds α` is given by the Hausdorff edistance -/
lemma closeds.edist_eq {s t : closeds α} : edist s t = Hausdorff_edist s.val t.val := rfl
/-- In a complete space, the type of closed subsets is complete for the
Hausdorff edistance. -/
instance closeds.complete_space [complete_space α] : complete_space (closeds α) :=
begin
/- We will show that, if a sequence of sets `s n` satisfies
`edist (s n) (s (n+1)) < 2^{-n}`, then it converges. This is enough to guarantee
completeness, by a standard completeness criterion.
We use the shorthand `B n = 2^{-n}` in ennreal. -/
let B : ℕ → ennreal := λ n, (2⁻¹)^n,
have B_pos : ∀ n, (0:ennreal) < B n,
by simp [B, ennreal.pow_pos],
have B_ne_top : ∀ n, B n ≠ ⊤,
by simp [B, ennreal.div_def, ennreal.pow_ne_top],
/- Consider a sequence of closed sets `s n` with `edist (s n) (s (n+1)) < B n`.
We will show that it converges. The limit set is t0 = ⋂n, closure (⋃m≥n, s m).
We will have to show that a point in `s n` is close to a point in `t0`, and a point
in `t0` is close to a point in `s n`. The completeness then follows from a
standard criterion. -/
refine complete_of_convergent_controlled_sequences B B_pos (λs hs, _),
let t0 := ⋂n, closure (⋃m≥n, (s m).val),
let t : closeds α := ⟨t0, is_closed_Inter (λ_, is_closed_closure)⟩,
use t,
-- The inequality is written this way to agree with `edist_le_of_edist_le_geometric_of_tendsto₀`
have I1 : ∀n:ℕ, ∀x ∈ (s n).val, ∃y ∈ t0, edist x y ≤ 2 * B n,
{ /- This is the main difficulty of the proof. Starting from `x ∈ s n`, we want
to find a point in `t0` which is close to `x`. Define inductively a sequence of
points `z m` with `z n = x` and `z m ∈ s m` and `edist (z m) (z (m+1)) ≤ B m`. This is
possible since the Hausdorff distance between `s m` and `s (m+1)` is at most `B m`.
This sequence is a Cauchy sequence, therefore converging as the space is complete, to
a limit which satisfies the required properties. -/
assume n x hx,
obtain ⟨z, hz₀, hz⟩ : ∃ z : Π l, (s (n+l)).val, (z 0:α) = x ∧
∀ k, edist (z k:α) (z (k+1):α) ≤ B n / 2^k,
{ -- We prove existence of the sequence by induction.
have : ∀ (l : ℕ) (z : (s (n+l)).val), ∃ z' : (s (n+l+1)).val, edist (z:α) z' ≤ B n / 2^l,
{ assume l z,
obtain ⟨z', z'_mem, hz'⟩ : ∃ z' ∈ (s (n+l+1)).val, edist (z:α) z' < B n / 2^l,
{ apply exists_edist_lt_of_Hausdorff_edist_lt z.2,
simp only [B, ennreal.div_def, ennreal.inv_pow'],
rw [← pow_add],
apply hs; simp },
exact ⟨⟨z', z'_mem⟩, le_of_lt hz'⟩ },
use [λ k, nat.rec_on k ⟨x, hx⟩ (λl z, some (this l z)), rfl],
exact λ k, some_spec (this k _) },
-- it follows from the previous bound that `z` is a Cauchy sequence
have : cauchy_seq (λ k, ((z k):α)),
from cauchy_seq_of_edist_le_geometric_two (B n) (B_ne_top n) hz,
-- therefore, it converges
rcases cauchy_seq_tendsto_of_complete this with ⟨y, y_lim⟩,
use y,
-- the limit point `y` will be the desired point, in `t0` and close to our initial point `x`.
-- First, we check it belongs to `t0`.
have : y ∈ t0 := mem_Inter.2 (λk, mem_closure_of_tendsto (by simp) y_lim
begin
simp only [exists_prop, set.mem_Union, filter.mem_at_top_sets, set.mem_preimage, set.preimage_Union],
exact ⟨k, λ m hm, ⟨n+m, zero_add k ▸ add_le_add (zero_le n) hm, (z m).2⟩⟩
end),
use this,
-- Then, we check that `y` is close to `x = z n`. This follows from the fact that `y`
-- is the limit of `z k`, and the distance between `z n` and `z k` has already been estimated.
rw [← hz₀],
exact edist_le_of_edist_le_geometric_two_of_tendsto₀ (B n) hz y_lim },
have I2 : ∀n:ℕ, ∀x ∈ t0, ∃y ∈ (s n).val, edist x y ≤ 2 * B n,
{ /- For the (much easier) reverse inequality, we start from a point `x ∈ t0` and we want
to find a point `y ∈ s n` which is close to `x`.
`x` belongs to `t0`, the intersection of the closures. In particular, it is well
approximated by a point `z` in `⋃m≥n, s m`, say in `s m`. Since `s m` and
`s n` are close, this point is itself well approximated by a point `y` in `s n`,
as required. -/
assume n x xt0,
have : x ∈ closure (⋃m≥n, (s m).val), by apply mem_Inter.1 xt0 n,
rcases mem_closure_iff'.1 this (B n) (B_pos n) with ⟨z, hz, Dxz⟩,
-- z : α, Dxz : edist x z < B n,
simp only [exists_prop, set.mem_Union] at hz,
rcases hz with ⟨m, ⟨m_ge_n, hm⟩⟩,
-- m : ℕ, m_ge_n : m ≥ n, hm : z ∈ (s m).val
have : Hausdorff_edist (s m).val (s n).val < B n := hs n m n m_ge_n (le_refl n),
rcases exists_edist_lt_of_Hausdorff_edist_lt hm this with ⟨y, hy, Dzy⟩,
-- y : α, hy : y ∈ (s n).val, Dzy : edist z y < B n
exact ⟨y, hy, calc
edist x y ≤ edist x z + edist z y : edist_triangle _ _ _
... ≤ B n + B n : add_le_add' (le_of_lt Dxz) (le_of_lt Dzy)
... = 2 * B n : (two_mul _).symm ⟩ },
-- Deduce from the above inequalities that the distance between `s n` and `t0` is at most `2 B n`.
have main : ∀n:ℕ, edist (s n) t ≤ 2 * B n := λn, Hausdorff_edist_le_of_mem_edist (I1 n) (I2 n),
-- from this, the convergence of `s n` to `t0` follows.
refine (tendsto_at_top _).2 (λε εpos, _),
have : tendsto (λn, 2 * B n) at_top (𝓝 (2 * 0)),
from ennreal.tendsto.const_mul
(ennreal.tendsto_pow_at_top_nhds_0_of_lt_1 $ by simp [ennreal.one_lt_two])
(or.inr $ by simp),
rw mul_zero at this,
obtain ⟨N, hN⟩ : ∃ N, ∀ b ≥ N, ε > 2 * B b,
from ((tendsto_order.1 this).2 ε εpos).exists_forall_of_at_top,
exact ⟨N, λn hn, lt_of_le_of_lt (main n) (hN n hn)⟩
end
/-- In a compact space, the type of closed subsets is compact. -/
instance closeds.compact_space [compact_space α] : compact_space (closeds α) :=
⟨begin
/- by completeness, it suffices to show that it is totally bounded,
i.e., for all ε>0, there is a finite set which is ε-dense.
start from a set `s` which is ε-dense in α. Then the subsets of `s`
are finitely many, and ε-dense for the Hausdorff distance. -/
refine compact_of_totally_bounded_is_closed (emetric.totally_bounded_iff.2 (λε εpos, _)) is_closed_univ,
rcases dense εpos with ⟨δ, δpos, δlt⟩,
rcases emetric.totally_bounded_iff.1 (compact_iff_totally_bounded_complete.1 (@compact_univ α _ _)).1 δ δpos
with ⟨s, fs, hs⟩,
-- s : set α, fs : finite s, hs : univ ⊆ ⋃ (y : α) (H : y ∈ s), eball y δ
-- we first show that any set is well approximated by a subset of `s`.
have main : ∀ u : set α, ∃v ⊆ s, Hausdorff_edist u v ≤ δ,
{ assume u,
let v := {x : α | x ∈ s ∧ ∃y∈u, edist x y < δ},
existsi [v, ((λx hx, hx.1) : v ⊆ s)],
refine Hausdorff_edist_le_of_mem_edist _ _,
{ assume x hx,
have : x ∈ ⋃y ∈ s, ball y δ := hs (by simp),
rcases mem_bUnion_iff.1 this with ⟨y, ys, dy⟩,
have : edist y x < δ := by simp at dy; rwa [edist_comm] at dy,
exact ⟨y, ⟨ys, ⟨x, hx, this⟩⟩, le_of_lt dy⟩ },
{ rintros x ⟨hx1, ⟨y, yu, hy⟩⟩,
exact ⟨y, yu, le_of_lt hy⟩ }},
-- introduce the set F of all subsets of `s` (seen as members of `closeds α`).
let F := {f : closeds α | f.val ⊆ s},
use F,
split,
-- `F` is finite
{ apply @finite_of_finite_image _ _ F (λf, f.val),
{ apply set.inj_on_of_injective, simp [subtype.val_injective] },
{ refine finite_subset (finite_subsets_of_finite fs) (λb, _),
simp only [and_imp, set.mem_image, set.mem_set_of_eq, exists_imp_distrib],
assume x hx hx',
rwa hx' at hx }},
-- `F` is ε-dense
{ assume u _,
rcases main u.val with ⟨t0, t0s, Dut0⟩,
have : is_closed t0 := closed_of_compact _ (finite_subset fs t0s).compact,
let t : closeds α := ⟨t0, this⟩,
have : t ∈ F := t0s,
have : edist u t < ε := lt_of_le_of_lt Dut0 δlt,
apply mem_bUnion_iff.2,
exact ⟨t, ‹t ∈ F›, this⟩ }
end⟩
/-- In an emetric space, the type of non-empty compact subsets is an emetric space,
where the edistance is the Hausdorff edistance -/
instance nonempty_compacts.emetric_space : emetric_space (nonempty_compacts α) :=
{ edist := λs t, Hausdorff_edist s.val t.val,
edist_self := λs, Hausdorff_edist_self,
edist_comm := λs t, Hausdorff_edist_comm,
edist_triangle := λs t u, Hausdorff_edist_triangle,
eq_of_edist_eq_zero := λs t h, subtype.eq $ begin
have : closure (s.val) = closure (t.val) := Hausdorff_edist_zero_iff_closure_eq_closure.1 h,
rwa [closure_eq_iff_is_closed.2 (closed_of_compact _ s.property.2),
closure_eq_iff_is_closed.2 (closed_of_compact _ t.property.2)] at this,
end }
/-- `nonempty_compacts.to_closeds` is a uniform embedding (as it is an isometry) -/
lemma nonempty_compacts.to_closeds.uniform_embedding :
uniform_embedding (@nonempty_compacts.to_closeds α _ _) :=
isometry.uniform_embedding $ λx y, rfl
/-- The range of `nonempty_compacts.to_closeds` is closed in a complete space -/
lemma nonempty_compacts.is_closed_in_closeds [complete_space α] :
is_closed (nonempty_compacts.to_closeds '' (univ : set (nonempty_compacts α))) :=
begin
have : nonempty_compacts.to_closeds '' univ = {s : closeds α | s.val.nonempty ∧ compact s.val},
{ ext,
simp only [set.image_univ, set.mem_range, ne.def, set.mem_set_of_eq],
split,
{ rintros ⟨y, hy⟩,
have : x.val = y.val := by rcases hy; simp,
rw this,
exact y.property },
{ rintros ⟨hx1, hx2⟩,
existsi (⟨x.val, ⟨hx1, hx2⟩⟩ : nonempty_compacts α),
apply subtype.eq,
refl }},
rw this,
refine is_closed_of_closure_subset (λs hs, _),
split,
{ -- take a set set t which is nonempty and at distance at most 1 of s
rcases mem_closure_iff'.1 hs 1 ennreal.zero_lt_one with ⟨t, ht, Dst⟩,
rw edist_comm at Dst,
-- this set t contains a point x
rcases ht.1 with ⟨x, hx⟩,
-- by the Hausdorff distance control, this point x is at distance at most 1
-- of a point y in s
rcases exists_edist_lt_of_Hausdorff_edist_lt hx Dst with ⟨y, hy, _⟩,
-- this shows that s is not empty
exact ⟨_, hy⟩ },
{ refine compact_iff_totally_bounded_complete.2 ⟨_, is_complete_of_is_closed s.property⟩,
refine totally_bounded_iff.2 (λε εpos, _),
-- we have to show that s is covered by finitely many eballs of radius ε
-- pick a nonempty compact set t at distance at most ε/2 of s
rcases mem_closure_iff'.1 hs (ε/2) (ennreal.half_pos εpos) with ⟨t, ht, Dst⟩,
-- cover this space with finitely many balls of radius ε/2
rcases totally_bounded_iff.1 (compact_iff_totally_bounded_complete.1 ht.2).1 (ε/2) (ennreal.half_pos εpos)
with ⟨u, fu, ut⟩,
refine ⟨u, ⟨fu, λx hx, _⟩⟩,
-- u : set α, fu : finite u, ut : t.val ⊆ ⋃ (y : α) (H : y ∈ u), eball y (ε / 2)
-- then s is covered by the union of the balls centered at u of radius ε
rcases exists_edist_lt_of_Hausdorff_edist_lt hx Dst with ⟨z, hz, Dxz⟩,
rcases mem_bUnion_iff.1 (ut hz) with ⟨y, hy, Dzy⟩,
have : edist x y < ε := calc
edist x y ≤ edist x z + edist z y : edist_triangle _ _ _
... < ε/2 + ε/2 : ennreal.add_lt_add Dxz Dzy
... = ε : ennreal.add_halves _,
exact mem_bUnion hy this },
end
/-- In a complete space, the type of nonempty compact subsets is complete. This follows
from the same statement for closed subsets -/
instance nonempty_compacts.complete_space [complete_space α] : complete_space (nonempty_compacts α) :=
begin
apply complete_space_of_is_complete_univ,
apply (is_complete_image_iff nonempty_compacts.to_closeds.uniform_embedding).1,
apply is_complete_of_is_closed,
exact nonempty_compacts.is_closed_in_closeds
end
/-- In a compact space, the type of nonempty compact subsets is compact. This follows from
the same statement for closed subsets -/
instance nonempty_compacts.compact_space [compact_space α] : compact_space (nonempty_compacts α) :=
⟨begin
rw embedding.compact_iff_compact_image nonempty_compacts.to_closeds.uniform_embedding.embedding,
exact nonempty_compacts.is_closed_in_closeds.compact
end⟩
/-- In a second countable space, the type of nonempty compact subsets is second countable -/
instance nonempty_compacts.second_countable_topology [second_countable_topology α] :
second_countable_topology (nonempty_compacts α) :=
begin
haveI : separable_space (nonempty_compacts α) :=
begin
/- To obtain a countable dense subset of `nonempty_compacts α`, start from
a countable dense subset `s` of α, and then consider all its finite nonempty subsets.
This set is countable and made of nonempty compact sets. It turns out to be dense:
by total boundedness, any compact set `t` can be covered by finitely many small balls, and
approximations in `s` of the centers of these balls give the required finite approximation
of `t`. -/
have : separable_space α := by apply_instance,
rcases this.exists_countable_closure_eq_univ with ⟨s, cs, s_dense⟩,
let v0 := {t : set α | finite t ∧ t ⊆ s},
let v : set (nonempty_compacts α) := {t : nonempty_compacts α | t.val ∈ v0},
refine ⟨⟨v, ⟨_, _⟩⟩⟩,
{ have : countable (subtype.val '' v),
{ refine countable_subset (λx hx, _) (countable_set_of_finite_subset cs),
rcases (mem_image _ _ _).1 hx with ⟨y, ⟨hy, yx⟩⟩,
rw ← yx,
exact hy },
apply countable_of_injective_of_countable_image _ this,
apply inj_on_of_inj_on_of_subset (injective_iff_inj_on_univ.1 subtype.val_injective)
(subset_univ _) },
{ refine subset.antisymm (subset_univ _) (λt ht, mem_closure_iff'.2 (λε εpos, _)),
-- t is a compact nonempty set, that we have to approximate uniformly by a a set in `v`.
rcases dense εpos with ⟨δ, δpos, δlt⟩,
-- construct a map F associating to a point in α an approximating point in s, up to δ/2.
have Exy : ∀x, ∃y, y ∈ s ∧ edist x y < δ/2,
{ assume x,
have : x ∈ closure s := by rw s_dense; exact mem_univ _,
rcases mem_closure_iff'.1 this (δ/2) (ennreal.half_pos δpos) with ⟨y, ys, hy⟩,
exact ⟨y, ⟨ys, hy⟩⟩ },
let F := λx, some (Exy x),
have Fspec : ∀x, F x ∈ s ∧ edist x (F x) < δ/2 := λx, some_spec (Exy x),
-- cover `t` with finitely many balls. Their centers form a set `a`
have : totally_bounded t.val := (compact_iff_totally_bounded_complete.1 t.property.2).1,
rcases totally_bounded_iff.1 this (δ/2) (ennreal.half_pos δpos) with ⟨a, af, ta⟩,
-- a : set α, af : finite a, ta : t.val ⊆ ⋃ (y : α) (H : y ∈ a), eball y (δ / 2)
-- replace each center by a nearby approximation in `s`, giving a new set `b`
let b := F '' a,
have : finite b := finite_image _ af,
have tb : ∀x ∈ t.val, ∃y ∈ b, edist x y < δ,
{ assume x hx,
rcases mem_bUnion_iff.1 (ta hx) with ⟨z, za, Dxz⟩,
existsi [F z, mem_image_of_mem _ za],
calc edist x (F z) ≤ edist x z + edist z (F z) : edist_triangle _ _ _
... < δ/2 + δ/2 : ennreal.add_lt_add Dxz (Fspec z).2
... = δ : ennreal.add_halves _ },
-- keep only the points in `b` that are close to point in `t`, yielding a new set `c`
let c := {y ∈ b | ∃x∈t.val, edist x y < δ},
have : finite c := finite_subset ‹finite b› (λx hx, hx.1),
-- points in `t` are well approximated by points in `c`
have tc : ∀x ∈ t.val, ∃y ∈ c, edist x y ≤ δ,
{ assume x hx,
rcases tb x hx with ⟨y, yv, Dxy⟩,
have : y ∈ c := by simp [c, -mem_image]; exact ⟨yv, ⟨x, hx, Dxy⟩⟩,
exact ⟨y, this, le_of_lt Dxy⟩ },
-- points in `c` are well approximated by points in `t`
have ct : ∀y ∈ c, ∃x ∈ t.val, edist y x ≤ δ,
{ rintros y ⟨hy1, ⟨x, xt, Dyx⟩⟩,
have : edist y x ≤ δ := calc
edist y x = edist x y : edist_comm _ _
... ≤ δ : le_of_lt Dyx,
exact ⟨x, xt, this⟩ },
-- it follows that their Hausdorff distance is small
have : Hausdorff_edist t.val c ≤ δ :=
Hausdorff_edist_le_of_mem_edist tc ct,
have Dtc : Hausdorff_edist t.val c < ε := lt_of_le_of_lt this δlt,
-- the set `c` is not empty, as it is well approximated by a nonempty set
have hc : c.nonempty,
from nonempty_of_Hausdorff_edist_ne_top t.property.1 (lattice.ne_top_of_lt Dtc),
-- let `d` be the version of `c` in the type `nonempty_compacts α`
let d : nonempty_compacts α := ⟨c, ⟨hc, ‹finite c›.compact⟩⟩,
have : c ⊆ s,
{ assume x hx,
rcases (mem_image _ _ _).1 hx.1 with ⟨y, ⟨ya, yx⟩⟩,
rw ← yx,
exact (Fspec y).1 },
have : d ∈ v := ⟨‹finite c›, this⟩,
-- we have proved that `d` is a good approximation of `t` as requested
exact ⟨d, ‹d ∈ v›, Dtc⟩ },
end,
apply second_countable_of_separable,
end
end --section
end emetric --namespace
namespace metric
section
variables {α : Type u} [metric_space α]
/-- `nonempty_compacts α` inherits a metric space structure, as the Hausdorff
edistance between two such sets is finite. -/
instance nonempty_compacts.metric_space : metric_space (nonempty_compacts α) :=
emetric_space.to_metric_space $ λx y, Hausdorff_edist_ne_top_of_nonempty_of_bounded x.2.1 y.2.1
(bounded_of_compact x.2.2) (bounded_of_compact y.2.2)
/-- The distance on `nonempty_compacts α` is the Hausdorff distance, by construction -/
lemma nonempty_compacts.dist_eq {x y : nonempty_compacts α} :
dist x y = Hausdorff_dist x.val y.val := rfl
lemma lipschitz_inf_dist_set (x : α) :
lipschitz_with 1 (λ s : nonempty_compacts α, inf_dist x s.val) :=
lipschitz_with.one_of_le_add $ assume s t,
by { rw dist_comm,
exact inf_dist_le_inf_dist_add_Hausdorff_dist (edist_ne_top t s) }
lemma lipschitz_inf_dist :
lipschitz_with 2 (λ p : α × (nonempty_compacts α), inf_dist p.1 p.2.val) :=
@lipschitz_with.uncurry' _ _ _ _ _ _ (λ (x : α) (s : nonempty_compacts α), inf_dist x s.val) 1 1
(λ s, lipschitz_inf_dist_pt s.val) lipschitz_inf_dist_set
lemma uniform_continuous_inf_dist_Hausdorff_dist :
uniform_continuous (λp : α × (nonempty_compacts α), inf_dist p.1 (p.2).val) :=
lipschitz_inf_dist.to_uniform_continuous
end --section
end metric --namespace
|
730966d0ef4edadd7bf6ddffcc5812eb10c04f34 | 9be442d9ec2fcf442516ed6e9e1660aa9071b7bd | /tests/pkg/user_ext/lakefile.lean | 370b5b551c6be402f84a1e32ac4647ca7edb2e8c | [
"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 | 85 | lean | import Lake
open System Lake DSL
package user_ext
@[defaultTarget] lean_lib UserExt
|
365f186743baea3d2fd89c79a523fc95e164901d | c777c32c8e484e195053731103c5e52af26a25d1 | /src/topology/category/Compactum.lean | 6bc1fc6992906e7bbe875ca6cec535f92cf80ee3 | [
"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 | 17,825 | lean | /-
Copyright (c) 2020 Adam Topaz. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Adam Topaz
-/
import category_theory.monad.types
import category_theory.monad.limits
import category_theory.equivalence
import topology.category.CompHaus.basic
import topology.category.Profinite.basic
import data.set.constructions
/-!
# Compacta and Compact Hausdorff Spaces
Recall that, given a monad `M` on `Type*`, an *algebra* for `M` consists of the following data:
- A type `X : Type*`
- A "structure" map `M X → X`.
This data must also satisfy a distributivity and unit axiom, and algebras for `M` form a category
in an evident way.
See the file `category_theory.monad.algebra` for a general version, as well as the following link.
https://ncatlab.org/nlab/show/monad
This file proves the equivalence between the category of *compact Hausdorff topological spaces*
and the category of algebras for the *ultrafilter monad*.
## Notation:
Here are the main objects introduced in this file.
- `Compactum` is the type of compacta, which we define as algebras for the ultrafilter monad.
- `Compactum_to_CompHaus` is the functor `Compactum ⥤ CompHaus`. Here `CompHaus` is the usual
category of compact Hausdorff spaces.
- `Compactum_to_CompHaus.is_equivalence` is a term of type `is_equivalence Compactum_to_CompHaus`.
The proof of this equivalence is a bit technical. But the idea is quite simply that the structure
map `ultrafilter X → X` for an algebra `X` of the ultrafilter monad should be considered as the map
sending an ultrafilter to its limit in `X`. The topology on `X` is then defined by mimicking the
characterization of open sets in terms of ultrafilters.
Any `X : Compactum` is endowed with a coercion to `Type*`, as well as the following instances:
- `topological_space X`.
- `compact_space X`.
- `t2_space X`.
Any morphism `f : X ⟶ Y` of is endowed with a coercion to a function `X → Y`, which is shown to
be continuous in `continuous_of_hom`.
The function `Compactum.of_topological_space` can be used to construct a `Compactum` from a
topological space which satisfies `compact_space` and `t2_space`.
We also add wrappers around structures which already exist. Here are the main ones, all in the
`Compactum` namespace:
- `forget : Compactum ⥤ Type*` is the forgetful functor, which induces a `concrete_category`
instance for `Compactum`.
- `free : Type* ⥤ Compactum` is the left adjoint to `forget`, and the adjunction is in `adj`.
- `str : ultrafilter X → X` is the structure map for `X : Compactum`.
The notation `X.str` is preferred.
- `join : ultrafilter (ultrafilter X) → ultrafilter X` is the monadic join for `X : Compactum`.
Again, the notation `X.join` is preferred.
- `incl : X → ultrafilter X` is the unit for `X : Compactum`. The notation `X.incl` is preferred.
## References
- E. Manes, Algebraic Theories, Graduate Texts in Mathematics 26, Springer-Verlag, 1976.
- https://ncatlab.org/nlab/show/ultrafilter
-/
universe u
open category_theory filter ultrafilter topological_space category_theory.limits has_finite_inter
open_locale classical topology
local notation `β` := of_type_monad ultrafilter
/-- The type `Compactum` of Compacta, defined as algebras for the ultrafilter monad. -/
@[derive [category, inhabited]]
def Compactum := monad.algebra β
namespace Compactum
/-- The forgetful functor to Type* -/
@[derive [creates_limits,faithful]]
def forget : Compactum ⥤ Type* := monad.forget _
/-- The "free" Compactum functor. -/
def free : Type* ⥤ Compactum := monad.free _
/-- The adjunction between `free` and `forget`. -/
def adj : free ⊣ forget := monad.adj _
-- Basic instances
instance : concrete_category Compactum := { forget := forget }
instance : has_coe_to_sort Compactum Type* := ⟨forget.obj⟩
instance {X Y : Compactum} : has_coe_to_fun (X ⟶ Y) (λ f, X → Y) := ⟨λ f, f.f⟩
instance : has_limits Compactum := has_limits_of_has_limits_creates_limits forget
/-- The structure map for a compactum, essentially sending an ultrafilter to its limit. -/
def str (X : Compactum) : ultrafilter X → X := X.a
/-- The monadic join. -/
def join (X : Compactum) : ultrafilter (ultrafilter X) → ultrafilter X := β .μ.app _
/-- The inclusion of `X` into `ultrafilter X`. -/
def incl (X : Compactum) : X → ultrafilter X := β .η.app _
@[simp] lemma str_incl (X : Compactum) (x : X) : X.str (X.incl x) = x :=
begin
change (β .η.app _ ≫ X.a) _ = _,
rw monad.algebra.unit,
refl,
end
@[simp] lemma str_hom_commute (X Y : Compactum) (f : X ⟶ Y) (xs : ultrafilter X) :
f (X.str xs) = Y.str (map f xs) :=
begin
change (X.a ≫ f.f) _ = _,
rw ←f.h,
refl,
end
@[simp] lemma join_distrib (X : Compactum) (uux : ultrafilter (ultrafilter X)) :
X.str (X.join uux) = X.str (map X.str uux) :=
begin
change (β .μ.app _ ≫ X.a) _ = _,
rw monad.algebra.assoc,
refl,
end
instance {X : Compactum} : topological_space X :=
{ is_open := λ U, ∀ (F : ultrafilter X), X.str F ∈ U → U ∈ F,
is_open_univ := λ _ _, filter.univ_sets _,
is_open_inter := λ S T h3 h4 h5 h6,
filter.inter_sets _ (h3 _ h6.1) (h4 _ h6.2),
is_open_sUnion := λ S h1 F ⟨T,hT,h2⟩,
mem_of_superset (h1 T hT _ h2) (set.subset_sUnion_of_mem hT) }
theorem is_closed_iff {X : Compactum} (S : set X) : is_closed S ↔
(∀ F : ultrafilter X, S ∈ F → X.str F ∈ S) :=
begin
rw ← is_open_compl_iff,
split,
{ intros cond F h,
by_contradiction c,
specialize cond F c,
rw compl_mem_iff_not_mem at cond,
contradiction },
{ intros h1 F h2,
specialize h1 F,
cases F.mem_or_compl_mem S, exacts [absurd (h1 h) h2, h] }
end
instance {X : Compactum} : compact_space X :=
begin
constructor,
rw is_compact_iff_ultrafilter_le_nhds,
intros F h,
refine ⟨X.str F, by tauto, _⟩,
rw le_nhds_iff,
intros S h1 h2,
exact h2 F h1
end
/-- A local definition used only in the proofs. -/
private def basic {X : Compactum} (A : set X) : set (ultrafilter X) := {F | A ∈ F}
/-- A local definition used only in the proofs. -/
private def cl {X : Compactum} (A : set X) : set X := X.str '' (basic A)
private lemma basic_inter {X : Compactum} (A B : set X) : basic (A ∩ B) = basic A ∩ basic B :=
begin
ext G,
split,
{ intro hG,
split; filter_upwards [hG] with _,
exacts [and.left, and.right] },
{ rintros ⟨h1, h2⟩,
exact inter_mem h1 h2 }
end
private lemma subset_cl {X : Compactum} (A : set X) : A ⊆ cl A := λ a ha, ⟨X.incl a, ha,by simp⟩
private theorem cl_cl {X : Compactum} (A : set X) : cl (cl A) ⊆ cl A :=
begin
rintros _ ⟨F,hF,rfl⟩,
-- Notation to be used in this proof.
let fsu := finset (set (ultrafilter X)),
let ssu := set (set (ultrafilter X)),
let ι : fsu → ssu := coe,
let C0 : ssu := {Z | ∃ B ∈ F, X.str ⁻¹' B = Z},
let AA := {G : ultrafilter X | A ∈ G},
let C1 := insert AA C0,
let C2 := finite_inter_closure C1,
-- C0 is closed under intersections.
have claim1 : ∀ B C ∈ C0, B ∩ C ∈ C0,
{ rintros B ⟨Q,hQ,rfl⟩ C ⟨R,hR,rfl⟩,
use Q ∩ R,
simp only [and_true, eq_self_iff_true, set.preimage_inter, subtype.val_eq_coe],
exact inter_sets _ hQ hR },
-- All sets in C0 are nonempty.
have claim2 : ∀ B ∈ C0, set.nonempty B,
{ rintros B ⟨Q,hQ,rfl⟩,
obtain ⟨q⟩ := filter.nonempty_of_mem hQ,
use X.incl q,
simpa, },
-- The intersection of AA with every set in C0 is nonempty.
have claim3 : ∀ B ∈ C0, (AA ∩ B).nonempty,
{ rintros B ⟨Q,hQ,rfl⟩,
have : (Q ∩ cl A).nonempty :=
filter.nonempty_of_mem (inter_mem hQ hF),
rcases this with ⟨q,hq1,P,hq2,hq3⟩,
refine ⟨P,hq2,_⟩,
rw ←hq3 at hq1,
simpa },
-- Suffices to show that the intersection of any finite subcollection of C1 is nonempty.
suffices : ∀ (T : fsu), ι T ⊆ C1 → (⋂₀ ι T).nonempty,
{ obtain ⟨G, h1⟩ := exists_ultrafilter_of_finite_inter_nonempty _ this,
use X.join G,
have : G.map X.str = F :=
ultrafilter.coe_le_coe.1 (λ S hS, h1 (or.inr ⟨S, hS, rfl⟩)),
rw [join_distrib, this],
exact ⟨h1 (or.inl rfl), rfl⟩ },
-- C2 is closed under finite intersections (by construction!).
have claim4 := finite_inter_closure_has_finite_inter C1,
-- C0 is closed under finite intersections by claim1.
have claim5 : has_finite_inter C0 :=
⟨⟨_, univ_mem, set.preimage_univ⟩, claim1⟩,
-- Every element of C2 is nonempty.
have claim6 : ∀ P ∈ C2, (P : set (ultrafilter X)).nonempty,
{ suffices : ∀ P ∈ C2, P ∈ C0 ∨ ∃ Q ∈ C0, P = AA ∩ Q,
{ intros P hP,
cases this P hP,
{ exact claim2 _ h },
{ rcases h with ⟨Q, hQ, rfl⟩,
exact claim3 _ hQ } },
intros P hP,
exact claim5.finite_inter_closure_insert _ hP },
intros T hT,
-- Suffices to show that the intersection of the T's is contained in C2.
suffices : ⋂₀ ι T ∈ C2, by exact claim6 _ this,
-- Finish
apply claim4.finite_inter_mem,
intros t ht,
exact finite_inter_closure.basic (@hT t ht),
end
lemma is_closed_cl {X : Compactum} (A : set X) : is_closed (cl A) :=
begin
rw is_closed_iff,
intros F hF,
exact cl_cl _ ⟨F, hF, rfl⟩,
end
lemma str_eq_of_le_nhds {X : Compactum} (F : ultrafilter X) (x : X) :
↑F ≤ 𝓝 x → X.str F = x :=
begin
-- Notation to be used in this proof.
let fsu := finset (set (ultrafilter X)),
let ssu := set (set (ultrafilter X)),
let ι : fsu → ssu := coe,
let T0 : ssu := { S | ∃ A ∈ F, S = basic A },
let AA := (X.str ⁻¹' {x}),
let T1 := insert AA T0,
let T2 := finite_inter_closure T1,
intro cond,
-- If F contains a closed set A, then x is contained in A.
have claim1 : ∀ (A : set X), is_closed A → A ∈ F → x ∈ A,
{ intros A hA h,
by_contradiction H,
rw le_nhds_iff at cond,
specialize cond Aᶜ H hA.is_open_compl,
rw [ultrafilter.mem_coe, ultrafilter.compl_mem_iff_not_mem] at cond,
contradiction },
-- If A ∈ F, then x ∈ cl A.
have claim2 : ∀ (A : set X), A ∈ F → x ∈ cl A,
{ intros A hA,
exact claim1 (cl A) (is_closed_cl A) (mem_of_superset hA (subset_cl A)) },
-- T0 is closed under intersections.
have claim3 : ∀ (S1 S2 ∈ T0), S1 ∩ S2 ∈ T0,
{ rintros S1 ⟨S1, hS1, rfl⟩ S2 ⟨S2, hS2, rfl⟩,
exact ⟨S1 ∩ S2, inter_mem hS1 hS2, by simp [basic_inter]⟩ },
-- For every S ∈ T0, the intersection AA ∩ S is nonempty.
have claim4 : ∀ (S ∈ T0), (AA ∩ S).nonempty,
{ rintros S ⟨S, hS, rfl⟩,
rcases claim2 _ hS with ⟨G, hG, hG2⟩,
exact ⟨G, hG2, hG⟩ },
-- Every element of T0 is nonempty.
have claim5 : ∀ (S ∈ T0), set.nonempty S,
{ rintros S ⟨S, hS, rfl⟩,
exact ⟨F, hS⟩ },
-- Every element of T2 is nonempty.
have claim6 : ∀ (S ∈ T2), set.nonempty S,
{ suffices : ∀ S ∈ T2, S ∈ T0 ∨ ∃ Q ∈ T0, S = AA ∩ Q,
{ intros S hS,
cases this _ hS with h h,
{ exact claim5 S h },
{ rcases h with ⟨Q, hQ, rfl⟩,
exact claim4 Q hQ } },
intros S hS,
apply finite_inter_closure_insert,
{ split,
{ use set.univ,
refine ⟨filter.univ_sets _, _⟩,
ext,
refine ⟨_, by tauto⟩,
{ intro,
apply filter.univ_sets, } },
{ exact claim3 } },
{ exact hS} },
-- It suffices to show that the intersection of any finite subset of T1 is nonempty.
suffices : ∀ (F : fsu), ↑F ⊆ T1 → (⋂₀ ι F).nonempty,
{ obtain ⟨G,h1⟩ := ultrafilter.exists_ultrafilter_of_finite_inter_nonempty _ this,
have c1 : X.join G = F := ultrafilter.coe_le_coe.1 (λ P hP, h1 (or.inr ⟨P, hP, rfl⟩)),
have c2 : G.map X.str = X.incl x,
{ refine ultrafilter.coe_le_coe.1 (λ P hP, _),
apply mem_of_superset (h1 (or.inl rfl)),
rintros x ⟨rfl⟩,
exact hP },
simp [←c1, c2] },
-- Finish...
intros T hT,
refine claim6 _ (finite_inter_mem (finite_inter_closure_has_finite_inter _) _ _),
intros t ht,
exact finite_inter_closure.basic (@hT t ht)
end
lemma le_nhds_of_str_eq {X : Compactum} (F : ultrafilter X) (x : X) :
X.str F = x → ↑F ≤ 𝓝 x := λ h, le_nhds_iff.mpr (λ s hx hs, hs _ $ by rwa h)
-- All the hard work above boils down to this t2_space instance.
instance {X : Compactum} : t2_space X :=
begin
rw t2_iff_ultrafilter,
intros _ _ F hx hy,
rw [← str_eq_of_le_nhds _ _ hx, ← str_eq_of_le_nhds _ _ hy]
end
/-- The structure map of a compactum actually computes limits. -/
lemma Lim_eq_str {X : Compactum} (F : ultrafilter X) : F.Lim = X.str F :=
begin
rw [ultrafilter.Lim_eq_iff_le_nhds, le_nhds_iff],
tauto,
end
lemma cl_eq_closure {X : Compactum} (A : set X) : cl A = closure A :=
begin
ext,
rw mem_closure_iff_ultrafilter,
split,
{ rintro ⟨F, h1, h2⟩,
exact ⟨F, h1, le_nhds_of_str_eq _ _ h2⟩ },
{ rintro ⟨F, h1, h2⟩,
exact ⟨F, h1, str_eq_of_le_nhds _ _ h2⟩ }
end
/-- Any morphism of compacta is continuous. -/
lemma continuous_of_hom {X Y : Compactum} (f : X ⟶ Y) : continuous f :=
begin
rw continuous_iff_ultrafilter,
intros x _ h,
rw [tendsto, ← coe_map],
apply le_nhds_of_str_eq,
rw [← str_hom_commute, str_eq_of_le_nhds _ x h]
end
/-- Given any compact Hausdorff space, we construct a Compactum. -/
noncomputable def of_topological_space (X : Type*) [topological_space X]
[compact_space X] [t2_space X] : Compactum :=
{ A := X,
a := ultrafilter.Lim,
unit' := by {ext x, exact Lim_eq (pure_le_nhds _) },
assoc' := begin
ext FF,
change ultrafilter (ultrafilter X) at FF,
set x := (ultrafilter.map ultrafilter.Lim FF).Lim with c1,
have c2 : ∀ (U : set X) (F : ultrafilter X), F.Lim ∈ U → is_open U → U ∈ F,
{ intros U F h1 hU,
exact c1 ▸ is_open_iff_ultrafilter.mp hU _ h1 _ (ultrafilter.le_nhds_Lim _) },
have c3 : ↑(ultrafilter.map ultrafilter.Lim FF) ≤ 𝓝 x,
{ rw le_nhds_iff,
intros U hx hU,
exact mem_coe.2 (c2 _ _ (by rwa ← c1) hU) },
have c4 : ∀ (U : set X), x ∈ U → is_open U → { G : ultrafilter X | U ∈ G } ∈ FF,
{ intros U hx hU,
suffices : ultrafilter.Lim ⁻¹' U ∈ FF,
{ apply mem_of_superset this,
intros P hP,
exact c2 U P hP hU },
exact @c3 U (is_open.mem_nhds hU hx) },
apply Lim_eq,
rw le_nhds_iff,
exact c4,
end }
/-- Any continuous map between Compacta is a morphism of compacta. -/
def hom_of_continuous {X Y : Compactum} (f : X → Y) (cont : continuous f) : X ⟶ Y :=
{ f := f,
h' := begin
rw continuous_iff_ultrafilter at cont,
ext (F : ultrafilter X),
specialize cont (X.str F) F (le_nhds_of_str_eq F (X.str F) rfl),
have := str_eq_of_le_nhds (ultrafilter.map f F) _ cont,
simpa only [←this, types_comp_apply, of_type_functor_map],
end }
end Compactum
/-- The functor functor from Compactum to CompHaus. -/
def Compactum_to_CompHaus : Compactum ⥤ CompHaus :=
{ obj := λ X, { to_Top := { α := X } },
map := λ X Y f,
{ to_fun := f,
continuous_to_fun := Compactum.continuous_of_hom _ }}
namespace Compactum_to_CompHaus
/-- The functor Compactum_to_CompHaus is full. -/
def full : full Compactum_to_CompHaus.{u} :=
{ preimage := λ X Y f, Compactum.hom_of_continuous f.1 f.2 }
/-- The functor Compactum_to_CompHaus is faithful. -/
lemma faithful : faithful Compactum_to_CompHaus := {}
/-- This definition is used to prove essential surjectivity of Compactum_to_CompHaus. -/
def iso_of_topological_space {D : CompHaus} :
Compactum_to_CompHaus.obj (Compactum.of_topological_space D) ≅ D :=
{ hom :=
{ to_fun := id,
continuous_to_fun := continuous_def.2 $ λ _ h, by {rw is_open_iff_ultrafilter' at h, exact h} },
inv :=
{ to_fun := id,
continuous_to_fun := continuous_def.2 $
λ _ h1, by {rw is_open_iff_ultrafilter', intros _ h2, exact h1 _ h2} } }
/-- The functor Compactum_to_CompHaus is essentially surjective. -/
lemma ess_surj : ess_surj Compactum_to_CompHaus :=
{ mem_ess_image := λ X, ⟨Compactum.of_topological_space X, ⟨iso_of_topological_space⟩⟩ }
/-- The functor Compactum_to_CompHaus is an equivalence of categories. -/
noncomputable instance is_equivalence : is_equivalence Compactum_to_CompHaus :=
begin
apply equivalence.of_fully_faithfully_ess_surj _,
exact Compactum_to_CompHaus.full,
exact Compactum_to_CompHaus.faithful,
exact Compactum_to_CompHaus.ess_surj,
end
end Compactum_to_CompHaus
/-- The forgetful functors of `Compactum` and `CompHaus` are compatible via
`Compactum_to_CompHaus`. -/
def Compactum_to_CompHaus_comp_forget :
Compactum_to_CompHaus ⋙ category_theory.forget CompHaus ≅ Compactum.forget :=
nat_iso.of_components (λ X, eq_to_iso rfl) $
by { intros X Y f, dsimp, simpa }
/-
TODO: `forget CompHaus` is monadic, as it is isomorphic to the composition
of an equivalence with the monadic functor `forget Compactum`.
Once we have the API to transfer monadicity of functors along such isomorphisms,
the instance `creates_limits (forget CompHaus)` can be deduced from this
monadicity.
-/
noncomputable
instance CompHaus.forget_creates_limits : creates_limits (forget CompHaus) :=
begin
let e : forget CompHaus ≅ Compactum_to_CompHaus.inv ⋙ Compactum.forget :=
_ ≪≫ iso_whisker_left _ Compactum_to_CompHaus_comp_forget,
swap,
refine _ ≪≫ functor.associator _ _ _,
refine (functor.left_unitor _).symm ≪≫ _,
refine iso_whisker_right _ _,
exact Compactum_to_CompHaus.as_equivalence.symm.unit_iso,
exact creates_limits_of_nat_iso e.symm,
end
noncomputable
instance Profinite.forget_creates_limits : creates_limits (forget Profinite) :=
begin
change creates_limits (Profinite_to_CompHaus ⋙ forget _),
apply_instance,
end
|
f4ffaf1afee9a704b5fa3ba4d99dbf3c71945b6b | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/data/rbtree/find.lean | 3d1ea6186417f8c36db94db034f51e46e15f49ef | [
"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,812 | lean | /-
Copyright (c) 2017 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
import data.rbtree.basic
universe u
namespace rbnode
variables {α : Type u}
@[elab_simple]
lemma find.induction {p : rbnode α → Prop} (lt) [decidable_rel lt]
(t x)
(h₁ : p leaf)
(h₂ : ∀ l y r (h : cmp_using lt x y = ordering.lt) (ih : p l), p (red_node l y r))
(h₃ : ∀ l y r (h : cmp_using lt x y = ordering.eq), p (red_node l y r))
(h₄ : ∀ l y r (h : cmp_using lt x y = ordering.gt) (ih : p r), p (red_node l y r))
(h₅ : ∀ l y r (h : cmp_using lt x y = ordering.lt) (ih : p l), p (black_node l y r))
(h₆ : ∀ l y r (h : cmp_using lt x y = ordering.eq), p (black_node l y r))
(h₇ : ∀ l y r (h : cmp_using lt x y = ordering.gt) (ih : p r), p (black_node l y r))
: p t :=
begin
induction t,
case leaf { assumption },
case red_node : l y r
{ cases h : cmp_using lt x y,
case ordering.lt { apply h₂, assumption, assumption },
case ordering.eq { apply h₃, assumption },
case ordering.gt { apply h₄, assumption, assumption }, },
case black_node : l y r
{ cases h : cmp_using lt x y,
case ordering.lt { apply h₅, assumption, assumption },
case ordering.eq { apply h₆, assumption },
case ordering.gt { apply h₇, assumption, assumption }, }
end
lemma find_correct {t : rbnode α} {lt x} [decidable_rel lt] [is_strict_weak_order α lt] :
∀ {lo hi} (hs : is_searchable lt t lo hi), mem lt x t ↔ ∃ y, find lt t x = some y ∧ x ≈[lt] y :=
begin
apply find.induction lt t x; intros; simp only [mem, find, *],
{ simp },
iterate 2 { -- red and black cases are identical
{ cases hs,
apply iff.intro,
{ intro hm, blast_disjs,
{ exact iff.mp (ih hs_hs₁) hm },
{ simp at h, cases hm, contradiction },
{ have hyx : lift lt (some y) (some x) := (range hs_hs₂ hm).1,
simp [lift] at hyx,
have hxy : lt x y, { simp [cmp_using] at h, assumption },
exact absurd (trans_of lt hxy hyx) (irrefl_of lt x) } },
{ intro hc, left, exact iff.mpr (ih hs_hs₁) hc }, },
{ simp at h, simp [h, strict_weak_order.equiv] },
{ cases hs,
apply iff.intro,
{ intro hm, blast_disjs,
{ have hxy : lift lt (some x) (some y) := (range hs_hs₁ hm).2,
simp [lift] at hxy,
have hyx : lt y x, { simp [cmp_using] at h, exact h.2 },
exact absurd (trans_of lt hxy hyx) (irrefl_of lt x) },
{ simp at h, cases hm, contradiction },
{ exact iff.mp (ih hs_hs₂) hm } },
{ intro hc, right, right, exact iff.mpr (ih hs_hs₂) hc }, } }
end
lemma mem_of_mem_exact {lt} [is_irrefl α lt] {x t} : mem_exact x t → mem lt x t :=
begin
induction t; simp [mem_exact, mem, false_implies_iff]; intro h,
all_goals { blast_disjs, simp [t_ih_lchild h], simp [h, irrefl_of lt t_val],
simp [t_ih_rchild h] }
end
lemma find_correct_exact {t : rbnode α} {lt x} [decidable_rel lt] [is_strict_weak_order α lt] :
∀ {lo hi} (hs : is_searchable lt t lo hi), mem_exact x t ↔ find lt t x = some x :=
begin
apply find.induction lt t x; intros; simp only [mem_exact, find, *],
iterate 2
{ { cases hs,
apply iff.intro,
{ intro hm, blast_disjs,
{ exact iff.mp (ih hs_hs₁) hm },
{ simp at h, subst x, exact absurd h (irrefl y) },
{ have hyx : lift lt (some y) (some x) := (range hs_hs₂ (mem_of_mem_exact hm)).1,
simp [lift] at hyx,
have hxy : lt x y, { simp [cmp_using] at h, assumption },
exact absurd (trans_of lt hxy hyx) (irrefl_of lt x) } },
{ intro hc, left, exact iff.mpr (ih hs_hs₁) hc }, },
{ simp at h,
cases hs,
apply iff.intro,
{ intro hm, blast_disjs,
{ have hxy : lift lt (some x) (some y) := (range hs_hs₁ (mem_of_mem_exact hm)).2,
simp [lift] at hxy,
exact absurd hxy h.1 },
{ subst hm },
{ have hyx : lift lt (some y) (some x) := (range hs_hs₂ (mem_of_mem_exact hm)).1,
simp [lift] at hyx,
exact absurd hyx h.2 } },
{ intro hm, simp [*] } },
{ cases hs,
apply iff.intro,
{ intro hm, blast_disjs,
{ have hxy : lift lt (some x) (some y) := (range hs_hs₁ (mem_of_mem_exact hm)).2,
simp [lift] at hxy,
have hyx : lt y x, { simp [cmp_using] at h, exact h.2 },
exact absurd (trans_of lt hxy hyx) (irrefl_of lt x) },
{ simp at h, subst x, exact absurd h (irrefl y) },
{ exact iff.mp (ih hs_hs₂) hm } },
{ intro hc, right, right, exact iff.mpr (ih hs_hs₂) hc } } }
end
lemma eqv_of_find_some {t : rbnode α} {lt x y} [decidable_rel lt] :
∀ {lo hi} (hs : is_searchable lt t lo hi) (he : find lt t x = some y), x ≈[lt] y :=
begin
apply find.induction lt t x; intros; simp only [mem, find, *] at *,
iterate 2
{ { cases hs, exact ih hs_hs₁ rfl },
{ subst y, simp at h, exact h },
{ cases hs, exact ih hs_hs₂ rfl } }
end
lemma find_eq_find_of_eqv {lt a b} [decidable_rel lt] [is_strict_weak_order α lt] {t : rbnode α} :
∀ {lo hi} (hs : is_searchable lt t lo hi) (heqv : a ≈[lt] b), find lt t a = find lt t b :=
begin
apply find.induction lt t a; intros;
simp [mem, find, strict_weak_order.equiv, *, true_implies_iff] at *,
iterate 2
{ { have : lt b y := lt_of_incomp_of_lt heqv.swap h,
simp [cmp_using, find, *], cases hs, apply ih hs_hs₁ },
{ have := incomp_trans_of lt heqv.swap h, simp [cmp_using, find, *] },
{ have := lt_of_lt_of_incomp h heqv,
have := not_lt_of_lt this,
simp [cmp_using, find, *], cases hs, apply ih hs_hs₂ } }
end
end rbnode
|
4250a94e705b4842ba556d32cc346635f8e16a5f | 0d4c30038160d9c35586ce4dace36fe26a35023b | /src/topology/metric_space/basic.lean | 5c8d9554f1044d48c19e80430209942230175cfe | [
"Apache-2.0"
] | permissive | b-mehta/mathlib | b0c8ec929ec638447e4262f7071570d23db52e14 | ce72cde867feabe5bb908cf9e895acc0e11bf1eb | refs/heads/master | 1,599,457,264,781 | 1,586,969,260,000 | 1,586,969,260,000 | 220,672,634 | 0 | 0 | Apache-2.0 | 1,583,944,480,000 | 1,573,317,991,000 | Lean | UTF-8 | Lean | false | false | 70,257 | lean | /-
Copyright (c) 2015, 2017 Jeremy Avigad. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Metric spaces.
Authors: Jeremy Avigad, Robert Y. Lewis, Johannes Hölzl, Mario Carneiro, Sébastien Gouëzel
Many definitions and theorems expected on metric spaces are already introduced on uniform spaces and
topological spaces. For example:
open and closed sets, compactness, completeness, continuity and uniform continuity
-/
import data.real.nnreal topology.metric_space.emetric_space topology.algebra.ordered
open set filter classical topological_space
noncomputable theory
open_locale uniformity topological_space
universes u v w
variables {α : Type u} {β : Type v} {γ : Type w}
/-- Construct a uniform structure from a distance function and metric space axioms -/
def uniform_space_of_dist
(dist : α → α → ℝ)
(dist_self : ∀ x : α, dist x x = 0)
(dist_comm : ∀ x y : α, dist x y = dist y x)
(dist_triangle : ∀ x y z : α, dist x z ≤ dist x y + dist y z) : uniform_space α :=
uniform_space.of_core {
uniformity := (⨅ ε>0, principal {p:α×α | dist p.1 p.2 < ε}),
refl := le_infi $ assume ε, le_infi $
by simp [set.subset_def, id_rel, dist_self, (>)] {contextual := tt},
comp := le_infi $ assume ε, le_infi $ assume h, lift'_le
(mem_infi_sets (ε / 2) $ mem_infi_sets (div_pos_of_pos_of_pos h two_pos) (subset.refl _)) $
have ∀ (a b c : α), dist a c < ε / 2 → dist c b < ε / 2 → dist a b < ε,
from assume a b c hac hcb,
calc dist a b ≤ dist a c + dist c b : dist_triangle _ _ _
... < ε / 2 + ε / 2 : add_lt_add hac hcb
... = ε : by rw [div_add_div_same, add_self_div_two],
by simpa [comp_rel],
symm := tendsto_infi.2 $ assume ε, tendsto_infi.2 $ assume h,
tendsto_infi' ε $ tendsto_infi' h $ tendsto_principal_principal.2 $ by simp [dist_comm] }
/-- The distance function (given an ambient metric space on `α`), which returns
a nonnegative real number `dist x y` given `x y : α`. -/
class has_dist (α : Type*) := (dist : α → α → ℝ)
export has_dist (dist)
section prio
set_option default_priority 100 -- see Note [default priority]
/-- Metric space
Each metric space induces a canonical `uniform_space` and hence a canonical `topological_space`.
This is enforced in the type class definition, by extending the `uniform_space` structure. When
instantiating a `metric_space` structure, the uniformity fields are not necessary, they will be
filled in by default. In the same way, each metric space induces an emetric space structure.
It is included in the structure, but filled in by default.
When one instantiates a metric space structure, for instance a product structure,
this makes it possible to use a uniform structure and an edistance that are exactly
the ones for the uniform spaces product and the emetric spaces products, thereby
ensuring that everything in defeq in diamonds.-/
class metric_space (α : Type u) extends has_dist α : Type u :=
(dist_self : ∀ x : α, dist x x = 0)
(eq_of_dist_eq_zero : ∀ {x y : α}, dist x y = 0 → x = y)
(dist_comm : ∀ x y : α, dist x y = dist y x)
(dist_triangle : ∀ x y z : α, dist x z ≤ dist x y + dist y z)
(edist : α → α → ennreal := λx y, ennreal.of_real (dist x y))
(edist_dist : ∀ x y : α, edist x y = ennreal.of_real (dist x y) . control_laws_tac)
(to_uniform_space : uniform_space α := uniform_space_of_dist dist dist_self dist_comm dist_triangle)
(uniformity_dist : 𝓤 α = ⨅ ε>0, principal {p:α×α | dist p.1 p.2 < ε} . control_laws_tac)
end prio
variables [metric_space α]
@[priority 100] -- see Note [lower instance priority]
instance metric_space.to_uniform_space' : uniform_space α :=
metric_space.to_uniform_space
@[priority 200] -- see Note [lower instance priority]
instance metric_space.to_has_edist : has_edist α := ⟨metric_space.edist⟩
@[simp] theorem dist_self (x : α) : dist x x = 0 := metric_space.dist_self x
theorem eq_of_dist_eq_zero {x y : α} : dist x y = 0 → x = y :=
metric_space.eq_of_dist_eq_zero
theorem dist_comm (x y : α) : dist x y = dist y x := metric_space.dist_comm x y
theorem edist_dist (x y : α) : edist x y = ennreal.of_real (dist x y) :=
metric_space.edist_dist x y
@[simp] theorem dist_eq_zero {x y : α} : dist x y = 0 ↔ x = y :=
iff.intro eq_of_dist_eq_zero (assume : x = y, this ▸ dist_self _)
@[simp] theorem zero_eq_dist {x y : α} : 0 = dist x y ↔ x = y :=
by rw [eq_comm, dist_eq_zero]
theorem dist_triangle (x y z : α) : dist x z ≤ dist x y + dist y z :=
metric_space.dist_triangle x y z
theorem dist_triangle_left (x y z : α) : dist x y ≤ dist z x + dist z y :=
by rw dist_comm z; apply dist_triangle
theorem dist_triangle_right (x y z : α) : dist x y ≤ dist x z + dist y z :=
by rw dist_comm y; apply dist_triangle
lemma dist_triangle4 (x y z w : α) :
dist x w ≤ dist x y + dist y z + dist z w :=
calc
dist x w ≤ dist x z + dist z w : dist_triangle x z w
... ≤ (dist x y + dist y z) + dist z w : add_le_add_right (metric_space.dist_triangle x y z) _
lemma dist_triangle4_left (x₁ y₁ x₂ y₂ : α) :
dist x₂ y₂ ≤ dist x₁ y₁ + (dist x₁ x₂ + dist y₁ y₂) :=
by rw [add_left_comm, dist_comm x₁, ← add_assoc]; apply dist_triangle4
lemma dist_triangle4_right (x₁ y₁ x₂ y₂ : α) :
dist x₁ y₁ ≤ dist x₁ x₂ + dist y₁ y₂ + dist x₂ y₂ :=
by rw [add_right_comm, dist_comm y₁]; apply dist_triangle4
/-- The triangle (polygon) inequality for sequences of points; `finset.Ico` version. -/
lemma dist_le_Ico_sum_dist (f : ℕ → α) {m n} (h : m ≤ n) :
dist (f m) (f n) ≤ (finset.Ico m n).sum (λ i, dist (f i) (f (i + 1))) :=
begin
revert n,
apply nat.le_induction,
{ simp only [finset.sum_empty, finset.Ico.self_eq_empty, dist_self] },
{ assume n hn hrec,
calc dist (f m) (f (n+1)) ≤ dist (f m) (f n) + dist _ _ : dist_triangle _ _ _
... ≤ (finset.Ico m n).sum _ + _ : add_le_add hrec (le_refl _)
... = (finset.Ico m (n+1)).sum _ :
by rw [finset.Ico.succ_top hn, finset.sum_insert, add_comm]; simp }
end
/-- The triangle (polygon) inequality for sequences of points; `finset.range` version. -/
lemma dist_le_range_sum_dist (f : ℕ → α) (n : ℕ) :
dist (f 0) (f n) ≤ (finset.range n).sum (λ i, dist (f i) (f (i + 1))) :=
finset.Ico.zero_bot n ▸ dist_le_Ico_sum_dist f (nat.zero_le n)
/-- A version of `dist_le_Ico_sum_dist` with each intermediate distance replaced
with an upper estimate. -/
lemma dist_le_Ico_sum_of_dist_le {f : ℕ → α} {m n} (hmn : m ≤ n)
{d : ℕ → ℝ} (hd : ∀ {k}, m ≤ k → k < n → dist (f k) (f (k + 1)) ≤ d k) :
dist (f m) (f n) ≤ (finset.Ico m n).sum d :=
le_trans (dist_le_Ico_sum_dist f hmn) $
finset.sum_le_sum $ λ k hk, hd (finset.Ico.mem.1 hk).1 (finset.Ico.mem.1 hk).2
/-- A version of `dist_le_range_sum_dist` with each intermediate distance replaced
with an upper estimate. -/
lemma dist_le_range_sum_of_dist_le {f : ℕ → α} (n : ℕ)
{d : ℕ → ℝ} (hd : ∀ {k}, k < n → dist (f k) (f (k + 1)) ≤ d k) :
dist (f 0) (f n) ≤ (finset.range n).sum d :=
finset.Ico.zero_bot n ▸ dist_le_Ico_sum_of_dist_le (zero_le n) (λ _ _, hd)
theorem swap_dist : function.swap (@dist α _) = dist :=
by funext x y; exact dist_comm _ _
theorem abs_dist_sub_le (x y z : α) : abs (dist x z - dist y z) ≤ dist x y :=
abs_sub_le_iff.2
⟨sub_le_iff_le_add.2 (dist_triangle _ _ _),
sub_le_iff_le_add.2 (dist_triangle_left _ _ _)⟩
theorem dist_nonneg {x y : α} : 0 ≤ dist x y :=
have 2 * dist x y ≥ 0,
from calc 2 * dist x y = dist x y + dist y x : by rw [dist_comm x y, two_mul]
... ≥ 0 : by rw ← dist_self x; apply dist_triangle,
nonneg_of_mul_nonneg_left this two_pos
@[simp] theorem dist_le_zero {x y : α} : dist x y ≤ 0 ↔ x = y :=
by simpa [le_antisymm_iff, dist_nonneg] using @dist_eq_zero _ _ x y
@[simp] theorem dist_pos {x y : α} : 0 < dist x y ↔ x ≠ y :=
by simpa [-dist_le_zero] using not_congr (@dist_le_zero _ _ x y)
@[simp] theorem abs_dist {a b : α} : abs (dist a b) = dist a b :=
abs_of_nonneg dist_nonneg
theorem eq_of_forall_dist_le {x y : α} (h : ∀ε, ε > 0 → dist x y ≤ ε) : x = y :=
eq_of_dist_eq_zero (eq_of_le_of_forall_le_of_dense dist_nonneg h)
/-- Distance as a nonnegative real number. -/
def nndist (a b : α) : nnreal := ⟨dist a b, dist_nonneg⟩
/--Express `nndist` in terms of `edist`-/
lemma nndist_edist (x y : α) : nndist x y = (edist x y).to_nnreal :=
by simp [nndist, edist_dist, nnreal.of_real, max_eq_left dist_nonneg, ennreal.of_real]
/--Express `edist` in terms of `nndist`-/
lemma edist_nndist (x y : α) : edist x y = ↑(nndist x y) :=
by { rw [edist_dist, nndist, ennreal.of_real_eq_coe_nnreal] }
/--In a metric space, the extended distance is always finite-/
lemma edist_ne_top (x y : α) : edist x y ≠ ⊤ :=
by rw [edist_dist x y]; apply ennreal.coe_ne_top
/--In a metric space, the extended distance is always finite-/
lemma edist_lt_top {α : Type*} [metric_space α] (x y : α) : edist x y < ⊤ :=
ennreal.lt_top_iff_ne_top.2 (edist_ne_top x y)
/--`nndist x x` vanishes-/
@[simp] lemma nndist_self (a : α) : nndist a a = 0 := (nnreal.coe_eq_zero _).1 (dist_self a)
/--Express `dist` in terms of `nndist`-/
lemma dist_nndist (x y : α) : dist x y = ↑(nndist x y) := rfl
/--Express `nndist` in terms of `dist`-/
lemma nndist_dist (x y : α) : nndist x y = nnreal.of_real (dist x y) :=
by rw [dist_nndist, nnreal.of_real_coe]
/--Deduce the equality of points with the vanishing of the nonnegative distance-/
theorem eq_of_nndist_eq_zero {x y : α} : nndist x y = 0 → x = y :=
by simp only [nnreal.eq_iff.symm, (dist_nndist _ _).symm, imp_self, nnreal.coe_zero, dist_eq_zero]
theorem nndist_comm (x y : α) : nndist x y = nndist y x :=
by simpa [nnreal.eq_iff.symm] using dist_comm x y
/--Characterize the equality of points with the vanishing of the nonnegative distance-/
@[simp] theorem nndist_eq_zero {x y : α} : nndist x y = 0 ↔ x = y :=
by simp only [nnreal.eq_iff.symm, (dist_nndist _ _).symm, imp_self, nnreal.coe_zero, dist_eq_zero]
@[simp] theorem zero_eq_nndist {x y : α} : 0 = nndist x y ↔ x = y :=
by simp only [nnreal.eq_iff.symm, (dist_nndist _ _).symm, imp_self, nnreal.coe_zero, zero_eq_dist]
/--Triangle inequality for the nonnegative distance-/
theorem nndist_triangle (x y z : α) : nndist x z ≤ nndist x y + nndist y z :=
by simpa [nnreal.coe_le_coe] using dist_triangle x y z
theorem nndist_triangle_left (x y z : α) : nndist x y ≤ nndist z x + nndist z y :=
by simpa [nnreal.coe_le_coe] using dist_triangle_left x y z
theorem nndist_triangle_right (x y z : α) : nndist x y ≤ nndist x z + nndist y z :=
by simpa [nnreal.coe_le_coe] using dist_triangle_right x y z
/--Express `dist` in terms of `edist`-/
lemma dist_edist (x y : α) : dist x y = (edist x y).to_real :=
by rw [edist_dist, ennreal.to_real_of_real (dist_nonneg)]
namespace metric
/- instantiate metric space as a topology -/
variables {x y z : α} {ε ε₁ ε₂ : ℝ} {s : set α}
/-- `ball x ε` is the set of all points `y` with `dist y x < ε` -/
def ball (x : α) (ε : ℝ) : set α := {y | dist y x < ε}
@[simp] theorem mem_ball : y ∈ ball x ε ↔ dist y x < ε := iff.rfl
theorem mem_ball' : y ∈ ball x ε ↔ dist x y < ε := by rw dist_comm; refl
/-- `closed_ball x ε` is the set of all points `y` with `dist y x ≤ ε` -/
def closed_ball (x : α) (ε : ℝ) := {y | dist y x ≤ ε}
@[simp] theorem mem_closed_ball : y ∈ closed_ball x ε ↔ dist y x ≤ ε := iff.rfl
theorem ball_subset_closed_ball : ball x ε ⊆ closed_ball x ε :=
assume y (hy : _ < _), le_of_lt hy
theorem pos_of_mem_ball (hy : y ∈ ball x ε) : ε > 0 :=
lt_of_le_of_lt dist_nonneg hy
theorem mem_ball_self (h : ε > 0) : x ∈ ball x ε :=
show dist x x < ε, by rw dist_self; assumption
theorem mem_closed_ball_self (h : ε ≥ 0) : x ∈ closed_ball x ε :=
show dist x x ≤ ε, by rw dist_self; assumption
theorem mem_ball_comm : x ∈ ball y ε ↔ y ∈ ball x ε :=
by simp [dist_comm]
theorem ball_subset_ball (h : ε₁ ≤ ε₂) : ball x ε₁ ⊆ ball x ε₂ :=
λ y (yx : _ < ε₁), lt_of_lt_of_le yx h
theorem closed_ball_subset_closed_ball {α : Type u} [metric_space α] {ε₁ ε₂ : ℝ} {x : α} (h : ε₁ ≤ ε₂) :
closed_ball x ε₁ ⊆ closed_ball x ε₂ :=
λ y (yx : _ ≤ ε₁), le_trans yx h
theorem ball_disjoint (h : ε₁ + ε₂ ≤ dist x y) : ball x ε₁ ∩ ball y ε₂ = ∅ :=
eq_empty_iff_forall_not_mem.2 $ λ z ⟨h₁, h₂⟩,
not_lt_of_le (dist_triangle_left x y z)
(lt_of_lt_of_le (add_lt_add h₁ h₂) h)
theorem ball_disjoint_same (h : ε ≤ dist x y / 2) : ball x ε ∩ ball y ε = ∅ :=
ball_disjoint $ by rwa [← two_mul, ← le_div_iff' (@two_pos ℝ _)]
theorem ball_subset (h : dist x y ≤ ε₂ - ε₁) : ball x ε₁ ⊆ ball y ε₂ :=
λ z zx, by rw ← add_sub_cancel'_right ε₁ ε₂; exact
lt_of_le_of_lt (dist_triangle z x y) (add_lt_add_of_lt_of_le zx h)
theorem ball_half_subset (y) (h : y ∈ ball x (ε / 2)) : ball y (ε / 2) ⊆ ball x ε :=
ball_subset $ by rw sub_self_div_two; exact le_of_lt h
theorem exists_ball_subset_ball (h : y ∈ ball x ε) : ∃ ε' > 0, ball y ε' ⊆ ball x ε :=
⟨_, sub_pos.2 h, ball_subset $ by rw sub_sub_self⟩
theorem ball_eq_empty_iff_nonpos : ε ≤ 0 ↔ ball x ε = ∅ :=
(eq_empty_iff_forall_not_mem.trans
⟨λ h, le_of_not_gt $ λ ε0, h _ $ mem_ball_self ε0,
λ ε0 y h, not_lt_of_le ε0 $ pos_of_mem_ball h⟩).symm
@[simp] lemma ball_zero : ball x 0 = ∅ :=
by rw [← metric.ball_eq_empty_iff_nonpos]
theorem uniformity_basis_dist :
(𝓤 α).has_basis (λ ε : ℝ, 0 < ε) (λ ε, {p:α×α | dist p.1 p.2 < ε}) :=
begin
rw ← metric_space.uniformity_dist.symm,
refine has_basis_binfi_principal _ nonempty_Ioi,
exact λ r (hr : 0 < r) p (hp : 0 < p), ⟨min r p, lt_min hr hp,
λ x (hx : dist _ _ < _), lt_of_lt_of_le hx (min_le_left r p),
λ x (hx : dist _ _ < _), lt_of_lt_of_le hx (min_le_right r p)⟩
end
/-- Given `f : β → ℝ`, if `f` sends `{i | p i}` to a set of positive numbers
accumulating to zero, then `f i`-neighborhoods of the diagonal form a basis of `𝓤 α`.
For specific bases see `uniformity_basis_dist`, `uniformity_basis_dist_inv_nat_succ`,
and `uniformity_basis_dist_inv_nat_pos`. -/
protected theorem mk_uniformity_basis {β : Type*} {p : β → Prop} {f : β → ℝ}
(hf₀ : ∀ i, p i → 0 < f i) (hf : ∀ ⦃ε⦄, 0 < ε → ∃ i (hi : p i), f i ≤ ε) :
(𝓤 α).has_basis p (λ i, {p:α×α | dist p.1 p.2 < f i}) :=
begin
refine ⟨λ s, uniformity_basis_dist.mem_iff.trans _⟩,
split,
{ rintros ⟨ε, ε₀, hε⟩,
obtain ⟨i, hi, H⟩ : ∃ i (hi : p i), f i ≤ ε, from hf ε₀,
exact ⟨i, hi, λ x (hx : _ < _), hε $ lt_of_lt_of_le hx H⟩ },
{ exact λ ⟨i, hi, H⟩, ⟨f i, hf₀ i hi, H⟩ }
end
theorem uniformity_basis_dist_inv_nat_succ :
(𝓤 α).has_basis (λ _, true) (λ n:ℕ, {p:α×α | dist p.1 p.2 < 1 / (↑n+1) }) :=
metric.mk_uniformity_basis (λ n _, div_pos zero_lt_one $ nat.cast_add_one_pos n)
(λ ε ε0, (exists_nat_one_div_lt ε0).imp $ λ n hn, ⟨trivial, le_of_lt hn⟩)
theorem uniformity_basis_dist_inv_nat_pos :
(𝓤 α).has_basis (λ n:ℕ, 0<n) (λ n:ℕ, {p:α×α | dist p.1 p.2 < 1 / ↑n }) :=
metric.mk_uniformity_basis (λ n hn, div_pos zero_lt_one $ nat.cast_pos.2 hn)
(λ ε ε0, let ⟨n, hn⟩ := exists_nat_one_div_lt ε0 in ⟨n+1, nat.succ_pos n, le_of_lt hn⟩)
/-- Given `f : β → ℝ`, if `f` sends `{i | p i}` to a set of positive numbers
accumulating to zero, then closed neighborhoods of the diagonal of sizes `{f i | p i}`
form a basis of `𝓤 α`.
Currently we have only one specific basis `uniformity_basis_dist_le` based on this constructor.
More can be easily added if needed in the future. -/
protected theorem mk_uniformity_basis_le {β : Type*} {p : β → Prop} {f : β → ℝ}
(hf₀ : ∀ x, p x → 0 < f x) (hf : ∀ ε, 0 < ε → ∃ x (hx : p x), f x ≤ ε) :
(𝓤 α).has_basis p (λ x, {p:α×α | dist p.1 p.2 ≤ f x}) :=
begin
refine ⟨λ s, uniformity_basis_dist.mem_iff.trans _⟩,
split,
{ rintros ⟨ε, ε₀, hε⟩,
rcases dense ε₀ with ⟨ε', hε'⟩,
rcases hf ε' hε'.1 with ⟨i, hi, H⟩,
exact ⟨i, hi, λ x (hx : _ ≤ _), hε $ lt_of_le_of_lt (le_trans hx H) hε'.2⟩ },
{ exact λ ⟨i, hi, H⟩, ⟨f i, hf₀ i hi, λ x (hx : _ < _), H (le_of_lt hx)⟩ }
end
/-- Contant size closed neighborhoods of the diagonal form a basis
of the uniformity filter. -/
theorem uniformity_basis_dist_le :
(𝓤 α).has_basis (λ ε : ℝ, 0 < ε) (λ ε, {p:α×α | dist p.1 p.2 ≤ ε}) :=
metric.mk_uniformity_basis_le (λ _, id) (λ ε ε₀, ⟨ε, ε₀, le_refl ε⟩)
theorem mem_uniformity_dist {s : set (α×α)} :
s ∈ 𝓤 α ↔ (∃ε>0, ∀{a b:α}, dist a b < ε → (a, b) ∈ s) :=
uniformity_basis_dist.mem_uniformity_iff
/-- A constant size neighborhood of the diagonal is an entourage. -/
theorem dist_mem_uniformity {ε:ℝ} (ε0 : 0 < ε) :
{p:α×α | dist p.1 p.2 < ε} ∈ 𝓤 α :=
mem_uniformity_dist.2 ⟨ε, ε0, λ a b, id⟩
theorem uniform_continuous_iff [metric_space β] {f : α → β} :
uniform_continuous f ↔ ∀ ε > 0, ∃ δ > 0,
∀{a b:α}, dist a b < δ → dist (f a) (f b) < ε :=
uniformity_basis_dist.uniform_continuous_iff uniformity_basis_dist
theorem uniform_embedding_iff [metric_space β] {f : α → β} :
uniform_embedding f ↔ function.injective f ∧ uniform_continuous f ∧
∀ δ > 0, ∃ ε > 0, ∀ {a b : α}, dist (f a) (f b) < ε → dist a b < δ :=
uniform_embedding_def'.trans $ and_congr iff.rfl $ and_congr iff.rfl
⟨λ H δ δ0, let ⟨t, tu, ht⟩ := H _ (dist_mem_uniformity δ0),
⟨ε, ε0, hε⟩ := mem_uniformity_dist.1 tu in
⟨ε, ε0, λ a b h, ht _ _ (hε h)⟩,
λ H s su, let ⟨δ, δ0, hδ⟩ := mem_uniformity_dist.1 su, ⟨ε, ε0, hε⟩ := H _ δ0 in
⟨_, dist_mem_uniformity ε0, λ a b h, hδ (hε h)⟩⟩
/-- A map between metric spaces is a uniform embedding if and only if the distance between `f x`
and `f y` is controlled in terms of the distance between `x` and `y` and conversely. -/
theorem uniform_embedding_iff' [metric_space β] {f : α → β} :
uniform_embedding f ↔
(∀ ε > 0, ∃ δ > 0, ∀ {a b : α}, dist a b < δ → dist (f a) (f b) < ε) ∧
(∀ δ > 0, ∃ ε > 0, ∀ {a b : α}, dist (f a) (f b) < ε → dist a b < δ) :=
begin
split,
{ assume h,
exact ⟨uniform_continuous_iff.1 (uniform_embedding_iff.1 h).2.1,
(uniform_embedding_iff.1 h).2.2⟩ },
{ rintros ⟨h₁, h₂⟩,
refine uniform_embedding_iff.2 ⟨_, uniform_continuous_iff.2 h₁, h₂⟩,
assume x y hxy,
have : dist x y ≤ 0,
{ refine le_of_forall_lt' (λδ δpos, _),
rcases h₂ δ δpos with ⟨ε, εpos, hε⟩,
have : dist (f x) (f y) < ε, by simpa [hxy],
exact hε this },
simpa using this }
end
theorem totally_bounded_iff {s : set α} :
totally_bounded s ↔ ∀ ε > 0, ∃t : set α, finite t ∧ s ⊆ ⋃y∈t, ball y ε :=
⟨λ H ε ε0, H _ (dist_mem_uniformity ε0),
λ H r ru, let ⟨ε, ε0, hε⟩ := mem_uniformity_dist.1 ru,
⟨t, ft, h⟩ := H ε ε0 in
⟨t, ft, subset.trans h $ Union_subset_Union $ λ y, Union_subset_Union $ λ yt z, hε⟩⟩
/-- A metric space space is totally bounded if one can reconstruct up to any ε>0 any element of the
space from finitely many data. -/
lemma totally_bounded_of_finite_discretization {α : Type u} [metric_space α] {s : set α}
(H : ∀ε > (0 : ℝ), ∃ (β : Type u) [fintype β] (F : s → β),
∀x y, F x = F y → dist (x:α) y < ε) :
totally_bounded s :=
begin
cases s.eq_empty_or_nonempty with hs hs,
{ rw hs, exact totally_bounded_empty },
rcases hs with ⟨x0, hx0⟩,
haveI : inhabited s := ⟨⟨x0, hx0⟩⟩,
refine totally_bounded_iff.2 (λ ε ε0, _),
rcases H ε ε0 with ⟨β, fβ, F, hF⟩,
let Finv := function.inv_fun F,
refine ⟨range (subtype.val ∘ Finv), finite_range _, λ x xs, _⟩,
let x' := Finv (F ⟨x, xs⟩),
have : F x' = F ⟨x, xs⟩ := function.inv_fun_eq ⟨⟨x, xs⟩, rfl⟩,
simp only [set.mem_Union, set.mem_range],
exact ⟨_, ⟨F ⟨x, xs⟩, rfl⟩, hF _ _ this.symm⟩
end
/-- Expressing locally uniform convergence on a set using `dist`. -/
@[nolint ge_or_gt] -- see Note [nolint_ge]
lemma tendsto_locally_uniformly_on_iff {ι : Type*} [topological_space β]
{F : ι → β → α} {f : β → α} {p : filter ι} {s : set β} :
tendsto_locally_uniformly_on F f p s ↔
∀ ε > 0, ∀ x ∈ s, ∃ t ∈ nhds_within x s, ∀ᶠ n in p, ∀ y ∈ t, dist (f y) (F n y) < ε :=
begin
refine ⟨λ H ε hε, H _ (dist_mem_uniformity hε), λ H u hu x hx, _⟩,
rcases mem_uniformity_dist.1 hu with ⟨ε, εpos, hε⟩,
rcases H ε εpos x hx with ⟨t, ht, Ht⟩,
exact ⟨t, ht, Ht.mono (λ n hs x hx, hε (hs x hx))⟩
end
/-- Expressing uniform convergence on a set using `dist`. -/
@[nolint ge_or_gt] -- see Note [nolint_ge]
lemma tendsto_uniformly_on_iff {ι : Type*}
{F : ι → β → α} {f : β → α} {p : filter ι} {s : set β} :
tendsto_uniformly_on F f p s ↔ ∀ ε > 0, ∀ᶠ n in p, ∀ x ∈ s, dist (f x) (F n x) < ε :=
begin
refine ⟨λ H ε hε, H _ (dist_mem_uniformity hε), λ H u hu, _⟩,
rcases mem_uniformity_dist.1 hu with ⟨ε, εpos, hε⟩,
exact (H ε εpos).mono (λ n hs x hx, hε (hs x hx))
end
/-- Expressing locally uniform convergence using `dist`. -/
@[nolint ge_or_gt] -- see Note [nolint_ge]
lemma tendsto_locally_uniformly_iff {ι : Type*} [topological_space β]
{F : ι → β → α} {f : β → α} {p : filter ι} :
tendsto_locally_uniformly F f p ↔
∀ ε > 0, ∀ (x : β), ∃ t ∈ 𝓝 x, ∀ᶠ n in p, ∀ y ∈ t, dist (f y) (F n y) < ε :=
by simp [← nhds_within_univ, ← tendsto_locally_uniformly_on_univ, tendsto_locally_uniformly_on_iff]
/-- Expressing uniform convergence using `dist`. -/
@[nolint ge_or_gt] -- see Note [nolint_ge]
lemma tendsto_uniformly_iff {ι : Type*}
{F : ι → β → α} {f : β → α} {p : filter ι} :
tendsto_uniformly F f p ↔ ∀ ε > 0, ∀ᶠ n in p, ∀ x, dist (f x) (F n x) < ε :=
by { rw [← tendsto_uniformly_on_univ, tendsto_uniformly_on_iff], simp }
protected lemma cauchy_iff {f : filter α} :
cauchy f ↔ f ≠ ⊥ ∧ ∀ ε > 0, ∃ t ∈ f, ∀ x y ∈ t, dist x y < ε :=
uniformity_basis_dist.cauchy_iff
theorem nhds_basis_ball : (𝓝 x).has_basis (λ ε:ℝ, 0 < ε) (ball x) :=
nhds_basis_uniformity uniformity_basis_dist
theorem mem_nhds_iff : s ∈ 𝓝 x ↔ ∃ε>0, ball x ε ⊆ s :=
nhds_basis_ball.mem_iff
theorem nhds_basis_closed_ball : (𝓝 x).has_basis (λ ε:ℝ, 0 < ε) (closed_ball x) :=
nhds_basis_uniformity uniformity_basis_dist_le
theorem nhds_basis_ball_inv_nat_succ :
(𝓝 x).has_basis (λ _, true) (λ n:ℕ, ball x (1 / (↑n+1))) :=
nhds_basis_uniformity uniformity_basis_dist_inv_nat_succ
theorem nhds_basis_ball_inv_nat_pos :
(𝓝 x).has_basis (λ n, 0<n) (λ n:ℕ, ball x (1 / ↑n)) :=
nhds_basis_uniformity uniformity_basis_dist_inv_nat_pos
theorem is_open_iff : is_open s ↔ ∀x∈s, ∃ε>0, ball x ε ⊆ s :=
by simp only [is_open_iff_nhds, mem_nhds_iff, le_principal_iff]
theorem is_open_ball : is_open (ball x ε) :=
is_open_iff.2 $ λ y, exists_ball_subset_ball
theorem ball_mem_nhds (x : α) {ε : ℝ} (ε0 : 0 < ε) : ball x ε ∈ 𝓝 x :=
mem_nhds_sets is_open_ball (mem_ball_self ε0)
theorem nhds_within_basis_ball {s : set α} :
(nhds_within x s).has_basis (λ ε:ℝ, 0 < ε) (λ ε, ball x ε ∩ s) :=
nhds_within_has_basis nhds_basis_ball s
@[nolint ge_or_gt] -- see Note [nolint_ge]
theorem mem_nhds_within_iff {t : set α} : s ∈ nhds_within x t ↔ ∃ε>0, ball x ε ∩ t ⊆ s :=
nhds_within_basis_ball.mem_iff
@[nolint ge_or_gt] -- see Note [nolint_ge]
theorem tendsto_nhds_within_nhds_within [metric_space β] {t : set β} {f : α → β} {a b} :
tendsto f (nhds_within a s) (nhds_within b t) ↔
∀ ε > 0, ∃ δ > 0, ∀{x:α}, x ∈ s → dist x a < δ → f x ∈ t ∧ dist (f x) b < ε :=
(nhds_within_basis_ball.tendsto_iff nhds_within_basis_ball).trans $
by simp only [inter_comm, mem_inter_iff, and_imp, mem_ball]
@[nolint ge_or_gt] -- see Note [nolint_ge]
theorem tendsto_nhds_within_nhds [metric_space β] {f : α → β} {a b} :
tendsto f (nhds_within a s) (𝓝 b) ↔
∀ ε > 0, ∃ δ > 0, ∀{x:α}, x ∈ s → dist x a < δ → dist (f x) b < ε :=
by { rw [← nhds_within_univ, tendsto_nhds_within_nhds_within],
simp only [mem_univ, true_and] }
@[nolint ge_or_gt] -- see Note [nolint_ge]
theorem tendsto_nhds_nhds [metric_space β] {f : α → β} {a b} :
tendsto f (𝓝 a) (𝓝 b) ↔
∀ ε > 0, ∃ δ > 0, ∀{x:α}, dist x a < δ → dist (f x) b < ε :=
nhds_basis_ball.tendsto_iff nhds_basis_ball
@[nolint ge_or_gt] -- see Note [nolint_ge]
theorem continuous_at_iff [metric_space β] {f : α → β} {a : α} :
continuous_at f a ↔
∀ ε > 0, ∃ δ > 0, ∀{x:α}, dist x a < δ → dist (f x) (f a) < ε :=
by rw [continuous_at, tendsto_nhds_nhds]
@[nolint ge_or_gt] -- see Note [nolint_ge]
theorem continuous_within_at_iff [metric_space β] {f : α → β} {a : α} {s : set α} :
continuous_within_at f s a ↔
∀ ε > 0, ∃ δ > 0, ∀{x:α}, x ∈ s → dist x a < δ → dist (f x) (f a) < ε :=
by rw [continuous_within_at, tendsto_nhds_within_nhds]
@[nolint ge_or_gt] -- see Note [nolint_ge]
theorem continuous_on_iff [metric_space β] {f : α → β} {s : set α} :
continuous_on f s ↔
∀ (b ∈ s) (ε > 0), ∃ δ > 0, ∀a ∈ s, dist a b < δ → dist (f a) (f b) < ε :=
by simp [continuous_on, continuous_within_at_iff]
@[nolint ge_or_gt] -- see Note [nolint_ge]
theorem continuous_iff [metric_space β] {f : α → β} :
continuous f ↔
∀b (ε > 0), ∃ δ > 0, ∀a, dist a b < δ → dist (f a) (f b) < ε :=
continuous_iff_continuous_at.trans $ forall_congr $ λ b, tendsto_nhds_nhds
theorem tendsto_nhds {f : filter β} {u : β → α} {a : α} :
tendsto u f (𝓝 a) ↔ ∀ ε > 0, ∀ᶠ x in f, dist (u x) a < ε :=
nhds_basis_ball.tendsto_right_iff
@[nolint ge_or_gt] -- see Note [nolint_ge]
theorem continuous_at_iff' [topological_space β] {f : β → α} {b : β} :
continuous_at f b ↔
∀ ε > 0, ∀ᶠ x in 𝓝 b, dist (f x) (f b) < ε :=
by rw [continuous_at, tendsto_nhds]
@[nolint ge_or_gt] -- see Note [nolint_ge]
theorem continuous_within_at_iff' [topological_space β] {f : β → α} {b : β} {s : set β} :
continuous_within_at f s b ↔
∀ ε > 0, ∀ᶠ x in nhds_within b s, dist (f x) (f b) < ε :=
by rw [continuous_within_at, tendsto_nhds]
@[nolint ge_or_gt] -- see Note [nolint_ge]
theorem continuous_on_iff' [topological_space β] {f : β → α} {s : set β} :
continuous_on f s ↔
∀ (b ∈ s) (ε > 0), ∀ᶠ x in nhds_within b s, dist (f x) (f b) < ε :=
by simp [continuous_on, continuous_within_at_iff']
@[nolint ge_or_gt] -- see Note [nolint_ge]
theorem continuous_iff' [topological_space β] {f : β → α} :
continuous f ↔ ∀a (ε > 0), ∀ᶠ x in 𝓝 a, dist (f x) (f a) < ε :=
continuous_iff_continuous_at.trans $ forall_congr $ λ b, tendsto_nhds
theorem tendsto_at_top [nonempty β] [semilattice_sup β] {u : β → α} {a : α} :
tendsto u at_top (𝓝 a) ↔ ∀ε>0, ∃N, ∀n≥N, dist (u n) a < ε :=
(at_top_basis.tendsto_iff nhds_basis_ball).trans $
by { simp only [exists_prop, true_and], refl }
end metric
open metric
@[priority 100] -- see Note [lower instance priority]
instance metric_space.to_separated : separated α :=
separated_def.2 $ λ x y h, eq_of_forall_dist_le $
λ ε ε0, le_of_lt (h _ (dist_mem_uniformity ε0))
/-Instantiate a metric space as an emetric space. Before we can state the instance,
we need to show that the uniform structure coming from the edistance and the
distance coincide. -/
/-- Expressing the uniformity in terms of `edist` -/
protected lemma metric.uniformity_basis_edist :
(𝓤 α).has_basis (λ ε:ennreal, 0 < ε) (λ ε, {p | edist p.1 p.2 < ε}) :=
⟨begin
intro t,
refine mem_uniformity_dist.trans ⟨_, _⟩; rintro ⟨ε, ε0, Hε⟩,
{ use [ennreal.of_real ε, ennreal.of_real_pos.2 ε0],
rintros ⟨a, b⟩,
simp only [edist_dist, ennreal.of_real_lt_of_real_iff ε0],
exact Hε },
{ rcases ennreal.lt_iff_exists_real_btwn.1 ε0 with ⟨ε', _, ε0', hε⟩,
rw [ennreal.of_real_pos] at ε0',
refine ⟨ε', ε0', λ a b h, Hε (lt_trans _ hε)⟩,
rwa [edist_dist, ennreal.of_real_lt_of_real_iff ε0'] }
end⟩
@[nolint ge_or_gt] -- see Note [nolint_ge]
theorem metric.uniformity_edist : 𝓤 α = (⨅ ε>0, principal {p:α×α | edist p.1 p.2 < ε}) :=
metric.uniformity_basis_edist.eq_binfi
/-- A metric space induces an emetric space -/
@[priority 100] -- see Note [lower instance priority]
instance metric_space.to_emetric_space : emetric_space α :=
{ edist := edist,
edist_self := by simp [edist_dist],
eq_of_edist_eq_zero := assume x y h, by simpa [edist_dist] using h,
edist_comm := by simp only [edist_dist, dist_comm]; simp,
edist_triangle := assume x y z, begin
simp only [edist_dist, (ennreal.of_real_add _ _).symm, dist_nonneg],
rw ennreal.of_real_le_of_real_iff _,
{ exact dist_triangle _ _ _ },
{ simpa using add_le_add (dist_nonneg : 0 ≤ dist x y) dist_nonneg }
end,
uniformity_edist := metric.uniformity_edist,
..‹metric_space α› }
/-- Balls defined using the distance or the edistance coincide -/
lemma metric.emetric_ball {x : α} {ε : ℝ} : emetric.ball x (ennreal.of_real ε) = ball x ε :=
begin
ext y,
simp only [emetric.mem_ball, mem_ball, edist_dist],
exact ennreal.of_real_lt_of_real_iff_of_nonneg dist_nonneg
end
/-- Balls defined using the distance or the edistance coincide -/
lemma metric.emetric_ball_nnreal {x : α} {ε : nnreal} : emetric.ball x ε = ball x ε :=
by { convert metric.emetric_ball, simp }
/-- Closed balls defined using the distance or the edistance coincide -/
lemma metric.emetric_closed_ball {x : α} {ε : ℝ} (h : 0 ≤ ε) :
emetric.closed_ball x (ennreal.of_real ε) = closed_ball x ε :=
by ext y; simp [edist_dist]; rw ennreal.of_real_le_of_real_iff h
/-- Closed balls defined using the distance or the edistance coincide -/
lemma metric.emetric_closed_ball_nnreal {x : α} {ε : nnreal} :
emetric.closed_ball x ε = closed_ball x ε :=
by { convert metric.emetric_closed_ball ε.2, simp }
def metric_space.replace_uniformity {α} [U : uniform_space α] (m : metric_space α)
(H : @uniformity _ U = @uniformity _ emetric_space.to_uniform_space') :
metric_space α :=
{ dist := @dist _ m.to_has_dist,
dist_self := dist_self,
eq_of_dist_eq_zero := @eq_of_dist_eq_zero _ _,
dist_comm := dist_comm,
dist_triangle := dist_triangle,
edist := edist,
edist_dist := edist_dist,
to_uniform_space := U,
uniformity_dist := H.trans metric_space.uniformity_dist }
/-- One gets a metric space from an emetric space if the edistance
is everywhere finite, by pushing the edistance to reals. We set it up so that the edist and the
uniformity are defeq in the metric space and the emetric space. In this definition, the distance
is given separately, to be able to prescribe some expression which is not defeq to the push-forward
of the edistance to reals. -/
def emetric_space.to_metric_space_of_dist {α : Type u} [e : emetric_space α]
(dist : α → α → ℝ)
(edist_ne_top : ∀x y: α, edist x y ≠ ⊤)
(h : ∀x y, dist x y = ennreal.to_real (edist x y)) :
metric_space α :=
let m : metric_space α :=
{ dist := dist,
eq_of_dist_eq_zero := λx y hxy, by simpa [h, ennreal.to_real_eq_zero_iff, edist_ne_top x y] using hxy,
dist_self := λx, by simp [h],
dist_comm := λx y, by simp [h, emetric_space.edist_comm],
dist_triangle := λx y z, begin
simp only [h],
rw [← ennreal.to_real_add (edist_ne_top _ _) (edist_ne_top _ _),
ennreal.to_real_le_to_real (edist_ne_top _ _)],
{ exact edist_triangle _ _ _ },
{ simp [ennreal.add_eq_top, edist_ne_top] }
end,
edist := λx y, edist x y,
edist_dist := λx y, by simp [h, ennreal.of_real_to_real, edist_ne_top] } in
m.replace_uniformity $ by { rw [uniformity_edist, metric.uniformity_edist], refl }
/-- One gets a metric space from an emetric space if the edistance
is everywhere finite, by pushing the edistance to reals. We set it up so that the edist and the
uniformity are defeq in the metric space and the emetric space. -/
def emetric_space.to_metric_space {α : Type u} [e : emetric_space α] (h : ∀x y: α, edist x y ≠ ⊤) :
metric_space α :=
emetric_space.to_metric_space_of_dist (λx y, ennreal.to_real (edist x y)) h (λx y, rfl)
/-- A very useful criterion to show that a space is complete is to show that all sequences
which satisfy a bound of the form `dist (u n) (u m) < B N` for all `n m ≥ N` are
converging. This is often applied for `B N = 2^{-N}`, i.e., with a very fast convergence to
`0`, which makes it possible to use arguments of converging series, while this is impossible
to do in general for arbitrary Cauchy sequences. -/
theorem metric.complete_of_convergent_controlled_sequences (B : ℕ → real) (hB : ∀n, 0 < B n)
(H : ∀u : ℕ → α, (∀N n m : ℕ, N ≤ n → N ≤ m → dist (u n) (u m) < B N) → ∃x, tendsto u at_top (𝓝 x)) :
complete_space α :=
begin
-- this follows from the same criterion in emetric spaces. We just need to translate
-- the convergence assumption from `dist` to `edist`
apply emetric.complete_of_convergent_controlled_sequences (λn, ennreal.of_real (B n)),
{ simp [hB] },
{ assume u Hu,
apply H,
assume N n m hn hm,
rw [← ennreal.of_real_lt_of_real_iff (hB N), ← edist_dist],
exact Hu N n m hn hm }
end
theorem metric.complete_of_cauchy_seq_tendsto :
(∀ u : ℕ → α, cauchy_seq u → ∃a, tendsto u at_top (𝓝 a)) → complete_space α :=
emetric.complete_of_cauchy_seq_tendsto
section real
/-- Instantiate the reals as a metric space. -/
instance real.metric_space : metric_space ℝ :=
{ dist := λx y, abs (x - y),
dist_self := by simp [abs_zero],
eq_of_dist_eq_zero := by simp [sub_eq_zero],
dist_comm := assume x y, abs_sub _ _,
dist_triangle := assume x y z, abs_sub_le _ _ _ }
theorem real.dist_eq (x y : ℝ) : dist x y = abs (x - y) := rfl
theorem real.dist_0_eq_abs (x : ℝ) : dist x 0 = abs x :=
by simp [real.dist_eq]
instance : order_topology ℝ :=
order_topology_of_nhds_abs $ λ x, begin
simp only [show ∀ r, {b : ℝ | abs (x - b) < r} = ball x r,
by simp [-sub_eq_add_neg, abs_sub, ball, real.dist_eq]],
apply le_antisymm,
{ simp [le_infi_iff],
exact λ ε ε0, mem_nhds_sets (is_open_ball) (mem_ball_self ε0) },
{ intros s h,
rcases mem_nhds_iff.1 h with ⟨ε, ε0, ss⟩,
exact mem_infi_sets _ (mem_infi_sets ε0 (mem_principal_sets.2 ss)) },
end
lemma closed_ball_Icc {x r : ℝ} : closed_ball x r = Icc (x-r) (x+r) :=
by ext y; rw [mem_closed_ball, dist_comm, real.dist_eq,
abs_sub_le_iff, mem_Icc, ← sub_le_iff_le_add', sub_le]
/-- Special case of the sandwich theorem; see `tendsto_of_tendsto_of_tendsto_of_le_of_le`
and `tendsto_of_tendsto_of_tendsto_of_le_of_le'` for the general case. -/
lemma squeeze_zero {α} {f g : α → ℝ} {t₀ : filter α} (hf : ∀t, 0 ≤ f t) (hft : ∀t, f t ≤ g t)
(g0 : tendsto g t₀ (𝓝 0)) : tendsto f t₀ (𝓝 0) :=
tendsto_of_tendsto_of_tendsto_of_le_of_le tendsto_const_nhds g0 hf hft
theorem metric.uniformity_eq_comap_nhds_zero :
𝓤 α = comap (λp:α×α, dist p.1 p.2) (𝓝 (0 : ℝ)) :=
by { ext s,
simp [mem_uniformity_dist, (nhds_basis_ball.comap _).mem_iff, subset_def, real.dist_0_eq_abs] }
lemma cauchy_seq_iff_tendsto_dist_at_top_0 [nonempty β] [semilattice_sup β] {u : β → α} :
cauchy_seq u ↔ tendsto (λ (n : β × β), dist (u n.1) (u n.2)) at_top (𝓝 0) :=
by rw [cauchy_seq_iff_tendsto, metric.uniformity_eq_comap_nhds_zero, tendsto_comap_iff,
prod.map_def]
end real
section cauchy_seq
variables [nonempty β] [semilattice_sup β]
/-- In a metric space, Cauchy sequences are characterized by the fact that, eventually,
the distance between its elements is arbitrarily small -/
theorem metric.cauchy_seq_iff {u : β → α} :
cauchy_seq u ↔ ∀ε>0, ∃N, ∀m n≥N, dist (u m) (u n) < ε :=
uniformity_basis_dist.cauchy_seq_iff
/-- A variation around the metric characterization of Cauchy sequences -/
theorem metric.cauchy_seq_iff' {u : β → α} :
cauchy_seq u ↔ ∀ε>0, ∃N, ∀n≥N, dist (u n) (u N) < ε :=
uniformity_basis_dist.cauchy_seq_iff'
/-- If the distance between `s n` and `s m`, `n, m ≥ N` is bounded above by `b N`
and `b` converges to zero, then `s` is a Cauchy sequence. -/
lemma cauchy_seq_of_le_tendsto_0 {s : β → α} (b : β → ℝ)
(h : ∀ n m N : β, N ≤ n → N ≤ m → dist (s n) (s m) ≤ b N) (h₀ : tendsto b at_top (nhds 0)) :
cauchy_seq s :=
metric.cauchy_seq_iff.2 $ λ ε ε0,
(metric.tendsto_at_top.1 h₀ ε ε0).imp $ λ N hN m n hm hn,
calc dist (s m) (s n) ≤ b N : h m n N hm hn
... ≤ abs (b N) : le_abs_self _
... = dist (b N) 0 : by rw real.dist_0_eq_abs; refl
... < ε : (hN _ (le_refl N))
/-- A Cauchy sequence on the natural numbers is bounded. -/
theorem cauchy_seq_bdd {u : ℕ → α} (hu : cauchy_seq u) :
∃ R > 0, ∀ m n, dist (u m) (u n) < R :=
begin
rcases metric.cauchy_seq_iff'.1 hu 1 zero_lt_one with ⟨N, hN⟩,
suffices : ∃ R > 0, ∀ n, dist (u n) (u N) < R,
{ rcases this with ⟨R, R0, H⟩,
exact ⟨_, add_pos R0 R0, λ m n,
lt_of_le_of_lt (dist_triangle_right _ _ _) (add_lt_add (H m) (H n))⟩ },
let R := finset.sup (finset.range N) (λ n, nndist (u n) (u N)),
refine ⟨↑R + 1, add_pos_of_nonneg_of_pos R.2 zero_lt_one, λ n, _⟩,
cases le_or_lt N n,
{ exact lt_of_lt_of_le (hN _ h) (le_add_of_nonneg_left R.2) },
{ have : _ ≤ R := finset.le_sup (finset.mem_range.2 h),
exact lt_of_le_of_lt this (lt_add_of_pos_right _ zero_lt_one) }
end
/-- Yet another metric characterization of Cauchy sequences on integers. This one is often the
most efficient. -/
lemma cauchy_seq_iff_le_tendsto_0 {s : ℕ → α} : cauchy_seq s ↔ ∃ b : ℕ → ℝ,
(∀ n, 0 ≤ b n) ∧
(∀ n m N : ℕ, N ≤ n → N ≤ m → dist (s n) (s m) ≤ b N) ∧
tendsto b at_top (𝓝 0) :=
⟨λ hs, begin
/- `s` is a Cauchy sequence. The sequence `b` will be constructed by taking
the supremum of the distances between `s n` and `s m` for `n m ≥ N`.
First, we prove that all these distances are bounded, as otherwise the Sup
would not make sense. -/
let S := λ N, (λ(p : ℕ × ℕ), dist (s p.1) (s p.2)) '' {p | p.1 ≥ N ∧ p.2 ≥ N},
have hS : ∀ N, ∃ x, ∀ y ∈ S N, y ≤ x,
{ rcases cauchy_seq_bdd hs with ⟨R, R0, hR⟩,
refine λ N, ⟨R, _⟩, rintro _ ⟨⟨m, n⟩, _, rfl⟩,
exact le_of_lt (hR m n) },
have bdd : bdd_above (range (λ(p : ℕ × ℕ), dist (s p.1) (s p.2))),
{ rcases cauchy_seq_bdd hs with ⟨R, R0, hR⟩,
use R, rintro _ ⟨⟨m, n⟩, rfl⟩, exact le_of_lt (hR m n) },
-- Prove that it bounds the distances of points in the Cauchy sequence
have ub : ∀ m n N, N ≤ m → N ≤ n → dist (s m) (s n) ≤ Sup (S N) :=
λ m n N hm hn, real.le_Sup _ (hS N) ⟨⟨_, _⟩, ⟨hm, hn⟩, rfl⟩,
have S0m : ∀ n, (0:ℝ) ∈ S n := λ n, ⟨⟨n, n⟩, ⟨le_refl _, le_refl _⟩, dist_self _⟩,
have S0 := λ n, real.le_Sup _ (hS n) (S0m n),
-- Prove that it tends to `0`, by using the Cauchy property of `s`
refine ⟨λ N, Sup (S N), S0, ub, metric.tendsto_at_top.2 (λ ε ε0, _)⟩,
refine (metric.cauchy_seq_iff.1 hs (ε/2) (half_pos ε0)).imp (λ N hN n hn, _),
rw [real.dist_0_eq_abs, abs_of_nonneg (S0 n)],
refine lt_of_le_of_lt (real.Sup_le_ub _ ⟨_, S0m _⟩ _) (half_lt_self ε0),
rintro _ ⟨⟨m', n'⟩, ⟨hm', hn'⟩, rfl⟩,
exact le_of_lt (hN _ _ (le_trans hn hm') (le_trans hn hn'))
end,
λ ⟨b, _, b_bound, b_lim⟩, cauchy_seq_of_le_tendsto_0 b b_bound b_lim⟩
end cauchy_seq
def metric_space.induced {α β} (f : α → β) (hf : function.injective f)
(m : metric_space β) : metric_space α :=
{ dist := λ x y, dist (f x) (f y),
dist_self := λ x, dist_self _,
eq_of_dist_eq_zero := λ x y h, hf (dist_eq_zero.1 h),
dist_comm := λ x y, dist_comm _ _,
dist_triangle := λ x y z, dist_triangle _ _ _,
edist := λ x y, edist (f x) (f y),
edist_dist := λ x y, edist_dist _ _,
to_uniform_space := uniform_space.comap f m.to_uniform_space,
uniformity_dist := begin
apply @uniformity_dist_of_mem_uniformity _ _ _ _ _ (λ x y, dist (f x) (f y)),
refine λ s, mem_comap_sets.trans _,
split; intro H,
{ rcases H with ⟨r, ru, rs⟩,
rcases mem_uniformity_dist.1 ru with ⟨ε, ε0, hε⟩,
refine ⟨ε, ε0, λ a b h, rs (hε _)⟩, exact h },
{ rcases H with ⟨ε, ε0, hε⟩,
exact ⟨_, dist_mem_uniformity ε0, λ ⟨a, b⟩, hε⟩ }
end }
instance subtype.metric_space {α : Type*} {p : α → Prop} [t : metric_space α] :
metric_space (subtype p) :=
metric_space.induced coe (λ x y, subtype.coe_ext.2) t
theorem subtype.dist_eq {p : α → Prop} (x y : subtype p) : dist x y = dist (x : α) y := rfl
section nnreal
instance : metric_space nnreal := by unfold nnreal; apply_instance
lemma nnreal.dist_eq (a b : nnreal) : dist a b = abs ((a:ℝ) - b) := rfl
lemma nnreal.nndist_eq (a b : nnreal) :
nndist a b = max (a - b) (b - a) :=
begin
wlog h : a ≤ b,
{ apply nnreal.coe_eq.1,
rw [nnreal.sub_eq_zero h, max_eq_right (zero_le $ b - a), ← dist_nndist, nnreal.dist_eq,
nnreal.coe_sub h, abs, neg_sub],
apply max_eq_right,
linarith [nnreal.coe_le_coe.2 h] },
rwa [nndist_comm, max_comm]
end
end nnreal
section prod
instance prod.metric_space_max [metric_space β] : metric_space (α × β) :=
{ dist := λ x y, max (dist x.1 y.1) (dist x.2 y.2),
dist_self := λ x, by simp,
eq_of_dist_eq_zero := λ x y h, begin
cases max_le_iff.1 (le_of_eq h) with h₁ h₂,
exact prod.ext_iff.2 ⟨dist_le_zero.1 h₁, dist_le_zero.1 h₂⟩
end,
dist_comm := λ x y, by simp [dist_comm],
dist_triangle := λ x y z, max_le
(le_trans (dist_triangle _ _ _) (add_le_add (le_max_left _ _) (le_max_left _ _)))
(le_trans (dist_triangle _ _ _) (add_le_add (le_max_right _ _) (le_max_right _ _))),
edist := λ x y, max (edist x.1 y.1) (edist x.2 y.2),
edist_dist := assume x y, begin
have : monotone ennreal.of_real := assume x y h, ennreal.of_real_le_of_real h,
rw [edist_dist, edist_dist, this.map_max.symm]
end,
uniformity_dist := begin
refine uniformity_prod.trans _,
simp only [uniformity_basis_dist.eq_binfi, comap_infi],
rw ← infi_inf_eq, congr, funext,
rw ← infi_inf_eq, congr, funext,
simp [inf_principal, ext_iff, max_lt_iff]
end,
to_uniform_space := prod.uniform_space }
lemma prod.dist_eq [metric_space β] {x y : α × β} :
dist x y = max (dist x.1 y.1) (dist x.2 y.2) := rfl
end prod
theorem uniform_continuous_dist' : uniform_continuous (λp:α×α, dist p.1 p.2) :=
metric.uniform_continuous_iff.2 (λ ε ε0, ⟨ε/2, half_pos ε0,
begin
suffices,
{ intros p q h, cases p with p₁ p₂, cases q with q₁ q₂,
cases max_lt_iff.1 h with h₁ h₂, clear h,
dsimp at h₁ h₂ ⊢,
rw real.dist_eq,
refine abs_sub_lt_iff.2 ⟨_, _⟩,
{ revert p₁ p₂ q₁ q₂ h₁ h₂, exact this },
{ apply this; rwa dist_comm } },
intros p₁ p₂ q₁ q₂ h₁ h₂,
have := add_lt_add
(abs_sub_lt_iff.1 (lt_of_le_of_lt (abs_dist_sub_le p₁ q₁ p₂) h₁)).1
(abs_sub_lt_iff.1 (lt_of_le_of_lt (abs_dist_sub_le p₂ q₂ q₁) h₂)).1,
rwa [add_halves, dist_comm p₂, sub_add_sub_cancel, dist_comm q₂] at this
end⟩)
theorem uniform_continuous_dist [uniform_space β] {f g : β → α}
(hf : uniform_continuous f) (hg : uniform_continuous g) :
uniform_continuous (λb, dist (f b) (g b)) :=
uniform_continuous_dist'.comp (hf.prod_mk hg)
theorem continuous_dist : continuous (λp:α×α, dist p.1 p.2) :=
uniform_continuous_dist'.continuous
theorem continuous.dist [topological_space β] {f g : β → α}
(hf : continuous f) (hg : continuous g) : continuous (λb, dist (f b) (g b)) :=
continuous_dist.comp (hf.prod_mk hg)
theorem filter.tendsto.dist {f g : β → α} {x : filter β} {a b : α}
(hf : tendsto f x (𝓝 a)) (hg : tendsto g x (𝓝 b)) :
tendsto (λx, dist (f x) (g x)) x (𝓝 (dist a b)) :=
(continuous_dist.tendsto (a, b)).comp (hf.prod_mk_nhds hg)
lemma nhds_comap_dist (a : α) : (𝓝 (0 : ℝ)).comap (λa', dist a' a) = 𝓝 a :=
by simp only [@nhds_eq_comap_uniformity α, metric.uniformity_eq_comap_nhds_zero,
comap_comap_comp, (∘), dist_comm]
lemma tendsto_iff_dist_tendsto_zero {f : β → α} {x : filter β} {a : α} :
(tendsto f x (𝓝 a)) ↔ (tendsto (λb, dist (f b) a) x (𝓝 0)) :=
by rw [← nhds_comap_dist a, tendsto_comap_iff]
lemma uniform_continuous_nndist : uniform_continuous (λp:α×α, nndist p.1 p.2) :=
uniform_continuous_subtype_mk uniform_continuous_dist' _
lemma continuous_nndist : continuous (λp:α×α, nndist p.1 p.2) :=
uniform_continuous_nndist.continuous
lemma continuous.nndist [topological_space β] {f g : β → α}
(hf : continuous f) (hg : continuous g) : continuous (λb, nndist (f b) (g b)) :=
continuous_nndist.comp (hf.prod_mk hg)
theorem filter.tendsto.nndist {f g : β → α} {x : filter β} {a b : α}
(hf : tendsto f x (𝓝 a)) (hg : tendsto g x (𝓝 b)) :
tendsto (λx, nndist (f x) (g x)) x (𝓝 (nndist a b)) :=
(continuous_nndist.tendsto (a, b)).comp (hf.prod_mk_nhds hg)
namespace metric
variables {x y z : α} {ε ε₁ ε₂ : ℝ} {s : set α}
theorem is_closed_ball : is_closed (closed_ball x ε) :=
is_closed_le (continuous_id.dist continuous_const) continuous_const
/-- ε-characterization of the closure in metric spaces-/
@[nolint ge_or_gt] -- see Note [nolint_ge]
theorem mem_closure_iff {α : Type u} [metric_space α] {s : set α} {a : α} :
a ∈ closure s ↔ ∀ε>0, ∃b ∈ s, dist a b < ε :=
(mem_closure_iff_nhds_basis nhds_basis_ball).trans $
by simp only [mem_ball, dist_comm]
lemma mem_closure_range_iff {α : Type u} [metric_space α] {e : β → α} {a : α} :
a ∈ closure (range e) ↔ ∀ε>0, ∃ k : β, dist a (e k) < ε :=
by simp only [mem_closure_iff, exists_range_iff]
lemma mem_closure_range_iff_nat {α : Type u} [metric_space α] {e : β → α} {a : α} :
a ∈ closure (range e) ↔ ∀n : ℕ, ∃ k : β, dist a (e k) < 1 / ((n : ℝ) + 1) :=
(mem_closure_iff_nhds_basis nhds_basis_ball_inv_nat_succ).trans $
by simp only [mem_ball, dist_comm, exists_range_iff, forall_const]
theorem mem_of_closed' {α : Type u} [metric_space α] {s : set α} (hs : is_closed s)
{a : α} : a ∈ s ↔ ∀ε>0, ∃b ∈ s, dist a b < ε :=
by simpa only [closure_eq_of_is_closed hs] using @mem_closure_iff _ _ s a
end metric
section pi
open finset
variables {π : β → Type*} [fintype β] [∀b, metric_space (π b)]
/-- A finite product of metric spaces is a metric space, with the sup distance. -/
instance metric_space_pi : metric_space (Πb, π b) :=
begin
/- we construct the instance from the emetric space instance to avoid checking again that the
uniformity is the same as the product uniformity, but we register nevertheless a nice formula
for the distance -/
refine emetric_space.to_metric_space_of_dist
(λf g, ((sup univ (λb, nndist (f b) (g b)) : nnreal) : ℝ)) _ _,
show ∀ (x y : Π (b : β), π b), edist x y ≠ ⊤,
{ assume x y,
rw ← lt_top_iff_ne_top,
have : (⊥ : ennreal) < ⊤ := ennreal.coe_lt_top,
simp [edist, this],
assume b,
rw lt_top_iff_ne_top,
exact edist_ne_top (x b) (y b) },
show ∀ (x y : Π (b : β), π b), ↑(sup univ (λ (b : β), nndist (x b) (y b))) =
ennreal.to_real (sup univ (λ (b : β), edist (x b) (y b))),
{ assume x y,
have : sup univ (λ (b : β), edist (x b) (y b)) = ↑(sup univ (λ (b : β), nndist (x b) (y b))),
{ simp [edist_nndist],
refine eq.symm (comp_sup_eq_sup_comp _ _ _),
exact (assume x y h, ennreal.coe_le_coe.2 h), refl },
rw this,
refl }
end
lemma dist_pi_def (f g : Πb, π b) :
dist f g = (sup univ (λb, nndist (f b) (g b)) : nnreal) := rfl
lemma dist_pi_lt_iff {f g : Πb, π b} {r : ℝ} (hr : 0 < r) :
dist f g < r ↔ ∀b, dist (f b) (g b) < r :=
begin
lift r to nnreal using le_of_lt hr,
rw_mod_cast [dist_pi_def, finset.sup_lt_iff],
{ simp [nndist], refl },
{ exact hr }
end
lemma dist_pi_le_iff {f g : Πb, π b} {r : ℝ} (hr : 0 ≤ r) :
dist f g ≤ r ↔ ∀b, dist (f b) (g b) ≤ r :=
begin
lift r to nnreal using hr,
rw_mod_cast [dist_pi_def, finset.sup_le_iff],
simp [nndist],
refl
end
/-- An open ball in a product space is a product of open balls. The assumption `0 < r`
is necessary for the case of the empty product. -/
lemma ball_pi (x : Πb, π b) {r : ℝ} (hr : 0 < r) :
ball x r = { y | ∀b, y b ∈ ball (x b) r } :=
by { ext p, simp [dist_pi_lt_iff hr] }
/-- A closed ball in a product space is a product of closed balls. The assumption `0 ≤ r`
is necessary for the case of the empty product. -/
lemma closed_ball_pi (x : Πb, π b) {r : ℝ} (hr : 0 ≤ r) :
closed_ball x r = { y | ∀b, y b ∈ closed_ball (x b) r } :=
by { ext p, simp [dist_pi_le_iff hr] }
end pi
section compact
/-- Any compact set in a metric space can be covered by finitely many balls of a given positive
radius -/
lemma finite_cover_balls_of_compact {α : Type u} [metric_space α] {s : set α}
(hs : compact s) {e : ℝ} (he : 0 < e) :
∃t ⊆ s, finite t ∧ s ⊆ ⋃x∈t, ball x e :=
begin
apply hs.elim_finite_subcover_image,
{ simp [is_open_ball] },
{ intros x xs,
simp,
exact ⟨x, ⟨xs, by simpa⟩⟩ }
end
alias finite_cover_balls_of_compact ← compact.finite_cover_balls
end compact
section proper_space
open metric
/-- A metric space is proper if all closed balls are compact. -/
class proper_space (α : Type u) [metric_space α] : Prop :=
(compact_ball : ∀x:α, ∀r, compact (closed_ball x r))
/-- If all closed balls of large enough radius are compact, then the space is proper. Especially
useful when the lower bound for the radius is 0. -/
lemma proper_space_of_compact_closed_ball_of_le
(R : ℝ) (h : ∀x:α, ∀r, R ≤ r → compact (closed_ball x r)) :
proper_space α :=
⟨begin
assume x r,
by_cases hr : R ≤ r,
{ exact h x r hr },
{ have : closed_ball x r = closed_ball x R ∩ closed_ball x r,
{ symmetry,
apply inter_eq_self_of_subset_right,
exact closed_ball_subset_closed_ball (le_of_lt (not_le.1 hr)) },
rw this,
exact (h x R (le_refl _)).inter_right is_closed_ball }
end⟩
/- A compact metric space is proper -/
@[priority 100] -- see Note [lower instance priority]
instance proper_of_compact [compact_space α] : proper_space α :=
⟨assume x r, compact_of_is_closed_subset compact_univ is_closed_ball (subset_univ _)⟩
/-- A proper space is locally compact -/
@[priority 100] -- see Note [lower instance priority]
instance locally_compact_of_proper [proper_space α] :
locally_compact_space α :=
begin
apply locally_compact_of_compact_nhds,
intros x,
existsi closed_ball x 1,
split,
{ apply mem_nhds_iff.2,
existsi (1 : ℝ),
simp,
exact ⟨zero_lt_one, ball_subset_closed_ball⟩ },
{ apply proper_space.compact_ball }
end
/-- A proper space is complete -/
@[priority 100] -- see Note [lower instance priority]
instance complete_of_proper [proper_space α] : complete_space α :=
⟨begin
intros f hf,
/- We want to show that the Cauchy filter `f` is converging. It suffices to find a closed
ball (therefore compact by properness) where it is nontrivial. -/
have A : ∃ t ∈ f, ∀ x y ∈ t, dist x y < 1 := (metric.cauchy_iff.1 hf).2 1 zero_lt_one,
rcases A with ⟨t, ⟨t_fset, ht⟩⟩,
rcases nonempty_of_mem_sets hf.1 t_fset with ⟨x, xt⟩,
have : t ⊆ closed_ball x 1 := by intros y yt; simp [dist_comm]; apply le_of_lt (ht x y xt yt),
have : closed_ball x 1 ∈ f := f.sets_of_superset t_fset this,
rcases (compact_iff_totally_bounded_complete.1 (proper_space.compact_ball x 1)).2 f hf (le_principal_iff.2 this)
with ⟨y, _, hy⟩,
exact ⟨y, hy⟩
end⟩
/-- A proper metric space is separable, and therefore second countable. Indeed, any ball is
compact, and therefore admits a countable dense subset. Taking a countable union over the balls
centered at a fixed point and with integer radius, one obtains a countable set which is
dense in the whole space. -/
@[priority 100] -- see Note [lower instance priority]
instance second_countable_of_proper [proper_space α] :
second_countable_topology α :=
begin
/- We show that the space admits a countable dense subset. The case where the space is empty
is special, and trivial. -/
have A : (univ : set α) = ∅ → ∃(s : set α), countable s ∧ closure s = (univ : set α) :=
assume H, ⟨∅, ⟨by simp, by simp; exact H.symm⟩⟩,
have B : (univ : set α).nonempty → ∃(s : set α), countable s ∧ closure s = (univ : set α) :=
begin
/- When the space is not empty, we take a point `x` in the space, and then a countable set
`T r` which is dense in the closed ball `closed_ball x r` for each `r`. Then the set
`t = ⋃ T n` (where the union is over all integers `n`) is countable, as a countable union
of countable sets, and dense in the space by construction. -/
rintros ⟨x, x_univ⟩,
choose T a using show ∀ (r:ℝ), ∃ t ⊆ closed_ball x r, (countable (t : set α) ∧ closed_ball x r = closure t),
from assume r, emetric.countable_closure_of_compact (proper_space.compact_ball _ _),
let t := (⋃n:ℕ, T (n : ℝ)),
have T₁ : countable t := by finish [countable_Union],
have T₂ : closure t ⊆ univ := by simp,
have T₃ : univ ⊆ closure t :=
begin
intros y y_univ,
rcases exists_nat_gt (dist y x) with ⟨n, n_large⟩,
have h : y ∈ closed_ball x (n : ℝ) := by simp; apply le_of_lt n_large,
have h' : closed_ball x (n : ℝ) = closure (T (n : ℝ)) := by finish,
have : y ∈ closure (T (n : ℝ)) := by rwa h' at h,
show y ∈ closure t, from mem_of_mem_of_subset this (by apply closure_mono; apply subset_Union (λ(n:ℕ), T (n:ℝ))),
end,
exact ⟨t, ⟨T₁, subset.antisymm T₂ T₃⟩⟩
end,
haveI : separable_space α := ⟨(eq_empty_or_nonempty univ).elim A B⟩,
apply emetric.second_countable_of_separable,
end
/-- A finite product of proper spaces is proper. -/
instance pi_proper_space {π : β → Type*} [fintype β] [∀b, metric_space (π b)]
[h : ∀b, proper_space (π b)] : proper_space (Πb, π b) :=
begin
refine proper_space_of_compact_closed_ball_of_le 0 (λx r hr, _),
rw closed_ball_pi _ hr,
apply compact_pi_infinite (λb, _),
apply (h b).compact_ball
end
end proper_space
namespace metric
section second_countable
open topological_space
/-- A metric space is second countable if, for every ε > 0, there is a countable set which is ε-dense. -/
lemma second_countable_of_almost_dense_set
(H : ∀ε > (0 : ℝ), ∃ s : set α, countable s ∧ (∀x, ∃y ∈ s, dist x y ≤ ε)) :
second_countable_topology α :=
begin
choose T T_dense using H,
have I1 : ∀n:ℕ, (n:ℝ) + 1 > 0 :=
λn, lt_of_lt_of_le zero_lt_one (le_add_of_nonneg_left (nat.cast_nonneg _)),
have I : ∀n:ℕ, (n+1 : ℝ)⁻¹ > 0 := λn, inv_pos.2 (I1 n),
let t := ⋃n:ℕ, T (n+1)⁻¹ (I n),
have count_t : countable t := by finish [countable_Union],
have clos_t : closure t = univ,
{ refine subset.antisymm (subset_univ _) (λx xuniv, mem_closure_iff.2 (λε εpos, _)),
rcases exists_nat_gt ε⁻¹ with ⟨n, hn⟩,
have : ε⁻¹ < n + 1 := lt_of_lt_of_le hn (le_add_of_nonneg_right zero_le_one),
have nε : ((n:ℝ)+1)⁻¹ < ε := (inv_lt (I1 n) εpos).2 this,
rcases (T_dense (n+1)⁻¹ (I n)).2 x with ⟨y, yT, Dxy⟩,
have : y ∈ t := mem_of_mem_of_subset yT (by apply subset_Union (λ (n:ℕ), T (n+1)⁻¹ (I n))),
exact ⟨y, this, lt_of_le_of_lt Dxy nε⟩ },
haveI : separable_space α := ⟨⟨t, ⟨count_t, clos_t⟩⟩⟩,
exact emetric.second_countable_of_separable α
end
/-- A metric space space is second countable if one can reconstruct up to any ε>0 any element of the
space from countably many data. -/
lemma second_countable_of_countable_discretization {α : Type u} [metric_space α]
(H : ∀ε > (0 : ℝ), ∃ (β : Type u) [encodable β] (F : α → β), ∀x y, F x = F y → dist x y ≤ ε) :
second_countable_topology α :=
begin
cases (univ : set α).eq_empty_or_nonempty with hs hs,
{ haveI : compact_space α := ⟨by rw hs; exact compact_empty⟩, by apply_instance },
rcases hs with ⟨x0, hx0⟩,
letI : inhabited α := ⟨x0⟩,
refine second_countable_of_almost_dense_set (λε ε0, _),
rcases H ε ε0 with ⟨β, fβ, F, hF⟩,
let Finv := function.inv_fun F,
refine ⟨range Finv, ⟨countable_range _, λx, _⟩⟩,
let x' := Finv (F x),
have : F x' = F x := function.inv_fun_eq ⟨x, rfl⟩,
exact ⟨x', mem_range_self _, hF _ _ this.symm⟩
end
end second_countable
end metric
lemma lebesgue_number_lemma_of_metric
{s : set α} {ι} {c : ι → set α} (hs : compact s)
(hc₁ : ∀ i, is_open (c i)) (hc₂ : s ⊆ ⋃ i, c i) :
∃ δ > 0, ∀ x ∈ s, ∃ i, ball x δ ⊆ c i :=
let ⟨n, en, hn⟩ := lebesgue_number_lemma hs hc₁ hc₂,
⟨δ, δ0, hδ⟩ := mem_uniformity_dist.1 en in
⟨δ, δ0, assume x hx, let ⟨i, hi⟩ := hn x hx in
⟨i, assume y hy, hi (hδ (mem_ball'.mp hy))⟩⟩
lemma lebesgue_number_lemma_of_metric_sUnion
{s : set α} {c : set (set α)} (hs : compact s)
(hc₁ : ∀ t ∈ c, is_open t) (hc₂ : s ⊆ ⋃₀ c) :
∃ δ > 0, ∀ x ∈ s, ∃ t ∈ c, ball x δ ⊆ t :=
by rw sUnion_eq_Union at hc₂;
simpa using lebesgue_number_lemma_of_metric hs (by simpa) hc₂
namespace metric
/-- Boundedness of a subset of a metric space. We formulate the definition to work
even in the empty space. -/
def bounded (s : set α) : Prop :=
∃C, ∀x y ∈ s, dist x y ≤ C
section bounded
variables {x : α} {s t : set α} {r : ℝ}
@[simp] lemma bounded_empty : bounded (∅ : set α) :=
⟨0, by simp⟩
lemma bounded_iff_mem_bounded : bounded s ↔ ∀ x ∈ s, bounded s :=
⟨λ h _ _, h, λ H,
s.eq_empty_or_nonempty.elim
(λ hs, hs.symm ▸ bounded_empty)
(λ ⟨x, hx⟩, H x hx)⟩
/-- Subsets of a bounded set are also bounded -/
lemma bounded.subset (incl : s ⊆ t) : bounded t → bounded s :=
Exists.imp $ λ C hC x y hx hy, hC x y (incl hx) (incl hy)
/-- Closed balls are bounded -/
lemma bounded_closed_ball : bounded (closed_ball x r) :=
⟨r + r, λ y z hy hz, begin
simp only [mem_closed_ball] at *,
calc dist y z ≤ dist y x + dist z x : dist_triangle_right _ _ _
... ≤ r + r : add_le_add hy hz
end⟩
/-- Open balls are bounded -/
lemma bounded_ball : bounded (ball x r) :=
bounded_closed_ball.subset ball_subset_closed_ball
/-- Given a point, a bounded subset is included in some ball around this point -/
lemma bounded_iff_subset_ball (c : α) : bounded s ↔ ∃r, s ⊆ closed_ball c r :=
begin
split; rintro ⟨C, hC⟩,
{ cases s.eq_empty_or_nonempty with h h,
{ subst s, exact ⟨0, by simp⟩ },
{ rcases h with ⟨x, hx⟩,
exact ⟨C + dist x c, λ y hy, calc
dist y c ≤ dist y x + dist x c : dist_triangle _ _ _
... ≤ C + dist x c : add_le_add_right (hC y x hy hx) _⟩ } },
{ exact bounded_closed_ball.subset hC }
end
/-- The union of two bounded sets is bounded iff each of the sets is bounded -/
@[simp] lemma bounded_union :
bounded (s ∪ t) ↔ bounded s ∧ bounded t :=
⟨λh, ⟨h.subset (by simp), h.subset (by simp)⟩,
begin
rintro ⟨hs, ht⟩,
refine bounded_iff_mem_bounded.2 (λ x _, _),
rw bounded_iff_subset_ball x at hs ht ⊢,
rcases hs with ⟨Cs, hCs⟩, rcases ht with ⟨Ct, hCt⟩,
exact ⟨max Cs Ct, union_subset
(subset.trans hCs $ closed_ball_subset_closed_ball $ le_max_left _ _)
(subset.trans hCt $ closed_ball_subset_closed_ball $ le_max_right _ _)⟩,
end⟩
/-- A finite union of bounded sets is bounded -/
lemma bounded_bUnion {I : set β} {s : β → set α} (H : finite I) :
bounded (⋃i∈I, s i) ↔ ∀i ∈ I, bounded (s i) :=
finite.induction_on H (by simp) $ λ x I _ _ IH,
by simp [or_imp_distrib, forall_and_distrib, IH]
/-- A compact set is bounded -/
lemma bounded_of_compact {s : set α} (h : compact s) : bounded s :=
-- We cover the compact set by finitely many balls of radius 1,
-- and then argue that a finite union of bounded sets is bounded
let ⟨t, ht, fint, subs⟩ := finite_cover_balls_of_compact h zero_lt_one in
bounded.subset subs $ (bounded_bUnion fint).2 $ λ i hi, bounded_ball
alias bounded_of_compact ← compact.bounded
/-- A finite set is bounded -/
lemma bounded_of_finite {s : set α} (h : finite s) : bounded s :=
h.compact.bounded
/-- A singleton is bounded -/
lemma bounded_singleton {x : α} : bounded ({x} : set α) :=
bounded_of_finite $ finite_singleton _
/-- Characterization of the boundedness of the range of a function -/
lemma bounded_range_iff {f : β → α} : bounded (range f) ↔ ∃C, ∀x y, dist (f x) (f y) ≤ C :=
exists_congr $ λ C, ⟨
λ H x y, H _ _ ⟨x, rfl⟩ ⟨y, rfl⟩,
by rintro H _ _ ⟨x, rfl⟩ ⟨y, rfl⟩; exact H x y⟩
/-- In a compact space, all sets are bounded -/
lemma bounded_of_compact_space [compact_space α] : bounded s :=
compact_univ.bounded.subset (subset_univ _)
/-- The Heine–Borel theorem:
In a proper space, a set is compact if and only if it is closed and bounded -/
lemma compact_iff_closed_bounded [proper_space α] :
compact s ↔ is_closed s ∧ bounded s :=
⟨λ h, ⟨closed_of_compact _ h, h.bounded⟩, begin
rintro ⟨hc, hb⟩,
cases s.eq_empty_or_nonempty with h h, {simp [h, compact_empty]},
rcases h with ⟨x, hx⟩,
rcases (bounded_iff_subset_ball x).1 hb with ⟨r, hr⟩,
exact compact_of_is_closed_subset (proper_space.compact_ball x r) hc hr
end⟩
/-- The image of a proper space under an expanding onto map is proper. -/
lemma proper_image_of_proper [proper_space α] [metric_space β] (f : α → β)
(f_cont : continuous f) (hf : range f = univ) (C : ℝ)
(hC : ∀x y, dist x y ≤ C * dist (f x) (f y)) : proper_space β :=
begin
apply proper_space_of_compact_closed_ball_of_le 0 (λx₀ r hr, _),
let K := f ⁻¹' (closed_ball x₀ r),
have A : is_closed K :=
continuous_iff_is_closed.1 f_cont (closed_ball x₀ r) (is_closed_ball),
have B : bounded K := ⟨max C 0 * (r + r), λx y hx hy, calc
dist x y ≤ C * dist (f x) (f y) : hC x y
... ≤ max C 0 * dist (f x) (f y) : mul_le_mul_of_nonneg_right (le_max_left _ _) (dist_nonneg)
... ≤ max C 0 * (dist (f x) x₀ + dist (f y) x₀) :
mul_le_mul_of_nonneg_left (dist_triangle_right (f x) (f y) x₀) (le_max_right _ _)
... ≤ max C 0 * (r + r) : begin
simp only [mem_closed_ball, mem_preimage] at hx hy,
exact mul_le_mul_of_nonneg_left (add_le_add hx hy) (le_max_right _ _)
end⟩,
have : compact K := compact_iff_closed_bounded.2 ⟨A, B⟩,
have C : compact (f '' K) := this.image f_cont,
have : f '' K = closed_ball x₀ r,
by { rw image_preimage_eq_of_subset, rw hf, exact subset_univ _ },
rwa this at C
end
end bounded
section diam
variables {s : set α} {x y z : α}
/-- The diameter of a set in a metric space. To get controllable behavior even when the diameter
should be infinite, we express it in terms of the emetric.diameter -/
def diam (s : set α) : ℝ := ennreal.to_real (emetric.diam s)
/-- The diameter of a set is always nonnegative -/
lemma diam_nonneg : 0 ≤ diam s := ennreal.to_real_nonneg
lemma diam_subsingleton (hs : s.subsingleton) : diam s = 0 :=
by simp only [diam, emetric.diam_subsingleton hs, ennreal.zero_to_real]
/-- The empty set has zero diameter -/
@[simp] lemma diam_empty : diam (∅ : set α) = 0 :=
diam_subsingleton subsingleton_empty
/-- A singleton has zero diameter -/
@[simp] lemma diam_singleton : diam ({x} : set α) = 0 :=
diam_subsingleton subsingleton_singleton
-- Does not work as a simp-lemma, since {x, y} reduces to (insert y {x})
lemma diam_pair : diam ({x, y} : set α) = dist x y :=
by simp only [diam, emetric.diam_pair, dist_edist]
-- Does not work as a simp-lemma, since {x, y, z} reduces to (insert z (insert y {x}))
lemma diam_triple :
metric.diam ({x, y, z} : set α) = max (dist x y) (max (dist y z) (dist x z)) :=
begin
simp only [metric.diam, emetric.diam_triple, dist_edist],
rw [ennreal.to_real_max, ennreal.to_real_max];
apply_rules [ne_of_lt, edist_lt_top, max_lt]
end
/-- If the distance between any two points in a set is bounded by some constant `C`,
then `ennreal.of_real C` bounds the emetric diameter of this set. -/
lemma ediam_le_of_forall_dist_le {C : ℝ} (h : ∀ (x ∈ s) (y ∈ s), dist x y ≤ C) :
emetric.diam s ≤ ennreal.of_real C :=
emetric.diam_le_of_forall_edist_le $
λ x hx y hy, (edist_dist x y).symm ▸ ennreal.of_real_le_of_real (h x hx y hy)
/-- If the distance between any two points in a set is bounded by some non-negative constant,
this constant bounds the diameter. -/
lemma diam_le_of_forall_dist_le {C : ℝ} (h₀ : 0 ≤ C) (h : ∀ (x ∈ s) (y ∈ s), dist x y ≤ C) :
diam s ≤ C :=
ennreal.to_real_le_of_le_of_real h₀ (ediam_le_of_forall_dist_le h)
/-- If the distance between any two points in a nonempty set is bounded by some constant,
this constant bounds the diameter. -/
lemma diam_le_of_forall_dist_le_of_nonempty (hs : s.nonempty) {C : ℝ}
(h : ∀ (x ∈ s) (y ∈ s), dist x y ≤ C) : diam s ≤ C :=
have h₀ : 0 ≤ C, from let ⟨x, hx⟩ := hs in le_trans dist_nonneg (h x hx x hx),
diam_le_of_forall_dist_le h₀ h
/-- The distance between two points in a set is controlled by the diameter of the set. -/
lemma dist_le_diam_of_mem' (h : emetric.diam s ≠ ⊤) (hx : x ∈ s) (hy : y ∈ s) :
dist x y ≤ diam s :=
begin
rw [diam, dist_edist],
rw ennreal.to_real_le_to_real (edist_ne_top _ _) h,
exact emetric.edist_le_diam_of_mem hx hy
end
/-- Characterize the boundedness of a set in terms of the finiteness of its emetric.diameter. -/
lemma bounded_iff_ediam_ne_top : bounded s ↔ emetric.diam s ≠ ⊤ :=
iff.intro
(λ ⟨C, hC⟩, ne_top_of_le_ne_top ennreal.of_real_ne_top
(ediam_le_of_forall_dist_le $ λ x hx y hy, hC x y hx hy))
(λ h, ⟨diam s, λ x y hx hy, dist_le_diam_of_mem' h hx hy⟩)
lemma bounded.ediam_ne_top (h : bounded s) : emetric.diam s ≠ ⊤ :=
bounded_iff_ediam_ne_top.1 h
/-- The distance between two points in a set is controlled by the diameter of the set. -/
lemma dist_le_diam_of_mem (h : bounded s) (hx : x ∈ s) (hy : y ∈ s) : dist x y ≤ diam s :=
dist_le_diam_of_mem' h.ediam_ne_top hx hy
/-- An unbounded set has zero diameter. If you would prefer to get the value ∞, use `emetric.diam`.
This lemma makes it possible to avoid side conditions in some situations -/
lemma diam_eq_zero_of_unbounded (h : ¬(bounded s)) : diam s = 0 :=
begin
simp only [bounded_iff_ediam_ne_top, not_not, ne.def] at h,
simp [diam, h]
end
/-- If `s ⊆ t`, then the diameter of `s` is bounded by that of `t`, provided `t` is bounded. -/
lemma diam_mono {s t : set α} (h : s ⊆ t) (ht : bounded t) : diam s ≤ diam t :=
begin
unfold diam,
rw ennreal.to_real_le_to_real (bounded.subset h ht).ediam_ne_top ht.ediam_ne_top,
exact emetric.diam_mono h
end
/-- The diameter of a union is controlled by the sum of the diameters, and the distance between
any two points in each of the sets. This lemma is true without any side condition, since it is
obviously true if `s ∪ t` is unbounded. -/
lemma diam_union {t : set α} (xs : x ∈ s) (yt : y ∈ t) : diam (s ∪ t) ≤ diam s + dist x y + diam t :=
begin
classical, by_cases H : bounded (s ∪ t),
{ have hs : bounded s, from H.subset (subset_union_left _ _),
have ht : bounded t, from H.subset (subset_union_right _ _),
rw [bounded_iff_ediam_ne_top] at H hs ht,
rw [dist_edist, diam, diam, diam, ← ennreal.to_real_add, ← ennreal.to_real_add,
ennreal.to_real_le_to_real];
repeat { apply ennreal.add_ne_top.2; split }; try { assumption };
try { apply edist_ne_top },
exact emetric.diam_union xs yt },
{ rw [diam_eq_zero_of_unbounded H],
apply_rules [add_nonneg, diam_nonneg, dist_nonneg] }
end
/-- If two sets intersect, the diameter of the union is bounded by the sum of the diameters. -/
lemma diam_union' {t : set α} (h : (s ∩ t).nonempty) : diam (s ∪ t) ≤ diam s + diam t :=
begin
rcases h with ⟨x, ⟨xs, xt⟩⟩,
simpa using diam_union xs xt
end
/-- The diameter of a closed ball of radius `r` is at most `2 r`. -/
lemma diam_closed_ball {r : ℝ} (h : r ≥ 0) : diam (closed_ball x r) ≤ 2 * r :=
diam_le_of_forall_dist_le (mul_nonneg (le_of_lt two_pos) h) $ λa ha b hb, calc
dist a b ≤ dist a x + dist b x : dist_triangle_right _ _ _
... ≤ r + r : add_le_add ha hb
... = 2 * r : by simp [mul_two, mul_comm]
/-- The diameter of a ball of radius `r` is at most `2 r`. -/
lemma diam_ball {r : ℝ} (h : r ≥ 0) : diam (ball x r) ≤ 2 * r :=
le_trans (diam_mono ball_subset_closed_ball bounded_closed_ball) (diam_closed_ball h)
end diam
end metric
|
4bcda603680ee457851acac45180ce066c809e1b | d406927ab5617694ec9ea7001f101b7c9e3d9702 | /src/analysis/normed_space/matrix_exponential.lean | 423ad6dfbd9ea0c8bfce3fd1959f0d1535e40997 | [
"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 | 9,075 | lean | /-
Copyright (c) 2022 Eric Wieser. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Eric Wieser
-/
import analysis.normed_space.exponential
import analysis.matrix
import linear_algebra.matrix.zpow
import topology.uniform_space.matrix
/-!
# Lemmas about the matrix exponential
In this file, we provide results about `exp` on `matrix`s over a topological or normed algebra.
Note that generic results over all topological spaces such as `exp_zero` can be used on matrices
without issue, so are not repeated here. The topological results specific to matrices are:
* `matrix.exp_transpose`
* `matrix.exp_conj_transpose`
* `matrix.exp_diagonal`
* `matrix.exp_block_diagonal`
* `matrix.exp_block_diagonal'`
Lemmas like `exp_add_of_commute` require a canonical norm on the type; while there are multiple
sensible choices for the norm of a `matrix` (`matrix.normed_add_comm_group`,
`matrix.frobenius_normed_add_comm_group`, `matrix.linfty_op_normed_add_comm_group`), none of them
are canonical. In an application where a particular norm is chosen using
`local attribute [instance]`, then the usual lemmas about `exp` are fine. When choosing a norm is
undesirable, the results in this file can be used.
In this file, we copy across the lemmas about `exp`, but hide the requirement for a norm inside the
proof.
* `matrix.exp_add_of_commute`
* `matrix.exp_sum_of_commute`
* `matrix.exp_nsmul`
* `matrix.is_unit_exp`
* `matrix.exp_units_conj`
* `matrix.exp_units_conj'`
Additionally, we prove some results about `matrix.has_inv` and `matrix.div_inv_monoid`, as the
results for general rings are instead stated about `ring.inverse`:
* `matrix.exp_neg`
* `matrix.exp_zsmul`
* `matrix.exp_conj`
* `matrix.exp_conj'`
## Implementation notes
This file runs into some sharp edges on typeclass search in lean 3, especially regarding pi types.
To work around this, we copy a handful of instances for when lean can't find them by itself.
Hopefully we will be able to remove these in Lean 4.
## TODO
* Show that `matrix.det (exp 𝕂 A) = exp 𝕂 (matrix.trace A)`
## References
* https://en.wikipedia.org/wiki/Matrix_exponential
-/
open_locale matrix big_operators
section hacks_for_pi_instance_search
/-- A special case of `pi.topological_ring` for when `R` is not dependently typed. -/
instance function.topological_ring (I : Type*) (R : Type*)
[non_unital_ring R] [topological_space R] [topological_ring R] :
topological_ring (I → R) :=
pi.topological_ring
/-- A special case of `function.algebra` for when A is a `ring` not a `semiring` -/
instance function.algebra_ring (I : Type*) {R : Type*} (A : Type*) [comm_semiring R]
[ring A] [algebra R A] : algebra R (I → A) :=
pi.algebra _ _
/-- A special case of `pi.algebra` for when `f = λ i, matrix (m i) (m i) A`. -/
instance pi.matrix_algebra (I R A : Type*) (m : I → Type*)
[comm_semiring R] [semiring A] [algebra R A]
[Π i, fintype (m i)] [Π i, decidable_eq (m i)] :
algebra R (Π i, matrix (m i) (m i) A) :=
@pi.algebra I R (λ i, matrix (m i) (m i) A) _ _ (λ i, matrix.algebra)
/-- A special case of `pi.topological_ring` for when `f = λ i, matrix (m i) (m i) A`. -/
instance pi.matrix_topological_ring (I A : Type*) (m : I → Type*)
[ring A] [topological_space A] [topological_ring A]
[Π i, fintype (m i)] :
topological_ring (Π i, matrix (m i) (m i) A) :=
@pi.topological_ring _ (λ i, matrix (m i) (m i) A) _ _ (λ i, matrix.topological_ring)
end hacks_for_pi_instance_search
variables (𝕂 : Type*) {m n p : Type*} {n' : m → Type*} {𝔸 : Type*}
namespace matrix
section topological
section ring
variables [fintype m] [decidable_eq m] [fintype n] [decidable_eq n]
[Π i, fintype (n' i)] [Π i, decidable_eq (n' i)]
[field 𝕂] [ring 𝔸] [topological_space 𝔸] [topological_ring 𝔸] [algebra 𝕂 𝔸] [t2_space 𝔸]
lemma exp_diagonal (v : m → 𝔸) : exp 𝕂 (diagonal v) = diagonal (exp 𝕂 v) :=
by simp_rw [exp_eq_tsum, diagonal_pow, ←diagonal_smul, ←diagonal_tsum]
lemma exp_block_diagonal (v : m → matrix n n 𝔸) :
exp 𝕂 (block_diagonal v) = block_diagonal (exp 𝕂 v) :=
by simp_rw [exp_eq_tsum, ←block_diagonal_pow, ←block_diagonal_smul, ←block_diagonal_tsum]
lemma exp_block_diagonal' (v : Π i, matrix (n' i) (n' i) 𝔸) :
exp 𝕂 (block_diagonal' v) = block_diagonal' (exp 𝕂 v) :=
by simp_rw [exp_eq_tsum, ←block_diagonal'_pow, ←block_diagonal'_smul, ←block_diagonal'_tsum]
lemma exp_conj_transpose [star_ring 𝔸] [has_continuous_star 𝔸] (A : matrix m m 𝔸) :
exp 𝕂 Aᴴ = (exp 𝕂 A)ᴴ :=
(star_exp A).symm
end ring
section comm_ring
variables [fintype m] [decidable_eq m] [field 𝕂]
[comm_ring 𝔸] [topological_space 𝔸] [topological_ring 𝔸] [algebra 𝕂 𝔸] [t2_space 𝔸]
lemma exp_transpose (A : matrix m m 𝔸) : exp 𝕂 Aᵀ = (exp 𝕂 A)ᵀ :=
by simp_rw [exp_eq_tsum, transpose_tsum, transpose_smul, transpose_pow]
end comm_ring
end topological
section normed
variables [is_R_or_C 𝕂]
[fintype m] [decidable_eq m]
[fintype n] [decidable_eq n]
[Π i, fintype (n' i)] [Π i, decidable_eq (n' i)]
[normed_ring 𝔸] [normed_algebra 𝕂 𝔸] [complete_space 𝔸]
lemma exp_add_of_commute (A B : matrix m m 𝔸) (h : commute A B) :
exp 𝕂 (A + B) = exp 𝕂 A ⬝ exp 𝕂 B :=
begin
letI : semi_normed_ring (matrix m m 𝔸) := matrix.linfty_op_semi_normed_ring,
letI : normed_ring (matrix m m 𝔸) := matrix.linfty_op_normed_ring,
letI : normed_algebra 𝕂 (matrix m m 𝔸) := matrix.linfty_op_normed_algebra,
exact exp_add_of_commute h,
end
lemma exp_sum_of_commute {ι} (s : finset ι) (f : ι → matrix m m 𝔸)
(h : (s : set ι).pairwise $ λ i j, commute (f i) (f j)) :
exp 𝕂 (∑ i in s, f i) = s.noncomm_prod (λ i, exp 𝕂 (f i))
(λ i hi j hj _, (h.of_refl hi hj).exp 𝕂) :=
begin
letI : semi_normed_ring (matrix m m 𝔸) := matrix.linfty_op_semi_normed_ring,
letI : normed_ring (matrix m m 𝔸) := matrix.linfty_op_normed_ring,
letI : normed_algebra 𝕂 (matrix m m 𝔸) := matrix.linfty_op_normed_algebra,
exact exp_sum_of_commute s f h,
end
lemma exp_nsmul (n : ℕ) (A : matrix m m 𝔸) :
exp 𝕂 (n • A) = exp 𝕂 A ^ n :=
begin
letI : semi_normed_ring (matrix m m 𝔸) := matrix.linfty_op_semi_normed_ring,
letI : normed_ring (matrix m m 𝔸) := matrix.linfty_op_normed_ring,
letI : normed_algebra 𝕂 (matrix m m 𝔸) := matrix.linfty_op_normed_algebra,
exact exp_nsmul n A,
end
lemma is_unit_exp (A : matrix m m 𝔸) : is_unit (exp 𝕂 A) :=
begin
letI : semi_normed_ring (matrix m m 𝔸) := matrix.linfty_op_semi_normed_ring,
letI : normed_ring (matrix m m 𝔸) := matrix.linfty_op_normed_ring,
letI : normed_algebra 𝕂 (matrix m m 𝔸) := matrix.linfty_op_normed_algebra,
exact is_unit_exp _ A,
end
lemma exp_units_conj (U : (matrix m m 𝔸)ˣ) (A : matrix m m 𝔸) :
exp 𝕂 (↑U ⬝ A ⬝ ↑(U⁻¹) : matrix m m 𝔸) = ↑U ⬝ exp 𝕂 A ⬝ ↑(U⁻¹) :=
begin
letI : semi_normed_ring (matrix m m 𝔸) := matrix.linfty_op_semi_normed_ring,
letI : normed_ring (matrix m m 𝔸) := matrix.linfty_op_normed_ring,
letI : normed_algebra 𝕂 (matrix m m 𝔸) := matrix.linfty_op_normed_algebra,
exact exp_units_conj _ U A,
end
lemma exp_units_conj' (U : (matrix m m 𝔸)ˣ) (A : matrix m m 𝔸) :
exp 𝕂 (↑(U⁻¹) ⬝ A ⬝ U : matrix m m 𝔸) = ↑(U⁻¹) ⬝ exp 𝕂 A ⬝ U :=
exp_units_conj 𝕂 U⁻¹ A
end normed
section normed_comm
variables [is_R_or_C 𝕂]
[fintype m] [decidable_eq m]
[fintype n] [decidable_eq n]
[Π i, fintype (n' i)] [Π i, decidable_eq (n' i)]
[normed_comm_ring 𝔸] [normed_algebra 𝕂 𝔸] [complete_space 𝔸]
lemma exp_neg (A : matrix m m 𝔸) : exp 𝕂 (-A) = (exp 𝕂 A)⁻¹ :=
begin
rw nonsing_inv_eq_ring_inverse,
letI : semi_normed_ring (matrix m m 𝔸) := matrix.linfty_op_semi_normed_ring,
letI : normed_ring (matrix m m 𝔸) := matrix.linfty_op_normed_ring,
letI : normed_algebra 𝕂 (matrix m m 𝔸) := matrix.linfty_op_normed_algebra,
exact (ring.inverse_exp _ A).symm,
end
lemma exp_zsmul (z : ℤ) (A : matrix m m 𝔸) : exp 𝕂 (z • A) = exp 𝕂 A ^ z :=
begin
obtain ⟨n, rfl | rfl⟩ := z.eq_coe_or_neg,
{ rw [zpow_coe_nat, coe_nat_zsmul, exp_nsmul] },
{ have : is_unit (exp 𝕂 A).det := (matrix.is_unit_iff_is_unit_det _).mp (is_unit_exp _ _),
rw [matrix.zpow_neg this, zpow_coe_nat, neg_smul,
exp_neg, coe_nat_zsmul, exp_nsmul] },
end
lemma exp_conj (U : matrix m m 𝔸) (A : matrix m m 𝔸) (hy : is_unit U) :
exp 𝕂 (U ⬝ A ⬝ U⁻¹) = U ⬝ exp 𝕂 A ⬝ U⁻¹ :=
let ⟨u, hu⟩ := hy in hu ▸ by simpa only [matrix.coe_units_inv] using exp_units_conj 𝕂 u A
lemma exp_conj' (U : matrix m m 𝔸) (A : matrix m m 𝔸) (hy : is_unit U) :
exp 𝕂 (U⁻¹ ⬝ A ⬝ U) = U⁻¹ ⬝ exp 𝕂 A ⬝ U :=
let ⟨u, hu⟩ := hy in hu ▸ by simpa only [matrix.coe_units_inv] using exp_units_conj' 𝕂 u A
end normed_comm
end matrix
|
3c8ba143639fb0a7081a189388a882cd02fc5ca7 | 6432ea7a083ff6ba21ea17af9ee47b9c371760f7 | /tests/lean/run/borrowBug.lean | 36869cbd1a701d500bc7a462da99c8493f1a4c3a | [
"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 | 360 | lean |
@[noinline] def g (x : Nat) : Nat × Nat := (x, x)
@[noinline] def p (x : Nat) : Bool := x > 10
set_option trace.compiler.ir.rc true
def f (x : Nat) (y : Nat) : Bool :=
let jp (x : Nat) : Bool := -- x must be owned
p x || p (x+1)
match x with
| 0 => let z := g y; jp z.1
| _ => let z := g x; jp z.1
def h (x : Nat) : Bool := -- x must be borrowed
x > 5
|
f8f9f6b7cd757699b1230a755cbd8aa9b429a1ba | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/data/dlist/instances_auto.lean | 5694d428d9a573dcbbffa7ddee7e24ecc7c82461 | [] | 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 | 968 | lean | /-
Copyright (c) 2018 Simon Hudon. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Simon Hudon
Traversable instance for dlists.
-/
import Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
import Mathlib.Lean3Lib.data.dlist
import Mathlib.control.traversable.equiv
import Mathlib.control.traversable.instances
import Mathlib.PostPort
universes u_1
namespace Mathlib
namespace dlist
/-- The natural equivalence between lists and difference lists, using
`dlist.of_list` and `dlist.to_list`. -/
def list_equiv_dlist (α : Type u_1) : List α ≃ dlist α := equiv.mk of_list to_list sorry sorry
protected instance traversable : traversable dlist := equiv.traversable list_equiv_dlist
protected instance is_lawful_traversable : is_lawful_traversable dlist :=
equiv.is_lawful_traversable list_equiv_dlist
protected instance inhabited {α : Type u_1} : Inhabited (dlist α) := { default := empty }
end Mathlib |
61586bcb409724337559cc3ed72233ec8a3c209a | 55c7fc2bf55d496ace18cd6f3376e12bb14c8cc5 | /src/data/mv_polynomial.lean | 7e28f57724a38b7611e49c16e30cede6ceecc27c | [
"Apache-2.0"
] | permissive | dupuisf/mathlib | 62de4ec6544bf3b79086afd27b6529acfaf2c1bb | 8582b06b0a5d06c33ee07d0bdf7c646cae22cf36 | refs/heads/master | 1,669,494,854,016 | 1,595,692,409,000 | 1,595,692,409,000 | 272,046,630 | 0 | 0 | Apache-2.0 | 1,592,066,143,000 | 1,592,066,142,000 | null | UTF-8 | Lean | false | false | 59,755 | 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, Shing Tak Lam
-/
import data.polynomial.eval
import data.equiv.ring
import data.equiv.fin
import tactic.omega
/-!
# 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 ∈ σ]`. 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`
* `degrees p` : the multiset of variables representing the union of the multisets corresponding
to each non-zero monomial in `p`. For example if `7 ≠ 0` in `R` and `p = x²y+7y³` then
`degrees p = {x, x, y, y, y}`
* `vars p` : the finset of variables occurring in `p`. For example if `p = x⁴y+yz` then
`vars p = {x, y, z}`
* `degree_of n p : ℕ` -- the total degree of `p` with respect to the variable `n`. For example
if `p = x⁴y+yz` then `degree_of y p = 1`.
* `total_degree p : ℕ` -- the max of the sizes of the multisets `s` whose monomials `X^s` occur
in `p`. For example if `p = x⁴y+yz` then `total_degree p = 5`.
* `pderivative i p` : the partial derivative of `p` with respect to `i`.
## 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 σ α` is `(σ →₀ ℕ) →₀ α` ; here `σ →₀ ℕ` denotes the space of all
monomials in the variables, and the function to `α` sends a monomial to its coefficient in
the polynomial being represented.
## Tags
polynomial, multivariate polynomial, multivariable polynomial
-/
noncomputable theory
open_locale classical big_operators
open set function finsupp add_monoid_algebra
open_locale big_operators
universes u v w x
variables {α : Type u} {β : Type v} {γ : Type w} {δ : Type x}
/-- Multivariate polynomial, where `σ` is the index set of the variables and
`α` is the coefficient ring -/
def mv_polynomial (σ : Type*) (α : Type*) [comm_semiring α] := add_monoid_algebra α (σ →₀ ℕ)
namespace mv_polynomial
variables {σ : Type*} {a a' a₁ a₂ : α} {e : ℕ} {n m : σ} {s : σ →₀ ℕ}
section comm_semiring
variables [comm_semiring α] {p q : mv_polynomial σ α}
instance decidable_eq_mv_polynomial [decidable_eq σ] [decidable_eq α] :
decidable_eq (mv_polynomial σ α) := finsupp.decidable_eq
instance : comm_semiring (mv_polynomial σ α) := add_monoid_algebra.comm_semiring
instance : inhabited (mv_polynomial σ α) := ⟨0⟩
instance : has_scalar α (mv_polynomial σ α) := add_monoid_algebra.has_scalar
instance : semimodule α (mv_polynomial σ α) := add_monoid_algebra.semimodule
instance : algebra α (mv_polynomial σ α) := 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 σ α) :=
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 : α) : mv_polynomial σ α := single s a
/-- `C a` is the constant polynomial with value `a` -/
def C : α →+* mv_polynomial σ α :=
{ 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] }
/-- `X n` is the degree `1` monomial `1*n` -/
def X (n : σ) : mv_polynomial σ α := monomial (single n 1) 1
@[simp] lemma C_0 : C 0 = (0 : mv_polynomial σ α) := by simp [C, monomial]; refl
@[simp] lemma C_1 : C 1 = (1 : mv_polynomial σ α) := 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 σ α) = C a + C a' := single_add
@[simp] lemma C_mul : (C (a * a') : mv_polynomial σ α) = C a * C a' := C_mul_monomial.symm
@[simp] lemma C_pow (a : α) (n : ℕ) : (C (a^n) : mv_polynomial σ α) = (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 σ α) = n :=
by induction n; simp [nat.succ_eq_add_one, *]
lemma X_pow_eq_single : X n ^ e = monomial (single n e) (1 : α) :=
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 : α} {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 : α} :
monomial s a + monomial s b = monomial s (a + b) :=
by simp [monomial]
@[simp] lemma monomial_mul {s s' : σ →₀ ℕ} {a b : α} :
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 : α) = 0 :=
by rw [monomial, single_zero]; refl
@[simp] lemma sum_monomial {A : Type*} [add_comm_monoid A]
{u : σ →₀ ℕ} {r : α} {b : (σ →₀ ℕ) → α → 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 σ α) :=
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 σ α → Prop} (p : mv_polynomial σ α)
(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 σ α → Prop} (p : mv_polynomial σ α)
(h1 : ∀ (u : σ →₀ ℕ) (a : α), P (monomial u a))
(h2 : ∀ (p q : mv_polynomial σ α), 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 γ]
(f g : mv_polynomial σ α → γ) (hf : is_semiring_hom f) (hg : is_semiring_hom g)
(hC : ∀a:α, f (C a) = g (C a)) (hX : ∀n:σ, f (X n) = g (X n)) (p : mv_polynomial σ α) :
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 σ α → mv_polynomial σ α) (hf : is_semiring_hom f)
(hC : ∀a:α, f (C a) = (C a)) (hX : ∀n:σ, f (X n) = (X n)) (p : mv_polynomial σ α) :
f p = p :=
hom_eq_hom f id hf is_semiring_hom.id hC hX p
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 σ α) : α := p m
end
lemma ext (p q : mv_polynomial σ α) :
(∀ m, coeff m p = coeff m q) → p = q := ext
lemma ext_iff (p q : mv_polynomial σ α) :
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 σ α) :
coeff m (p + q) = coeff m p + coeff m q := add_apply
@[simp] lemma coeff_zero (m : σ →₀ ℕ) :
coeff m (0 : mv_polynomial σ α) = 0 := rfl
@[simp] lemma coeff_zero_X (i : σ) : coeff 0 (X i : mv_polynomial σ α) = 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 σ α → α) :=
{ map_add := coeff_add m,
map_zero := coeff_zero m }
lemma coeff_sum {X : Type*} (s : finset X) (f : X → mv_polynomial σ α) (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:α) = (m.prod $ λn e, X n ^ e : mv_polynomial σ α) :=
by simp [monomial_eq]
@[simp] lemma coeff_monomial (m n) (a) :
coeff m (monomial n a : mv_polynomial σ α) = if n = m then a else 0 :=
by convert single_apply
@[simp] lemma coeff_C (m) (a) :
coeff m (C a : mv_polynomial σ α) = 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 σ α) = if single i k = m then 1 else 0 :=
begin
have := coeff_monomial m (finsupp.single i k) (1:α),
rwa [@monomial_eq _ _ (1:α) (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 σ α) = 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 σ α) = 1 :=
by rw [coeff_X', if_pos rfl]
@[simp] lemma coeff_C_mul (m) (a : α) (p : mv_polynomial σ α) : 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],
exact sum_zero, -- TODO doesn't work if we put this inside the simp
end
lemma coeff_mul (p q : mv_polynomial σ α) (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 (σ →₀ ℕ) α _ _ 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 σ α) :
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 σ α) :
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' 1, ext 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
end coeff
section as_sum
@[simp]
lemma support_sum_monomial_coeff (p : mv_polynomial σ α) : ∑ v in p.support, monomial v (coeff v p) = p :=
finsupp.sum_single p
lemma as_sum (p : mv_polynomial σ α) : p = ∑ v in p.support, monomial v (coeff v p) :=
(support_sum_monomial_coeff p).symm
end as_sum
section eval₂
variables [comm_semiring β]
variables (f : α → β) (g : σ → β)
/-- 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 σ α) : β :=
p.sum (λs a, f a * s.prod (λn e, g n ^ e))
lemma eval₂_eq (g : α →+* β) (x : σ → β) (f : mv_polynomial σ α) :
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 : α →+* β) (x : σ → β) (f : mv_polynomial σ α) :
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 σ α).eval₂ f g = 0 :=
finsupp.sum_zero_index
section
variables [is_semiring_hom f]
@[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 σ α).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 σ α} : ∀{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 : α →+* β) (g : σ → β) : mv_polynomial σ α →+* β := ring_hom.of (eval₂ f g)
@[simp] lemma coe_eval₂_hom (f : α →+* β) (g : σ → β) : ⇑(eval₂_hom f g) = eval₂ f g := rfl
end
section
local attribute [instance, priority 10] is_semiring_hom.comp
lemma eval₂_comp_left {γ} [comm_semiring γ]
(k : β → γ) [is_semiring_hom k]
(f : α → β) [is_semiring_hom f] (g : σ → β)
(p) : k (eval₂ f g p) = eval₂ (k ∘ f) (k ∘ g) p :=
by apply mv_polynomial.induction_on p; simp [
eval₂_add, is_semiring_hom.map_add k,
eval₂_mul, is_semiring_hom.map_mul k] {contextual := tt}
end
@[simp] lemma eval₂_eta (p : mv_polynomial σ α) : eval₂ C X p = p :=
by apply mv_polynomial.induction_on p;
simp [eval₂_add, eval₂_mul] {contextual := tt}
lemma eval₂_congr (g₁ g₂ : σ → β)
(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
variables [is_semiring_hom f]
@[simp] lemma eval₂_prod (s : finset γ) (p : γ → mv_polynomial σ α) :
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 γ) (p : γ → mv_polynomial σ α) :
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 : γ → mv_polynomial σ α) (p : mv_polynomial γ α) :
eval₂ f (λ t, eval₂ f g (q t)) p = eval₂ f g (eval₂ C q p) :=
by { rw eval₂_comp_left (eval₂ f g), congr, funext, simp }
end eval₂
section eval
variables {f : σ → α}
/-- Evaluate a polynomial `p` given a valuation `f` of all the variables -/
def eval (f : σ → α) : mv_polynomial σ α → α := eval₂ id f
lemma eval_eq (x : σ → α) (f : mv_polynomial σ α) :
f.eval x = ∑ d in f.support, f.coeff d * ∏ i in d.support, x i ^ d i :=
rfl
lemma eval_eq' [fintype σ] (x : σ → α) (f : mv_polynomial σ α) :
f.eval x = ∑ d in f.support, f.coeff d * ∏ i, x i ^ d i :=
eval₂_eq' (ring_hom.id α) x f
@[simp] lemma eval_zero : (0 : mv_polynomial σ α).eval f = 0 := eval₂_zero _ _
@[simp] lemma eval_one : (1 : mv_polynomial σ α).eval f = 1 := eval₂_one _ _
@[simp] lemma eval_add : (p + q).eval f = p.eval f + q.eval f := eval₂_add _ _
lemma eval_monomial : (monomial s a).eval f = a * s.prod (λn e, f n ^ e) :=
eval₂_monomial _ _
@[simp] lemma eval_C : ∀ a, (C a).eval f = a := eval₂_C _ _
@[simp] lemma eval_X : ∀ n, (X n).eval f = f n := eval₂_X _ _
@[simp] lemma eval_mul : (p * q).eval f = p.eval f * q.eval f := eval₂_mul _ _
@[simp] lemma eval_pow (n : ℕ) : (p ^ n).eval f = (p.eval f) ^ n := eval₂_pow _ _
instance eval.is_semiring_hom : is_semiring_hom (eval f) :=
eval₂.is_semiring_hom _ _
lemma eval_sum {ι : Type*} (s : finset ι) (f : ι → mv_polynomial σ α) (g : σ → α) :
eval g (∑ i in s, f i) = ∑ i in s, eval g (f i) :=
eval₂_sum (ring_hom.id α) g s f
@[to_additive]
lemma eval_prod {ι : Type*} (s : finset ι) (f : ι → mv_polynomial σ α) (g : σ → α) :
eval g (∏ i in s, f i) = ∏ i in s, eval g (f i) :=
eval₂_prod (ring_hom.id α) g s f
theorem eval_assoc {τ}
(f : σ → mv_polynomial τ α) (g : τ → α)
(p : mv_polynomial σ α) :
p.eval (eval g ∘ f) = (eval₂ C f p).eval g :=
begin
rw eval₂_comp_left (eval g),
unfold eval, congr; funext a; simp
end
end eval
section map
variables [comm_semiring β]
variables (f : α → β)
/-- `map f p` maps a polynomial `p` across a ring hom `f` -/
def map : mv_polynomial σ α → mv_polynomial σ β := eval₂ (C ∘ f) X
variables [is_semiring_hom f]
instance is_semiring_hom_C_f :
is_semiring_hom ((C : β → mv_polynomial σ β) ∘ f) :=
is_semiring_hom.comp _ _
@[simp] theorem map_monomial (s : σ →₀ ℕ) (a : α) : map f (monomial s a) = monomial s (f a) :=
(eval₂_monomial _ _).trans monomial_eq.symm
@[simp] theorem map_C : ∀ (a : α), map f (C a : mv_polynomial σ α) = C (f a) := map_monomial _ _
@[simp] theorem map_X : ∀ (n : σ), map f (X n : mv_polynomial σ α) = X n := eval₂_X _ _
@[simp] theorem map_one : map f (1 : mv_polynomial σ α) = 1 := eval₂_one _ _
@[simp] theorem map_add (p q : mv_polynomial σ α) :
map f (p + q) = map f p + map f q := eval₂_add _ _
@[simp] theorem map_mul (p q : mv_polynomial σ α) :
map f (p * q) = map f p * map f q := eval₂_mul _ _
@[simp] lemma map_pow (p : mv_polynomial σ α) (n : ℕ) :
map f (p^n) = (map f p)^n := eval₂_pow _ _
instance map.is_semiring_hom :
is_semiring_hom (map f : mv_polynomial σ α → mv_polynomial σ β) :=
eval₂.is_semiring_hom _ _
theorem map_id : ∀ (p : mv_polynomial σ α), map id p = p := eval₂_eta
theorem map_map [comm_semiring γ]
(g : β → γ) [is_semiring_hom g]
(p : mv_polynomial σ α) :
map g (map f p) = map (g ∘ f) p :=
(eval₂_comp_left (map g) (C ∘ f) X p).trans $
by congr; funext a; simp
theorem eval₂_eq_eval_map (g : σ → β) (p : mv_polynomial σ α) :
p.eval₂ f g = (map f p).eval g :=
begin
unfold map eval,
rw eval₂_comp_left (eval₂ id g),
congr; funext a; simp
end
lemma eval₂_comp_right {γ} [comm_semiring γ]
(k : β → γ) [is_semiring_hom k]
(f : α → β) [is_semiring_hom f] (g : σ → β)
(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, is_semiring_hom.map_add k, map_add, eval₂_add, hp, hq] },
{ intros p s hp,
rw [eval₂_mul, is_semiring_hom.map_mul k, map_mul, eval₂_mul, map_X, hp, eval₂_X, eval₂_X] }
end
lemma map_eval₂ (f : α → β) [is_semiring_hom f] (g : γ → mv_polynomial δ α) (p : mv_polynomial γ α) :
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_add, hp, hq, map_add, eval₂_add] },
{ intros p s hp,
rw [eval₂_mul, map_mul, hp, map_mul, map_X, eval₂_mul, eval₂_X, eval₂_X] }
end
lemma coeff_map (p : mv_polynomial σ α) : ∀ (m : σ →₀ ℕ), coeff m (p.map f) = 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 is_semiring_hom.map_zero f },
{ intros p q hp hq m, simp only [hp, hq, map_add, coeff_add], rw is_semiring_hom.map_add f },
{ intros p i hp m, simp only [hp, 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 σ α → mv_polynomial σ β) :=
begin
intros p q h,
simp only [ext_iff, coeff_map] at h ⊢,
intro m,
exact hf (h m),
end
end map
section degrees
section comm_semiring
/--
The maximal degrees of each variable in a multi-variable polynomial, expressed as a multiset.
(For example, `degrees (x^2 * y + y^3)` would be `{x, x, y, y, y}`.)
-/
def degrees (p : mv_polynomial σ α) : multiset σ :=
p.support.sup (λs:σ →₀ ℕ, s.to_multiset)
lemma degrees_monomial (s : σ →₀ ℕ) (a : α) : degrees (monomial s a) ≤ s.to_multiset :=
finset.sup_le $ assume t h,
begin
have := finsupp.support_single_subset h,
rw [finset.mem_singleton] at this,
rw this
end
lemma degrees_monomial_eq (s : σ →₀ ℕ) (a : α) (ha : a ≠ 0) :
degrees (monomial s a) = s.to_multiset :=
le_antisymm (degrees_monomial s a) $ finset.le_sup $
by rw [monomial, finsupp.support_single_ne_zero ha, finset.mem_singleton]
lemma degrees_C (a : α) : degrees (C a : mv_polynomial σ α) = 0 :=
multiset.le_zero.1 $ degrees_monomial _ _
lemma degrees_X (n : σ) : degrees (X n : mv_polynomial σ α) ≤ {n} :=
le_trans (degrees_monomial _ _) $ le_of_eq $ to_multiset_single _ _
lemma degrees_zero : degrees (0 : mv_polynomial σ α) = 0 :=
by { rw ← C_0, exact degrees_C 0 }
lemma degrees_one : degrees (1 : mv_polynomial σ α) = 0 := degrees_C 1
lemma degrees_add (p q : mv_polynomial σ α) : (p + q).degrees ≤ p.degrees ⊔ q.degrees :=
begin
refine finset.sup_le (assume b hb, _),
have := finsupp.support_add hb, rw finset.mem_union at this,
cases this,
{ exact le_sup_left_of_le (finset.le_sup this) },
{ exact le_sup_right_of_le (finset.le_sup this) },
end
lemma degrees_sum {ι : Type*} (s : finset ι) (f : ι → mv_polynomial σ α) :
(∑ i in s, f i).degrees ≤ s.sup (λi, (f i).degrees) :=
begin
refine s.induction _ _,
{ simp only [finset.sum_empty, finset.sup_empty, degrees_zero], exact le_refl _ },
{ assume i s his ih,
rw [finset.sup_insert, finset.sum_insert his],
exact le_trans (degrees_add _ _) (sup_le_sup_left ih _) }
end
lemma degrees_mul (p q : mv_polynomial σ α) : (p * q).degrees ≤ p.degrees + q.degrees :=
begin
refine finset.sup_le (assume b hb, _),
have := support_mul p q hb,
simp only [finset.mem_bind, finset.mem_singleton] at this,
rcases this with ⟨a₁, h₁, a₂, h₂, rfl⟩,
rw [finsupp.to_multiset_add],
exact add_le_add (finset.le_sup h₁) (finset.le_sup h₂)
end
lemma degrees_prod {ι : Type*} (s : finset ι) (f : ι → mv_polynomial σ α) :
(∏ i in s, f i).degrees ≤ ∑ i in s, (f i).degrees :=
begin
refine s.induction _ _,
{ simp only [finset.prod_empty, finset.sum_empty, degrees_one] },
{ assume i s his ih,
rw [finset.prod_insert his, finset.sum_insert his],
exact le_trans (degrees_mul _ _) (add_le_add_left ih _) }
end
lemma degrees_pow (p : mv_polynomial σ α) :
∀(n : ℕ), (p^n).degrees ≤ n •ℕ p.degrees
| 0 := begin rw [pow_zero, degrees_one], exact multiset.zero_le _ end
| (n + 1) := le_trans (degrees_mul _ _) (add_le_add_left (degrees_pow n) _)
end comm_semiring
end degrees
section vars
/-- `vars p` is the set of variables appearing in the polynomial `p` -/
def vars (p : mv_polynomial σ α) : finset σ := p.degrees.to_finset
@[simp] lemma vars_0 : (0 : mv_polynomial σ α).vars = ∅ :=
by rw [vars, degrees_zero, multiset.to_finset_zero]
@[simp] lemma vars_monomial (h : a ≠ 0) : (monomial s a).vars = s.support :=
by rw [vars, degrees_monomial_eq _ _ h, finsupp.to_finset_to_multiset]
@[simp] lemma vars_C : (C a : mv_polynomial σ α).vars = ∅ :=
by rw [vars, degrees_C, multiset.to_finset_zero]
@[simp] lemma vars_X (h : 0 ≠ (1 : α)) : (X n : mv_polynomial σ α).vars = {n} :=
by rw [X, vars_monomial h.symm, finsupp.support_single_ne_zero (one_ne_zero : 1 ≠ 0)]
lemma mem_support_not_mem_vars_zero {f : mv_polynomial σ α} {x : σ →₀ ℕ} (H : x ∈ f.support) {v : σ} (h : v ∉ vars f) :
x v = 0 :=
begin
rw [vars, multiset.mem_to_finset] at h,
rw ←not_mem_support_iff,
contrapose! h,
unfold degrees,
rw (show f.support = insert x f.support, from eq.symm $ finset.insert_eq_of_mem H),
rw finset.sup_insert,
simp only [multiset.mem_union, multiset.sup_eq_union],
left,
rwa [←to_finset_to_multiset, multiset.mem_to_finset] at h,
end
end vars
section degree_of
/-- `degree_of n p` gives the highest power of X_n that appears in `p` -/
def degree_of (n : σ) (p : mv_polynomial σ α) : ℕ := p.degrees.count n
end degree_of
section total_degree
/-- `total_degree p` gives the maximum |s| over the monomials X^s in `p` -/
def total_degree (p : mv_polynomial σ α) : ℕ := p.support.sup (λs, s.sum $ λn e, e)
lemma total_degree_eq (p : mv_polynomial σ α) :
p.total_degree = p.support.sup (λm, m.to_multiset.card) :=
begin
rw [total_degree],
congr, funext m,
exact (finsupp.card_to_multiset _).symm
end
lemma total_degree_le_degrees_card (p : mv_polynomial σ α) :
p.total_degree ≤ p.degrees.card :=
begin
rw [total_degree_eq],
exact finset.sup_le (assume s hs, multiset.card_le_of_le $ finset.le_sup hs)
end
@[simp] lemma total_degree_C (a : α) : (C a : mv_polynomial σ α).total_degree = 0 :=
nat.eq_zero_of_le_zero $ finset.sup_le $ assume n hn,
have _ := finsupp.support_single_subset hn,
begin
rw [finset.mem_singleton] at this,
subst this,
exact le_refl _
end
@[simp] lemma total_degree_zero : (0 : mv_polynomial σ α).total_degree = 0 :=
by rw [← C_0]; exact total_degree_C (0 : α)
@[simp] lemma total_degree_one : (1 : mv_polynomial σ α).total_degree = 0 :=
total_degree_C (1 : α)
@[simp] lemma total_degree_X {α} [comm_semiring α] [nontrivial α] (s : σ) :
(X s : mv_polynomial σ α).total_degree = 1 :=
begin
rw [total_degree, X, monomial, finsupp.support_single_ne_zero (one_ne_zero : (1 : α) ≠ 0)],
simp only [finset.sup, sum_single_index, finset.fold_singleton, sup_bot_eq],
end
lemma total_degree_add (a b : mv_polynomial σ α) :
(a + b).total_degree ≤ max a.total_degree b.total_degree :=
finset.sup_le $ assume n hn,
have _ := finsupp.support_add hn,
begin
rw finset.mem_union at this,
cases this,
{ exact le_max_left_of_le (finset.le_sup this) },
{ exact le_max_right_of_le (finset.le_sup this) }
end
lemma total_degree_mul (a b : mv_polynomial σ α) :
(a * b).total_degree ≤ a.total_degree + b.total_degree :=
finset.sup_le $ assume n hn,
have _ := add_monoid_algebra.support_mul a b hn,
begin
simp only [finset.mem_bind, finset.mem_singleton] at this,
rcases this with ⟨a₁, h₁, a₂, h₂, rfl⟩,
rw [finsupp.sum_add_index],
{ exact add_le_add (finset.le_sup h₁) (finset.le_sup h₂) },
{ assume a, refl },
{ assume a b₁ b₂, refl }
end
lemma total_degree_pow (a : mv_polynomial σ α) (n : ℕ) :
(a ^ n).total_degree ≤ n * a.total_degree :=
begin
induction n with n ih,
{ simp only [nat.nat_zero_eq_zero, zero_mul, pow_zero, total_degree_one] },
rw pow_succ,
calc total_degree (a * a ^ n) ≤ a.total_degree + (a^n).total_degree : total_degree_mul _ _
... ≤ a.total_degree + n * a.total_degree : add_le_add_left ih _
... = (n+1) * a.total_degree : by rw [add_mul, one_mul, add_comm]
end
lemma total_degree_list_prod :
∀(s : list (mv_polynomial σ α)), s.prod.total_degree ≤ (s.map mv_polynomial.total_degree).sum
| [] := by rw [@list.prod_nil (mv_polynomial σ α) _, total_degree_one]; refl
| (p :: ps) :=
begin
rw [@list.prod_cons (mv_polynomial σ α) _, list.map, list.sum_cons],
exact le_trans (total_degree_mul _ _) (add_le_add_left (total_degree_list_prod ps) _)
end
lemma total_degree_multiset_prod (s : multiset (mv_polynomial σ α)) :
s.prod.total_degree ≤ (s.map mv_polynomial.total_degree).sum :=
begin
refine quotient.induction_on s (assume l, _),
rw [multiset.quot_mk_to_coe, multiset.coe_prod, multiset.coe_map, multiset.coe_sum],
exact total_degree_list_prod l
end
lemma total_degree_finset_prod {ι : Type*}
(s : finset ι) (f : ι → mv_polynomial σ α) :
(s.prod f).total_degree ≤ ∑ i in s, (f i).total_degree :=
begin
refine le_trans (total_degree_multiset_prod _) _,
rw [multiset.map_map],
refl
end
lemma exists_degree_lt [fintype σ] (f : mv_polynomial σ α) (n : ℕ)
(h : f.total_degree < n * fintype.card σ) {d : σ →₀ ℕ} (hd : d ∈ f.support) :
∃ i, d i < n :=
begin
contrapose! h,
calc n * fintype.card σ
= ∑ s:σ, n : by rw [finset.sum_const, nat.nsmul_eq_mul, mul_comm, finset.card_univ]
... ≤ ∑ s, d s : finset.sum_le_sum (λ s _, h s)
... ≤ d.sum (λ i e, e) : by { rw [finsupp.sum_fintype], intros, refl }
... ≤ f.total_degree : finset.le_sup hd,
end
end total_degree
section aeval
/-! ### The algebra of multivariate polynomials -/
variables {R : Type u} {A : Type v} (f : σ → A)
variables [comm_semiring R] [comm_semiring A] [algebra R A]
/-- A map `σ → A` where `A` is an algebra over `R` generates an `R`-algebra homomorphism
from multivariate polynomials over `σ` to `A`. -/
def aeval : mv_polynomial σ R →ₐ[R] A :=
{ commutes' := λ r, eval₂_C _ _ _
.. eval₂_hom (algebra_map R A) f }
theorem aeval_def (p : mv_polynomial σ R) : aeval f p = eval₂ (algebra_map R A) 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 A r := eval₂_C _ _ _
theorem eval_unique (φ : mv_polynomial σ R →ₐ[R] A) :
φ = 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
end aeval
end comm_semiring
section comm_ring
variable [comm_ring α]
variables {p q : mv_polynomial σ α}
instance : comm_ring (mv_polynomial σ α) := add_monoid_algebra.comm_ring
instance C.is_ring_hom : is_ring_hom (C : α → mv_polynomial σ α) :=
by apply is_ring_hom.of_semiring
variables (σ a a')
@[simp] lemma C_sub : (C (a - a') : mv_polynomial σ α) = C a - C a' := is_ring_hom.map_sub _
@[simp] lemma C_neg : (C (-a) : mv_polynomial σ α) = -C a := is_ring_hom.map_neg _
@[simp] lemma coeff_neg (m : σ →₀ ℕ) (p : mv_polynomial σ α) :
coeff m (-p) = -coeff m p := finsupp.neg_apply
@[simp] lemma coeff_sub (m : σ →₀ ℕ) (p q : mv_polynomial σ α) :
coeff m (p - q) = coeff m p - coeff m q := finsupp.sub_apply
instance coeff.is_add_group_hom (m : σ →₀ ℕ) :
is_add_group_hom (coeff m : mv_polynomial σ α → α) :=
{ map_add := coeff_add m }
variables {σ} (p)
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 α (mv_polynomial σ α) _ _ _ a).symm },
intros p b f haf hb0 ih,
rw [mul_add, ih, @smul_add α (mv_polynomial σ α) _ _ _ 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 σ α) (a : α) : a • p = C a * p :=
begin
rw [← finsupp.sum_single p, @finsupp.smul_sum (σ →₀ ℕ) α α, finsupp.mul_sum],
refine finset.sum_congr rfl (assume n _, _),
simp only [finsupp.smul_single],
exact C_mul_monomial.symm
end
@[simp] lemma smul_eval (x) (p : mv_polynomial σ α) (s) : (s • p).eval x = s * p.eval x :=
by rw [smul_eq_C_mul, eval_mul, eval_C]
section degrees
lemma degrees_neg (p : mv_polynomial σ α) : (- p).degrees = p.degrees :=
by rw [degrees, finsupp.support_neg]; refl
lemma degrees_sub (p q : mv_polynomial σ α) :
(p - q).degrees ≤ p.degrees ⊔ q.degrees :=
le_trans (degrees_add p (-q)) $ by rw [degrees_neg]
end degrees
section eval₂
variables [comm_ring β]
variables (f : α → β) [is_ring_hom f] (g : σ → β)
instance eval₂.is_ring_hom : is_ring_hom (eval₂ f g) :=
by apply is_ring_hom.of_semiring
@[simp] lemma eval₂_sub : (p - q).eval₂ f g = p.eval₂ f g - q.eval₂ f g := is_ring_hom.map_sub _
@[simp] lemma eval₂_neg : (-p).eval₂ f g = -(p.eval₂ f g) := is_ring_hom.map_neg _
lemma hom_C (f : mv_polynomial σ ℤ → β) [is_ring_hom f] (n : ℤ) : f (C n) = (n : β) :=
((ring_hom.of f).comp (ring_hom.of C)).eq_int_cast n
/-- A ring homomorphism f : Z[X_1, X_2, ...] → R
is determined by the evaluations f(X_1), f(X_2), ... -/
@[simp] lemma eval₂_hom_X {α : Type u} (c : ℤ → β) [is_ring_hom c]
(f : mv_polynomial α ℤ → β) [is_ring_hom f] (x : mv_polynomial α ℤ) :
eval₂ c (f ∘ X) x = f x :=
mv_polynomial.induction_on x
(λ n, by { rw [hom_C f, eval₂_C], exact (ring_hom.of c).eq_int_cast n })
(λ p q hp hq, by { rw [eval₂_add, hp, hq], exact (is_ring_hom.map_add f).symm })
(λ p n hp, by { rw [eval₂_mul, eval₂_X, hp], exact (is_ring_hom.map_mul f).symm })
/-- Ring homomorphisms out of integer polynomials on a type `σ` are the same as
functions out of the type `σ`, -/
def hom_equiv : (mv_polynomial σ ℤ →+* β) ≃ (σ → β) :=
{ to_fun := λ f, ⇑f ∘ X,
inv_fun := λ f, eval₂_hom (int.cast_ring_hom β) f,
left_inv := λ f, ring_hom.ext $ eval₂_hom_X _ _,
right_inv := λ f, funext $ λ x, by simp only [coe_eval₂_hom, function.comp_app, eval₂_X] }
end eval₂
section eval
variables (f : σ → α)
instance eval.is_ring_hom : is_ring_hom (eval f) := eval₂.is_ring_hom _ _
@[simp] lemma eval_sub : (p - q).eval f = p.eval f - q.eval f := is_ring_hom.map_sub _
@[simp] lemma eval_neg : (-p).eval f = -(p.eval f) := is_ring_hom.map_neg _
end eval
section map
variables [comm_ring β]
variables (f : α → β) [is_ring_hom f]
instance is_ring_hom_C_f : is_ring_hom ((C : β → mv_polynomial σ β) ∘ f) :=
is_ring_hom.comp _ _
instance map.is_ring_hom : is_ring_hom (map f : mv_polynomial σ α → mv_polynomial σ β) :=
eval₂.is_ring_hom _ _
@[simp] lemma map_sub : (p - q).map f = p.map f - q.map f := is_ring_hom.map_sub _
@[simp] lemma map_neg : (-p).map f = -(p.map f) := is_ring_hom.map_neg _
end map
section total_degree
@[simp] lemma total_degree_neg (a : mv_polynomial σ α) :
(-a).total_degree = a.total_degree :=
by simp only [total_degree, finsupp.support_neg]
lemma total_degree_sub (a b : mv_polynomial σ α) :
(a - b).total_degree ≤ max a.total_degree b.total_degree :=
calc (a - b).total_degree = (a + -b).total_degree : by rw sub_eq_add_neg
... ≤ max a.total_degree (-b).total_degree : total_degree_add a (-b)
... = max a.total_degree b.total_degree : by rw total_degree_neg
end total_degree
end comm_ring
section rename
variables {α} [comm_semiring α]
/-- Rename all the variables in a multivariable polynomial. -/
def rename (f : β → γ) : mv_polynomial β α → mv_polynomial γ α :=
eval₂ C (X ∘ f)
instance rename.is_semiring_hom (f : β → γ) :
is_semiring_hom (rename f : mv_polynomial β α → mv_polynomial γ α) :=
by unfold rename; apply_instance
@[simp] lemma rename_C (f : β → γ) (a : α) : rename f (C a) = C a :=
eval₂_C _ _ _
@[simp] lemma rename_X (f : β → γ) (b : β) : rename f (X b : mv_polynomial β α) = X (f b) :=
eval₂_X _ _ _
@[simp] lemma rename_zero (f : β → γ) :
rename f (0 : mv_polynomial β α) = 0 :=
eval₂_zero _ _
@[simp] lemma rename_one (f : β → γ) :
rename f (1 : mv_polynomial β α) = 1 :=
eval₂_one _ _
@[simp] lemma rename_add (f : β → γ) (p q : mv_polynomial β α) :
rename f (p + q) = rename f p + rename f q :=
eval₂_add _ _
@[simp] lemma rename_neg {α} [comm_ring α]
(f : β → γ) (p : mv_polynomial β α) :
rename f (-p) = -rename f p :=
eval₂_neg _ _ _
@[simp] lemma rename_sub {α} [comm_ring α]
(f : β → γ) (p q : mv_polynomial β α) :
rename f (p - q) = rename f p - rename f q :=
eval₂_sub _ _ _
@[simp] lemma rename_mul (f : β → γ) (p q : mv_polynomial β α) :
rename f (p * q) = rename f p * rename f q :=
eval₂_mul _ _
@[simp] lemma rename_pow (f : β → γ) (p : mv_polynomial β α) (n : ℕ) :
rename f (p^n) = (rename f p)^n :=
eval₂_pow _ _
lemma map_rename [comm_semiring β] (f : α → β) [is_semiring_hom f]
(g : γ → δ) (p : mv_polynomial γ α) :
map f (rename g p) = rename g (map f p) :=
mv_polynomial.induction_on p
(λ a, by simp)
(λ p q hp hq, by simp [hp, hq])
(λ p n hp, by simp [hp])
@[simp] lemma rename_rename (f : β → γ) (g : γ → δ) (p : mv_polynomial β α) :
rename g (rename f p) = rename (g ∘ f) p :=
show rename g (eval₂ C (X ∘ f) p) = _,
by simp only [eval₂_comp_left (rename g) C (X ∘ f) p, (∘), rename_C, rename_X]; refl
@[simp] lemma rename_id (p : mv_polynomial β α) : rename id p = p :=
eval₂_eta p
lemma rename_monomial (f : β → γ) (p : β →₀ ℕ) (a : α) :
rename f (monomial p a) = monomial (p.map_domain f) a :=
begin
rw [rename, eval₂_monomial, monomial_eq, finsupp.prod_map_domain_index],
{ exact assume n, pow_zero _ },
{ exact assume n i₁ i₂, pow_add _ _ _ }
end
lemma rename_eq (f : β → γ) (p : mv_polynomial β α) :
rename f p = finsupp.map_domain (finsupp.map_domain f) p :=
begin
simp only [rename, eval₂, finsupp.map_domain],
congr, ext s a : 2,
rw [← monomial, monomial_eq, finsupp.prod_sum_index],
congr, ext n i : 2,
rw [finsupp.prod_single_index],
exact pow_zero _,
exact assume a, pow_zero _,
exact assume a b c, pow_add _ _ _
end
lemma rename_injective (f : β → γ) (hf : function.injective f) :
function.injective (rename f : mv_polynomial β α → mv_polynomial γ α) :=
have (rename f : mv_polynomial β α → mv_polynomial γ α) =
finsupp.map_domain (finsupp.map_domain f) := funext (rename_eq f),
begin
rw this,
exact finsupp.map_domain_injective (finsupp.map_domain_injective hf)
end
lemma total_degree_rename_le (f : β → γ) (p : mv_polynomial β α) :
(p.rename f).total_degree ≤ p.total_degree :=
finset.sup_le $ assume b,
begin
assume h,
rw rename_eq at h,
have h' := finsupp.map_domain_support h,
rw finset.mem_image at h',
rcases h' with ⟨s, hs, rfl⟩,
rw finsupp.sum_map_domain_index,
exact le_trans (le_refl _) (finset.le_sup hs),
exact assume _, rfl,
exact assume _ _ _, rfl
end
section
variables [comm_semiring β] (f : α → β) [is_semiring_hom f]
variables (k : γ → δ) (g : δ → β) (p : mv_polynomial γ α)
lemma eval₂_rename : (p.rename k).eval₂ f g = p.eval₂ f (g ∘ k) :=
by apply mv_polynomial.induction_on p; { intros, simp [*] }
lemma rename_eval₂ (g : δ → mv_polynomial γ α) :
(p.eval₂ C (g ∘ k)).rename k = (p.rename k).eval₂ C (rename k ∘ g) :=
by apply mv_polynomial.induction_on p; { intros, simp [*] }
lemma rename_prodmk_eval₂ (d : δ) (g : γ → mv_polynomial γ α) :
(p.eval₂ C g).rename (prod.mk d) = p.eval₂ C (λ x, (g x).rename (prod.mk d)) :=
by apply mv_polynomial.induction_on p; { intros, simp [*] }
lemma eval₂_rename_prodmk (g : δ × γ → β) (d : δ) :
(rename (prod.mk d) p).eval₂ f g = eval₂ f (λ i, g (d, i)) p :=
by apply mv_polynomial.induction_on p; { intros, simp [*] }
lemma eval_rename_prodmk (g : δ × γ → α) (d : δ) :
(rename (prod.mk d) p).eval g = eval (λ i, g (d, i)) p :=
eval₂_rename_prodmk id _ _ _
end
/-- Every polynomial is a polynomial in finitely many variables. -/
theorem exists_finset_rename (p : mv_polynomial γ α) :
∃ (s : finset γ) (q : mv_polynomial {x // x ∈ s} α), p = q.rename coe :=
begin
apply induction_on p,
{ intro r, exact ⟨∅, C r, by rw rename_C⟩ },
{ rintro p q ⟨s, p, rfl⟩ ⟨t, q, rfl⟩,
refine ⟨s ∪ t, ⟨_, _⟩⟩,
{ exact rename (subtype.map id (finset.subset_union_left s t)) p +
rename (subtype.map id (finset.subset_union_right s t)) q },
{ rw [rename_add, rename_rename, rename_rename], refl } },
{ rintro p n ⟨s, p, rfl⟩,
refine ⟨insert n s, ⟨_, _⟩⟩,
{ exact rename (subtype.map id (finset.subset_insert n s)) p * X ⟨n, s.mem_insert_self n⟩ },
{ rw [rename_mul, rename_X, rename_rename], refl } }
end
/-- Every polynomial is a polynomial in finitely many variables. -/
theorem exists_fin_rename (p : mv_polynomial γ α) :
∃ (n : ℕ) (f : fin n → γ) (hf : injective f) (q : mv_polynomial (fin n) α), p = q.rename f :=
begin
obtain ⟨s, q, rfl⟩ := exists_finset_rename p,
obtain ⟨n, ⟨e⟩⟩ := fintype.exists_equiv_fin {x // x ∈ s},
refine ⟨n, coe ∘ e.symm, subtype.val_injective.comp e.symm.injective, q.rename e, _⟩,
rw [← rename_rename, rename_rename e],
simp only [function.comp, equiv.symm_apply_apply, rename_rename]
end
end rename
lemma eval₂_cast_comp {β : Type u} {γ : Type v} (f : γ → β)
{α : Type w} [comm_ring α] (c : ℤ → α) [is_ring_hom c] (g : β → α) (x : mv_polynomial γ ℤ) :
eval₂ c (g ∘ f) x = eval₂ c g (rename f x) :=
mv_polynomial.induction_on x
(λ n, by simp only [eval₂_C, rename_C])
(λ p q hp hq, by simp only [hp, hq, rename, eval₂_add])
(λ p n hp, by simp only [hp, rename, eval₂_X, eval₂_mul])
instance rename.is_ring_hom
{α} [comm_ring α] (f : β → γ) :
is_ring_hom (rename f : mv_polynomial β α → mv_polynomial γ α) :=
@is_ring_hom.of_semiring (mv_polynomial β α) (mv_polynomial γ α) _ _ (rename f)
(rename.is_semiring_hom f)
section equiv
variables (α) [comm_semiring α]
/-- The ring isomorphism between multivariable polynomials in no variables and the ground ring. -/
def pempty_ring_equiv : mv_polynomial pempty α ≃+* α :=
{ to_fun := mv_polynomial.eval₂ id $ pempty.elim,
inv_fun := C,
left_inv := is_id _ (by apply_instance) (assume a, by rw [eval₂_C]; refl) (assume a, a.elim),
right_inv := λ r, eval₂_C _ _ _,
map_mul' := λ _ _, eval₂_mul _ _,
map_add' := λ _ _, eval₂_add _ _ }
/--
The ring isomorphism between multivariable polynomials in a single variable and
polynomials over the ground ring.
-/
def punit_ring_equiv : mv_polynomial punit α ≃+* polynomial α :=
{ to_fun := eval₂ polynomial.C (λu:punit, polynomial.X),
inv_fun := polynomial.eval₂ mv_polynomial.C (X punit.star),
left_inv :=
begin
refine is_id _ _ _ _,
apply is_semiring_hom.comp (eval₂ polynomial.C (λu:punit, polynomial.X)) _; apply_instance,
{ assume a, rw [eval₂_C, polynomial.eval₂_C] },
{ rintros ⟨⟩, rw [eval₂_X, polynomial.eval₂_X] }
end,
right_inv := assume p, polynomial.induction_on p
(assume a, by rw [polynomial.eval₂_C, mv_polynomial.eval₂_C])
(assume p q hp hq, by rw [polynomial.eval₂_add, mv_polynomial.eval₂_add, hp, hq])
(assume p n hp,
by rw [polynomial.eval₂_mul, polynomial.eval₂_pow, polynomial.eval₂_X, polynomial.eval₂_C,
eval₂_mul, eval₂_C, eval₂_pow, eval₂_X]),
map_mul' := λ _ _, eval₂_mul _ _,
map_add' := λ _ _, eval₂_add _ _ }
/-- The ring isomorphism between multivariable polynomials induced by an equivalence of the variables. -/
def ring_equiv_of_equiv (e : β ≃ γ) : mv_polynomial β α ≃+* mv_polynomial γ α :=
{ to_fun := rename e,
inv_fun := rename e.symm,
left_inv := λ p, by simp only [rename_rename, (∘), e.symm_apply_apply]; exact rename_id p,
right_inv := λ p, by simp only [rename_rename, (∘), e.apply_symm_apply]; exact rename_id p,
map_mul' := rename_mul e,
map_add' := rename_add e }
/-- The ring isomorphism between multivariable polynomials induced by a ring isomorphism of the ground ring. -/
def ring_equiv_congr [comm_semiring γ] (e : α ≃+* γ) : mv_polynomial β α ≃+* mv_polynomial β γ :=
{ to_fun := map e,
inv_fun := map e.symm,
left_inv := assume p,
have (e.symm ∘ e) = id,
{ ext a, exact e.symm_apply_apply a },
by simp only [map_map, this, map_id],
right_inv := assume p,
have (e ∘ e.symm) = id,
{ ext a, exact e.apply_symm_apply a },
by simp only [map_map, this, map_id],
map_mul' := map_mul _,
map_add' := map_add _ }
section
variables (β γ δ)
/--
The function from multivariable polynomials in a sum of two types,
to multivariable polynomials in one of the types,
with coefficents in multivariable polynomials in the other type.
See `sum_ring_equiv` for the ring isomorphism.
-/
def sum_to_iter : mv_polynomial (β ⊕ γ) α → mv_polynomial β (mv_polynomial γ α) :=
eval₂ (C ∘ C) (λbc, sum.rec_on bc X (C ∘ X))
instance is_semiring_hom_C_C :
is_semiring_hom (C ∘ C : α → mv_polynomial β (mv_polynomial γ α)) :=
@is_semiring_hom.comp _ _ _ _ C _ _ _ C _
instance is_semiring_hom_sum_to_iter : is_semiring_hom (sum_to_iter α β γ) :=
eval₂.is_semiring_hom _ _
lemma sum_to_iter_C (a : α) : sum_to_iter α β γ (C a) = C (C a) :=
eval₂_C _ _ a
lemma sum_to_iter_Xl (b : β) : sum_to_iter α β γ (X (sum.inl b)) = X b :=
eval₂_X _ _ (sum.inl b)
lemma sum_to_iter_Xr (c : γ) : sum_to_iter α β γ (X (sum.inr c)) = C (X c) :=
eval₂_X _ _ (sum.inr c)
/--
The function from multivariable polynomials in one type,
with coefficents in multivariable polynomials in another type,
to multivariable polynomials in the sum of the two types.
See `sum_ring_equiv` for the ring isomorphism.
-/
def iter_to_sum : mv_polynomial β (mv_polynomial γ α) → mv_polynomial (β ⊕ γ) α :=
eval₂ (eval₂ C (X ∘ sum.inr)) (X ∘ sum.inl)
instance is_semiring_hom_iter_to_sum : is_semiring_hom (iter_to_sum α β γ) :=
eval₂.is_semiring_hom _ _
lemma iter_to_sum_C_C (a : α) : iter_to_sum α β γ (C (C a)) = C a :=
eq.trans (eval₂_C _ _ (C a)) (eval₂_C _ _ _)
lemma iter_to_sum_X (b : β) : iter_to_sum α β γ (X b) = X (sum.inl b) :=
eval₂_X _ _ _
lemma iter_to_sum_C_X (c : γ) : iter_to_sum α β γ (C (X c)) = X (sum.inr c) :=
eq.trans (eval₂_C _ _ (X c)) (eval₂_X _ _ _)
/-- A helper function for `sum_ring_equiv`. -/
def mv_polynomial_equiv_mv_polynomial [comm_semiring δ]
(f : mv_polynomial β α → mv_polynomial γ δ) (hf : is_semiring_hom f)
(g : mv_polynomial γ δ → mv_polynomial β α) (hg : is_semiring_hom g)
(hfgC : ∀a, f (g (C a)) = C a)
(hfgX : ∀n, f (g (X n)) = X n)
(hgfC : ∀a, g (f (C a)) = C a)
(hgfX : ∀n, g (f (X n)) = X n) :
mv_polynomial β α ≃+* mv_polynomial γ δ :=
{ to_fun := f, inv_fun := g,
left_inv := is_id _ (is_semiring_hom.comp _ _) hgfC hgfX,
right_inv := is_id _ (is_semiring_hom.comp _ _) hfgC hfgX,
map_mul' := hf.map_mul,
map_add' := hf.map_add }
/--
The ring isomorphism between multivariable polynomials in a sum of two types,
and multivariable polynomials in one of the types,
with coefficents in multivariable polynomials in the other type.
-/
def sum_ring_equiv : mv_polynomial (β ⊕ γ) α ≃+* mv_polynomial β (mv_polynomial γ α) :=
begin
apply @mv_polynomial_equiv_mv_polynomial α (β ⊕ γ) _ _ _ _
(sum_to_iter α β γ) _ (iter_to_sum α β γ) _,
{ assume p,
apply hom_eq_hom _ _ _ _ _ _ p,
apply_instance,
{ apply @is_semiring_hom.comp _ _ _ _ _ _ _ _ _ _,
apply_instance,
apply @is_semiring_hom.comp _ _ _ _ _ _ _ _ _ _,
apply_instance,
{ apply_instance, },
{ apply mv_polynomial.is_semiring_hom_iter_to_sum α β γ },
{ apply mv_polynomial.is_semiring_hom_sum_to_iter α β γ } },
{ apply_instance, },
{ assume a, rw [iter_to_sum_C_C α β γ, sum_to_iter_C α β γ] },
{ assume c, rw [iter_to_sum_C_X α β γ, sum_to_iter_Xr α β γ] } },
{ assume b, rw [iter_to_sum_X α β γ, sum_to_iter_Xl α β γ] },
{ assume a, rw [sum_to_iter_C α β γ, iter_to_sum_C_C α β γ] },
{ assume n, cases n with b c,
{ rw [sum_to_iter_Xl, iter_to_sum_X] },
{ rw [sum_to_iter_Xr, iter_to_sum_C_X] } },
{ apply mv_polynomial.is_semiring_hom_sum_to_iter α β γ },
{ apply mv_polynomial.is_semiring_hom_iter_to_sum α β γ }
end
/--
The ring isomorphism between multivariable polynomials in `option β` and
polynomials with coefficients in `mv_polynomial β α`.
-/
def option_equiv_left : mv_polynomial (option β) α ≃+* polynomial (mv_polynomial β α) :=
(ring_equiv_of_equiv α $ (equiv.option_equiv_sum_punit β).trans (equiv.sum_comm _ _)).trans $
(sum_ring_equiv α _ _).trans $
punit_ring_equiv _
/--
The ring isomorphism between multivariable polynomials in `option β` and
multivariable polynomials with coefficients in polynomials.
-/
def option_equiv_right : mv_polynomial (option β) α ≃+* mv_polynomial β (polynomial α) :=
(ring_equiv_of_equiv α $ equiv.option_equiv_sum_punit.{0} β).trans $
(sum_ring_equiv α β unit).trans $
ring_equiv_congr (mv_polynomial unit α) (punit_ring_equiv α)
/--
The ring isomorphism between multivariable polynomials in `fin (n + 1)` and
polynomials over multivariable polynomials in `fin n`.
-/
def fin_succ_equiv (n : ℕ) :
mv_polynomial (fin (n + 1)) α ≃+* polynomial (mv_polynomial (fin n) α) :=
(ring_equiv_of_equiv α (fin_succ_equiv n)).trans
(option_equiv_left α (fin n))
end
end equiv
/-!
## Partial derivatives
-/
section pderivative
variables {R : Type} [comm_ring R]
variable {S : Type}
/-- `pderivative v p` is the partial derivative of `p` with respect to `v` -/
def pderivative (v : S) (p : mv_polynomial S R) : mv_polynomial S R :=
p.sum (λ A B, monomial (A - single v 1) (B * (A v)))
@[simp]
lemma pderivative_add {v : S} {f g : mv_polynomial S R} :
pderivative v (f + g) = pderivative v f + pderivative v g :=
begin
refine sum_add_index _ _,
{ simp },
simp [add_mul],
end
@[simp]
lemma pderivative_monomial {v : S} {u : S →₀ ℕ} {a : R} :
pderivative v (monomial u a) = monomial (u - single v 1) (a * (u v)) :=
by simp [pderivative]
@[simp]
lemma pderivative_C {v : S} {a : R} : pderivative v (C a) = 0 :=
suffices pderivative v (monomial 0 a) = 0, by simpa,
by simp
@[simp]
lemma pderivative_zero {v : S} : pderivative v (0 : mv_polynomial S R) = 0 :=
suffices pderivative v (C 0 : mv_polynomial S R) = 0, by simpa,
show pderivative v (C 0 : mv_polynomial S R) = 0, from pderivative_C
section
variables (R)
/-- `pderivative : S → mv_polynomial S R → mv_polynomial S R` as an `add_monoid_hom` -/
def pderivative.add_monoid_hom (v : S) : mv_polynomial S R →+ mv_polynomial S R :=
{ to_fun := pderivative v,
map_zero' := pderivative_zero,
map_add' := λ x y, pderivative_add, }
@[simp]
lemma pderivative.add_monoid_hom_apply (v : S) (p : mv_polynomial S R) :
(pderivative.add_monoid_hom R v) p = pderivative v p :=
rfl
end
lemma pderivative_eq_zero_of_not_mem_vars {v : S} {f : mv_polynomial S R} (h : v ∉ f.vars) :
pderivative v f = 0 :=
begin
change (pderivative.add_monoid_hom R v) f = 0,
rw [f.as_sum, add_monoid_hom.map_sum],
apply finset.sum_eq_zero,
intros,
simp [mem_support_not_mem_vars_zero H h],
end
lemma pderivative_monomial_single {a : R} {v : S} {n : ℕ} :
pderivative v (monomial (single v n) a) = monomial (single v (n-1)) (a * n) :=
by simp
private lemma monomial_sub_single_one_add {v : S} {u u' : S →₀ ℕ} {r r' : R} :
monomial (u - single v 1 + u') (r * (u v) * r') =
monomial (u + u' - single v 1) (r * (u v) * r') :=
by by_cases h : u v = 0; simp [h, sub_single_one_add]
private lemma monomial_add_sub_single_one {v : S} {u u' : S →₀ ℕ} {r r' : R} :
monomial (u + (u' - single v 1)) (r * (r' * (u' v))) =
monomial (u + u' - single v 1) (r * (r' * (u' v))) :=
by by_cases h : u' v = 0; simp [h, add_sub_single_one]
lemma pderivative_monomial_mul {v : S} {u u' : S →₀ ℕ} {r r' : R} :
pderivative v (monomial u r * monomial u' r') =
pderivative v (monomial u r) * monomial u' r' + monomial u r * pderivative v (monomial u' r') :=
begin
simp [monomial_sub_single_one_add, monomial_add_sub_single_one],
congr,
ring,
end
@[simp]
lemma pderivative_mul {v : S} {f g : mv_polynomial S R} :
pderivative v (f * g) = pderivative v f * g + f * pderivative v g :=
begin
apply induction_on' f,
{ apply induction_on' g,
{ intros u r u' r', exact pderivative_monomial_mul },
{ intros p q hp hq u r,
rw [mul_add, pderivative_add, hp, hq, mul_add, pderivative_add],
ring } },
{ intros p q hp hq,
simp [add_mul, hp, hq],
ring, }
end
@[simp]
lemma pderivative_C_mul {a : R} {f : mv_polynomial S R} {v : S} :
pderivative v (C a * f) = C a * pderivative v f :=
by rw [pderivative_mul, pderivative_C, zero_mul, zero_add]
end pderivative
end mv_polynomial
|
f28e3192cd68b683579d56f8425b8a298243d186 | 2b0e277371df7056b343785ee43e0917e5844dac | /src/risk_measures.lean | 7752864a43be449f52c647984f5dd54dab05af40 | [] | no_license | kodyvajjha/lean-crm | f3795ddff12bbc04dc08f6b6e4708698929c1af1 | f6cbb0061e4521632d26a1ab23fbdfe231e4c18a | refs/heads/master | 1,587,882,457,792 | 1,553,563,945,000 | 1,553,563,945,000 | 173,365,069 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 2,074 | lean | import .random_variable
import measure_theory.measure_space
import measure_theory.integration
import tactic.find
open lattice measure_theory ennreal set
universe u
local attribute [instance] classical.prop_decidable
noncomputable theory
variables {s α : Type u} [probability_space s] (p : probability_measure s) {X : s → ℝ} (hX : measurable X)
/-- Value-at-Risk at level a-/
def VaR {a : nnreal} (hX : measurable X) (ha : a ∈ Ioo (0:nnreal) (1:nnreal)) : ℝ := Inf { x : ℝ | distribution_function p hX x ≥ a }
def Icc_ind (p : ennreal) : ennreal → ennreal :=
λ h : ennreal, if h ∈ (set.Icc p (1:ennreal)) then (1* (1/1-p):ennreal) else (0:ennreal)
/-- Expected Shortfall at level a-/
def ES {a : nnreal} (X : s → ℝ) (hX : measurable X) (ha : a ∈ Ioo (0:nnreal) (1:nnreal))
: ennreal :=
measure.integral (@measure_theory.measure_space.μ ℝ _) (λ h, ennreal.of_real(VaR p hX ha) * Icc_ind a (ennreal.of_real h) )
-- def distribution_function {X : s → ℝ} (hX : measurable X) :=
-- (λ x:ℝ, prob p({ω : s | X(ω) ≤ x}))
-- def unif_df (F : prob_distribution s p) := F.cdf = λ x : ℝ, if (x < 0) then (0:nnreal) else (if (x < 1) then nnreal.of_real x else 0)
/-- Uniformly distributed random variable -/
structure uniform_distribution (s : Type*) [probability_space s](p : probability_measure s) :=
(X : s → ℝ)
(is_rv : measurable X)
(ucdf : distribution_function p is_rv = λ x : ℝ, if (x < 0) then (0:nnreal) else (if (x < 1) then nnreal.of_real x else 0))
def expectation : ennreal := measure.integral (@probability_measure.to_measure s _ p) (λ (ω :s), ennreal.of_real (X ω))
def ess_sup (X : s → ℝ) : ennreal :=
if {a : ennreal | prob p ({x | X x > ennreal.to_real a})= 0} ≠ ∅ then Inf {a : ennreal | prob p ({x | X x > ennreal.to_real a})= 0} else ⊤
def ess_inf (X : s → ℝ) : ennreal :=
if { b : ennreal | prob p ({x | X x < ennreal.to_real b})= 0} ≠ ∅ then Sup { b : ennreal | prob p ({x | X x < ennreal.to_real b})= 0} else ⊥
-- structure coherent_risk_measure :=
-- (to_fun : ) |
8702eda902b504c5430c1aae7f6fde2b8d933115 | 57aec6ee746bc7e3a3dd5e767e53bd95beb82f6d | /stage0/src/Lean/Meta/PPGoal.lean | 4b22f4c6a2c6de92e6c32531098500b2a1ef5c96 | [
"Apache-2.0"
] | permissive | collares/lean4 | 861a9269c4592bce49b71059e232ff0bfe4594cc | 52a4f535d853a2c7c7eea5fee8a4fa04c682c1ee | refs/heads/master | 1,691,419,031,324 | 1,618,678,138,000 | 1,618,678,138,000 | 358,989,750 | 0 | 0 | Apache-2.0 | 1,618,696,333,000 | 1,618,696,333,000 | null | UTF-8 | Lean | false | false | 9,165 | lean | /-
Copyright (c) 2020 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Leonardo de Moura
-/
import Lean.Hygiene
import Lean.Meta.InferType
namespace Lean.Meta
register_builtin_option pp.auxDecls : Bool := {
defValue := false
group := "pp"
descr := "display auxiliary declarations used to compile recursive functions"
}
register_builtin_option pp.inaccessibleNames : Bool := {
defValue := false
group := "pp"
descr := "display inaccessible declarations in the local context"
}
def withPPInaccessibleNames (x : MetaM α) (flag := true) : MetaM α :=
withTheReader Core.Context (fun ctx => { ctx with options := pp.inaccessibleNames.setIfNotSet ctx.options flag }) x
namespace ToHide
structure State where
hiddenInaccessibleProp : NameSet := {} -- FVarIds of Propostions with inaccessible names but containing only visible names. We show only their types
hiddenInaccessible : NameSet := {} -- FVarIds with inaccessible names, but not in hiddenInaccessibleProp
modified : Bool := false
structure Context where
goalTarget : Expr
abbrev M := ReaderT Context $ StateRefT State MetaM
/- Return true if `fvarId` is marked as an hidden inaccessible or inaccessible proposition -/
def isMarked (fvarId : FVarId) : M Bool := do
let s ← get
return s.hiddenInaccessible.contains fvarId || s.hiddenInaccessibleProp.contains fvarId
/- If `fvarId` isMarked, then unmark it. -/
def unmark (fvarId : FVarId) : M Unit := do
modify fun s => {
hiddenInaccessible := s.hiddenInaccessible.erase fvarId
hiddenInaccessibleProp := s.hiddenInaccessibleProp.erase fvarId
modified := true
}
def moveToHiddeProp (fvarId : FVarId) : M Unit := do
modify fun s => {
hiddenInaccessible := s.hiddenInaccessible.erase fvarId
hiddenInaccessibleProp := s.hiddenInaccessibleProp.insert fvarId
modified := true
}
/- Return true if the given local declaration has a "visible dependency", that is, it contains
a free variable that is `hiddenInaccessible`
Recall that hiddenInaccessibleProps are visible, only their names are hidden -/
def hasVisibleDep (localDecl : LocalDecl) : M Bool := do
let s ← get
return (← getMCtx).findLocalDeclDependsOn localDecl fun fvarId =>
!s.hiddenInaccessible.contains fvarId
/- Return true if the given local declaration has a "nonvisible dependency", that is, it contains
a free variable that is `hiddenInaccessible` or `hiddenInaccessibleProp` -/
def hasInaccessibleNameDep (localDecl : LocalDecl) : M Bool := do
let s ← get
return (← getMCtx).findLocalDeclDependsOn localDecl fun fvarId =>
s.hiddenInaccessible.contains fvarId || s.hiddenInaccessibleProp.contains fvarId
/- If `e` is visible, then any inaccessible in `e` marked as hidden should be unmarked. -/
partial def visitVisibleExpr (e : Expr) : M Unit := do
visit (← instantiateMVars e) |>.run
where
visit (e : Expr) : MonadCacheT Expr Unit M Unit := do
if e.hasFVar then
checkCache e fun _ => do
match e with
| Expr.forallE _ d b _ => visit d; visit b
| Expr.lam _ d b _ => visit d; visit b
| Expr.letE _ t v b _ => visit t; visit v; visit b
| Expr.app f a _ => visit f; visit a
| Expr.mdata _ b _ => visit b
| Expr.proj _ _ b _ => visit b
| Expr.fvar fvarId _ => if (← isMarked fvarId) then unmark fvarId
| _ => pure ()
def fixpointStep : M Unit := do
visitVisibleExpr (← read).goalTarget -- The goal target is a visible forward dependency
(← getLCtx).forM fun localDecl => do
let fvarId := localDecl.fvarId
if (← get).hiddenInaccessible.contains fvarId then
if (← hasVisibleDep localDecl) then
/- localDecl is marked to be hidden, but it has a (backward) visible dependency. -/
unmark fvarId
if (← isProp localDecl.type) then
unless (← hasInaccessibleNameDep localDecl) do
moveToHiddeProp fvarId
else
visitVisibleExpr localDecl.type
match localDecl.value? with
| some value => visitVisibleExpr value
| _ => pure ()
partial def fixpoint : M Unit := do
modify fun s => { s with modified := false }
fixpointStep
if (← get).modified then
fixpoint
/-
If pp.inaccessibleNames == false, then collect two sets of `FVarId`s : `hiddenInaccessible` and `hiddenInaccessibleProp`
1- `hiddenInaccessible` contains `FVarId`s of free variables with inaccessible names that
a) are not propositions or are propositions containing "visible" names.
2- `hiddenInaccessibleProp` contains `FVarId`s of free variables with inaccessible names that are propositions
containing "visible" names.
Both sets do not contain `FVarId`s that contain visible backward or forward dependencies.
The `goalTarget` counts as a forward dependency.
We say a name is visible if it is a free variable with FVarId not in `hiddenInaccessible` nor `hiddenInaccessibleProp`
-/
def collect (goalTarget : Expr) : MetaM (NameSet × NameSet) := do
if pp.inaccessibleNames.get (← getOptions) then
/- Don't hide inaccessible names when `pp.inaccessibleNames` is set to true. -/
return ({}, {})
else
let lctx ← getLCtx
let hiddenInaccessible := lctx.foldl (init := {}) fun hiddenInaccessible localDecl => do
if isInaccessibleUserName localDecl.userName then
hiddenInaccessible.insert localDecl.fvarId
else
hiddenInaccessible
let (_, s) ← fixpoint.run { goalTarget := goalTarget } |>.run { hiddenInaccessible := hiddenInaccessible }
return (s.hiddenInaccessible, s.hiddenInaccessibleProp)
end ToHide
private def addLine (fmt : Format) : Format :=
if fmt.isNil then fmt else fmt ++ Format.line
def ppGoal (mvarId : MVarId) : MetaM Format := do
match (← getMCtx).findDecl? mvarId with
| none => pure "unknown goal"
| some mvarDecl => do
let indent := 2 -- Use option
let ppAuxDecls := pp.auxDecls.get (← getOptions)
let lctx := mvarDecl.lctx
let lctx := lctx.sanitizeNames.run' { options := (← getOptions) }
withLCtx lctx mvarDecl.localInstances do
let (hidden, hiddenProp) ← ToHide.collect mvarDecl.type
-- The followint two `let rec`s are being used to control the generated code size.
-- Then should be remove after we rewrite the compiler in Lean
let rec pushPending (ids : List Name) (type? : Option Expr) (fmt : Format) : MetaM Format :=
if ids.isEmpty then
pure fmt
else
let fmt := addLine fmt
match ids, type? with
| [], _ => pure fmt
| _, none => pure fmt
| _, some type => do
let typeFmt ← ppExpr type
pure $ fmt ++ (Format.joinSep ids.reverse " " ++ " :" ++ Format.nest indent (Format.line ++ typeFmt)).group
let rec ppVars (varNames : List Name) (prevType? : Option Expr) (fmt : Format) (localDecl : LocalDecl) : MetaM (List Name × Option Expr × Format) := do
if hiddenProp.contains localDecl.fvarId then
let fmt ← pushPending varNames prevType? fmt
let fmt := addLine fmt
let type ← instantiateMVars localDecl.type
let typeFmt ← ppExpr type
let fmt := fmt ++ " : " ++ typeFmt
pure ([], none, fmt)
else
match localDecl with
| LocalDecl.cdecl _ _ varName type _ =>
let varName := varName.simpMacroScopes
let type ← instantiateMVars type
if prevType? == none || prevType? == some type then
pure (varName :: varNames, some type, fmt)
else do
let fmt ← pushPending varNames prevType? fmt
pure ([varName], some type, fmt)
| LocalDecl.ldecl _ _ varName type val _ => do
let varName := varName.simpMacroScopes
let fmt ← pushPending varNames prevType? fmt
let fmt := addLine fmt
let type ← instantiateMVars type
let val ← instantiateMVars val
let typeFmt ← ppExpr type
let valFmt ← ppExpr val
let fmt := fmt ++ (format varName ++ " : " ++ typeFmt ++ " :=" ++ Format.nest indent (Format.line ++ valFmt)).group
pure ([], none, fmt)
let (varNames, type?, fmt) ← lctx.foldlM (init := ([], none, Format.nil)) fun (varNames, prevType?, fmt) (localDecl : LocalDecl) =>
if !ppAuxDecls && localDecl.isAuxDecl || hidden.contains localDecl.fvarId then
pure (varNames, prevType?, fmt)
else
ppVars varNames prevType? fmt localDecl
let fmt ← pushPending varNames type? fmt
let fmt := addLine fmt
let typeFmt ← ppExpr mvarDecl.type
let fmt := fmt ++ "⊢" ++ " " ++ Format.nest indent typeFmt
match mvarDecl.userName with
| Name.anonymous => pure fmt
| name => return "case " ++ format name.eraseMacroScopes ++ Format.line ++ fmt
end Lean.Meta
|
53109eebb4ec93380135f310db083b0969322d92 | 94e33a31faa76775069b071adea97e86e218a8ee | /src/ring_theory/witt_vector/truncated.lean | 4aa9b539e664aacba9e8e529973adda2c8055c9f | [
"Apache-2.0"
] | permissive | urkud/mathlib | eab80095e1b9f1513bfb7f25b4fa82fa4fd02989 | 6379d39e6b5b279df9715f8011369a301b634e41 | refs/heads/master | 1,658,425,342,662 | 1,658,078,703,000 | 1,658,078,703,000 | 186,910,338 | 0 | 0 | Apache-2.0 | 1,568,512,083,000 | 1,557,958,709,000 | Lean | UTF-8 | Lean | false | false | 15,692 | 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 ring_theory.witt_vector.init_tail
/-!
# Truncated Witt vectors
The ring of truncated Witt vectors (of length `n`) is a quotient of the ring of Witt vectors.
It retains the first `n` coefficients of each Witt vector.
In this file, we set up the basic quotient API for this ring.
The ring of Witt vectors is the projective limit of all the rings of truncated Witt vectors.
## Main declarations
- `truncated_witt_vector`: the underlying type of the ring of truncated Witt vectors
- `truncated_witt_vector.comm_ring`: the ring structure on truncated Witt vectors
- `witt_vector.truncate`: the quotient homomorphism that truncates a Witt vector,
to obtain a truncated Witt vector
- `truncated_witt_vector.truncate`: the homomorphism that truncates
a truncated Witt vector of length `n` to one of length `m` (for some `m ≤ n`)
- `witt_vector.lift`: the unique ring homomorphism into the ring of Witt vectors
that is compatible with a family of ring homomorphisms to the truncated Witt vectors:
this realizes the ring of Witt vectors as projective limit of the rings of truncated Witt vectors
## References
* [Hazewinkel, *Witt Vectors*][Haze09]
* [Commelin and Lewis, *Formalizing the Ring of Witt Vectors*][CL21]
-/
open function (injective surjective)
noncomputable theory
variables {p : ℕ} [hp : fact p.prime] (n : ℕ) (R : Type*)
local notation `𝕎` := witt_vector p -- type as `\bbW`
/--
A truncated Witt vector over `R` is a vector of elements of `R`,
i.e., the first `n` coefficients of a Witt vector.
We will define operations on this type that are compatible with the (untruncated) Witt
vector operations.
`truncated_witt_vector p n R` takes a parameter `p : ℕ` that is not used in the definition.
In practice, this number `p` is assumed to be a prime number,
and under this assumption we construct a ring structure on `truncated_witt_vector p n R`.
(`truncated_witt_vector p₁ n R` and `truncated_witt_vector p₂ n R` are definitionally
equal as types but will have different ring operations.)
-/
@[nolint unused_arguments]
def truncated_witt_vector (p : ℕ) (n : ℕ) (R : Type*) := fin n → R
instance (p n : ℕ) (R : Type*) [inhabited R] : inhabited (truncated_witt_vector p n R) :=
⟨λ _, default⟩
variables {n R}
namespace truncated_witt_vector
variables (p)
/-- Create a `truncated_witt_vector` from a vector `x`. -/
def mk (x : fin n → R) : truncated_witt_vector p n R := x
variables {p}
/-- `x.coeff i` is the `i`th entry of `x`. -/
def coeff (i : fin n) (x : truncated_witt_vector p n R) : R := x i
@[ext]
lemma ext {x y : truncated_witt_vector p n R} (h : ∀ i, x.coeff i = y.coeff i) : x = y :=
funext h
lemma ext_iff {x y : truncated_witt_vector p n R} : x = y ↔ ∀ i, x.coeff i = y.coeff i :=
⟨λ h i, by rw h, ext⟩
@[simp] lemma coeff_mk (x : fin n → R) (i : fin n) :
(mk p x).coeff i = x i := rfl
@[simp] lemma mk_coeff (x : truncated_witt_vector p n R) :
mk p (λ i, x.coeff i) = x :=
by { ext i, rw [coeff_mk] }
variable [comm_ring R]
/--
We can turn a truncated Witt vector `x` into a Witt vector
by setting all coefficients after `x` to be 0.
-/
def out (x : truncated_witt_vector p n R) : 𝕎 R :=
witt_vector.mk p $ λ i, if h : i < n then x.coeff ⟨i, h⟩ else 0
@[simp]
lemma coeff_out (x : truncated_witt_vector p n R) (i : fin n) :
x.out.coeff i = x.coeff i :=
by rw [out, witt_vector.coeff_mk, dif_pos i.is_lt, fin.eta]
lemma out_injective : injective (@out p n R _) :=
begin
intros x y h,
ext i,
rw [witt_vector.ext_iff] at h,
simpa only [coeff_out] using h ↑i
end
end truncated_witt_vector
namespace witt_vector
variables {p} (n)
section
/-- `truncate_fun n x` uses the first `n` entries of `x` to construct a `truncated_witt_vector`,
which has the same base `p` as `x`.
This function is bundled into a ring homomorphism in `witt_vector.truncate` -/
def truncate_fun (x : 𝕎 R) : truncated_witt_vector p n R :=
truncated_witt_vector.mk p $ λ i, x.coeff i
end
variables {n}
@[simp] lemma coeff_truncate_fun (x : 𝕎 R) (i : fin n) :
(truncate_fun n x).coeff i = x.coeff i :=
by rw [truncate_fun, truncated_witt_vector.coeff_mk]
variable [comm_ring R]
@[simp] lemma out_truncate_fun (x : 𝕎 R) :
(truncate_fun n x).out = init n x :=
begin
ext i,
dsimp [truncated_witt_vector.out, init, select],
split_ifs with hi, swap, { refl },
rw [coeff_truncate_fun, fin.coe_mk],
end
end witt_vector
namespace truncated_witt_vector
variable [comm_ring R]
@[simp] lemma truncate_fun_out (x : truncated_witt_vector p n R) :
x.out.truncate_fun n = x :=
by simp only [witt_vector.truncate_fun, coeff_out, mk_coeff]
open witt_vector
variables (p n R)
include hp
instance : has_zero (truncated_witt_vector p n R) :=
⟨truncate_fun n 0⟩
instance : has_one (truncated_witt_vector p n R) :=
⟨truncate_fun n 1⟩
instance : has_nat_cast (truncated_witt_vector p n R) :=
⟨λ i, truncate_fun n i⟩
instance : has_int_cast (truncated_witt_vector p n R) :=
⟨λ i, truncate_fun n i⟩
instance : has_add (truncated_witt_vector p n R) :=
⟨λ x y, truncate_fun n (x.out + y.out)⟩
instance : has_mul (truncated_witt_vector p n R) :=
⟨λ x y, truncate_fun n (x.out * y.out)⟩
instance : has_neg (truncated_witt_vector p n R) :=
⟨λ x, truncate_fun n (- x.out)⟩
instance : has_sub (truncated_witt_vector p n R) :=
⟨λ x y, truncate_fun n (x.out - y.out)⟩
instance has_nat_scalar : has_smul ℕ (truncated_witt_vector p n R) :=
⟨λ m x, truncate_fun n (m • x.out)⟩
instance has_int_scalar : has_smul ℤ (truncated_witt_vector p n R) :=
⟨λ m x, truncate_fun n (m • x.out)⟩
instance has_nat_pow : has_pow (truncated_witt_vector p n R) ℕ :=
⟨λ x m, truncate_fun n (x.out ^ m)⟩
@[simp] lemma coeff_zero (i : fin n) :
(0 : truncated_witt_vector p n R).coeff i = 0 :=
begin
show coeff i (truncate_fun _ 0 : truncated_witt_vector p n R) = 0,
rw [coeff_truncate_fun, witt_vector.zero_coeff],
end
end truncated_witt_vector
/-- A macro tactic used to prove that `truncate_fun` respects ring operations. -/
meta def tactic.interactive.witt_truncate_fun_tac : tactic unit :=
`[show _ = truncate_fun n _,
apply truncated_witt_vector.out_injective,
iterate { rw [out_truncate_fun] }]
namespace witt_vector
variables (p n R)
variable [comm_ring R]
lemma truncate_fun_surjective :
surjective (@truncate_fun p n R) :=
function.right_inverse.surjective truncated_witt_vector.truncate_fun_out
include hp
@[simp]
lemma truncate_fun_zero : truncate_fun n (0 : 𝕎 R) = 0 := rfl
@[simp]
lemma truncate_fun_one : truncate_fun n (1 : 𝕎 R) = 1 := rfl
variables {p R}
@[simp]
lemma truncate_fun_add (x y : 𝕎 R) :
truncate_fun n (x + y) = truncate_fun n x + truncate_fun n y :=
by { witt_truncate_fun_tac, rw init_add }
@[simp]
lemma truncate_fun_mul (x y : 𝕎 R) :
truncate_fun n (x * y) = truncate_fun n x * truncate_fun n y :=
by { witt_truncate_fun_tac, rw init_mul }
lemma truncate_fun_neg (x : 𝕎 R) :
truncate_fun n (-x) = -truncate_fun n x :=
by { witt_truncate_fun_tac, rw init_neg }
lemma truncate_fun_sub (x y : 𝕎 R) :
truncate_fun n (x - y) = truncate_fun n x - truncate_fun n y :=
by { witt_truncate_fun_tac, rw init_sub }
lemma truncate_fun_nsmul (x : 𝕎 R) (m : ℕ) :
truncate_fun n (m • x) = m • truncate_fun n x :=
by { witt_truncate_fun_tac, rw init_nsmul }
lemma truncate_fun_zsmul (x : 𝕎 R) (m : ℤ) :
truncate_fun n (m • x) = m • truncate_fun n x :=
by { witt_truncate_fun_tac, rw init_zsmul }
lemma truncate_fun_pow (x : 𝕎 R) (m : ℕ) :
truncate_fun n (x ^ m) = truncate_fun n x ^ m :=
by { witt_truncate_fun_tac, rw init_pow }
lemma truncate_fun_nat_cast (m : ℕ) : truncate_fun n (m : 𝕎 R) = m := rfl
lemma truncate_fun_int_cast (m : ℤ) : truncate_fun n (m : 𝕎 R) = m := rfl
end witt_vector
namespace truncated_witt_vector
open witt_vector
variables (p n R)
variable [comm_ring R]
include hp
instance : comm_ring (truncated_witt_vector p n R) :=
(truncate_fun_surjective p n R).comm_ring _
(truncate_fun_zero p n R)
(truncate_fun_one p n R)
(truncate_fun_add n)
(truncate_fun_mul n)
(truncate_fun_neg n)
(truncate_fun_sub n)
(truncate_fun_nsmul n)
(truncate_fun_zsmul n)
(truncate_fun_pow n)
(truncate_fun_nat_cast n)
(truncate_fun_int_cast n)
end truncated_witt_vector
namespace witt_vector
open truncated_witt_vector
variables (n)
variable [comm_ring R]
include hp
/-- `truncate n` is a ring homomorphism that truncates `x` to its first `n` entries
to obtain a `truncated_witt_vector`, which has the same base `p` as `x`. -/
noncomputable! def truncate : 𝕎 R →+* truncated_witt_vector p n R :=
{ to_fun := truncate_fun n,
map_zero' := truncate_fun_zero p n R,
map_add' := truncate_fun_add n,
map_one' := truncate_fun_one p n R,
map_mul' := truncate_fun_mul n }
variables (p n R)
lemma truncate_surjective : surjective (truncate n : 𝕎 R → truncated_witt_vector p n R) :=
truncate_fun_surjective p n R
variables {p n R}
@[simp] lemma coeff_truncate (x : 𝕎 R) (i : fin n) :
(truncate n x).coeff i = x.coeff i :=
coeff_truncate_fun _ _
variables (n)
lemma mem_ker_truncate (x : 𝕎 R) :
x ∈ (@truncate p _ n R _).ker ↔ ∀ i < n, x.coeff i = 0 :=
begin
simp only [ring_hom.mem_ker, truncate, truncate_fun, ring_hom.coe_mk,
truncated_witt_vector.ext_iff, truncated_witt_vector.coeff_mk, coeff_zero],
exact subtype.forall
end
variables (p)
@[simp] lemma truncate_mk (f : ℕ → R) :
truncate n (mk p f) = truncated_witt_vector.mk _ (λ k, f k) :=
begin
ext i,
rw [coeff_truncate, coeff_mk, truncated_witt_vector.coeff_mk],
end
end witt_vector
namespace truncated_witt_vector
variable [comm_ring R]
include hp
/--
A ring homomorphism that truncates a truncated Witt vector of length `m` to
a truncated Witt vector of length `n`, for `n ≤ m`.
-/
def truncate {m : ℕ} (hm : n ≤ m) : truncated_witt_vector p m R →+* truncated_witt_vector p n R :=
ring_hom.lift_of_right_inverse (witt_vector.truncate m) out truncate_fun_out
⟨witt_vector.truncate n,
begin
intro x,
simp only [witt_vector.mem_ker_truncate],
intros h i hi,
exact h i (lt_of_lt_of_le hi hm)
end⟩
@[simp] lemma truncate_comp_witt_vector_truncate {m : ℕ} (hm : n ≤ m) :
(@truncate p _ n R _ m hm).comp (witt_vector.truncate m) = witt_vector.truncate n :=
ring_hom.lift_of_right_inverse_comp _ _ _ _
@[simp] lemma truncate_witt_vector_truncate {m : ℕ} (hm : n ≤ m) (x : 𝕎 R) :
truncate hm (witt_vector.truncate m x) = witt_vector.truncate n x :=
ring_hom.lift_of_right_inverse_comp_apply _ _ _ _ _
@[simp] lemma truncate_truncate {n₁ n₂ n₃ : ℕ} (h1 : n₁ ≤ n₂) (h2 : n₂ ≤ n₃)
(x : truncated_witt_vector p n₃ R) :
(truncate h1) (truncate h2 x) = truncate (h1.trans h2) x :=
begin
obtain ⟨x, rfl⟩ := witt_vector.truncate_surjective p n₃ R x,
simp only [truncate_witt_vector_truncate],
end
@[simp] lemma truncate_comp {n₁ n₂ n₃ : ℕ} (h1 : n₁ ≤ n₂) (h2 : n₂ ≤ n₃) :
(@truncate p _ _ R _ _ h1).comp (truncate h2) = truncate (h1.trans h2) :=
begin
ext1 x, simp only [truncate_truncate, function.comp_app, ring_hom.coe_comp]
end
lemma truncate_surjective {m : ℕ} (hm : n ≤ m) : surjective (@truncate p _ _ R _ _ hm) :=
begin
intro x,
obtain ⟨x, rfl⟩ := witt_vector.truncate_surjective p _ R x,
exact ⟨witt_vector.truncate _ x, truncate_witt_vector_truncate _ _⟩
end
@[simp] lemma coeff_truncate {m : ℕ} (hm : n ≤ m) (i : fin n) (x : truncated_witt_vector p m R) :
(truncate hm x).coeff i = x.coeff (fin.cast_le hm i) :=
begin
obtain ⟨y, rfl⟩ := witt_vector.truncate_surjective p _ _ x,
simp only [truncate_witt_vector_truncate, witt_vector.coeff_truncate, fin.coe_cast_le],
end
section fintype
omit hp
instance {R : Type*} [fintype R] : fintype (truncated_witt_vector p n R) := pi.fintype
variables (p n R)
lemma card {R : Type*} [fintype R] :
fintype.card (truncated_witt_vector p n R) = fintype.card R ^ n :=
by simp only [truncated_witt_vector, fintype.card_fin, fintype.card_fun]
end fintype
lemma infi_ker_truncate : (⨅ i : ℕ, (@witt_vector.truncate p _ i R _).ker) = ⊥ :=
begin
rw [submodule.eq_bot_iff],
intros x hx,
ext,
simp only [witt_vector.mem_ker_truncate, ideal.mem_infi, witt_vector.zero_coeff] at hx ⊢,
exact hx _ _ (nat.lt_succ_self _)
end
end truncated_witt_vector
namespace witt_vector
open truncated_witt_vector (hiding truncate coeff)
section lift
variable [comm_ring R]
variables {S : Type*} [semiring S]
variable (f : Π k : ℕ, S →+* truncated_witt_vector p k R)
variable f_compat : ∀ (k₁ k₂ : ℕ) (hk : k₁ ≤ k₂),
(truncated_witt_vector.truncate hk).comp (f k₂) = f k₁
variables {p R}
variable (n)
/--
Given a family `fₖ : S → truncated_witt_vector p k R` and `s : S`, we produce a Witt vector by
defining the `k`th entry to be the final entry of `fₖ s`.
-/
def lift_fun (s : S) : 𝕎 R :=
witt_vector.mk p $ λ k, truncated_witt_vector.coeff (fin.last k) (f (k+1) s)
variables {f}
include f_compat
@[simp] lemma truncate_lift_fun (s : S) :
witt_vector.truncate n (lift_fun f s) = f n s :=
begin
ext i,
simp only [lift_fun, truncated_witt_vector.coeff_mk, witt_vector.truncate_mk],
rw [← f_compat (i+1) n i.is_lt, ring_hom.comp_apply, truncated_witt_vector.coeff_truncate],
-- this is a bit unfortunate
congr' with _,
simp only [fin.coe_last, fin.coe_cast_le],
end
variable (f)
/--
Given compatible ring homs from `S` into `truncated_witt_vector n` for each `n`, we can lift these
to a ring hom `S → 𝕎 R`.
`lift` defines the universal property of `𝕎 R` as the inverse limit of `truncated_witt_vector n`.
-/
def lift : S →+* 𝕎 R :=
by refine_struct { to_fun := lift_fun f };
{ intros,
rw [← sub_eq_zero, ← ideal.mem_bot, ← infi_ker_truncate, ideal.mem_infi],
simp [ring_hom.mem_ker, f_compat] }
variable {f}
@[simp] lemma truncate_lift (s : S) :
witt_vector.truncate n (lift _ f_compat s) = f n s :=
truncate_lift_fun _ f_compat s
@[simp] lemma truncate_comp_lift :
(witt_vector.truncate n).comp (lift _ f_compat) = f n :=
by { ext1, rw [ring_hom.comp_apply, truncate_lift] }
/-- The uniqueness part of the universal property of `𝕎 R`. -/
lemma lift_unique (g : S →+* 𝕎 R) (g_compat : ∀ k, (witt_vector.truncate k).comp g = f k) :
lift _ f_compat = g :=
begin
ext1 x,
rw [← sub_eq_zero, ← ideal.mem_bot, ← infi_ker_truncate, ideal.mem_infi],
intro i,
simp only [ring_hom.mem_ker, g_compat, ←ring_hom.comp_apply,
truncate_comp_lift, ring_hom.map_sub, sub_self],
end
omit f_compat
include hp
/-- The universal property of `𝕎 R` as projective limit of truncated Witt vector rings. -/
@[simps] def lift_equiv : {f : Π k, S →+* truncated_witt_vector p k R // ∀ k₁ k₂ (hk : k₁ ≤ k₂),
(truncated_witt_vector.truncate hk).comp (f k₂) = f k₁} ≃ (S →+* 𝕎 R) :=
{ to_fun := λ f, lift f.1 f.2,
inv_fun := λ g, ⟨λ k, (truncate k).comp g,
by { intros _ _ h, simp only [←ring_hom.comp_assoc, truncate_comp_witt_vector_truncate] }⟩,
left_inv := by { rintro ⟨f, hf⟩, simp only [truncate_comp_lift] },
right_inv := λ g, lift_unique _ _ $ λ _, rfl }
lemma hom_ext (g₁ g₂ : S →+* 𝕎 R) (h : ∀ k, (truncate k).comp g₁ = (truncate k).comp g₂) :
g₁ = g₂ :=
lift_equiv.symm.injective $ subtype.ext $ funext h
end lift
end witt_vector
|
85ce4a43f97097002f31ad4afd9e71ddada01ddf | 1dd482be3f611941db7801003235dc84147ec60a | /src/data/nat/prime.lean | 2c8066174c2196a9c323a40091ded102e1d3a633 | [
"Apache-2.0"
] | permissive | sanderdahmen/mathlib | 479039302bd66434bb5672c2a4cecf8d69981458 | 8f0eae75cd2d8b7a083cf935666fcce4565df076 | refs/heads/master | 1,587,491,322,775 | 1,549,672,060,000 | 1,549,672,060,000 | 169,748,224 | 0 | 0 | Apache-2.0 | 1,549,636,694,000 | 1,549,636,694,000 | null | UTF-8 | Lean | false | false | 16,536 | lean | /-
Copyright (c) 2015 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura, Jeremy Avigad, Mario Carneiro
Prime numbers.
-/
import data.nat.sqrt data.nat.gcd data.list.basic data.list.perm
open bool subtype
namespace nat
open decidable
/-- `prime p` means that `p` is a prime number, that is, a natural number
at least 2 whose only divisors are `p` and `1`. -/
def prime (p : ℕ) := p ≥ 2 ∧ ∀ m ∣ p, m = 1 ∨ m = p
theorem prime.ge_two {p : ℕ} : prime p → p ≥ 2 := and.left
theorem prime.gt_one {p : ℕ} : prime p → p > 1 := prime.ge_two
lemma prime.ne_one {p : ℕ} (hp : p.prime) : p ≠ 1 :=
ne.symm $ (ne_of_lt hp.gt_one)
theorem prime_def_lt {p : ℕ} : prime p ↔ p ≥ 2 ∧ ∀ m < p, m ∣ p → m = 1 :=
and_congr_right $ λ p2, forall_congr $ λ m,
⟨λ h l d, (h d).resolve_right (ne_of_lt l),
λ h d, (decidable.lt_or_eq_of_le $
le_of_dvd (le_of_succ_le p2) d).imp_left (λ l, h l d)⟩
theorem prime_def_lt' {p : ℕ} : prime p ↔ p ≥ 2 ∧ ∀ m, 2 ≤ m → m < p → ¬ m ∣ p :=
prime_def_lt.trans $ and_congr_right $ λ p2, forall_congr $ λ m,
⟨λ h m2 l d, not_lt_of_ge m2 ((h l d).symm ▸ dec_trivial),
λ h l d, begin
rcases m with _|_|m,
{ rw eq_zero_of_zero_dvd d at p2, revert p2, exact dec_trivial },
{ refl },
{ exact (h dec_trivial l).elim d }
end⟩
theorem prime_def_le_sqrt {p : ℕ} : prime p ↔ p ≥ 2 ∧
∀ m, 2 ≤ m → m ≤ sqrt p → ¬ m ∣ p :=
prime_def_lt'.trans $ and_congr_right $ λ p2,
⟨λ a m m2 l, a m m2 $ lt_of_le_of_lt l $ sqrt_lt_self p2,
λ a, have ∀ {m k}, m ≤ k → 1 < m → p ≠ m * k, from
λ m k mk m1 e, a m m1
(le_sqrt.2 (e.symm ▸ mul_le_mul_left m mk)) ⟨k, e⟩,
λ m m2 l ⟨k, e⟩, begin
cases (le_total m k) with mk km,
{ exact this mk m2 e },
{ rw [mul_comm] at e,
refine this km (lt_of_mul_lt_mul_right _ (zero_le m)) e,
rwa [one_mul, ← e] }
end⟩
def decidable_prime_1 (p : ℕ) : decidable (prime p) :=
decidable_of_iff' _ prime_def_lt'
local attribute [instance] decidable_prime_1
lemma prime.ne_zero {n : ℕ} (h : prime n) : n ≠ 0 :=
assume hn : n = 0,
have h2 : ¬ prime 0, from dec_trivial,
h2 (hn ▸ h)
theorem prime.pos {p : ℕ} (pp : prime p) : p > 0 :=
lt_of_succ_lt pp.gt_one
theorem not_prime_zero : ¬ prime 0 := dec_trivial
theorem not_prime_one : ¬ prime 1 := dec_trivial
theorem prime_two : prime 2 := dec_trivial
theorem prime_three : prime 3 := dec_trivial
theorem prime.pred_pos {p : ℕ} (pp : prime p) : pred p > 0 :=
lt_pred_iff.2 pp.gt_one
theorem succ_pred_prime {p : ℕ} (pp : prime p) : succ (pred p) = p :=
succ_pred_eq_of_pos pp.pos
theorem dvd_prime {p m : ℕ} (pp : prime p) : m ∣ p ↔ m = 1 ∨ m = p :=
⟨λ d, pp.2 m d, λ h, h.elim (λ e, e.symm ▸ one_dvd _) (λ e, e.symm ▸ dvd_refl _)⟩
theorem dvd_prime_ge_two {p m : ℕ} (pp : prime p) (H : m ≥ 2) : m ∣ p ↔ m = p :=
(dvd_prime pp).trans $ or_iff_right_of_imp $ not.elim $ ne_of_gt H
theorem prime.not_dvd_one {p : ℕ} (pp : prime p) : ¬ p ∣ 1
| d := (not_le_of_gt pp.gt_one) $ le_of_dvd dec_trivial d
theorem not_prime_mul {a b : ℕ} (a1 : 1 < a) (b1 : 1 < b) : ¬ prime (a * b) :=
λ h, ne_of_lt (nat.mul_lt_mul_of_pos_left b1 (lt_of_succ_lt a1)) $
by simpa using (dvd_prime_ge_two h a1).1 (dvd_mul_right _ _)
section min_fac
private lemma min_fac_lemma (n k : ℕ) (h : ¬ k * k > n) :
sqrt n - k < sqrt n + 2 - k :=
(nat.sub_lt_sub_right_iff $ le_sqrt.2 $ le_of_not_gt h).2 $
nat.lt_add_of_pos_right dec_trivial
def min_fac_aux (n : ℕ) : ℕ → ℕ | k :=
if h : n < k * k then n else
if k ∣ n then k else
have _, from min_fac_lemma n k h,
min_fac_aux (k + 2)
using_well_founded {rel_tac :=
λ _ _, `[exact ⟨_, measure_wf (λ k, sqrt n + 2 - k)⟩]}
/-- Returns the smallest prime factor of `n ≠ 1`. -/
def min_fac : ℕ → ℕ
| 0 := 2
| 1 := 1
| (n+2) := if 2 ∣ n then 2 else min_fac_aux (n + 2) 3
@[simp] theorem min_fac_zero : min_fac 0 = 2 := rfl
@[simp] theorem min_fac_one : min_fac 1 = 1 := rfl
theorem min_fac_eq : ∀ n, min_fac n = if 2 ∣ n then 2 else min_fac_aux n 3
| 0 := rfl
| 1 := by simp [show 2≠1, from dec_trivial]; rw min_fac_aux; refl
| (n+2) :=
have 2 ∣ n + 2 ↔ 2 ∣ n, from
(nat.dvd_add_iff_left (by refl)).symm,
by simp [min_fac, this]; congr
private def min_fac_prop (n k : ℕ) :=
k ≥ 2 ∧ k ∣ n ∧ ∀ m ≥ 2, m ∣ n → k ≤ m
theorem min_fac_aux_has_prop {n : ℕ} (n2 : n ≥ 2) (nd2 : ¬ 2 ∣ n) :
∀ k i, k = 2*i+3 → (∀ m ≥ 2, m ∣ n → k ≤ m) → min_fac_prop n (min_fac_aux n k)
| k := λ i e a, begin
rw min_fac_aux,
by_cases h : n < k*k; simp [h],
{ have pp : prime n :=
prime_def_le_sqrt.2 ⟨n2, λ m m2 l d,
not_lt_of_ge l $ lt_of_lt_of_le (sqrt_lt.2 h) (a m m2 d)⟩,
from ⟨n2, dvd_refl _, λ m m2 d, le_of_eq
((dvd_prime_ge_two pp m2).1 d).symm⟩ },
have k2 : 2 ≤ k, { subst e, exact dec_trivial },
by_cases dk : k ∣ n; simp [dk],
{ exact ⟨k2, dk, a⟩ },
{ refine have _, from min_fac_lemma n k h,
min_fac_aux_has_prop (k+2) (i+1)
(by simp [e, left_distrib]) (λ m m2 d, _),
cases nat.eq_or_lt_of_le (a m m2 d) with me ml,
{ subst me, contradiction },
apply (nat.eq_or_lt_of_le ml).resolve_left, intro me,
rw [← me, e] at d, change 2 * (i + 2) ∣ n at d,
have := dvd_of_mul_right_dvd d, contradiction }
end
using_well_founded {rel_tac :=
λ _ _, `[exact ⟨_, measure_wf (λ k, sqrt n + 2 - k)⟩]}
theorem min_fac_has_prop {n : ℕ} (n1 : n ≠ 1) :
min_fac_prop n (min_fac n) :=
begin
by_cases n0 : n = 0, {simp [n0, min_fac_prop, ge]},
have n2 : 2 ≤ n, { revert n0 n1, rcases n with _|_|_; exact dec_trivial },
simp [min_fac_eq],
by_cases d2 : 2 ∣ n; simp [d2],
{ exact ⟨le_refl _, d2, λ k k2 d, k2⟩ },
{ refine min_fac_aux_has_prop n2 d2 3 0 rfl
(λ m m2 d, (nat.eq_or_lt_of_le m2).resolve_left (mt _ d2)),
exact λ e, e.symm ▸ d }
end
theorem min_fac_dvd (n : ℕ) : min_fac n ∣ n :=
by by_cases n1 : n = 1;
[exact n1.symm ▸ dec_trivial, exact (min_fac_has_prop n1).2.1]
theorem min_fac_prime {n : ℕ} (n1 : n ≠ 1) : prime (min_fac n) :=
let ⟨f2, fd, a⟩ := min_fac_has_prop n1 in
prime_def_lt'.2 ⟨f2, λ m m2 l d, not_le_of_gt l (a m m2 (dvd_trans d fd))⟩
theorem min_fac_le_of_dvd {n : ℕ} : ∀ {m : ℕ}, m ≥ 2 → m ∣ n → min_fac n ≤ m :=
by by_cases n1 : n = 1;
[exact λ m m2 d, n1.symm ▸ le_trans dec_trivial m2,
exact (min_fac_has_prop n1).2.2]
theorem min_fac_pos (n : ℕ) : min_fac n > 0 :=
by by_cases n1 : n = 1;
[exact n1.symm ▸ dec_trivial, exact (min_fac_prime n1).pos]
theorem min_fac_le {n : ℕ} (H : n > 0) : min_fac n ≤ n :=
le_of_dvd H (min_fac_dvd n)
theorem prime_def_min_fac {p : ℕ} : prime p ↔ p ≥ 2 ∧ min_fac p = p :=
⟨λ pp, ⟨pp.ge_two,
let ⟨f2, fd, a⟩ := min_fac_has_prop $ ne_of_gt pp.gt_one in
((dvd_prime pp).1 fd).resolve_left (ne_of_gt f2)⟩,
λ ⟨p2, e⟩, e ▸ min_fac_prime (ne_of_gt p2)⟩
instance decidable_prime (p : ℕ) : decidable (prime p) :=
decidable_of_iff' _ prime_def_min_fac
theorem not_prime_iff_min_fac_lt {n : ℕ} (n2 : n ≥ 2) : ¬ prime n ↔ min_fac n < n :=
(not_congr $ prime_def_min_fac.trans $ and_iff_right n2).trans $
(lt_iff_le_and_ne.trans $ and_iff_right $ min_fac_le $ le_of_succ_le n2).symm
end min_fac
theorem exists_dvd_of_not_prime {n : ℕ} (n2 : n ≥ 2) (np : ¬ prime n) :
∃ m, m ∣ n ∧ m ≠ 1 ∧ m ≠ n :=
⟨min_fac n, min_fac_dvd _, ne_of_gt (min_fac_prime (ne_of_gt n2)).gt_one,
ne_of_lt $ (not_prime_iff_min_fac_lt n2).1 np⟩
theorem exists_dvd_of_not_prime2 {n : ℕ} (n2 : n ≥ 2) (np : ¬ prime n) :
∃ m, m ∣ n ∧ m ≥ 2 ∧ m < n :=
⟨min_fac n, min_fac_dvd _, (min_fac_prime (ne_of_gt n2)).ge_two,
(not_prime_iff_min_fac_lt n2).1 np⟩
theorem exists_prime_and_dvd {n : ℕ} (n2 : n ≥ 2) : ∃ p, prime p ∧ p ∣ n :=
⟨min_fac n, min_fac_prime (ne_of_gt n2), min_fac_dvd _⟩
theorem exists_infinite_primes (n : ℕ) : ∃ p, p ≥ n ∧ prime p :=
let p := min_fac (fact n + 1) in
have f1 : fact n + 1 ≠ 1, from ne_of_gt $ succ_lt_succ $ fact_pos _,
have pp : prime p, from min_fac_prime f1,
have np : n ≤ p, from le_of_not_ge $ λ h,
have h₁ : p ∣ fact n, from dvd_fact (min_fac_pos _) h,
have h₂ : p ∣ 1, from (nat.dvd_add_iff_right h₁).2 (min_fac_dvd _),
pp.not_dvd_one h₂,
⟨p, np, pp⟩
lemma prime.eq_two_or_odd {p : ℕ} (hp : prime p) : p = 2 ∨ p % 2 = 1 :=
(nat.mod_two_eq_zero_or_one p).elim
(λ h, or.inl ((hp.2 2 (dvd_of_mod_eq_zero h)).resolve_left dec_trivial).symm)
or.inr
theorem factors_lemma {k} : (k+2) / min_fac (k+2) < k+2 :=
div_lt_self dec_trivial (min_fac_prime dec_trivial).gt_one
/-- `factors n` is the prime factorization of `n`, listed in increasing order. -/
def factors : ℕ → list ℕ
| 0 := []
| 1 := []
| n@(k+2) :=
let m := min_fac n in have n / m < n := factors_lemma,
m :: factors (n / m)
lemma mem_factors : ∀ {n p}, p ∈ factors n → prime p
| 0 := λ p, false.elim
| 1 := λ p, false.elim
| n@(k+2) := λ p h,
let m := min_fac n in have n / m < n := factors_lemma,
have h₁ : p = m ∨ p ∈ (factors (n / m)) :=
(list.mem_cons_iff _ _ _).1 h,
or.cases_on h₁ (λ h₂, h₂.symm ▸ min_fac_prime dec_trivial)
mem_factors
lemma prod_factors : ∀ {n}, 0 < n → list.prod (factors n) = n
| 0 := (lt_irrefl _).elim
| 1 := λ h, rfl
| n@(k+2) := λ h,
let m := min_fac n in have n / m < n := factors_lemma,
show list.prod (m :: factors (n / m)) = n, from
have h₁ : 0 < n / m :=
nat.pos_of_ne_zero $ λ h,
have n = 0 * m := (nat.div_eq_iff_eq_mul_left (min_fac_pos _) (min_fac_dvd _)).1 h,
by rw zero_mul at this; exact (show k + 2 ≠ 0, from dec_trivial) this,
by rw [list.prod_cons, prod_factors h₁, nat.mul_div_cancel' (min_fac_dvd _)]
theorem prime.coprime_iff_not_dvd {p n : ℕ} (pp : prime p) : coprime p n ↔ ¬ p ∣ n :=
⟨λ co d, pp.not_dvd_one $ co.dvd_of_dvd_mul_left (by simp [d]),
λ nd, coprime_of_dvd $ λ m m2 mp, ((dvd_prime_ge_two pp m2).1 mp).symm ▸ nd⟩
theorem prime.dvd_iff_not_coprime {p n : ℕ} (pp : prime p) : p ∣ n ↔ ¬ coprime p n :=
iff_not_comm.2 pp.coprime_iff_not_dvd
theorem prime.dvd_mul {p m n : ℕ} (pp : prime p) : p ∣ m * n ↔ p ∣ m ∨ p ∣ n :=
⟨λ H, or_iff_not_imp_left.2 $ λ h,
(pp.coprime_iff_not_dvd.2 h).dvd_of_dvd_mul_left H,
or.rec (λ h, dvd_mul_of_dvd_left h _) (λ h, dvd_mul_of_dvd_right h _)⟩
theorem prime.not_dvd_mul {p m n : ℕ} (pp : prime p)
(Hm : ¬ p ∣ m) (Hn : ¬ p ∣ n) : ¬ p ∣ m * n :=
mt pp.dvd_mul.1 $ by simp [Hm, Hn]
theorem prime.dvd_of_dvd_pow {p m n : ℕ} (pp : prime p) (h : p ∣ m^n) : p ∣ m :=
by induction n with n IH;
[exact pp.not_dvd_one.elim h,
exact (pp.dvd_mul.1 h).elim IH id]
lemma prime.dvd_fact : ∀ {n p : ℕ} (hp : prime p), p ∣ n.fact ↔ p ≤ n
| 0 p hp := iff_of_false hp.not_dvd_one (not_le_of_lt hp.pos)
| (n+1) p hp := begin
rw [fact_succ, hp.dvd_mul, prime.dvd_fact hp],
exact ⟨λ h, h.elim (le_of_dvd (succ_pos _)) le_succ_of_le,
λ h, (_root_.lt_or_eq_of_le h).elim (or.inr ∘ le_of_lt_succ)
(λ h, or.inl $ by rw h)⟩
end
theorem prime.coprime_pow_of_not_dvd {p m a : ℕ} (pp : prime p) (h : ¬ p ∣ a) : coprime a (p^m) :=
(pp.coprime_iff_not_dvd.2 h).symm.pow_right _
theorem coprime_primes {p q : ℕ} (pp : prime p) (pq : prime q) : coprime p q ↔ p ≠ q :=
pp.coprime_iff_not_dvd.trans $ not_congr $ dvd_prime_ge_two pq pp.ge_two
theorem coprime_pow_primes {p q : ℕ} (n m : ℕ) (pp : prime p) (pq : prime q) (h : p ≠ q) :
coprime (p^n) (q^m) :=
((coprime_primes pp pq).2 h).pow _ _
theorem coprime_or_dvd_of_prime {p} (pp : prime p) (i : ℕ) : coprime p i ∨ p ∣ i :=
by rw [pp.dvd_iff_not_coprime]; apply em
theorem dvd_prime_pow {p : ℕ} (pp : prime p) {m i : ℕ} : i ∣ (p^m) ↔ ∃ k ≤ m, i = p^k :=
begin
induction m with m IH generalizing i, {simp [pow_succ, le_zero_iff] at *},
by_cases p ∣ i,
{ cases h with a e, subst e,
rw [pow_succ, mul_comm (p^m) p, nat.mul_dvd_mul_iff_left pp.pos, IH],
split; intro h; rcases h with ⟨k, h, e⟩,
{ exact ⟨succ k, succ_le_succ h, by rw [mul_comm, e]; refl⟩ },
cases k with k,
{ apply pp.not_dvd_one.elim,
simp at e, rw ← e, apply dvd_mul_right },
{ refine ⟨k, le_of_succ_le_succ h, _⟩,
rwa [mul_comm, pow_succ, nat.mul_right_inj pp.pos] at e } },
{ split; intro d,
{ rw (pp.coprime_pow_of_not_dvd h).eq_one_of_dvd d,
exact ⟨0, zero_le _, rfl⟩ },
{ rcases d with ⟨k, l, e⟩,
rw e, exact pow_dvd_pow _ l } }
end
section
open list
lemma mem_list_primes_of_dvd_prod {p : ℕ} (hp : prime p) :
∀ {l : list ℕ}, (∀ p ∈ l, prime p) → p ∣ prod l → p ∈ l
| [] := λ h₁ h₂, absurd h₂ (prime.not_dvd_one hp)
| (q :: l) := λ h₁ h₂,
have h₃ : p ∣ q * prod l := @prod_cons _ _ l q ▸ h₂,
have hq : prime q := h₁ q (mem_cons_self _ _),
or.cases_on ((prime.dvd_mul hp).1 h₃)
(λ h, by rw [prime.dvd_iff_not_coprime hp, coprime_primes hp hq, ne.def, not_not] at h;
exact h ▸ mem_cons_self _ _)
(λ h, have hl : ∀ p ∈ l, prime p := λ p hlp, h₁ p ((mem_cons_iff _ _ _).2 (or.inr hlp)),
(mem_cons_iff _ _ _).2 (or.inr (mem_list_primes_of_dvd_prod hl h)))
lemma mem_factors_iff_dvd {n p : ℕ} (hn : 0 < n) (hp : prime p) : p ∈ factors n ↔ p ∣ n :=
⟨λ h, prod_factors hn ▸ list.dvd_prod h,
λ h, mem_list_primes_of_dvd_prod hp (@mem_factors n) ((prod_factors hn).symm ▸ h)⟩
lemma perm_of_prod_eq_prod : ∀ {l₁ l₂ : list ℕ}, prod l₁ = prod l₂ →
(∀ p ∈ l₁, prime p) → (∀ p ∈ l₂, prime p) → l₁ ~ l₂
| [] [] _ _ _ := perm.nil
| [] (a :: l) h₁ h₂ h₃ :=
have ha : a ∣ 1 := @prod_nil ℕ _ ▸ h₁.symm ▸ (@prod_cons _ _ l a).symm ▸ dvd_mul_right _ _,
absurd ha (prime.not_dvd_one (h₃ a (mem_cons_self _ _)))
| (a :: l) [] h₁ h₂ h₃ :=
have ha : a ∣ 1 := @prod_nil ℕ _ ▸ h₁ ▸ (@prod_cons _ _ l a).symm ▸ dvd_mul_right _ _,
absurd ha (prime.not_dvd_one (h₂ a (mem_cons_self _ _)))
| (a :: l₁) (b :: l₂) h hl₁ hl₂ :=
have hl₁' : ∀ p ∈ l₁, prime p := λ p hp, hl₁ p (mem_cons_of_mem _ hp),
have hl₂' : ∀ p ∈ (b :: l₂).erase a, prime p := λ p hp, hl₂ p (mem_of_mem_erase hp),
have ha : a ∈ (b :: l₂) := mem_list_primes_of_dvd_prod (hl₁ a (mem_cons_self _ _)) hl₂
(h ▸ by rw prod_cons; exact dvd_mul_right _ _),
have hb : b :: l₂ ~ a :: (b :: l₂).erase a := perm_erase ha,
have hl : prod l₁ = prod ((b :: l₂).erase a) :=
(nat.mul_left_inj (prime.pos (hl₁ a (mem_cons_self _ _)))).1 $
by rwa [← prod_cons, ← prod_cons, ← prod_eq_of_perm hb],
perm.trans (perm.skip _ (perm_of_prod_eq_prod hl hl₁' hl₂')) hb.symm
lemma factors_unique {n : ℕ} {l : list ℕ} (h₁ : prod l = n) (h₂ : ∀ p ∈ l, prime p) : l ~ factors n :=
have hn : 0 < n := nat.pos_of_ne_zero $ λ h, begin
rw h at *, clear h,
induction l with a l hi,
{ exact absurd h₁ dec_trivial },
{ rw prod_cons at h₁,
exact nat.mul_ne_zero (ne_of_lt (prime.pos (h₂ a (mem_cons_self _ _)))).symm
(hi (λ p hp, h₂ p (mem_cons_of_mem _ hp))) h₁ }
end,
perm_of_prod_eq_prod (by rwa prod_factors hn) h₂ (@mem_factors _)
end
lemma succ_dvd_or_succ_dvd_of_succ_sum_dvd_mul {p : ℕ} (p_prime : prime p) {m n k l : ℕ}
(hpm : p ^ k ∣ m) (hpn : p ^ l ∣ n) (hpmn : p ^ (k+l+1) ∣ m*n) :
p ^ (k+1) ∣ m ∨ p ^ (l+1) ∣ n :=
have hpd : p^(k+l) * p ∣ m*n, from hpmn,
have hpd2 : p ∣ (m*n) / p ^ (k+l), from dvd_div_of_mul_dvd hpd,
have hpd3 : p ∣ (m*n) / (p^k * p^l), by simpa [nat.pow_add] using hpd2,
have hpd4 : p ∣ (m / p^k) * (n / p^l), by simpa [nat.div_mul_div hpm hpn] using hpd3,
have hpd5 : p ∣ (m / p^k) ∨ p ∣ (n / p^l), from (prime.dvd_mul p_prime).1 hpd4,
show p^k*p ∣ m ∨ p^l*p ∣ n, from
hpd5.elim
(assume : p ∣ m / p ^ k, or.inl $ mul_dvd_of_dvd_div hpm this)
(assume : p ∣ n / p ^ l, or.inr $ mul_dvd_of_dvd_div hpn this)
end nat
|
df88423d046011ac8167e34cf5deacbdf61fb636 | 3dd1b66af77106badae6edb1c4dea91a146ead30 | /tests/lean/t3.lean | 1a3c30ad41575243ec1553959bd05441a1ea24fd | [
"Apache-2.0"
] | permissive | silky/lean | 79c20c15c93feef47bb659a2cc139b26f3614642 | df8b88dca2f8da1a422cb618cd476ef5be730546 | refs/heads/master | 1,610,737,587,697 | 1,406,574,534,000 | 1,406,574,534,000 | 22,362,176 | 1 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 1,073 | lean | universe u
print raw Type.{u}
namespace tst
universe v
print raw Type.{v}
print raw Type.{tst.v}
end
print raw Type.{tst.v}
print raw Type.{v} -- Error: alias 'v' is not available anymore
section
universe z -- Remark: this is a local universe
print raw Type.{z}
end
print raw Type.{z} -- Error: local universe 'z' is gone
section
namespace foo -- Error: we cannot create a namespace inside a section
end
namespace tst
print raw Type.{v} -- Remark: alias 'v' is available again
print raw Type.{u}
namespace foo
universe U
end
end
print raw Type.{tst.foo.U}
namespace tst.foo -- Error: we cannot use qualified names in declarations
universe full.name.U -- Error: we cannot use qualified names in declarations
namespace tst
namespace foo
print raw Type.{v} -- Remark: alias 'v' for 'tst.v' is available again
print raw Type.{U} -- Remark: alias 'U' for 'tst.foo.U' is available again
end
end
namespace bla
universe u -- Error: we cannot shadow universe levels
end
print raw Type.{bla.u} -- Error: we failed to declare bla.u
|
f055683d87eb8b11e38d6100a88b6b89580cfbcf | d406927ab5617694ec9ea7001f101b7c9e3d9702 | /src/algebra/category/Semigroup/basic.lean | 65bb2df05eb967197a6c851af7c0f5fdc12b61eb | [
"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,290 | lean | /-
Copyright (c) 2021 Julian Kuelshammer. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Julian Kuelshammer
-/
import algebra.pempty_instances
import algebra.hom.equiv.basic
import category_theory.concrete_category.bundled_hom
import category_theory.functor.reflects_isomorphisms
import category_theory.elementwise
/-!
# Category instances for has_mul, has_add, semigroup and add_semigroup
We introduce the bundled categories:
* `Magma`
* `AddMagma`
* `Semigroup`
* `AddSemigroup`
along with the relevant forgetful functors between them.
This closely follows `algebra.category.Mon.basic`.
## TODO
* Limits in these categories
* free/forgetful adjunctions
-/
universes u v
open category_theory
/-- The category of magmas and magma morphisms. -/
@[to_additive AddMagma]
def Magma : Type (u+1) := bundled has_mul
/-- The category of additive magmas and additive magma morphisms. -/
add_decl_doc AddMagma
namespace Magma
@[to_additive]
instance bundled_hom : bundled_hom @mul_hom :=
⟨@mul_hom.to_fun, @mul_hom.id, @mul_hom.comp, @mul_hom.coe_inj⟩
attribute [derive [large_category, concrete_category]] Magma
attribute [to_additive] Magma.large_category Magma.concrete_category
@[to_additive] instance : has_coe_to_sort Magma Type* := bundled.has_coe_to_sort
/-- Construct a bundled `Magma` from the underlying type and typeclass. -/
@[to_additive]
def of (M : Type u) [has_mul M] : Magma := bundled.of M
/-- Construct a bundled `AddMagma` from the underlying type and typeclass. -/
add_decl_doc AddMagma.of
/-- Typecheck a `mul_hom` as a morphism in `Magma`. -/
@[to_additive] def of_hom {X Y : Type u} [has_mul X] [has_mul Y] (f : X →ₙ* Y) :
of X ⟶ of Y := f
/-- Typecheck a `add_hom` as a morphism in `AddMagma`. -/
add_decl_doc AddMagma.of_hom
@[simp, to_additive] lemma of_hom_apply {X Y : Type u} [has_mul X] [has_mul Y] (f : X →ₙ* Y)
(x : X) : of_hom f x = f x := rfl
@[to_additive]
instance : inhabited Magma := ⟨Magma.of pempty⟩
@[to_additive]
instance (M : Magma) : has_mul M := M.str
@[simp, to_additive] lemma coe_of (R : Type u) [has_mul R] : (Magma.of R : Type u) = R := rfl
end Magma
/-- The category of semigroups and semigroup morphisms. -/
@[to_additive AddSemigroup]
def Semigroup : Type (u+1) := bundled semigroup
/-- The category of additive semigroups and semigroup morphisms. -/
add_decl_doc AddSemigroup
namespace Semigroup
@[to_additive]
instance : bundled_hom.parent_projection semigroup.to_has_mul := ⟨⟩
attribute [derive [large_category, concrete_category]] Semigroup
attribute [to_additive] Semigroup.large_category Semigroup.concrete_category
@[to_additive] instance : has_coe_to_sort Semigroup Type* := bundled.has_coe_to_sort
/-- Construct a bundled `Semigroup` from the underlying type and typeclass. -/
@[to_additive]
def of (M : Type u) [semigroup M] : Semigroup := bundled.of M
/-- Construct a bundled `AddSemigroup` from the underlying type and typeclass. -/
add_decl_doc AddSemigroup.of
/-- Typecheck a `mul_hom` as a morphism in `Semigroup`. -/
@[to_additive] def of_hom {X Y : Type u} [semigroup X] [semigroup Y] (f : X →ₙ* Y) :
of X ⟶ of Y := f
/-- Typecheck a `add_hom` as a morphism in `AddSemigroup`. -/
add_decl_doc AddSemigroup.of_hom
@[simp, to_additive] lemma of_hom_apply {X Y : Type u} [semigroup X] [semigroup Y] (f : X →ₙ* Y)
(x : X) : of_hom f x = f x := rfl
@[to_additive]
instance : inhabited Semigroup := ⟨Semigroup.of pempty⟩
@[to_additive]
instance (M : Semigroup) : semigroup M := M.str
@[simp, to_additive] lemma coe_of (R : Type u) [semigroup R] : (Semigroup.of R : Type u) = R := rfl
@[to_additive has_forget_to_AddMagma]
instance has_forget_to_Magma : has_forget₂ Semigroup Magma := bundled_hom.forget₂ _ _
end Semigroup
variables {X Y : Type u}
section
variables [has_mul X] [has_mul Y]
/-- Build an isomorphism in the category `Magma` from a `mul_equiv` between `has_mul`s. -/
@[to_additive add_equiv.to_AddMagma_iso "Build an isomorphism in the category `AddMagma` from
an `add_equiv` between `has_add`s.", simps]
def mul_equiv.to_Magma_iso (e : X ≃* Y) : Magma.of X ≅ Magma.of Y :=
{ hom := e.to_mul_hom,
inv := e.symm.to_mul_hom }
end
section
variables [semigroup X] [semigroup Y]
/-- Build an isomorphism in the category `Semigroup` from a `mul_equiv` between `semigroup`s. -/
@[to_additive add_equiv.to_AddSemigroup_iso "Build an isomorphism in the category
`AddSemigroup` from an `add_equiv` between `add_semigroup`s.", simps]
def mul_equiv.to_Semigroup_iso (e : X ≃* Y) : Semigroup.of X ≅ Semigroup.of Y :=
{ hom := e.to_mul_hom,
inv := e.symm.to_mul_hom }
end
namespace category_theory.iso
/-- Build a `mul_equiv` from an isomorphism in the category `Magma`. -/
@[to_additive AddMagma_iso_to_add_equiv "Build an `add_equiv` from an isomorphism in the category
`AddMagma`."]
def Magma_iso_to_mul_equiv {X Y : Magma} (i : X ≅ Y) : X ≃* Y :=
{ to_fun := i.hom,
inv_fun := i.inv,
left_inv := λ x, by simp,
right_inv := λ y, by simp,
map_mul' := by simp }
/-- Build a `mul_equiv` from an isomorphism in the category `Semigroup`. -/
@[to_additive "Build an `add_equiv` from an isomorphism in the category
`AddSemigroup`."]
def Semigroup_iso_to_mul_equiv {X Y : Semigroup} (i : X ≅ Y) : X ≃* Y :=
{ to_fun := i.hom,
inv_fun := i.inv,
left_inv := λ x, by simp,
right_inv := λ y, by simp,
map_mul' := by simp }
end category_theory.iso
/-- multiplicative equivalences between `has_mul`s are the same as (isomorphic to) isomorphisms
in `Magma` -/
@[to_additive add_equiv_iso_AddMagma_iso "additive equivalences between `has_add`s are the same
as (isomorphic to) isomorphisms in `AddMagma`"]
def mul_equiv_iso_Magma_iso {X Y : Type u} [has_mul X] [has_mul Y] :
(X ≃* Y) ≅ (Magma.of X ≅ Magma.of Y) :=
{ hom := λ e, e.to_Magma_iso,
inv := λ i, i.Magma_iso_to_mul_equiv }
/-- multiplicative equivalences between `semigroup`s are the same as (isomorphic to) isomorphisms
in `Semigroup` -/
@[to_additive add_equiv_iso_AddSemigroup_iso "additive equivalences between `add_semigroup`s are
the same as (isomorphic to) isomorphisms in `AddSemigroup`"]
def mul_equiv_iso_Semigroup_iso {X Y : Type u} [semigroup X] [semigroup Y] :
(X ≃* Y) ≅ (Semigroup.of X ≅ Semigroup.of Y) :=
{ hom := λ e, e.to_Semigroup_iso,
inv := λ i, i.Semigroup_iso_to_mul_equiv }
@[to_additive]
instance Magma.forget_reflects_isos : reflects_isomorphisms (forget Magma.{u}) :=
{ reflects := λ X Y f _,
begin
resetI,
let i := as_iso ((forget Magma).map f),
let e : X ≃* Y := { ..f, ..i.to_equiv },
exact ⟨(is_iso.of_iso e.to_Magma_iso).1⟩,
end }
@[to_additive]
instance Semigroup.forget_reflects_isos : reflects_isomorphisms (forget Semigroup.{u}) :=
{ reflects := λ X Y f _,
begin
resetI,
let i := as_iso ((forget Semigroup).map f),
let e : X ≃* Y := { ..f, ..i.to_equiv },
exact ⟨(is_iso.of_iso e.to_Semigroup_iso).1⟩,
end }
/-!
Once we've shown that the forgetful functors to type reflect isomorphisms,
we automatically obtain that the `forget₂` functors between our concrete categories
reflect isomorphisms.
-/
example : reflects_isomorphisms (forget₂ Semigroup Magma) := by apply_instance
|
1c7a9ea73251c8835a923d1d0809a6b02fd5b91c | ea5678cc400c34ff95b661fa26d15024e27ea8cd | /ring_tac.lean | 6b6c460e1606c8f5d64114b700246184c5d3c8e3 | [] | no_license | ChrisHughes24/leanstuff | dca0b5349c3ed893e8792ffbd98cbcadaff20411 | 9efa85f72efaccd1d540385952a6acc18fce8687 | refs/heads/master | 1,654,883,241,759 | 1,652,873,885,000 | 1,652,873,885,000 | 134,599,537 | 1 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 684 | lean | import data.num.lemmas
inductive poly : Type
| const : znum → poly
| add : poly → poly → poly
| mul : poly → poly → poly
| pow : poly → num → poly
| var : ℕ → poly
instance : has_pow poly num := ⟨poly.pow⟩
instance : has_add poly := ⟨poly.add⟩
instance : has_mul poly := ⟨poly.mul⟩
inductive horner_poly : Type
| const : znum → horner_poly
-- The poly (f * X_i^n + b)
| horner (i : ℕ) (f : horner_poly) (n : pos_num) (b : horner_poly) : horner_poly
open poly horner_poly
@[simp] def add : horner_poly → horner_poly → horner_poly
| (const m) (const n) := const (m + n)
| f (horner i g n b) := horner i g n (add _ _)
|
63b89905a7473c00e5ebecafbd1c1b9f3a612c9e | 8b9f17008684d796c8022dab552e42f0cb6fb347 | /library/data/nat/sqrt.lean | c051e773ab252a83bfd0c7bc629cf87c38e45460 | [
"Apache-2.0"
] | permissive | chubbymaggie/lean | 0d06ae25f9dd396306fb02190e89422ea94afd7b | d2c7b5c31928c98f545b16420d37842c43b4ae9a | refs/heads/master | 1,611,313,622,901 | 1,430,266,839,000 | 1,430,267,083,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 4,521 | lean | /-
Copyright (c) 2015 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Module: data.nat.sqrt
Authors: Leonardo de Moura
Very simple (sqrt n) function that returns s s.t.
s*s ≤ n ≤ s*s + s + s
-/
import data.nat.order data.nat.sub
namespace nat
open decidable
-- This is the simplest possible function that just performs a linear search
definition sqrt_aux : nat → nat → nat
| 0 n := 0
| (succ s) n := if (succ s)*(succ s) ≤ n then succ s else sqrt_aux s n
theorem sqrt_aux_succ_of_pos {s n} : (succ s)*(succ s) ≤ n → sqrt_aux (succ s) n = (succ s) :=
assume h, if_pos h
theorem sqrt_aux_succ_of_neg {s n} : ¬ (succ s)*(succ s) ≤ n → sqrt_aux (succ s) n = sqrt_aux s n :=
assume h, if_neg h
theorem sqrt_aux_of_le : ∀ {s n : nat}, s * s ≤ n → sqrt_aux s n = s
| 0 n h := rfl
| (succ s) n h := by rewrite [sqrt_aux_succ_of_pos h]
definition sqrt (n : nat) : nat :=
sqrt_aux n n
theorem sqrt_aux_lower : ∀ {s n : nat}, s ≤ n → sqrt_aux s n * sqrt_aux s n ≤ n
| 0 n h := h
| (succ s) n h := by_cases
(λ h₁ : (succ s)*(succ s) ≤ n, by rewrite [sqrt_aux_succ_of_pos h₁]; exact h₁)
(λ h₂ : ¬ (succ s)*(succ s) ≤ n,
assert aux : s ≤ n, from lt.step (lt_of_succ_le h),
by rewrite [sqrt_aux_succ_of_neg h₂]; exact (sqrt_aux_lower aux))
theorem sqrt_lower (n : nat) : sqrt n * sqrt n ≤ n :=
sqrt_aux_lower (le.refl n)
theorem sqrt_aux_upper : ∀ {s n : nat}, n ≤ s*s + s + s → n ≤ sqrt_aux s n * sqrt_aux s n + sqrt_aux s n + sqrt_aux s n
| 0 n h := h
| (succ s) n h := by_cases
(λ h₁ : (succ s)*(succ s) ≤ n,
by rewrite [sqrt_aux_succ_of_pos h₁]; exact h)
(λ h₂ : ¬ (succ s)*(succ s) ≤ n,
assert h₃ : n < (succ s) * (succ s), from lt_of_not_le h₂,
assert h₄ : n ≤ s * s + s + s, by rewrite [succ_mul_succ_eq at h₃]; exact h₃,
by rewrite [sqrt_aux_succ_of_neg h₂]; exact (sqrt_aux_upper h₄))
theorem sqrt_upper (n : nat) : n ≤ sqrt n * sqrt n + sqrt n + sqrt n :=
have aux : n ≤ n*n + n + n, from le_add_of_le_right (le_add_of_le_left (le.refl n)),
sqrt_aux_upper aux
private theorem le_squared : ∀ (n : nat), n ≤ n*n
| 0 := !le.refl
| (succ n) :=
have aux₁ : 1 ≤ succ n, from succ_le_succ !zero_le,
assert aux₂ : 1 * succ n ≤ succ n * succ n, from mul_le_mul aux₁ !le.refl,
by rewrite [one_mul at aux₂]; exact aux₂
theorem sqrt_aux_offset_eq {n k : nat} (h₁ : k ≤ n + n) : ∀ {s}, s ≥ n → sqrt_aux s (n*n + k) = n
| 0 h₂ :=
assert neqz : n = 0, from eq_zero_of_le_zero h₂,
by rewrite neqz
| (succ s) h₂ := by_cases
(λ hl : (succ s)*(succ s) ≤ n*n + k,
have l₁ : n*n + k ≤ n*n + n + n, from by rewrite [add.assoc]; exact (add_le_add_left h₁ (n*n)),
assert l₂ : n*n + k < n*n + n + n + 1, from l₁,
have l₃ : n*n + k < (succ n)*(succ n), by rewrite [-succ_mul_succ_eq at l₂]; exact l₂,
assert l₄ : (succ s)*(succ s) < (succ n)*(succ n), from lt_of_le_of_lt hl l₃,
have ng : ¬ succ s > (succ n), from
assume g : succ s > succ n,
have g₁ : (succ s)*(succ s) > (succ n)*(succ n), from mul_lt_mul_of_le_of_le g g,
absurd (lt.trans g₁ l₄) !lt.irrefl,
have sslesn : succ s ≤ succ n, from le_of_not_lt ng,
have ssnesn : succ s ≠ succ n, from
assume sseqsn : succ s = succ n,
by rewrite [sseqsn at l₄]; exact (absurd l₄ !lt.irrefl),
have sslen : succ s ≤ n, from lt_of_le_and_ne sslesn ssnesn,
assert sseqn : succ s = n, from le.antisymm sslen h₂,
by rewrite [sqrt_aux_succ_of_pos hl]; exact sseqn)
(λ hg : ¬ (succ s)*(succ s) ≤ n*n + k,
or.elim (eq_or_lt_of_le h₂)
(λ neqss : n = succ s,
have p : n*n ≤ n*n + k, from !le_add_right,
have n : ¬ n*n ≤ n*n + k, by rewrite [-neqss at hg]; exact hg,
absurd p n)
(λ sgen : s ≥ n,
by rewrite [sqrt_aux_succ_of_neg hg]; exact (sqrt_aux_offset_eq sgen)))
theorem sqrt_offset_eq {n k : nat} : k ≤ n + n → sqrt (n*n + k) = n :=
assume h,
have h₁ : n ≤ n*n + k, from le.trans !le_squared !le_add_right,
sqrt_aux_offset_eq h h₁
theorem sqrt_eq (n : nat) : sqrt (n*n) = n :=
sqrt_offset_eq !zero_le
theorem mul_square_cancel {a b : nat} : a*a = b*b → a = b :=
assume h,
assert aux : sqrt (a*a) = sqrt (b*b), by rewrite h,
by rewrite [*sqrt_eq at aux]; exact aux
end nat
|
6c2617b21ba61a4f2f892813fcd5963e86795e98 | dd0f5513e11c52db157d2fcc8456d9401a6cd9da | /02_Dependent_Type_Theory.org.18.lean | a3e1248ddd061d5d9c782917de0adb1338e58453 | [] | 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 | 253 | lean | /- page 20 -/
import standard
import data.prod
open prod
definition curry (A B C : Type) (f : A × B → C) : A → B → C :=
λ a b, f (a, b)
definition uncurry (A B C : Type) (f : A → B → C) : A × B → C :=
λ p, f (pr₁ p) (pr₂ p)
|
02e63d15397c085e388685b41aec0f38496b59fb | b7f22e51856f4989b970961f794f1c435f9b8f78 | /tests/lean/run/blast_cc_subsingleton1.lean | 663eedb417b88a7e043e6bfe9e3a14c78ecf1639 | [
"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 | 581 | lean | import data.unit
open nat unit
constant f {A : Type} (a : A) {B : Type} (b : B) : nat
constant g : unit → nat
set_option blast.strategy "cc"
example (a b : unit) : g a = g b :=
by blast
example (a c : unit) (b d : nat) : b = d → f a b = f c d :=
by blast
constant h {A B : Type} : A → B → nat
example (a b c d : unit) : h a b = h c d :=
by blast
definition C [reducible] : nat → Type₁
| nat.zero := unit
| (nat.succ a) := nat
constant g₂ : Π {n : nat}, C n → nat → nat
example (a b : C zero) (c d : nat) : c = d → g₂ a c = g₂ b d :=
by blast
|
44fc3ee7fd09164f0847fd4a5bbf2b01275a4eee | 46125763b4dbf50619e8846a1371029346f4c3db | /src/tactic/alias.lean | 71af97aa7fd32aa805b2647207d85d4bc7eedb01 | [
"Apache-2.0"
] | permissive | thjread/mathlib | a9d97612cedc2c3101060737233df15abcdb9eb1 | 7cffe2520a5518bba19227a107078d83fa725ddc | refs/heads/master | 1,615,637,696,376 | 1,583,953,063,000 | 1,583,953,063,000 | 246,680,271 | 0 | 0 | Apache-2.0 | 1,583,960,875,000 | 1,583,960,875,000 | null | UTF-8 | Lean | false | false | 4,493 | lean | /-
Copyright (c) 2017 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro
-/
import data.buffer.parser meta.expr
/-!
# The `alias` command
This file defines an `alias` command, which can be used to create copies
of a theorem or definition with different names.
Syntax:
```
/ -- doc string - /
alias my_theorem ← alias1 alias2 ...
```
This produces defs or theorems of the form:
```
/ -- doc string - /
@[alias] theorem alias1 : <type of my_theorem> := my_theorem
/ -- doc string - /
@[alias] theorem alias2 : <type of my_theorem> := my_theorem
```
Iff alias syntax:
```
alias A_iff_B ↔ B_of_A A_of_B
alias A_iff_B ↔ ..
```
This gets an existing biconditional theorem `A_iff_B` and produces
the one-way implications `B_of_A` and `A_of_B` (with no change in
implicit arguments). A blank `_` can be used to avoid generating one direction.
The `..` notation attempts to generate the 'of'-names automatically when the
input theorem has the form `A_iff_B` or `A_iff_B_left` etc.
-/
open lean.parser tactic interactive parser
namespace tactic.alias
@[user_attribute] meta def alias_attr : user_attribute :=
{ name := `alias, descr := "This definition is an alias of another." }
meta def alias_direct (d : declaration) (doc : string) (al : name) : tactic unit :=
do updateex_env $ λ env,
env.add (match d.to_definition with
| declaration.defn n ls t _ _ _ :=
declaration.defn al ls t (expr.const n (level.param <$> ls))
reducibility_hints.abbrev tt
| declaration.thm n ls t _ :=
declaration.thm al ls t $ task.pure $ expr.const n (level.param <$> ls)
| _ := undefined
end),
alias_attr.set al () tt,
add_doc_string al doc
meta def mk_iff_mp_app (iffmp : name) : expr → (nat → expr) → tactic expr
| (expr.pi n bi e t) f := expr.lam n bi e <$> mk_iff_mp_app t (λ n, f (n+1) (expr.var n))
| `(%%a ↔ %%b) f := pure $ @expr.const tt iffmp [] a b (f 0)
| _ f := fail "Target theorem must have the form `Π x y z, a ↔ b`"
meta def alias_iff (d : declaration) (doc : string) (al : name) (iffmp : name) : tactic unit :=
(if al = `_ then skip else get_decl al >> skip) <|> do
let ls := d.univ_params,
let t := d.type,
v ← mk_iff_mp_app iffmp t (λ_, expr.const d.to_name (level.param <$> ls)),
t' ← infer_type v,
updateex_env $ λ env, env.add (declaration.thm al ls t' $ task.pure v),
alias_attr.set al () tt,
add_doc_string al doc
meta def make_left_right : name → tactic (name × name)
| (name.mk_string s p) := do
let buf : char_buffer := s.to_char_buffer,
sum.inr parts ← pure $ run (sep_by1 (ch '_') (many_char (sat (≠ '_')))) s.to_char_buffer,
(left, _::right) ← pure $ parts.span (≠ "iff"),
let pfx (a b : string) := a.to_list.is_prefix_of b.to_list,
(suffix', right') ← pure $ right.reverse.span (λ s, pfx "left" s ∨ pfx "right" s),
let right := right'.reverse,
let suffix := suffix'.reverse,
pure (p <.> "_".intercalate (right ++ "of" :: left ++ suffix),
p <.> "_".intercalate (left ++ "of" :: right ++ suffix))
| _ := failed
@[user_command] meta def alias_cmd (meta_info : decl_meta_info)
(_ : parse $ tk "alias") : lean.parser unit :=
do old ← ident,
d ← (do old ← resolve_constant old, get_decl old) <|>
fail ("declaration " ++ to_string old ++ " not found"),
let doc := λ al : name, meta_info.doc_string.get_or_else $
"**Alias** of `" ++ to_string old ++ "`.",
do {
tk "←" <|> tk "<-",
aliases ← many ident,
↑(aliases.mmap' $ λ al, alias_direct d (doc al) al) } <|>
do {
tk "↔" <|> tk "<->",
(left, right) ←
mcond ((tk "." *> tk "." >> pure tt) <|> pure ff)
(make_left_right old <|> fail "invalid name for automatic name generation")
(prod.mk <$> types.ident_ <*> types.ident_),
alias_iff d (doc left) left `iff.mp,
alias_iff d (doc right) right `iff.mpr }
meta def get_lambda_body : expr → expr
| (expr.lam _ _ _ b) := get_lambda_body b
| a := a
meta def get_alias_target (n : name) : tactic (option name) :=
do attr ← try_core (has_attribute `alias n),
option.cases_on attr (pure none) $ λ_, do
d ← get_decl n,
let (head, args) := (get_lambda_body d.value).get_app_fn_args,
let head := if head.is_constant_of `iff.mp ∨ head.is_constant_of `iff.mpr then
expr.get_app_fn (head.ith_arg 2)
else head,
guardb $ head.is_constant,
pure $ head.const_name
end tactic.alias
|
7003637bcf4f1c5f502c84e81800814958010fbd | d1a52c3f208fa42c41df8278c3d280f075eb020c | /stage0/src/Lean/Meta/Match/MatchEqs.lean | f12a0814473d9d90587e6959b61f323ebd9ac4d2 | [
"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 | 15,320 | lean | /-
Copyright (c) 2021 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
import Lean.Meta.Match.Match
import Lean.Meta.Tactic.Apply
import Lean.Meta.Tactic.Delta
import Lean.Meta.Tactic.SplitIf
namespace Lean.Meta
/--
Helper method for `proveCondEqThm`. Given a goal of the form `C.rec ... xMajor = rhs`,
apply `cases xMajor`. -/
partial def casesOnStuckLHS (mvarId : MVarId) : MetaM (Array MVarId) := do
let target ← getMVarType mvarId
if let some (_, lhs, rhs) ← matchEq? target then
if let some fvarId ← findFVar? lhs then
return (← cases mvarId fvarId).map fun s => s.mvarId
throwError "'casesOnStuckLHS' failed"
where
findFVar? (e : Expr) : MetaM (Option FVarId) := do
match e with
| Expr.proj _ _ e _ => findFVar? e
| Expr.app .. =>
let f := e.getAppFn
if !f.isConst then
return none
else
let declName := f.constName!
let args := e.getAppArgs
match (← getProjectionFnInfo? declName) with
| some projInfo =>
if projInfo.numParams < args.size then
findFVar? args[projInfo.numParams]
else
return none
| none =>
matchConstRec e.getAppFn (fun _ => return none) fun recVal _ => do
if recVal.getMajorIdx >= args.size then
return none
let major := args[recVal.getMajorIdx]
if major.isFVar then
return some major.fvarId!
else
return none
| _ => return none
def casesOnStuckLHS? (mvarId : MVarId) : MetaM (Option (Array MVarId)) := do
try casesOnStuckLHS mvarId catch _ => return none
namespace Match
structure MatchEqns where
eqnNames : Array Name
splitterName : Name
splitterAltNumParams : Array Nat
deriving Inhabited, Repr
structure MatchEqnsExtState where
map : Std.PHashMap Name MatchEqns := {}
deriving Inhabited
/- We generate the equations and splitter on demand, and do not save them on .olean files. -/
builtin_initialize matchEqnsExt : EnvExtension MatchEqnsExtState ←
registerEnvExtension (pure {})
private def registerMatchEqns (matchDeclName : Name) (matchEqns : MatchEqns) : CoreM Unit :=
modifyEnv fun env => matchEqnsExt.modifyState env fun s => { s with map := s.map.insert matchDeclName matchEqns }
/-- Create a "unique" base name for conditional equations and splitter -/
private def mkBaseNameFor (env : Environment) (matchDeclName : Name) : Name :=
Lean.mkBaseNameFor env matchDeclName `splitter `_matchEqns
/--
Helper method. Recall that alternatives that do not have variables have a `Unit` parameter to ensure
they are not eagerly evaluated. -/
private def toFVarsRHSArgs (ys : Array Expr) (resultType : Expr) : MetaM (Array Expr × Array Expr) := do
if ys.size == 1 then
if (← inferType ys[0]).isConstOf ``Unit && !(← dependsOn resultType ys[0].fvarId!) then
return (#[], #[mkConst ``Unit.unit])
return (ys, ys)
/--
Simplify/filter hypotheses that ensure that a match alternative does not match the previous ones.
Remark: if there is no overlaping between the alternatives, the empty array is returned. -/
private partial def simpHs (hs : Array Expr) (numPatterns : Nat) : MetaM (Array Expr) := do
hs.filterMapM fun h => forallTelescope h fun ys _ => do
let xs := ys[:ys.size - numPatterns].toArray
let eqs ← ys[ys.size - numPatterns : ys.size].toArray.mapM inferType
if let some eqsNew ← simpEqs eqs *> get |>.run |>.run' #[] then
let newH ← eqsNew.foldrM (init := mkConst ``False) mkArrow
let xs ← xs.filterM fun x => dependsOn newH x.fvarId!
return some (← mkForallFVars xs newH)
else
none
where
simpEq (lhs : Expr) (rhs : Expr) : OptionT (StateRefT (Array Expr) MetaM) Unit := do
if isMatchValue lhs && isMatchValue rhs then
unless (← isDefEq lhs rhs) do
failure
else if rhs.isFVar then
-- Ignore case since it matches anything
pure ()
else match lhs.arrayLit?, rhs.arrayLit? with
| some (_, lhsArgs), some (_, rhsArgs) =>
if lhsArgs.length != rhsArgs.length then
failure
else
for lhsArg in lhsArgs, rhsArg in rhsArgs do
simpEq lhsArg rhsArg
| _, _ =>
match toCtorIfLit lhs |>.constructorApp? (← getEnv), toCtorIfLit rhs |>.constructorApp? (← getEnv) with
| some (lhsCtor, lhsArgs), some (rhsCtor, rhsArgs) =>
if lhsCtor.name == rhsCtor.name then
for lhsArg in lhsArgs[lhsCtor.numParams:], rhsArg in rhsArgs[lhsCtor.numParams:] do
simpEq lhsArg rhsArg
else
failure
| _, _ =>
let newEq ← mkEq lhs rhs
modify fun eqs => eqs.push newEq
simpEqs (eqs : Array Expr) : OptionT (StateRefT (Array Expr) MetaM) Unit := do
eqs.forM fun eq =>
match eq.eq? with
| some (_, lhs, rhs) => simpEq lhs rhs
| _ => throwError "failed to generate equality theorems for 'match', equality expected{indentExpr eq}"
/--
Helper method for proving a conditional equational theorem associated with an alternative of
the `match`-eliminator `matchDeclName`. `type` contains the type of the theorem. -/
partial def proveCondEqThm (matchDeclName : Name) (type : Expr) : MetaM Expr := do
let type ← instantiateMVars type
withLCtx {} {} <| forallTelescope type fun ys target => do
let mvar0 ← mkFreshExprSyntheticOpaqueMVar target
let mvarId ← deltaTarget mvar0.mvarId! (. == matchDeclName)
trace[Meta.Match.matchEqs] "{MessageData.ofGoal mvarId}"
go mvarId 0
mkLambdaFVars ys (← instantiateMVars mvar0)
where
go (mvarId : MVarId) (depth : Nat) : MetaM Unit := withIncRecDepth do
let mvarId' ← modifyTargetEqLHS mvarId whnfCore
let mvarId := mvarId'
let subgoals ←
(do applyRefl mvarId; return #[])
<|>
(do contradiction mvarId { genDiseq := true }; return #[])
<|>
(casesOnStuckLHS mvarId)
<|>
(do let mvarId' ← simpIfTarget mvarId (useDecide := true)
if mvarId' == mvarId then throwError "simpIf failed"
return #[mvarId'])
<|>
(do if let some (s₁, s₂) ← splitIfTarget? mvarId then
let mvarId₁ ← trySubst s₁.mvarId s₁.fvarId
return #[mvarId₁, s₂.mvarId]
else
throwError "spliIf failed")
<|>
(throwError "failed to generate equality theorems for `match` expression, support for array literals has not been implemented yet\n{MessageData.ofGoal mvarId}")
subgoals.forM (go . (depth+1))
/-- Construct new local declarations `xs` with types `altTypes`, and then execute `f xs` -/
private partial def withSplitterAlts (altTypes : Array Expr) (f : Array Expr → MetaM α) : MetaM α := do
let rec go (i : Nat) (xs : Array Expr) : MetaM α := do
if h : i < altTypes.size then
let hName := (`h).appendIndexAfter (i+1)
withLocalDeclD hName (altTypes.get ⟨i, h⟩) fun x =>
go (i+1) (xs.push x)
else
f xs
go 0 #[]
inductive InjectionAnyResult where
| solved
| failed
| subgoal (mvarId : MVarId)
private def injenctionAny (mvarId : MVarId) : MetaM InjectionAnyResult :=
withMVarContext mvarId do
for localDecl in (← getLCtx) do
if let some (_, lhs, rhs) ← matchEq? localDecl.type then
unless (← isDefEq lhs rhs) do
let lhs ← whnf lhs
let rhs ← whnf rhs
unless lhs.isNatLit && rhs.isNatLit do
try
match (← injection mvarId localDecl.fvarId) with
| InjectionResult.solved => return InjectionAnyResult.solved
| InjectionResult.subgoal mvarId .. => return InjectionAnyResult.subgoal mvarId
catch _ =>
pure ()
return InjectionAnyResult.failed
/--
Construct a proof for the splitter generated by `mkEquationsfor`.
The proof uses the definition of the `match`-declaration as a template (argument `template`).
- `alts` are free variables corresponding to alternatives of the `match` auxiliary declaration being processed.
- `altNews` are the new free variables which contains aditional hypotheses that ensure they are only used
when the previous overlapping alternatives are not applicable. -/
private partial def mkSplitterProof (matchDeclName : Name) (template : Expr) (alts altsNew : Array Expr) : MetaM Expr := do
trace[Meta.Match.matchEqs] "proof template: {template}"
let map := mkMap
let (proof, mvarIds) ← convertTemplate map |>.run #[]
trace[Meta.Match.matchEqs] "splitter proof: {proof}"
for mvarId in mvarIds do
proveSubgoal mvarId
instantiateMVars proof
where
mkMap : FVarIdMap Expr := Id.run <| do
let mut m := {}
for alt in alts, altNew in altsNew do
m := m.insert alt.fvarId! altNew
return m
convertTemplate (m : FVarIdMap Expr) : StateRefT (Array MVarId) MetaM Expr :=
transform template fun e => do
match e.getAppFn with
| Expr.fvar fvarId .. =>
match m.find? fvarId with
| some altNew =>
trace[Meta.Match.matchEqs] ">> {e}, {altNew}"
let eNew ←
if (← shouldCopyArgs e) then
addExtraParams (mkAppN altNew e.getAppArgs)
else
addExtraParams altNew
return TransformStep.done eNew
| none => return TransformStep.visit e
| _ => return TransformStep.visit e
shouldCopyArgs (e : Expr) : MetaM Bool := do
if e.getAppNumArgs == 1 then
match (← whnfD (← inferType e.appFn!)) with
| Expr.forallE _ d b _ =>
/- If result type does not depend on the argument, then
argument is an auxiliary unit used because Lean is an eager language, we should not copy it. -/
return b.hasLooseBVar 0
| _ => unreachable!
return true
addExtraParams (e : Expr) : StateRefT (Array MVarId) MetaM Expr := do
trace[Meta.Match.matchEqs] "addExtraParams {e}"
let (mvars, _, _) ← forallMetaTelescopeReducing (← inferType e) (kind := MetavarKind.syntheticOpaque)
modify fun s => s ++ (mvars.map (·.mvarId!))
return mkAppN e mvars
proveSubgoalLoop (mvarId : MVarId) : MetaM Unit := do
if (← contradictionCore mvarId {}) then
return ()
match (← injenctionAny mvarId) with
| InjectionAnyResult.solved => return ()
| InjectionAnyResult.failed => throwError "failed to generate splitter for match auxiliary declaration '{matchDeclName}', unsolved subgoal:\n{MessageData.ofGoal mvarId}"
| InjectionAnyResult.subgoal mvarId => proveSubgoalLoop mvarId
proveSubgoal (mvarId : MVarId) : MetaM Unit := do
trace[Meta.Match.matchEqs] "subgoal {mkMVar mvarId}, {repr (← getMVarDecl mvarId).kind}, {← isExprMVarAssigned mvarId}\n{MessageData.ofGoal mvarId}"
let (_, mvarId) ← intros mvarId
let mvarId ← tryClearMany mvarId (alts.map (·.fvarId!))
proveSubgoalLoop mvarId
/--
Create conditional equations and splitter for the given match auxiliary declaration. -/
private partial def mkEquationsFor (matchDeclName : Name) : MetaM MatchEqns :=
withConfig (fun c => { c with etaStruct := false }) do
let baseName := mkBaseNameFor (← getEnv) matchDeclName
let constInfo ← getConstInfo matchDeclName
let us := constInfo.levelParams.map mkLevelParam
let some matchInfo ← getMatcherInfo? matchDeclName | throwError "'{matchDeclName}' is not a matcher function"
forallTelescopeReducing constInfo.type fun xs matchResultType => do
let mut eqnNames := #[]
let params := xs[:matchInfo.numParams]
let motive := xs[matchInfo.getMotivePos]
let alts := xs[xs.size - matchInfo.numAlts:]
let firstDiscrIdx := matchInfo.numParams + 1
let discrs := xs[firstDiscrIdx : firstDiscrIdx + matchInfo.numDiscrs]
let mut notAlts := #[]
let mut idx := 1
let mut splitterAltTypes := #[]
let mut splitterAltNumParams := #[]
for alt in alts do
let thmName := baseName ++ ((`eq).appendIndexAfter idx)
eqnNames := eqnNames.push thmName
let altType ← inferType alt
let (notAlt, splitterAltType, splitterAltNumParam) ← forallTelescopeReducing altType fun ys altResultType => do
let (ys, rhsArgs) ← toFVarsRHSArgs ys altResultType
let patterns := altResultType.getAppArgs
let mut hs := #[]
for notAlt in notAlts do
hs := hs.push (← instantiateForall notAlt patterns)
hs ← simpHs hs patterns.size
trace[Meta.Match.matchEqs] "hs: {hs}"
let splitterAltType ← mkForallFVars ys (← hs.foldrM (init := altResultType) mkArrow)
let splitterAltNumParam := hs.size + ys.size
-- Create a proposition for representing terms that do not match `patterns`
let mut notAlt := mkConst ``False
for discr in discrs.toArray.reverse, pattern in patterns.reverse do
notAlt ← mkArrow (← mkEq discr pattern) notAlt
notAlt ← mkForallFVars (discrs ++ ys) notAlt
let lhs := mkAppN (mkConst constInfo.name us) (params ++ #[motive] ++ patterns ++ alts)
let rhs := mkAppN alt rhsArgs
let thmType ← mkEq lhs rhs
let thmType ← hs.foldrM (init := thmType) mkArrow
let thmType ← mkForallFVars (params ++ #[motive] ++ alts ++ ys) thmType
let thmVal ← proveCondEqThm matchDeclName thmType
addDecl <| Declaration.thmDecl {
name := thmName
levelParams := constInfo.levelParams
type := thmType
value := thmVal
}
return (notAlt, splitterAltType, splitterAltNumParam)
notAlts := notAlts.push notAlt
splitterAltTypes := splitterAltTypes.push splitterAltType
splitterAltNumParams := splitterAltNumParams.push splitterAltNumParam
trace[Meta.Match.matchEqs] "splitterAltType: {splitterAltType}"
idx := idx + 1
-- Define splitter with conditional/refined alternatives
withSplitterAlts splitterAltTypes fun altsNew => do
let splitterParams := params.toArray ++ #[motive] ++ discrs.toArray ++ altsNew
let splitterType ← mkForallFVars splitterParams matchResultType
trace[Meta.Match.matchEqs] "splitterType: {splitterType}"
let template ← mkAppN (mkConst constInfo.name us) (params ++ #[motive] ++ discrs ++ alts)
let template ← deltaExpand template (. == constInfo.name)
let splitterVal ← mkLambdaFVars splitterParams (← mkSplitterProof matchDeclName template alts altsNew)
let splitterName := baseName ++ `splitter
addDecl <| Declaration.thmDecl {
name := splitterName
levelParams := constInfo.levelParams
type := splitterType
value := splitterVal
}
let result := { eqnNames, splitterName, splitterAltNumParams }
registerMatchEqns matchDeclName result
return result
def getEquationsFor (matchDeclName : Name) : MetaM MatchEqns := do
match matchEqnsExt.getState (← getEnv) |>.map.find? matchDeclName with
| some matchEqns => return matchEqns
| none => mkEquationsFor matchDeclName
builtin_initialize registerTraceClass `Meta.Match.matchEqs
end Lean.Meta.Match
|
bc82e487ce8b779f5b2fbae07e2c4479015629ab | 12dabd587ce2621d9a4eff9f16e354d02e206c8e | /world03/level04.lean | 56bbce0794dd83e7d27b2a6b83633d84bf627673 | [] | no_license | abdelq/natural-number-game | a1b5b8f1d52625a7addcefc97c966d3f06a48263 | bbddadc6d2e78ece2e9acd40fa7702ecc2db75c2 | refs/heads/master | 1,668,606,478,691 | 1,594,175,058,000 | 1,594,175,058,000 | 278,673,209 | 0 | 1 | null | null | null | null | UTF-8 | Lean | false | false | 207 | lean | lemma mul_add (t a b : mynat) : t * (a + b) = t * a + t * b :=
begin
induction b with h hd,
rw mul_zero,
rw add_zero,
rw add_zero,
refl,
rw add_succ,
rw mul_succ,
rw hd,
rw mul_succ,
rw add_assoc,
refl,
end
|
9ad29302564f4736ba72f3e5b03259746fbb9330 | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/linear_algebra/bilinear_map.lean | 164757c87cb16595dfcefb780dc75dd75f78f8b6 | [
"Apache-2.0"
] | permissive | leanprover-community/mathlib | 56a2cadd17ac88caf4ece0a775932fa26327ba0e | 442a83d738cb208d3600056c489be16900ba701d | refs/heads/master | 1,693,584,102,358 | 1,693,471,902,000 | 1,693,471,902,000 | 97,922,418 | 1,595 | 352 | Apache-2.0 | 1,694,693,445,000 | 1,500,624,130,000 | Lean | UTF-8 | Lean | false | false | 14,871 | 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 linear_algebra.basic
/-!
# Basics on bilinear maps
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
This file provides basics on bilinear maps. The most general form considered are maps that are
semilinear in both arguments. They are of type `M →ₛₗ[ρ₁₂] N →ₛₗ[σ₁₂] P`, where `M` and `N`
are modules over `R` and `S` respectively, `P` is a module over both `R₂` and `S₂` with
commuting actions, and `ρ₁₂ : R →+* R₂` and `σ₁₂ : S →+* S₂`.
## Main declarations
* `linear_map.mk₂`: a constructor for bilinear maps,
taking an unbundled function together with proof witnesses of bilinearity
* `linear_map.flip`: turns a bilinear map `M × N → P` into `N × M → P`
* `linear_map.lcomp` and `linear_map.llcomp`: composition of linear maps as a bilinear map
* `linear_map.compl₂`: composition of a bilinear map `M × N → P` with a linear map `Q → M`
* `linear_map.compr₂`: composition of a bilinear map `M × N → P` with a linear map `Q → N`
* `linear_map.lsmul`: scalar multiplication as a bilinear map `R × M → M`
## Tags
bilinear
-/
namespace linear_map
section semiring
-- the `ₗ` subscript variables are for special cases about linear (as opposed to semilinear) maps
variables {R : Type*} [semiring R] {S : Type*} [semiring S]
variables {R₂ : Type*} [semiring R₂] {S₂ : Type*} [semiring S₂]
variables {M : Type*} {N : Type*} {P : Type*}
variables {M₂ : Type*} {N₂ : Type*} {P₂ : Type*}
variables {Nₗ : Type*} {Pₗ : Type*}
variables {M' : Type*} {N' : Type*} {P' : Type*}
variables [add_comm_monoid M] [add_comm_monoid N] [add_comm_monoid P]
variables [add_comm_monoid M₂] [add_comm_monoid N₂] [add_comm_monoid P₂]
variables [add_comm_monoid Nₗ] [add_comm_monoid Pₗ]
variables [add_comm_group M'] [add_comm_group N'] [add_comm_group P']
variables [module R M] [module S N] [module R₂ P] [module S₂ P]
variables [module R M₂] [module S N₂] [module R P₂] [module S₂ P₂]
variables [module R Pₗ] [module S Pₗ]
variables [module R M'] [module S N'] [module R₂ P'] [module S₂ P']
variables [smul_comm_class S₂ R₂ P] [smul_comm_class S R Pₗ] [smul_comm_class S₂ R₂ P']
variables [smul_comm_class S₂ R P₂]
variables {ρ₁₂ : R →+* R₂} {σ₁₂ : S →+* S₂}
variables (ρ₁₂ σ₁₂)
/-- Create a bilinear map from a function that is semilinear in each component.
See `mk₂'` and `mk₂` for the linear case. -/
def mk₂'ₛₗ (f : M → N → P)
(H1 : ∀ m₁ m₂ n, f (m₁ + m₂) n = f m₁ n + f m₂ n)
(H2 : ∀ (c:R) m n, f (c • m) n = (ρ₁₂ c) • f m n)
(H3 : ∀ m n₁ n₂, f m (n₁ + n₂) = f m n₁ + f m n₂)
(H4 : ∀ (c:S) m n, f m (c • n) = (σ₁₂ c) • f m n) : M →ₛₗ[ρ₁₂] N →ₛₗ[σ₁₂] P :=
{ to_fun := λ m, { to_fun := f m, map_add' := H3 m, map_smul' := λ c, H4 c m},
map_add' := λ m₁ m₂, linear_map.ext $ H1 m₁ m₂,
map_smul' := λ c m, linear_map.ext $ H2 c m }
variables {ρ₁₂ σ₁₂}
@[simp] theorem mk₂'ₛₗ_apply
(f : M → N → P) {H1 H2 H3 H4} (m : M) (n : N) :
(mk₂'ₛₗ ρ₁₂ σ₁₂ f H1 H2 H3 H4 : M →ₛₗ[ρ₁₂] N →ₛₗ[σ₁₂] P) m n = f m n := rfl
variables (R S)
/-- Create a bilinear map from a function that is linear in each component.
See `mk₂` for the special case where both arguments come from modules over the same ring. -/
def mk₂' (f : M → N → Pₗ)
(H1 : ∀ m₁ m₂ n, f (m₁ + m₂) n = f m₁ n + f m₂ n)
(H2 : ∀ (c:R) m n, f (c • m) n = c • f m n)
(H3 : ∀ m n₁ n₂, f m (n₁ + n₂) = f m n₁ + f m n₂)
(H4 : ∀ (c:S) m n, f m (c • n) = c • f m n) : M →ₗ[R] N →ₗ[S] Pₗ :=
mk₂'ₛₗ (ring_hom.id R) (ring_hom.id S) f H1 H2 H3 H4
variables {R S}
@[simp] theorem mk₂'_apply
(f : M → N → Pₗ) {H1 H2 H3 H4} (m : M) (n : N) :
(mk₂' R S f H1 H2 H3 H4 : M →ₗ[R] N →ₗ[S] Pₗ) m n = f m n := rfl
theorem ext₂ {f g : M →ₛₗ[ρ₁₂] N →ₛₗ[σ₁₂] P}
(H : ∀ m n, f m n = g m n) : f = g :=
linear_map.ext (λ m, linear_map.ext $ λ n, H m n)
lemma congr_fun₂ {f g : M →ₛₗ[ρ₁₂] N →ₛₗ[σ₁₂] P} (h : f = g) (x y) : f x y = g x y :=
linear_map.congr_fun (linear_map.congr_fun h x) y
section
local attribute [instance] smul_comm_class.symm
/-- Given a linear map from `M` to linear maps from `N` to `P`, i.e., a bilinear map from `M × N` to
`P`, change the order of variables and get a linear map from `N` to linear maps from `M` to `P`. -/
def flip (f : M →ₛₗ[ρ₁₂] N →ₛₗ[σ₁₂] P) : N →ₛₗ[σ₁₂] M →ₛₗ[ρ₁₂] P :=
mk₂'ₛₗ σ₁₂ ρ₁₂ (λ n m, f m n)
(λ n₁ n₂ m, (f m).map_add _ _)
(λ c n m, (f m).map_smulₛₗ _ _)
(λ n m₁ m₂, by rw f.map_add; refl)
(λ c n m, by rw f.map_smulₛₗ; refl)
end
@[simp] theorem flip_apply (f : M →ₛₗ[ρ₁₂] N →ₛₗ[σ₁₂] P) (m : M) (n : N) : flip f n m = f m n := rfl
@[simp] lemma flip_flip [smul_comm_class R₂ S₂ P] (f : M →ₛₗ[ρ₁₂] N →ₛₗ[σ₁₂] P) :
f.flip.flip = f := linear_map.ext₂ (λ x y, ((f.flip).flip_apply _ _).trans (f.flip_apply _ _))
open_locale big_operators
variables {R}
theorem flip_inj {f g : M →ₛₗ[ρ₁₂] N →ₛₗ[σ₁₂] P} (H : flip f = flip g) : f = g :=
ext₂ $ λ m n, show flip f n m = flip g n m, by rw H
theorem map_zero₂ (f : M →ₛₗ[ρ₁₂] N →ₛₗ[σ₁₂] P) (y) : f 0 y = 0 :=
(flip f y).map_zero
theorem map_neg₂ (f : M' →ₛₗ[ρ₁₂] N →ₛₗ[σ₁₂] P') (x y) : f (-x) y = -f x y :=
(flip f y).map_neg _
theorem map_sub₂ (f : M' →ₛₗ[ρ₁₂] N →ₛₗ[σ₁₂] P') (x y z) : f (x - y) z = f x z - f y z :=
(flip f z).map_sub _ _
theorem map_add₂ (f : M →ₛₗ[ρ₁₂] N →ₛₗ[σ₁₂] P) (x₁ x₂ y) : f (x₁ + x₂) y = f x₁ y + f x₂ y :=
(flip f y).map_add _ _
theorem map_smul₂ (f : M₂ →ₗ[R] N₂ →ₛₗ[σ₁₂] P₂) (r : R) (x y) : f (r • x) y = r • f x y :=
(flip f y).map_smul _ _
theorem map_smulₛₗ₂ (f : M →ₛₗ[ρ₁₂] N →ₛₗ[σ₁₂] P) (r : R) (x y) : f (r • x) y = (ρ₁₂ r) • f x y :=
(flip f y).map_smulₛₗ _ _
theorem map_sum₂ {ι : Type*} (f : M →ₛₗ[ρ₁₂] N →ₛₗ[σ₁₂] P) (t : finset ι) (x : ι → M) (y) :
f (∑ i in t, x i) y = ∑ i in t, f (x i) y :=
(flip f y).map_sum
/-- Restricting a bilinear map in the second entry -/
def dom_restrict₂ (f : M →ₛₗ[ρ₁₂] N →ₛₗ[σ₁₂] P) (q : submodule S N) :
M →ₛₗ[ρ₁₂] q →ₛₗ[σ₁₂] P :=
{ to_fun := λ m, (f m).dom_restrict q,
map_add' := λ m₁ m₂, linear_map.ext $ λ _, by simp only [map_add, dom_restrict_apply, add_apply],
map_smul' := λ c m, linear_map.ext $ λ _, by simp only [f.map_smulₛₗ, dom_restrict_apply,
smul_apply]}
lemma dom_restrict₂_apply (f : M →ₛₗ[ρ₁₂] N →ₛₗ[σ₁₂] P) (q : submodule S N) (x : M) (y : q) :
f.dom_restrict₂ q x y = f x y := rfl
/-- Restricting a bilinear map in both components -/
def dom_restrict₁₂ (f : M →ₛₗ[ρ₁₂] N →ₛₗ[σ₁₂] P) (p : submodule R M) (q : submodule S N) :
p →ₛₗ[ρ₁₂] q →ₛₗ[σ₁₂] P := (f.dom_restrict p).dom_restrict₂ q
lemma dom_restrict₁₂_apply (f : M →ₛₗ[ρ₁₂] N →ₛₗ[σ₁₂] P) (p : submodule R M) (q : submodule S N)
(x : p) (y : q) : f.dom_restrict₁₂ p q x y = f x y := rfl
end semiring
section comm_semiring
variables {R : Type*} [comm_semiring R] {R₂ : Type*} [comm_semiring R₂]
variables {R₃ : Type*} [comm_semiring R₃] {R₄ : Type*} [comm_semiring R₄]
variables {M : Type*} {N : Type*} {P : Type*} {Q : Type*}
variables {Mₗ : Type*} {Nₗ : Type*} {Pₗ : Type*} {Qₗ Qₗ': Type*}
variables [add_comm_monoid M] [add_comm_monoid N] [add_comm_monoid P] [add_comm_monoid Q]
variables [add_comm_monoid Mₗ] [add_comm_monoid Nₗ] [add_comm_monoid Pₗ]
variables [add_comm_monoid Qₗ] [add_comm_monoid Qₗ']
variables [module R M] [module R₂ N] [module R₃ P] [module R₄ Q]
variables [module R Mₗ] [module R Nₗ] [module R Pₗ] [module R Qₗ] [module R Qₗ']
variables {σ₁₂ : R →+* R₂} {σ₂₃ : R₂ →+* R₃} {σ₁₃ : R →+* R₃}
variables {σ₄₂ : R₄ →+* R₂} {σ₄₃ : R₄ →+* R₃}
variables [ring_hom_comp_triple σ₁₂ σ₂₃ σ₁₃] [ring_hom_comp_triple σ₄₂ σ₂₃ σ₄₃]
variables (R)
/-- Create a bilinear map from a function that is linear in each component.
This is a shorthand for `mk₂'` for the common case when `R = S`. -/
def mk₂ (f : M → Nₗ → Pₗ)
(H1 : ∀ m₁ m₂ n, f (m₁ + m₂) n = f m₁ n + f m₂ n)
(H2 : ∀ (c:R) m n, f (c • m) n = c • f m n)
(H3 : ∀ m n₁ n₂, f m (n₁ + n₂) = f m n₁ + f m n₂)
(H4 : ∀ (c:R) m n, f m (c • n) = c • f m n) : M →ₗ[R] Nₗ →ₗ[R] Pₗ :=
mk₂' R R f H1 H2 H3 H4
@[simp] theorem mk₂_apply
(f : M → Nₗ → Pₗ) {H1 H2 H3 H4} (m : M) (n : Nₗ) :
(mk₂ R f H1 H2 H3 H4 : M →ₗ[R] Nₗ →ₗ[R] Pₗ) m n = f m n := rfl
variables (R M N P)
/-- Given a linear map from `M` to linear maps from `N` to `P`, i.e., a bilinear map `M → N → P`,
change the order of variables and get a linear map from `N` to linear maps from `M` to `P`. -/
def lflip : (M →ₛₗ[σ₁₃] N →ₛₗ[σ₂₃] P) →ₗ[R₃] N →ₛₗ[σ₂₃] M →ₛₗ[σ₁₃] P :=
{ to_fun := flip, map_add' := λ _ _, rfl, map_smul' := λ _ _, rfl }
variables {R M N P}
variables (f : M →ₛₗ[σ₁₃] N →ₛₗ[σ₂₃] P)
@[simp] theorem lflip_apply (m : M) (n : N) : lflip R M N P f n m = f m n := rfl
variables (R Pₗ)
/-- Composing a linear map `M → N` and a linear map `N → P` to form a linear map `M → P`. -/
def lcomp (f : M →ₗ[R] Nₗ) : (Nₗ →ₗ[R] Pₗ) →ₗ[R] M →ₗ[R] Pₗ :=
flip $ linear_map.comp (flip id) f
variables {R Pₗ}
@[simp] theorem lcomp_apply (f : M →ₗ[R] Nₗ) (g : Nₗ →ₗ[R] Pₗ) (x : M) :
lcomp R Pₗ f g x = g (f x) := rfl
theorem lcomp_apply' (f : M →ₗ[R] Nₗ) (g : Nₗ →ₗ[R] Pₗ) :
lcomp R Pₗ f g = g ∘ₗ f := rfl
variables (P σ₂₃)
/-- Composing a semilinear map `M → N` and a semilinear map `N → P` to form a semilinear map
`M → P` is itself a linear map. -/
def lcompₛₗ (f : M →ₛₗ[σ₁₂] N) : (N →ₛₗ[σ₂₃] P) →ₗ[R₃] M →ₛₗ[σ₁₃] P :=
flip $ linear_map.comp (flip id) f
variables {P σ₂₃}
include σ₁₃
@[simp] theorem lcompₛₗ_apply (f : M →ₛₗ[σ₁₂] N) (g : N →ₛₗ[σ₂₃] P) (x : M) :
lcompₛₗ P σ₂₃ f g x = g (f x) := rfl
omit σ₁₃
variables (R M Nₗ Pₗ)
/-- Composing a linear map `M → N` and a linear map `N → P` to form a linear map `M → P`. -/
def llcomp : (Nₗ →ₗ[R] Pₗ) →ₗ[R] (M →ₗ[R] Nₗ) →ₗ[R] M →ₗ[R] Pₗ :=
flip { to_fun := lcomp R Pₗ,
map_add' := λ f f', ext₂ $ λ g x, g.map_add _ _,
map_smul' := λ (c : R) f, ext₂ $ λ g x, g.map_smul _ _ }
variables {R M Nₗ Pₗ}
section
@[simp] theorem llcomp_apply (f : Nₗ →ₗ[R] Pₗ) (g : M →ₗ[R] Nₗ) (x : M) :
llcomp R M Nₗ Pₗ f g x = f (g x) := rfl
theorem llcomp_apply' (f : Nₗ →ₗ[R] Pₗ) (g : M →ₗ[R] Nₗ) :
llcomp R M Nₗ Pₗ f g = f ∘ₗ g := rfl
end
/-- Composing a linear map `Q → N` and a bilinear map `M → N → P` to
form a bilinear map `M → Q → P`. -/
def compl₂ (g : Q →ₛₗ[σ₄₂] N) : M →ₛₗ[σ₁₃] Q →ₛₗ[σ₄₃] P := (lcompₛₗ _ _ g).comp f
include σ₄₃
@[simp] theorem compl₂_apply (g : Q →ₛₗ[σ₄₂] N) (m : M) (q : Q) :
f.compl₂ g m q = f m (g q) := rfl
omit σ₄₃
@[simp] theorem compl₂_id : f.compl₂ linear_map.id = f :=
by { ext, rw [compl₂_apply, id_coe, id.def] }
/-- Composing linear maps `Q → M` and `Q' → N` with a bilinear map `M → N → P` to
form a bilinear map `Q → Q' → P`. -/
def compl₁₂ (f : Mₗ →ₗ[R] Nₗ →ₗ[R] Pₗ) (g : Qₗ →ₗ[R] Mₗ) (g' : Qₗ' →ₗ[R] Nₗ) :
Qₗ →ₗ[R] Qₗ' →ₗ[R] Pₗ :=
(f.comp g).compl₂ g'
@[simp] theorem compl₁₂_apply (f : Mₗ →ₗ[R] Nₗ →ₗ[R] Pₗ) (g : Qₗ →ₗ[R] Mₗ) (g' : Qₗ' →ₗ[R] Nₗ)
(x : Qₗ) (y : Qₗ') : f.compl₁₂ g g' x y = f (g x) (g' y) := rfl
@[simp] theorem compl₁₂_id_id (f : Mₗ →ₗ[R] Nₗ →ₗ[R] Pₗ) :
f.compl₁₂ (linear_map.id) (linear_map.id) = f :=
by { ext, simp_rw [compl₁₂_apply, id_coe, id.def] }
lemma compl₁₂_inj {f₁ f₂ : Mₗ →ₗ[R] Nₗ →ₗ[R] Pₗ} {g : Qₗ →ₗ[R] Mₗ} {g' : Qₗ' →ₗ[R] Nₗ}
(hₗ : function.surjective g) (hᵣ : function.surjective g') :
f₁.compl₁₂ g g' = f₂.compl₁₂ g g' ↔ f₁ = f₂ :=
begin
split; intros h,
{ -- B₁.comp l r = B₂.comp l r → B₁ = B₂
ext x y,
cases hₗ x with x' hx, subst hx,
cases hᵣ y with y' hy, subst hy,
convert linear_map.congr_fun₂ h x' y' },
{ -- B₁ = B₂ → B₁.comp l r = B₂.comp l r
subst h },
end
/-- Composing a linear map `P → Q` and a bilinear map `M → N → P` to
form a bilinear map `M → N → Q`. -/
def compr₂ (f : M →ₗ[R] Nₗ →ₗ[R] Pₗ) (g : Pₗ →ₗ[R] Qₗ) : M →ₗ[R] Nₗ →ₗ[R] Qₗ :=
(llcomp R Nₗ Pₗ Qₗ g) ∘ₗ f
@[simp] theorem compr₂_apply (f : M →ₗ[R] Nₗ →ₗ[R] Pₗ) (g : Pₗ →ₗ[R] Qₗ) (m : M) (n : Nₗ) :
f.compr₂ g m n = g (f m n) := rfl
variables (R M)
/-- Scalar multiplication as a bilinear map `R → M → M`. -/
def lsmul : R →ₗ[R] M →ₗ[R] M :=
mk₂ R (•) add_smul (λ _ _ _, mul_smul _ _ _) smul_add
(λ r s m, by simp only [smul_smul, smul_eq_mul, mul_comm])
variables {R M}
@[simp] theorem lsmul_apply (r : R) (m : M) : lsmul R M r m = r • m := rfl
end comm_semiring
section comm_ring
variables {R R₂ S S₂ M N P : Type*}
variables {Mₗ Nₗ Pₗ : Type*}
variables [comm_ring R] [comm_ring S] [comm_ring R₂] [comm_ring S₂]
section add_comm_group
variables [add_comm_group M] [add_comm_group N] [add_comm_group P]
variables [module R M] [module S N] [module R₂ P] [module S₂ P]
lemma lsmul_injective [no_zero_smul_divisors R M] {x : R} (hx : x ≠ 0) :
function.injective (lsmul R M x) :=
smul_right_injective _ hx
lemma ker_lsmul [no_zero_smul_divisors R M] {a : R} (ha : a ≠ 0) :
(linear_map.lsmul R M a).ker = ⊥ :=
linear_map.ker_eq_bot_of_injective (linear_map.lsmul_injective ha)
end add_comm_group
end comm_ring
end linear_map
|
33cb76c583d332dc603721b4ed9513515aaede86 | df561f413cfe0a88b1056655515399c546ff32a5 | /2-addition-world/l5.lean | b130ef51907dd66a2579f3b3da919786157b9cd0 | [] | no_license | nicholaspun/natural-number-game-solutions | 31d5158415c6f582694680044c5c6469032c2a06 | 1e2aed86d2e76a3f4a275c6d99e795ad30cf6df0 | refs/heads/main | 1,675,123,625,012 | 1,607,633,548,000 | 1,607,633,548,000 | 318,933,860 | 3 | 1 | null | null | null | null | UTF-8 | Lean | false | false | 118 | lean | theorem succ_eq_add_one (n : mynat) : succ n = n + 1 :=
begin
rw one_eq_succ_zero, rw add_succ, rw add_zero, refl,
end |
63bb47ac39dff8213c30040b4734294e9ea0084f | 31f556cdeb9239ffc2fad8f905e33987ff4feab9 | /src/Lean/Compiler/LCNF/InferType.lean | a9714d5f9fa9caefc82e2a36408e03697079a445 | [
"Apache-2.0",
"LLVM-exception",
"NCSA",
"LGPL-3.0-only",
"LicenseRef-scancode-inner-net-2.0",
"BSD-3-Clause",
"LGPL-2.0-or-later",
"Spencer-94",
"LGPL-2.1-or-later",
"HPND",
"LicenseRef-scancode-pcre",
"ISC",
"LGPL-2.1-only",
"LicenseRef-scancode-other-permissive",
"SunPro",
"CMU-Mach"... | permissive | tobiasgrosser/lean4 | ce0fd9cca0feba1100656679bf41f0bffdbabb71 | ebdbdc10436a4d9d6b66acf78aae7a23f5bd073f | refs/heads/master | 1,673,103,412,948 | 1,664,930,501,000 | 1,664,930,501,000 | 186,870,185 | 0 | 0 | Apache-2.0 | 1,665,129,237,000 | 1,557,939,901,000 | Lean | UTF-8 | Lean | false | false | 16,478 | lean | /-
Copyright (c) 2022 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
import Lean.Compiler.LCNF.CompilerM
import Lean.Compiler.LCNF.Types
import Lean.Compiler.LCNF.PhaseExt
import Lean.Compiler.LCNF.OtherDecl
namespace Lean.Compiler.LCNF
/-! # Type inference for LCNF -/
/-
Note about **erasure confusion**.
1- After instantiating universe polymorphic code, we may have
some types that become propositions, and all propositions are erased.
For example, suppose we have
```
def f (α : Sort u) (x : α → α → Sort v) (a b : α) (h : x a b) ...
```
The LCNF type for this universe polymorphic declaration is
```
def f (α : Sort u) (x : α → α → Sort v) (a b : α) (h : x ◾ ◾) ...
```
Now, if we instantiate with `v` with the universe `0`, we have that `x ◾ ◾` is also a proposition
and should be erased.
2- We may also get "erasure confusion" when instantiating
polymorphic code with types and type formers. For example, suppose we have
```
structure S (α : Type u) (β : Type v) (f : α → β) where
a : α
b : β := f a
```
The LCNF type for `S.mk` is
```
S.mk : {α : Type u} → {β : Type v} → {f : α → β} → α → β → S α β ◾
```
Note that `f` was erased from the resulting type `S α β ◾` because it is
not a type former. Now, suppose we have the valid Lean declaration
```
def f : S Nat Type (fun _ => Nat) :=
S.mk 0 Nat
```
The LNCF type for the value `S.mk 0 Nat` is `S Nat Type ◾` (see `S.mk` type above),
but the expected type is `S Nat Type (fun x => Nat)`. `fun x => Nat` is not erased
here because it is a type former.
-/
namespace InferType
/-
Type inference algorithm for LCNF. Invoked by the LCNF type checker
to check correctness of LCNF IR.
-/
/--
We use a regular local context to store temporary local declarations
created during type inference.
-/
abbrev InferTypeM := ReaderT LocalContext CompilerM
def getBinderName (fvarId : FVarId) : InferTypeM Name := do
match (← read).find? fvarId with
| some localDecl => return localDecl.userName
| none => LCNF.getBinderName fvarId
def getType (fvarId : FVarId) : InferTypeM Expr := do
match (← read).find? fvarId with
| some localDecl => return localDecl.type
| none => LCNF.getType fvarId
def mkForallFVars (xs : Array Expr) (type : Expr) : InferTypeM Expr :=
let b := type.abstract xs
xs.size.foldRevM (init := b) fun i b => do
let x := xs[i]!
let n ← InferType.getBinderName x.fvarId!
let ty ← InferType.getType x.fvarId!
let ty := ty.abstractRange i xs;
return .forallE n ty b .default
def mkForallParams (params : Array Param) (type : Expr) : InferTypeM Expr :=
let xs := params.map fun p => .fvar p.fvarId
mkForallFVars xs type |>.run {}
@[inline] def withLocalDecl (binderName : Name) (type : Expr) (binderInfo : BinderInfo) (k : Expr → InferTypeM α) : InferTypeM α := do
let fvarId ← mkFreshFVarId
withReader (fun lctx => lctx.mkLocalDecl fvarId binderName type binderInfo) do
k (.fvar fvarId)
def inferConstType (declName : Name) (us : List Level) : CompilerM Expr := do
if declName == ``lcAny || declName == ``lcErased then
return anyTypeExpr
else if let some decl ← getDecl? declName then
return decl.instantiateTypeLevelParams us
else
/- Declaration does not have code associated with it: constructor, inductive type, foreign function -/
getOtherDeclType declName us
mutual
partial def inferType (e : Expr) : InferTypeM Expr :=
match e with
| .const c us => inferConstType c us
| .proj n i s => inferProjType n i s
| .app .. => inferAppType e
| .mvar .. => throwError "unexpected metavariable {e}"
| .fvar fvarId => InferType.getType fvarId
| .bvar .. => throwError "unexpected bound variable {e}"
| .mdata _ e => inferType e
| .lit v => return v.type
| .sort lvl => return .sort (mkLevelSucc lvl)
| .forallE .. => inferForallType e
| .lam .. => inferLambdaType e
| .letE .. => inferLambdaType e
partial def inferAppTypeCore (f : Expr) (args : Array Expr) : InferTypeM Expr := do
let mut j := 0
let mut fType ← inferType f
for i in [:args.size] do
fType := fType.headBeta
match fType with
| .forallE _ _ b _ => fType := b
| _ =>
fType := fType.instantiateRevRange j i args |>.headBeta
match fType with
| .forallE _ _ b _ => j := i; fType := b
| _ =>
if fType.isAnyType then return anyTypeExpr
throwError "function expected{indentExpr (mkAppN f args[:i])} : {fType}\nfunction type{indentExpr (← inferType f)}"
return fType.instantiateRevRange j args.size args |>.headBeta
partial def inferAppType (e : Expr) : InferTypeM Expr := do
inferAppTypeCore e.getAppFn e.getAppArgs
partial def inferProjType (structName : Name) (idx : Nat) (s : Expr) : InferTypeM Expr := do
let failed {α} : Unit → InferTypeM α := fun _ =>
throwError "invalid projection{indentExpr (mkProj structName idx s)}"
let structType := (← inferType s).headBeta
if structType.isAnyType then
/- TODO: after we erase universe variables, we can just extract a better type using just `structName` and `idx`. -/
return anyTypeExpr
else
matchConstStruct structType.getAppFn failed fun structVal structLvls ctorVal =>
let n := structVal.numParams
let structParams := structType.getAppArgs
if n != structParams.size then
failed ()
else do
let mut ctorType ← inferAppType (mkAppN (mkConst ctorVal.name structLvls) structParams)
for _ in [:idx] do
match ctorType with
| .forallE _ _ body _ =>
if body.hasLooseBVars then
-- This can happen when one of the fields is a type or type former.
ctorType := body.instantiate1 anyTypeExpr
else
ctorType := body
| _ =>
if ctorType.isAnyType then return anyTypeExpr
failed ()
match ctorType with
| .forallE _ d _ _ => return d
| _ =>
if ctorType.isAnyType then return anyTypeExpr
failed ()
partial def getLevel? (type : Expr) : InferTypeM (Option Level) := do
match (← inferType type) with
| .sort u => return some u
| e =>
if e.isAnyType then
return none
else
throwError "type expected{indentExpr type}"
partial def inferForallType (e : Expr) : InferTypeM Expr :=
go e #[]
where
go (e : Expr) (fvars : Array Expr) : InferTypeM Expr := do
match e with
| .forallE n d b bi =>
withLocalDecl n (d.instantiateRev fvars) bi fun fvar =>
go b (fvars.push fvar)
| _ =>
let e := e.instantiateRev fvars
let some u ← getLevel? e | return anyTypeExpr
let mut u := u
for x in fvars.reverse do
let xType ← inferType x
let some v ← getLevel? xType | return anyTypeExpr
u := mkLevelIMax' v u
return .sort u.normalize
partial def inferLambdaType (e : Expr) : InferTypeM Expr :=
go e #[] #[]
where
go (e : Expr) (fvars : Array Expr) (all : Array Expr) : InferTypeM Expr := do
match e with
| .lam n d b bi =>
withLocalDecl n (d.instantiateRev all) bi fun fvar => go b (fvars.push fvar) (all.push fvar)
| .letE n t _ b _ =>
withLocalDecl n (t.instantiateRev all) .default fun fvar => go b fvars (all.push fvar)
| e =>
let type ← inferType (e.instantiateRev all)
mkForallFVars fvars type
end
end InferType
def inferType (e : Expr) : CompilerM Expr :=
InferType.inferType e |>.run {}
def getLevel (type : Expr) : CompilerM Level := do
match (← inferType type) with
| .sort u => return u
| e => if e.isAnyType then return levelOne else throwError "type expected{indentExpr type}"
/-- Create `lcCast expectedType e : expectedType` -/
def mkLcCast (e : Expr) (expectedType : Expr) : CompilerM Expr := do
let type ← inferType e
let u ← getLevel type
let v ← getLevel expectedType
return mkApp3 (.const ``lcCast [u, v]) type expectedType e
def Code.inferType (code : Code) : CompilerM Expr := do
match code with
| .let _ k | .fun _ k | .jp _ k => k.inferType
| .return fvarId => getType fvarId
| .jmp fvarId args => InferType.inferAppTypeCore (.fvar fvarId) args |>.run {}
| .unreach type => return type
| .cases c => return c.resultType
def Code.inferParamType (params : Array Param) (code : Code) : CompilerM Expr := do
let type ← code.inferType
let xs := params.map fun p => .fvar p.fvarId
InferType.mkForallFVars xs type |>.run {}
def AltCore.inferType (alt : Alt) : CompilerM Expr :=
alt.getCode.inferType
def mkAuxLetDecl (e : Expr) (prefixName := `_x) : CompilerM LetDecl := do
mkLetDecl (← mkFreshBinderName prefixName) (← inferType e) e
def mkForallParams (params : Array Param) (type : Expr) : CompilerM Expr :=
InferType.mkForallParams params type |>.run {}
def mkAuxFunDecl (params : Array Param) (code : Code) (prefixName := `_f) : CompilerM FunDecl := do
let type ← mkForallParams params (← code.inferType)
let binderName ← mkFreshBinderName prefixName
mkFunDecl binderName type params code
def mkAuxJpDecl (params : Array Param) (code : Code) (prefixName := `_jp) : CompilerM FunDecl := do
mkAuxFunDecl params code prefixName
def mkAuxJpDecl' (param : Param) (code : Code) (prefixName := `_jp) : CompilerM FunDecl := do
let params := #[param]
mkAuxFunDecl params code prefixName
def instantiateForall (type : Expr) (params : Array Param) : CoreM Expr :=
go type 0
where
go (type : Expr) (i : Nat) : CoreM Expr :=
if h : i < params.size then
let p := params[i]
match type.headBeta with
| .forallE _ _ b _ => go (b.instantiate1 (.fvar p.fvarId)) (i+1)
| _ => throwError "invalid instantiateForall, too many parameters"
else
return type
termination_by go i => params.size - i
def mkCasesResultType (alts : Array Alt) : CompilerM Expr := do
if alts.isEmpty then
throwError "`Code.bind` failed, empty `cases` found"
let mut resultType ← alts[0]!.inferType
for alt in alts[1:] do
resultType := joinTypes resultType (← alt.inferType)
return resultType
/--
Return `true` if `type` should be erased. See item 1 in the note above where `x ◾ ◾` is
a proposition and should be erased when the universe level parameter is set to 0.
Remark: `predVars` is a bitmask that indicates whether de-bruijn variables are predicates or not.
That is, `#i` is a predicate if `predVars[predVars.size - i - 1] = true`
-/
partial def isErasedCompatible (type : Expr) (predVars : Array Bool := #[]): CompilerM Bool :=
go type predVars
where
go (type : Expr) (predVars : Array Bool) : CompilerM Bool := do
let type := type.headBeta
match type with
| .const .. => return type.isErased
| .sort .. => return false
| .mdata _ e => go e predVars
| .forallE _ t b _
| .lam _ t b _ => go b (predVars.push <| isPredicateType t)
| .app f _ => go f predVars
| .bvar idx => return predVars[predVars.size - idx - 1]!
| .fvar fvarId => return isPredicateType (← getType fvarId)
| .proj .. | .mvar .. | .letE .. | .lit .. => unreachable!
/--
Quick check for `compatibleTypes`. It is not monadic, but it is incomplete
because it does not eta-expand type formers. See comment at `compatibleTypes`.
Remark: if the result is `true`, then `a` and `b` are indeed compatible.
If it is `false`, we must use the full-check.
-/
partial def compatibleTypesQuick (a b : Expr) : Bool :=
if a.isAnyType || b.isAnyType then
true
else if a.isErased || b.isErased then
true
else
let a' := a.headBeta
let b' := b.headBeta
if a != a' || b != b' then
compatibleTypesQuick a' b'
else if a == b then
true
else
match a, b with
| .mdata _ a, b => compatibleTypesQuick a b
| a, .mdata _ b => compatibleTypesQuick a b
-- Note that even after reducing to head-beta, we can still have `.app` terms. For example,
-- an inductive constructor application such as `List Int`
| .app f a, .app g b => compatibleTypesQuick f g && compatibleTypesQuick a b
| .forallE _ d₁ b₁ _, .forallE _ d₂ b₂ _ => compatibleTypesQuick d₁ d₂ && compatibleTypesQuick b₁ b₂
| .lam _ d₁ b₁ _, .lam _ d₂ b₂ _ => compatibleTypesQuick d₁ d₂ && compatibleTypesQuick b₁ b₂
| .sort u, .sort v => Level.isEquiv u v
| .const n us, .const m vs => n == m && List.isEqv us vs Level.isEquiv
| _, _ => false
/--
Complete check for `compatibleTypes`. It eta-expands type formers. See comment at `compatibleTypes`.
-/
partial def InferType.compatibleTypesFull (a b : Expr) : InferTypeM Bool := do
if a.isAnyType || b.isAnyType then
return true
else if a.isErased || b.isErased then
return true
else
let a' := a.headBeta
let b' := b.headBeta
if a != a' || b != b' then
compatibleTypesFull a' b'
else if a == b then
return true
else
match a, b with
| .mdata _ a, b => compatibleTypesFull a b
| a, .mdata _ b => compatibleTypesFull a b
-- Note that even after reducing to head-beta, we can still have `.app` terms. For example,
-- an inductive constructor application such as `List Int`
| .app f a, .app g b => compatibleTypesFull f g <&&> compatibleTypesFull a b
| .forallE n d₁ b₁ bi, .forallE _ d₂ b₂ _ =>
unless (← compatibleTypesFull d₁ d₂) do return false
withLocalDecl n d₁ bi fun x =>
compatibleTypesFull (b₁.instantiate1 x) (b₂.instantiate1 x)
| .lam n d₁ b₁ bi, .lam _ d₂ b₂ _ =>
unless (← compatibleTypesFull d₁ d₂) do return false
withLocalDecl n d₁ bi fun x =>
compatibleTypesFull (b₁.instantiate1 x) (b₂.instantiate1 x)
| .sort u, .sort v => return Level.isEquiv u v
| .const n us, .const m vs => return n == m && List.isEqv us vs Level.isEquiv
| _, _ =>
if a.isLambda then
let some b ← etaExpand? b | return false
compatibleTypesFull a b
else if b.isLambda then
let some a ← etaExpand? a | return false
compatibleTypesFull a b
else
return false
where
etaExpand? (e : Expr) : InferTypeM (Option Expr) := do
match (← inferType e).headBeta with
| .forallE n d _ bi =>
/-
In principle, `.app e (.bvar 0)` may not be a valid LCNF type sub-expression
because `d` may not be a type former type, See remark `compatibleTypes` for
a justification why this is ok.
-/
return some (.lam n d (.app e (.bvar 0)) bi)
| _ => return none
/--
Return true if the LCNF types `a` and `b` are compatible.
Remark: `a` and `b` can be type formers (e.g., `List`, or `fun (α : Type) => Nat → Nat × α`)
Remark: We may need to eta-expand type formers to establish whether they are compatible or not.
For example, suppose we have
```
fun (x : B) => Id B ◾ ◾
Id B ◾
```
We must eta-expand `Id B ◾` to `fun (x : B) => Id B ◾ x`. Note that, we use `x` instead of `◾` to
make the implementation simpler and skip the check whether `B` is a type former type. However,
this simplification should not affect correctness since `◾` is compatible with everything.
Remark: see comment at `isErasedCompatible`.
Remark: because of "erasure confusion" see note above, we assume `◾` (aka `lcErasure`) is compatible with everything.
This is a simplification. We used to use `isErasedCompatible`, but this only address item 1.
For item 2, we would have to modify the `toLCNFType` function and make sure a type former is erased if the expected
type is not always a type former (see `S.mk` type and example in the note above).
-/
def InferType.compatibleTypes (a b : Expr) : InferTypeM Bool := do
if compatibleTypesQuick a b then
return true
else
compatibleTypesFull a b
@[inheritDoc InferType.compatibleTypes]
def compatibleTypes (a b : Expr) : CompilerM Bool :=
if compatibleTypesQuick a b then
return true
else
InferType.compatibleTypesFull a b |>.run {}
end Lean.Compiler.LCNF
|
03a86bfda79f0e533f6ddbc266c15ff9407e754a | f4bff2062c030df03d65e8b69c88f79b63a359d8 | /kb_solns/sets_level08.lean | 10c9dd77c037741780d275ecdf361f1c835be9d0 | [
"Apache-2.0"
] | permissive | adastra7470/real-number-game | 776606961f52db0eb824555ed2f8e16f92216ea3 | f9dcb7d9255a79b57e62038228a23346c2dc301b | refs/heads/master | 1,669,221,575,893 | 1,594,669,800,000 | 1,594,669,800,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 934 | lean | import data.real.basic --hide
/-
# Chapter 1 : Sets
## Level 8
-/
/-
This is a very basic example of working with intervals of real numbers in Lean.
An interval that is closed at both endpoints $a$ and $b$ can be
constructed using `set.Icc a b`. For an open-closed interval, the notation
is `set.Ioc a b`, etc. The usual closed-interval notation, using square
brackets, is used here as a wrapper around these definitions.
After `intro hx,` the `split` tactic will showcase the conditions for
membership. The inequality goals can be met with the `linarith` tactic.
The latter is very useful when dealing with goals that don't involve any
nonlinearity in the involved variables, in particular with inequalities.
-/
notation `[` a `,` b `]` := set.Icc a b
/- Lemma
If $x = 2$ then $x ∈ [0,5]$
-/
lemma in_closed_interval (x:ℝ) : x = 2 → x ∈ [(0:ℝ), 5] :=
begin
intro hx,
split, linarith, linarith, done
end
|
b4442c34c3367c9ca78da3323eefdda6ab024e3d | 1abd1ed12aa68b375cdef28959f39531c6e95b84 | /src/analysis/normed_space/dual.lean | 5598997d78ffdfe03db0028af772009425f61b5f | [
"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 | 4,286 | lean | /-
Copyright (c) 2020 Heather Macbeth. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Heather Macbeth
-/
import analysis.normed_space.hahn_banach
/-!
# The topological dual of a normed space
In this file we define the topological dual `normed_space.dual` of a normed space, and the
continuous linear map `normed_space.inclusion_in_double_dual` from a normed space into its double
dual.
For base field `𝕜 = ℝ` or `𝕜 = ℂ`, this map is actually an isometric embedding; we provide a
version `normed_space.inclusion_in_double_dual_li` of the map which is of type a bundled linear
isometric embedding, `E →ₗᵢ[𝕜] (dual 𝕜 (dual 𝕜 E))`.
Since a lot of elementary properties don't require `eq_of_dist_eq_zero` we start setting up the
theory for `semi_normed_space` and we specialize to `normed_space` when needed.
## Tags
dual
-/
noncomputable theory
open_locale classical
universes u v
namespace normed_space
section general
variables (𝕜 : Type*) [nondiscrete_normed_field 𝕜]
variables (E : Type*) [semi_normed_group E] [semi_normed_space 𝕜 E]
variables (F : Type*) [normed_group F] [normed_space 𝕜 F]
/-- The topological dual of a seminormed space `E`. -/
@[derive [inhabited, semi_normed_group, semi_normed_space 𝕜]] def dual := E →L[𝕜] 𝕜
instance : has_coe_to_fun (dual 𝕜 E) (λ _, E → 𝕜) := continuous_linear_map.to_fun
instance : normed_group (dual 𝕜 F) := continuous_linear_map.to_normed_group
instance : normed_space 𝕜 (dual 𝕜 F) := continuous_linear_map.to_normed_space
/-- The inclusion of a normed space in its double (topological) dual, considered
as a bounded linear map. -/
def inclusion_in_double_dual : E →L[𝕜] (dual 𝕜 (dual 𝕜 E)) :=
continuous_linear_map.apply 𝕜 𝕜
@[simp] lemma dual_def (x : E) (f : dual 𝕜 E) : inclusion_in_double_dual 𝕜 E x f = f x := rfl
lemma inclusion_in_double_dual_norm_eq :
∥inclusion_in_double_dual 𝕜 E∥ = ∥(continuous_linear_map.id 𝕜 (dual 𝕜 E))∥ :=
continuous_linear_map.op_norm_flip _
lemma inclusion_in_double_dual_norm_le : ∥inclusion_in_double_dual 𝕜 E∥ ≤ 1 :=
by { rw inclusion_in_double_dual_norm_eq, exact continuous_linear_map.norm_id_le }
lemma double_dual_bound (x : E) : ∥(inclusion_in_double_dual 𝕜 E) x∥ ≤ ∥x∥ :=
by simpa using continuous_linear_map.le_of_op_norm_le _ (inclusion_in_double_dual_norm_le 𝕜 E) x
end general
section bidual_isometry
variables (𝕜 : Type v) [is_R_or_C 𝕜]
{E : Type u} [normed_group E] [normed_space 𝕜 E]
/-- If one controls the norm of every `f x`, then one controls the norm of `x`.
Compare `continuous_linear_map.op_norm_le_bound`. -/
lemma norm_le_dual_bound (x : E) {M : ℝ} (hMp: 0 ≤ M) (hM : ∀ (f : dual 𝕜 E), ∥f x∥ ≤ M * ∥f∥) :
∥x∥ ≤ M :=
begin
classical,
by_cases h : x = 0,
{ simp only [h, hMp, norm_zero] },
{ obtain ⟨f, hf⟩ : ∃ g : E →L[𝕜] 𝕜, _ := exists_dual_vector 𝕜 x h,
calc ∥x∥ = ∥norm' 𝕜 x∥ : (norm_norm' _ _ _).symm
... = ∥f x∥ : by rw hf.2
... ≤ M * ∥f∥ : hM f
... = M : by rw [hf.1, mul_one] }
end
lemma eq_zero_of_forall_dual_eq_zero {x : E} (h : ∀ f : dual 𝕜 E, f x = (0 : 𝕜)) : x = 0 :=
norm_eq_zero.mp (le_antisymm (norm_le_dual_bound 𝕜 x le_rfl (λ f, by simp [h f])) (norm_nonneg _))
lemma eq_zero_iff_forall_dual_eq_zero (x : E) : x = 0 ↔ ∀ g : dual 𝕜 E, g x = 0 :=
⟨λ hx, by simp [hx], λ h, eq_zero_of_forall_dual_eq_zero 𝕜 h⟩
lemma eq_iff_forall_dual_eq {x y : E} :
x = y ↔ ∀ g : dual 𝕜 E, g x = g y :=
begin
rw [← sub_eq_zero, eq_zero_iff_forall_dual_eq_zero 𝕜 (x - y)],
simp [sub_eq_zero],
end
/-- The inclusion of a normed space in its double dual is an isometry onto its image.-/
def inclusion_in_double_dual_li : E →ₗᵢ[𝕜] (dual 𝕜 (dual 𝕜 E)) :=
{ norm_map' := begin
intros x,
apply le_antisymm,
{ exact double_dual_bound 𝕜 E x },
rw continuous_linear_map.norm_def,
apply le_cInf continuous_linear_map.bounds_nonempty,
rintros c ⟨hc1, hc2⟩,
exact norm_le_dual_bound 𝕜 x hc1 hc2
end,
.. inclusion_in_double_dual 𝕜 E }
end bidual_isometry
end normed_space
|
09fedd33a1562719efe85559def137994be9c2f6 | 05f637fa14ac28031cb1ea92086a0f4eb23ff2b1 | /src/builtin/proof_irrel.lean | 018c00c5c54b38e56e71d55d3dba9607fe28643d | [
"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 | 2,702 | lean | import macros
definition has_fixpoint (A : Bool) : Bool
:= ∃ F : (A → A) → A, ∀ f : A → A, F f = f (F f)
theorem eq_arrow (A : Bool) : inhabited A → (A → A) = A
:= assume Hin : inhabited A,
obtain (p : A) (Hp : true), from Hin,
iff_intro
(assume Hl : A → A, p)
(assume Hr : A, (assume H : A, H))
theorem bool_fixpoint (A : Bool) : inhabited A → has_fixpoint A
:= assume Hin : inhabited A,
have Heq1 : (A → A) == A,
from (to_heq (eq_arrow A Hin)),
have Heq2 : A == (A → A),
from hsymm Heq1,
let g1 : A → (A → A) := λ x : A, cast Heq2 x,
g2 : (A → A) → A := λ x : A → A, cast Heq1 x,
Y : (A → A) → A := (λ f : A → A, (λ x : A, f (g1 x x)) (g2 (λ x : A, f (g1 x x)))) in
have R : ∀ f, g1 (g2 f) = f,
from take f : A → A,
calc g1 (g2 f) = cast Heq2 (cast Heq1 f) : refl _
... = cast (htrans Heq1 Heq2) f : cast_trans _ _ _
... = f : cast_eq _ _,
have Fix : (∀ f, Y f = f (Y f)),
from take f : A → A,
let h : A → A := λ x : A, f (g1 x x) in
have H1 : Y f = f (g1 (g2 h) (g2 h)),
from refl (Y f),
have H2 : g1 (g2 h) = h,
from R h,
have H3 : Y f = f (h (g2 h)),
from substp (λ x, Y f = f (x (g2 h))) H1 H2,
have H4 : f (Y f) = f (h (g2 h)),
from refl (f (Y f)),
trans H3 (symm H4),
@exists_intro ((A → A) → A) (λ Y, ∀ f, Y f = f (Y f)) Y Fix
theorem proof_irrel_new (A : Bool) (p1 p2 : A) : p1 = p2
:= have H1 : inhabited A,
from inhabited_intro p1,
obtain (Y : (A → A) → A) (HY : ∀ f : A → A, Y f = f (Y f)), from bool_fixpoint A H1,
let h : A → A := (λ x : A, if x = p1 then p2 else p1) in
have HYh : Y h = h (Y h),
from HY h,
or_elim (em (Y h = p1))
(assume Heq : Y h = p1,
have Heq1 : h (Y h) = p2,
from calc h (Y h) = if Y h = p1 then p2 else p1 : refl _
... = if true then p2 else p1 : { eqt_intro Heq }
... = p2 : if_true _ _,
calc p1 = Y h : symm Heq
... = h (Y h) : HYh
... = p2 : Heq1)
(assume Hne : Y h ≠ p1,
have Heq1 : h (Y h) = p1,
from calc h (Y h) = if Y h = p1 then p2 else p1 : refl _
... = if false then p2 else p1 : { eqf_intro Hne }
... = p1 : if_false _ _,
have Heq2 : Y h = p1,
from trans HYh Heq1,
absurd_elim (p1 = p2) Heq2 Hne)
|
645faa50f22bcd874e784f5f5beab302eedd1d2e | 94e33a31faa76775069b071adea97e86e218a8ee | /src/ring_theory/chain_of_divisors.lean | afe5284d40bf91da3c1335010fc8530ab33bd9a0 | [
"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 | 21,269 | lean | /-
Copyright (c) 2021 Paul Lezeau. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Anne Baanen, Paul Lezeau
-/
import algebra.is_prime_pow
import algebra.squarefree
import order.hom.bounded
import algebra.gcd_monoid.basic
/-!
# Chains of divisors
The results in this file show that in the monoid `associates M` of a `unique_factorization_monoid`
`M`, an element `a` is an n-th prime power iff its set of divisors is a strictly increasing chain
of length `n + 1`, meaning that we can find a strictly increasing bijection between `fin (n + 1)`
and the set of factors of `a`.
## Main results
- `divisor_chain.exists_chain_of_prime_pow` : existence of a chain for prime powers.
- `divisor_chain.is_prime_pow_of_has_chain` : elements that have a chain are prime powers.
- `multiplicity_prime_eq_multiplicity_image_by_factor_order_iso` : if there is a
monotone bijection `d` between the set of factors of `a : associates M` and the set of factors of
`b : associates N` then for any prime `p ∣ a`, `multiplicity p a = multiplicity (d p) b`.
- `multiplicity_eq_multiplicity_factor_dvd_iso_of_mem_normalized_factor` : if there is a bijection
between the set of factors of `a : M` and `b : N` then for any prime `p ∣ a`,
`multiplicity p a = multiplicity (d p) b`
## Todo
- Create a structure for chains of divisors.
- Simplify proof of `mem_normalized_factors_factor_dvd_iso_of_mem_normalized_factors` using
`mem_normalized_factors_factor_order_iso_of_mem_normalized_factors` or vice versa.
-/
variables {M : Type*} [cancel_comm_monoid_with_zero M]
open unique_factorization_monoid multiplicity irreducible associates
namespace divisor_chain
lemma exists_chain_of_prime_pow {p : associates M} {n : ℕ} (hn : n ≠ 0) (hp : prime p) :
∃ c : fin (n + 1) → associates M,
c 1 = p ∧ strict_mono c ∧
∀ {r : associates M}, r ≤ p^n ↔ ∃ i, r = c i :=
begin
refine ⟨λ i, p^(i : ℕ), _, λ n m h, _, λ y, ⟨λ h, _, _⟩⟩,
{ rw [fin.coe_one', nat.mod_eq_of_lt, pow_one],
exact nat.lt_succ_of_le (nat.one_le_iff_ne_zero.mpr hn) },
{ exact associates.dvd_not_unit_iff_lt.mp ⟨pow_ne_zero n hp.ne_zero, p^(m - n : ℕ),
not_is_unit_of_not_is_unit_dvd hp.not_unit (dvd_pow dvd_rfl (nat.sub_pos_of_lt h).ne'),
(pow_mul_pow_sub p h.le).symm⟩ },
{ obtain ⟨i, i_le, hi⟩ := (dvd_prime_pow hp n).1 h,
rw associated_iff_eq at hi,
exact ⟨⟨i, nat.lt_succ_of_le i_le⟩, hi⟩ },
{ rintro ⟨i, rfl⟩,
exact ⟨p^(n - i : ℕ), (pow_mul_pow_sub p (nat.succ_le_succ_iff.mp i.2)).symm⟩ }
end
lemma element_of_chain_not_is_unit_of_index_ne_zero {n : ℕ} {i : fin (n + 1)} (i_pos : i ≠ 0)
{c : fin (n + 1) → associates M} (h₁ : strict_mono c) :
¬ is_unit (c i) :=
dvd_not_unit.not_unit (associates.dvd_not_unit_iff_lt.2
(h₁ $ show (0 : fin (n + 1)) < i, from i.pos_iff_ne_zero.mpr i_pos))
lemma first_of_chain_is_unit {q : associates M} {n : ℕ} {c : fin (n + 1) → associates M}
(h₁ : strict_mono c) (h₂ : ∀ {r}, r ≤ q ↔ ∃ i, r = c i) : is_unit (c 0) :=
begin
obtain ⟨i, hr⟩ := h₂.mp associates.one_le,
rw [associates.is_unit_iff_eq_one, ← associates.le_one_iff, hr],
exact h₁.monotone (fin.zero_le i)
end
/-- The second element of a chain is irreducible. -/
lemma second_of_chain_is_irreducible {q : associates M} {n : ℕ} (hn : n ≠ 0)
{c : fin (n + 1) → associates M} (h₁ : strict_mono c) (h₂ : ∀ {r}, r ≤ q ↔ ∃ i, r = c i)
(hq : q ≠ 0) : irreducible (c 1) :=
begin
cases n, { contradiction },
refine (associates.is_atom_iff (ne_zero_of_dvd_ne_zero hq (h₂.2 ⟨1, rfl⟩))).mp ⟨_, λ b hb, _⟩,
{ exact ne_bot_of_gt (h₁ (show (0 : fin (n + 2)) < 1, from fin.one_pos)) },
obtain ⟨⟨i, hi⟩, rfl⟩ := h₂.1 (hb.le.trans (h₂.2 ⟨1, rfl⟩)),
cases i,
{ exact (associates.is_unit_iff_eq_one _).mp (first_of_chain_is_unit h₁ @h₂) },
{ simpa [fin.lt_iff_coe_lt_coe] using h₁.lt_iff_lt.mp hb },
end
lemma eq_second_of_chain_of_prime_dvd {p q r : associates M} {n : ℕ} (hn : n ≠ 0)
{c : fin (n + 1) → associates M} (h₁ : strict_mono c)
(h₂ : ∀ {r : associates M}, r ≤ q ↔ ∃ i, r = c i) (hp : prime p) (hr : r ∣ q) (hp' : p ∣ r) :
p = c 1 :=
begin
cases n,
{ contradiction },
obtain ⟨i, rfl⟩ := h₂.1 (dvd_trans hp' hr),
refine congr_arg c (eq_of_ge_of_not_gt _ $ λ hi, _),
{ rw [fin.le_iff_coe_le_coe, fin.coe_one, nat.succ_le_iff, ← fin.coe_zero,
← fin.lt_iff_coe_lt_coe, fin.pos_iff_ne_zero],
rintro rfl,
exact hp.not_unit (first_of_chain_is_unit h₁ @h₂) },
obtain (rfl | ⟨j, rfl⟩) := i.eq_zero_or_eq_succ,
{ cases hi },
refine not_irreducible_of_not_unit_dvd_not_unit
(dvd_not_unit.not_unit (associates.dvd_not_unit_iff_lt.2
(h₁ (show (0 : fin (n + 2)) < j, from _)) )) _ hp.irreducible,
{ simpa [← fin.succ_zero_eq_one, fin.succ_lt_succ_iff] using hi },
{ refine associates.dvd_not_unit_iff_lt.2 (h₁ _),
simpa only [fin.coe_eq_cast_succ] using fin.lt_succ }
end
lemma card_subset_divisors_le_length_of_chain {q : associates M}
{n : ℕ} {c : fin (n + 1) → associates M} (h₂ : ∀ {r}, r ≤ q ↔ ∃ i, r = c i)
{m : finset (associates M)} (hm : ∀ r, r ∈ m → r ≤ q) : m.card ≤ n + 1 :=
begin
classical,
have mem_image : ∀ (r : associates M), r ≤ q → r ∈ finset.univ.image c,
{ intros r hr,
obtain ⟨i, hi⟩ := h₂.1 hr,
exact finset.mem_image.2 ⟨i, finset.mem_univ _, hi.symm⟩ },
rw ←finset.card_fin (n + 1),
exact (finset.card_le_of_subset $ λ x hx, mem_image x $ hm x hx).trans finset.card_image_le,
end
variables [unique_factorization_monoid M]
lemma element_of_chain_eq_pow_second_of_chain {q r : associates M} {n : ℕ} (hn : n ≠ 0)
{c : fin (n + 1) → associates M} (h₁ : strict_mono c)
(h₂ : ∀ {r}, r ≤ q ↔ ∃ i, r = c i) (hr : r ∣ q)
(hq : q ≠ 0) : ∃ (i : fin (n + 1)), r = (c 1) ^ (i : ℕ) :=
begin
classical,
let i := (normalized_factors r).card,
have hi : normalized_factors r = multiset.repeat (c 1) i,
{ apply multiset.eq_repeat_of_mem,
intros b hb,
refine eq_second_of_chain_of_prime_dvd hn h₁ (λ r', h₂) (prime_of_normalized_factor b hb) hr
(dvd_of_mem_normalized_factors hb) },
have H : r = (c 1)^i,
{ have := unique_factorization_monoid.normalized_factors_prod (ne_zero_of_dvd_ne_zero hq hr),
rw [associated_iff_eq, hi, multiset.prod_repeat] at this,
rw this },
refine ⟨⟨i, _⟩, H⟩,
have : (finset.univ.image (λ (m : fin (i + 1)), (c 1) ^ (m : ℕ))).card = i + 1,
{ conv_rhs { rw [← finset.card_fin (i+1)] },
cases n, { contradiction },
rw finset.card_image_iff,
refine set.inj_on_of_injective (λ m m' h, fin.ext _) _,
refine pow_injective_of_not_unit
(element_of_chain_not_is_unit_of_index_ne_zero (by simp) h₁) _ h,
exact irreducible.ne_zero (second_of_chain_is_irreducible hn h₁ @h₂ hq) },
suffices H' : ∀ r ∈ (finset.univ.image (λ (m : fin (i + 1)), (c 1) ^ (m : ℕ))), r ≤ q,
{ simp only [← nat.succ_le_iff, nat.succ_eq_add_one, ← this],
apply card_subset_divisors_le_length_of_chain @h₂ H' },
simp only [finset.mem_image],
rintros r ⟨a, ha, rfl⟩,
refine dvd_trans _ hr,
use (c 1)^(i - a),
rw pow_mul_pow_sub (c 1),
{ exact H },
{ exact nat.succ_le_succ_iff.mp a.2 }
end
lemma eq_pow_second_of_chain_of_has_chain {q : associates M} {n : ℕ} (hn : n ≠ 0)
{c : fin (n + 1) → associates M} (h₁ : strict_mono c)
(h₂ : ∀ {r : associates M}, r ≤ q ↔ ∃ i, r = c i) (hq : q ≠ 0) : q = (c 1)^n :=
begin
classical,
obtain ⟨i, hi'⟩ := element_of_chain_eq_pow_second_of_chain hn h₁ (λ r, h₂) (dvd_refl q) hq,
convert hi',
refine (nat.lt_succ_iff.1 i.prop).antisymm' (nat.le_of_succ_le_succ _),
calc n + 1 = (finset.univ : finset (fin (n + 1))).card : (finset.card_fin _).symm
... = (finset.univ.image c).card :
(finset.card_image_iff.mpr (h₁.injective.inj_on _)).symm
... ≤ (finset.univ.image (λ (m : fin (i + 1)), (c 1)^(m : ℕ))).card :
finset.card_le_of_subset _
... ≤ (finset.univ : finset (fin (i + 1))).card : finset.card_image_le
... = i + 1 : finset.card_fin _,
intros r hr,
obtain ⟨j, -, rfl⟩ := finset.mem_image.1 hr,
have := h₂.2 ⟨j, rfl⟩,
rw hi' at this,
obtain ⟨u, hu, hu'⟩ := (dvd_prime_pow (show prime (c 1), from _) i).1 this,
refine finset.mem_image.mpr ⟨u, finset.mem_univ _, _⟩,
{ rw associated_iff_eq at hu', rw [fin.coe_coe_of_lt (nat.lt_succ_of_le hu), hu'] },
{ rw ← irreducible_iff_prime, exact second_of_chain_is_irreducible hn h₁ @h₂ hq, }
end
lemma is_prime_pow_of_has_chain {q : associates M} {n : ℕ} (hn : n ≠ 0)
{c : fin (n + 1) → associates M} (h₁ : strict_mono c)
(h₂ : ∀ {r : associates M}, r ≤ q ↔ ∃ i, r = c i) (hq : q ≠ 0) : is_prime_pow q :=
⟨c 1, n, irreducible_iff_prime.mp (second_of_chain_is_irreducible hn h₁ @h₂ hq),
zero_lt_iff.mpr hn, (eq_pow_second_of_chain_of_has_chain hn h₁ @h₂ hq).symm⟩
end divisor_chain
variables {N : Type*} [cancel_comm_monoid_with_zero N]
lemma factor_order_iso_map_one_eq_bot {m : associates M} {n : associates N}
(d : {l : associates M // l ≤ m} ≃o {l : associates N // l ≤ n}) :
(d ⟨1, one_dvd m⟩ : associates N) = 1 :=
begin
letI : order_bot {l : associates M // l ≤ m} := subtype.order_bot bot_le,
letI : order_bot {l : associates N // l ≤ n} := subtype.order_bot bot_le,
simp [←associates.bot_eq_one]
end
lemma coe_factor_order_iso_map_eq_one_iff {m u : associates M} {n : associates N}
(hu' : u ≤ m) (d : set.Iic m ≃o set.Iic n) :
(d ⟨u, hu'⟩ : associates N) = 1 ↔ u = 1 :=
⟨λ hu, by { rw (show u = ↑(d.symm ⟨↑(d ⟨u, hu'⟩), (d ⟨u, hu'⟩).prop⟩), by simp only
[subtype.coe_eta, order_iso.symm_apply_apply, subtype.coe_mk]),
convert factor_order_iso_map_one_eq_bot d.symm },
λ hu, by {simp_rw hu, convert factor_order_iso_map_one_eq_bot d } ⟩
section
variables [unique_factorization_monoid N] [unique_factorization_monoid M]
open divisor_chain
lemma pow_image_of_prime_by_factor_order_iso_dvd [decidable_eq (associates M)] {m p : associates M}
{n : associates N} (hn : n ≠ 0) (hp : p ∈ normalized_factors m)
(d : set.Iic m ≃o set.Iic n) {s : ℕ} (hs' : p^s ≤ m) :
(d ⟨p, dvd_of_mem_normalized_factors hp⟩ : associates N)^s ≤ n :=
begin
by_cases hs : s = 0,
{ simp [hs], },
suffices : (d ⟨p, dvd_of_mem_normalized_factors hp⟩ : associates N)^s = ↑(d ⟨p^s, hs'⟩),
{ rw this,
apply subtype.prop (d ⟨p^s, hs'⟩) },
obtain ⟨c₁, rfl, hc₁', hc₁''⟩ := exists_chain_of_prime_pow hs (prime_of_normalized_factor p hp),
set c₂ : fin (s + 1) → associates N := λ t, d ⟨c₁ t, le_trans (hc₁''.2 ⟨t, by simp⟩) hs'⟩,
have c₂.def : ∀ (t), c₂ t = d ⟨c₁ t, _⟩ := λ t, rfl,
refine (congr_arg (^s) (c₂.def 1).symm).trans _,
refine (eq_pow_second_of_chain_of_has_chain hs (λ t u h, _) (λ r, ⟨λ hr, _, _⟩) _).symm,
{ rw [c₂.def, c₂.def, subtype.coe_lt_coe, d.lt_iff_lt, subtype.mk_lt_mk, (hc₁').lt_iff_lt],
exact h },
{ have : r ≤ n := hr.trans (d ⟨c₁ 1 ^ s, _⟩).2,
suffices : d.symm ⟨r, this⟩ ≤ ⟨c₁ 1 ^ s, hs'⟩,
{ obtain ⟨i, hi⟩ := hc₁''.1 this,
use i,
simp only [c₂.def, ← hi, d.apply_symm_apply, subtype.coe_eta, subtype.coe_mk] },
conv_rhs { rw ← d.symm_apply_apply ⟨c₁ 1 ^ s, hs'⟩ },
rw d.symm.le_iff_le,
simpa only [← subtype.coe_le_coe, subtype.coe_mk] using hr },
{ rintros ⟨i, hr⟩,
rw [hr, c₂.def, subtype.coe_le_coe, d.le_iff_le],
simpa [subtype.mk_le_mk] using hc₁''.2 ⟨i, rfl⟩ },
exact ne_zero_of_dvd_ne_zero hn (subtype.prop (d ⟨c₁ 1 ^ s, _⟩))
end
lemma map_prime_of_factor_order_iso [decidable_eq (associates M)]
{m p : associates M} {n : associates N} (hn : n ≠ 0) (hp : p ∈ normalized_factors m)
(d : set.Iic m ≃o set.Iic n) : prime (d ⟨p, dvd_of_mem_normalized_factors hp⟩ : associates N) :=
begin
rw ← irreducible_iff_prime,
refine (associates.is_atom_iff $ ne_zero_of_dvd_ne_zero hn (d ⟨p, _⟩).prop).mp ⟨_, λ b hb, _⟩,
{ rw [ne.def, ← associates.is_unit_iff_eq_bot, associates.is_unit_iff_eq_one,
coe_factor_order_iso_map_eq_one_iff _ d],
rintro rfl,
exact (prime_of_normalized_factor 1 hp).not_unit is_unit_one },
{ obtain ⟨x, hx⟩ := d.surjective ⟨b, le_trans (le_of_lt hb)
(d ⟨p, dvd_of_mem_normalized_factors hp⟩).prop⟩,
rw [← subtype.coe_mk b _ , subtype.coe_lt_coe, ← hx] at hb,
letI : order_bot {l : associates M // l ≤ m} := subtype.order_bot bot_le,
letI : order_bot {l : associates N // l ≤ n} := subtype.order_bot bot_le,
suffices : x = ⊥,
{ rw [this, order_iso.map_bot d] at hx,
refine (subtype.mk_eq_bot_iff _ _).mp hx.symm,
exact bot_le },
obtain ⟨a, ha⟩ := x,
rw subtype.mk_eq_bot_iff,
{ exact ((associates.is_atom_iff $ prime.ne_zero $ prime_of_normalized_factor p hp).mpr $
irreducible_of_normalized_factor p hp).right a (subtype.mk_lt_mk.mp $ d.lt_iff_lt.mp hb) },
exact bot_le }
end
lemma mem_normalized_factors_factor_order_iso_of_mem_normalized_factors
[decidable_eq (associates M)] [decidable_eq (associates N)] {m p : associates M}
{n : associates N} (hn : n ≠ 0) (hp : p ∈ normalized_factors m)
(d : set.Iic m ≃o set.Iic n) :
↑(d ⟨p, dvd_of_mem_normalized_factors hp⟩) ∈ normalized_factors n :=
begin
obtain ⟨q, hq, hq'⟩ := exists_mem_normalized_factors_of_dvd hn
(map_prime_of_factor_order_iso hn hp d).irreducible
(d ⟨p, dvd_of_mem_normalized_factors hp⟩).prop,
rw associated_iff_eq at hq',
rwa hq'
end
variables [decidable_rel ((∣) : M → M → Prop)] [decidable_rel ((∣) : N → N → Prop)]
lemma multiplicity_prime_le_multiplicity_image_by_factor_order_iso [decidable_eq (associates M)]
{m p : associates M} {n : associates N} (hp : p ∈ normalized_factors m)
(d : set.Iic m ≃o set.Iic n) :
multiplicity p m ≤ multiplicity ↑(d ⟨p, dvd_of_mem_normalized_factors hp⟩) n :=
begin
by_cases hn : n = 0,
{ simp [hn], },
by_cases hm : m = 0,
{ simpa [hm] using hp, },
rw [← part_enat.coe_get
(finite_iff_dom.1 $ finite_prime_left (prime_of_normalized_factor p hp) hm),
← pow_dvd_iff_le_multiplicity],
exact pow_image_of_prime_by_factor_order_iso_dvd hn hp d (pow_multiplicity_dvd _),
end
lemma multiplicity_prime_eq_multiplicity_image_by_factor_order_iso [decidable_eq (associates M)]
{m p : associates M} {n : associates N} (hn : n ≠ 0)
(hp : p ∈ normalized_factors m) (d : set.Iic m ≃o set.Iic n) :
multiplicity p m = multiplicity ↑(d ⟨p, dvd_of_mem_normalized_factors hp⟩) n :=
begin
refine le_antisymm (multiplicity_prime_le_multiplicity_image_by_factor_order_iso hp d) _,
suffices : multiplicity ↑(d ⟨p, dvd_of_mem_normalized_factors hp⟩) n ≤
multiplicity ↑(d.symm (d ⟨p, dvd_of_mem_normalized_factors hp⟩)) m,
{ rw [d.symm_apply_apply ⟨p, dvd_of_mem_normalized_factors hp⟩, subtype.coe_mk] at this,
exact this },
letI := classical.dec_eq (associates N),
simpa only [subtype.coe_eta] using
(multiplicity_prime_le_multiplicity_image_by_factor_order_iso
(mem_normalized_factors_factor_order_iso_of_mem_normalized_factors hn hp d) d.symm),
end
end
variables [unique (Mˣ)] [unique (Nˣ)]
/-- The order isomorphism between the factors of `mk m` and the factors of `mk n` induced by a
bijection between the factors of `m` and the factors of `n` that preserves `∣`. -/
@[simps]
def mk_factor_order_iso_of_factor_dvd_equiv
{m : M} {n : N} (d : {l : M // l ∣ m} ≃ {l : N // l ∣ n})
(hd : ∀ l l', ((d l) : N) ∣ (d l') ↔ (l : M) ∣ (l' : M)) :
set.Iic (associates.mk m) ≃o set.Iic (associates.mk n) :=
{ to_fun := λ l, ⟨associates.mk (d ⟨associates_equiv_of_unique_units ↑l,
by { obtain ⟨x, hx⟩ := l, rw [subtype.coe_mk, associates_equiv_of_unique_units_apply,
out_dvd_iff], exact hx } ⟩),
mk_le_mk_iff_dvd_iff.mpr (subtype.prop (d ⟨associates_equiv_of_unique_units ↑l, _ ⟩)) ⟩,
inv_fun := λ l, ⟨associates.mk (d.symm (⟨(associates_equiv_of_unique_units ↑l),
by obtain ⟨x, hx⟩ := l ; rw [subtype.coe_mk, associates_equiv_of_unique_units_apply,
out_dvd_iff] ; exact hx ⟩)),
mk_le_mk_iff_dvd_iff.mpr (subtype.prop (d.symm ⟨associates_equiv_of_unique_units ↑l, _ ⟩)) ⟩,
left_inv := λ ⟨l, hl⟩, by simp only [subtype.coe_eta, equiv.symm_apply_apply, subtype.coe_mk,
associates_equiv_of_unique_units_apply, mk_out, out_mk, normalize_eq],
right_inv := λ ⟨l, hl⟩, by simp only [subtype.coe_eta, equiv.apply_symm_apply, subtype.coe_mk,
associates_equiv_of_unique_units_apply, out_mk, normalize_eq, mk_out],
map_rel_iff' :=
by rintros ⟨a, ha⟩ ⟨b, hb⟩ ; simp only [equiv.coe_fn_mk, subtype.mk_le_mk,
associates.mk_le_mk_iff_dvd_iff, hd, subtype.coe_mk, associates_equiv_of_unique_units_apply,
out_dvd_iff, mk_out] }
variables [unique_factorization_monoid M] [unique_factorization_monoid N]
[decidable_eq M]
lemma mem_normalized_factors_factor_dvd_iso_of_mem_normalized_factors [decidable_eq N] {m p : M}
{n : N} (hm : m ≠ 0) (hn : n ≠ 0) (hp : p ∈ normalized_factors m)
(d : {l : M // l ∣ m} ≃ {l : N // l ∣ n})
(hd : ∀ l l', ((d l) : N) ∣ (d l') ↔ (l : M) ∣ (l' : M)) :
↑(d ⟨p, dvd_of_mem_normalized_factors hp⟩) ∈ normalized_factors n :=
begin
suffices : prime ↑(d ⟨associates_equiv_of_unique_units (associates_equiv_of_unique_units.symm p),
by simp [dvd_of_mem_normalized_factors hp]⟩),
{ simp only [associates_equiv_of_unique_units_apply, out_mk, normalize_eq,
associates_equiv_of_unique_units_symm_apply] at this,
obtain ⟨q, hq, hq'⟩ := exists_mem_normalized_factors_of_dvd hn (this.irreducible)
(d ⟨p, by apply dvd_of_mem_normalized_factors ; convert hp⟩).prop,
rwa associated_iff_eq.mp hq' },
have : associates.mk ↑(d ⟨associates_equiv_of_unique_units
(associates_equiv_of_unique_units.symm p), by simp only [dvd_of_mem_normalized_factors hp,
associates_equiv_of_unique_units_apply, out_mk, normalize_eq,
associates_equiv_of_unique_units_symm_apply] ⟩)
= ↑(mk_factor_order_iso_of_factor_dvd_equiv d hd ⟨( associates_equiv_of_unique_units.symm p),
by simp only [associates_equiv_of_unique_units_symm_apply] ;
exact mk_dvd_mk.mpr (dvd_of_mem_normalized_factors hp) ⟩),
{ rw mk_factor_order_iso_of_factor_dvd_equiv_apply_coe,
simp only [subtype.coe_mk] },
rw [ ← associates.prime_mk, this],
letI := classical.dec_eq (associates M),
refine map_prime_of_factor_order_iso (mk_ne_zero.mpr hn) _ _,
obtain ⟨q, hq, hq'⟩ := exists_mem_normalized_factors_of_dvd (mk_ne_zero.mpr hm)
((prime_mk p).mpr (prime_of_normalized_factor p (by convert hp))).irreducible
(mk_le_mk_of_dvd (dvd_of_mem_normalized_factors hp)),
simpa only [associated_iff_eq.mp hq', associates_equiv_of_unique_units_symm_apply] using hq,
end
variables [decidable_rel ((∣) : M → M → Prop)] [decidable_rel ((∣) : N → N → Prop)]
lemma multiplicity_eq_multiplicity_factor_dvd_iso_of_mem_normalized_factor {m p : M} {n : N}
(hm : m ≠ 0) (hn : n ≠ 0) (hp : p ∈ normalized_factors m)
(d : {l : M // l ∣ m} ≃ {l : N // l ∣ n}) (hd : ∀ l l', ((d l) : N) ∣ (d l') ↔ (l : M) ∣ l') :
multiplicity p m = multiplicity ((d ⟨p, dvd_of_mem_normalized_factors hp⟩) : N) n :=
begin
suffices : multiplicity (associates.mk p) (associates.mk m) = multiplicity (associates.mk
↑(d ⟨associates_equiv_of_unique_units (associates_equiv_of_unique_units.symm p),
by simp [dvd_of_mem_normalized_factors hp]⟩))
(associates.mk n),
{ simpa only [multiplicity_mk_eq_multiplicity, associates_equiv_of_unique_units_symm_apply,
associates_equiv_of_unique_units_apply, out_mk, normalize_eq] using this },
have : associates.mk ↑(d ⟨associates_equiv_of_unique_units
(associates_equiv_of_unique_units.symm p), by simp only [dvd_of_mem_normalized_factors hp,
associates_equiv_of_unique_units_symm_apply, associates_equiv_of_unique_units_apply,
out_mk, normalize_eq] ⟩)
= ↑(mk_factor_order_iso_of_factor_dvd_equiv d hd ⟨(associates_equiv_of_unique_units.symm p),
by rw [associates_equiv_of_unique_units_symm_apply] ;
exact mk_le_mk_of_dvd (dvd_of_mem_normalized_factors hp) ⟩),
{ rw mk_factor_order_iso_of_factor_dvd_equiv_apply_coe, refl },
rw this,
letI := classical.dec_eq (associates M),
refine multiplicity_prime_eq_multiplicity_image_by_factor_order_iso (mk_ne_zero.mpr hn) _
(mk_factor_order_iso_of_factor_dvd_equiv d hd),
obtain ⟨q, hq, hq'⟩ := exists_mem_normalized_factors_of_dvd (mk_ne_zero.mpr hm)
((prime_mk p).mpr (prime_of_normalized_factor p hp)).irreducible
(mk_le_mk_of_dvd (dvd_of_mem_normalized_factors hp)),
rwa associated_iff_eq.mp hq',
end
|
ef5637465f1f665b9f5d51000691d8458a45f1c7 | 4727251e0cd73359b15b664c3170e5d754078599 | /src/category_theory/sites/left_exact.lean | a4e62d9e152186c536da47de1a168dc42bd45928 | [
"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 | 9,961 | lean | /-
Copyright (c) 2021 Adam Topaz. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Adam Topaz
-/
import category_theory.sites.sheafification
import category_theory.sites.limits
import category_theory.limits.functor_category
import category_theory.limits.filtered_colimit_commutes_finite_limit
/-!
# Left exactness of sheafification
In this file we show that sheafification commutes with finite limits.
-/
open category_theory
open category_theory.limits
open opposite
universes w v u
variables {C : Type (max v u)} [category.{v} C] {J : grothendieck_topology C}
variables {D : Type w} [category.{max v u} D]
variables [∀ (P : Cᵒᵖ ⥤ D) (X : C) (S : J.cover X), has_multiequalizer (S.index P)]
noncomputable theory
namespace category_theory.grothendieck_topology
/-- An auxiliary definition to be used in the proof of the fact that
`J.diagram_functor D X` preserves limits. -/
@[simps]
def cone_comp_evaluation_of_cone_comp_diagram_functor_comp_evaluation
{X : C} {K : Type (max v u)} [small_category K]
{F : K ⥤ Cᵒᵖ ⥤ D} {W : J.cover X} (i : W.arrow)
(E : cone (F ⋙ J.diagram_functor D X ⋙ (evaluation (J.cover X)ᵒᵖ D).obj (op W))) :
cone (F ⋙ (evaluation _ _).obj (op i.Y)) :=
{ X := E.X,
π :=
{ app := λ k, E.π.app k ≫ multiequalizer.ι (W.index (F.obj k)) i,
naturality' := begin
intros a b f,
dsimp,
rw [category.id_comp, category.assoc, ← E.w f],
dsimp [diagram_nat_trans],
simp only [multiequalizer.lift_ι, category.assoc],
end } }
/-- An auxiliary definition to be used in the proof of the fact that
`J.diagram_functor D X` preserves limits. -/
abbreviation lift_to_diagram_limit_obj
{X : C} {K : Type (max v u)} [small_category K] [has_limits_of_shape K D]
{W : (J.cover X)ᵒᵖ} (F : K ⥤ Cᵒᵖ ⥤ D)
(E : cone (F ⋙ J.diagram_functor D X ⋙ (evaluation (J.cover X)ᵒᵖ D).obj W)) :
E.X ⟶ (J.diagram (limit F) X).obj W :=
multiequalizer.lift _ _ (λ i,
(is_limit_of_preserves ((evaluation _ _).obj (op i.Y)) (limit.is_limit _)).lift
(cone_comp_evaluation_of_cone_comp_diagram_functor_comp_evaluation i E))
begin
intros i,
change (_ ≫ _) ≫ _ = (_ ≫ _) ≫ _,
dsimp [evaluate_combined_cones],
erw [category.comp_id, category.comp_id, category.assoc,
category.assoc, ← (limit.lift F _).naturality, ← (limit.lift F _).naturality,
← category.assoc, ← category.assoc],
congr' 1, ext1,
erw [category.assoc, category.assoc, limit.lift_π, limit.lift_π,
limit.lift_π_assoc, limit.lift_π_assoc, category.assoc,
category.assoc, multiequalizer.condition],
refl,
end
instance (X : C) (K : Type (max v u)) [small_category K] [has_limits_of_shape K D]
(F : K ⥤ Cᵒᵖ ⥤ D) : preserves_limit F (J.diagram_functor D X) :=
preserves_limit_of_evaluation _ _ $ λ W,
preserves_limit_of_preserves_limit_cone (limit.is_limit _)
{ lift := λ E, lift_to_diagram_limit_obj F E,
fac' := begin
intros E k,
dsimp [diagram_nat_trans],
ext1,
simp only [multiequalizer.lift_ι, multiequalizer.lift_ι_assoc, category.assoc],
change (_ ≫ _) ≫ _ = _,
dsimp [evaluate_combined_cones],
erw [category.comp_id, category.assoc, ← nat_trans.comp_app, limit.lift_π, limit.lift_π],
refl,
end,
uniq' := begin
intros E m hm,
ext,
delta lift_to_diagram_limit_obj,
erw [multiequalizer.lift_ι, category.assoc],
change _ = (_ ≫ _) ≫ _,
dsimp [evaluate_combined_cones],
erw [category.comp_id, category.assoc, ← nat_trans.comp_app, limit.lift_π, limit.lift_π],
dsimp,
rw ← hm,
dsimp [diagram_nat_trans],
simp,
end } .
instance (X : C) (K : Type (max v u)) [small_category K] [has_limits_of_shape K D] :
preserves_limits_of_shape K (J.diagram_functor D X) := ⟨⟩
instance (X : C) [has_limits D] : preserves_limits (J.diagram_functor D X) := ⟨⟩
variables [∀ (X : C), has_colimits_of_shape (J.cover X)ᵒᵖ D]
variables [concrete_category.{max v u} D]
variables [∀ (X : C), preserves_colimits_of_shape (J.cover X)ᵒᵖ (forget D)]
/-- An auxiliary definition to be used in the proof that `J.plus_functor D` commutes
with finite limits. -/
def lift_to_plus_obj_limit_obj {K : Type (max v u)} [small_category K] [fin_category K]
[has_limits_of_shape K D] [preserves_limits_of_shape K (forget D)]
[reflects_limits_of_shape K (forget D)] (F : K ⥤ Cᵒᵖ ⥤ D) (X : C)
(S : cone (F ⋙ J.plus_functor D ⋙ (evaluation Cᵒᵖ D).obj (op X))) :
S.X ⟶ (J.plus_obj (limit F)).obj (op X) :=
let
e := colimit_limit_iso (F ⋙ J.diagram_functor D X),
t : J.diagram (limit F) X ≅ limit (F ⋙ J.diagram_functor D X) :=
(is_limit_of_preserves (J.diagram_functor D X) (limit.is_limit _)).cone_point_unique_up_to_iso
(limit.is_limit _),
p : (J.plus_obj (limit F)).obj (op X) ≅ colimit (limit (F ⋙ J.diagram_functor D X)) :=
has_colimit.iso_of_nat_iso t,
s : colimit (F ⋙ J.diagram_functor D X).flip ≅
F ⋙ J.plus_functor D ⋙ (evaluation Cᵒᵖ D).obj (op X) :=
nat_iso.of_components (λ k, colimit_obj_iso_colimit_comp_evaluation _ k) begin
intros i j f,
rw [← iso.eq_comp_inv, category.assoc, ← iso.inv_comp_eq],
ext w,
dsimp [plus_map],
erw [colimit.ι_map_assoc, colimit_obj_iso_colimit_comp_evaluation_ι_inv
((F ⋙ J.diagram_functor D X).flip) w j,
colimit_obj_iso_colimit_comp_evaluation_ι_inv_assoc
((F ⋙ J.diagram_functor D X).flip) w i],
rw ← (colimit.ι (F ⋙ J.diagram_functor D X).flip w).naturality,
refl
end in
limit.lift _ S ≫ (has_limit.iso_of_nat_iso s.symm).hom ≫ e.inv ≫ p.inv
-- This lemma should not be used directly. Instead, one should use the fact that
-- `J.plus_functor D` preserves finite limits, along with the fact that
-- evaluation preserves limits.
lemma lift_to_plus_obj_limit_obj_fac {K : Type (max v u)} [small_category K] [fin_category K]
[has_limits_of_shape K D] [preserves_limits_of_shape K (forget D)]
[reflects_limits_of_shape K (forget D)] (F : K ⥤ Cᵒᵖ ⥤ D) (X : C)
(S : cone (F ⋙ J.plus_functor D ⋙ (evaluation Cᵒᵖ D).obj (op X))) (k) :
lift_to_plus_obj_limit_obj F X S ≫ (J.plus_map (limit.π F k)).app (op X) = S.π.app k :=
begin
dsimp only [lift_to_plus_obj_limit_obj],
rw [← (limit.is_limit (F ⋙ J.plus_functor D ⋙ (evaluation Cᵒᵖ D).obj (op X))).fac S k,
category.assoc],
congr' 1,
dsimp,
simp only [category.assoc],
rw [← iso.eq_inv_comp, iso.inv_comp_eq, iso.inv_comp_eq],
ext,
dsimp [plus_map],
simp only [has_colimit.iso_of_nat_iso_ι_hom_assoc, ι_colim_map],
dsimp [is_limit.cone_point_unique_up_to_iso, has_limit.iso_of_nat_iso,
is_limit.map],
rw limit.lift_π,
dsimp,
rw ι_colimit_limit_iso_limit_π_assoc,
simp_rw [← nat_trans.comp_app, ← category.assoc, ← nat_trans.comp_app],
rw [limit.lift_π, category.assoc],
congr' 1,
rw ← iso.comp_inv_eq,
erw colimit.ι_desc,
refl,
end
instance (K : Type (max v u))
[small_category K] [fin_category K] [has_limits_of_shape K D]
[preserves_limits_of_shape K (forget D)]
[reflects_limits_of_shape K (forget D)] :
preserves_limits_of_shape K (J.plus_functor D) :=
begin
constructor, intros F, apply preserves_limit_of_evaluation, intros X,
apply preserves_limit_of_preserves_limit_cone (limit.is_limit F),
refine ⟨λ S, lift_to_plus_obj_limit_obj F X.unop S, _, _⟩,
{ intros S k,
apply lift_to_plus_obj_limit_obj_fac },
{ intros S m hm,
dsimp [lift_to_plus_obj_limit_obj],
simp_rw [← category.assoc, iso.eq_comp_inv, ← iso.comp_inv_eq],
ext,
simp only [limit.lift_π, category.assoc, ← hm],
congr' 1,
ext,
dsimp [plus_map, plus_obj],
erw [colimit.ι_map, colimit.ι_desc_assoc, limit.lift_π],
dsimp,
simp only [category.assoc],
rw ι_colimit_limit_iso_limit_π_assoc,
simp only [nat_iso.of_components.inv_app,
colimit_obj_iso_colimit_comp_evaluation_ι_app_hom, iso.symm_inv],
dsimp [is_limit.cone_point_unique_up_to_iso],
rw [← category.assoc, ← nat_trans.comp_app, limit.lift_π],
refl }
end
instance [has_finite_limits D] [preserves_finite_limits (forget D)]
[reflects_isomorphisms (forget D)] : preserves_finite_limits (J.plus_functor D) :=
begin
constructor, introsI K _ _,
haveI : reflects_limits_of_shape K (forget D) :=
reflects_limits_of_shape_of_reflects_isomorphisms,
apply_instance
end
instance (K : Type (max v u))
[small_category K] [fin_category K] [has_limits_of_shape K D]
[preserves_limits_of_shape K (forget D)]
[reflects_limits_of_shape K (forget D)] :
preserves_limits_of_shape K (J.sheafification D) :=
limits.comp_preserves_limits_of_shape _ _
instance [has_finite_limits D] [preserves_finite_limits (forget D)]
[reflects_isomorphisms (forget D)] : preserves_finite_limits (J.sheafification D) :=
limits.comp_preserves_finite_limits _ _
end category_theory.grothendieck_topology
namespace category_theory
variables [∀ (X : C), has_colimits_of_shape (J.cover X)ᵒᵖ D]
variables [concrete_category.{max v u} D]
variables [∀ (X : C), preserves_colimits_of_shape (J.cover X)ᵒᵖ (forget D)]
variables [preserves_limits (forget D)]
variables [reflects_isomorphisms (forget D)]
variables (K : Type (max v u))
variables [small_category K] [fin_category K] [has_limits_of_shape K D]
instance : preserves_limits_of_shape K (presheaf_to_Sheaf J D) :=
begin
constructor, intros F, constructor, intros S hS,
apply is_limit_of_reflects (Sheaf_to_presheaf J D),
haveI : reflects_limits_of_shape K (forget D) :=
reflects_limits_of_shape_of_reflects_isomorphisms,
apply is_limit_of_preserves (J.sheafification D) hS,
end
instance [has_finite_limits D] : preserves_finite_limits (presheaf_to_Sheaf J D) :=
⟨λ K _ _, by { resetI, apply_instance }⟩
end category_theory
|
6ca42b54c3265681cca17095430a0ca8376a914d | 947fa6c38e48771ae886239b4edce6db6e18d0fb | /src/number_theory/legendre_symbol/quadratic_char.lean | 97b3738473c1fc80e74c1cdc3d9ca6cf2e4e4b91 | [
"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 | 18,451 | lean | /-
Copyright (c) 2022 Michael Stoll. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Michael Stoll
-/
import number_theory.legendre_symbol.zmod_char
import field_theory.finite.basic
import number_theory.legendre_symbol.gauss_sum
/-!
# Quadratic characters of finite fields
This file defines the quadratic character on a finite field `F` and proves
some basic statements about it.
## Tags
quadratic character
-/
/-!
### Definition of the quadratic character
We define the quadratic character of a finite field `F` with values in ℤ.
-/
section define
/-- Define the quadratic character with values in ℤ on a monoid with zero `α`.
It takes the value zero at zero; for non-zero argument `a : α`, it is `1`
if `a` is a square, otherwise it is `-1`.
This only deserves the name "character" when it is multiplicative,
e.g., when `α` is a finite field. See `quadratic_char_mul`.
We will later define `quadratic_char` to be a multiplicative character
of type `mul_char F ℤ`, when the domain is a finite field `F`.
-/
def quadratic_char_fun (α : Type*) [monoid_with_zero α] [decidable_eq α]
[decidable_pred (is_square : α → Prop)] (a : α) : ℤ :=
if a = 0 then 0 else if is_square a then 1 else -1
end define
/-!
### Basic properties of the quadratic character
We prove some properties of the quadratic character.
We work with a finite field `F` here.
The interesting case is when the characteristic of `F` is odd.
-/
section quadratic_char
open mul_char
variables {F : Type*} [field F] [fintype F] [decidable_eq F]
/-- Some basic API lemmas -/
lemma quadratic_char_eq_zero_iff' {a : F} : quadratic_char_fun F a = 0 ↔ a = 0 :=
begin
simp only [quadratic_char_fun],
by_cases ha : a = 0,
{ simp only [ha, eq_self_iff_true, if_true], },
{ simp only [ha, if_false, iff_false],
split_ifs; simp only [neg_eq_zero, one_ne_zero, not_false_iff], },
end
@[simp]
lemma quadratic_char_zero : quadratic_char_fun F 0 = 0 :=
by simp only [quadratic_char_fun, eq_self_iff_true, if_true, id.def]
@[simp]
lemma quadratic_char_one : quadratic_char_fun F 1 = 1 :=
by simp only [quadratic_char_fun, one_ne_zero, is_square_one, if_true, if_false, id.def]
/-- If `ring_char F = 2`, then `quadratic_char_fun F` takes the value `1` on nonzero elements. -/
lemma quadratic_char_eq_one_of_char_two' (hF : ring_char F = 2) {a : F} (ha : a ≠ 0) :
quadratic_char_fun F a = 1 :=
begin
simp only [quadratic_char_fun, ha, if_false, ite_eq_left_iff],
exact λ h, false.rec _ (h (finite_field.is_square_of_char_two hF a))
end
/-- If `ring_char F` is odd, then `quadratic_char_fun F a` can be computed in
terms of `a ^ (fintype.card F / 2)`. -/
lemma quadratic_char_eq_pow_of_char_ne_two' (hF : ring_char F ≠ 2) {a : F} (ha : a ≠ 0) :
quadratic_char_fun F a = if a ^ (fintype.card F / 2) = 1 then 1 else -1 :=
begin
simp only [quadratic_char_fun, ha, if_false],
simp_rw finite_field.is_square_iff hF ha,
end
/-- The quadratic character is multiplicative. -/
lemma quadratic_char_mul (a b : F) :
quadratic_char_fun F (a * b) = quadratic_char_fun F a * quadratic_char_fun F b :=
begin
by_cases ha : a = 0,
{ rw [ha, zero_mul, quadratic_char_zero, zero_mul], },
-- now `a ≠ 0`
by_cases hb : b = 0,
{ rw [hb, mul_zero, quadratic_char_zero, mul_zero], },
-- now `a ≠ 0` and `b ≠ 0`
have hab := mul_ne_zero ha hb,
by_cases hF : ring_char F = 2,
{ -- case `ring_char F = 2`
rw [quadratic_char_eq_one_of_char_two' hF ha,
quadratic_char_eq_one_of_char_two' hF hb,
quadratic_char_eq_one_of_char_two' hF hab,
mul_one], },
{ -- case of odd characteristic
rw [quadratic_char_eq_pow_of_char_ne_two' hF ha,
quadratic_char_eq_pow_of_char_ne_two' hF hb,
quadratic_char_eq_pow_of_char_ne_two' hF hab,
mul_pow],
cases finite_field.pow_dichotomy hF hb with hb' hb',
{ simp only [hb', mul_one, eq_self_iff_true, if_true], },
{ have h := ring.neg_one_ne_one_of_char_ne_two hF, -- `-1 ≠ 1`
simp only [hb', h, mul_neg, mul_one, if_false, ite_mul, neg_mul],
cases finite_field.pow_dichotomy hF ha with ha' ha';
simp only [ha', h, neg_neg, eq_self_iff_true, if_true, if_false], }, },
end
variables (F)
/-- The quadratic character as a multiplicative character. -/
@[simps] def quadratic_char : mul_char F ℤ :=
{ to_fun := quadratic_char_fun F,
map_one' := quadratic_char_one,
map_mul' := quadratic_char_mul,
map_nonunit' := λ a ha, by { rw of_not_not (mt ne.is_unit ha), exact quadratic_char_zero, } }
variables {F}
/-- The value of the quadratic character on `a` is zero iff `a = 0`. -/
lemma quadratic_char_eq_zero_iff {a : F} : quadratic_char F a = 0 ↔ a = 0 :=
quadratic_char_eq_zero_iff'
/-- For nonzero `a : F`, `quadratic_char F a = 1 ↔ is_square a`. -/
lemma quadratic_char_one_iff_is_square {a : F} (ha : a ≠ 0) :
quadratic_char F a = 1 ↔ is_square a :=
by simp only [quadratic_char_apply, quadratic_char_fun, ha, (dec_trivial : (-1 : ℤ) ≠ 1),
if_false, ite_eq_left_iff, imp_false, not_not]
/-- The quadratic character takes the value `1` on nonzero squares. -/
lemma quadratic_char_sq_one' {a : F} (ha : a ≠ 0) : quadratic_char F (a ^ 2) = 1 :=
by simp only [quadratic_char_fun, ha, pow_eq_zero_iff, nat.succ_pos', is_square_sq, if_true,
if_false, quadratic_char_apply]
/-- The square of the quadratic character on nonzero arguments is `1`. -/
lemma quadratic_char_sq_one {a : F} (ha : a ≠ 0) : (quadratic_char F a) ^ 2 = 1 :=
by rwa [pow_two, ← map_mul, ← pow_two, quadratic_char_sq_one']
/-- The quadratic character is `1` or `-1` on nonzero arguments. -/
lemma quadratic_char_dichotomy {a : F} (ha : a ≠ 0) :
quadratic_char F a = 1 ∨ quadratic_char F a = -1 :=
sq_eq_one_iff.1 $ quadratic_char_sq_one ha
/-- The quadratic character is `1` or `-1` on nonzero arguments. -/
lemma quadratic_char_eq_neg_one_iff_not_one {a : F} (ha : a ≠ 0) :
quadratic_char F a = -1 ↔ ¬ quadratic_char F a = 1 :=
begin
refine ⟨λ h, _, λ h₂, (or_iff_right h₂).mp (quadratic_char_dichotomy ha)⟩,
rw h,
norm_num,
end
/-- For `a : F`, `quadratic_char F a = -1 ↔ ¬ is_square a`. -/
lemma quadratic_char_neg_one_iff_not_is_square {a : F} :
quadratic_char F a = -1 ↔ ¬ is_square a :=
begin
by_cases ha : a = 0,
{ simp only [ha, is_square_zero, mul_char.map_zero, zero_eq_neg, one_ne_zero, not_true], },
{ rw [quadratic_char_eq_neg_one_iff_not_one ha, quadratic_char_one_iff_is_square ha] },
end
/-- If `F` has odd characteristic, then `quadratic_char F` takes the value `-1`. -/
lemma quadratic_char_exists_neg_one (hF : ring_char F ≠ 2) : ∃ a, quadratic_char F a = -1 :=
(finite_field.exists_nonsquare hF).imp $ λ b h₁, quadratic_char_neg_one_iff_not_is_square.mpr h₁
/-- If `ring_char F = 2`, then `quadratic_char F` takes the value `1` on nonzero elements. -/
lemma quadratic_char_eq_one_of_char_two (hF : ring_char F = 2) {a : F} (ha : a ≠ 0) :
quadratic_char F a = 1 :=
quadratic_char_eq_one_of_char_two' hF ha
/-- If `ring_char F` is odd, then `quadratic_char F a` can be computed in
terms of `a ^ (fintype.card F / 2)`. -/
lemma quadratic_char_eq_pow_of_char_ne_two (hF : ring_char F ≠ 2) {a : F} (ha : a ≠ 0) :
quadratic_char F a = if a ^ (fintype.card F / 2) = 1 then 1 else -1 :=
quadratic_char_eq_pow_of_char_ne_two' hF ha
lemma quadratic_char_eq_pow_of_char_ne_two'' (hF : ring_char F ≠ 2) (a : F) :
(quadratic_char F a : F) = a ^ (fintype.card F / 2) :=
begin
by_cases ha : a = 0,
{ have : 0 < fintype.card F / 2 := nat.div_pos fintype.one_lt_card two_pos,
simp only [ha, zero_pow this, quadratic_char_apply, quadratic_char_zero, int.cast_zero], },
{ rw [quadratic_char_eq_pow_of_char_ne_two hF ha],
by_cases ha' : a ^ (fintype.card F / 2) = 1,
{ simp only [ha', eq_self_iff_true, if_true, int.cast_one], },
{ have ha'' := or.resolve_left (finite_field.pow_dichotomy hF ha) ha',
simp only [ha'', int.cast_ite, int.cast_one, int.cast_neg, ite_eq_right_iff],
exact eq.symm, } }
end
variables (F)
/-- The quadratic character is quadratic as a multiplicative character. -/
lemma quadratic_char_is_quadratic : (quadratic_char F).is_quadratic :=
begin
intro a,
by_cases ha : a = 0,
{ left, rw ha, exact quadratic_char_zero, },
{ right, exact quadratic_char_dichotomy ha, },
end
variables {F}
/-- The quadratic character is nontrivial as a multiplicative character
when the domain has odd characteristic. -/
lemma quadratic_char_is_nontrivial (hF : ring_char F ≠ 2) : (quadratic_char F).is_nontrivial :=
begin
rcases quadratic_char_exists_neg_one hF with ⟨a, ha⟩,
have hu : is_unit a := by { by_contra hf, rw map_nonunit _ hf at ha, norm_num at ha, },
refine ⟨hu.unit, (_ : quadratic_char F a ≠ 1)⟩,
rw ha,
norm_num,
end
/-- The number of solutions to `x^2 = a` is determined by the quadratic character. -/
lemma quadratic_char_card_sqrts (hF : ring_char F ≠ 2) (a : F) :
↑{x : F | x^2 = a}.to_finset.card = quadratic_char F a + 1 :=
begin
-- we consider the cases `a = 0`, `a` is a nonzero square and `a` is a nonsquare in turn
by_cases h₀ : a = 0,
{ simp only [h₀, pow_eq_zero_iff, nat.succ_pos', int.coe_nat_succ, int.coe_nat_zero,
mul_char.map_zero, set.set_of_eq_eq_singleton, set.to_finset_card,
set.card_singleton], },
{ set s := {x : F | x^2 = a}.to_finset with hs,
by_cases h : is_square a,
{ rw (quadratic_char_one_iff_is_square h₀).mpr h,
rcases h with ⟨b, h⟩,
rw [h, mul_self_eq_zero] at h₀,
have h₁ : s = [b, -b].to_finset := by
{ ext x,
simp only [finset.mem_filter, finset.mem_univ, true_and, list.to_finset_cons,
list.to_finset_nil, insert_emptyc_eq, finset.mem_insert, finset.mem_singleton],
rw ← pow_two at h,
simp only [hs, set.mem_to_finset, set.mem_set_of_eq, h],
split,
{ exact eq_or_eq_neg_of_sq_eq_sq _ _, },
{ rintro (h₂ | h₂); rw h₂,
simp only [neg_sq], }, },
norm_cast,
rw [h₁, list.to_finset_cons, list.to_finset_cons, list.to_finset_nil],
exact finset.card_doubleton
(ne.symm (mt (ring.eq_self_iff_eq_zero_of_char_ne_two hF).mp h₀)), },
{ rw quadratic_char_neg_one_iff_not_is_square.mpr h,
simp only [int.coe_nat_eq_zero, finset.card_eq_zero, set.to_finset_card,
fintype.card_of_finset, set.mem_set_of_eq, add_left_neg],
ext x,
simp only [iff_false, finset.mem_filter, finset.mem_univ, true_and, finset.not_mem_empty],
rw is_square_iff_exists_sq at h,
exact λ h', h ⟨_, h'.symm⟩, }, },
end
open_locale big_operators
/-- The sum over the values of the quadratic character is zero when the characteristic is odd. -/
lemma quadratic_char_sum_zero (hF : ring_char F ≠ 2) : ∑ (a : F), quadratic_char F a = 0 :=
is_nontrivial.sum_eq_zero (quadratic_char_is_nontrivial hF)
end quadratic_char
/-!
### Special values of the quadratic character
We express `quadratic_char F (-1)` in terms of `χ₄`.
-/
section special_values
open zmod mul_char
variables {F : Type} [field F] [fintype F]
/-- The value of the quadratic character at `-1` -/
lemma quadratic_char_neg_one [decidable_eq F] (hF : ring_char F ≠ 2) :
quadratic_char F (-1) = χ₄ (fintype.card F) :=
begin
have h := quadratic_char_eq_pow_of_char_ne_two hF (neg_ne_zero.mpr one_ne_zero),
rw [h, χ₄_eq_neg_one_pow (finite_field.odd_card_of_char_ne_two hF)],
set n := fintype.card F / 2,
cases (nat.even_or_odd n) with h₂ h₂,
{ simp only [even.neg_one_pow h₂, eq_self_iff_true, if_true], },
{ simp only [odd.neg_one_pow h₂, ite_eq_right_iff],
exact λ hf, false.rec (1 = -1) (ring.neg_one_ne_one_of_char_ne_two hF hf), },
end
/-- `-1` is a square in `F` iff `#F` is not congruent to `3` mod `4`. -/
lemma finite_field.is_square_neg_one_iff : is_square (-1 : F) ↔ fintype.card F % 4 ≠ 3 :=
begin
classical, -- suggested by the linter (instead of `[decidable_eq F]`)
by_cases hF : ring_char F = 2,
{ simp only [finite_field.is_square_of_char_two hF, ne.def, true_iff],
exact (λ hf, one_ne_zero $ (nat.odd_of_mod_four_eq_three hf).symm.trans
$ finite_field.even_card_of_char_two hF) },
{ have h₁ := finite_field.odd_card_of_char_ne_two hF,
rw [← quadratic_char_one_iff_is_square (neg_ne_zero.mpr (@one_ne_zero F _ _)),
quadratic_char_neg_one hF, χ₄_nat_eq_if_mod_four, h₁],
simp only [nat.one_ne_zero, if_false, ite_eq_left_iff, ne.def, (dec_trivial : (-1 : ℤ) ≠ 1),
imp_false, not_not],
exact ⟨λ h, ne_of_eq_of_ne h (dec_trivial : 1 ≠ 3),
or.resolve_right (nat.odd_mod_four_iff.mp h₁)⟩, },
end
/-- The value of the quadratic character at `2` -/
lemma quadratic_char_two [decidable_eq F] (hF : ring_char F ≠ 2) :
quadratic_char F 2 = χ₈ (fintype.card F) :=
is_quadratic.eq_of_eq_coe (quadratic_char_is_quadratic F) is_quadratic_χ₈ hF
((quadratic_char_eq_pow_of_char_ne_two'' hF 2).trans (finite_field.two_pow_card hF))
/-- `2` is a square in `F` iff `#F` is not congruent to `3` or `5` mod `8`. -/
lemma finite_field.is_square_two_iff :
is_square (2 : F) ↔ fintype.card F % 8 ≠ 3 ∧ fintype.card F % 8 ≠ 5 :=
begin
classical,
by_cases hF : ring_char F = 2,
focus
{ have h := finite_field.even_card_of_char_two hF,
simp only [finite_field.is_square_of_char_two hF, true_iff], },
rotate, focus
{ have h := finite_field.odd_card_of_char_ne_two hF,
rw [← quadratic_char_one_iff_is_square (ring.two_ne_zero hF), quadratic_char_two hF,
χ₈_nat_eq_if_mod_eight],
simp only [h, nat.one_ne_zero, if_false, ite_eq_left_iff, ne.def, (dec_trivial : (-1 : ℤ) ≠ 1),
imp_false, not_not], },
all_goals
{ rw [← nat.mod_mod_of_dvd _ (by norm_num : 2 ∣ 8)] at h,
have h₁ := nat.mod_lt (fintype.card F) (dec_trivial : 0 < 8),
revert h₁ h,
generalize : fintype.card F % 8 = n,
dec_trivial!, }
end
/-- The value of the quadratic character at `-2` -/
lemma quadratic_char_neg_two [decidable_eq F] (hF : ring_char F ≠ 2) :
quadratic_char F (-2) = χ₈' (fintype.card F) :=
begin
rw [(by norm_num : (-2 : F) = (-1) * 2), map_mul, χ₈'_eq_χ₄_mul_χ₈, quadratic_char_neg_one hF,
quadratic_char_two hF, @cast_nat_cast _ (zmod 4) _ _ _ (by norm_num : 4 ∣ 8)],
end
/-- `-2` is a square in `F` iff `#F` is not congruent to `5` or `7` mod `8`. -/
lemma finite_field.is_square_neg_two_iff :
is_square (-2 : F) ↔ fintype.card F % 8 ≠ 5 ∧ fintype.card F % 8 ≠ 7 :=
begin
classical,
by_cases hF : ring_char F = 2,
focus
{ have h := finite_field.even_card_of_char_two hF,
simp only [finite_field.is_square_of_char_two hF, true_iff], },
rotate, focus
{ have h := finite_field.odd_card_of_char_ne_two hF,
rw [← quadratic_char_one_iff_is_square (neg_ne_zero.mpr (ring.two_ne_zero hF)),
quadratic_char_neg_two hF, χ₈'_nat_eq_if_mod_eight],
simp only [h, nat.one_ne_zero, if_false, ite_eq_left_iff, ne.def, (dec_trivial : (-1 : ℤ) ≠ 1),
imp_false, not_not], },
all_goals
{ rw [← nat.mod_mod_of_dvd _ (by norm_num : 2 ∣ 8)] at h,
have h₁ := nat.mod_lt (fintype.card F) (dec_trivial : 0 < 8),
revert h₁ h,
generalize : fintype.card F % 8 = n,
dec_trivial! }
end
/-- The relation between the values of the quadratic character of one field `F` at the
cardinality of another field `F'` and of the quadratic character of `F'` at the cardinality
of `F`. -/
lemma quadratic_char_card_card [decidable_eq F] (hF : ring_char F ≠ 2) {F' : Type} [field F']
[fintype F'] [decidable_eq F'] (hF' : ring_char F' ≠ 2) (h : ring_char F' ≠ ring_char F) :
quadratic_char F (fintype.card F') = quadratic_char F' (quadratic_char F (-1) * fintype.card F) :=
begin
let χ := (quadratic_char F).ring_hom_comp (algebra_map ℤ F'),
have hχ₁ : χ.is_nontrivial,
{ obtain ⟨a, ha⟩ := quadratic_char_exists_neg_one hF,
have hu : is_unit a,
{ contrapose ha,
exact ne_of_eq_of_ne (map_nonunit (quadratic_char F) ha)
(mt zero_eq_neg.mp one_ne_zero), },
use hu.unit,
simp only [is_unit.unit_spec, ring_hom_comp_apply, ring_hom.eq_int_cast, ne.def, ha],
rw [int.cast_neg, int.cast_one],
exact ring.neg_one_ne_one_of_char_ne_two hF', },
have hχ₂ : χ.is_quadratic := is_quadratic.comp (quadratic_char_is_quadratic F) _,
have h := char.card_pow_card hχ₁ hχ₂ h hF',
rw [← quadratic_char_eq_pow_of_char_ne_two'' hF'] at h,
exact (is_quadratic.eq_of_eq_coe (quadratic_char_is_quadratic F')
(quadratic_char_is_quadratic F) hF' h).symm,
end
/-- The value of the quadratic character at an odd prime `p` different from `ring_char F`. -/
lemma quadratic_char_odd_prime [decidable_eq F] (hF : ring_char F ≠ 2) {p : ℕ} [fact p.prime]
(hp₁ : p ≠ 2) (hp₂ : ring_char F ≠ p) :
quadratic_char F p = quadratic_char (zmod p) (χ₄ (fintype.card F) * fintype.card F) :=
begin
rw [← quadratic_char_neg_one hF],
have h := quadratic_char_card_card hF (ne_of_eq_of_ne (ring_char_zmod_n p) hp₁)
(ne_of_eq_of_ne (ring_char_zmod_n p) hp₂.symm),
rwa [card p] at h,
end
/-- An odd prime `p` is a square in `F` iff the quadratic character of `zmod p` does not
take the value `-1` on `χ₄(#F) * #F`. -/
lemma finite_field.is_square_odd_prime_iff (hF : ring_char F ≠ 2) {p : ℕ} [fact p.prime]
(hp : p ≠ 2) :
is_square (p : F) ↔ quadratic_char (zmod p) (χ₄ (fintype.card F) * fintype.card F) ≠ -1 :=
begin
classical,
by_cases hFp : ring_char F = p,
{ rw [show (p : F) = 0, by { rw ← hFp, exact ring_char.nat.cast_ring_char }],
simp only [is_square_zero, ne.def, true_iff, map_mul],
obtain ⟨n, _, hc⟩ := finite_field.card F (ring_char F),
have hchar : ring_char F = ring_char (zmod p) := by {rw hFp, exact (ring_char_zmod_n p).symm},
conv {congr, to_lhs, congr, skip, rw [hc, nat.cast_pow, map_pow, hchar, map_ring_char], },
simp only [zero_pow n.pos, mul_zero, zero_eq_neg, one_ne_zero, not_false_iff], },
{ rw [← iff.not_left (@quadratic_char_neg_one_iff_not_is_square F _ _ _ _),
quadratic_char_odd_prime hF hp],
exact hFp, },
end
end special_values
|
be218e4cee225b9eb37a0b2ef7ec0bcab25257ed | 94e33a31faa76775069b071adea97e86e218a8ee | /src/category_theory/preadditive/Mat.lean | 6e0685e0c24c758fd8b26d55e3104c037ae258a8 | [
"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 | 18,689 | 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.big_operators.basic
import algebra.big_operators.pi
import category_theory.limits.shapes.biproducts
import category_theory.preadditive
import category_theory.preadditive.additive_functor
import data.matrix.dmatrix
import data.matrix.basic
import category_theory.Fintype
import category_theory.preadditive.single_obj
import algebra.opposites
/-!
# Matrices over a category.
When `C` is a preadditive category, `Mat_ C` is the preadditive category
whose objects are finite tuples of objects in `C`, and
whose morphisms are matrices of morphisms from `C`.
There is a functor `Mat_.embedding : C ⥤ Mat_ C` sending morphisms to one-by-one matrices.
`Mat_ C` has finite biproducts.
## The additive envelope
We show that this construction is the "additive envelope" of `C`,
in the sense that any additive functor `F : C ⥤ D` to a category `D` with biproducts
lifts to a functor `Mat_.lift F : Mat_ C ⥤ D`,
Moreover, this functor is unique (up to natural isomorphisms) amongst functors `L : Mat_ C ⥤ D`
such that `embedding C ⋙ L ≅ F`.
(As we don't have 2-category theory, we can't explicitly state that `Mat_ C` is
the initial object in the 2-category of categories under `C` which have biproducts.)
As a consequence, when `C` already has finite biproducts we have `Mat_ C ≌ C`.
## Future work
We should provide a more convenient `Mat R`, when `R` is a ring,
as a category with objects `n : FinType`,
and whose morphisms are matrices with components in `R`.
Ideally this would conveniently interact with both `Mat_` and `matrix`.
-/
open category_theory category_theory.preadditive
open_locale big_operators classical
noncomputable theory
namespace category_theory
universes w v₁ v₂ u₁ u₂
variables (C : Type u₁) [category.{v₁} C] [preadditive C]
/--
An object in `Mat_ C` is a finite tuple of objects in `C`.
-/
structure Mat_ :=
(ι : Type)
[F : fintype ι]
(X : ι → C)
attribute [instance] Mat_.F
namespace Mat_
variables {C}
/-- A morphism in `Mat_ C` is a dependently typed matrix of morphisms. -/
@[nolint has_inhabited_instance]
def hom (M N : Mat_ C) : Type v₁ := dmatrix M.ι N.ι (λ i j, M.X i ⟶ N.X j)
namespace hom
/-- The identity matrix consists of identity morphisms on the diagonal, and zeros elsewhere. -/
def id (M : Mat_ C) : hom M M := λ i j, if h : i = j then eq_to_hom (congr_arg M.X h) else 0
/-- Composition of matrices using matrix multiplication. -/
def comp {M N K : Mat_ C} (f : hom M N) (g : hom N K) : hom M K :=
λ i k, ∑ j : N.ι, f i j ≫ g j k
end hom
section
local attribute [simp] hom.id hom.comp
instance : category.{v₁} (Mat_ C) :=
{ hom := hom,
id := hom.id,
comp := λ M N K f g, f.comp g,
id_comp' := λ M N f, by simp [dite_comp],
comp_id' := λ M N f, by simp [comp_dite],
assoc' := λ M N K L f g h, begin
ext i k,
simp_rw [hom.comp, sum_comp, comp_sum, category.assoc],
rw finset.sum_comm,
end, }.
lemma id_def (M : Mat_ C) :
(𝟙 M : hom M M) = λ i j, if h : i = j then eq_to_hom (congr_arg M.X h) else 0 :=
rfl
lemma id_apply (M : Mat_ C) (i j : M.ι) :
(𝟙 M : hom M M) i j = if h : i = j then eq_to_hom (congr_arg M.X h) else 0 :=
rfl
@[simp] lemma id_apply_self (M : Mat_ C) (i : M.ι) :
(𝟙 M : hom M M) i i = 𝟙 _ :=
by simp [id_apply]
@[simp] lemma id_apply_of_ne (M : Mat_ C) (i j : M.ι) (h : i ≠ j) :
(𝟙 M : hom M M) i j = 0 :=
by simp [id_apply, h]
lemma comp_def {M N K : Mat_ C} (f : M ⟶ N) (g : N ⟶ K) :
(f ≫ g) = λ i k, ∑ j : N.ι, f i j ≫ g j k := rfl
@[simp] lemma comp_apply {M N K : Mat_ C} (f : M ⟶ N) (g : N ⟶ K) (i k) :
(f ≫ g) i k = ∑ j : N.ι, f i j ≫ g j k := rfl
instance (M N : Mat_ C) : inhabited (M ⟶ N) := ⟨λ i j, (0 : M.X i ⟶ N.X j)⟩
end
instance : preadditive (Mat_ C) :=
{ hom_group := λ M N, by { change add_comm_group (dmatrix M.ι N.ι _), apply_instance, },
add_comp' := λ M N K f f' g, by { ext, simp [finset.sum_add_distrib], },
comp_add' := λ M N K f g g', by { ext, simp [finset.sum_add_distrib], }, }
@[simp] lemma add_apply {M N : Mat_ C} (f g : M ⟶ N) (i j) : (f + g) i j = f i j + g i j := rfl
open category_theory.limits
/--
We now prove that `Mat_ C` has finite biproducts.
Be warned, however, that `Mat_ C` is not necessarily Krull-Schmidt,
and so the internal indexing of a biproduct may have nothing to do with the external indexing,
even though the construction we give uses a sigma type.
See however `iso_biproduct_embedding`.
-/
instance has_finite_biproducts : has_finite_biproducts (Mat_ C) :=
{ has_biproducts_of_shape := λ J 𝒟, by exactI
{ has_biproduct := λ f,
has_biproduct_of_total
{ X := ⟨Σ j : J, (f j).ι, λ p, (f p.1).X p.2⟩,
π := λ j x y,
begin
dsimp at x ⊢,
refine if h : x.1 = j then _ else 0,
refine if h' : (@eq.rec J x.1 (λ j, (f j).ι) x.2 _ h) = y then _ else 0,
apply eq_to_hom,
substs h h', -- Notice we were careful not to use `subst` until we had a goal in `Prop`.
end,
ι := λ j x y,
begin
dsimp at y ⊢,
refine if h : y.1 = j then _ else 0,
refine if h' : (@eq.rec J y.1 (λ j, (f j).ι) y.2 _ h) = x then _ else 0,
apply eq_to_hom,
substs h h',
end,
ι_π := λ j j',
begin
ext x y,
dsimp,
simp_rw [dite_comp, comp_dite],
simp only [if_t_t, dite_eq_ite, dif_ctx_congr, limits.comp_zero, limits.zero_comp,
eq_to_hom_trans, finset.sum_congr],
erw finset.sum_sigma,
dsimp,
simp only [if_congr, if_true, dif_ctx_congr, finset.sum_dite_irrel, finset.mem_univ,
finset.sum_const_zero, finset.sum_congr, finset.sum_dite_eq'],
split_ifs with h h',
{ substs h h',
simp only [category_theory.eq_to_hom_refl, category_theory.Mat_.id_apply_self], },
{ subst h,
simp only [id_apply_of_ne _ _ _ h', category_theory.eq_to_hom_refl], },
{ refl, },
end, }
begin
dsimp,
funext i₁,
dsimp at i₁ ⊢,
rcases i₁ with ⟨j₁, i₁⟩,
-- I'm not sure why we can't just `simp` by `finset.sum_apply`: something doesn't quite match
convert finset.sum_apply _ _ _ using 1,
{ refl, },
{ apply heq_of_eq,
symmetry,
funext i₂,
rcases i₂ with ⟨j₂, i₂⟩,
simp only [comp_apply, dite_comp, comp_dite,
if_t_t, dite_eq_ite, if_congr, if_true, dif_ctx_congr,
finset.sum_dite_irrel, finset.sum_dite_eq, finset.mem_univ, finset.sum_const_zero,
finset.sum_congr, finset.sum_dite_eq, finset.sum_apply,
limits.comp_zero, limits.zero_comp, eq_to_hom_trans, Mat_.id_apply],
by_cases h : j₁ = j₂,
{ subst h, simp, },
{ simp [h], }, },
end }}.
end Mat_
namespace functor
variables {C} {D : Type*} [category.{v₁} D] [preadditive D]
local attribute [simp] Mat_.id_apply eq_to_hom_map
/--
A functor induces a functor of matrix categories.
-/
@[simps]
def map_Mat_ (F : C ⥤ D) [functor.additive F] : Mat_ C ⥤ Mat_ D :=
{ obj := λ M, ⟨M.ι, λ i, F.obj (M.X i)⟩,
map := λ M N f i j, F.map (f i j),
map_comp' := λ M N K f g, by { ext i k, simp,}, }
/--
The identity functor induces the identity functor on matrix categories.
-/
@[simps]
def map_Mat_id : (𝟭 C).map_Mat_ ≅ 𝟭 (Mat_ C) :=
nat_iso.of_components (λ M, eq_to_iso (by { cases M, refl, }))
(λ M N f, begin
ext i j,
cases M, cases N,
simp [comp_dite, dite_comp],
end)
/--
Composite functors induce composite functors on matrix categories.
-/
@[simps]
def map_Mat_comp {E : Type*} [category.{v₁} E] [preadditive E]
(F : C ⥤ D) [functor.additive F] (G : D ⥤ E) [functor.additive G] :
(F ⋙ G).map_Mat_ ≅ F.map_Mat_ ⋙ G.map_Mat_ :=
nat_iso.of_components (λ M, eq_to_iso (by { cases M, refl, }))
(λ M N f, begin
ext i j,
cases M, cases N,
simp [comp_dite, dite_comp],
end)
end functor
namespace Mat_
variables (C)
/-- The embedding of `C` into `Mat_ C` as one-by-one matrices.
(We index the summands by `punit`.) -/
@[simps]
def embedding : C ⥤ Mat_ C :=
{ obj := λ X, ⟨punit, λ _, X⟩,
map := λ X Y f, λ _ _, f,
map_id' := λ X, by { ext ⟨⟩ ⟨⟩, simp, },
map_comp' := λ X Y Z f g, by { ext ⟨⟩ ⟨⟩, simp, }, }
namespace embedding
instance : faithful (embedding C) :=
{ map_injective' := λ X Y f g h, congr_fun (congr_fun h punit.star) punit.star, }
instance : full (embedding C) :=
{ preimage := λ X Y f, f punit.star punit.star, }
instance : functor.additive (embedding C) := {}
end embedding
instance [inhabited C] : inhabited (Mat_ C) := ⟨(embedding C).obj default⟩
open category_theory.limits
variables {C}
/--
Every object in `Mat_ C` is isomorphic to the biproduct of its summands.
-/
@[simps]
def iso_biproduct_embedding (M : Mat_ C) : M ≅ ⨁ (λ i, (embedding C).obj (M.X i)) :=
{ hom := biproduct.lift (λ i j k, if h : j = i then eq_to_hom (congr_arg M.X h) else 0),
inv := biproduct.desc (λ i j k, if h : i = k then eq_to_hom (congr_arg M.X h) else 0),
hom_inv_id' :=
begin
simp only [biproduct.lift_desc],
funext i,
dsimp,
convert finset.sum_apply _ _ _,
{ dsimp, refl, },
{ apply heq_of_eq,
symmetry,
funext j,
simp only [finset.sum_apply],
dsimp,
simp [dite_comp, comp_dite, Mat_.id_apply], }
end,
inv_hom_id' :=
begin
apply biproduct.hom_ext,
intro i,
apply biproduct.hom_ext',
intro j,
simp only [category.id_comp, category.assoc,
biproduct.lift_π, biproduct.ι_desc_assoc, biproduct.ι_π],
ext ⟨⟩ ⟨⟩,
simp [dite_comp, comp_dite],
split_ifs,
{ subst h, simp, },
{ simp [h], },
end, }.
variables {D : Type u₁} [category.{v₁} D] [preadditive D]
/-- Every `M` is a direct sum of objects from `C`, and `F` preserves biproducts. -/
@[simps]
def additive_obj_iso_biproduct (F : Mat_ C ⥤ D) [functor.additive F] (M : Mat_ C) :
F.obj M ≅ ⨁ (λ i, F.obj ((embedding C).obj (M.X i))) :=
(F.map_iso (iso_biproduct_embedding M)) ≪≫ (F.map_biproduct _)
variables [has_finite_biproducts D]
@[reassoc] lemma additive_obj_iso_biproduct_naturality (F : Mat_ C ⥤ D) [functor.additive F]
{M N : Mat_ C} (f : M ⟶ N) :
F.map f ≫ (additive_obj_iso_biproduct F N).hom =
(additive_obj_iso_biproduct F M).hom ≫
biproduct.matrix (λ i j, F.map ((embedding C).map (f i j))) :=
begin
-- This is disappointingly tedious.
ext,
simp only [additive_obj_iso_biproduct_hom, category.assoc, biproduct.lift_π, functor.map_bicone_π,
biproduct.bicone_π, biproduct.lift_matrix],
dsimp [embedding],
simp only [←F.map_comp, biproduct.lift_π, biproduct.matrix_π, category.assoc],
simp only [←F.map_comp, ←F.map_sum, biproduct.lift_desc, biproduct.lift_π_assoc, comp_sum],
simp only [comp_def, comp_dite, comp_zero, finset.sum_dite_eq', finset.mem_univ, if_true],
dsimp,
simp only [finset.sum_singleton, dite_comp, zero_comp],
congr,
symmetry,
convert finset.sum_fn _ _, -- It's hard to use this as a simp lemma!
simp only [finset.sum_fn, finset.sum_dite_eq],
ext,
simp,
end
@[reassoc] lemma additive_obj_iso_biproduct_naturality' (F : Mat_ C ⥤ D) [functor.additive F]
{M N : Mat_ C} (f : M ⟶ N) :
(additive_obj_iso_biproduct F M).inv ≫ F.map f =
biproduct.matrix (λ i j, F.map ((embedding C).map (f i j)) : _) ≫
(additive_obj_iso_biproduct F N).inv :=
by rw [iso.inv_comp_eq, ←category.assoc, iso.eq_comp_inv, additive_obj_iso_biproduct_naturality]
/-- Any additive functor `C ⥤ D` to a category `D` with finite biproducts extends to
a functor `Mat_ C ⥤ D`. -/
@[simps]
def lift (F : C ⥤ D) [functor.additive F] : Mat_ C ⥤ D :=
{ obj := λ X, ⨁ (λ i, F.obj (X.X i)),
map := λ X Y f, biproduct.matrix (λ i j, F.map (f i j)),
map_id' := λ X, begin
ext i j,
by_cases h : i = j,
{ subst h, simp, },
{ simp [h, Mat_.id_apply], },
end,
map_comp' := λ X Y Z f g, by { ext i j, simp, }, }.
instance lift_additive (F : C ⥤ D) [functor.additive F] : functor.additive (lift F) := {}
/-- An additive functor `C ⥤ D` factors through its lift to `Mat_ C ⥤ D`. -/
@[simps]
def embedding_lift_iso (F : C ⥤ D) [functor.additive F] : embedding C ⋙ lift F ≅ F :=
nat_iso.of_components (λ X,
{ hom := biproduct.desc (λ P, 𝟙 (F.obj X)),
inv := biproduct.lift (λ P, 𝟙 (F.obj X)), })
(λ X Y f, begin
dsimp,
ext,
simp only [category.id_comp, biproduct.ι_desc_assoc],
erw biproduct.ι_matrix_assoc, -- Not sure why this doesn't fire via `simp`.
simp,
end).
/--
`Mat_.lift F` is the unique additive functor `L : Mat_ C ⥤ D` such that `F ≅ embedding C ⋙ L`.
-/
def lift_unique (F : C ⥤ D) [functor.additive F] (L : Mat_ C ⥤ D) [functor.additive L]
(α : embedding C ⋙ L ≅ F) :
L ≅ lift F :=
nat_iso.of_components
(λ M, (additive_obj_iso_biproduct L M) ≪≫
(biproduct.map_iso (λ i, α.app (M.X i))) ≪≫
(biproduct.map_iso (λ i, (embedding_lift_iso F).symm.app (M.X i))) ≪≫
(additive_obj_iso_biproduct (lift F) M).symm)
(λ M N f, begin
dsimp only [iso.trans_hom, iso.symm_hom, biproduct.map_iso_hom],
simp only [additive_obj_iso_biproduct_naturality_assoc],
simp only [biproduct.matrix_map_assoc, category.assoc],
simp only [additive_obj_iso_biproduct_naturality'],
simp only [biproduct.map_matrix_assoc, category.assoc],
congr,
ext j k ⟨⟩,
dsimp, simp,
exact α.hom.naturality (f j k),
end).
-- TODO is there some uniqueness statement for the natural isomorphism in `lift_unique`?
/-- Two additive functors `Mat_ C ⥤ D` are naturally isomorphic if
their precompositions with `embedding C` are naturally isomorphic as functors `C ⥤ D`. -/
@[ext]
def ext {F G : Mat_ C ⥤ D} [functor.additive F] [functor.additive G]
(α : embedding C ⋙ F ≅ embedding C ⋙ G) : F ≅ G :=
(lift_unique (embedding C ⋙ G) _ α) ≪≫ (lift_unique _ _ (iso.refl _)).symm
/--
Natural isomorphism needed in the construction of `equivalence_self_of_has_finite_biproducts`.
-/
def equivalence_self_of_has_finite_biproducts_aux [has_finite_biproducts C] :
embedding C ⋙ 𝟭 (Mat_ C) ≅ embedding C ⋙ lift (𝟭 C) ⋙ embedding C :=
functor.right_unitor _ ≪≫
(functor.left_unitor _).symm ≪≫
(iso_whisker_right (embedding_lift_iso _).symm _) ≪≫
functor.associator _ _ _
/--
A preadditive category that already has finite biproducts is equivalent to its additive envelope.
Note that we only prove this for a large category;
otherwise there are universe issues that I haven't attempted to sort out.
-/
def equivalence_self_of_has_finite_biproducts
(C : Type (u₁+1)) [large_category C] [preadditive C] [has_finite_biproducts C] :
Mat_ C ≌ C :=
equivalence.mk -- I suspect this is already an adjoint equivalence, but it seems painful to verify.
(lift (𝟭 C))
(embedding C)
(ext equivalence_self_of_has_finite_biproducts_aux)
(embedding_lift_iso (𝟭 C))
@[simp] lemma equivalence_self_of_has_finite_biproducts_functor
{C : Type (u₁+1)} [large_category C] [preadditive C] [has_finite_biproducts C] :
(equivalence_self_of_has_finite_biproducts C).functor = lift (𝟭 C) :=
rfl
@[simp] lemma equivalence_self_of_has_finite_biproducts_inverse
{C : Type (u₁+1)} [large_category C] [preadditive C] [has_finite_biproducts C] :
(equivalence_self_of_has_finite_biproducts C).inverse = embedding C :=
rfl
end Mat_
universe u
/-- A type synonym for `Fintype`, which we will equip with a category structure
where the morphisms are matrices with components in `R`. -/
@[nolint unused_arguments, derive inhabited]
def Mat (R : Type u) := Fintype.{u}
instance (R : Type u) : has_coe_to_sort (Mat R) (Type u) := bundled.has_coe_to_sort
open_locale classical matrix
instance (R : Type u) [semiring R] : category (Mat R) :=
{ hom := λ X Y, matrix X Y R,
id := λ X, 1,
comp := λ X Y Z f g, f ⬝ g,
assoc' := by { intros, simp [matrix.mul_assoc], }, }
namespace Mat
section
variables (R : Type u) [semiring R]
lemma id_def (M : Mat R) :
𝟙 M = λ i j, if h : i = j then 1 else 0 :=
rfl
lemma id_apply (M : Mat R) (i j : M) :
(𝟙 M : matrix M M R) i j = if h : i = j then 1 else 0 :=
rfl
@[simp] lemma id_apply_self (M : Mat R) (i : M) :
(𝟙 M : matrix M M R) i i = 1 :=
by simp [id_apply]
@[simp] lemma id_apply_of_ne (M : Mat R) (i j : M) (h : i ≠ j) :
(𝟙 M : matrix M M R) i j = 0 :=
by simp [id_apply, h]
lemma comp_def {M N K : Mat R} (f : M ⟶ N) (g : N ⟶ K) :
(f ≫ g) = λ i k, ∑ j : N, f i j * g j k := rfl
@[simp] lemma comp_apply {M N K : Mat R} (f : M ⟶ N) (g : N ⟶ K) (i k) :
(f ≫ g) i k = ∑ j : N, f i j * g j k := rfl
instance (M N : Mat R) : inhabited (M ⟶ N) := ⟨λ (i : M) (j : N), (0 : R)⟩
end
variables (R : Type) [ring R]
open opposite
/-- Auxiliary definition for `category_theory.Mat.equivalence_single_obj`. -/
@[simps]
def equivalence_single_obj_inverse : Mat_ (single_obj Rᵐᵒᵖ) ⥤ Mat R :=
{ obj := λ X, Fintype.of X.ι,
map := λ X Y f i j, mul_opposite.unop (f i j),
map_id' := λ X, by { ext i j, simp [id_def, Mat_.id_def], split_ifs; refl, }, }
instance : faithful (equivalence_single_obj_inverse R) :=
{ map_injective' := λ X Y f g w, begin
ext i j,
apply_fun mul_opposite.unop using mul_opposite.unop_injective,
exact (congr_fun (congr_fun w i) j),
end }
instance : full (equivalence_single_obj_inverse R) :=
{ preimage := λ X Y f i j, mul_opposite.op (f i j), }
instance : ess_surj (equivalence_single_obj_inverse R) :=
{ mem_ess_image := λ X,
⟨{ ι := X, X := λ _, punit.star }, ⟨eq_to_iso (by { dsimp, cases X, congr, })⟩⟩, }
/-- The categorical equivalence between the category of matrices over a ring,
and the category of matrices over that ring considered as a single-object category. -/
def equivalence_single_obj : Mat R ≌ Mat_ (single_obj Rᵐᵒᵖ) :=
begin
haveI := equivalence.of_fully_faithfully_ess_surj (equivalence_single_obj_inverse R),
exact (equivalence_single_obj_inverse R).as_equivalence.symm,
end
instance : preadditive (Mat R) :=
{ add_comp' := by { intros, ext, simp [add_mul, finset.sum_add_distrib], },
comp_add' := by { intros, ext, simp [mul_add, finset.sum_add_distrib], }, }
-- TODO show `Mat R` has biproducts, and that `biprod.map` "is" forming a block diagonal matrix.
end Mat
end category_theory
|
51a55449c89aecdd37fefe647bb2406d771b476f | aa3f8992ef7806974bc1ffd468baa0c79f4d6643 | /tests/lean/notation2.lean | 306011cd201ace35e6b9b201f9507248cb856699 | [
"Apache-2.0"
] | permissive | codyroux/lean | 7f8dff750722c5382bdd0a9a9275dc4bb2c58dd3 | 0cca265db19f7296531e339192e9b9bae4a31f8b | refs/heads/master | 1,610,909,964,159 | 1,407,084,399,000 | 1,416,857,075,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 111 | lean | import data.list data.num
open list
infixr `::` := cons
check 1 :: 2 :: nil
check 1 :: 2 :: 3 :: 4 :: 5 :: nil
|
affb5de29fb8bf9596566d847935d4578bc37113 | 5d166a16ae129621cb54ca9dde86c275d7d2b483 | /tests/lean/run/using_smt1.lean | b1414206c52307dacbad0c2cb1cba6507ed678b1 | [
"Apache-2.0"
] | permissive | jcarlson23/lean | b00098763291397e0ac76b37a2dd96bc013bd247 | 8de88701247f54d325edd46c0eed57aeacb64baf | refs/heads/master | 1,611,571,813,719 | 1,497,020,963,000 | 1,497,021,515,000 | 93,882,536 | 1 | 0 | null | 1,497,029,896,000 | 1,497,029,896,000 | null | UTF-8 | Lean | false | false | 1,273 | lean | open smt_tactic tactic
lemma ex1 (a b c : nat) : a = c → a = b → b = c :=
by using_smt intros
set_option pp.all true
lemma ex2 (a b c : nat) : a > nat.zero → a = c → a = b → b = c :=
by using_smt intros
lemma ex3 (p q r : Prop) : p → q → ¬p → r :=
by using_smt intros
lemma ex4 (a b c : nat) : a > nat.zero → 0 < a :=
by using_smt intros
lemma ex5 (a b c d : nat) : a ≠ d → a = b ∧ b = c → a = c :=
by using_smt intros
set_option pp.all false
lemma ex6 (f : nat → nat) (a b c : nat) :
f a = 0 →
f b = 1 →
f a = f b ∨ f a = c →
c = 0 :=
by using_smt intros
lemma ex7 (f : nat → nat) (a b c d e: nat) :
f a = 0 →
f a = d →
f b = e →
f b = 1 →
d = e ∨ f a = c →
c = 0 :=
by using_smt intros
lemma ex8 (f : bool → bool) (a b c : bool) :
f a = ff →
f b = tt →
f a = f b ∨ f a = c →
c = ff :=
by using_smt intros
lemma ex9 (f : list nat → list nat) (a b c : list nat) :
f a = [] →
f b = [0, 1] →
f a = f b ∨ f a = c →
c = [] :=
by using_smt intros
lemma ex10 (a b c d e : int) : a = b → b ≠ c → (a = c ∨ d = e) → d = e :=
by using_smt intros
|
07a5e2108e51b520717f12e19a3037cbf1fed124 | d406927ab5617694ec9ea7001f101b7c9e3d9702 | /src/topology/metric_space/antilipschitz.lean | 05db82f6f4b9a331e342c86bd45938e20dcab0b0 | [
"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 | 9,507 | 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 topology.metric_space.lipschitz
import topology.uniform_space.complete_separated
/-!
# Antilipschitz functions
We say that a map `f : α → β` between two (extended) metric spaces is
`antilipschitz_with K`, `K ≥ 0`, if for all `x, y` we have `edist x y ≤ K * edist (f x) (f y)`.
For a metric space, the latter inequality is equivalent to `dist x y ≤ K * dist (f x) (f y)`.
## Implementation notes
The parameter `K` has type `ℝ≥0`. This way we avoid conjuction in the definition and have
coercions both to `ℝ` and `ℝ≥0∞`. We do not require `0 < K` in the definition, mostly because
we do not have a `posreal` type.
-/
variables {α : Type*} {β : Type*} {γ : Type*}
open_locale nnreal ennreal uniformity
open set filter bornology
/-- We say that `f : α → β` is `antilipschitz_with K` if for any two points `x`, `y` we have
`K * edist x y ≤ edist (f x) (f y)`. -/
def antilipschitz_with [pseudo_emetric_space α] [pseudo_emetric_space β] (K : ℝ≥0) (f : α → β) :=
∀ x y, edist x y ≤ K * edist (f x) (f y)
lemma antilipschitz_with.edist_lt_top [pseudo_emetric_space α] [pseudo_metric_space β] {K : ℝ≥0}
{f : α → β} (h : antilipschitz_with K f) (x y : α) : edist x y < ⊤ :=
(h x y).trans_lt $ ennreal.mul_lt_top ennreal.coe_ne_top (edist_ne_top _ _)
lemma antilipschitz_with.edist_ne_top [pseudo_emetric_space α] [pseudo_metric_space β] {K : ℝ≥0}
{f : α → β} (h : antilipschitz_with K f) (x y : α) : edist x y ≠ ⊤ :=
(h.edist_lt_top x y).ne
section metric
variables [pseudo_metric_space α] [pseudo_metric_space β] {K : ℝ≥0} {f : α → β}
lemma antilipschitz_with_iff_le_mul_nndist :
antilipschitz_with K f ↔ ∀ x y, nndist x y ≤ K * nndist (f x) (f y) :=
by { simp only [antilipschitz_with, edist_nndist], norm_cast }
alias antilipschitz_with_iff_le_mul_nndist ↔ antilipschitz_with.le_mul_nndist
antilipschitz_with.of_le_mul_nndist
lemma antilipschitz_with_iff_le_mul_dist :
antilipschitz_with K f ↔ ∀ x y, dist x y ≤ K * dist (f x) (f y) :=
by { simp only [antilipschitz_with_iff_le_mul_nndist, dist_nndist], norm_cast }
alias antilipschitz_with_iff_le_mul_dist ↔ antilipschitz_with.le_mul_dist
antilipschitz_with.of_le_mul_dist
namespace antilipschitz_with
lemma mul_le_nndist (hf : antilipschitz_with K f) (x y : α) :
K⁻¹ * nndist x y ≤ nndist (f x) (f y) :=
by simpa only [div_eq_inv_mul] using nnreal.div_le_of_le_mul' (hf.le_mul_nndist x y)
lemma mul_le_dist (hf : antilipschitz_with K f) (x y : α) :
(K⁻¹ * dist x y : ℝ) ≤ dist (f x) (f y) :=
by exact_mod_cast hf.mul_le_nndist x y
end antilipschitz_with
end metric
namespace antilipschitz_with
variables [pseudo_emetric_space α] [pseudo_emetric_space β] [pseudo_emetric_space γ]
variables {K : ℝ≥0} {f : α → β}
open emetric
/-- Extract the constant from `hf : antilipschitz_with K f`. This is useful, e.g.,
if `K` is given by a long formula, and we want to reuse this value. -/
@[nolint unused_arguments] -- uses neither `f` nor `hf`
protected def K (hf : antilipschitz_with K f) : ℝ≥0 := K
protected lemma injective {α : Type*} {β : Type*} [emetric_space α] [pseudo_emetric_space β]
{K : ℝ≥0} {f : α → β} (hf : antilipschitz_with K f) : function.injective f :=
λ x y h, by simpa only [h, edist_self, mul_zero, edist_le_zero] using hf x y
lemma mul_le_edist (hf : antilipschitz_with K f) (x y : α) :
(K⁻¹ * edist x y : ℝ≥0∞) ≤ edist (f x) (f y) :=
begin
rw [mul_comm, ← div_eq_mul_inv],
exact ennreal.div_le_of_le_mul' (hf x y)
end
lemma ediam_preimage_le (hf : antilipschitz_with K f) (s : set β) : diam (f ⁻¹' s) ≤ K * diam s :=
diam_le $ λ x hx y hy, (hf x y).trans $ mul_le_mul_left' (edist_le_diam_of_mem hx hy) K
lemma le_mul_ediam_image (hf : antilipschitz_with K f) (s : set α) : diam s ≤ K * diam (f '' s) :=
(diam_mono (subset_preimage_image _ _)).trans (hf.ediam_preimage_le (f '' s))
protected lemma id : antilipschitz_with 1 (id : α → α) :=
λ x y, by simp only [ennreal.coe_one, one_mul, id, le_refl]
lemma comp {Kg : ℝ≥0} {g : β → γ} (hg : antilipschitz_with Kg g)
{Kf : ℝ≥0} {f : α → β} (hf : antilipschitz_with Kf f) :
antilipschitz_with (Kf * Kg) (g ∘ f) :=
λ x y,
calc edist x y ≤ Kf * edist (f x) (f y) : hf x y
... ≤ Kf * (Kg * edist (g (f x)) (g (f y))) : ennreal.mul_left_mono (hg _ _)
... = _ : by rw [ennreal.coe_mul, mul_assoc]
lemma restrict (hf : antilipschitz_with K f) (s : set α) :
antilipschitz_with K (s.restrict f) :=
λ x y, hf x y
lemma cod_restrict (hf : antilipschitz_with K f) {s : set β} (hs : ∀ x, f x ∈ s) :
antilipschitz_with K (s.cod_restrict f hs) :=
λ x y, hf x y
lemma to_right_inv_on' {s : set α} (hf : antilipschitz_with K (s.restrict f))
{g : β → α} {t : set β} (g_maps : maps_to g t s) (g_inv : right_inv_on g f t) :
lipschitz_with K (t.restrict g) :=
λ x y, by simpa only [restrict_apply, g_inv x.mem, g_inv y.mem, subtype.edist_eq, subtype.coe_mk]
using hf ⟨g x, g_maps x.mem⟩ ⟨g y, g_maps y.mem⟩
lemma to_right_inv_on (hf : antilipschitz_with K f) {g : β → α} {t : set β}
(h : right_inv_on g f t) :
lipschitz_with K (t.restrict g) :=
(hf.restrict univ).to_right_inv_on' (maps_to_univ g t) h
lemma to_right_inverse (hf : antilipschitz_with K f) {g : β → α} (hg : function.right_inverse g f) :
lipschitz_with K g :=
begin
intros x y,
have := hf (g x) (g y),
rwa [hg x, hg y] at this
end
lemma comap_uniformity_le (hf : antilipschitz_with K f) :
(𝓤 β).comap (prod.map f f) ≤ 𝓤 α :=
begin
refine ((uniformity_basis_edist.comap _).le_basis_iff uniformity_basis_edist).2 (λ ε h₀, _),
refine ⟨K⁻¹ * ε, ennreal.mul_pos (ennreal.inv_ne_zero.2 ennreal.coe_ne_top) h₀.ne', _⟩,
refine λ x hx, (hf x.1 x.2).trans_lt _,
rw [mul_comm, ← div_eq_mul_inv] at hx,
rw mul_comm,
exact ennreal.mul_lt_of_lt_div hx
end
protected lemma uniform_inducing (hf : antilipschitz_with K f) (hfc : uniform_continuous f) :
uniform_inducing f :=
⟨le_antisymm hf.comap_uniformity_le hfc.le_comap⟩
protected lemma uniform_embedding {α : Type*} {β : Type*} [emetric_space α] [pseudo_emetric_space β]
{K : ℝ≥0} {f : α → β} (hf : antilipschitz_with K f) (hfc : uniform_continuous f) :
uniform_embedding f :=
⟨hf.uniform_inducing hfc, hf.injective⟩
lemma is_complete_range [complete_space α] (hf : antilipschitz_with K f)
(hfc : uniform_continuous f) : is_complete (range f) :=
(hf.uniform_inducing hfc).is_complete_range
lemma is_closed_range {α β : Type*} [pseudo_emetric_space α] [emetric_space β] [complete_space α]
{f : α → β} {K : ℝ≥0} (hf : antilipschitz_with K f) (hfc : uniform_continuous f) :
is_closed (range f) :=
(hf.is_complete_range hfc).is_closed
lemma closed_embedding {α : Type*} {β : Type*} [emetric_space α] [emetric_space β] {K : ℝ≥0}
{f : α → β} [complete_space α] (hf : antilipschitz_with K f) (hfc : uniform_continuous f) :
closed_embedding f :=
{ closed_range := hf.is_closed_range hfc,
.. (hf.uniform_embedding hfc).embedding }
lemma subtype_coe (s : set α) : antilipschitz_with 1 (coe : s → α) :=
antilipschitz_with.id.restrict s
lemma of_subsingleton [subsingleton α] {K : ℝ≥0} : antilipschitz_with K f :=
λ x y, by simp only [subsingleton.elim x y, edist_self, zero_le]
/-- If `f : α → β` is `0`-antilipschitz, then `α` is a `subsingleton`. -/
protected lemma subsingleton {α β} [emetric_space α] [pseudo_emetric_space β] {f : α → β}
(h : antilipschitz_with 0 f) : subsingleton α :=
⟨λ x y, edist_le_zero.1 $ (h x y).trans_eq $ zero_mul _⟩
end antilipschitz_with
namespace antilipschitz_with
open metric
variables [pseudo_metric_space α] [pseudo_metric_space β] {K : ℝ≥0} {f : α → β}
lemma bounded_preimage (hf : antilipschitz_with K f)
{s : set β} (hs : bounded s) :
bounded (f ⁻¹' s) :=
exists.intro (K * diam s) $ λ x hx y hy,
calc dist x y ≤ K * dist (f x) (f y) : hf.le_mul_dist x y
... ≤ K * diam s : mul_le_mul_of_nonneg_left (dist_le_diam_of_mem hs hx hy) K.2
lemma tendsto_cobounded (hf : antilipschitz_with K f) : tendsto f (cobounded α) (cobounded β) :=
compl_surjective.forall.2 $ λ s (hs : is_bounded s), metric.is_bounded_iff.2 $
hf.bounded_preimage $ metric.is_bounded_iff.1 hs
/-- The image of a proper space under an expanding onto map is proper. -/
protected lemma proper_space {α : Type*} [metric_space α] {K : ℝ≥0} {f : α → β} [proper_space α]
(hK : antilipschitz_with K f) (f_cont : continuous f) (hf : function.surjective f) :
proper_space β :=
begin
apply proper_space_of_compact_closed_ball_of_le 0 (λx₀ r hr, _),
let K := f ⁻¹' (closed_ball x₀ r),
have A : is_closed K := is_closed_ball.preimage f_cont,
have B : bounded K := hK.bounded_preimage bounded_closed_ball,
have : is_compact K := is_compact_iff_is_closed_bounded.2 ⟨A, B⟩,
convert this.image f_cont,
exact (hf.image_preimage _).symm
end
end antilipschitz_with
lemma lipschitz_with.to_right_inverse [pseudo_emetric_space α] [pseudo_emetric_space β] {K : ℝ≥0}
{f : α → β} (hf : lipschitz_with K f) {g : β → α} (hg : function.right_inverse g f) :
antilipschitz_with K g :=
λ x y, by simpa only [hg _] using hf (g x) (g y)
|
033d82cbed77b5b31901c67f69069d7a43c4aff4 | b7f22e51856f4989b970961f794f1c435f9b8f78 | /tests/lean/simplifier2.lean | df3e1bd45dea49a5ae8be906103f20e1725db26c | [
"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 | 426 | lean | /- Basic rewriting with eq and lambda without congruence or conditionals -/
universe l
constant T : Type.{l}
constants (x y z : T) (f g h : T → T)
constants (Hfxgy : f x = g y) (Hgyhz : g y = h z)
namespace tst attribute Hfxgy [simp] end tst
#simplify eq tst 0 (λ a b c : bool, f x) -- λ (a b c : bool), g y
namespace tst attribute Hgyhz [simp] end tst
#simplify eq tst 0 (λ a b c : bool, f x) -- λ (a b c : bool), h z
|
ec02fb281128c961dff048e6b3818f352c489d74 | 77c5b91fae1b966ddd1db969ba37b6f0e4901e88 | /src/order/bounded_lattice.lean | 37ad7a3d5daaedb783e7b64bcd25d65450f31592 | [
"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 | 48,170 | lean | /-
Copyright (c) 2017 Johannes Hölzl. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johannes Hölzl
-/
import data.option.basic
import logic.nontrivial
import order.lattice
import tactic.pi_instances
/-!
# ⊤ and ⊥, bounded lattices and variants
This file defines top and bottom elements (greatest and least elements) of a type, the bounded
variants of different kinds of lattices, sets up the typeclass hierarchy between them and provides
instances for `Prop` and `fun`.
## Main declarations
* `has_<top/bot> α`: Typeclasses to declare the `⊤`/`⊥` notation.
* `order_<top/bot> α`: Order with a top/bottom element.
* `with_<top/bot> α`: Equips `option α` with the order on `α` plus `none` as the top/bottom element.
* `semilattice_<sup/inf>_<top/bot>`: Semilattice with a join/meet and a top/bottom element (all four
combinations). Typical examples include `ℕ`.
* `bounded_lattice α`: Lattice with a top and bottom element.
* `distrib_lattice_bot α`: Distributive lattice with a bottom element. It captures the properties
of `disjoint` that are common to `generalized_boolean_algebra` and `bounded_distrib_lattice`.
* `bounded_distrib_lattice α`: Bounded and distributive lattice. Typical examples include `Prop` and
`set α`.
* `is_compl x y`: In a bounded lattice, predicate for "`x` is a complement of `y`". Note that in a
non distributive lattice, an element can have several complements.
* `is_complemented α`: Typeclass stating that any element of a lattice has a complement.
## Implementation notes
We didn't define `distrib_lattice_top` because the dual notion of `disjoint` isn't really used
anywhere.
-/
/-! ### Top, bottom element -/
set_option old_structure_cmd true
universes u v
variables {α : Type u} {β : Type v}
/-- Typeclass for the `⊤` (`\top`) notation -/
@[notation_class] class has_top (α : Type u) := (top : α)
/-- Typeclass for the `⊥` (`\bot`) notation -/
@[notation_class] class has_bot (α : Type u) := (bot : α)
notation `⊤` := has_top.top
notation `⊥` := has_bot.bot
@[priority 100] instance has_top_nonempty (α : Type u) [has_top α] : nonempty α := ⟨⊤⟩
@[priority 100] instance has_bot_nonempty (α : Type u) [has_bot α] : nonempty α := ⟨⊥⟩
attribute [pattern] has_bot.bot has_top.top
/-- An `order_top` is a partial order with a greatest element.
(We could state this on preorders, but then it wouldn't be unique
so distinguishing one would seem odd.) -/
class order_top (α : Type u) extends has_top α, partial_order α :=
(le_top : ∀ a : α, a ≤ ⊤)
section order_top
variables [order_top α] {a b : α}
@[simp] theorem le_top : a ≤ ⊤ :=
order_top.le_top a
theorem top_unique (h : ⊤ ≤ a) : a = ⊤ :=
le_top.antisymm h
-- TODO: delete in favor of the next?
theorem eq_top_iff : a = ⊤ ↔ ⊤ ≤ a :=
⟨λ eq, eq.symm ▸ le_refl ⊤, top_unique⟩
@[simp] theorem top_le_iff : ⊤ ≤ a ↔ a = ⊤ :=
⟨top_unique, λ h, h.symm ▸ le_refl ⊤⟩
@[simp] theorem not_top_lt : ¬ ⊤ < a :=
λ h, lt_irrefl a (lt_of_le_of_lt le_top h)
@[simp] theorem is_top_iff_eq_top : is_top a ↔ a = ⊤ :=
⟨λ h, h.unique le_top, λ h b, h.symm ▸ le_top⟩
theorem eq_top_mono (h : a ≤ b) (h₂ : a = ⊤) : b = ⊤ :=
top_le_iff.1 $ h₂ ▸ h
lemma lt_top_iff_ne_top : a < ⊤ ↔ a ≠ ⊤ := le_top.lt_iff_ne
lemma ne_top_of_lt (h : a < b) : a ≠ ⊤ :=
lt_top_iff_ne_top.1 $ lt_of_lt_of_le h le_top
alias ne_top_of_lt ← has_lt.lt.ne_top
theorem ne_top_of_le_ne_top {a b : α} (hb : b ≠ ⊤) (hab : a ≤ b) : a ≠ ⊤ :=
λ ha, hb $ top_unique $ ha ▸ hab
lemma eq_top_of_maximal (h : ∀ b, ¬ a < b) : a = ⊤ :=
or.elim (lt_or_eq_of_le le_top) (λ hlt, absurd hlt (h ⊤)) (λ he, he)
lemma ne.lt_top (h : a ≠ ⊤) : a < ⊤ := lt_top_iff_ne_top.mpr h
lemma ne.lt_top' (h : ⊤ ≠ a) : a < ⊤ := h.symm.lt_top
end order_top
lemma strict_mono.maximal_preimage_top [linear_order α] [order_top β]
{f : α → β} (H : strict_mono f) {a} (h_top : f a = ⊤) (x : α) :
x ≤ a :=
H.maximal_of_maximal_image (λ p, by { rw h_top, exact le_top }) x
theorem order_top.ext_top {α} {A B : order_top α}
(H : ∀ x y : α, (by haveI := A; exact x ≤ y) ↔ x ≤ y) :
(by haveI := A; exact ⊤ : α) = ⊤ :=
top_unique $ by rw ← H; apply le_top
theorem order_top.ext {α} {A B : order_top α}
(H : ∀ x y : α, (by haveI := A; exact x ≤ y) ↔ x ≤ y) : A = B :=
begin
have := partial_order.ext H,
have tt := order_top.ext_top H,
casesI A, casesI B,
injection this; congr'
end
/-- An `order_bot` is a partial order with a least element.
(We could state this on preorders, but then it wouldn't be unique
so distinguishing one would seem odd.) -/
class order_bot (α : Type u) extends has_bot α, partial_order α :=
(bot_le : ∀ a : α, ⊥ ≤ a)
section order_bot
variables [order_bot α] {a b : α}
@[simp] theorem bot_le : ⊥ ≤ a := order_bot.bot_le a
theorem bot_unique (h : a ≤ ⊥) : a = ⊥ :=
h.antisymm bot_le
-- TODO: delete?
theorem eq_bot_iff : a = ⊥ ↔ a ≤ ⊥ :=
⟨λ eq, eq.symm ▸ le_refl ⊥, bot_unique⟩
@[simp] theorem le_bot_iff : a ≤ ⊥ ↔ a = ⊥ :=
⟨bot_unique, λ h, h.symm ▸ le_refl ⊥⟩
@[simp] theorem not_lt_bot : ¬ a < ⊥ :=
λ h, lt_irrefl a (lt_of_lt_of_le h bot_le)
@[simp] theorem is_bot_iff_eq_bot : is_bot a ↔ a = ⊥ :=
⟨λ h, h.unique bot_le, λ h b, h.symm ▸ bot_le⟩
theorem ne_bot_of_le_ne_bot {a b : α} (hb : b ≠ ⊥) (hab : b ≤ a) : a ≠ ⊥ :=
λ ha, hb $ bot_unique $ ha ▸ hab
theorem eq_bot_mono (h : a ≤ b) (h₂ : b = ⊥) : a = ⊥ :=
le_bot_iff.1 $ h₂ ▸ h
lemma bot_lt_iff_ne_bot : ⊥ < a ↔ a ≠ ⊥ :=
begin
haveI := classical.dec_eq α,
haveI : decidable (a ≤ ⊥) := decidable_of_iff' _ le_bot_iff,
simp only [lt_iff_le_not_le, not_iff_not.mpr le_bot_iff, true_and, bot_le],
end
lemma ne_bot_of_gt (h : a < b) : b ≠ ⊥ :=
bot_lt_iff_ne_bot.1 $ lt_of_le_of_lt bot_le h
alias ne_bot_of_gt ← has_lt.lt.ne_bot
lemma eq_bot_of_minimal (h : ∀ b, ¬ b < a) : a = ⊥ :=
or.elim (lt_or_eq_of_le bot_le) (λ hlt, absurd hlt (h ⊥)) (λ he, he.symm)
lemma ne.bot_lt (h : a ≠ ⊥) : ⊥ < a := bot_lt_iff_ne_bot.mpr h
lemma ne.bot_lt' (h : ⊥ ≠ a) : ⊥ < a := h.symm.bot_lt
end order_bot
lemma strict_mono.minimal_preimage_bot [linear_order α] [order_bot β]
{f : α → β} (H : strict_mono f) {a} (h_bot : f a = ⊥) (x : α) :
a ≤ x :=
H.minimal_of_minimal_image (λ p, by { rw h_bot, exact bot_le }) x
theorem order_bot.ext_bot {α} {A B : order_bot α}
(H : ∀ x y : α, (by haveI := A; exact x ≤ y) ↔ x ≤ y) :
(by haveI := A; exact ⊥ : α) = ⊥ :=
bot_unique $ by rw ← H; apply bot_le
theorem order_bot.ext {α} {A B : order_bot α}
(H : ∀ x y : α, (by haveI := A; exact x ≤ y) ↔ x ≤ y) : A = B :=
begin
have := partial_order.ext H,
have tt := order_bot.ext_bot H,
casesI A, casesI B,
injection this; congr'
end
/-- A `semilattice_sup_top` is a semilattice with top and join. -/
class semilattice_sup_top (α : Type u) extends order_top α, semilattice_sup α
section semilattice_sup_top
variables [semilattice_sup_top α] {a : α}
@[simp] theorem top_sup_eq : ⊤ ⊔ a = ⊤ :=
sup_of_le_left le_top
@[simp] theorem sup_top_eq : a ⊔ ⊤ = ⊤ :=
sup_of_le_right le_top
end semilattice_sup_top
/-- A `semilattice_sup_bot` is a semilattice with bottom and join. -/
class semilattice_sup_bot (α : Type u) extends order_bot α, semilattice_sup α
section semilattice_sup_bot
variables [semilattice_sup_bot α] {a b : α}
@[simp] theorem bot_sup_eq : ⊥ ⊔ a = a :=
sup_of_le_right bot_le
@[simp] theorem sup_bot_eq : a ⊔ ⊥ = a :=
sup_of_le_left bot_le
@[simp] theorem sup_eq_bot_iff : a ⊔ b = ⊥ ↔ (a = ⊥ ∧ b = ⊥) :=
by rw [eq_bot_iff, sup_le_iff]; simp
end semilattice_sup_bot
instance nat.semilattice_sup_bot : semilattice_sup_bot ℕ :=
{ bot := 0, bot_le := nat.zero_le, .. nat.distrib_lattice }
/-- A `semilattice_inf_top` is a semilattice with top and meet. -/
class semilattice_inf_top (α : Type u) extends order_top α, semilattice_inf α
section semilattice_inf_top
variables [semilattice_inf_top α] {a b : α}
@[simp] theorem top_inf_eq : ⊤ ⊓ a = a :=
inf_of_le_right le_top
@[simp] theorem inf_top_eq : a ⊓ ⊤ = a :=
inf_of_le_left le_top
@[simp] theorem inf_eq_top_iff : a ⊓ b = ⊤ ↔ (a = ⊤ ∧ b = ⊤) :=
by rw [eq_top_iff, le_inf_iff]; simp
end semilattice_inf_top
/-- A `semilattice_inf_bot` is a semilattice with bottom and meet. -/
class semilattice_inf_bot (α : Type u) extends order_bot α, semilattice_inf α
section semilattice_inf_bot
variables [semilattice_inf_bot α] {a : α}
@[simp] theorem bot_inf_eq : ⊥ ⊓ a = ⊥ :=
inf_of_le_left bot_le
@[simp] theorem inf_bot_eq : a ⊓ ⊥ = ⊥ :=
inf_of_le_right bot_le
end semilattice_inf_bot
/-! ### Bounded lattice -/
/-- A bounded lattice is a lattice with a top and bottom element,
denoted `⊤` and `⊥` respectively. This allows for the interpretation
of all finite suprema and infima, taking `inf ∅ = ⊤` and `sup ∅ = ⊥`. -/
class bounded_lattice (α : Type u) extends lattice α, order_top α, order_bot α
@[priority 100] -- see Note [lower instance priority]
instance semilattice_inf_top_of_bounded_lattice (α : Type u) [bl : bounded_lattice α] :
semilattice_inf_top α :=
{ le_top := λ x, @le_top α _ x, ..bl }
@[priority 100] -- see Note [lower instance priority]
instance semilattice_inf_bot_of_bounded_lattice (α : Type u) [bl : bounded_lattice α] :
semilattice_inf_bot α :=
{ bot_le := λ x, @bot_le α _ x, ..bl }
@[priority 100] -- see Note [lower instance priority]
instance semilattice_sup_top_of_bounded_lattice (α : Type u) [bl : bounded_lattice α] :
semilattice_sup_top α :=
{ le_top := λ x, @le_top α _ x, ..bl }
@[priority 100] -- see Note [lower instance priority]
instance semilattice_sup_bot_of_bounded_lattice (α : Type u) [bl : bounded_lattice α] :
semilattice_sup_bot α :=
{ bot_le := λ x, @bot_le α _ x, ..bl }
theorem bounded_lattice.ext {α} {A B : bounded_lattice α}
(H : ∀ x y : α, (by haveI := A; exact x ≤ y) ↔ x ≤ y) : A = B :=
begin
have H1 : @bounded_lattice.to_lattice α A =
@bounded_lattice.to_lattice α B := lattice.ext H,
have H2 := order_bot.ext H,
have H3 : @bounded_lattice.to_order_top α A =
@bounded_lattice.to_order_top α B := order_top.ext H,
have tt := order_bot.ext_bot H,
casesI A, casesI B,
injection H1; injection H2; injection H3; congr'
end
/-- A `distrib_lattice_bot` is a distributive lattice with a least element. -/
class distrib_lattice_bot α extends distrib_lattice α, semilattice_inf_bot α, semilattice_sup_bot α
/-- A bounded distributive lattice is exactly what it sounds like. -/
class bounded_distrib_lattice α extends distrib_lattice_bot α, bounded_lattice α
lemma inf_eq_bot_iff_le_compl {α : Type u} [bounded_distrib_lattice α] {a b c : α}
(h₁ : b ⊔ c = ⊤) (h₂ : b ⊓ c = ⊥) : a ⊓ b = ⊥ ↔ a ≤ c :=
⟨λ h,
calc a ≤ a ⊓ (b ⊔ c) : by simp [h₁]
... = (a ⊓ b) ⊔ (a ⊓ c) : by simp [inf_sup_left]
... ≤ c : by simp [h, inf_le_right],
λ h,
bot_unique $
calc a ⊓ b ≤ b ⊓ c : by { rw inf_comm, exact inf_le_inf_left _ h }
... = ⊥ : h₂⟩
/-- Propositions form a bounded distributive lattice. -/
instance Prop.bounded_distrib_lattice : bounded_distrib_lattice Prop :=
{ le := λ a b, a → b,
le_refl := λ _, id,
le_trans := λ a b c f g, g ∘ f,
le_antisymm := λ a b Hab Hba, propext ⟨Hab, Hba⟩,
sup := or,
le_sup_left := @or.inl,
le_sup_right := @or.inr,
sup_le := λ a b c, or.rec,
inf := and,
inf_le_left := @and.left,
inf_le_right := @and.right,
le_inf := λ a b c Hab Hac Ha, and.intro (Hab Ha) (Hac Ha),
le_sup_inf := λ a b c H, or_iff_not_imp_left.2 $
λ Ha, ⟨H.1.resolve_left Ha, H.2.resolve_left Ha⟩,
top := true,
le_top := λ a Ha, true.intro,
bot := false,
bot_le := @false.elim }
noncomputable instance Prop.linear_order : linear_order Prop :=
@lattice.to_linear_order Prop _ (classical.dec_eq _) (classical.dec_rel _) (classical.dec_rel _) $
λ p q, by { change (p → q) ∨ (q → p), tauto! }
@[simp] lemma le_Prop_eq : ((≤) : Prop → Prop → Prop) = (→) := rfl
@[simp] lemma sup_Prop_eq : (⊔) = (∨) := rfl
@[simp] lemma inf_Prop_eq : (⊓) = (∧) := rfl
section logic
variable [preorder α]
theorem monotone_and {p q : α → Prop} (m_p : monotone p) (m_q : monotone q) :
monotone (λ x, p x ∧ q x) :=
λ a b h, and.imp (m_p h) (m_q h)
-- Note: by finish [monotone] doesn't work
theorem monotone_or {p q : α → Prop} (m_p : monotone p) (m_q : monotone q) :
monotone (λ x, p x ∨ q x) :=
λ a b h, or.imp (m_p h) (m_q h)
end logic
instance pi.order_bot {α : Type*} {β : α → Type*} [∀ a, order_bot $ β a] : order_bot (Π a, β a) :=
{ bot := λ _, ⊥,
bot_le := λ x a, bot_le,
.. pi.partial_order }
/-! ### Function lattices -/
namespace pi
variables {ι : Type*} {α' : ι → Type*}
instance [Π i, has_bot (α' i)] : has_bot (Π i, α' i) := ⟨λ i, ⊥⟩
@[simp] lemma bot_apply [Π i, has_bot (α' i)] (i : ι) : (⊥ : Π i, α' i) i = ⊥ := rfl
lemma bot_def [Π i, has_bot (α' i)] : (⊥ : Π i, α' i) = λ i, ⊥ := rfl
instance [Π i, has_top (α' i)] : has_top (Π i, α' i) := ⟨λ i, ⊤⟩
@[simp] lemma top_apply [Π i, has_top (α' i)] (i : ι) : (⊤ : Π i, α' i) i = ⊤ := rfl
lemma top_def [Π i, has_top (α' i)] : (⊤ : Π i, α' i) = λ i, ⊤ := rfl
instance [Π i, semilattice_inf_bot (α' i)] : semilattice_inf_bot (Π i, α' i) :=
by refine_struct { inf := (⊓), bot := ⊥, .. pi.partial_order }; tactic.pi_instance_derive_field
instance [Π i, semilattice_inf_top (α' i)] : semilattice_inf_top (Π i, α' i) :=
by refine_struct { inf := (⊓), top := ⊤, .. pi.partial_order }; tactic.pi_instance_derive_field
instance [Π i, semilattice_sup_bot (α' i)] : semilattice_sup_bot (Π i, α' i) :=
by refine_struct { sup := (⊔), bot := ⊥, .. pi.partial_order }; tactic.pi_instance_derive_field
instance [Π i, semilattice_sup_top (α' i)] : semilattice_sup_top (Π i, α' i) :=
by refine_struct { sup := (⊔), top := ⊤, .. pi.partial_order }; tactic.pi_instance_derive_field
instance [Π i, bounded_lattice (α' i)] : bounded_lattice (Π i, α' i) :=
{ .. pi.semilattice_sup_top, .. pi.semilattice_inf_bot }
instance [Π i, distrib_lattice_bot (α' i)] : distrib_lattice_bot (Π i, α' i) :=
{ .. pi.distrib_lattice, .. pi.order_bot }
instance [Π i, bounded_distrib_lattice (α' i)] : bounded_distrib_lattice (Π i, α' i) :=
{ .. pi.bounded_lattice, .. pi.distrib_lattice }
end pi
lemma eq_bot_of_bot_eq_top {α : Type*} [bounded_lattice α] (hα : (⊥ : α) = ⊤) (x : α) :
x = (⊥ : α) :=
eq_bot_mono le_top (eq.symm hα)
lemma eq_top_of_bot_eq_top {α : Type*} [bounded_lattice α] (hα : (⊥ : α) = ⊤) (x : α) :
x = (⊤ : α) :=
eq_top_mono bot_le hα
lemma subsingleton_of_top_le_bot {α : Type*} [bounded_lattice α] (h : (⊤ : α) ≤ (⊥ : α)) :
subsingleton α :=
⟨λ a b, le_antisymm (le_trans le_top $ le_trans h bot_le) (le_trans le_top $ le_trans h bot_le)⟩
lemma subsingleton_of_bot_eq_top {α : Type*} [bounded_lattice α] (hα : (⊥ : α) = (⊤ : α)) :
subsingleton α :=
subsingleton_of_top_le_bot (ge_of_eq hα)
lemma subsingleton_iff_bot_eq_top {α : Type*} [bounded_lattice α] :
(⊥ : α) = (⊤ : α) ↔ subsingleton α :=
⟨subsingleton_of_bot_eq_top, λ h, by exactI subsingleton.elim ⊥ ⊤⟩
/-! ### `with_bot`, `with_top` -/
/-- Attach `⊥` to a type. -/
def with_bot (α : Type*) := option α
namespace with_bot
meta instance {α} [has_to_format α] : has_to_format (with_bot α) :=
{ to_format := λ x,
match x with
| none := "⊥"
| (some x) := to_fmt x
end }
instance : has_coe_t α (with_bot α) := ⟨some⟩
instance has_bot : has_bot (with_bot α) := ⟨none⟩
instance : inhabited (with_bot α) := ⟨⊥⟩
lemma none_eq_bot : (none : with_bot α) = (⊥ : with_bot α) := rfl
lemma some_eq_coe (a : α) : (some a : with_bot α) = (↑a : with_bot α) := rfl
@[simp] theorem bot_ne_coe (a : α) : ⊥ ≠ (a : with_bot α) .
@[simp] theorem coe_ne_bot (a : α) : (a : with_bot α) ≠ ⊥ .
/-- Recursor for `with_bot` using the preferred forms `⊥` and `↑a`. -/
@[elab_as_eliminator]
def rec_bot_coe {C : with_bot α → Sort*} (h₁ : C ⊥) (h₂ : Π (a : α), C a) :
Π (n : with_bot α), C n :=
option.rec h₁ h₂
@[norm_cast]
theorem coe_eq_coe {a b : α} : (a : with_bot α) = b ↔ a = b :=
by rw [← option.some.inj_eq a b]; refl
lemma ne_bot_iff_exists {x : with_bot α} : x ≠ ⊥ ↔ ∃ (a : α), ↑a = x :=
option.ne_none_iff_exists
/-- Deconstruct a `x : with_bot α` to the underlying value in `α`, given a proof that `x ≠ ⊥`. -/
def unbot : Π (x : with_bot α), x ≠ ⊥ → α
| ⊥ h := absurd rfl h
| (some x) h := x
@[simp] lemma coe_unbot {α : Type*} (x : with_bot α) (h : x ≠ ⊥) :
(x.unbot h : with_bot α) = x :=
by { cases x, simpa using h, refl, }
@[simp] lemma unbot_coe (x : α) (h : (x : with_bot α) ≠ ⊥ := coe_ne_bot _) :
(x : with_bot α).unbot h = x := rfl
@[priority 10]
instance has_lt [has_lt α] : has_lt (with_bot α) :=
{ lt := λ o₁ o₂ : option α, ∃ b ∈ o₂, ∀ a ∈ o₁, a < b }
@[simp] theorem some_lt_some [has_lt α] {a b : α} :
@has_lt.lt (with_bot α) _ (some a) (some b) ↔ a < b :=
by simp [(<)]
lemma none_lt_some [has_lt α] (a : α) :
@has_lt.lt (with_bot α) _ none (some a) :=
⟨a, rfl, λ b hb, (option.not_mem_none _ hb).elim⟩
lemma bot_lt_coe [has_lt α] (a : α) : (⊥ : with_bot α) < a := none_lt_some a
instance : can_lift (with_bot α) α :=
{ coe := coe,
cond := λ r, r ≠ ⊥,
prf := λ x hx, ⟨option.get $ option.ne_none_iff_is_some.1 hx, option.some_get _⟩ }
instance [preorder α] : preorder (with_bot α) :=
{ le := λ o₁ o₂ : option α, ∀ a ∈ o₁, ∃ b ∈ o₂, a ≤ b,
lt := (<),
lt_iff_le_not_le := by intros; cases a; cases b;
simp [lt_iff_le_not_le]; simp [(<)];
split; refl,
le_refl := λ o a ha, ⟨a, ha, le_refl _⟩,
le_trans := λ o₁ o₂ o₃ h₁ h₂ a ha,
let ⟨b, hb, ab⟩ := h₁ a ha, ⟨c, hc, bc⟩ := h₂ b hb in
⟨c, hc, le_trans ab bc⟩ }
instance partial_order [partial_order α] : partial_order (with_bot α) :=
{ le_antisymm := λ o₁ o₂ h₁ h₂, begin
cases o₁ with a,
{ cases o₂ with b, {refl},
rcases h₂ b rfl with ⟨_, ⟨⟩, _⟩ },
{ rcases h₁ a rfl with ⟨b, ⟨⟩, h₁'⟩,
rcases h₂ b rfl with ⟨_, ⟨⟩, h₂'⟩,
rw le_antisymm h₁' h₂' }
end,
.. with_bot.preorder }
instance order_bot [partial_order α] : order_bot (with_bot α) :=
{ bot_le := λ a a' h, option.no_confusion h,
..with_bot.partial_order, ..with_bot.has_bot }
@[simp, norm_cast] theorem coe_le_coe [preorder α] {a b : α} :
(a : with_bot α) ≤ b ↔ a ≤ b :=
⟨λ h, by rcases h a rfl with ⟨_, ⟨⟩, h⟩; exact h,
λ h a' e, option.some_inj.1 e ▸ ⟨b, rfl, h⟩⟩
@[simp] theorem some_le_some [preorder α] {a b : α} :
@has_le.le (with_bot α) _ (some a) (some b) ↔ a ≤ b := coe_le_coe
theorem coe_le [preorder α] {a b : α} :
∀ {o : option α}, b ∈ o → ((a : with_bot α) ≤ o ↔ a ≤ b)
| _ rfl := coe_le_coe
@[norm_cast]
lemma coe_lt_coe [preorder α] {a b : α} : (a : with_bot α) < b ↔ a < b := some_lt_some
lemma le_coe_get_or_else [preorder α] : ∀ (a : with_bot α) (b : α), a ≤ a.get_or_else b
| (some a) b := le_refl a
| none b := λ _ h, option.no_confusion h
@[simp] lemma get_or_else_bot (a : α) : option.get_or_else (⊥ : with_bot α) a = a := rfl
lemma get_or_else_bot_le_iff [order_bot α] {a : with_bot α} {b : α} :
a.get_or_else ⊥ ≤ b ↔ a ≤ b :=
by cases a; simp [none_eq_bot, some_eq_coe]
instance decidable_le [preorder α] [@decidable_rel α (≤)] : @decidable_rel (with_bot α) (≤)
| none x := is_true $ λ a h, option.no_confusion h
| (some x) (some y) :=
if h : x ≤ y
then is_true (some_le_some.2 h)
else is_false $ by simp *
| (some x) none := is_false $ λ h, by rcases h x rfl with ⟨y, ⟨_⟩, _⟩
instance decidable_lt [has_lt α] [@decidable_rel α (<)] : @decidable_rel (with_bot α) (<)
| none (some x) := is_true $ by existsi [x,rfl]; rintros _ ⟨⟩
| (some x) (some y) :=
if h : x < y
then is_true $ by simp *
else is_false $ by simp *
| x none := is_false $ by rintro ⟨a,⟨⟨⟩⟩⟩
instance [partial_order α] [is_total α (≤)] : is_total (with_bot α) (≤) :=
{ total := λ a b, match a, b with
| none , _ := or.inl bot_le
| _ , none := or.inr bot_le
| some x, some y := by simp only [some_le_some, total_of]
end }
instance semilattice_sup [semilattice_sup α] : semilattice_sup_bot (with_bot α) :=
{ sup := option.lift_or_get (⊔),
le_sup_left := λ o₁ o₂ a ha,
by cases ha; cases o₂; simp [option.lift_or_get],
le_sup_right := λ o₁ o₂ a ha,
by cases ha; cases o₁; simp [option.lift_or_get],
sup_le := λ o₁ o₂ o₃ h₁ h₂ a ha, begin
cases o₁ with b; cases o₂ with c; cases ha,
{ exact h₂ a rfl },
{ exact h₁ a rfl },
{ rcases h₁ b rfl with ⟨d, ⟨⟩, h₁'⟩,
simp at h₂,
exact ⟨d, rfl, sup_le h₁' h₂⟩ }
end,
..with_bot.order_bot }
lemma coe_sup [semilattice_sup α] (a b : α) : ((a ⊔ b : α) : with_bot α) = a ⊔ b := rfl
instance semilattice_inf [semilattice_inf α] : semilattice_inf_bot (with_bot α) :=
{ inf := λ o₁ o₂, o₁.bind (λ a, o₂.map (λ b, a ⊓ b)),
inf_le_left := λ o₁ o₂ a ha, begin
simp at ha, rcases ha with ⟨b, rfl, c, rfl, rfl⟩,
exact ⟨_, rfl, inf_le_left⟩
end,
inf_le_right := λ o₁ o₂ a ha, begin
simp at ha, rcases ha with ⟨b, rfl, c, rfl, rfl⟩,
exact ⟨_, rfl, inf_le_right⟩
end,
le_inf := λ o₁ o₂ o₃ h₁ h₂ a ha, begin
cases ha,
rcases h₁ a rfl with ⟨b, ⟨⟩, ab⟩,
rcases h₂ a rfl with ⟨c, ⟨⟩, ac⟩,
exact ⟨_, rfl, le_inf ab ac⟩
end,
..with_bot.order_bot }
lemma coe_inf [semilattice_inf α] (a b : α) : ((a ⊓ b : α) : with_bot α) = a ⊓ b := rfl
instance lattice [lattice α] : lattice (with_bot α) :=
{ ..with_bot.semilattice_sup, ..with_bot.semilattice_inf }
instance linear_order [linear_order α] : linear_order (with_bot α) :=
lattice.to_linear_order _ $ λ o₁ o₂,
begin
cases o₁ with a, {exact or.inl bot_le},
cases o₂ with b, {exact or.inr bot_le},
simp [le_total]
end
@[norm_cast] -- this is not marked simp because the corresponding with_top lemmas are used
lemma coe_min [linear_order α] (x y : α) : ((min x y : α) : with_bot α) = min x y := rfl
@[norm_cast] -- this is not marked simp because the corresponding with_top lemmas are used
lemma coe_max [linear_order α] (x y : α) : ((max x y : α) : with_bot α) = max x y := rfl
instance order_top [order_top α] : order_top (with_bot α) :=
{ top := some ⊤,
le_top := λ o a ha, by cases ha; exact ⟨_, rfl, le_top⟩,
..with_bot.partial_order }
instance bounded_lattice [bounded_lattice α] : bounded_lattice (with_bot α) :=
{ ..with_bot.lattice, ..with_bot.order_top, ..with_bot.order_bot }
lemma well_founded_lt [partial_order α] (h : well_founded ((<) : α → α → Prop)) :
well_founded ((<) : with_bot α → with_bot α → Prop) :=
have acc_bot : acc ((<) : with_bot α → with_bot α → Prop) ⊥ :=
acc.intro _ (λ a ha, (not_le_of_gt ha bot_le).elim),
⟨λ a, option.rec_on a acc_bot (λ a, acc.intro _ (λ b, option.rec_on b (λ _, acc_bot)
(λ b, well_founded.induction h b
(show ∀ b : α, (∀ c, c < b → (c : with_bot α) < a →
acc ((<) : with_bot α → with_bot α → Prop) c) → (b : with_bot α) < a →
acc ((<) : with_bot α → with_bot α → Prop) b,
from λ b ih hba, acc.intro _ (λ c, option.rec_on c (λ _, acc_bot)
(λ c hc, ih _ (some_lt_some.1 hc) (lt_trans hc hba)))))))⟩
instance densely_ordered [partial_order α] [densely_ordered α] [no_bot_order α] :
densely_ordered (with_bot α) :=
⟨ λ a b,
match a, b with
| a, none := λ h : a < ⊥, (not_lt_bot h).elim
| none, some b := λ h, let ⟨a, ha⟩ := no_bot b in ⟨a, bot_lt_coe a, coe_lt_coe.2 ha⟩
| some a, some b := λ h, let ⟨a, ha₁, ha₂⟩ := exists_between (coe_lt_coe.1 h) in
⟨a, coe_lt_coe.2 ha₁, coe_lt_coe.2 ha₂⟩
end⟩
end with_bot
--TODO(Mario): Construct using order dual on with_bot
/-- Attach `⊤` to a type. -/
def with_top (α : Type*) := option α
namespace with_top
meta instance {α} [has_to_format α] : has_to_format (with_top α) :=
{ to_format := λ x,
match x with
| none := "⊤"
| (some x) := to_fmt x
end }
instance : has_coe_t α (with_top α) := ⟨some⟩
instance has_top : has_top (with_top α) := ⟨none⟩
instance : inhabited (with_top α) := ⟨⊤⟩
lemma none_eq_top : (none : with_top α) = (⊤ : with_top α) := rfl
lemma some_eq_coe (a : α) : (some a : with_top α) = (↑a : with_top α) := rfl
/-- Recursor for `with_top` using the preferred forms `⊤` and `↑a`. -/
@[elab_as_eliminator]
def rec_top_coe {C : with_top α → Sort*} (h₁ : C ⊤) (h₂ : Π (a : α), C a) :
Π (n : with_top α), C n :=
option.rec h₁ h₂
@[norm_cast]
theorem coe_eq_coe {a b : α} : (a : with_top α) = b ↔ a = b :=
by rw [← option.some.inj_eq a b]; refl
@[simp] theorem top_ne_coe {a : α} : ⊤ ≠ (a : with_top α) .
@[simp] theorem coe_ne_top {a : α} : (a : with_top α) ≠ ⊤ .
lemma ne_top_iff_exists {x : with_top α} : x ≠ ⊤ ↔ ∃ (a : α), ↑a = x :=
option.ne_none_iff_exists
/-- Deconstruct a `x : with_top α` to the underlying value in `α`, given a proof that `x ≠ ⊤`. -/
def untop : Π (x : with_top α), x ≠ ⊤ → α :=
with_bot.unbot
@[simp] lemma coe_untop {α : Type*} (x : with_top α) (h : x ≠ ⊤) :
(x.untop h : with_top α) = x :=
by { cases x, simpa using h, refl, }
@[simp] lemma untop_coe (x : α) (h : (x : with_top α) ≠ ⊤ := coe_ne_top) :
(x : with_top α).untop h = x := rfl
@[priority 10]
instance has_lt [has_lt α] : has_lt (with_top α) :=
{ lt := λ o₁ o₂ : option α, ∃ b ∈ o₁, ∀ a ∈ o₂, b < a }
@[priority 10]
instance has_le [has_le α] : has_le (with_top α) :=
{ le := λ o₁ o₂ : option α, ∀ a ∈ o₂, ∃ b ∈ o₁, b ≤ a }
@[simp] theorem some_lt_some [has_lt α] {a b : α} :
@has_lt.lt (with_top α) _ (some a) (some b) ↔ a < b :=
by simp [(<)]
@[simp] theorem some_le_some [has_le α] {a b : α} :
@has_le.le (with_top α) _ (some a) (some b) ↔ a ≤ b :=
by simp [(≤)]
@[simp] theorem le_none [has_le α] {a : with_top α} :
@has_le.le (with_top α) _ a none :=
by simp [(≤)]
@[simp] theorem some_lt_none [has_lt α] (a : α) :
@has_lt.lt (with_top α) _ (some a) none :=
by simp [(<)]; existsi a; refl
instance : can_lift (with_top α) α :=
{ coe := coe,
cond := λ r, r ≠ ⊤,
prf := λ x hx, ⟨option.get $ option.ne_none_iff_is_some.1 hx, option.some_get _⟩ }
instance [preorder α] : preorder (with_top α) :=
{ le := λ o₁ o₂ : option α, ∀ a ∈ o₂, ∃ b ∈ o₁, b ≤ a,
lt := (<),
lt_iff_le_not_le := by { intros; cases a; cases b;
simp [lt_iff_le_not_le]; simp [(<),(≤)] },
le_refl := λ o a ha, ⟨a, ha, le_refl _⟩,
le_trans := λ o₁ o₂ o₃ h₁ h₂ c hc,
let ⟨b, hb, bc⟩ := h₂ c hc, ⟨a, ha, ab⟩ := h₁ b hb in
⟨a, ha, le_trans ab bc⟩,
}
instance partial_order [partial_order α] : partial_order (with_top α) :=
{ le_antisymm := λ o₁ o₂ h₁ h₂, begin
cases o₂ with b,
{ cases o₁ with a, {refl},
rcases h₂ a rfl with ⟨_, ⟨⟩, _⟩ },
{ rcases h₁ b rfl with ⟨a, ⟨⟩, h₁'⟩,
rcases h₂ a rfl with ⟨_, ⟨⟩, h₂'⟩,
rw le_antisymm h₁' h₂' }
end,
.. with_top.preorder }
instance order_top [partial_order α] : order_top (with_top α) :=
{ le_top := λ a a' h, option.no_confusion h,
..with_top.partial_order, .. with_top.has_top }
@[simp, norm_cast] theorem coe_le_coe [preorder α] {a b : α} :
(a : with_top α) ≤ b ↔ a ≤ b :=
⟨λ h, by rcases h b rfl with ⟨_, ⟨⟩, h⟩; exact h,
λ h a' e, option.some_inj.1 e ▸ ⟨a, rfl, h⟩⟩
theorem le_coe [preorder α] {a b : α} :
∀ {o : option α}, a ∈ o →
(@has_le.le (with_top α) _ o b ↔ a ≤ b)
| _ rfl := coe_le_coe
theorem le_coe_iff [partial_order α] {b : α} : ∀{x : with_top α}, x ≤ b ↔ (∃a:α, x = a ∧ a ≤ b)
| (some a) := by simp [some_eq_coe, coe_eq_coe]
| none := by simp [none_eq_top]
theorem coe_le_iff [partial_order α] {a : α} : ∀{x : with_top α}, ↑a ≤ x ↔ (∀b:α, x = ↑b → a ≤ b)
| (some b) := by simp [some_eq_coe, coe_eq_coe]
| none := by simp [none_eq_top]
theorem lt_iff_exists_coe [partial_order α] : ∀{a b : with_top α}, a < b ↔ (∃p:α, a = p ∧ ↑p < b)
| (some a) b := by simp [some_eq_coe, coe_eq_coe]
| none b := by simp [none_eq_top]
@[norm_cast]
lemma coe_lt_coe [preorder α] {a b : α} : (a : with_top α) < b ↔ a < b := some_lt_some
lemma coe_lt_top [preorder α] (a : α) : (a : with_top α) < ⊤ := some_lt_none a
theorem coe_lt_iff [preorder α] {a : α} : ∀{x : with_top α}, ↑a < x ↔ (∀b:α, x = ↑b → a < b)
| (some b) := by simp [some_eq_coe, coe_eq_coe, coe_lt_coe]
| none := by simp [none_eq_top, coe_lt_top]
lemma not_top_le_coe [preorder α] (a : α) : ¬ (⊤:with_top α) ≤ ↑a :=
λ h, (lt_irrefl ⊤ (lt_of_le_of_lt h (coe_lt_top a))).elim
instance decidable_le [preorder α] [@decidable_rel α (≤)] : @decidable_rel (with_top α) (≤) :=
λ x y, @with_bot.decidable_le (order_dual α) _ _ y x
instance decidable_lt [has_lt α] [@decidable_rel α (<)] : @decidable_rel (with_top α) (<) :=
λ x y, @with_bot.decidable_lt (order_dual α) _ _ y x
instance [partial_order α] [is_total α (≤)] : is_total (with_top α) (≤) :=
{ total := λ a b, match a, b with
| none , _ := or.inr le_top
| _ , none := or.inl le_top
| some x, some y := by simp only [some_le_some, total_of]
end }
instance semilattice_inf [semilattice_inf α] : semilattice_inf_top (with_top α) :=
{ inf := option.lift_or_get (⊓),
inf_le_left := λ o₁ o₂ a ha,
by cases ha; cases o₂; simp [option.lift_or_get],
inf_le_right := λ o₁ o₂ a ha,
by cases ha; cases o₁; simp [option.lift_or_get],
le_inf := λ o₁ o₂ o₃ h₁ h₂ a ha, begin
cases o₂ with b; cases o₃ with c; cases ha,
{ exact h₂ a rfl },
{ exact h₁ a rfl },
{ rcases h₁ b rfl with ⟨d, ⟨⟩, h₁'⟩,
simp at h₂,
exact ⟨d, rfl, le_inf h₁' h₂⟩ }
end,
..with_top.order_top }
lemma coe_inf [semilattice_inf α] (a b : α) : ((a ⊓ b : α) : with_top α) = a ⊓ b := rfl
instance semilattice_sup [semilattice_sup α] : semilattice_sup_top (with_top α) :=
{ sup := λ o₁ o₂, o₁.bind (λ a, o₂.map (λ b, a ⊔ b)),
le_sup_left := λ o₁ o₂ a ha, begin
simp at ha, rcases ha with ⟨b, rfl, c, rfl, rfl⟩,
exact ⟨_, rfl, le_sup_left⟩
end,
le_sup_right := λ o₁ o₂ a ha, begin
simp at ha, rcases ha with ⟨b, rfl, c, rfl, rfl⟩,
exact ⟨_, rfl, le_sup_right⟩
end,
sup_le := λ o₁ o₂ o₃ h₁ h₂ a ha, begin
cases ha,
rcases h₁ a rfl with ⟨b, ⟨⟩, ab⟩,
rcases h₂ a rfl with ⟨c, ⟨⟩, ac⟩,
exact ⟨_, rfl, sup_le ab ac⟩
end,
..with_top.order_top }
lemma coe_sup [semilattice_sup α] (a b : α) : ((a ⊔ b : α) : with_top α) = a ⊔ b := rfl
instance lattice [lattice α] : lattice (with_top α) :=
{ ..with_top.semilattice_sup, ..with_top.semilattice_inf }
instance linear_order [linear_order α] : linear_order (with_top α) :=
lattice.to_linear_order _ $ λ o₁ o₂,
begin
cases o₁ with a, {exact or.inr le_top},
cases o₂ with b, {exact or.inl le_top},
simp [le_total]
end
@[simp, norm_cast]
lemma coe_min [linear_order α] (x y : α) : ((min x y : α) : with_top α) = min x y := rfl
@[simp, norm_cast]
lemma coe_max [linear_order α] (x y : α) : ((max x y : α) : with_top α) = max x y := rfl
instance order_bot [order_bot α] : order_bot (with_top α) :=
{ bot := some ⊥,
bot_le := λ o a ha, by cases ha; exact ⟨_, rfl, bot_le⟩,
..with_top.partial_order }
instance bounded_lattice [bounded_lattice α] : bounded_lattice (with_top α) :=
{ ..with_top.lattice, ..with_top.order_top, ..with_top.order_bot }
lemma well_founded_lt {α : Type*} [partial_order α] (h : well_founded ((<) : α → α → Prop)) :
well_founded ((<) : with_top α → with_top α → Prop) :=
have acc_some : ∀ a : α, acc ((<) : with_top α → with_top α → Prop) (some a) :=
λ a, acc.intro _ (well_founded.induction h a
(show ∀ b, (∀ c, c < b → ∀ d : with_top α, d < some c → acc (<) d) →
∀ y : with_top α, y < some b → acc (<) y,
from λ b ih c, option.rec_on c (λ hc, (not_lt_of_ge le_top hc).elim)
(λ c hc, acc.intro _ (ih _ (some_lt_some.1 hc))))),
⟨λ a, option.rec_on a (acc.intro _ (λ y, option.rec_on y (λ h, (lt_irrefl _ h).elim)
(λ _ _, acc_some _))) acc_some⟩
instance densely_ordered [partial_order α] [densely_ordered α] [no_top_order α] :
densely_ordered (with_top α) :=
⟨ λ a b,
match a, b with
| none, a := λ h : ⊤ < a, (not_top_lt h).elim
| some a, none := λ h, let ⟨b, hb⟩ := no_top a in ⟨b, coe_lt_coe.2 hb, coe_lt_top b⟩
| some a, some b := λ h, let ⟨a, ha₁, ha₂⟩ := exists_between (coe_lt_coe.1 h) in
⟨a, coe_lt_coe.2 ha₁, coe_lt_coe.2 ha₂⟩
end⟩
lemma lt_iff_exists_coe_btwn [partial_order α] [densely_ordered α] [no_top_order α]
{a b : with_top α} :
(a < b) ↔ (∃ x : α, a < ↑x ∧ ↑x < b) :=
⟨λ h, let ⟨y, hy⟩ := exists_between h, ⟨x, hx⟩ := lt_iff_exists_coe.1 hy.2 in ⟨x, hx.1 ▸ hy⟩,
λ ⟨x, hx⟩, lt_trans hx.1 hx.2⟩
end with_top
/-! ### Subtype, order dual, product lattices -/
namespace subtype
/-- A subtype forms a `⊔`-`⊥`-semilattice if `⊥` and `⊔` preserve the property.
See note [reducible non-instances]. -/
@[reducible]
protected def semilattice_sup_bot [semilattice_sup_bot α] {P : α → Prop}
(Pbot : P ⊥) (Psup : ∀⦃x y⦄, P x → P y → P (x ⊔ y)) : semilattice_sup_bot {x : α // P x} :=
{ bot := ⟨⊥, Pbot⟩,
bot_le := λ x, @bot_le α _ x,
..subtype.semilattice_sup Psup }
/-- A subtype forms a `⊓`-`⊥`-semilattice if `⊥` and `⊓` preserve the property.
See note [reducible non-instances]. -/
@[reducible]
protected def semilattice_inf_bot [semilattice_inf_bot α] {P : α → Prop}
(Pbot : P ⊥) (Pinf : ∀⦃x y⦄, P x → P y → P (x ⊓ y)) : semilattice_inf_bot {x : α // P x} :=
{ bot := ⟨⊥, Pbot⟩,
bot_le := λ x, @bot_le α _ x,
..subtype.semilattice_inf Pinf }
/-- A subtype forms a `⊔`-`⊤`-semilattice if `⊤` and `⊔` preserve the property.
See note [reducible non-instances]. -/
@[reducible]
protected def semilattice_sup_top [semilattice_sup_top α] {P : α → Prop}
(Ptop : P ⊤) (Psup : ∀{{x y}}, P x → P y → P (x ⊔ y)) : semilattice_sup_top {x : α // P x} :=
{ top := ⟨⊤, Ptop⟩,
le_top := λ x, @le_top α _ x,
..subtype.semilattice_sup Psup }
/-- A subtype forms a `⊓`-`⊤`-semilattice if `⊤` and `⊓` preserve the property.
See note [reducible non-instances]. -/
@[reducible]
protected def semilattice_inf_top [semilattice_inf_top α] {P : α → Prop}
(Ptop : P ⊤) (Pinf : ∀{{x y}}, P x → P y → P (x ⊓ y)) : semilattice_inf_top {x : α // P x} :=
{ top := ⟨⊤, Ptop⟩,
le_top := λ x, @le_top α _ x,
..subtype.semilattice_inf Pinf }
end subtype
namespace order_dual
variable (α)
instance [has_bot α] : has_top (order_dual α) := ⟨(⊥ : α)⟩
instance [has_top α] : has_bot (order_dual α) := ⟨(⊤ : α)⟩
instance [order_bot α] : order_top (order_dual α) :=
{ le_top := @bot_le α _,
.. order_dual.partial_order α, .. order_dual.has_top α }
instance [order_top α] : order_bot (order_dual α) :=
{ bot_le := @le_top α _,
.. order_dual.partial_order α, .. order_dual.has_bot α }
instance [semilattice_inf_bot α] : semilattice_sup_top (order_dual α) :=
{ .. order_dual.semilattice_sup α, .. order_dual.order_top α }
instance [semilattice_inf_top α] : semilattice_sup_bot (order_dual α) :=
{ .. order_dual.semilattice_sup α, .. order_dual.order_bot α }
instance [semilattice_sup_bot α] : semilattice_inf_top (order_dual α) :=
{ .. order_dual.semilattice_inf α, .. order_dual.order_top α }
instance [semilattice_sup_top α] : semilattice_inf_bot (order_dual α) :=
{ .. order_dual.semilattice_inf α, .. order_dual.order_bot α }
instance [bounded_lattice α] : bounded_lattice (order_dual α) :=
{ .. order_dual.lattice α, .. order_dual.order_top α, .. order_dual.order_bot α }
/- If you define `distrib_lattice_top`, add the `order_dual` instances between `distrib_lattice_bot`
and `distrib_lattice_top` here -/
instance [bounded_distrib_lattice α] : bounded_distrib_lattice (order_dual α) :=
{ .. order_dual.bounded_lattice α, .. order_dual.distrib_lattice α }
end order_dual
namespace prod
variables (α β)
instance [has_top α] [has_top β] : has_top (α × β) := ⟨⟨⊤, ⊤⟩⟩
instance [has_bot α] [has_bot β] : has_bot (α × β) := ⟨⟨⊥, ⊥⟩⟩
instance [order_top α] [order_top β] : order_top (α × β) :=
{ le_top := λ a, ⟨le_top, le_top⟩,
.. prod.partial_order α β, .. prod.has_top α β }
instance [order_bot α] [order_bot β] : order_bot (α × β) :=
{ bot_le := λ a, ⟨bot_le, bot_le⟩,
.. prod.partial_order α β, .. prod.has_bot α β }
instance [semilattice_sup_top α] [semilattice_sup_top β] : semilattice_sup_top (α × β) :=
{ .. prod.semilattice_sup α β, .. prod.order_top α β }
instance [semilattice_inf_top α] [semilattice_inf_top β] : semilattice_inf_top (α × β) :=
{ .. prod.semilattice_inf α β, .. prod.order_top α β }
instance [semilattice_sup_bot α] [semilattice_sup_bot β] : semilattice_sup_bot (α × β) :=
{ .. prod.semilattice_sup α β, .. prod.order_bot α β }
instance [semilattice_inf_bot α] [semilattice_inf_bot β] : semilattice_inf_bot (α × β) :=
{ .. prod.semilattice_inf α β, .. prod.order_bot α β }
instance [bounded_lattice α] [bounded_lattice β] : bounded_lattice (α × β) :=
{ .. prod.lattice α β, .. prod.order_top α β, .. prod.order_bot α β }
instance [distrib_lattice_bot α] [distrib_lattice_bot β] :
distrib_lattice_bot (α × β) :=
{ .. prod.distrib_lattice α β, .. prod.order_bot α β }
instance [bounded_distrib_lattice α] [bounded_distrib_lattice β] :
bounded_distrib_lattice (α × β) :=
{ .. prod.bounded_lattice α β, .. prod.distrib_lattice α β }
end prod
/-! ### Disjointness and complements -/
section disjoint
section semilattice_inf_bot
variable [semilattice_inf_bot α]
/-- Two elements of a lattice are disjoint if their inf is the bottom element.
(This generalizes disjoint sets, viewed as members of the subset lattice.) -/
def disjoint (a b : α) : Prop := a ⊓ b ≤ ⊥
theorem disjoint.eq_bot {a b : α} (h : disjoint a b) : a ⊓ b = ⊥ :=
eq_bot_iff.2 h
theorem disjoint_iff {a b : α} : disjoint a b ↔ a ⊓ b = ⊥ :=
eq_bot_iff.symm
theorem disjoint.comm {a b : α} : disjoint a b ↔ disjoint b a :=
by rw [disjoint, disjoint, inf_comm]
@[symm] theorem disjoint.symm ⦃a b : α⦄ : disjoint a b → disjoint b a :=
disjoint.comm.1
lemma symmetric_disjoint : symmetric (disjoint : α → α → Prop) := disjoint.symm
@[simp] theorem disjoint_bot_left {a : α} : disjoint ⊥ a := inf_le_left
@[simp] theorem disjoint_bot_right {a : α} : disjoint a ⊥ := inf_le_right
theorem disjoint.mono {a b c d : α} (h₁ : a ≤ b) (h₂ : c ≤ d) :
disjoint b d → disjoint a c := le_trans (inf_le_inf h₁ h₂)
theorem disjoint.mono_left {a b c : α} (h : a ≤ b) : disjoint b c → disjoint a c :=
disjoint.mono h (le_refl _)
theorem disjoint.mono_right {a b c : α} (h : b ≤ c) : disjoint a c → disjoint a b :=
disjoint.mono (le_refl _) h
@[simp] lemma disjoint_self {a : α} : disjoint a a ↔ a = ⊥ :=
by simp [disjoint]
lemma disjoint.ne {a b : α} (ha : a ≠ ⊥) (hab : disjoint a b) : a ≠ b :=
by { intro h, rw [←h, disjoint_self] at hab, exact ha hab }
lemma disjoint.eq_bot_of_le {a b : α} (hab : disjoint a b) (h : a ≤ b) : a = ⊥ :=
eq_bot_iff.2 (by rwa ←inf_eq_left.2 h)
lemma disjoint.of_disjoint_inf_of_le {a b c : α} (h : disjoint (a ⊓ b) c) (hle : a ≤ c) :
disjoint a b := by rw [disjoint_iff, h.eq_bot_of_le (inf_le_left.trans hle)]
lemma disjoint.of_disjoint_inf_of_le' {a b c : α} (h : disjoint (a ⊓ b) c) (hle : b ≤ c) :
disjoint a b := by rw [disjoint_iff, h.eq_bot_of_le (inf_le_right.trans hle)]
end semilattice_inf_bot
section bounded_lattice
variables [bounded_lattice α] {a : α}
@[simp] theorem disjoint_top : disjoint a ⊤ ↔ a = ⊥ := by simp [disjoint_iff]
@[simp] theorem top_disjoint : disjoint ⊤ a ↔ a = ⊥ := by simp [disjoint_iff]
lemma eq_bot_of_disjoint_absorbs
{a b : α} (w : disjoint a b) (h : a ⊔ b = a) : b = ⊥ :=
begin
rw disjoint_iff at w,
rw [←w, right_eq_inf],
rwa sup_eq_left at h,
end
end bounded_lattice
section distrib_lattice_bot
variables [distrib_lattice_bot α] {a b c : α}
@[simp] lemma disjoint_sup_left : disjoint (a ⊔ b) c ↔ disjoint a c ∧ disjoint b c :=
by simp only [disjoint_iff, inf_sup_right, sup_eq_bot_iff]
@[simp] lemma disjoint_sup_right : disjoint a (b ⊔ c) ↔ disjoint a b ∧ disjoint a c :=
by simp only [disjoint_iff, inf_sup_left, sup_eq_bot_iff]
lemma disjoint.sup_left (ha : disjoint a c) (hb : disjoint b c) : disjoint (a ⊔ b) c :=
disjoint_sup_left.2 ⟨ha, hb⟩
lemma disjoint.sup_right (hb : disjoint a b) (hc : disjoint a c) : disjoint a (b ⊔ c) :=
disjoint_sup_right.2 ⟨hb, hc⟩
lemma disjoint.left_le_of_le_sup_right {a b c : α} (h : a ≤ b ⊔ c) (hd : disjoint a c) : a ≤ b :=
(λ x, le_of_inf_le_sup_le x (sup_le h le_sup_right)) ((disjoint_iff.mp hd).symm ▸ bot_le)
lemma disjoint.left_le_of_le_sup_left {a b c : α} (h : a ≤ c ⊔ b) (hd : disjoint a c) : a ≤ b :=
@le_of_inf_le_sup_le _ _ a b c ((disjoint_iff.mp hd).symm ▸ bot_le)
((@sup_comm _ _ c b) ▸ (sup_le h le_sup_left))
end distrib_lattice_bot
section semilattice_inf_bot
variables [semilattice_inf_bot α] {a b : α} (c : α)
lemma disjoint.inf_left (h : disjoint a b) : disjoint (a ⊓ c) b :=
h.mono_left inf_le_left
lemma disjoint.inf_left' (h : disjoint a b) : disjoint (c ⊓ a) b :=
h.mono_left inf_le_right
lemma disjoint.inf_right (h : disjoint a b) : disjoint a (b ⊓ c) :=
h.mono_right inf_le_left
lemma disjoint.inf_right' (h : disjoint a b) : disjoint a (c ⊓ b) :=
h.mono_right inf_le_right
end semilattice_inf_bot
end disjoint
section is_compl
/-- Two elements `x` and `y` are complements of each other if `x ⊔ y = ⊤` and `x ⊓ y = ⊥`. -/
structure is_compl [bounded_lattice α] (x y : α) : Prop :=
(inf_le_bot : x ⊓ y ≤ ⊥)
(top_le_sup : ⊤ ≤ x ⊔ y)
namespace is_compl
section bounded_lattice
variables [bounded_lattice α] {x y z : α}
protected lemma disjoint (h : is_compl x y) : disjoint x y := h.1
@[symm] protected lemma symm (h : is_compl x y) : is_compl y x :=
⟨by { rw inf_comm, exact h.1 }, by { rw sup_comm, exact h.2 }⟩
lemma of_eq (h₁ : x ⊓ y = ⊥) (h₂ : x ⊔ y = ⊤) : is_compl x y :=
⟨le_of_eq h₁, le_of_eq h₂.symm⟩
lemma inf_eq_bot (h : is_compl x y) : x ⊓ y = ⊥ := h.disjoint.eq_bot
lemma sup_eq_top (h : is_compl x y) : x ⊔ y = ⊤ := top_unique h.top_le_sup
lemma to_order_dual (h : is_compl x y) : @is_compl (order_dual α) _ x y := ⟨h.2, h.1⟩
end bounded_lattice
variables [bounded_distrib_lattice α] {x y z : α}
lemma inf_left_eq_bot_iff (h : is_compl y z) : x ⊓ y = ⊥ ↔ x ≤ z :=
inf_eq_bot_iff_le_compl h.sup_eq_top h.inf_eq_bot
lemma inf_right_eq_bot_iff (h : is_compl y z) : x ⊓ z = ⊥ ↔ x ≤ y :=
h.symm.inf_left_eq_bot_iff
lemma disjoint_left_iff (h : is_compl y z) : disjoint x y ↔ x ≤ z :=
by { rw disjoint_iff, exact h.inf_left_eq_bot_iff }
lemma disjoint_right_iff (h : is_compl y z) : disjoint x z ↔ x ≤ y :=
h.symm.disjoint_left_iff
lemma le_left_iff (h : is_compl x y) : z ≤ x ↔ disjoint z y :=
h.disjoint_right_iff.symm
lemma le_right_iff (h : is_compl x y) : z ≤ y ↔ disjoint z x :=
h.symm.le_left_iff
lemma left_le_iff (h : is_compl x y) : x ≤ z ↔ ⊤ ≤ z ⊔ y :=
h.to_order_dual.le_left_iff
lemma right_le_iff (h : is_compl x y) : y ≤ z ↔ ⊤ ≤ z ⊔ x :=
h.symm.left_le_iff
protected lemma antitone {x' y'} (h : is_compl x y) (h' : is_compl x' y') (hx : x ≤ x') :
y' ≤ y :=
h'.right_le_iff.2 $ le_trans h.symm.top_le_sup (sup_le_sup_left hx _)
lemma right_unique (hxy : is_compl x y) (hxz : is_compl x z) :
y = z :=
le_antisymm (hxz.antitone hxy $ le_refl x) (hxy.antitone hxz $ le_refl x)
lemma left_unique (hxz : is_compl x z) (hyz : is_compl y z) :
x = y :=
hxz.symm.right_unique hyz.symm
lemma sup_inf {x' y'} (h : is_compl x y) (h' : is_compl x' y') :
is_compl (x ⊔ x') (y ⊓ y') :=
of_eq
(by rw [inf_sup_right, ← inf_assoc, h.inf_eq_bot, bot_inf_eq, bot_sup_eq, inf_left_comm,
h'.inf_eq_bot, inf_bot_eq])
(by rw [sup_inf_left, @sup_comm _ _ x, sup_assoc, h.sup_eq_top, sup_top_eq, top_inf_eq,
sup_assoc, sup_left_comm, h'.sup_eq_top, sup_top_eq])
lemma inf_sup {x' y'} (h : is_compl x y) (h' : is_compl x' y') :
is_compl (x ⊓ x') (y ⊔ y') :=
(h.symm.sup_inf h'.symm).symm
end is_compl
lemma is_compl_bot_top [bounded_lattice α] : is_compl (⊥ : α) ⊤ :=
is_compl.of_eq bot_inf_eq sup_top_eq
lemma is_compl_top_bot [bounded_lattice α] : is_compl (⊤ : α) ⊥ :=
is_compl.of_eq inf_bot_eq top_sup_eq
section
variables [bounded_lattice α] {x : α}
lemma eq_top_of_is_compl_bot (h : is_compl x ⊥) : x = ⊤ :=
sup_bot_eq.symm.trans h.sup_eq_top
lemma eq_top_of_bot_is_compl (h : is_compl ⊥ x) : x = ⊤ :=
eq_top_of_is_compl_bot h.symm
lemma eq_bot_of_is_compl_top (h : is_compl x ⊤) : x = ⊥ :=
eq_top_of_is_compl_bot h.to_order_dual
lemma eq_bot_of_top_is_compl (h : is_compl ⊤ x) : x = ⊥ :=
eq_top_of_bot_is_compl h.to_order_dual
end
/-- A complemented bounded lattice is one where every element has a (not necessarily unique)
complement. -/
class is_complemented (α) [bounded_lattice α] : Prop :=
(exists_is_compl : ∀ (a : α), ∃ (b : α), is_compl a b)
export is_complemented (exists_is_compl)
namespace is_complemented
variables [bounded_lattice α] [is_complemented α]
instance : is_complemented (order_dual α) :=
⟨λ a, let ⟨b, hb⟩ := exists_is_compl (show α, from a) in ⟨b, hb.to_order_dual⟩⟩
end is_complemented
end is_compl
section nontrivial
variables [bounded_lattice α] [nontrivial α]
lemma bot_ne_top : (⊥ : α) ≠ ⊤ :=
λ H, not_nontrivial_iff_subsingleton.mpr (subsingleton_of_bot_eq_top H) ‹_›
lemma top_ne_bot : (⊤ : α) ≠ ⊥ := ne.symm bot_ne_top
end nontrivial
namespace bool
-- Could be generalised to `bounded_distrib_lattice` and `is_complemented`
instance : bounded_lattice bool :=
{ top := tt,
le_top := λ x, le_tt,
bot := ff,
bot_le := λ x, ff_le,
.. (infer_instance : lattice bool)}
end bool
section bool
@[simp] lemma top_eq_tt : ⊤ = tt := rfl
@[simp] lemma bot_eq_ff : ⊥ = ff := rfl
end bool
|
169adbed3e24cf992dc4d26474f981cab4d74a5d | 6432ea7a083ff6ba21ea17af9ee47b9c371760f7 | /tests/lean/run/1829.lean | 8a53e8a0446762ca6b10fa76b368d21c871d19f5 | [
"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 | 551 | lean | theorem eq_iff_true_of_subsingleton [Subsingleton α] (x y : α) : x = y ↔ True :=
⟨fun _ => ⟨⟩, fun _ => (Subsingleton.elim ..)⟩
attribute [simp] eq_iff_true_of_subsingleton in
example : True := trivial
structure Func' (α : Sort _) (β : Sort _) :=
(toFun : α → β)
def r : Func' α α := ⟨id⟩
@[simp] theorem r_toFun {α : Sort u_1} (a : α) : Func'.toFun r a = id a := rfl
example (x y : α) (h : x = y) : r.toFun x = y := by simp <;> rw [h]
theorem noissue (x y : α) (h : x = y) : r.toFun x = y := by simp <;> rw [h]
|
2209653d19994951e504bda079b14f85a362b087 | 94e33a31faa76775069b071adea97e86e218a8ee | /src/number_theory/legendre_symbol/quadratic_reciprocity.lean | 9aca5e1c254d2a2f668927408046b1c2d0cc4c01 | [
"Apache-2.0"
] | permissive | urkud/mathlib | eab80095e1b9f1513bfb7f25b4fa82fa4fd02989 | 6379d39e6b5b279df9715f8011369a301b634e41 | refs/heads/master | 1,658,425,342,662 | 1,658,078,703,000 | 1,658,078,703,000 | 186,910,338 | 0 | 0 | Apache-2.0 | 1,568,512,083,000 | 1,557,958,709,000 | Lean | UTF-8 | Lean | false | false | 15,300 | lean | /-
Copyright (c) 2018 Chris Hughes. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Chris Hughes, Michael Stoll
-/
import number_theory.legendre_symbol.gauss_eisenstein_lemmas
import number_theory.legendre_symbol.quadratic_char
/-!
# Legendre symbol and quadratic reciprocity.
This file contains results about quadratic residues modulo a prime number.
We define the Legendre symbol `(a / p)` as `legendre_sym p a`.
Note the order of arguments! The advantage of this form is that then `legendre_sym p`
is a multiplicative map.
The main results are the law of quadratic reciprocity, `quadratic_reciprocity`, as well as the
interpretations in terms of existence of square roots depending on the congruence mod 4,
`exists_sq_eq_prime_iff_of_mod_four_eq_one`, and
`exists_sq_eq_prime_iff_of_mod_four_eq_three`.
Also proven are conditions for `-1` and `2` to be a square modulo a prime,
`legende_sym_neg_one` and `exists_sq_eq_neg_one_iff` for `-1`, and
`exists_sq_eq_two_iff` for `2`
## Implementation notes
The proof of quadratic reciprocity implemented uses Gauss' lemma and Eisenstein's lemma
-/
open finset nat char
namespace zmod
variables (p q : ℕ) [fact p.prime] [fact q.prime]
/-- Euler's Criterion: A unit `x` of `zmod p` is a square if and only if `x ^ (p / 2) = 1`. -/
lemma euler_criterion_units (x : (zmod p)ˣ) :
(∃ y : (zmod p)ˣ, y ^ 2 = x) ↔ x ^ (p / 2) = 1 :=
begin
by_cases hc : p = 2,
{ substI hc,
simp only [eq_iff_true_of_subsingleton, exists_const], },
{ have h₀ := finite_field.unit_is_square_iff (by rwa ring_char_zmod_n) x,
have hs : (∃ y : (zmod p)ˣ, y ^ 2 = x) ↔ is_square(x) :=
by { rw is_square_iff_exists_sq x,
simp_rw eq_comm, },
rw hs,
rwa card p at h₀, },
end
/-- Euler's Criterion: a nonzero `a : zmod p` is a square if and only if `x ^ (p / 2) = 1`. -/
lemma euler_criterion {a : zmod p} (ha : a ≠ 0) :
is_square (a : zmod p) ↔ a ^ (p / 2) = 1 :=
begin
apply (iff_congr _ (by simp [units.ext_iff])).mp (euler_criterion_units p (units.mk0 a ha)),
simp only [units.ext_iff, sq, units.coe_mk0, units.coe_mul],
split, { rintro ⟨y, hy⟩, exact ⟨y, hy.symm⟩ },
{ rintro ⟨y, rfl⟩,
have hy : y ≠ 0, { rintro rfl, simpa [zero_pow] using ha, },
refine ⟨units.mk0 y hy, _⟩, simp, }
end
lemma exists_sq_eq_neg_one_iff : is_square (-1 : zmod p) ↔ p % 4 ≠ 3 :=
begin
have h := @is_square_neg_one_iff (zmod p) _ _,
rw card p at h,
exact h,
end
lemma mod_four_ne_three_of_sq_eq_neg_one {y : zmod p} (hy : y ^ 2 = -1) : p % 4 ≠ 3 :=
begin
rw pow_two at hy,
exact (exists_sq_eq_neg_one_iff p).1 ⟨y, hy.symm⟩
end
lemma mod_four_ne_three_of_sq_eq_neg_sq' {x y : zmod p} (hy : y ≠ 0) (hxy : x ^ 2 = - y ^ 2) :
p % 4 ≠ 3 :=
@mod_four_ne_three_of_sq_eq_neg_one p _ (x / y) begin
apply_fun (λ z, z / y ^ 2) at hxy,
rwa [neg_div, ←div_pow, ←div_pow, div_self hy, one_pow] at hxy
end
lemma mod_four_ne_three_of_sq_eq_neg_sq {x y : zmod p} (hx : x ≠ 0) (hxy : x ^ 2 = - y ^ 2) :
p % 4 ≠ 3 :=
begin
apply_fun (λ x, -x) at hxy,
rw neg_neg at hxy,
exact mod_four_ne_three_of_sq_eq_neg_sq' p hx hxy.symm
end
lemma pow_div_two_eq_neg_one_or_one {a : zmod p} (ha : a ≠ 0) :
a ^ (p / 2) = 1 ∨ a ^ (p / 2) = -1 :=
begin
cases nat.prime.eq_two_or_odd (fact.out p.prime) with hp2 hp_odd,
{ substI p, revert a ha, dec_trivial },
rw [← mul_self_eq_one_iff, ← pow_add, ← two_mul, two_mul_odd_div_two hp_odd],
exact pow_card_sub_one_eq_one ha
end
/-- The Legendre symbol of `a : ℤ` and a prime `p`, `legendre_sym p a`,
is an integer defined as
* `0` if `a` is `0` modulo `p`;
* `1` if `a` is a square modulo `p`
* `-1` otherwise.
Note the order of the arguments! The advantage of the order chosen here is
that `legendre_sym p` is a multiplicative function `ℤ → ℤ`.
-/
def legendre_sym (p : ℕ) [fact p.prime] (a : ℤ) : ℤ := quadratic_char (zmod p) a
/-- We have the congruence `legendre_sym p a ≡ a ^ (p / 2) mod p`. -/
lemma legendre_sym_eq_pow (p : ℕ) (a : ℤ) [hp : fact p.prime] :
(legendre_sym p a : zmod p) = (a ^ (p / 2)) :=
begin
rw legendre_sym,
by_cases ha : (a : zmod p) = 0,
{ simp only [ha, zero_pow (nat.div_pos (hp.1.two_le) (succ_pos 1)), quadratic_char_zero,
int.cast_zero], },
by_cases hp₁ : p = 2,
{ substI p,
generalize : (a : (zmod 2)) = b, revert b, dec_trivial, },
{ have h₁ := quadratic_char_eq_pow_of_char_ne_two (by rwa ring_char_zmod_n p) ha,
rw card p at h₁,
rw h₁,
have h₂ := ring.neg_one_ne_one_of_char_ne_two (by rwa ring_char_zmod_n p),
cases pow_div_two_eq_neg_one_or_one p ha with h h,
{ rw [if_pos h, h, int.cast_one], },
{ rw [h, if_neg h₂, int.cast_neg, int.cast_one], } }
end
/-- If `p ∤ a`, then `legendre_sym p a` is `1` or `-1`. -/
lemma legendre_sym_eq_one_or_neg_one (p : ℕ) [fact p.prime] (a : ℤ) (ha : (a : zmod p) ≠ 0) :
legendre_sym p a = 1 ∨ legendre_sym p a = -1 :=
quadratic_char_dichotomy ha
lemma legendre_sym_eq_neg_one_iff_not_one {a : ℤ} (ha : (a : zmod p) ≠ 0) :
legendre_sym p a = -1 ↔ ¬ legendre_sym p a = 1 :=
quadratic_char_eq_neg_one_iff_not_one ha
/-- The Legendre symbol of `p` and `a` is zero iff `p ∣ a`. -/
lemma legendre_sym_eq_zero_iff (p : ℕ) [fact p.prime] (a : ℤ) :
legendre_sym p a = 0 ↔ (a : zmod p) = 0 :=
quadratic_char_eq_zero_iff a
@[simp] lemma legendre_sym_zero (p : ℕ) [fact p.prime] : legendre_sym p 0 = 0 :=
by rw [legendre_sym, int.cast_zero, quadratic_char_zero]
@[simp] lemma legendre_sym_one (p : ℕ) [fact p.prime] : legendre_sym p 1 = 1 :=
by rw [legendre_sym, int.cast_one, quadratic_char_one]
/-- The Legendre symbol is multiplicative in `a` for `p` fixed. -/
lemma legendre_sym_mul (p : ℕ) [fact p.prime] (a b : ℤ) :
legendre_sym p (a * b) = legendre_sym p a * legendre_sym p b :=
begin
rw [legendre_sym, legendre_sym, legendre_sym],
push_cast,
exact quadratic_char_mul (a : zmod p) b,
end
/-- The Legendre symbol is a homomorphism of monoids with zero. -/
@[simps] def legendre_sym_hom (p : ℕ) [fact p.prime] : ℤ →*₀ ℤ :=
{ to_fun := legendre_sym p,
map_zero' := legendre_sym_zero p,
map_one' := legendre_sym_one p,
map_mul' := legendre_sym_mul p }
/-- The square of the symbol is 1 if `p ∤ a`. -/
theorem legendre_sym_sq_one (p : ℕ) [fact p.prime] (a : ℤ) (ha : (a : zmod p) ≠ 0) :
(legendre_sym p a)^2 = 1 :=
quadratic_char_sq_one ha
/-- The Legendre symbol of `a^2` at `p` is 1 if `p ∤ a`. -/
theorem legendre_sym_sq_one' (p : ℕ) [fact p.prime] (a : ℤ) (ha : (a : zmod p) ≠ 0) :
legendre_sym p (a ^ 2) = 1 :=
begin
rw [legendre_sym],
push_cast,
exact quadratic_char_sq_one' ha,
end
/-- The Legendre symbol depends only on `a` mod `p`. -/
theorem legendre_sym_mod (p : ℕ) [fact p.prime] (a : ℤ) :
legendre_sym p a = legendre_sym p (a % p) :=
by simp only [legendre_sym, int_cast_mod]
/-- Gauss' lemma. The legendre symbol can be computed by considering the number of naturals less
than `p/2` such that `(a * x) % p > p / 2` -/
lemma gauss_lemma {a : ℤ} (hp : p ≠ 2) (ha0 : (a : zmod p) ≠ 0) :
legendre_sym p a = (-1) ^ ((Ico 1 (p / 2).succ).filter
(λ x : ℕ, p / 2 < (a * x : zmod p).val)).card :=
begin
haveI hp' : fact (p % 2 = 1) := ⟨nat.prime.mod_two_eq_one_iff_ne_two.mpr hp⟩,
have : (legendre_sym p a : zmod p) = (((-1)^((Ico 1 (p / 2).succ).filter
(λ x : ℕ, p / 2 < (a * x : zmod p).val)).card : ℤ) : zmod p) :=
by { rw [legendre_sym_eq_pow, legendre_symbol.gauss_lemma_aux p ha0]; simp },
cases legendre_sym_eq_one_or_neg_one p a ha0;
cases neg_one_pow_eq_or ℤ ((Ico 1 (p / 2).succ).filter
(λ x : ℕ, p / 2 < (a * x : zmod p).val)).card;
simp [*, ne_neg_self p one_ne_zero, (ne_neg_self p one_ne_zero).symm] at *
end
/-- When `p ∤ a`, then `legendre_sym p a = 1` iff `a` is a square mod `p`. -/
lemma legendre_sym_eq_one_iff {a : ℤ} (ha0 : (a : zmod p) ≠ 0) :
legendre_sym p a = 1 ↔ is_square (a : zmod p) :=
quadratic_char_one_iff_is_square ha0
/-- `legendre_sym p a = -1` iff`a` is a nonsquare mod `p`. -/
lemma legendre_sym_eq_neg_one_iff {a : ℤ} :
legendre_sym p a = -1 ↔ ¬ is_square (a : zmod p) :=
quadratic_char_neg_one_iff_not_is_square
/-- The number of square roots of `a` modulo `p` is determined by the Legendre symbol. -/
lemma legendre_sym_card_sqrts (hp : p ≠ 2) (a : ℤ) :
↑{x : zmod p | x^2 = a}.to_finset.card = legendre_sym p a + 1 :=
begin
have h : ring_char (zmod p) ≠ 2 := by { rw ring_char_zmod_n, exact hp, },
exact quadratic_char_card_sqrts h a,
end
/-- `legendre_sym p (-1)` is given by `χ₄ p`. -/
lemma legendre_sym_neg_one (hp : p ≠ 2) : legendre_sym p (-1) = χ₄ p :=
begin
have h : ring_char (zmod p) ≠ 2 := by { rw ring_char_zmod_n, exact hp, },
have h₁ := quadratic_char_neg_one h,
rw card p at h₁,
exact_mod_cast h₁,
end
open_locale big_operators
lemma eisenstein_lemma (hp : p ≠ 2) {a : ℕ} (ha1 : a % 2 = 1) (ha0 : (a : zmod p) ≠ 0) :
legendre_sym p a = (-1)^∑ x in Ico 1 (p / 2).succ, (x * a) / p :=
begin
haveI hp' : fact (p % 2 = 1) := ⟨nat.prime.mod_two_eq_one_iff_ne_two.mpr hp⟩,
have ha0' : ((a : ℤ) : zmod p) ≠ 0 := by { norm_cast, exact ha0 },
rw [neg_one_pow_eq_pow_mod_two, gauss_lemma p hp ha0', neg_one_pow_eq_pow_mod_two,
(by norm_cast : ((a : ℤ) : zmod p) = (a : zmod p)),
show _ = _, from legendre_symbol.eisenstein_lemma_aux p ha1 ha0]
end
/-- **Quadratic reciprocity theorem** -/
theorem quadratic_reciprocity (hp1 : p ≠ 2) (hq1 : q ≠ 2) (hpq : p ≠ q) :
legendre_sym q p * legendre_sym p q = (-1) ^ ((p / 2) * (q / 2)) :=
have hpq0 : (p : zmod q) ≠ 0, from prime_ne_zero q p hpq.symm,
have hqp0 : (q : zmod p) ≠ 0, from prime_ne_zero p q hpq,
by rw [eisenstein_lemma q hq1 (nat.prime.mod_two_eq_one_iff_ne_two.mpr hp1) hpq0,
eisenstein_lemma p hp1 (nat.prime.mod_two_eq_one_iff_ne_two.mpr hq1) hqp0,
← pow_add, legendre_symbol.sum_mul_div_add_sum_mul_div_eq_mul q p hpq0, mul_comm]
lemma legendre_sym_two (hp2 : p ≠ 2) : legendre_sym p 2 = (-1) ^ (p / 4 + p / 2) :=
begin
have hp1 := nat.prime.mod_two_eq_one_iff_ne_two.mpr hp2,
have hp22 : p / 2 / 2 = _ := legendre_symbol.div_eq_filter_card (show 0 < 2, from dec_trivial)
(nat.div_le_self (p / 2) 2),
have hcard : (Ico 1 (p / 2).succ).card = p / 2, by simp,
have hx2 : ∀ x ∈ Ico 1 (p / 2).succ, (2 * x : zmod p).val = 2 * x,
from λ x hx, have h2xp : 2 * x < p,
from calc 2 * x ≤ 2 * (p / 2) : mul_le_mul_of_nonneg_left
(le_of_lt_succ $ (mem_Ico.mp hx).2) dec_trivial
... < _ : by conv_rhs {rw [← div_add_mod p 2, hp1]}; exact lt_succ_self _,
by rw [← nat.cast_two, ← nat.cast_mul, val_cast_of_lt h2xp],
have hdisj : disjoint
((Ico 1 (p / 2).succ).filter (λ x, p / 2 < ((2 : ℕ) * x : zmod p).val))
((Ico 1 (p / 2).succ).filter (λ x, x * 2 ≤ p / 2)),
from disjoint_filter.2 (λ x hx, by { rw [nat.cast_two, hx2 x hx, mul_comm], simp }),
have hunion :
((Ico 1 (p / 2).succ).filter (λ x, p / 2 < ((2 : ℕ) * x : zmod p).val)) ∪
((Ico 1 (p / 2).succ).filter (λ x, x * 2 ≤ p / 2)) =
Ico 1 (p / 2).succ,
begin
rw [filter_union_right],
conv_rhs {rw [← @filter_true _ (Ico 1 (p / 2).succ)]},
exact filter_congr (λ x hx,
by rw [nat.cast_two, hx2 x hx, mul_comm, iff_true_intro (lt_or_le _ _)])
end,
have hp2' := prime_ne_zero p 2 hp2,
rw (by norm_cast : ((2 : ℕ) : zmod p) = (2 : ℤ)) at *,
erw [gauss_lemma p hp2 hp2',
neg_one_pow_eq_pow_mod_two, @neg_one_pow_eq_pow_mod_two _ _ (p / 4 + p / 2)],
refine congr_arg2 _ rfl ((eq_iff_modeq_nat 2).1 _),
rw [show 4 = 2 * 2, from rfl, ← nat.div_div_eq_div_mul, hp22, nat.cast_add,
← sub_eq_iff_eq_add', sub_eq_add_neg, neg_eq_self_mod_two,
← nat.cast_add, ← card_disjoint_union hdisj, hunion, hcard]
end
lemma exists_sq_eq_two_iff (hp1 : p ≠ 2) :
is_square (2 : zmod p) ↔ p % 8 = 1 ∨ p % 8 = 7 :=
begin
have hp2 : ((2 : ℤ) : zmod p) ≠ 0, by exact_mod_cast prime_ne_zero p 2 hp1,
have hpm4 : p % 4 = p % 8 % 4, from (nat.mod_mul_left_mod p 2 4).symm,
have hpm2 : p % 2 = p % 8 % 2, from (nat.mod_mul_left_mod p 4 2).symm,
rw [show (2 : zmod p) = (2 : ℤ), by simp, ← legendre_sym_eq_one_iff p hp2],
erw [legendre_sym_two p hp1, neg_one_pow_eq_one_iff_even (show (-1 : ℤ) ≠ 1, from dec_trivial),
even_add, even_div, even_div],
have := nat.mod_lt p (show 0 < 8, from dec_trivial),
have hp := nat.prime.mod_two_eq_one_iff_ne_two.mpr hp1,
revert this hp,
erw [hpm4, hpm2],
generalize hm : p % 8 = m, unfreezingI {clear_dependent p},
dec_trivial!,
end
lemma exists_sq_eq_prime_iff_of_mod_four_eq_one (hp1 : p % 4 = 1) (hq1 : q ≠ 2) :
is_square (q : zmod p) ↔ is_square (p : zmod q) :=
if hpq : p = q then by substI hpq else
have h1 : ((p / 2) * (q / 2)) % 2 = 0,
from dvd_iff_mod_eq_zero.1
(dvd_mul_of_dvd_left (dvd_iff_mod_eq_zero.2 $
by rw [← mod_mul_right_div_self, show 2 * 2 = 4, from rfl, hp1]; refl) _),
begin
have hp_odd : p ≠ 2 := by { by_contra, simp [h] at hp1, norm_num at hp1, },
have hpq0 : ((p : ℤ) : zmod q) ≠ 0 := by exact_mod_cast prime_ne_zero q p (ne.symm hpq),
have hqp0 : ((q : ℤ) : zmod p) ≠ 0 := by exact_mod_cast prime_ne_zero p q hpq,
have := quadratic_reciprocity p q hp_odd hq1 hpq,
rw [neg_one_pow_eq_pow_mod_two, h1, pow_zero] at this,
rw [(by norm_cast : (p : zmod q) = (p : ℤ)), (by norm_cast : (q : zmod p) = (q : ℤ)),
← legendre_sym_eq_one_iff _ hpq0, ← legendre_sym_eq_one_iff _ hqp0],
cases (legendre_sym_eq_one_or_neg_one p q hqp0) with h h,
{ simp only [h, eq_self_iff_true, true_iff, mul_one] at this ⊢,
exact this, },
{ simp only [h, mul_neg, mul_one] at this ⊢,
rw eq_neg_of_eq_neg this.symm, },
end
lemma exists_sq_eq_prime_iff_of_mod_four_eq_three (hp3 : p % 4 = 3)
(hq3 : q % 4 = 3) (hpq : p ≠ q) : is_square (q : zmod p) ↔ ¬ is_square (p : zmod q) :=
have h1 : ((p / 2) * (q / 2)) % 2 = 1,
from nat.odd_mul_odd
(by rw [← mod_mul_right_div_self, show 2 * 2 = 4, from rfl, hp3]; refl)
(by rw [← mod_mul_right_div_self, show 2 * 2 = 4, from rfl, hq3]; refl),
begin
have hp_odd : p ≠ 2 := by { by_contra, simp [h] at hp3, norm_num at hp3, },
have hq_odd : q ≠ 2 := by { by_contra, simp [h] at hq3, norm_num at hq3, },
have hpq0 : ((p : ℤ) : zmod q) ≠ 0 := by exact_mod_cast prime_ne_zero q p (ne.symm hpq),
have hqp0 : ((q : ℤ) : zmod p) ≠ 0 := by exact_mod_cast prime_ne_zero p q hpq,
have := quadratic_reciprocity p q hp_odd hq_odd hpq,
rw [neg_one_pow_eq_pow_mod_two, h1, pow_one] at this,
rw [(by norm_cast : (p : zmod q) = (p : ℤ)), (by norm_cast : (q : zmod p) = (q : ℤ)),
← legendre_sym_eq_one_iff _ hpq0, ← legendre_sym_eq_one_iff _ hqp0],
cases (legendre_sym_eq_one_or_neg_one q p hpq0) with h h,
{ simp only [h, eq_self_iff_true, not_true, iff_false, one_mul] at this ⊢,
simp only [this],
norm_num, },
{ simp only [h, neg_mul, one_mul, neg_inj] at this ⊢,
simp only [this, eq_self_iff_true, true_iff],
norm_num, },
end
end zmod
|
62fe836c8576d9974bbbff1112a1af9f25fb6b66 | 9ad8d18fbe5f120c22b5e035bc240f711d2cbd7e | /src/data/finset_transfer.lean | 699aa69de3712bfa5b928abf6343e068e6c75492 | [] | no_license | agusakov/lean_lib | c0e9cc29fc7d2518004e224376adeb5e69b5cc1a | f88d162da2f990b87c4d34f5f46bbca2bbc5948e | refs/heads/master | 1,642,141,461,087 | 1,557,395,798,000 | 1,557,395,798,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 11,285 | lean | /-
Copyright (c) 2019 Neil Strickland. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Neil Strickland
Suppose we have two types α and β with decidable equality, and
an equivalence between them (as defined in
mathlib/data/equiv/basic.lean). We then get an equivalence
between the associated types (finset α) and (finset β) of finite
subsets, and this equivalence respects membership, inclusion,
intersections and unions and various other kinds of structure.
In this file we prove a variety of facts of that type.
All this should probably be done in some more abstract and
general framework of functors from types to types, or something
like that. Also, the naming conventions should be changed for
greater compatibility with mathlib.
-/
import data.finset data.fintype
/-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~-/
namespace finset
open finset fintype equiv
universes u v
variables {α : Type u} {β : Type v}
[decidable_eq α] [decidable_eq β]
def finset_equiv_of_equiv (f : α ≃ β) :
(finset α) ≃ (finset β) := {
to_fun := (finset.image f.to_fun),
inv_fun := (finset.image f.inv_fun),
left_inv := begin
unfold function.left_inverse at ⊢,
intro x,
rw[image_image],
have li : f.inv_fun ∘ f.to_fun = id,
{ext t,simp[f.left_inv t]},
rw[li,image_id]
end,
right_inv := begin
unfold function.right_inverse at ⊢,
intro y,
rw[image_image],
have ri : f.to_fun ∘ f.inv_fun = id,
{ext u,simp[f.right_inv u]},
rw[ri,image_id]
end
}
lemma finset_equiv_symm : ∀ (f : α ≃ β),
(finset_equiv_of_equiv f).symm = finset_equiv_of_equiv (f.symm)
| ⟨ft,fi,l,r⟩ :=
begin
unfold equiv.symm,
unfold finset_equiv_of_equiv
end
lemma mem_transfer (f : α ≃ β) (a : α) (u : finset α) :
a ∈ u ↔ f.to_fun a ∈ (finset_equiv_of_equiv f).to_fun u :=
begin
split,
exact mem_image_of_mem f.to_fun,
intro f_a_in_f_u,
have : (∃ a0 ∈ u, f.to_fun a0 = f.to_fun a) := (mem_image.mp f_a_in_f_u),
cases this with a0 Z0,
cases Z0 with a0_in_u same_image,
have a0_eq_a : a0 = a :=
calc a0 = f.inv_fun (f.to_fun a0) : (f.left_inv a0).symm
... = f.inv_fun (f.to_fun a) : congr_arg f.inv_fun same_image
... = a : f.left_inv a,
exact eq.subst a0_eq_a a0_in_u
end
lemma mem_transfer_inv (f : α ≃ β) (b : β) (u : finset α) :
b ∈ (finset_equiv_of_equiv f).to_fun u ↔ f.inv_fun b ∈ u :=
begin
split,
{intro b_in_f_u,
have : (∃ a ∈ u, f.to_fun a = b) := (mem_image.mp b_in_f_u),
cases this with a a_in_u_f_a_eq_b,
cases a_in_u_f_a_eq_b with a_in_u f_a_eq_b,
have f_inv_b_eq_a : f.inv_fun b = a := eq.subst f_a_eq_b (f.left_inv a),
exact eq.subst f_inv_b_eq_a.symm a_in_u},
{intro f_inv_b_in_u,
exact eq.subst (f.right_inv b) (mem_image_of_mem f.to_fun f_inv_b_in_u)
}
end
lemma mem_transfer_alt (f : α ≃ β) (a : α) (v : finset β) :
a ∈ (finset_equiv_of_equiv f).inv_fun v ↔ f a ∈ v :=
begin
let Pf := finset_equiv_of_equiv f,
let u := Pf.inv_fun v,
let E := Pf.right_inv v,
let T := (mem_transfer f a u),
rw E at T,
exact T
end
lemma empty_transfer (f : α ≃ β) :
(finset_equiv_of_equiv f) ∅ = ∅ := (image_empty f.to_fun)
lemma subset_transfer (f : α ≃ β) {u v : finset α} :
u ⊆ v ↔ (finset_equiv_of_equiv f) u ⊆ (finset_equiv_of_equiv f) v :=
begin
split,
{intro u_sse_v,
exact image_subset_image u_sse_v},
{intro f_u_sse_f_v,
apply subset_iff.mpr,
intros a a_in_u,
have f_a_in_f_u : f a ∈ (finset_equiv_of_equiv f) u :=
mem_image_of_mem f a_in_u,
have f_a_in_f_v : f a ∈ (finset_equiv_of_equiv f) v :=
subset_iff.mp f_u_sse_f_v f_a_in_f_u,
exact (mem_transfer f a v).mpr (f_a_in_f_v)}
end
lemma ssubset_transfer (f : α ≃ β ) {u v : finset α} :
u ⊂ v ↔ (finset_equiv_of_equiv f) u ⊂ (finset_equiv_of_equiv f) v :=
begin
let Pf := finset_equiv_of_equiv f,
have uu_eq_u : image f.inv_fun (Pf u) = u := Pf.left_inv u,
have vv_eq_v : image f.inv_fun (Pf v) = v := Pf.left_inv v,
split,
intro u_ssubset_v,
have u_subset_v := u_ssubset_v.left,
have v_not_subset_u := u_ssubset_v.right,
have f_u_subset_f_v : Pf u ⊆ Pf v :=
(subset_transfer f).mp u_subset_v,
have f_v_not_subset_f_u :
not (Pf v ⊆ Pf u) :=
begin
intro f_v_subset_f_u,
let vv_subset_uu := @image_subset_image β α _ f.inv_fun _ _ f_v_subset_f_u,
rw[uu_eq_u,vv_eq_v] at vv_subset_uu,
exact v_not_subset_u vv_subset_uu
end,
exact ⟨f_u_subset_f_v,f_v_not_subset_f_u⟩,
intro f_u_ssubset_f_v,
have f_u_subset_f_v := f_u_ssubset_f_v.left,
have f_v_not_subset_f_u := f_u_ssubset_f_v.right,
have uu_subset_vv := (subset_transfer f).mpr f_u_subset_f_v,
have not_vv_subset_uu : not (v ⊆ u) :=
begin
intro v_subset_u,
have f_v_subset_f_u := (subset_transfer f).mp v_subset_u,
exact f_v_not_subset_f_u f_v_subset_f_u,
end,
exact ⟨uu_subset_vv,not_vv_subset_uu⟩
end
lemma union_transfer (f : α ≃ β) (u v : finset α) :
(finset_equiv_of_equiv f).to_fun (u ∪ v) =
(finset_equiv_of_equiv f).to_fun (u) ∪ (finset_equiv_of_equiv f).to_fun (v) :=
(image_union u v)
lemma intersect_transfer (f : α ≃ β) (u v : finset α) :
(finset_equiv_of_equiv f).to_fun (u ∩ v) =
(finset_equiv_of_equiv f).to_fun (u) ∩ (finset_equiv_of_equiv f).to_fun (v) :=
begin
simp[ext],
intro b,
let P := mem_transfer_inv f b u,
let Q := mem_transfer_inv f b v,
let R := mem_transfer_inv f b (u ∩ v),
split,
{intro H,
exact ⟨P.mpr (mem_inter.mp (R.mp H)).left,
Q.mpr (mem_inter.mp (R.mp H)).right⟩},
{intro H,
exact R.mpr (mem_inter.mpr ⟨P.mp H.left,Q.mp H.right⟩)}
end
lemma sdiff_transfer (f : α ≃ β) (u v : finset α) :
(finset_equiv_of_equiv f).to_fun (u \ v) =
(finset_equiv_of_equiv f).to_fun (u) \ (finset_equiv_of_equiv f).to_fun (v) :=
begin
simp[ext],
intro b,
let P := mem_transfer_inv f b u,
let Q := mem_transfer_inv f b v,
let R := mem_transfer_inv f b (u \ v),
split,
{intro H,
exact ⟨P.mpr (mem_sdiff.mp (R.mp H)).left,
λ U,(mem_sdiff.mp (R.mp H)).right (Q.mp U)⟩},
{intro H,
exact R.mpr (mem_sdiff.mpr ⟨P.mp H.left,λ U,H.right (Q.mpr U)⟩)}
end
lemma singleton_transfer (f : α ≃ β) (a : α) :
(finset_equiv_of_equiv f) (singleton a) = singleton (f a) := rfl
lemma insert_transfer (f : α ≃ β) (a : α) (u : finset α) :
(finset_equiv_of_equiv f) (insert a u) =
insert (f a) ((finset_equiv_of_equiv f) u) :=
image_insert f a u
lemma card_transfer (f : α ≃ β) (u : finset α) :
card ((finset_equiv_of_equiv f) u) = card u :=
card_image_of_injective u (function.injective_of_left_inverse f.left_inv)
lemma erase_transfer (f : α ≃ β) (u : finset α) (a : α) :
(finset_equiv_of_equiv f) (erase u a) = erase ((finset_equiv_of_equiv f) u) (f a) :=
begin
let Pf := (finset_equiv_of_equiv f),
simp[ext],
intro b,
split,
intro b_in_f_erase,
have f_inv_b_in_erase := (mem_transfer_inv f b (erase u a)).mp b_in_f_erase,
have f_inv_b_neq_a : ¬ (f.inv_fun b = a) := (mem_erase.mp f_inv_b_in_erase).left,
have f_inv_b_in_u : f.inv_fun b ∈ u := (mem_erase.mp f_inv_b_in_erase).right,
split,
intro b_eq_f_a,
have f_inv_b_eq_a := eq.trans (congr_arg f.inv_fun b_eq_f_a) (f.left_inv a),
exact f_inv_b_neq_a f_inv_b_eq_a,
have b_in_f_u := (mem_transfer f (f.inv_fun b) u).mp f_inv_b_in_u,
rw[f.right_inv b] at b_in_f_u,
exact b_in_f_u,
intro H,
have f_inv_b_in_erase : f.inv_fun b ∈ erase u a :=
begin
apply mem_erase.mpr,
split,
intro f_inv_b_eq_a,
exact H.left (eq.trans (f.right_inv b).symm (congr_arg f f_inv_b_eq_a)),
have f_inv_b_in_uu := mem_image_of_mem f.inv_fun H.right,
have uu_eq_u : image f.inv_fun (Pf u) = u := Pf.left_inv u,
rw[uu_eq_u] at f_inv_b_in_uu,
exact f_inv_b_in_uu
end,
have b_in_f_erase := mem_image_of_mem f f_inv_b_in_erase,
have bb_eq_b : f (f.inv_fun b) = b := f.right_inv b,
rw[bb_eq_b] at b_in_f_erase,
exact b_in_f_erase
end
lemma filter_transfer
(f : α ≃ β) (p : α → Prop) [decidable_pred p] (u : finset α) :
(finset_equiv_of_equiv f) (filter p u) =
filter (p ∘ f.inv_fun) ((finset_equiv_of_equiv f) u) :=
begin
let Pf := (finset_equiv_of_equiv f),
simp[ext],
intro b,
let a := f.inv_fun b,
split,
intro b_in_f_filter,
let a_in_filter : a ∈ filter p u :=
(mem_transfer_inv f b (filter p u)).mp b_in_f_filter,
have a_in_u : a ∈ u := (mem_filter.mp a_in_filter).left,
let p_a : p a := (mem_filter.mp a_in_filter).right,
{split,
exact (mem_transfer_inv f b u).mpr a_in_u,
exact p_a},
intro H,
have b_in_f_u := H.left,
have a_in_u : a ∈ u := (mem_transfer_inv f b u).mp b_in_f_u,
have p_a : p a := H.right,
have a_in_filter : a ∈ filter p u := mem_filter.mpr ⟨a_in_u,p_a⟩,
exact (mem_transfer_inv f b (filter p u)).mpr a_in_filter
end
lemma disjoint_transfer
(f : α ≃ β) (s0 s1 : finset α) :
(disjoint s0 s1) ↔
(disjoint ((finset_equiv_of_equiv f) s0) ((finset_equiv_of_equiv f) s1)) :=
begin
let Pf := finset_equiv_of_equiv f,
split,
{intro s_disjoint,
by calc
(Pf s0) ∩ (Pf s1) = Pf (s0 ∩ s1) : (intersect_transfer f s0 s1).symm
... ⊆ Pf ∅ : (subset_transfer f).mp s_disjoint
... = ∅ : empty_transfer f},
{intro t_disjoint,
let t0 := Pf s0,
let t1 := Pf s1,
let E := calc
Pf (s0 ∩ s1) = t0 ∩ t1 : intersect_transfer f s0 s1
... ⊆ ∅ : t_disjoint,
by calc
s0 ∩ s1 = Pf.inv_fun (Pf (s0 ∩ s1)) : (Pf.left_inv _).symm
... ⊆ Pf.inv_fun ∅ : (subset_transfer f.symm).mp E
... = ∅ : empty_transfer f.symm
}
end
end finset
namespace fintype
open finset fintype equiv
universes u v
variables {α : Type u} {β : Type v}
[decidable_eq α] [decidable_eq β]
lemma fintype_eq_of_elems_eq : ∀ {s t : fintype α}, s.1 = t.1 → s = t
| ⟨s, _⟩ ⟨t, _⟩ rfl := rfl
lemma fintype_unique (u v : fintype α) : u = v :=
begin
apply fintype_eq_of_elems_eq,
ext,split,
intro a_in_u,
exact (@fintype.complete α v a),
intro a_in_v,
exact (@fintype.complete α u a)
end
def fintype_equiv_of_equiv (f : α ≃ β) :
(fintype α ≃ fintype β ) :=
begin
let Pf := finset.finset_equiv_of_equiv f,
exact {
to_fun := λ u, {
elems := Pf.to_fun u.elems,
complete := λ b,
(mem_transfer_inv f b u.elems).mpr (@fintype.complete α u (f.inv_fun b))
},
inv_fun := λ v, {
elems := Pf.inv_fun v.elems,
complete := λ a,
(mem_transfer_alt f a v.elems).mpr (@fintype.complete β v (f.to_fun a))
},
left_inv := λ u,fintype_eq_of_elems_eq (Pf.left_inv u.elems),
right_inv := λ v,fintype_eq_of_elems_eq (Pf.right_inv v.elems)
}
end
lemma univ_transfer [u : fintype α] [v : fintype β] (f : α ≃ β) :
(finset_equiv_of_equiv f) (@univ α _) = (@univ β _) :=
begin
ext b,split,
intro,
exact (@fintype.complete β v b),
intro,
exact (mem_transfer_inv f b (@univ α _)).mpr
(@fintype.complete α u (f.inv_fun b)),
end
end fintype
|
0b266166a0e9a8a06a8fcf2aa259ae0bab3accb1 | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/number_theory/zsqrtd/quadratic_reciprocity.lean | bb4db5899c3c40fe57ac3da8343903995838c2ca | [
"Apache-2.0"
] | permissive | leanprover-community/mathlib | 56a2cadd17ac88caf4ece0a775932fa26327ba0e | 442a83d738cb208d3600056c489be16900ba701d | refs/heads/master | 1,693,584,102,358 | 1,693,471,902,000 | 1,693,471,902,000 | 97,922,418 | 1,595 | 352 | Apache-2.0 | 1,694,693,445,000 | 1,500,624,130,000 | Lean | UTF-8 | Lean | false | false | 4,432 | lean | /-
Copyright (c) 2019 Chris Hughes. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Chris Hughes
-/
import number_theory.zsqrtd.gaussian_int
import number_theory.legendre_symbol.quadratic_reciprocity
/-!
# Facts about the gaussian integers relying on quadratic reciprocity.
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
## Main statements
`prime_iff_mod_four_eq_three_of_nat_prime`
A prime natural number is prime in `ℤ[i]` if and only if it is `3` mod `4`
-/
open zsqrtd complex
open_locale complex_conjugate
local notation `ℤ[i]` := gaussian_int
namespace gaussian_int
open principal_ideal_ring
lemma mod_four_eq_three_of_nat_prime_of_prime (p : ℕ) [hp : fact p.prime] (hpi : prime (p : ℤ[i])) :
p % 4 = 3 :=
hp.1.eq_two_or_odd.elim
(λ hp2, absurd hpi (mt irreducible_iff_prime.2 $
λ ⟨hu, h⟩, begin
have := h ⟨1, 1⟩ ⟨1, -1⟩ (hp2.symm ▸ rfl),
rw [← norm_eq_one_iff, ← norm_eq_one_iff] at this,
exact absurd this dec_trivial
end))
(λ hp1, by_contradiction $ λ hp3 : p % 4 ≠ 3,
have hp41 : p % 4 = 1,
begin
rw [← nat.mod_mul_left_mod p 2 2, show 2 * 2 = 4, from rfl] at hp1,
have := nat.mod_lt p (show 0 < 4, from dec_trivial),
revert this hp3 hp1,
generalize : p % 4 = m, dec_trivial!,
end,
let ⟨k, hk⟩ := zmod.exists_sq_eq_neg_one_iff.2 $
by rw hp41; exact dec_trivial in
begin
obtain ⟨k, k_lt_p, rfl⟩ : ∃ (k' : ℕ) (h : k' < p), (k' : zmod p) = k,
{ refine ⟨k.val, k.val_lt, zmod.nat_cast_zmod_val k⟩ },
have hpk : p ∣ k ^ 2 + 1,
by { rw [pow_two, ← char_p.cast_eq_zero_iff (zmod p) p, nat.cast_add, nat.cast_mul,
nat.cast_one, ← hk, add_left_neg], },
have hkmul : (k ^ 2 + 1 : ℤ[i]) = ⟨k, 1⟩ * ⟨k, -1⟩ :=
by simp [sq, zsqrtd.ext],
have hpne1 : p ≠ 1 := ne_of_gt hp.1.one_lt,
have hkltp : 1 + k * k < p * p,
from calc 1 + k * k ≤ k + k * k :
add_le_add_right (nat.pos_of_ne_zero
(λ hk0, by clear_aux_decl; simp [*, pow_succ'] at *)) _
... = k * (k + 1) : by simp [add_comm, mul_add]
... < p * p : mul_lt_mul k_lt_p k_lt_p (nat.succ_pos _) (nat.zero_le _),
have hpk₁ : ¬ (p : ℤ[i]) ∣ ⟨k, -1⟩ :=
λ ⟨x, hx⟩, lt_irrefl (p * x : ℤ[i]).norm.nat_abs $
calc (norm (p * x : ℤ[i])).nat_abs = (zsqrtd.norm ⟨k, -1⟩).nat_abs : by rw hx
... < (norm (p : ℤ[i])).nat_abs : by simpa [add_comm, zsqrtd.norm] using hkltp
... ≤ (norm (p * x : ℤ[i])).nat_abs : norm_le_norm_mul_left _
(λ hx0, (show (-1 : ℤ) ≠ 0, from dec_trivial) $
by simpa [hx0] using congr_arg zsqrtd.im hx),
have hpk₂ : ¬ (p : ℤ[i]) ∣ ⟨k, 1⟩ :=
λ ⟨x, hx⟩, lt_irrefl (p * x : ℤ[i]).norm.nat_abs $
calc (norm (p * x : ℤ[i])).nat_abs = (zsqrtd.norm ⟨k, 1⟩).nat_abs : by rw hx
... < (norm (p : ℤ[i])).nat_abs : by simpa [add_comm, zsqrtd.norm] using hkltp
... ≤ (norm (p * x : ℤ[i])).nat_abs : norm_le_norm_mul_left _
(λ hx0, (show (1 : ℤ) ≠ 0, from dec_trivial) $
by simpa [hx0] using congr_arg zsqrtd.im hx),
have hpu : ¬ is_unit (p : ℤ[i]), from mt norm_eq_one_iff.2
(by rw [norm_nat_cast, int.nat_abs_mul, mul_eq_one];
exact λ h, (ne_of_lt hp.1.one_lt).symm h.1),
obtain ⟨y, hy⟩ := hpk,
have := hpi.2.2 ⟨k, 1⟩ ⟨k, -1⟩ ⟨y, by rw [← hkmul, ← nat.cast_mul p, ← hy]; simp⟩,
clear_aux_decl, tauto
end)
lemma prime_of_nat_prime_of_mod_four_eq_three (p : ℕ) [hp : fact p.prime] (hp3 : p % 4 = 3) :
prime (p : ℤ[i]) :=
irreducible_iff_prime.1 $ classical.by_contradiction $ λ hpi,
let ⟨a, b, hab⟩ := sq_add_sq_of_nat_prime_of_not_irreducible p hpi in
have ∀ a b : zmod 4, a^2 + b^2 ≠ p, by erw [← zmod.nat_cast_mod p 4, hp3]; exact dec_trivial,
this a b (hab ▸ by simp)
/-- A prime natural number is prime in `ℤ[i]` if and only if it is `3` mod `4` -/
lemma prime_iff_mod_four_eq_three_of_nat_prime (p : ℕ) [hp : fact p.prime] :
prime (p : ℤ[i]) ↔ p % 4 = 3 :=
⟨mod_four_eq_three_of_nat_prime_of_prime p, prime_of_nat_prime_of_mod_four_eq_three p⟩
end gaussian_int
|
02c8e8bc2ca66ef6cf54b6758ee00f0227fd4275 | 7cef822f3b952965621309e88eadf618da0c8ae9 | /src/data/quot.lean | 1a38f9a26fbf4a843bf921438965b5ba004a445e | [
"Apache-2.0"
] | permissive | rmitta/mathlib | 8d90aee30b4db2b013e01f62c33f297d7e64a43d | 883d974b608845bad30ae19e27e33c285200bf84 | refs/heads/master | 1,585,776,832,544 | 1,576,874,096,000 | 1,576,874,096,000 | 153,663,165 | 0 | 2 | Apache-2.0 | 1,544,806,490,000 | 1,539,884,365,000 | Lean | UTF-8 | Lean | false | false | 11,704 | 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
Quotients -- extends the core library
-/
import logic.relator
variables {α : Sort*} {β : Sort*}
namespace setoid
lemma ext {α : Sort*} :
∀{s t : setoid α}, (∀a b, @setoid.r α s a b ↔ @setoid.r α t a b) → s = t
| ⟨r, _⟩ ⟨p, _⟩ eq :=
have r = p, from funext $ assume a, funext $ assume b, propext $ eq a b,
by subst this
end setoid
namespace quot
variables {ra : α → α → Prop} {rb : β → β → Prop} {φ : quot ra → quot rb → Sort*}
local notation `⟦`:max a `⟧` := quot.mk _ a
protected def hrec_on₂ (qa : quot ra) (qb : quot rb) (f : ∀ a b, φ ⟦a⟧ ⟦b⟧)
(ca : ∀ {b a₁ a₂}, ra a₁ a₂ → f a₁ b == f a₂ b)
(cb : ∀ {a b₁ b₂}, rb b₁ b₂ → f a b₁ == f a b₂) : φ qa qb :=
quot.hrec_on qa (λ a, quot.hrec_on qb (f a) (λ b₁ b₂ pb, cb pb)) $ λ a₁ a₂ pa,
quot.induction_on qb $ λ b,
calc @quot.hrec_on _ _ (φ _) ⟦b⟧ (f a₁) (@cb _)
== f a₁ b : by simp
... == f a₂ b : ca pa
... == @quot.hrec_on _ _ (φ _) ⟦b⟧ (f a₂) (@cb _) : by simp
/-- Map a function `f : α → β` such that `ra x y` implies `rb (f x) (f y)`
to a map `quot ra → quot rb`. -/
protected def map (f : α → β) (h : (ra ⇒ rb) f f) : quot ra → quot rb :=
quot.lift (λ x, ⟦f x⟧) $ assume x y (h₁ : ra x y), quot.sound $ h h₁
/-- If `ra` is a subrelation of `ra'`, then we have a natural map `quot ra → quot ra'`. -/
protected def map_right {ra' : α → α → Prop} (h : ∀a₁ a₂, ra a₁ a₂ → ra' a₁ a₂) :
quot ra → quot ra' :=
quot.map id h
end quot
namespace quotient
variables [sa : setoid α] [sb : setoid β]
variables {φ : quotient sa → quotient sb → Sort*}
protected def hrec_on₂ (qa : quotient sa) (qb : quotient sb) (f : ∀ a b, φ ⟦a⟧ ⟦b⟧)
(c : ∀ a₁ b₁ a₂ b₂, a₁ ≈ a₂ → b₁ ≈ b₂ → f a₁ b₁ == f a₂ b₂) : φ qa qb :=
quot.hrec_on₂ qa qb f
(λ _ _ _ p, c _ _ _ _ p (setoid.refl _))
(λ _ _ _ p, c _ _ _ _ (setoid.refl _) p)
/-- Map a function `f : α → β` that sends equivalent elements to equivalent elements
to a function `quotient sa → quotient sb`. Useful to define unary operations on quotients. -/
protected def map (f : α → β) (h : ((≈) ⇒ (≈)) f f) : quotient sa → quotient sb :=
quot.map f @h
variables {γ : Sort*} [sc : setoid γ]
/-- Map a function `f : α → β → γ` that sends equivalent elements to equivalent elements
to a function `f : quotient sa → quotient sb → quotient sc`.
Useful to define binary operations on quotients. -/
protected def map₂ (f : α → β → γ) (h : ((≈) ⇒ (≈) ⇒ (≈)) f f) :
quotient sa → quotient sb → quotient sc :=
quotient.lift₂ (λ x y, ⟦f x y⟧) (λ x₁ y₁ x₂ y₂ h₁ h₂, quot.sound $ h h₁ h₂)
/-- A version of `quotient.map₂` using curly braces and unification. -/
protected def map₂' {α : Sort*} {β : Sort*} {γ : Sort*}
{sa : setoid α} {sb : setoid β} {sc : setoid γ}
(f : α → β → γ) (h : ((≈) ⇒ (≈) ⇒ (≈)) f f) :
quotient sa → quotient sb → quotient sc :=
quotient.map₂ f h
end quotient
@[simp] theorem quotient.eq [r : setoid α] {x y : α} : ⟦x⟧ = ⟦y⟧ ↔ x ≈ y :=
⟨quotient.exact, quotient.sound⟩
theorem forall_quotient_iff {α : Type*} [r : setoid α] {p : quotient r → Prop} :
(∀a:quotient r, p a) ↔ (∀a:α, p ⟦a⟧) :=
⟨assume h x, h _, assume h a, a.induction_on h⟩
@[simp] lemma quotient.lift_beta [s : setoid α] (f : α → β) (h : ∀ (a b : α), a ≈ b → f a = f b) (x : α) :
quotient.lift f h (quotient.mk x) = f x := rfl
@[simp] lemma quotient.lift_on_beta [s : setoid α] (f : α → β) (h : ∀ (a b : α), a ≈ b → f a = f b) (x : α) :
quotient.lift_on (quotient.mk x) f h = f x := rfl
/-- Choose an element of the equivalence class using the axiom of choice.
Sound but noncomputable. -/
noncomputable def quot.out {r : α → α → Prop} (q : quot r) : α :=
classical.some (quot.exists_rep q)
/-- Unwrap the VM representation of a quotient to obtain an element of the equivalence class.
Computable but unsound. -/
meta def quot.unquot {r : α → α → Prop} : quot r → α := unchecked_cast
@[simp] theorem quot.out_eq {r : α → α → Prop} (q : quot r) : quot.mk r q.out = q :=
classical.some_spec (quot.exists_rep q)
/-- Choose an element of the equivalence class using the axiom of choice.
Sound but noncomputable. -/
noncomputable def quotient.out [s : setoid α] : quotient s → α := quot.out
@[simp] theorem quotient.out_eq [s : setoid α] (q : quotient s) : ⟦q.out⟧ = q := q.out_eq
theorem quotient.mk_out [s : setoid α] (a : α) : ⟦a⟧.out ≈ a :=
quotient.exact (quotient.out_eq _)
instance pi_setoid {ι : Sort*} {α : ι → Sort*} [∀ i, setoid (α i)] : setoid (Π i, α i) :=
{ r := λ a b, ∀ i, a i ≈ b i,
iseqv := ⟨
λ a i, setoid.refl _,
λ a b h i, setoid.symm (h _),
λ a b c h₁ h₂ i, setoid.trans (h₁ _) (h₂ _)⟩ }
noncomputable def quotient.choice {ι : Type*} {α : ι → Type*} [S : ∀ i, setoid (α i)]
(f : ∀ i, quotient (S i)) : @quotient (Π i, α i) (by apply_instance) :=
⟦λ i, (f i).out⟧
theorem quotient.choice_eq {ι : Type*} {α : ι → Type*} [∀ i, setoid (α i)]
(f : ∀ i, α i) : quotient.choice (λ i, ⟦f i⟧) = ⟦f⟧ :=
quotient.sound $ λ i, quotient.mk_out _
lemma nonempty_quotient_iff (s : setoid α) : nonempty (quotient s) ↔ nonempty α :=
⟨assume ⟨a⟩, quotient.induction_on a nonempty.intro, assume ⟨a⟩, ⟨⟦a⟧⟩⟩
/-- `trunc α` is the quotient of `α` by the always-true relation. This
is related to the propositional truncation in HoTT, and is similar
in effect to `nonempty α`, but unlike `nonempty α`, `trunc α` is data,
so the VM representation is the same as `α`, and so this can be used to
maintain computability. -/
def {u} trunc (α : Sort u) : Sort u := @quot α (λ _ _, true)
theorem true_equivalence : @equivalence α (λ _ _, true) :=
⟨λ _, trivial, λ _ _ _, trivial, λ _ _ _ _ _, trivial⟩
namespace trunc
/-- Constructor for `trunc α` -/
def mk (a : α) : trunc α := quot.mk _ a
/-- Any constant function lifts to a function out of the truncation -/
def lift (f : α → β) (c : ∀ a b : α, f a = f b) : trunc α → β :=
quot.lift f (λ a b _, c a b)
theorem ind {β : trunc α → Prop} : (∀ a : α, β (mk a)) → ∀ q : trunc α, β q := quot.ind
protected theorem lift_beta (f : α → β) (c) (a : α) : lift f c (mk a) = f a := rfl
@[reducible, elab_as_eliminator]
protected def lift_on (q : trunc α) (f : α → β)
(c : ∀ a b : α, f a = f b) : β := lift f c q
@[elab_as_eliminator]
protected theorem induction_on {β : trunc α → Prop} (q : trunc α)
(h : ∀ a, β (mk a)) : β q := ind h q
theorem exists_rep (q : trunc α) : ∃ a : α, mk a = q := quot.exists_rep q
attribute [elab_as_eliminator]
protected theorem induction_on₂
{C : trunc α → trunc β → Prop} (q₁ : trunc α) (q₂ : trunc β) (h : ∀ a b, C (mk a) (mk b)) : C q₁ q₂ :=
trunc.induction_on q₁ $ λ a₁, trunc.induction_on q₂ (h a₁)
protected theorem eq (a b : trunc α) : a = b :=
trunc.induction_on₂ a b (λ x y, quot.sound trivial)
instance : subsingleton (trunc α) := ⟨trunc.eq⟩
def bind (q : trunc α) (f : α → trunc β) : trunc β :=
trunc.lift_on q f (λ a b, trunc.eq _ _)
def map (f : α → β) (q : trunc α) : trunc β := bind q (trunc.mk ∘ f)
instance : monad trunc :=
{ pure := @trunc.mk,
bind := @trunc.bind }
instance : is_lawful_monad trunc :=
{ id_map := λ α q, trunc.eq _ _,
pure_bind := λ α β q f, rfl,
bind_assoc := λ α β γ x f g, trunc.eq _ _ }
variable {C : trunc α → Sort*}
@[reducible, elab_as_eliminator]
protected def rec
(f : Π a, C (mk a)) (h : ∀ (a b : α), (eq.rec (f a) (trunc.eq (mk a) (mk b)) : C (mk b)) = f b)
(q : trunc α) : C q :=
quot.rec f (λ a b _, h a b) q
@[reducible, elab_as_eliminator]
protected def rec_on (q : trunc α) (f : Π a, C (mk a))
(h : ∀ (a b : α), (eq.rec (f a) (trunc.eq (mk a) (mk b)) : C (mk b)) = f b) : C q :=
trunc.rec f h q
@[reducible, elab_as_eliminator]
protected def rec_on_subsingleton
[∀ a, subsingleton (C (mk a))] (q : trunc α) (f : Π a, C (mk a)) : C q :=
trunc.rec f (λ a b, subsingleton.elim _ (f b)) q
/-- Noncomputably extract a representative of `trunc α` (using the axiom of choice). -/
noncomputable def out : trunc α → α := quot.out
@[simp] theorem out_eq (q : trunc α) : mk q.out = q := trunc.eq _ _
end trunc
theorem nonempty_of_trunc (q : trunc α) : nonempty α :=
let ⟨a, _⟩ := q.exists_rep in ⟨a⟩
namespace quotient
variables {γ : Sort*} {φ : Sort*}
{s₁ : setoid α} {s₂ : setoid β} {s₃ : setoid γ}
/- Versions of quotient definitions and lemmas ending in `'` use unification instead
of typeclass inference for inferring the `setoid` argument. This is useful when there are
several different quotient relations on a type, for example quotient groups, rings and modules -/
protected def mk' (a : α) : quotient s₁ := quot.mk s₁.1 a
@[elab_as_eliminator, reducible]
protected def lift_on' (q : quotient s₁) (f : α → φ)
(h : ∀ a b, @setoid.r α s₁ a b → f a = f b) : φ := quotient.lift_on q f h
@[elab_as_eliminator, reducible]
protected def lift_on₂' (q₁ : quotient s₁) (q₂ : quotient s₂) (f : α → β → γ)
(h : ∀ a₁ a₂ b₁ b₂, @setoid.r α s₁ a₁ b₁ → @setoid.r β s₂ a₂ b₂ → f a₁ a₂ = f b₁ b₂) : γ :=
quotient.lift_on₂ q₁ q₂ f h
@[elab_as_eliminator]
protected lemma ind' {p : quotient s₁ → Prop}
(h : ∀ a, p (quotient.mk' a)) (q : quotient s₁) : p q :=
quotient.ind h q
@[elab_as_eliminator]
protected lemma ind₂' {p : quotient s₁ → quotient s₂ → Prop}
(h : ∀ a₁ a₂, p (quotient.mk' a₁) (quotient.mk' a₂))
(q₁ : quotient s₁) (q₂ : quotient s₂) : p q₁ q₂ :=
quotient.ind₂ h q₁ q₂
@[elab_as_eliminator]
protected lemma induction_on' {p : quotient s₁ → Prop} (q : quotient s₁)
(h : ∀ a, p (quotient.mk' a)) : p q := quotient.induction_on q h
@[elab_as_eliminator]
protected lemma induction_on₂' {p : quotient s₁ → quotient s₂ → Prop} (q₁ : quotient s₁)
(q₂ : quotient s₂) (h : ∀ a₁ a₂, p (quotient.mk' a₁) (quotient.mk' a₂)) : p q₁ q₂ :=
quotient.induction_on₂ q₁ q₂ h
@[elab_as_eliminator]
protected lemma induction_on₃' {p : quotient s₁ → quotient s₂ → quotient s₃ → Prop}
(q₁ : quotient s₁) (q₂ : quotient s₂) (q₃ : quotient s₃)
(h : ∀ a₁ a₂ a₃, p (quotient.mk' a₁) (quotient.mk' a₂) (quotient.mk' a₃)) : p q₁ q₂ q₃ :=
quotient.induction_on₃ q₁ q₂ q₃ h
lemma exact' {a b : α} :
(quotient.mk' a : quotient s₁) = quotient.mk' b → @setoid.r _ s₁ a b :=
quotient.exact
lemma sound' {a b : α} : @setoid.r _ s₁ a b → @quotient.mk' α s₁ a = quotient.mk' b :=
quotient.sound
@[simp] protected lemma eq' {a b : α} : @quotient.mk' α s₁ a = quotient.mk' b ↔ @setoid.r _ s₁ a b :=
quotient.eq
noncomputable def out' (a : quotient s₁) : α := quotient.out a
@[simp] theorem out_eq' (q : quotient s₁) : quotient.mk' q.out' = q := q.out_eq
theorem mk_out' (a : α) : @setoid.r α s₁ (quotient.mk' a : quotient s₁).out' a :=
quotient.exact (quotient.out_eq _)
end quotient
|
dbc24ca1dd17c60ef4dcfb7f453f45818952b8c5 | a46270e2f76a375564f3b3e9c1bf7b635edc1f2c | /8.9.4.lean | 692679e7f9facbb9dd3293238cfa11876ae70177 | [
"CC0-1.0"
] | permissive | wudcscheme/lean-exercise | 88ea2506714eac343de2a294d1132ee8ee6d3a20 | 5b23b9be3d361fff5e981d5be3a0a1175504b9f6 | refs/heads/master | 1,678,958,930,293 | 1,583,197,205,000 | 1,583,197,205,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 683 | lean |
def fact: nat -> nat
| 0 := 1
| (n+1) := (n+1) * (fact n)
example: fact 5 = 120 := rfl
def c: nat -> nat
| 0 := 1
| 1 := 1
| (n+1) := (c n) * 2*(2*n + 1)/(n+2)
#eval c 1
#eval c 5
example: c 5 = 42 := rfl
#eval c 10
lemma lt_pred (x: nat) (h: 0 < x): (x-1) < x := nat.sub_lt h (nat.lt.base 0)
def fact' := well_founded.fix nat.lt_wf (λ x f, if h : x > 0 then x * (f (x-1) (lt_pred x h) ) else 1)
#eval fact' 8
example: fact' 8 = fact 8 := rfl.
lemma fact'_succ (n: nat): fact' (n+1) = (n+1)*(fact' n) := rfl.
theorem commutes (n: nat): fact n = fact' n := begin
induction n, reflexivity,
case nat.succ: n ih {
simp [fact, fact'_succ, ih],
}
end
|
4b6865e88f30f46415d3cc02fbaaa73e71e09f75 | d1a52c3f208fa42c41df8278c3d280f075eb020c | /stage0/src/Lean/Compiler/IR/Basic.lean | bd8038e9f991eac3860bf33bd81b7334ae833c9b | [
"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 | 26,228 | 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.Data.KVMap
import Lean.Data.Name
import Lean.Data.Format
import Lean.Compiler.ExternAttr
/-
Implements (extended) λPure and λRc proposed in the article
"Counting Immutable Beans", Sebastian Ullrich and Leonardo de Moura.
The Lean to IR transformation produces λPure code, and
this part is implemented in C++. The procedures described in the paper
above are implemented in Lean.
-/
namespace Lean.IR
/- Function identifier -/
abbrev FunId := Name
abbrev Index := Nat
/- Variable identifier -/
structure VarId where
idx : Index
deriving Inhabited
/- Join point identifier -/
structure JoinPointId where
idx : Index
deriving Inhabited
abbrev Index.lt (a b : Index) : Bool := a < b
instance : BEq VarId := ⟨fun a b => a.idx == b.idx⟩
instance : ToString VarId := ⟨fun a => "x_" ++ toString a.idx⟩
instance : ToFormat VarId := ⟨fun a => toString a⟩
instance : Hashable VarId := ⟨fun a => hash a.idx⟩
instance : BEq JoinPointId := ⟨fun a b => a.idx == b.idx⟩
instance : ToString JoinPointId := ⟨fun a => "block_" ++ toString a.idx⟩
instance : ToFormat JoinPointId := ⟨fun a => toString a⟩
instance : Hashable JoinPointId := ⟨fun a => hash a.idx⟩
abbrev MData := KVMap
abbrev MData.empty : MData := {}
/- Low Level IR types. Most are self explanatory.
- `usize` represents the C++ `size_t` Type. We have it here
because it is 32-bit in 32-bit machines, and 64-bit in 64-bit machines,
and we want the C++ backend for our Compiler to generate platform independent code.
- `irrelevant` for Lean types, propositions and proofs.
- `object` a pointer to a value in the heap.
- `tobject` a pointer to a value in the heap or tagged pointer
(i.e., the least significant bit is 1) storing a scalar value.
- `struct` and `union` are used to return small values (e.g., `Option`, `Prod`, `Except`)
on the stack.
Remark: the RC operations for `tobject` are slightly more expensive because we
first need to test whether the `tobject` is really a pointer or not.
Remark: the Lean runtime assumes that sizeof(void*) == sizeof(sizeT).
Lean cannot be compiled on old platforms where this is not True.
Since values of type `struct` and `union` are only used to return values,
We assume they must be used/consumed "linearly". We use the term "linear" here
to mean "exactly once" in each execution. That is, given `x : S`, where `S` is a struct,
then one of the following must hold in each (execution) branch.
1- `x` occurs only at a single `ret x` instruction. That is, it is being consumed by being returned.
2- `x` occurs only at a single `ctor`. That is, it is being "consumed" by being stored into another `struct/union`.
3- We extract (aka project) every single field of `x` exactly once. That is, we are consuming `x` by consuming each
of one of its components. Minor refinement: we don't need to consume scalar fields or struct/union
fields that do not contain object fields.
-/
inductive IRType where
| float | uint8 | uint16 | uint32 | uint64 | usize
| irrelevant | object | tobject
| struct (leanTypeName : Option Name) (types : Array IRType) : IRType
| union (leanTypeName : Name) (types : Array IRType) : IRType
deriving Inhabited
namespace IRType
partial def beq : IRType → IRType → Bool
| float, float => true
| uint8, uint8 => true
| uint16, uint16 => true
| uint32, uint32 => true
| uint64, uint64 => true
| usize, usize => true
| irrelevant, irrelevant => true
| object, object => true
| tobject, tobject => true
| struct n₁ tys₁, struct n₂ tys₂ => n₁ == n₂ && Array.isEqv tys₁ tys₂ beq
| union n₁ tys₁, union n₂ tys₂ => n₁ == n₂ && Array.isEqv tys₁ tys₂ beq
| _, _ => false
instance : BEq IRType := ⟨beq⟩
def isScalar : IRType → Bool
| float => true
| uint8 => true
| uint16 => true
| uint32 => true
| uint64 => true
| usize => true
| _ => false
def isObj : IRType → Bool
| object => true
| tobject => true
| _ => false
def isIrrelevant : IRType → Bool
| irrelevant => true
| _ => false
def isStruct : IRType → Bool
| struct _ _ => true
| _ => false
def isUnion : IRType → Bool
| union _ _ => true
| _ => false
end IRType
/- Arguments to applications, constructors, etc.
We use `irrelevant` for Lean types, propositions and proofs that have been erased.
Recall that for a Function `f`, we also generate `f._rarg` which does not take
`irrelevant` arguments. However, `f._rarg` is only safe to be used in full applications. -/
inductive Arg where
| var (id : VarId)
| irrelevant
deriving Inhabited
protected def Arg.beq : Arg → Arg → Bool
| var x, var y => x == y
| irrelevant, irrelevant => true
| _, _ => false
instance : BEq Arg := ⟨Arg.beq⟩
@[export lean_ir_mk_var_arg] def mkVarArg (id : VarId) : Arg := Arg.var id
inductive LitVal where
| num (v : Nat)
| str (v : String)
def LitVal.beq : LitVal → LitVal → Bool
| num v₁, num v₂ => v₁ == v₂
| str v₁, str v₂ => v₁ == v₂
| _, _ => false
instance : BEq LitVal := ⟨LitVal.beq⟩
/- Constructor information.
- `name` is the Name of the Constructor in Lean.
- `cidx` is the Constructor index (aka tag).
- `size` is the number of arguments of type `object/tobject`.
- `usize` is the number of arguments of type `usize`.
- `ssize` is the number of bytes used to store scalar values.
Recall that a Constructor object contains a header, then a sequence of
pointers to other Lean objects, a sequence of `USize` (i.e., `size_t`)
scalar values, and a sequence of other scalar values. -/
structure CtorInfo where
name : Name
cidx : Nat
size : Nat
usize : Nat
ssize : Nat
deriving Repr
def CtorInfo.beq : CtorInfo → CtorInfo → Bool
| ⟨n₁, cidx₁, size₁, usize₁, ssize₁⟩, ⟨n₂, cidx₂, size₂, usize₂, ssize₂⟩ =>
n₁ == n₂ && cidx₁ == cidx₂ && size₁ == size₂ && usize₁ == usize₂ && ssize₁ == ssize₂
instance : BEq CtorInfo := ⟨CtorInfo.beq⟩
def CtorInfo.isRef (info : CtorInfo) : Bool :=
info.size > 0 || info.usize > 0 || info.ssize > 0
def CtorInfo.isScalar (info : CtorInfo) : Bool :=
!info.isRef
inductive Expr where
/- We use `ctor` mainly for constructing Lean object/tobject values `lean_ctor_object` in the runtime.
This instruction is also used to creat `struct` and `union` return values.
For `union`, only `i.cidx` is relevant. For `struct`, `i` is irrelevant. -/
| ctor (i : CtorInfo) (ys : Array Arg)
| reset (n : Nat) (x : VarId)
/- `reuse x in ctor_i ys` instruction in the paper. -/
| reuse (x : VarId) (i : CtorInfo) (updtHeader : Bool) (ys : Array Arg)
/- Extract the `tobject` value at Position `sizeof(void*)*i` from `x`.
We also use `proj` for extracting fields from `struct` return values, and casting `union` return values. -/
| proj (i : Nat) (x : VarId)
/- Extract the `Usize` value at Position `sizeof(void*)*i` from `x`. -/
| uproj (i : Nat) (x : VarId)
/- Extract the scalar value at Position `sizeof(void*)*n + offset` from `x`. -/
| sproj (n : Nat) (offset : Nat) (x : VarId)
/- Full application. -/
| fap (c : FunId) (ys : Array Arg)
/- Partial application that creates a `pap` value (aka closure in our nonstandard terminology). -/
| pap (c : FunId) (ys : Array Arg)
/- Application. `x` must be a `pap` value. -/
| ap (x : VarId) (ys : Array Arg)
/- Given `x : ty` where `ty` is a scalar type, this operation returns a value of Type `tobject`.
For small scalar values, the Result is a tagged pointer, and no memory allocation is performed. -/
| box (ty : IRType) (x : VarId)
/- Given `x : [t]object`, obtain the scalar value. -/
| unbox (x : VarId)
| lit (v : LitVal)
/- Return `1 : uint8` Iff `RC(x) > 1` -/
| isShared (x : VarId)
/- Return `1 : uint8` Iff `x : tobject` is a tagged pointer (storing a scalar value). -/
| isTaggedPtr (x : VarId)
@[export lean_ir_mk_ctor_expr] def mkCtorExpr (n : Name) (cidx : Nat) (size : Nat) (usize : Nat) (ssize : Nat) (ys : Array Arg) : Expr :=
Expr.ctor ⟨n, cidx, size, usize, ssize⟩ ys
@[export lean_ir_mk_proj_expr] def mkProjExpr (i : Nat) (x : VarId) : Expr := Expr.proj i x
@[export lean_ir_mk_uproj_expr] def mkUProjExpr (i : Nat) (x : VarId) : Expr := Expr.uproj i x
@[export lean_ir_mk_sproj_expr] def mkSProjExpr (n : Nat) (offset : Nat) (x : VarId) : Expr := Expr.sproj n offset x
@[export lean_ir_mk_fapp_expr] def mkFAppExpr (c : FunId) (ys : Array Arg) : Expr := Expr.fap c ys
@[export lean_ir_mk_papp_expr] def mkPAppExpr (c : FunId) (ys : Array Arg) : Expr := Expr.pap c ys
@[export lean_ir_mk_app_expr] def mkAppExpr (x : VarId) (ys : Array Arg) : Expr := Expr.ap x ys
@[export lean_ir_mk_num_expr] def mkNumExpr (v : Nat) : Expr := Expr.lit (LitVal.num v)
@[export lean_ir_mk_str_expr] def mkStrExpr (v : String) : Expr := Expr.lit (LitVal.str v)
structure Param where
x : VarId
borrow : Bool
ty : IRType
deriving Inhabited
@[export lean_ir_mk_param]
def mkParam (x : VarId) (borrow : Bool) (ty : IRType) : Param := ⟨x, borrow, ty⟩
inductive AltCore (FnBody : Type) : Type where
| ctor (info : CtorInfo) (b : FnBody) : AltCore FnBody
| default (b : FnBody) : AltCore FnBody
inductive FnBody where
/- `let x : ty := e; b` -/
| vdecl (x : VarId) (ty : IRType) (e : Expr) (b : FnBody)
/- Join point Declaration `block_j (xs) := e; b` -/
| jdecl (j : JoinPointId) (xs : Array Param) (v : FnBody) (b : FnBody)
/- Store `y` at Position `sizeof(void*)*i` in `x`. `x` must be a Constructor object and `RC(x)` must be 1.
This operation is not part of λPure is only used during optimization. -/
| set (x : VarId) (i : Nat) (y : Arg) (b : FnBody)
| setTag (x : VarId) (cidx : Nat) (b : FnBody)
/- Store `y : Usize` at Position `sizeof(void*)*i` in `x`. `x` must be a Constructor object and `RC(x)` must be 1. -/
| uset (x : VarId) (i : Nat) (y : VarId) (b : FnBody)
/- Store `y : ty` at Position `sizeof(void*)*i + offset` in `x`. `x` must be a Constructor object and `RC(x)` must be 1.
`ty` must not be `object`, `tobject`, `irrelevant` nor `Usize`. -/
| sset (x : VarId) (i : Nat) (offset : Nat) (y : VarId) (ty : IRType) (b : FnBody)
/- RC increment for `object`. If c == `true`, then `inc` must check whether `x` is a tagged pointer or not.
If `persistent == true` then `x` is statically known to be a persistent object. -/
| inc (x : VarId) (n : Nat) (c : Bool) (persistent : Bool) (b : FnBody)
/- RC decrement for `object`. If c == `true`, then `inc` must check whether `x` is a tagged pointer or not.
If `persistent == true` then `x` is statically known to be a persistent object. -/
| dec (x : VarId) (n : Nat) (c : Bool) (persistent : Bool) (b : FnBody)
| del (x : VarId) (b : FnBody)
| mdata (d : MData) (b : FnBody)
| case (tid : Name) (x : VarId) (xType : IRType) (cs : Array (AltCore FnBody))
| ret (x : Arg)
/- Jump to join point `j` -/
| jmp (j : JoinPointId) (ys : Array Arg)
| unreachable
instance : Inhabited FnBody := ⟨FnBody.unreachable⟩
abbrev FnBody.nil := FnBody.unreachable
@[export lean_ir_mk_vdecl] def mkVDecl (x : VarId) (ty : IRType) (e : Expr) (b : FnBody) : FnBody := FnBody.vdecl x ty e b
@[export lean_ir_mk_jdecl] def mkJDecl (j : JoinPointId) (xs : Array Param) (v : FnBody) (b : FnBody) : FnBody := FnBody.jdecl j xs v b
@[export lean_ir_mk_uset] def mkUSet (x : VarId) (i : Nat) (y : VarId) (b : FnBody) : FnBody := FnBody.uset x i y b
@[export lean_ir_mk_sset] def mkSSet (x : VarId) (i : Nat) (offset : Nat) (y : VarId) (ty : IRType) (b : FnBody) : FnBody := FnBody.sset x i offset y ty b
@[export lean_ir_mk_case] def mkCase (tid : Name) (x : VarId) (cs : Array (AltCore FnBody)) : FnBody :=
-- Type field `xType` is set by `explicitBoxing` compiler pass.
FnBody.case tid x IRType.object cs
@[export lean_ir_mk_ret] def mkRet (x : Arg) : FnBody := FnBody.ret x
@[export lean_ir_mk_jmp] def mkJmp (j : JoinPointId) (ys : Array Arg) : FnBody := FnBody.jmp j ys
@[export lean_ir_mk_unreachable] def mkUnreachable : Unit → FnBody := fun _ => FnBody.unreachable
abbrev Alt := AltCore FnBody
@[matchPattern] abbrev Alt.ctor := @AltCore.ctor FnBody
@[matchPattern] abbrev Alt.default := @AltCore.default FnBody
instance : Inhabited Alt := ⟨Alt.default arbitrary⟩
def FnBody.isTerminal : FnBody → Bool
| FnBody.case _ _ _ _ => true
| FnBody.ret _ => true
| FnBody.jmp _ _ => true
| FnBody.unreachable => true
| _ => false
def FnBody.body : FnBody → FnBody
| FnBody.vdecl _ _ _ b => b
| FnBody.jdecl _ _ _ b => b
| FnBody.set _ _ _ b => b
| FnBody.uset _ _ _ b => b
| FnBody.sset _ _ _ _ _ b => b
| FnBody.setTag _ _ b => b
| FnBody.inc _ _ _ _ b => b
| FnBody.dec _ _ _ _ b => b
| FnBody.del _ b => b
| FnBody.mdata _ b => b
| other => other
def FnBody.setBody : FnBody → FnBody → FnBody
| FnBody.vdecl x t v _, b => FnBody.vdecl x t v b
| FnBody.jdecl j xs v _, b => FnBody.jdecl j xs v b
| FnBody.set x i y _, b => FnBody.set x i y b
| FnBody.uset x i y _, b => FnBody.uset x i y b
| FnBody.sset x i o y t _, b => FnBody.sset x i o y t b
| FnBody.setTag x i _, b => FnBody.setTag x i b
| FnBody.inc x n c p _, b => FnBody.inc x n c p b
| FnBody.dec x n c p _, b => FnBody.dec x n c p b
| FnBody.del x _, b => FnBody.del x b
| FnBody.mdata d _, b => FnBody.mdata d b
| other, b => other
@[inline] def FnBody.resetBody (b : FnBody) : FnBody :=
b.setBody FnBody.nil
/- If b is a non terminal, then return a pair `(c, b')` s.t. `b == c <;> b'`,
and c.body == FnBody.nil -/
@[inline] def FnBody.split (b : FnBody) : FnBody × FnBody :=
let b' := b.body
let c := b.resetBody
(c, b')
def AltCore.body : Alt → FnBody
| Alt.ctor _ b => b
| Alt.default b => b
def AltCore.setBody : Alt → FnBody → Alt
| Alt.ctor c _, b => Alt.ctor c b
| Alt.default _, b => Alt.default b
@[inline] def AltCore.modifyBody (f : FnBody → FnBody) : AltCore FnBody → Alt
| Alt.ctor c b => Alt.ctor c (f b)
| Alt.default b => Alt.default (f b)
@[inline] def AltCore.mmodifyBody {m : Type → Type} [Monad m] (f : FnBody → m FnBody) : AltCore FnBody → m Alt
| Alt.ctor c b => Alt.ctor c <$> f b
| Alt.default b => Alt.default <$> f b
def Alt.isDefault : Alt → Bool
| Alt.ctor _ _ => false
| Alt.default _ => true
def push (bs : Array FnBody) (b : FnBody) : Array FnBody :=
let b := b.resetBody
bs.push b
partial def flattenAux (b : FnBody) (r : Array FnBody) : (Array FnBody) × FnBody :=
if b.isTerminal then (r, b)
else flattenAux b.body (push r b)
def FnBody.flatten (b : FnBody) : (Array FnBody) × FnBody :=
flattenAux b #[]
partial def reshapeAux (a : Array FnBody) (i : Nat) (b : FnBody) : FnBody :=
if i == 0 then b
else
let i := i - 1
let (curr, a) := a.swapAt! i arbitrary
let b := curr.setBody b
reshapeAux a i b
def reshape (bs : Array FnBody) (term : FnBody) : FnBody :=
reshapeAux bs bs.size term
@[inline] def modifyJPs (bs : Array FnBody) (f : FnBody → FnBody) : Array FnBody :=
bs.map fun b => match b with
| FnBody.jdecl j xs v k => FnBody.jdecl j xs (f v) k
| other => other
@[inline] def mmodifyJPs {m : Type → Type} [Monad m] (bs : Array FnBody) (f : FnBody → m FnBody) : m (Array FnBody) :=
bs.mapM fun b => match b with
| FnBody.jdecl j xs v k => do let v ← f v; pure $ FnBody.jdecl j xs v k
| other => pure other
@[export lean_ir_mk_alt] def mkAlt (n : Name) (cidx : Nat) (size : Nat) (usize : Nat) (ssize : Nat) (b : FnBody) : Alt :=
Alt.ctor ⟨n, cidx, size, usize, ssize⟩ b
/-- Extra information associated with a declaration. -/
structure DeclInfo where
/-- If `some <blame>`, then declaration depends on `<blame>` which uses a `sorry` axiom. -/
sorryDep? : Option Name := none
inductive Decl where
| fdecl (f : FunId) (xs : Array Param) (type : IRType) (body : FnBody) (info : DeclInfo)
| extern (f : FunId) (xs : Array Param) (type : IRType) (ext : ExternAttrData)
deriving Inhabited
namespace Decl
def name : Decl → FunId
| Decl.fdecl f .. => f
| Decl.extern f .. => f
def params : Decl → Array Param
| Decl.fdecl (xs := xs) .. => xs
| Decl.extern (xs := xs) .. => xs
def resultType : Decl → IRType
| Decl.fdecl (type := t) .. => t
| Decl.extern (type := t) .. => t
def isExtern : Decl → Bool
| Decl.extern .. => true
| _ => false
def getInfo : Decl → DeclInfo
| Decl.fdecl (info := info) .. => info
| _ => {}
def updateBody! (d : Decl) (bNew : FnBody) : Decl :=
match d with
| Decl.fdecl f xs t b info => Decl.fdecl f xs t bNew info
| _ => panic! "expected definition"
end Decl
@[export lean_ir_mk_decl] def mkDecl (f : FunId) (xs : Array Param) (ty : IRType) (b : FnBody) : Decl :=
Decl.fdecl f xs ty b {}
@[export lean_ir_mk_extern_decl] def mkExternDecl (f : FunId) (xs : Array Param) (ty : IRType) (e : ExternAttrData) : Decl :=
Decl.extern f xs ty e
open Std (RBTree RBTree.empty RBMap)
/-- Set of variable and join point names -/
abbrev IndexSet := RBTree Index compare
instance : Inhabited IndexSet := ⟨{}⟩
def mkIndexSet (idx : Index) : IndexSet :=
RBTree.empty.insert idx
inductive LocalContextEntry where
| param : IRType → LocalContextEntry
| localVar : IRType → Expr → LocalContextEntry
| joinPoint : Array Param → FnBody → LocalContextEntry
abbrev LocalContext := RBMap Index LocalContextEntry compare
def LocalContext.addLocal (ctx : LocalContext) (x : VarId) (t : IRType) (v : Expr) : LocalContext :=
ctx.insert x.idx (LocalContextEntry.localVar t v)
def LocalContext.addJP (ctx : LocalContext) (j : JoinPointId) (xs : Array Param) (b : FnBody) : LocalContext :=
ctx.insert j.idx (LocalContextEntry.joinPoint xs b)
def LocalContext.addParam (ctx : LocalContext) (p : Param) : LocalContext :=
ctx.insert p.x.idx (LocalContextEntry.param p.ty)
def LocalContext.addParams (ctx : LocalContext) (ps : Array Param) : LocalContext :=
ps.foldl LocalContext.addParam ctx
def LocalContext.isJP (ctx : LocalContext) (idx : Index) : Bool :=
match ctx.find? idx with
| some (LocalContextEntry.joinPoint _ _) => true
| other => false
def LocalContext.getJPBody (ctx : LocalContext) (j : JoinPointId) : Option FnBody :=
match ctx.find? j.idx with
| some (LocalContextEntry.joinPoint _ b) => some b
| other => none
def LocalContext.getJPParams (ctx : LocalContext) (j : JoinPointId) : Option (Array Param) :=
match ctx.find? j.idx with
| some (LocalContextEntry.joinPoint ys _) => some ys
| other => none
def LocalContext.isParam (ctx : LocalContext) (idx : Index) : Bool :=
match ctx.find? idx with
| some (LocalContextEntry.param _) => true
| other => false
def LocalContext.isLocalVar (ctx : LocalContext) (idx : Index) : Bool :=
match ctx.find? idx with
| some (LocalContextEntry.localVar _ _) => true
| other => false
def LocalContext.contains (ctx : LocalContext) (idx : Index) : Bool :=
Std.RBMap.contains ctx idx
def LocalContext.eraseJoinPointDecl (ctx : LocalContext) (j : JoinPointId) : LocalContext :=
ctx.erase j.idx
def LocalContext.getType (ctx : LocalContext) (x : VarId) : Option IRType :=
match ctx.find? x.idx with
| some (LocalContextEntry.param t) => some t
| some (LocalContextEntry.localVar t _) => some t
| other => none
def LocalContext.getValue (ctx : LocalContext) (x : VarId) : Option Expr :=
match ctx.find? x.idx with
| some (LocalContextEntry.localVar _ v) => some v
| other => none
abbrev IndexRenaming := RBMap Index Index compare
class AlphaEqv (α : Type) where
aeqv : IndexRenaming → α → α → Bool
export AlphaEqv (aeqv)
def VarId.alphaEqv (ρ : IndexRenaming) (v₁ v₂ : VarId) : Bool :=
match ρ.find? v₁.idx with
| some v => v == v₂.idx
| none => v₁ == v₂
instance : AlphaEqv VarId := ⟨VarId.alphaEqv⟩
def Arg.alphaEqv (ρ : IndexRenaming) : Arg → Arg → Bool
| Arg.var v₁, Arg.var v₂ => aeqv ρ v₁ v₂
| Arg.irrelevant, Arg.irrelevant => true
| _, _ => false
instance : AlphaEqv Arg := ⟨Arg.alphaEqv⟩
def args.alphaEqv (ρ : IndexRenaming) (args₁ args₂ : Array Arg) : Bool :=
Array.isEqv args₁ args₂ (fun a b => aeqv ρ a b)
instance: AlphaEqv (Array Arg) := ⟨args.alphaEqv⟩
def Expr.alphaEqv (ρ : IndexRenaming) : Expr → Expr → Bool
| Expr.ctor i₁ ys₁, Expr.ctor i₂ ys₂ => i₁ == i₂ && aeqv ρ ys₁ ys₂
| Expr.reset n₁ x₁, Expr.reset n₂ x₂ => n₁ == n₂ && aeqv ρ x₁ x₂
| Expr.reuse x₁ i₁ u₁ ys₁, Expr.reuse x₂ i₂ u₂ ys₂ => aeqv ρ x₁ x₂ && i₁ == i₂ && u₁ == u₂ && aeqv ρ ys₁ ys₂
| Expr.proj i₁ x₁, Expr.proj i₂ x₂ => i₁ == i₂ && aeqv ρ x₁ x₂
| Expr.uproj i₁ x₁, Expr.uproj i₂ x₂ => i₁ == i₂ && aeqv ρ x₁ x₂
| Expr.sproj n₁ o₁ x₁, Expr.sproj n₂ o₂ x₂ => n₁ == n₂ && o₁ == o₂ && aeqv ρ x₁ x₂
| Expr.fap c₁ ys₁, Expr.fap c₂ ys₂ => c₁ == c₂ && aeqv ρ ys₁ ys₂
| Expr.pap c₁ ys₁, Expr.pap c₂ ys₂ => c₁ == c₂ && aeqv ρ ys₁ ys₂
| Expr.ap x₁ ys₁, Expr.ap x₂ ys₂ => aeqv ρ x₁ x₂ && aeqv ρ ys₁ ys₂
| Expr.box ty₁ x₁, Expr.box ty₂ x₂ => ty₁ == ty₂ && aeqv ρ x₁ x₂
| Expr.unbox x₁, Expr.unbox x₂ => aeqv ρ x₁ x₂
| Expr.lit v₁, Expr.lit v₂ => v₁ == v₂
| Expr.isShared x₁, Expr.isShared x₂ => aeqv ρ x₁ x₂
| Expr.isTaggedPtr x₁, Expr.isTaggedPtr x₂ => aeqv ρ x₁ x₂
| _, _ => false
instance : AlphaEqv Expr:= ⟨Expr.alphaEqv⟩
def addVarRename (ρ : IndexRenaming) (x₁ x₂ : Nat) :=
if x₁ == x₂ then ρ else ρ.insert x₁ x₂
def addParamRename (ρ : IndexRenaming) (p₁ p₂ : Param) : Option IndexRenaming :=
if p₁.ty == p₂.ty && p₁.borrow = p₂.borrow then
some (addVarRename ρ p₁.x.idx p₂.x.idx)
else
none
def addParamsRename (ρ : IndexRenaming) (ps₁ ps₂ : Array Param) : Option IndexRenaming := OptionM.run do
if ps₁.size != ps₂.size then
failure
else
let mut ρ := ρ
for i in [:ps₁.size] do
ρ ← addParamRename ρ ps₁[i] ps₂[i]
pure ρ
partial def FnBody.alphaEqv : IndexRenaming → FnBody → FnBody → Bool
| ρ, FnBody.vdecl x₁ t₁ v₁ b₁, FnBody.vdecl x₂ t₂ v₂ b₂ => t₁ == t₂ && aeqv ρ v₁ v₂ && alphaEqv (addVarRename ρ x₁.idx x₂.idx) b₁ b₂
| ρ, FnBody.jdecl j₁ ys₁ v₁ b₁, FnBody.jdecl j₂ ys₂ v₂ b₂ => match addParamsRename ρ ys₁ ys₂ with
| some ρ' => alphaEqv ρ' v₁ v₂ && alphaEqv (addVarRename ρ j₁.idx j₂.idx) b₁ b₂
| none => false
| ρ, FnBody.set x₁ i₁ y₁ b₁, FnBody.set x₂ i₂ y₂ b₂ => aeqv ρ x₁ x₂ && i₁ == i₂ && aeqv ρ y₁ y₂ && alphaEqv ρ b₁ b₂
| ρ, FnBody.uset x₁ i₁ y₁ b₁, FnBody.uset x₂ i₂ y₂ b₂ => aeqv ρ x₁ x₂ && i₁ == i₂ && aeqv ρ y₁ y₂ && alphaEqv ρ b₁ b₂
| ρ, FnBody.sset x₁ i₁ o₁ y₁ t₁ b₁, FnBody.sset x₂ i₂ o₂ y₂ t₂ b₂ =>
aeqv ρ x₁ x₂ && i₁ = i₂ && o₁ = o₂ && aeqv ρ y₁ y₂ && t₁ == t₂ && alphaEqv ρ b₁ b₂
| ρ, FnBody.setTag x₁ i₁ b₁, FnBody.setTag x₂ i₂ b₂ => aeqv ρ x₁ x₂ && i₁ == i₂ && alphaEqv ρ b₁ b₂
| ρ, FnBody.inc x₁ n₁ c₁ p₁ b₁, FnBody.inc x₂ n₂ c₂ p₂ b₂ => aeqv ρ x₁ x₂ && n₁ == n₂ && c₁ == c₂ && p₁ == p₂ && alphaEqv ρ b₁ b₂
| ρ, FnBody.dec x₁ n₁ c₁ p₁ b₁, FnBody.dec x₂ n₂ c₂ p₂ b₂ => aeqv ρ x₁ x₂ && n₁ == n₂ && c₁ == c₂ && p₁ == p₂ && alphaEqv ρ b₁ b₂
| ρ, FnBody.del x₁ b₁, FnBody.del x₂ b₂ => aeqv ρ x₁ x₂ && alphaEqv ρ b₁ b₂
| ρ, FnBody.mdata m₁ b₁, FnBody.mdata m₂ b₂ => m₁ == m₂ && alphaEqv ρ b₁ b₂
| ρ, FnBody.case n₁ x₁ _ alts₁, FnBody.case n₂ x₂ _ alts₂ => n₁ == n₂ && aeqv ρ x₁ x₂ && Array.isEqv alts₁ alts₂ (fun alt₁ alt₂ =>
match alt₁, alt₂ with
| Alt.ctor i₁ b₁, Alt.ctor i₂ b₂ => i₁ == i₂ && alphaEqv ρ b₁ b₂
| Alt.default b₁, Alt.default b₂ => alphaEqv ρ b₁ b₂
| _, _ => false)
| ρ, FnBody.jmp j₁ ys₁, FnBody.jmp j₂ ys₂ => j₁ == j₂ && aeqv ρ ys₁ ys₂
| ρ, FnBody.ret x₁, FnBody.ret x₂ => aeqv ρ x₁ x₂
| _, FnBody.unreachable, FnBody.unreachable => true
| _, _, _ => false
def FnBody.beq (b₁ b₂ : FnBody) : Bool :=
FnBody.alphaEqv ∅ b₁ b₂
instance : BEq FnBody := ⟨FnBody.beq⟩
abbrev VarIdSet := RBTree VarId (fun x y => compare x.idx y.idx)
instance : Inhabited VarIdSet := ⟨{}⟩
def mkIf (x : VarId) (t e : FnBody) : FnBody :=
FnBody.case `Bool x IRType.uint8 #[
Alt.ctor {name := `Bool.false, cidx := 0, size := 0, usize := 0, ssize := 0} e,
Alt.ctor {name := `Bool.true, cidx := 1, size := 0, usize := 0, ssize := 0} t
]
end Lean.IR
|
e30100c784dea85247147c2382f7ea674f78f712 | cf39355caa609c0f33405126beee2739aa3cb77e | /tests/lean/inductive_resultant_level_inference.lean | 23d863907953112877abb1a4ebefe528d987781a | [
"Apache-2.0"
] | permissive | leanprover-community/lean | 12b87f69d92e614daea8bcc9d4de9a9ace089d0e | cce7990ea86a78bdb383e38ed7f9b5ba93c60ce0 | refs/heads/master | 1,687,508,156,644 | 1,684,951,104,000 | 1,684,951,104,000 | 169,960,991 | 457 | 107 | Apache-2.0 | 1,686,744,372,000 | 1,549,790,268,000 | C++ | UTF-8 | Lean | false | false | 3,227 | lean | set_option pp.all true
universe variables u v w
namespace X1
#print "\n1. ?U does not unify with anything"
inductive foo (A : Type u) (B : Type (v+1))
| mk : A → B → foo
#check @foo.{u v} -- : Type (max u (v+1))
end X1
namespace X2
#print "\n2. ?U unifies with a constant, no others above: done"
inductive bar (A : Sort 2) : Sort 2
| mk : A → bar
inductive foo
| mk : Type → bar foo → foo
#check @foo -- : Type 1
end X2
namespace X3
#print "\n3. ?U unifies with a constant, and one above: error"
inductive bar (A : Sort 2) : Sort 2
| mk : A → bar
inductive foo (A : Sort u)
| mk : A → bar foo → foo
end X3
namespace X4
#print "\n4. ?U unifies with a meta, but nesting recursor goes to Prop: error"
inductive bar (A : Sort u) : Sort u
| mk : A → bar
inductive foo
| mk : bar foo → foo
end X4
namespace X5
#print "\n5. ?U unifies with a meta: old approach, set level-param"
inductive bar (A : Sort u) : Sort (max u 1)
| mk : A → bar
inductive foo (A : Sort u)
| mk : A → bar foo → foo
#check @foo.{u} -- Sort u → Sort (max u 1)
end X5
namespace X6
#print "\n6. ?U unifies with a shifted meta, no others above: set level-param to be inverse of meta"
inductive bar (A : Sort (u + 3)) : Sort (u + 3)
| mk : A → bar
inductive foo (A : Sort u)
| mk : A → bar foo → foo
#check @foo.{u} -- Sort u → Sort (u+3)
end X6
namespace X7
#print "\n7. ?U unifies with a max: error"
inductive bar (A : Sort (max u v)) : Sort (max u v 7)
| mk : A → bar
inductive foo (A : Sort v)
| mk : A → bar foo → foo
end X7
namespace X8
#print "\n8. wrapping inductive returns element in different universe: error"
inductive bar (A : Sort u) : Sort (u + 1)
| mk : A → bar
inductive foo (A : Sort v)
| mk : A → bar foo → foo
end X8
namespace X9
#print "\n9. nesting with no other level params"
inductive bar (A : Sort u) : Sort (max u 1)
| mk : A → bar
inductive foo
| mk : bar foo → foo
#check @foo
end X9
namespace X10
#print "\n10. original 1343"
inductive foo (α : Sort (u+1)) : Sort (u+1)
| mk : α → foo
inductive bug
| mk : foo bug → bug
#check @bug
end X10
namespace X11
#print "\n11. unifies with constant, result sort different: error"
inductive foo (α : Sort 2) : Sort 1
| mk : foo
inductive bug
| mk : foo bug → bug
end X11
namespace X12
#print "\n12. multiple nestings"
inductive foo₁ (α : Sort u) : Sort (max u 1)
| mk : foo₁
inductive foo₂ (α : Type u) : Type u
| mk : foo₂
inductive foo₃ (α : Type (u+1)) : Type (u+1)
| mk : foo₃
inductive bug
| mk₁ : foo₁ bug → foo₂ bug → foo₃ bug → foo₃ (foo₂ (foo₁ bug)) → foo₁ (foo₂ (foo₃ bug)) → bug
| mk₂ : foo₁ bug → foo₂ bug → foo₃ bug → foo₃ (foo₂ (foo₁ bug)) → foo₁ (foo₂ (foo₃ bug)) → bug
#check @bug
end X12
namespace X13
#print "\n13. ?U indirectly assigned to a constant"
inductive foo (α β : Sort u) : Sort (max u 1)
| mk : foo
inductive bug
| mk₁ : foo bug (Type 3) → bug
#check @bug
end X13
namespace X14
#print "\n14. No resultant level and lps are used in intro rule: error"
inductive foo (α : Type u) : Type u
| mk : foo
inductive bug
| mk : foo.{u} bug → bug
end X14
|
3524720882801d2b21ef79d90c405fd938340e5c | 64874bd1010548c7f5a6e3e8902efa63baaff785 | /tests/lean/run/have6.lean | b98b07533b2fc62cca0d9c91e5e4be609a905512 | [
"Apache-2.0"
] | permissive | tjiaqi/lean | 4634d729795c164664d10d093f3545287c76628f | d0ce4cf62f4246b0600c07e074d86e51f2195e30 | refs/heads/master | 1,622,323,796,480 | 1,422,643,069,000 | 1,422,643,069,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 659 | lean | prelude
definition Prop : Type.{1} := Type.{0}
constant and : Prop → Prop → Prop
infixl `∧`:25 := and
constant and_intro : forall (a b : Prop), a → b → a ∧ b
constants a b c d : Prop
axiom Ha : a
axiom Hb : b
axiom Hc : c
check
have a ∧ b, from and_intro a b Ha Hb,
have [visible] b ∧ a, from and_intro b a Hb Ha,
have H : a ∧ b, from and_intro a b Ha Hb,
have H [visible] : a ∧ b, from and_intro a b Ha Hb,
then have a ∧ b, from and_intro a b Ha Hb,
then have [visible] b ∧ a, from and_intro b a Hb Ha,
then have H : a ∧ b, from and_intro a b Ha Hb,
then have H [visible] : a ∧ b, from and_intro a b Ha Hb,
Ha
|
8e91d569bb3348fbbb133ff025227cc003aa689e | a4673261e60b025e2c8c825dfa4ab9108246c32e | /tests/lean/run/funext.lean | 742386d2e4ddd900ca4ac23d04bd20beb9731248 | [
"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 | 844 | lean | theorem ex1 : (fun y => y + 0) = (fun x => 0 + x) := by
funext x
rw [Nat.zeroAdd]
rfl
theorem ex2 : (fun y x => y + x + 0) = (fun x y => y + x) := by
funext x y
rw [Nat.addZero, Nat.addComm]
rfl
theorem ex3 : (fun (x : Nat × Nat) => x.1 + x.2) = (fun (x : Nat × Nat) => x.2 + x.1) := by
funext (a, b)
show a + b = b + a
rw [Nat.addComm]
rfl
theorem ex4 : (fun (x : Nat × Nat) (y : Nat × Nat) => x.1 + y.2) = (fun (x : Nat × Nat) (z : Nat × Nat) => z.2 + x.1) := by
funext (a, b) (c, d)
show a + d = d + a
rw [Nat.addComm]
rfl
theorem ex5 : (fun (x : Id Nat) => x.succ + 0) = (fun (x : Id Nat) => 0 + x.succ) := by
funext (x : Nat)
let! y := x + 1 -- if `(x : Nat)` is not used at `funext`, then `x+1` would fail to be elaborated since we don't have the instance `Add (Id Nat)`
rw [Nat.addComm]
rfl
|
dd6240ef5ead526e376e6c0d4370421f3fe13bb1 | b66669ef1ec06ddbd9526fe3afe0a68566dfbad3 | /src/hpp.lean | 67720d4d0cf582f7441d6aae683f06a59a002b36 | [
"MIT"
] | permissive | FerdoSil/LatticesAndCellularAutomata | 40185a9099bb3cf1371c85f1ca33a17c2e26fecb | 2a69d2e74a231addf0e446dca86ef90d50d60218 | refs/heads/master | 1,587,683,992,072 | 1,586,018,471,000 | 1,586,018,471,000 | 171,533,028 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 4,641 | lean | -- Implementation of HPP Lattice Gas CA.
-- Cell states 'cellT' are represented as constructors named as possible combinations of
-- of the four directly-connected cardinal directions. 'X' is an empty cell.
-- The definition 'mk_hpp' builds an instance of HPP
-- from an initial configuration of cell states.
import cell_automaton utils data.list.perm
open utils
namespace hpp
section hpp
-- 'X' is empty
-- 'N' 'W' 'E' 'S' and their combinations represent presence (or absence) of
-- a gas molecule heading in the respective direction.
@[derive decidable_eq]
inductive cellT | X | N | W | E | S
| NW | NE | NS | WS | WE | ES
| NWE | NWS | NES | WES | NWSE
-- Cardinal directions of HPP cells.
inductive cardinal | CN | CW | CE | CS
open cellT cardinal
def cellT_str : cellT → string
| N := "↑"
| W := "←"
| E := "→"
| S := "↓"
| NW := "↖"
| NE := "↗"
| NS := "↕"
| WS := "↙"
| WE := "↔"
| ES := "↙"
| NWE := "⊥"
| NWS := "⊣"
| NES := "⊢"
| WES := "⊤"
| NWSE := "+"
| X := " "
instance cellT_to_str : has_to_string cellT := ⟨cellT_str⟩
instance cellT_repr : has_repr cellT := ⟨cellT_str⟩
attribute [reducible]
def hpp := cell_automaton cellT
def has_cardinal : cellT → cardinal → bool
| N CN := tt
| N _ := ff
| W CW := tt
| W _ := ff
| E CE := tt
| E _ := ff
| S CS := tt
| S _ := ff
| NW CN := tt
| NW CW := tt
| NW _ := ff
| NE CN := tt
| NE CE := tt
| NE _ := ff
| NS CW := tt
| NS CE := tt
| NS _ := ff
| WS CW := tt
| WS CS := tt
| WS _ := ff
| WE CS := tt
| WE CN := tt
| WE _ := ff
| ES CE := tt
| ES CS := tt
| ES _ := ff
| NWE CN := tt
| NWE CW := tt
| NWE CE := tt
| NWE _ := ff
| NWS CN := tt
| NWS CW := tt
| NWS CS := tt
| NWS _ := ff
| NES CN := tt
| NES CE := tt
| NES CS := tt
| NES _ := ff
| WES CW := tt
| WES CE := tt
| WES CS := tt
| WES _ := ff
| NWSE _ := tt
| X _ := ff
def collision : cellT → cellT
| NS := WE
| WE := NS
| x := x
def translation' : bool → bool → bool → bool → cellT
| tt tt tt tt := NWSE
| tt tt tt ff := WES
| tt tt ff tt := NES
| tt tt ff ff := ES
| tt ff tt tt := NWS
| tt ff tt ff := WS
| tt ff ff tt := NS
| tt ff ff ff := S
| ff tt tt tt := NWE
| ff tt tt ff := WE
| ff tt ff tt := NE
| ff tt ff ff := E
| ff ff tt tt := NW
| ff ff tt ff := W
| ff ff ff tt := N
| ff ff ff ff := X
def translation (neigh : list cellT) : cellT :=
let north := list.nth neigh 0 in
let west := list.nth neigh 1 in
let east := list.nth neigh 2 in
let south := list.nth neigh 3 in
match north with
| none := X
| (some n) :=
match west with
| none := X
| (some w) :=
match east with
| none := X
| (some e) :=
match south with
| none := X
| (some s) :=
translation' (has_cardinal n CS)
(has_cardinal w CE)
(has_cardinal e CW)
(has_cardinal s CN)
end end end end
lemma translation_eq_translation' {neigh : list cellT}
(h : list.length neigh = 4) :
translation neigh =
let n := list.nth_le neigh 0 $ by simp [h]; exact dec_trivial in
let w := list.nth_le neigh 1 $ by simp [h]; exact dec_trivial in
let e := list.nth_le neigh 2 $ by simp [h]; exact dec_trivial in
let s := list.nth_le neigh 3 $ by simp [h]; exact dec_trivial in
translation' (has_cardinal n CS)
(has_cardinal w CE)
(has_cardinal e CW)
(has_cardinal s CN) :=
begin
cases neigh with x₁ xs₁, cases h,
cases xs₁ with x₂ xs₂, cases h,
cases xs₂ with x₃ xs₃, cases h,
cases xs₃ with x₄ xs₄, cases h,
cases xs₄ with x₅ xs₅, swap 2, cases h,
unfold translation, simp,
delta translation, simp
end
def mk_hpp (g : vec_grid₀ cellT) : hpp :=
⟨g, X, cell_automatons.neumann, (λ_ neigh, translation neigh), cell_automatons.ext_one⟩
def hpp_g :=
vec_grid₀.mk
⟨11, 11, dec_trivial,
⟨[X, X, X, X, X, X, X, X, X, X, X,
X, X, X, X, X, X, X, X, X, X, X,
X, X, X, X, X, X, X, X, X, X, X,
X, X, X, X, X, WE, X, X, X, S, X,
E, X, X, X, E, X, W, X, X, N, N,
X, X, X, X, X, N, X, X, X, X, X,
X, X, X, X, X, X, X, X, X, X, X,
X, X, X, X, X, X, X, X, X, X, X,
X, X, X, X, X, X, X, X, X, X, X,
X, X, X, X, X, X, X, X, X, X, X,
X, X, X, X, X, X, X, X, X, X, X], rfl⟩⟩
⟨0, 0⟩
def simple := mk_hpp hpp_g
end hpp
end hpp |
6ed48f087382997f0f5695fae861b3ee2956ae46 | 1b8f093752ba748c5ca0083afef2959aaa7dace5 | /src/category_theory/graphs/category.lean | 6b7c2442b521a4ee6352b217babb541633e8b808 | [] | no_license | khoek/lean-category-theory | 7ec4cda9cc64a5a4ffeb84712ac7d020dbbba386 | 63dcb598e9270a3e8b56d1769eb4f825a177cd95 | refs/heads/master | 1,585,251,725,759 | 1,539,344,445,000 | 1,539,344,445,000 | 145,281,070 | 0 | 0 | null | 1,534,662,376,000 | 1,534,662,376,000 | null | UTF-8 | Lean | false | false | 1,238 | lean | -- Copyright (c) 2017 Scott Morrison. All rights reserved.
-- Released under Apache 2.0 license as described in the file LICENSE.
-- Authors: Stephen Morgan and Scott Morrison
import category_theory.category
import category_theory.graphs
namespace category_theory
open category_theory.graphs
universe u
variable {C : Type u}
instance category.graph [𝒞 : small_category C] : graph C := {
edges := 𝒞.hom
}
variable [small_category C]
inductive morphism_path : C → C → Type (u+1)
| nil : Π (h : C), morphism_path h h
| cons : Π {h s t : C} (e : h ⟶ s) (l : morphism_path s t), morphism_path h t
notation a :: b := morphism_path.cons a b
notation `c[` l:(foldr `, ` (h t, morphism_path.cons h t) morphism_path.nil _ `]`) := l
def concatenate_paths : Π {x y z : C}, morphism_path x y → morphism_path y z → morphism_path x z
| ._ ._ _ (morphism_path.nil _) q := q
| ._ ._ _ (@morphism_path.cons ._ _ _ _ _ e p') q := morphism_path.cons e (concatenate_paths p' q)
def category.compose_path : Π {X Y : C}, morphism_path X Y → (X ⟶ Y)
| X ._ (morphism_path.nil ._) := 𝟙 X
| _ _ (@morphism_path.cons ._ ._ _ _ ._ e p) := e ≫ (category.compose_path p)
end category_theory |
32e9b87ab90341a3aad1617784c8f63817e7ea7d | d1a52c3f208fa42c41df8278c3d280f075eb020c | /stage0/src/Init.lean | 54741d4ed829490deac0caf24392ec2b2fa6aea7 | [
"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 | 458 | lean | /-
Copyright (c) 2014 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
prelude
import Init.Prelude
import Init.Notation
import Init.Core
import Init.Control
import Init.Data.Basic
import Init.WF
import Init.Data
import Init.System
import Init.Util
import Init.Fix
import Init.Meta
import Init.NotationExtra
import Init.SimpLemmas
import Init.Hints
import Init.Conv
|
ec1f20987453760964a1ebe832b9b3a95e7258bb | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/data/nat/choose/sum_auto.lean | 7eab27e2517a488fdcade6c0baeea1d8f6f4b3cd | [] | 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 | 2,880 | lean | /-
Copyright (c) 2018 Chris Hughes. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Chris Hughes, Patrick Stevens
-/
import Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
import Mathlib.data.nat.choose.basic
import Mathlib.tactic.linarith.default
import Mathlib.tactic.omega.default
import Mathlib.algebra.big_operators.ring
import Mathlib.algebra.big_operators.intervals
import Mathlib.algebra.big_operators.order
import Mathlib.PostPort
universes u_1 u_2
namespace Mathlib
/-!
# Sums of binomial coefficients
This file includes variants of the binomial theorem and other results on sums of binomial
coefficients. Theorems whose proofs depend on such sums may also go in this file for import
reasons.
-/
/-- A version of the binomial theorem for noncommutative semirings. -/
theorem commute.add_pow {α : Type u_1} [semiring α] {x : α} {y : α} (h : commute x y) (n : ℕ) :
(x + y) ^ n =
finset.sum (finset.range (n + 1)) fun (m : ℕ) => x ^ m * y ^ (n - m) * ↑(nat.choose n m) :=
sorry
/-- The binomial theorem -/
theorem add_pow {α : Type u_1} [comm_semiring α] (x : α) (y : α) (n : ℕ) :
(x + y) ^ n =
finset.sum (finset.range (n + 1)) fun (m : ℕ) => x ^ m * y ^ (n - m) * ↑(nat.choose n m) :=
commute.add_pow (commute.all x y) n
namespace nat
/-- The sum of entries in a row of Pascal's triangle -/
theorem sum_range_choose (n : ℕ) :
(finset.sum (finset.range (n + 1)) fun (m : ℕ) => choose n m) = bit0 1 ^ n :=
sorry
theorem sum_range_choose_halfway (m : ℕ) :
(finset.sum (finset.range (m + 1)) fun (i : ℕ) => choose (bit0 1 * m + 1) i) =
bit0 (bit0 1) ^ m :=
sorry
theorem choose_middle_le_pow (n : ℕ) : choose (bit0 1 * n + 1) n ≤ bit0 (bit0 1) ^ n := sorry
end nat
theorem int.alternating_sum_range_choose {n : ℕ} :
(finset.sum (finset.range (n + 1)) fun (m : ℕ) => (-1) ^ m * ↑(nat.choose n m)) =
ite (n = 0) 1 0 :=
sorry
theorem int.alternating_sum_range_choose_of_ne {n : ℕ} (h0 : n ≠ 0) :
(finset.sum (finset.range (n + 1)) fun (m : ℕ) => (-1) ^ m * ↑(nat.choose n m)) = 0 :=
sorry
namespace finset
theorem sum_powerset_apply_card {α : Type u_1} {β : Type u_2} [add_comm_monoid α] (f : ℕ → α)
{x : finset β} :
(finset.sum (powerset x) fun (m : finset β) => f (card m)) =
finset.sum (range (card x + 1)) fun (m : ℕ) => nat.choose (card x) m •ℕ f m :=
sorry
theorem sum_powerset_neg_one_pow_card {α : Type u_1} [DecidableEq α] {x : finset α} :
(finset.sum (powerset x) fun (m : finset α) => (-1) ^ card m) = ite (x = ∅) 1 0 :=
sorry
theorem sum_powerset_neg_one_pow_card_of_nonempty {α : Type u_1} {x : finset α}
(h0 : finset.nonempty x) : (finset.sum (powerset x) fun (m : finset α) => (-1) ^ card m) = 0 :=
sorry
end Mathlib |
7c4c56784a17d0d80a9683af0f654a2b8fb9e959 | 9dc8cecdf3c4634764a18254e94d43da07142918 | /src/probability/density.lean | 7dcbe2022356095f3c3136a661e4fd5ca122d1df | [
"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 | 19,163 | lean | /-
Copyright (c) 2021 Kexing Ying. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kexing Ying
-/
import measure_theory.decomposition.radon_nikodym
import measure_theory.measure.lebesgue
/-!
# Probability density function
This file defines the probability density function of random variables, by which we mean
measurable functions taking values in a Borel space. In particular, a measurable function `f`
is said to the probability density function of a random variable `X` if for all measurable
sets `S`, `ℙ(X ∈ S) = ∫ x in S, f x dx`. Probability density functions are one way of describing
the distribution of a random variable, and are useful for calculating probabilities and
finding moments (although the latter is better achieved with moment generating functions).
This file also defines the continuous uniform distribution and proves some properties about
random variables with this distribution.
## Main definitions
* `measure_theory.has_pdf` : A random variable `X : Ω → E` is said to `has_pdf` with
respect to the measure `ℙ` on `Ω` and `μ` on `E` if there exists a measurable function `f`
such that the push-forward measure of `ℙ` along `X` equals `μ.with_density f`.
* `measure_theory.pdf` : If `X` is a random variable that `has_pdf X ℙ μ`, then `pdf X`
is the measurable function `f` such that the push-forward measure of `ℙ` along `X` equals
`μ.with_density f`.
* `measure_theory.pdf.uniform` : A random variable `X` is said to follow the uniform
distribution if it has a constant probability density function with a compact, non-null support.
## Main results
* `measure_theory.pdf.integral_fun_mul_eq_integral` : Law of the unconscious statistician,
i.e. if a random variable `X : Ω → E` has pdf `f`, then `𝔼(g(X)) = ∫ x, g x * f x dx` for
all measurable `g : E → ℝ`.
* `measure_theory.pdf.integral_mul_eq_integral` : A real-valued random variable `X` with
pdf `f` has expectation `∫ x, x * f x dx`.
* `measure_theory.pdf.uniform.integral_eq` : If `X` follows the uniform distribution with
its pdf having support `s`, then `X` has expectation `(λ s)⁻¹ * ∫ x in s, x dx` where `λ`
is the Lebesgue measure.
## TODOs
Ultimately, we would also like to define characteristic functions to describe distributions as
it exists for all random variables. However, to define this, we will need Fourier transforms
which we currently do not have.
-/
noncomputable theory
open_locale classical measure_theory nnreal ennreal
namespace measure_theory
open topological_space measure_theory.measure
variables {Ω E : Type*} [measurable_space E]
/-- A random variable `X : Ω → E` is said to `has_pdf` with respect to the measure `ℙ` on `Ω` and
`μ` on `E` if there exists a measurable function `f` such that the push-forward measure of `ℙ`
along `X` equals `μ.with_density f`. -/
class has_pdf {m : measurable_space Ω} (X : Ω → E)
(ℙ : measure Ω) (μ : measure E . volume_tac) : Prop :=
(pdf' : measurable X ∧ ∃ (f : E → ℝ≥0∞), measurable f ∧ map X ℙ = μ.with_density f)
@[measurability]
lemma has_pdf.measurable {m : measurable_space Ω}
(X : Ω → E) (ℙ : measure Ω) (μ : measure E . volume_tac) [hX : has_pdf X ℙ μ] :
measurable X :=
hX.pdf'.1
/-- If `X` is a random variable that `has_pdf X ℙ μ`, then `pdf X` is the measurable function `f`
such that the push-forward measure of `ℙ` along `X` equals `μ.with_density f`. -/
def pdf {m : measurable_space Ω} (X : Ω → E) (ℙ : measure Ω) (μ : measure E . volume_tac) :=
if hX : has_pdf X ℙ μ then classical.some hX.pdf'.2 else 0
lemma pdf_undef {m : measurable_space Ω} {ℙ : measure Ω} {μ : measure E} {X : Ω → E}
(h : ¬ has_pdf X ℙ μ) :
pdf X ℙ μ = 0 :=
by simp only [pdf, dif_neg h]
lemma has_pdf_of_pdf_ne_zero {m : measurable_space Ω} {ℙ : measure Ω} {μ : measure E} {X : Ω → E}
(h : pdf X ℙ μ ≠ 0) : has_pdf X ℙ μ :=
begin
by_contra hpdf,
rw [pdf, dif_neg hpdf] at h,
exact hpdf (false.rec (has_pdf X ℙ μ) (h rfl))
end
lemma pdf_eq_zero_of_not_measurable {m : measurable_space Ω}
{ℙ : measure Ω} {μ : measure E} {X : Ω → E} (hX : ¬ measurable X) :
pdf X ℙ μ = 0 :=
pdf_undef (λ hpdf, hX hpdf.pdf'.1)
lemma measurable_of_pdf_ne_zero {m : measurable_space Ω}
{ℙ : measure Ω} {μ : measure E} (X : Ω → E) (h : pdf X ℙ μ ≠ 0) :
measurable X :=
by { by_contra hX, exact h (pdf_eq_zero_of_not_measurable hX) }
@[measurability]
lemma measurable_pdf {m : measurable_space Ω}
(X : Ω → E) (ℙ : measure Ω) (μ : measure E . volume_tac) :
measurable (pdf X ℙ μ) :=
begin
by_cases hX : has_pdf X ℙ μ,
{ rw [pdf, dif_pos hX],
exact (classical.some_spec hX.pdf'.2).1 },
{ rw [pdf, dif_neg hX],
exact measurable_zero }
end
lemma map_eq_with_density_pdf {m : measurable_space Ω}
(X : Ω → E) (ℙ : measure Ω) (μ : measure E . volume_tac) [hX : has_pdf X ℙ μ] :
measure.map X ℙ = μ.with_density (pdf X ℙ μ) :=
begin
rw [pdf, dif_pos hX],
exact (classical.some_spec hX.pdf'.2).2
end
lemma map_eq_set_lintegral_pdf {m : measurable_space Ω}
(X : Ω → E) (ℙ : measure Ω) (μ : measure E . volume_tac) [hX : has_pdf X ℙ μ]
{s : set E} (hs : measurable_set s) :
measure.map X ℙ s = ∫⁻ x in s, pdf X ℙ μ x ∂μ :=
by rw [← with_density_apply _ hs, map_eq_with_density_pdf X ℙ μ]
namespace pdf
variables {m : measurable_space Ω} {ℙ : measure Ω} {μ : measure E}
lemma lintegral_eq_measure_univ {X : Ω → E} [has_pdf X ℙ μ] :
∫⁻ x, pdf X ℙ μ x ∂μ = ℙ set.univ :=
begin
rw [← set_lintegral_univ, ← map_eq_set_lintegral_pdf X ℙ μ measurable_set.univ,
measure.map_apply (has_pdf.measurable X ℙ μ) measurable_set.univ, set.preimage_univ],
end
lemma ae_lt_top [is_finite_measure ℙ] {μ : measure E} {X : Ω → E} :
∀ᵐ x ∂μ, pdf X ℙ μ x < ∞ :=
begin
by_cases hpdf : has_pdf X ℙ μ,
{ haveI := hpdf,
refine ae_lt_top (measurable_pdf X ℙ μ) _,
rw lintegral_eq_measure_univ,
exact (measure_lt_top _ _).ne },
{ rw [pdf, dif_neg hpdf],
exact filter.eventually_of_forall (λ x, with_top.zero_lt_top) }
end
lemma of_real_to_real_ae_eq [is_finite_measure ℙ] {X : Ω → E} :
(λ x, ennreal.of_real (pdf X ℙ μ x).to_real) =ᵐ[μ] pdf X ℙ μ :=
of_real_to_real_ae_eq ae_lt_top
lemma integrable_iff_integrable_mul_pdf [is_finite_measure ℙ] {X : Ω → E} [has_pdf X ℙ μ]
{f : E → ℝ} (hf : measurable f) :
integrable (λ x, f (X x)) ℙ ↔ integrable (λ x, f x * (pdf X ℙ μ x).to_real) μ :=
begin
rw [← integrable_map_measure hf.ae_strongly_measurable (has_pdf.measurable X ℙ μ).ae_measurable,
map_eq_with_density_pdf X ℙ μ,
integrable_with_density_iff (measurable_pdf _ _ _) ae_lt_top],
apply_instance
end
/-- **The Law of the Unconscious Statistician**: Given a random variable `X` and a measurable
function `f`, `f ∘ X` is a random variable with expectation `∫ x, f x * pdf X ∂μ`
where `μ` is a measure on the codomain of `X`. -/
lemma integral_fun_mul_eq_integral [is_finite_measure ℙ]
{X : Ω → E} [has_pdf X ℙ μ] {f : E → ℝ} (hf : measurable f) :
∫ x, f x * (pdf X ℙ μ x).to_real ∂μ = ∫ x, f (X x) ∂ℙ :=
begin
by_cases hpdf : integrable (λ x, f x * (pdf X ℙ μ x).to_real) μ,
{ rw [← integral_map (has_pdf.measurable X ℙ μ).ae_measurable hf.ae_strongly_measurable,
map_eq_with_density_pdf X ℙ μ,
integral_eq_lintegral_pos_part_sub_lintegral_neg_part hpdf,
integral_eq_lintegral_pos_part_sub_lintegral_neg_part,
lintegral_with_density_eq_lintegral_mul _ (measurable_pdf X ℙ μ) hf.neg.ennreal_of_real,
lintegral_with_density_eq_lintegral_mul _ (measurable_pdf X ℙ μ) hf.ennreal_of_real],
{ congr' 2,
{ have : ∀ x, ennreal.of_real (f x * (pdf X ℙ μ x).to_real) =
ennreal.of_real (pdf X ℙ μ x).to_real * ennreal.of_real (f x),
{ intro x,
rw [mul_comm, ennreal.of_real_mul ennreal.to_real_nonneg] },
simp_rw [this],
exact lintegral_congr_ae (filter.eventually_eq.mul of_real_to_real_ae_eq (ae_eq_refl _)) },
{ have : ∀ x, ennreal.of_real (- (f x * (pdf X ℙ μ x).to_real)) =
ennreal.of_real (pdf X ℙ μ x).to_real * ennreal.of_real (-f x),
{ intro x,
rw [neg_mul_eq_neg_mul, mul_comm, ennreal.of_real_mul ennreal.to_real_nonneg] },
simp_rw [this],
exact lintegral_congr_ae (filter.eventually_eq.mul of_real_to_real_ae_eq
(ae_eq_refl _)) } },
{ refine ⟨hf.ae_strongly_measurable, _⟩,
rw [has_finite_integral, lintegral_with_density_eq_lintegral_mul _
(measurable_pdf _ _ _) hf.nnnorm.coe_nnreal_ennreal],
have : (λ x, (pdf X ℙ μ * λ x, ↑∥f x∥₊) x) =ᵐ[μ] (λ x, ∥f x * (pdf X ℙ μ x).to_real∥₊),
{ simp_rw [← smul_eq_mul, nnnorm_smul, ennreal.coe_mul],
rw [smul_eq_mul, mul_comm],
refine filter.eventually_eq.mul (ae_eq_refl _) (ae_eq_trans of_real_to_real_ae_eq.symm _),
convert ae_eq_refl _,
ext1 x,
exact real.ennnorm_eq_of_real ennreal.to_real_nonneg },
rw lintegral_congr_ae this,
exact hpdf.2 } },
{ rw [integral_undef hpdf, integral_undef],
rwa ← integrable_iff_integrable_mul_pdf hf at hpdf,
all_goals { apply_instance } }
end
lemma map_absolutely_continuous {X : Ω → E} [has_pdf X ℙ μ] : map X ℙ ≪ μ :=
by { rw map_eq_with_density_pdf X ℙ μ, exact with_density_absolutely_continuous _ _, }
/-- A random variable that `has_pdf` is quasi-measure preserving. -/
lemma to_quasi_measure_preserving {X : Ω → E} [has_pdf X ℙ μ] : quasi_measure_preserving X ℙ μ :=
{ measurable := has_pdf.measurable X ℙ μ,
absolutely_continuous := map_absolutely_continuous, }
lemma have_lebesgue_decomposition_of_has_pdf {X : Ω → E} [hX' : has_pdf X ℙ μ] :
(map X ℙ).have_lebesgue_decomposition μ :=
⟨⟨⟨0, pdf X ℙ μ⟩,
by simp only [zero_add, measurable_pdf X ℙ μ, true_and, mutually_singular.zero_left,
map_eq_with_density_pdf X ℙ μ] ⟩⟩
lemma has_pdf_iff {X : Ω → E} :
has_pdf X ℙ μ ↔ measurable X ∧ (map X ℙ).have_lebesgue_decomposition μ ∧ map X ℙ ≪ μ :=
begin
split,
{ intro hX',
exactI ⟨hX'.pdf'.1, have_lebesgue_decomposition_of_has_pdf, map_absolutely_continuous⟩ },
{ rintros ⟨hX, h_decomp, h⟩,
haveI := h_decomp,
refine ⟨⟨hX, (measure.map X ℙ).rn_deriv μ, measurable_rn_deriv _ _, _⟩⟩,
rwa with_density_rn_deriv_eq }
end
lemma has_pdf_iff_of_measurable {X : Ω → E} (hX : measurable X) :
has_pdf X ℙ μ ↔ (map X ℙ).have_lebesgue_decomposition μ ∧ map X ℙ ≪ μ :=
by { rw has_pdf_iff, simp only [hX, true_and], }
section
variables {F : Type*} [measurable_space F] {ν : measure F}
/-- A random variable that `has_pdf` transformed under a `quasi_measure_preserving`
map also `has_pdf` if `(map g (map X ℙ)).have_lebesgue_decomposition μ`.
`quasi_measure_preserving_has_pdf'` is more useful in the case we are working with a
probability measure and a real-valued random variable. -/
lemma quasi_measure_preserving_has_pdf {X : Ω → E} [has_pdf X ℙ μ]
{g : E → F} (hg : quasi_measure_preserving g μ ν)
(hmap : (map g (map X ℙ)).have_lebesgue_decomposition ν) :
has_pdf (g ∘ X) ℙ ν :=
begin
rw [has_pdf_iff, ← map_map hg.measurable (has_pdf.measurable X ℙ μ)],
refine ⟨hg.measurable.comp (has_pdf.measurable X ℙ μ), hmap, _⟩,
rw [map_eq_with_density_pdf X ℙ μ],
refine absolutely_continuous.mk (λ s hsm hs, _),
rw [map_apply hg.measurable hsm, with_density_apply _ (hg.measurable hsm)],
have := hg.absolutely_continuous hs,
rw map_apply hg.measurable hsm at this,
exact set_lintegral_measure_zero _ _ this,
end
lemma quasi_measure_preserving_has_pdf' [is_finite_measure ℙ] [sigma_finite ν]
{X : Ω → E} [has_pdf X ℙ μ] {g : E → F} (hg : quasi_measure_preserving g μ ν) :
has_pdf (g ∘ X) ℙ ν :=
quasi_measure_preserving_has_pdf hg infer_instance
end
section real
variables [is_finite_measure ℙ] {X : Ω → ℝ}
/-- A real-valued random variable `X` `has_pdf X ℙ λ` (where `λ` is the Lebesgue measure) if and
only if the push-forward measure of `ℙ` along `X` is absolutely continuous with respect to `λ`. -/
lemma real.has_pdf_iff_of_measurable (hX : measurable X) : has_pdf X ℙ ↔ map X ℙ ≪ volume :=
begin
rw [has_pdf_iff_of_measurable hX, and_iff_right_iff_imp],
exact λ h, infer_instance,
end
lemma real.has_pdf_iff : has_pdf X ℙ ↔ measurable X ∧ map X ℙ ≪ volume :=
begin
by_cases hX : measurable X,
{ rw [real.has_pdf_iff_of_measurable hX, iff_and_self],
exact λ h, hX,
apply_instance },
{ exact ⟨λ h, false.elim (hX h.pdf'.1), λ h, false.elim (hX h.1)⟩, }
end
/-- If `X` is a real-valued random variable that has pdf `f`, then the expectation of `X` equals
`∫ x, x * f x ∂λ` where `λ` is the Lebesgue measure. -/
lemma integral_mul_eq_integral [has_pdf X ℙ] :
∫ x, x * (pdf X ℙ volume x).to_real = ∫ x, X x ∂ℙ :=
integral_fun_mul_eq_integral measurable_id
lemma has_finite_integral_mul {f : ℝ → ℝ} {g : ℝ → ℝ≥0∞}
(hg : pdf X ℙ =ᵐ[volume] g) (hgi : ∫⁻ x, ∥f x∥₊ * g x ≠ ∞) :
has_finite_integral (λ x, f x * (pdf X ℙ volume x).to_real) :=
begin
rw has_finite_integral,
have : (λ x, ↑∥f x∥₊ * g x) =ᵐ[volume] (λ x, ∥f x * (pdf X ℙ volume x).to_real∥₊),
{ refine ae_eq_trans (filter.eventually_eq.mul (ae_eq_refl (λ x, ∥f x∥₊))
(ae_eq_trans hg.symm of_real_to_real_ae_eq.symm)) _,
simp_rw [← smul_eq_mul, nnnorm_smul, ennreal.coe_mul, smul_eq_mul],
refine filter.eventually_eq.mul (ae_eq_refl _) _,
convert ae_eq_refl _,
ext1 x,
exact real.ennnorm_eq_of_real ennreal.to_real_nonneg },
rwa [lt_top_iff_ne_top, ← lintegral_congr_ae this],
end
end real
section
/-! **Uniform Distribution** -/
/-- A random variable `X` has uniform distribution if it has a probability density function `f`
with support `s` such that `f = (μ s)⁻¹ 1ₛ` a.e. where `1ₛ` is the indicator function for `s`. -/
def is_uniform {m : measurable_space Ω} (X : Ω → E) (support : set E)
(ℙ : measure Ω) (μ : measure E . volume_tac) :=
pdf X ℙ μ =ᵐ[μ] support.indicator ((μ support)⁻¹ • 1)
namespace is_uniform
lemma has_pdf {m : measurable_space Ω} {X : Ω → E} {ℙ : measure Ω} {μ : measure E}
{s : set E} (hns : μ s ≠ 0) (hnt : μ s ≠ ∞) (hu : is_uniform X s ℙ μ) :
has_pdf X ℙ μ :=
has_pdf_of_pdf_ne_zero
begin
intro hpdf,
rw [is_uniform, hpdf] at hu,
suffices : μ (s ∩ function.support ((μ s)⁻¹ • 1)) = 0,
{ have heq : function.support ((μ s)⁻¹ • (1 : E → ℝ≥0∞)) = set.univ,
{ ext x,
rw [function.mem_support],
simp [hnt] },
rw [heq, set.inter_univ] at this,
exact hns this },
exact set.indicator_ae_eq_zero hu.symm,
end
lemma pdf_to_real_ae_eq {m : measurable_space Ω}
{X : Ω → E} {ℙ : measure Ω} {μ : measure E} {s : set E} (hX : is_uniform X s ℙ μ) :
(λ x, (pdf X ℙ μ x).to_real) =ᵐ[μ]
(λ x, (s.indicator ((μ s)⁻¹ • (1 : E → ℝ≥0∞)) x).to_real) :=
filter.eventually_eq.fun_comp hX ennreal.to_real
lemma measure_preimage {m : measurable_space Ω} {X : Ω → E} {ℙ : measure Ω} {μ : measure E}
{s : set E} (hns : μ s ≠ 0) (hnt : μ s ≠ ∞) (hms : measurable_set s)
(hu : is_uniform X s ℙ μ)
{A : set E} (hA : measurable_set A) :
ℙ (X ⁻¹' A) = μ (s ∩ A) / μ s :=
begin
haveI := hu.has_pdf hns hnt,
rw [←measure.map_apply (has_pdf.measurable X ℙ μ) hA, map_eq_set_lintegral_pdf X ℙ μ hA,
lintegral_congr_ae hu.restrict],
simp only [hms, hA, lintegral_indicator, pi.smul_apply, pi.one_apply, algebra.id.smul_eq_mul,
mul_one, lintegral_const, restrict_apply', set.univ_inter],
rw ennreal.div_eq_inv_mul,
end
lemma is_probability_measure {m : measurable_space Ω} {X : Ω → E} {ℙ : measure Ω} {μ : measure E}
{s : set E} (hns : μ s ≠ 0) (hnt : μ s ≠ ∞) (hms : measurable_set s)
(hu : is_uniform X s ℙ μ) :
is_probability_measure ℙ :=
⟨begin
have : X ⁻¹' set.univ = set.univ, { simp only [set.preimage_univ] },
rw [←this, hu.measure_preimage hns hnt hms measurable_set.univ, set.inter_univ,
ennreal.div_self hns hnt],
end⟩
variables {X : Ω → ℝ} {s : set ℝ} (hms : measurable_set s) (hns : volume s ≠ 0)
include hms hns
lemma mul_pdf_integrable [is_finite_measure ℙ] (hcs : is_compact s) (huX : is_uniform X s ℙ) :
integrable (λ x : ℝ, x * (pdf X ℙ volume x).to_real) :=
begin
by_cases hsupp : volume s = ∞,
{ have : pdf X ℙ =ᵐ[volume] 0,
{ refine ae_eq_trans huX _,
simp [hsupp] },
refine integrable.congr (integrable_zero _ _ _) _,
rw [(by simp : (λ x, 0 : ℝ → ℝ) = (λ x, x * (0 : ℝ≥0∞).to_real))],
refine filter.eventually_eq.mul (ae_eq_refl _)
(filter.eventually_eq.fun_comp this.symm ennreal.to_real) },
refine ⟨ae_strongly_measurable_id.mul
(measurable_pdf X ℙ).ae_measurable.ennreal_to_real.ae_strongly_measurable, _⟩,
refine has_finite_integral_mul huX _,
set ind := (volume s)⁻¹ • (1 : ℝ → ℝ≥0∞) with hind,
have : ∀ x, ↑∥x∥₊ * s.indicator ind x = s.indicator (λ x, ∥x∥₊ * ind x) x :=
λ x, (s.indicator_mul_right (λ x, ↑∥x∥₊) ind).symm,
simp only [this, lintegral_indicator _ hms, hind, mul_one,
algebra.id.smul_eq_mul, pi.one_apply, pi.smul_apply],
rw lintegral_mul_const _ measurable_nnnorm.coe_nnreal_ennreal,
{ refine (ennreal.mul_lt_top (set_lintegral_lt_top_of_is_compact
hsupp hcs continuous_nnnorm).ne (ennreal.inv_lt_top.2 (pos_iff_ne_zero.mpr hns)).ne).ne },
{ apply_instance }
end
/-- A real uniform random variable `X` with support `s` has expectation
`(λ s)⁻¹ * ∫ x in s, x ∂λ` where `λ` is the Lebesgue measure. -/
lemma integral_eq (hnt : volume s ≠ ∞) (huX : is_uniform X s ℙ) :
∫ x, X x ∂ℙ = (volume s)⁻¹.to_real * ∫ x in s, x :=
begin
haveI := has_pdf hns hnt huX,
haveI := huX.is_probability_measure hns hnt hms,
rw ← integral_mul_eq_integral,
rw integral_congr_ae (filter.eventually_eq.mul (ae_eq_refl _) (pdf_to_real_ae_eq huX)),
have : ∀ x, x * (s.indicator ((volume s)⁻¹ • (1 : ℝ → ℝ≥0∞)) x).to_real =
x * (s.indicator ((volume s)⁻¹.to_real • (1 : ℝ → ℝ)) x),
{ refine λ x, congr_arg ((*) x) _,
by_cases hx : x ∈ s,
{ simp [set.indicator_of_mem hx] },
{ simp [set.indicator_of_not_mem hx] }},
simp_rw [this, ← s.indicator_mul_right (λ x, x), integral_indicator hms],
change ∫ x in s, x * ((volume s)⁻¹.to_real • 1) ∂(volume) = _,
rw [integral_mul_right, mul_comm, algebra.id.smul_eq_mul, mul_one],
end .
end is_uniform
end
end pdf
end measure_theory
|
b88e6053a603e6abe41778347f6659be73427954 | 9dd3f3912f7321eb58ee9aa8f21778ad6221f87c | /tests/lean/run/968.lean | 90572184ff4f254690c50eda6b571682e25598cb | [
"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 | 212 | lean | variables (A : Type) [inhabited A]
definition f (a : A) : A := a
check @f nat nat.inhabited
structure foo :=
(a : A)
check @foo nat nat.inhabited
inductive bla
| mk : A → bla
check @bla nat nat.inhabited
|
1798cbbd8d6f6278a998e5d099c0f06b96ced681 | 9a0b1b3a653ea926b03d1495fef64da1d14b3174 | /tidy/rewrite_search/bundles/arithmetic.lean | e39ef0d55f0d9eee8f8d89d436ce4ed438a3d781 | [
"Apache-2.0"
] | permissive | khoek/mathlib-tidy | 8623b27b4e04e7d598164e7eaf248610d58f768b | 866afa6ab597c47f1b72e8fe2b82b97fff5b980f | refs/heads/master | 1,585,598,975,772 | 1,538,659,544,000 | 1,538,659,544,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 329 | lean | import tidy.rewrite_search.discovery.bundle
namespace tidy.rewrite_search.discovery
@[bundle] meta def arithmetic : bundle := {}
attribute [search arithmetic] add_comm add_assoc
attribute [search arithmetic] mul_comm mul_assoc mul_one
attribute [search arithmetic] left_distrib right_distrib
end tidy.rewrite_search.discovery |
ae18fe6170d1d9cd4774f7ddc07cdfaf89dcbd79 | 63abd62053d479eae5abf4951554e1064a4c45b4 | /archive/sensitivity.lean | 04390ac4239de0d427715ee5110959804cfc6394 | [
"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 | 15,513 | lean | /-
Copyright (c) 2019 Reid Barton, Johan Commelin, Jesse Han, Chris Hughes, Robert Y. Lewis, and
Patrick Massot. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Reid Barton, Johan Commelin, Jesse Han, Chris Hughes, Robert Y. Lewis, and Patrick Massot
-/
import tactic.fin_cases
import tactic.apply_fun
import linear_algebra.finite_dimensional
import linear_algebra.dual
import analysis.normed_space.basic
/-!
# Huang's sensitivity theorem
A formalization of Hao Huang's sensitivity theorem: in the hypercube of
dimension n ≥ 1, if one colors more than half the vertices then at least one
vertex has at least √n colored neighbors.
A fun summer collaboration by
Reid Barton, Johan Commelin, Jesse Han, Chris Hughes, Robert Y. Lewis, and Patrick Massot,
based on Don Knuth's account of the story
(https://www.cs.stanford.edu/~knuth/papers/huang.pdf),
using the Lean theorem prover (https://leanprover.github.io/),
by Leonardo de Moura at Microsoft Research, and his collaborators
(https://leanprover.github.io/people/),
and using Lean's user maintained mathematics library
(https://github.com/leanprover-community/mathlib).
The project was developed at https://github.com/leanprover-community/lean-sensitivity and is now
archived at https://github.com/leanprover-community/mathlib/blob/master/archive/sensitivity.lean
-/
/-! The next two lines assert we do not want to give a constructive proof,
but rather use classical logic. -/
noncomputable theory
open_locale classical
/-! We also want to use the notation `∑` for sums. -/
open_locale big_operators
notation `|`x`|` := abs x
notation `√` := real.sqrt
open function bool linear_map fintype finite_dimensional dual_pair
/-!
### The hypercube
Notations:
- `ℕ` denotes natural numbers (including zero).
- `fin n` = {0, ⋯ , n - 1}.
- `bool` = {`tt`, `ff`}.
-/
/-- The hypercube in dimension `n`. -/
@[derive [inhabited, fintype]] def Q (n : ℕ) := fin n → bool
/-- The projection from `Q (n + 1)` to `Q n` forgetting the first value
(ie. the image of zero). -/
def π {n : ℕ} : Q (n + 1) → Q n := λ p, p ∘ fin.succ
namespace Q
/-! `n` will always denote a natural number. -/
variable (n : ℕ)
/-- `Q 0` has a unique element. -/
instance : unique (Q 0) :=
⟨⟨λ _, tt⟩, by { intro, ext x, fin_cases x }⟩
/-- `Q n` has 2^n elements. -/
lemma card : card (Q n) = 2^n :=
by simp [Q]
/-! Until the end of this namespace, `n` will be an implicit argument (still
a natural number). -/
variable {n}
lemma succ_n_eq (p q : Q (n+1)) : p = q ↔ (p 0 = q 0 ∧ π p = π q) :=
begin
split,
{ rintro rfl, exact ⟨rfl, rfl⟩, },
{ rintros ⟨h₀, h⟩,
ext x,
by_cases hx : x = 0,
{ rwa hx },
{ rw ← fin.succ_pred x hx,
convert congr_fun h (fin.pred x hx) } }
end
/-- The adjacency relation defining the graph structure on `Q n`:
`p.adjacent q` if there is an edge from `p` to `q` in `Q n`. -/
def adjacent {n : ℕ} (p : Q n) : set (Q n) := λ q, ∃! i, p i ≠ q i
/-- In `Q 0`, no two vertices are adjacent. -/
lemma not_adjacent_zero (p q : Q 0) : ¬ p.adjacent q :=
by rintros ⟨v, _⟩; apply fin_zero_elim v
/-- If `p` and `q` in `Q (n+1)` have different values at zero then they are adjacent
iff their projections to `Q n` are equal. -/
lemma adj_iff_proj_eq {p q : Q (n+1)} (h₀ : p 0 ≠ q 0) :
p.adjacent q ↔ π p = π q :=
begin
split,
{ rintros ⟨i, h_eq, h_uni⟩,
ext x, by_contradiction hx,
apply fin.succ_ne_zero x,
rw [h_uni _ hx, h_uni _ h₀] },
{ intro heq,
use [0, h₀],
intros y hy,
contrapose! hy,
rw ←fin.succ_pred _ hy,
apply congr_fun heq }
end
/-- If `p` and `q` in `Q (n+1)` have the same value at zero then they are adjacent
iff their projections to `Q n` are adjacent. -/
lemma adj_iff_proj_adj {p q : Q (n+1)} (h₀ : p 0 = q 0) :
p.adjacent q ↔ (π p).adjacent (π q) :=
begin
split,
{ rintros ⟨i, h_eq, h_uni⟩,
have h_i : i ≠ 0, from λ h_i, absurd h₀ (by rwa h_i at h_eq),
use [i.pred h_i,
show p (fin.succ (fin.pred i _)) ≠ q (fin.succ (fin.pred i _)),
by rwa fin.succ_pred],
intros y hy,
simp [eq.symm (h_uni _ hy)] },
{ rintros ⟨i, h_eq, h_uni⟩,
use [i.succ, h_eq],
intros y hy,
rw [←fin.pred_inj, fin.pred_succ],
{ apply h_uni,
change p (fin.pred _ _).succ ≠ q (fin.pred _ _).succ,
simp [hy] },
{ contrapose! hy,
rw [hy, h₀] },
{ apply fin.succ_ne_zero } }
end
@[symm] lemma adjacent.symm {p q : Q n} : p.adjacent q ↔ q.adjacent p :=
by simp only [adjacent, ne_comm]
end Q
/-! ### The vector space -/
/-- The free vector space on vertices of a hypercube, defined inductively. -/
def V : ℕ → Type
| 0 := ℝ
| (n+1) := V n × V n
namespace V
variables (n : ℕ)
/-! `V n` is a real vector space whose equality relation is computable. -/
instance : decidable_eq (V n) :=
by { induction n ; { dunfold V, resetI, apply_instance } }
instance : add_comm_group (V n) :=
by { induction n ; { dunfold V, resetI, apply_instance } }
instance : vector_space ℝ (V n) :=
by { induction n ; { dunfold V, resetI, apply_instance } }
end V
/-- The basis of `V` indexed by the hypercube, defined inductively. -/
noncomputable def e : Π {n}, Q n → V n
| 0 := λ _, (1:ℝ)
| (n+1) := λ x, cond (x 0) (e (π x), 0) (0, e (π x))
@[simp] lemma e_zero_apply (x : Q 0) : e x = (1 : ℝ) := rfl
/-- The dual basis to `e`, defined inductively. -/
noncomputable def ε : Π {n : ℕ} (p : Q n), V n →ₗ[ℝ] ℝ
| 0 _ := linear_map.id
| (n+1) p := cond (p 0) ((ε $ π p).comp $ linear_map.fst _ _ _)
((ε $ π p).comp $ linear_map.snd _ _ _)
variable {n : ℕ}
lemma duality (p q : Q n) : ε p (e q) = if p = q then 1 else 0 :=
begin
induction n with n IH,
{ rw (show p = q, from subsingleton.elim p q),
dsimp [ε, e],
simp },
{ dsimp [ε, e],
cases hp : p 0 ; cases hq : q 0,
all_goals {
repeat {rw cond_tt},
repeat {rw cond_ff},
simp only [linear_map.fst_apply, linear_map.snd_apply, linear_map.comp_apply, IH],
try { congr' 1, rw Q.succ_n_eq, finish },
try {
erw (ε _).map_zero,
have : p ≠ q, { intro h, rw p.succ_n_eq q at h, finish },
simp [this] } } }
end
/-- Any vector in `V n` annihilated by all `ε p`'s is zero. -/
lemma epsilon_total {v : V n} (h : ∀ p : Q n, (ε p) v = 0) : v = 0 :=
begin
induction n with n ih,
{ dsimp [ε] at h, exact h (λ _, tt) },
{ cases v with v₁ v₂,
ext ; change _ = (0 : V n) ; simp only ; apply ih ; intro p ;
[ let q : Q (n+1) := λ i, if h : i = 0 then tt else p (i.pred h),
let q : Q (n+1) := λ i, if h : i = 0 then ff else p (i.pred h)],
all_goals {
specialize h q,
rw [ε, show q 0 = tt, from rfl, cond_tt] at h <|>
rw [ε, show q 0 = ff, from rfl, cond_ff] at h,
rwa show p = π q, by { ext, simp [q, fin.succ_ne_zero, π] } } }
end
/-- `e` and `ε` are dual families of vectors. It implies that `e` is indeed a basis
and `ε` computes coefficients of decompositions of vectors on that basis. -/
def dual_pair_e_ε (n : ℕ) : dual_pair (@e n) (@ε n) :=
{ eval := duality,
total := @epsilon_total _ }
/-! We will now derive the dimension of `V`, first as a cardinal in `dim_V` and,
since this cardinal is finite, as a natural number in `findim_V` -/
lemma dim_V : vector_space.dim ℝ (V n) = 2^n :=
have vector_space.dim ℝ (V n) = (2^n : ℕ),
by { rw [dim_eq_card_basis (dual_pair_e_ε _).is_basis, Q.card]; apply_instance },
by assumption_mod_cast
instance : finite_dimensional ℝ (V n) :=
finite_dimensional.of_fintype_basis (dual_pair_e_ε _).is_basis
lemma findim_V : findim ℝ (V n) = 2^n :=
have _ := @dim_V n,
by rw ←findim_eq_dim at this; assumption_mod_cast
/-! ### The linear map -/
/-- The linear operator $f_n$ corresponding to Huang's matrix $A_n$,
defined inductively as a ℝ-linear map from `V n` to `V n`. -/
noncomputable def f : Π n, V n →ₗ[ℝ] V n
| 0 := 0
| (n+1) := linear_map.prod
(linear_map.coprod (f n) linear_map.id)
(linear_map.coprod linear_map.id (-f n))
/-! The preceding definition uses linear map constructions to automatically
get that `f` is linear, but its values are somewhat buried as a side-effect.
The next two lemmas unbury them. -/
@[simp] lemma f_zero : f 0 = 0 := rfl
lemma f_succ_apply (v : V (n+1)) :
f (n+1) v = (f n v.1 + v.2, v.1 - f n v.2) :=
begin
cases v,
rw f,
simp only [linear_map.id_apply, linear_map.prod_apply, prod.mk.inj_iff,
linear_map.neg_apply, sub_eq_add_neg, linear_map.coprod_apply],
exact ⟨rfl, rfl⟩
end
/-! In the next statement, the explicit conversion `(n : ℝ)` of `n` to a real number
is necessary since otherwise `n • v` refers to the multiplication defined
using only the addition of `V`. -/
lemma f_squared : ∀ v : V n, (f n) (f n v) = (n : ℝ) • v :=
begin
induction n with n IH; intro,
{ simpa only [nat.cast_zero, zero_smul] },
{ cases v, simp [f_succ_apply, IH, add_smul, add_assoc], abel }
end
/-! We now compute the matrix of `f` in the `e` basis (`p` is the line index,
`q` the column index). -/
lemma f_matrix :
∀ p q : Q n, |ε q (f n (e p))| = if q.adjacent p then 1 else 0 :=
begin
induction n with n IH,
{ intros p q,
dsimp [f],
simp [Q.not_adjacent_zero] },
{ intros p q,
have ite_nonneg : ite (π q = π p) (1 : ℝ) 0 ≥ 0,
{ split_ifs ; norm_num },
have f_map_zero := (show linear_map ℝ (V (n+0)) (V n), from f n).map_zero,
dsimp [e, ε, f], cases hp : p 0 ; cases hq : q 0,
all_goals
{ repeat {rw cond_tt}, repeat {rw cond_ff},
simp [f_map_zero, hp, hq, IH, duality, abs_of_nonneg ite_nonneg, Q.adj_iff_proj_eq,
Q.adj_iff_proj_adj] } }
end
/-- The linear operator $g_m$ corresponding to Knuth's matrix $B_m$. -/
noncomputable def g (m : ℕ) : V m →ₗ[ℝ] V (m+1) :=
linear_map.prod (f m + √(m+1) • linear_map.id) linear_map.id
/-! In the following lemmas, `m` will denote a natural number. -/
variables {m : ℕ}
/-! Again we unpack what are the values of `g`. -/
lemma g_apply : ∀ v, g m v = (f m v + √(m+1) • v, v) :=
by delta g; simp
lemma g_injective : injective (g m) :=
begin
rw g,
intros x₁ x₂ h,
simp only [linear_map.prod_apply, linear_map.id_apply, prod.mk.inj_iff] at h,
exact h.right
end
lemma f_image_g (w : V (m + 1)) (hv : ∃ v, g m v = w) :
f (m + 1) w = √(m + 1) • w :=
begin
rcases hv with ⟨v, rfl⟩,
have : √(m+1) * √(m+1) = m+1 :=
real.mul_self_sqrt (by exact_mod_cast zero_le _),
simp [this, f_succ_apply, g_apply, f_squared, smul_add, add_smul, smul_smul],
abel
end
/-!
### The main proof
In this section, in order to enforce that `n` is positive, we write it as
`m + 1` for some natural number `m`. -/
/-! `dim X` will denote the dimension of a subspace `X` as a cardinal. -/
notation `dim` X:70 := vector_space.dim ℝ ↥X
/-! `fdim X` will denote the (finite) dimension of a subspace `X` as a natural number. -/
notation `fdim` := findim ℝ
/-! `Span S` will denote the ℝ-subspace spanned by `S`. -/
notation `Span` := submodule.span ℝ
/-! `Card X` will denote the cardinal of a subset of a finite type, as a
natural number. -/
notation `Card` X:70 := X.to_finset.card
/-! In the following, `⊓` and `⊔` will denote intersection and sums of ℝ-subspaces,
equipped with their subspace structures. The notations come from the general
theory of lattices, with inf and sup (also known as meet and join). -/
/-- If a subset `H` of `Q (m+1)` has cardinal at least `2^m + 1` then the
subspace of `V (m+1)` spanned by the corresponding basis vectors non-trivially
intersects the range of `g m`. -/
lemma exists_eigenvalue (H : set (Q (m + 1))) (hH : Card H ≥ 2^m + 1) :
∃ y ∈ Span (e '' H) ⊓ (g m).range, y ≠ (0 : _) :=
begin
let W := Span (e '' H),
let img := (g m).range,
suffices : 0 < dim (W ⊓ img),
{ simp only [exists_prop],
exact_mod_cast exists_mem_ne_zero_of_dim_pos this },
have dim_le : dim (W ⊔ img) ≤ 2^(m + 1),
{ convert ← dim_submodule_le (W ⊔ img),
apply dim_V },
have dim_add : dim (W ⊔ img) + dim (W ⊓ img) = dim W + 2^m,
{ convert ← dim_sup_add_dim_inf_eq W img,
rw ← dim_eq_of_injective (g m) g_injective,
apply dim_V },
have dimW : dim W = card H,
{ have li : linear_independent ℝ (set.restrict e H) :=
linear_independent.comp (dual_pair_e_ε _).is_basis.1 _ subtype.val_injective,
have hdW := dim_span li,
rw set.range_restrict at hdW,
convert hdW,
rw [cardinal.mk_image_eq (dual_pair_e_ε _).is_basis.injective, cardinal.fintype_card] },
rw ← findim_eq_dim ℝ at ⊢ dim_le dim_add dimW,
rw [← findim_eq_dim ℝ, ← findim_eq_dim ℝ] at dim_add,
norm_cast at ⊢ dim_le dim_add dimW,
rw pow_succ' at dim_le,
rw set.to_finset_card at hH,
linarith
end
theorem huang_degree_theorem (H : set (Q (m + 1))) (hH : Card H ≥ 2^m + 1) :
∃ q, q ∈ H ∧ √(m + 1) ≤ Card (H ∩ q.adjacent) :=
begin
rcases exists_eigenvalue H hH with ⟨y, ⟨⟨y_mem_H, y_mem_g⟩, y_ne⟩⟩,
have coeffs_support : ((dual_pair_e_ε (m+1)).coeffs y).support ⊆ H.to_finset,
{ intros p p_in,
rw finsupp.mem_support_iff at p_in,
rw set.mem_to_finset,
exact (dual_pair_e_ε _).mem_of_mem_span y_mem_H p p_in },
obtain ⟨q, H_max⟩ : ∃ q : Q (m+1), ∀ q' : Q (m+1), |(ε q' : _) y| ≤ |ε q y|,
from fintype.exists_max _,
have H_q_pos : 0 < |ε q y|,
{ contrapose! y_ne,
exact epsilon_total (λ p, abs_nonpos_iff.mp (le_trans (H_max p) y_ne)) },
refine ⟨q, (dual_pair_e_ε _).mem_of_mem_span y_mem_H q (abs_pos.mp H_q_pos), _⟩,
let s := √(m+1),
suffices : s * |ε q y| ≤ ↑(_) * |ε q y|,
from (mul_le_mul_right H_q_pos).mp ‹_›,
let coeffs := (dual_pair_e_ε (m+1)).coeffs,
calc
s * (abs (ε q y))
= abs (ε q (s • y)) : by rw [map_smul, smul_eq_mul, abs_mul, abs_of_nonneg (real.sqrt_nonneg _)]
... = abs (ε q (f (m+1) y)) : by rw [← f_image_g y (by simpa using y_mem_g)]
... = abs (ε q (f (m+1) (lc _ (coeffs y)))) : by rw (dual_pair_e_ε _).decomposition y
... = abs ((coeffs y).sum (λ (i : Q (m + 1)) (a : ℝ), a • ((ε q) ∘ (f (m + 1)) ∘ λ (i : Q (m + 1)), e i) i)): by
{ erw [(f $ m+1).map_finsupp_total, (ε q).map_finsupp_total, finsupp.total_apply] ; apply_instance }
... ≤ ∑ p in (coeffs y).support, |(coeffs y p) * (ε q $ f (m+1) $ e p)| : norm_sum_le _ $ λ p, coeffs y p * _
... = ∑ p in (coeffs y).support, |coeffs y p| * ite (q.adjacent p) 1 0 : by simp only [abs_mul, f_matrix]
... = ∑ p in (coeffs y).support.filter (Q.adjacent q), |coeffs y p| : by simp [finset.sum_filter]
... ≤ ∑ p in (coeffs y).support.filter (Q.adjacent q), |coeffs y q| : finset.sum_le_sum (λ p _, H_max p)
... = (finset.card ((coeffs y).support.filter (Q.adjacent q)): ℝ) * |coeffs y q| : by rw [finset.sum_const, nsmul_eq_mul]
... = (finset.card ((coeffs y).support ∩ (Q.adjacent q).to_finset): ℝ) * |coeffs y q| : by { congr' with x, simp, refl }
... ≤ (finset.card ((H ∩ Q.adjacent q).to_finset )) * |ε q y| :
(mul_le_mul_right H_q_pos).mpr (by {
norm_cast,
exact finset.card_le_of_subset (by rw set.to_finset_inter; convert finset.inter_subset_inter_right coeffs_support) })
end
|
3a618661354203f96aa52f7ab35ee1b1fc7790b5 | 947b78d97130d56365ae2ec264df196ce769371a | /src/Lean/Elab/Quotation.lean | 9045152218d0062dc1064675a39d38f5eaf64e9e | [
"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 | 20,832 | lean | /-
Copyright (c) 2019 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Sebastian Ullrich
Elaboration of syntax quotations as terms and patterns (in `match_syntax`). See also `./Hygiene.lean` for the basic
hygiene workings and data types.
-/
import Lean.Syntax
import Lean.Elab.ResolveName
import Lean.Elab.Term
/- TODO
Quotations are currently integrated hackily into the old frontend. This implies the following restrictions:
* quotations have to fit in a single line, because that's how the old scanner works :)
* `open` commands are not respected (but `export`, `namespace` are)
* antiquotation terms have to be trivial (locals, consts (w/ projections), and apps, basically)
After removing the old frontend, quotations in this and other files should be cleaned up.
-/
namespace Lean
namespace Elab
namespace Term
namespace Quotation
open Lean.Syntax (isQuot isAntiquot)
open Meta
-- Antiquotations can be escaped as in `$$x`, which is useful for nesting macros.
def isEscapedAntiquot (stx : Syntax) : Bool :=
!(stx.getArg 1).getArgs.isEmpty
def unescapeAntiquot (stx : Syntax) : Syntax :=
if isAntiquot stx then
stx.setArg 1 $ mkNullNode (stx.getArg 1).getArgs.pop
else stx
def getAntiquotTerm (stx : Syntax) : Syntax :=
let e := stx.getArg 2;
if e.isIdent then e
else
-- `e` is from `"(" >> termParser >> ")"`
e.getArg 1
def antiquotKind? : Syntax → Option SyntaxNodeKind
| Syntax.node (Name.str k "antiquot" _) args =>
if (args.get! 3).isOfKind `antiquotName then some k
else
-- we treat all antiquotations where the kind was left implicit (`$e`) the same (see `elimAntiquotChoices`)
some Name.anonymous
| _ => none
-- `$e*` is an antiquotation "splice" matching an arbitrary number of syntax nodes
def isAntiquotSplice (stx : Syntax) : Bool :=
isAntiquot stx && (stx.getArg 4).getOptional?.isSome
-- If any item of a `many` node is an antiquotation splice, its result should
-- be substituted into the `many` node's children
def isAntiquotSplicePat (stx : Syntax) : Bool :=
stx.isOfKind nullKind && stx.getArgs.any (fun arg => isAntiquotSplice arg && !isEscapedAntiquot arg)
/-- A term like `($e) is actually ambiguous: the antiquotation could be of kind `term`,
or `ident`, or ... . But it shouldn't really matter because antiquotations without
explicit kinds behave the same at runtime. So we replace `choice` nodes that contain
at least one implicit antiquotation with that antiquotation. -/
private partial def elimAntiquotChoices : Syntax → Syntax
| Syntax.node `choice args => match args.find? (fun arg => antiquotKind? arg == Name.anonymous) with
| some anti => anti
| none => Syntax.node `choice $ args.map elimAntiquotChoices
| Syntax.node k args => Syntax.node k $ args.map elimAntiquotChoices
| stx => stx
-- Elaborate the content of a syntax quotation term
private partial def quoteSyntax : Syntax → TermElabM Syntax
| Syntax.ident info rawVal val preresolved => do
-- Add global scopes at compilation time (now), add macro scope at runtime (in the quotation).
-- See the paper for details.
r ← resolveGlobalName val;
let preresolved := r ++ preresolved;
let val := quote val;
-- `scp` is bound in stxQuot.expand
`(Syntax.ident (SourceInfo.mk none none none) $(quote rawVal) (addMacroScope mainModule $val scp) $(quote preresolved))
-- if antiquotation, insert contents as-is, else recurse
| stx@(Syntax.node k _) =>
if isAntiquot stx && !isEscapedAntiquot stx then
-- splices must occur in a `many` node
if isAntiquotSplice stx then throwErrorAt stx "unexpected antiquotation splice"
else pure $ getAntiquotTerm stx
else do
empty ← `(Array.empty);
-- if escaped antiquotation, decrement by one escape level
let stx := unescapeAntiquot stx;
args ← stx.getArgs.foldlM (fun args arg =>
if k == nullKind && isAntiquotSplice arg then
-- antiquotation splice pattern: inject args array
`(Array.append $args $(getAntiquotTerm arg))
else do
arg ← quoteSyntax arg;
`(Array.push $args $arg)) empty;
`(Syntax.node $(quote k) $args)
| Syntax.atom info val =>
`(Syntax.atom (SourceInfo.mk none none none) $(quote val))
| Syntax.missing => unreachable!
def stxQuot.expand (stx : Syntax) : TermElabM Syntax := do
let quoted := stx.getArg 1;
/- Syntax quotations are monadic values depending on the current macro scope. For efficiency, we bind
the macro scope once for each quotation, then build the syntax tree in a completely pure computation
depending on this binding. Note that regular function calls do not introduce a new macro scope (i.e.
we preserve referential transparency), so we can refer to this same `scp` inside `quoteSyntax` by
including it literally in a syntax quotation. -/
-- TODO: simplify to `(do scp ← getCurrMacroScope; pure $(quoteSyntax quoted))
stx ← quoteSyntax (elimAntiquotChoices quoted);
`(bind getCurrMacroScope (fun scp => bind getMainModule (fun mainModule => pure $stx)))
/- NOTE: It may seem like the newly introduced binding `scp` may accidentally
capture identifiers in an antiquotation introduced by `quoteSyntax`. However,
note that the syntax quotation above enjoys the same hygiene guarantees as
anywhere else in Lean; that is, we implement hygienic quotations by making
use of the hygienic quotation support of the bootstrapped Lean compiler!
Aside: While this might sound "dangerous", it is in fact less reliant on a
"chain of trust" than other bootstrapping parts of Lean: because this
implementation itself never uses `scp` (or any other identifier) both inside
and outside quotations, it can actually correctly be compiled by an
unhygienic (but otherwise correct) implementation of syntax quotations. As
long as it is then compiled again with the resulting executable (i.e. up to
stage 2), the result is a correct hygienic implementation. In this sense the
implementation is "self-stabilizing". It was in fact originally compiled
by an unhygienic prototype implementation. -/
@[builtinTermElab Parser.Level.quot] def elabLevelQuot : TermElab := adaptExpander stxQuot.expand
@[builtinTermElab Parser.Term.quot] def elabTermQuot : TermElab := adaptExpander stxQuot.expand
@[builtinTermElab Parser.Term.funBinder.quot] def elabfunBinderQuot : TermElab := adaptExpander stxQuot.expand
@[builtinTermElab Parser.Tactic.quot] def elabTacticQuot : TermElab := adaptExpander stxQuot.expand
@[builtinTermElab Parser.Term.stx.quot] def elabStxQuot : TermElab := adaptExpander stxQuot.expand
/- match_syntax -/
-- an "alternative" of patterns plus right-hand side
private abbrev Alt := List Syntax × Syntax
/-- Information on a pattern's head that influences the compilation of a single
match step. -/
structure HeadInfo :=
-- Node kind to match, if any
(kind : Option SyntaxNodeKind := none)
-- Nested patterns for each argument, if any. In a single match step, we only
-- check that the arity matches. The arity is usually implied by the node kind,
-- but not in the case of `many` nodes.
(argPats : Option (Array Syntax) := none)
-- Function to apply to the right-hand side in case the match succeeds. Used to
-- bind pattern variables.
(rhsFn : Syntax → TermElabM Syntax := pure)
instance HeadInfo.Inhabited : Inhabited HeadInfo := ⟨{}⟩
/-- `h1.generalizes h2` iff h1 is equal to or more general than h2, i.e. it matches all nodes
h2 matches. This induces a partial ordering. -/
def HeadInfo.generalizes : HeadInfo → HeadInfo → Bool
| { kind := none, .. }, _ => true
| { kind := some k1, argPats := none, .. },
{ kind := some k2, .. } => k1 == k2
| { kind := some k1, argPats := some ps1, .. },
{ kind := some k2, argPats := some ps2, .. } => k1 == k2 && ps1.size == ps2.size
| _, _ => false
private def getHeadInfo (alt : Alt) : HeadInfo :=
let pat := alt.fst.head!;
let unconditional (rhsFn) := { rhsFn := rhsFn : HeadInfo };
-- variable pattern
if pat.isIdent then unconditional $ fun rhs => `(let $pat := discr; $rhs)
-- wildcard pattern
else if pat.isOfKind `Lean.Parser.Term.hole then unconditional pure
-- quotation pattern
else if isQuot pat then
let quoted := pat.getArg 1;
if quoted.isAtom then
-- We assume that atoms are uniquely determined by the node kind and never have to be checked
unconditional pure
else if isAntiquot quoted && !isEscapedAntiquot quoted then
-- quotation contains a single antiquotation
let k := antiquotKind? quoted;
-- Antiquotation kinds like `$id:ident` influence the parser, but also need to be considered by
-- match_syntax (but not by quotation terms). For example, `($id:ident) and `($e) are not
-- distinguishable without checking the kind of the node to be captured. Note that some
-- antiquotations like the latter one for terms do not correspond to any actual node kind
-- (signified by `k == Name.anonymous`), so we would only check for `ident` here.
--
-- if stx.isOfKind `ident then
-- let id := stx; ...
-- else
-- let e := stx; ...
let kind := if k == Name.anonymous then none else k;
let anti := getAntiquotTerm quoted;
-- Splices should only appear inside a nullKind node, see next case
if isAntiquotSplice quoted then unconditional $ fun _ => throwErrorAt quoted "unexpected antiquotation splice"
else if anti.isIdent then { kind := kind, rhsFn := fun rhs => `(let $anti := discr; $rhs) }
else unconditional $ fun _ => throwErrorAt anti ("match_syntax: antiquotation must be variable " ++ toString anti)
else if isAntiquotSplicePat quoted && quoted.getArgs.size == 1 then
-- quotation is a single antiquotation splice => bind args array
let anti := getAntiquotTerm (quoted.getArg 0);
unconditional $ fun rhs => `(let $anti := Syntax.getArgs discr; $rhs)
-- TODO: support for more complex antiquotation splices
else
-- not an antiquotation or escaped antiquotation: match head shape
let quoted := unescapeAntiquot quoted;
let argPats := quoted.getArgs.map (pat.setArg 1);
{ kind := quoted.getKind, argPats := argPats }
else
unconditional $ fun _ => throwErrorAt pat ("match_syntax: unexpected pattern kind " ++ toString pat)
-- Assuming that the first pattern of the alternative is taken, replace it with patterns (if any) for its
-- child nodes.
-- Ex: `($a + (- $b)) => `($a), `(+), `(- $b)
-- Note: The atom pattern `(+) will be discarded in a later step
private def explodeHeadPat (numArgs : Nat) : HeadInfo × Alt → TermElabM Alt
| (info, (pat::pats, rhs)) => do
let newPats := match info.argPats with
| some argPats => argPats.toList
| none => List.replicate numArgs $ Unhygienic.run `(_);
rhs ← info.rhsFn rhs;
pure (newPats ++ pats, rhs)
| _ => unreachable!
private partial def compileStxMatch : List Syntax → List Alt → TermElabM Syntax
| [], ([], rhs)::_ => pure rhs -- nothing left to match
| _, [] => throwError "non-exhaustive 'match_syntax'"
| discr::discrs, alts => do
let alts := (alts.map getHeadInfo).zip alts;
-- Choose a most specific pattern, ie. a minimal element according to `generalizes`.
-- If there are multiple minimal elements, the choice does not matter.
let (info, alt) := alts.tail!.foldl (fun (min : HeadInfo × Alt) (alt : HeadInfo × Alt) => if min.1.generalizes alt.1 then alt else min) alts.head!;
-- introduce pattern matches on the discriminant's children if there are any nested patterns
newDiscrs ← match info.argPats with
| some pats => (List.range pats.size).mapM $ fun i => `(Syntax.getArg discr $(quote i))
| none => pure [];
-- collect matching alternatives and explode them
let yesAlts := alts.filter $ fun (alt : HeadInfo × Alt) => alt.1.generalizes info;
yesAlts ← yesAlts.mapM $ explodeHeadPat newDiscrs.length;
-- NOTE: use fresh macro scopes for recursive call so that different `discr`s introduced by the quotations below do not collide
yes ← withFreshMacroScope $ compileStxMatch (newDiscrs ++ discrs) yesAlts;
some kind ← pure info.kind
-- unconditional match step
| `(let discr := $discr; $yes);
-- conditional match step
let noAlts := (alts.filter $ fun (alt : HeadInfo × Alt) => !info.generalizes alt.1).map Prod.snd;
no ← withFreshMacroScope $ compileStxMatch (discr::discrs) noAlts;
cond ← match info.argPats with
| some pats => `(Syntax.isOfKind discr $(quote kind) && Array.size (Syntax.getArgs discr) == $(quote pats.size))
| none => `(Syntax.isOfKind discr $(quote kind));
`(let discr := $discr; if $cond = true then $yes else $no)
| _, _ => unreachable!
private partial def getPatternVarsAux : Syntax → List Syntax
| stx@(Syntax.node k args) =>
if isAntiquot stx && !isEscapedAntiquot stx then
let anti := getAntiquotTerm stx;
if anti.isIdent then [anti]
else []
else
List.join $ args.toList.map getPatternVarsAux
| _ => []
-- Get all pattern vars (as `Syntax.ident`s) in `stx`
partial def getPatternVars (stx : Syntax) : List Syntax :=
if isQuot stx then do
let quoted := stx.getArg 1;
getPatternVarsAux stx
else if stx.isIdent then
[stx]
else []
-- Transform alternatives by binding all right-hand sides to outside the match_syntax in order to prevent
-- code duplication during match_syntax compilation
private def letBindRhss (cont : List Alt → TermElabM Syntax) : List Alt → List Alt → TermElabM Syntax
| [], altsRev' => cont altsRev'.reverse
| (pats, rhs)::alts, altsRev' => do
let vars := List.join $ pats.map getPatternVars;
match vars with
-- no antiquotations => introduce Unit parameter to preserve evaluation order
| [] => do
-- NOTE: references binding below
rhs' ← `(rhs ());
-- NOTE: new macro scope so that introduced bindings do not collide
stx ← withFreshMacroScope $ letBindRhss alts ((pats, rhs')::altsRev');
`(let rhs := fun _ => $rhs; $stx)
| _ => do
-- rhs ← `(fun $vars* => $rhs)
let rhs := Syntax.node `Lean.Parser.Term.fun #[mkAtom "fun", Syntax.node `null vars.toArray, mkAtom "=>", rhs];
rhs' ← `(rhs);
stx ← withFreshMacroScope $ letBindRhss alts ((pats, rhs')::altsRev');
`(let rhs := $rhs; $stx)
def match_syntax.expand (stx : Syntax) : TermElabM Syntax := do
let discr := stx.getArg 1;
let alts := (stx.getArg 3).getArg 1;
alts ← alts.getArgs.getSepElems.mapM $ fun alt => do {
let pats := alt.getArg 0;
pat ← if pats.getArgs.size == 1 then pure $ pats.getArg 0
else throwError "match_syntax: expected exactly one pattern per alternative";
let pat := if isQuot pat then pat.setArg 1 $ elimAntiquotChoices $ pat.getArg 1 else pat;
match pat.find? $ fun stx => stx.getKind == choiceKind with
| some choiceStx => throwErrorAt choiceStx "invalid pattern, nested syntax has multiple interpretations"
| none =>
let rhs := alt.getArg 2;
pure ([pat], rhs)
};
-- letBindRhss (compileStxMatch stx [discr]) alts.toList []
compileStxMatch [discr] alts.toList
@[builtinTermElab «match_syntax»] def elabMatchSyntax : TermElab :=
adaptExpander match_syntax.expand
-- REMOVE with old frontend
private def exprPlaceholder := mkMVar Name.anonymous
private unsafe partial def toPreterm : Syntax → TermElabM Expr
| stx => withRef stx $
match stx.getKind with
| `ident =>
match stx with
| Syntax.ident _ _ val preresolved => do
resolved ← resolveName val preresolved [];
match resolved with
| (pre,projs)::_ =>
let pre := match pre with
| Expr.const c _ _ => Lean.mkConst c -- remove universes confusing the old frontend
| _ => pre;
pure $ projs.foldl (fun e proj => mkMData (MData.empty.setName `fieldNotation proj) e) pre
| [] => unreachable!
| _ => unreachable!
| `Lean.Parser.Term.fun => do
let params := (stx.getArg 1).getArgs;
let body := stx.getArg 3;
if params.size == 0 then toPreterm body
else do
let param := params.get! 0;
(n, ty) ← if param.isIdent then
pure (param.getId, exprPlaceholder)
else if param.isOfKind `Lean.Parser.Term.hole then
pure (`_a, exprPlaceholder)
else do {
let n := ((param.getArg 1).getArg 0).getId;
ty ← toPreterm $ (((param.getArg 1).getArg 1).getArg 0).getArg 1;
pure (n, ty)
};
lctx ← getLCtx;
let lctx := lctx.mkLocalDecl n n ty;
let params := params.eraseIdx 0;
stx ← `(fun $params* => $body);
adaptTheReader Meta.Context (fun ctx => { ctx with lctx := lctx }) $ do
e ← toPreterm stx;
pure $ lctx.mkLambda #[mkFVar n] e
| `Lean.Parser.Term.let => do
let decl := (stx.getArg 1).getArg 0;
let n := decl.getIdAt 0;
let val := decl.getArg 4;
let body := stx.getArg 3;
val ← toPreterm val;
lctx ← getLCtx;
let lctx := lctx.mkLetDecl n n exprPlaceholder val;
adaptTheReader Meta.Context (fun ctx => { ctx with lctx := lctx }) $ do
e ← toPreterm $ body;
pure $ lctx.mkLambda #[mkFVar n] e
| `Lean.Parser.Term.app => do
fn ← toPreterm $ stx.getArg 0;
as ← (stx.getArg 1).getArgs.mapM toPreterm;
pure $ mkAppN fn as
| `Lean.Parser.Term.if => do
let con := stx.getArg 2;
let yes := stx.getArg 4;
let no := stx.getArg 6;
toPreterm $ Unhygienic.run `(ite $con $yes $no)
| `Lean.Parser.Term.paren =>
let inner := (stx.getArg 1).getArgs;
if inner.size == 0 then pure $ Lean.mkConst `Unit.unit
else toPreterm $ inner.get! 0
| `Lean.Parser.Term.band =>
let lhs := stx.getArg 0; let rhs := stx.getArg 2;
toPreterm $ Unhygienic.run `(and $lhs $rhs)
| `Lean.Parser.Term.beq =>
let lhs := stx.getArg 0; let rhs := stx.getArg 2;
toPreterm $ Unhygienic.run `(HasBeq.beq $lhs $rhs)
| `Lean.Parser.Term.eq =>
let lhs := stx.getArg 0; let rhs := stx.getArg 2;
toPreterm $ Unhygienic.run `(Eq $lhs $rhs)
| `strLit => pure $ mkStrLit $ stx.isStrLit?.getD ""
| `numLit => pure $ mkNatLit $ stx.isNatLit?.getD 0
| `expr => pure $ unsafeCast $ stx.getArg 0 -- HACK: see below
| k => throwError $ "stxQuot: unimplemented kind " ++ toString k
@[export lean_parse_expr]
def oldParseExpr (env : Environment) (input : String) (pos : String.Pos) : Except String (Syntax × String.Pos) := do
let c := Parser.mkParserContext env (Parser.mkInputContext input "<foo>");
let s := Parser.mkParserState c.input;
let s := s.setPos pos;
let s := (Parser.termParser Parser.maxPrec : Parser.Parser).fn { c with prec := Parser.maxPrec } s;
let stx := s.stxStack.back;
match s.errorMsg with
| some errorMsg =>
Except.error $ toString errorMsg
| none =>
Except.ok (stx, s.pos)
structure OldContext :=
(env : Environment)
(locals : List Name)
(open_nss : List Name)
private unsafe def oldRunTermElabMUnsafe {α} (oldCtx : OldContext) (x : TermElabM α) : Except String α := do
let ctxMeta : Meta.Context := {
lctx := oldCtx.locals.foldl (fun lctx l => LocalContext.mkLocalDecl lctx l l exprPlaceholder) $ LocalContext.mkEmpty ()
};
let ctxTerm : Term.Context := {
fileName := "foo",
fileMap := FileMap.ofString "",
currNamespace := Lean.TODELETE.getNamespace oldCtx.env,
openDecls := oldCtx.open_nss.map $ fun n => OpenDecl.simple n []
};
match unsafeIO $ x.toIO {} { env := oldCtx.env } ctxMeta {} ctxTerm {} with
| Except.ok (a, _, _, _) => Except.ok a
| Except.error e => Except.error (toString e)
@[implementedBy oldRunTermElabMUnsafe]
constant oldRunTermElabM {α} (oldCtx : OldContext) (x : TermElabM α) : Except String α := arbitrary _
@[export lean_expand_stx_quot]
unsafe def oldExpandStxQuot (ctx : OldContext) (stx : Syntax) : Except String Expr := oldRunTermElabM ctx $ do
stx ← stxQuot.expand stx;
toPreterm stx
@[export lean_get_antiquot_vars]
def oldGetPatternVars (ctx : OldContext) (pats : List Syntax) : Except String (List Name) := oldRunTermElabM ctx $ do
let vars := List.join $ pats.map getPatternVars;
pure $ vars.map $ fun var => var.getId
@[export lean_expand_match_syntax]
unsafe def oldExpandMatchSyntax (ctx : OldContext) (discr : Syntax) (alts : List (List Syntax × Syntax)) : Except String Expr := oldRunTermElabM ctx $ do
-- HACK: discr and the RHSs are actually `Expr`
let discr := Syntax.node `expr #[discr];
let alts := alts.map $ fun alt =>
let pats := alt.1.map elimAntiquotChoices;
(pats, Syntax.node `expr #[alt.2]);
-- letBindRhss (compileStxMatch Syntax.missing [discr]) alts []
stx ← compileStxMatch [discr] alts;
toPreterm stx
end Quotation
end Term
end Elab
end Lean
|
ea093a241a3097908f2252a35d4d62c1e6609021 | 57c233acf9386e610d99ed20ef139c5f97504ba3 | /test/instance_diamonds.lean | 79f991a7b58e65e83d7616d64c54389376c4fa39 | [
"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,127 | 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 algebra.module.pi
import data.polynomial.basic
import group_theory.group_action.prod
import group_theory.group_action.units
import data.complex.module
/-! # Tests that instances do not form diamonds -/
/-! ## Scalar action instances -/
section has_scalar
example :
(sub_neg_monoid.has_scalar_int : has_scalar ℤ ℂ) = (complex.has_scalar : has_scalar ℤ ℂ) :=
rfl
example (α β : Type*) [add_monoid α] [add_monoid β] :
(prod.has_scalar : has_scalar ℕ (α × β)) = add_monoid.has_scalar_nat := rfl
example (α β : Type*) [sub_neg_monoid α] [sub_neg_monoid β] :
(prod.has_scalar : has_scalar ℤ (α × β)) = sub_neg_monoid.has_scalar_int := rfl
example (α : Type*) (β : α → Type*) [Π a, add_monoid (β a)] :
(pi.has_scalar : has_scalar ℕ (Π a, β a)) = add_monoid.has_scalar_nat := rfl
example (α : Type*) (β : α → Type*) [Π a, sub_neg_monoid (β a)] :
(pi.has_scalar : has_scalar ℤ (Π a, β a)) = sub_neg_monoid.has_scalar_int := rfl
section units
example (α : Type*) [monoid α] :
(units.mul_action : mul_action αˣ (α × α)) = prod.mul_action := rfl
example (R α : Type*) (β : α → Type*) [monoid R] [Π i, mul_action R (β i)] :
(units.mul_action : mul_action Rˣ (Π i, β i)) = pi.mul_action _ := rfl
example (R α : Type*) (β : α → Type*) [monoid R] [semiring α] [distrib_mul_action R α] :
(units.distrib_mul_action : distrib_mul_action Rˣ (polynomial α)) =
polynomial.distrib_mul_action :=
rfl
/-!
TODO: https://leanprover.zulipchat.com/#narrow/stream/113488-general/topic/units.2Emul_action'.20diamond/near/246402813
```lean
example {α : Type*} [comm_monoid α] :
(units.mul_action' : mul_action αˣ αˣ) = monoid.to_mul_action _ :=
rfl -- fails
```
-/
end units
end has_scalar
/-! ## `with_top` (Type with point at infinity) instances -/
section with_top
example (R : Type*) [h : ordered_semiring R] :
(@with_top.add_comm_monoid R
(@non_unital_non_assoc_semiring.to_add_comm_monoid R
(@non_assoc_semiring.to_non_unital_non_assoc_semiring R
(@semiring.to_non_assoc_semiring R
(@ordered_semiring.to_semiring R h)))))
=
(@ordered_add_comm_monoid.to_add_comm_monoid (with_top R)
(@with_top.ordered_add_comm_monoid R
(@ordered_cancel_add_comm_monoid.to_ordered_add_comm_monoid R
(@ordered_semiring.to_ordered_cancel_add_comm_monoid R h)))) :=
rfl
end with_top
/-! ## `multiplicative` instances -/
section multiplicative
example :
@monoid.to_mul_one_class (multiplicative ℕ) (comm_monoid.to_monoid _) =
multiplicative.mul_one_class :=
rfl
-- `dunfold` can still break unification, but it's better to have `dunfold` break it than have the
-- above example fail.
example :
@monoid.to_mul_one_class (multiplicative ℕ) (comm_monoid.to_monoid _) =
multiplicative.mul_one_class :=
begin
dunfold has_one.one multiplicative.mul_one_class,
success_if_fail { refl, },
ext,
refl
end
end multiplicative
|
96a771b692ae76543efcfb5c6885ed78ca2d5ec4 | 302c785c90d40ad3d6be43d33bc6a558354cc2cf | /src/category_theory/limits/shapes/products.lean | 41479cd6b1382728ee50ecf6ce408638fe1cff30 | [
"Apache-2.0"
] | permissive | ilitzroth/mathlib | ea647e67f1fdfd19a0f7bdc5504e8acec6180011 | 5254ef14e3465f6504306132fe3ba9cec9ffff16 | refs/heads/master | 1,680,086,661,182 | 1,617,715,647,000 | 1,617,715,647,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 6,785 | lean | /-
Copyright (c) 2018 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Scott Morrison, Bhavik Mehta
-/
import category_theory.limits.has_limits
import category_theory.discrete_category
noncomputable theory
universes v u u₂
open category_theory
namespace category_theory.limits
variables {β : Type v}
variables {C : Type u} [category.{v} C]
-- We don't need an analogue of `pair` (for binary products), `parallel_pair` (for equalizers),
-- or `(co)span`, since we already have `discrete.functor`.
/-- A fan over `f : β → C` consists of a collection of maps from an object `P` to every `f b`. -/
abbreviation fan (f : β → C) := cone (discrete.functor f)
/-- A cofan over `f : β → C` consists of a collection of maps from every `f b` to an object `P`. -/
abbreviation cofan (f : β → C) := cocone (discrete.functor f)
/-- A fan over `f : β → C` consists of a collection of maps from an object `P` to every `f b`. -/
@[simps]
def fan.mk {f : β → C} (P : C) (p : Π b, P ⟶ f b) : fan f :=
{ X := P,
π := { app := p } }
/-- A cofan over `f : β → C` consists of a collection of maps from every `f b` to an object `P`. -/
@[simps]
def cofan.mk {f : β → C} (P : C) (p : Π b, f b ⟶ P) : cofan f :=
{ X := P,
ι := { app := p } }
/-- An abbreviation for `has_limit (discrete.functor f)`. -/
abbreviation has_product (f : β → C) := has_limit (discrete.functor f)
/-- An abbreviation for `has_colimit (discrete.functor f)`. -/
abbreviation has_coproduct (f : β → C) := has_colimit (discrete.functor f)
section
variables (C)
/-- An abbreviation for `has_limits_of_shape (discrete f)`. -/
abbreviation has_products_of_shape (β : Type v) := has_limits_of_shape.{v} (discrete β)
/-- An abbreviation for `has_colimits_of_shape (discrete f)`. -/
abbreviation has_coproducts_of_shape (β : Type v) := has_colimits_of_shape.{v} (discrete β)
end
/-- `pi_obj f` computes the product of a family of elements `f`.
(It is defined as an abbreviation for `limit (discrete.functor f)`,
so for most facts about `pi_obj f`, you will just use general facts about limits.) -/
abbreviation pi_obj (f : β → C) [has_product f] := limit (discrete.functor f)
/-- `sigma_obj f` computes the coproduct of a family of elements `f`.
(It is defined as an abbreviation for `colimit (discrete.functor f)`,
so for most facts about `sigma_obj f`, you will just use general facts about colimits.) -/
abbreviation sigma_obj (f : β → C) [has_coproduct f] := colimit (discrete.functor f)
notation `∏ ` f:20 := pi_obj f
notation `∐ ` f:20 := sigma_obj f
/-- The `b`-th projection from the pi object over `f` has the form `∏ f ⟶ f b`. -/
abbreviation pi.π (f : β → C) [has_product f] (b : β) : ∏ f ⟶ f b :=
limit.π (discrete.functor f) b
/-- The `b`-th inclusion into the sigma object over `f` has the form `f b ⟶ ∐ f`. -/
abbreviation sigma.ι (f : β → C) [has_coproduct f] (b : β) : f b ⟶ ∐ f :=
colimit.ι (discrete.functor f) b
/-- The fan constructed of the projections from the product is limiting. -/
def product_is_product (f : β → C) [has_product f] :
is_limit (fan.mk _ (pi.π f)) :=
is_limit.of_iso_limit (limit.is_limit (discrete.functor f)) (cones.ext (iso.refl _) (by tidy))
/-- A collection of morphisms `P ⟶ f b` induces a morphism `P ⟶ ∏ f`. -/
abbreviation pi.lift {f : β → C} [has_product f] {P : C} (p : Π b, P ⟶ f b) : P ⟶ ∏ f :=
limit.lift _ (fan.mk P p)
/-- A collection of morphisms `f b ⟶ P` induces a morphism `∐ f ⟶ P`. -/
abbreviation sigma.desc {f : β → C} [has_coproduct f] {P : C} (p : Π b, f b ⟶ P) : ∐ f ⟶ P :=
colimit.desc _ (cofan.mk P p)
/--
Construct a morphism between categorical products (indexed by the same type)
from a family of morphisms between the factors.
-/
abbreviation pi.map {f g : β → C} [has_product f] [has_product g]
(p : Π b, f b ⟶ g b) : ∏ f ⟶ ∏ g :=
lim_map (discrete.nat_trans p)
/--
Construct an isomorphism between categorical products (indexed by the same type)
from a family of isomorphisms between the factors.
-/
abbreviation pi.map_iso {f g : β → C} [has_products_of_shape β C]
(p : Π b, f b ≅ g b) : ∏ f ≅ ∏ g :=
lim.map_iso (discrete.nat_iso p)
/--
Construct a morphism between categorical coproducts (indexed by the same type)
from a family of morphisms between the factors.
-/
abbreviation sigma.map {f g : β → C} [has_coproduct f] [has_coproduct g]
(p : Π b, f b ⟶ g b) : ∐ f ⟶ ∐ g :=
colim_map (discrete.nat_trans p)
/--
Construct an isomorphism between categorical coproducts (indexed by the same type)
from a family of isomorphisms between the factors.
-/
abbreviation sigma.map_iso {f g : β → C} [has_coproducts_of_shape β C]
(p : Π b, f b ≅ g b) : ∐ f ≅ ∐ g :=
colim.map_iso (discrete.nat_iso p)
section comparison
variables {D : Type u₂} [category.{v} D] (G : C ⥤ D)
variables (f : β → C)
-- TODO: show this is an iso iff G preserves the product of f.
/-- The comparison morphism for the product of `f`. -/
def pi_comparison [has_product f] [has_product (λ b, G.obj (f b))] :
G.obj (∏ f) ⟶ ∏ (λ b, G.obj (f b)) :=
pi.lift (λ b, G.map (pi.π f b))
@[simp, reassoc]
lemma pi_comparison_comp_π [has_product f] [has_product (λ b, G.obj (f b))] (b : β) :
pi_comparison G f ≫ pi.π _ b = G.map (pi.π f b) :=
limit.lift_π _ b
@[simp, reassoc]
lemma map_lift_pi_comparison [has_product f] [has_product (λ b, G.obj (f b))]
(P : C) (g : Π j, P ⟶ f j) :
G.map (pi.lift g) ≫ pi_comparison G f = pi.lift (λ j, G.map (g j)) :=
by { ext, simp [← G.map_comp] }
-- TODO: show this is an iso iff G preserves the coproduct of f.
/-- The comparison morphism for the coproduct of `f`. -/
def sigma_comparison [has_coproduct f] [has_coproduct (λ b, G.obj (f b))] :
∐ (λ b, G.obj (f b)) ⟶ G.obj (∐ f) :=
sigma.desc (λ b, G.map (sigma.ι f b))
@[simp, reassoc]
lemma ι_comp_sigma_comparison [has_coproduct f] [has_coproduct (λ b, G.obj (f b))] (b : β) :
sigma.ι _ b ≫ sigma_comparison G f = G.map (sigma.ι f b) :=
colimit.ι_desc _ b
@[simp, reassoc]
lemma sigma_comparison_map_desc [has_coproduct f] [has_coproduct (λ b, G.obj (f b))]
(P : C) (g : Π j, f j ⟶ P) :
sigma_comparison G f ≫ G.map (sigma.desc g) = sigma.desc (λ j, G.map (g j)) :=
by { ext, simp [← G.map_comp] }
end comparison
variables (C)
/-- An abbreviation for `Π J, has_limits_of_shape (discrete J) C` -/
abbreviation has_products := Π (J : Type v), has_limits_of_shape (discrete J) C
/-- An abbreviation for `Π J, has_colimits_of_shape (discrete J) C` -/
abbreviation has_coproducts := Π (J : Type v), has_colimits_of_shape (discrete J) C
end category_theory.limits
|
a1fe0c06aeb2b80ae82741a54e152349ec420f6b | a45212b1526d532e6e83c44ddca6a05795113ddc | /src/ring_theory/subring.lean | 213ba699589ad970ae6b00eae7b23453917a0f52 | [
"Apache-2.0"
] | permissive | fpvandoorn/mathlib | b21ab4068db079cbb8590b58fda9cc4bc1f35df4 | b3433a51ea8bc07c4159c1073838fc0ee9b8f227 | refs/heads/master | 1,624,791,089,608 | 1,556,715,231,000 | 1,556,715,231,000 | 165,722,980 | 5 | 0 | Apache-2.0 | 1,552,657,455,000 | 1,547,494,646,000 | Lean | UTF-8 | Lean | false | false | 7,025 | lean | /-
Copyright (c) 2018 Johan Commelin. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johan Commelin
-/
import group_theory.subgroup
import algebra.ring
universes u v
open group
variables {R : Type u} [ring R]
/-- `S` is a subring: a set containing 1 and closed under multiplication, addition and and additive inverse. -/
class is_subring (S : set R) extends is_add_subgroup S, is_submonoid S : Prop.
instance subset.ring {S : set R} [is_subring S] : ring S :=
by subtype_instance
instance subtype.ring {S : set R} [is_subring S] : ring (subtype S) := subset.ring
namespace is_ring_hom
instance {S : set R} [is_subring S] : is_ring_hom (@subtype.val R S) :=
by refine {..} ; intros ; refl
instance is_subring_preimage {R : Type u} {S : Type v} [ring R] [ring S]
(f : R → S) [is_ring_hom f] (s : set S) [is_subring s] : is_subring (f ⁻¹' s) := {}
instance is_subring_image {R : Type u} {S : Type v} [ring R] [ring S]
(f : R → S) [is_ring_hom f] (s : set R) [is_subring s] : is_subring (f '' s) := {}
instance is_subring_set_range {R : Type u} {S : Type v} [ring R] [ring S]
(f : R → S) [is_ring_hom f] : is_subring (set.range f) := {}
end is_ring_hom
instance subtype_val.is_ring_hom {s : set R} [is_subring s] :
is_ring_hom (subtype.val : s → R) :=
{ ..subtype_val.is_add_group_hom, ..subtype_val.is_monoid_hom }
instance coe.is_ring_hom {s : set R} [is_subring s] : is_ring_hom (coe : s → R) :=
subtype_val.is_ring_hom
instance subtype_mk.is_ring_hom {γ : Type*} [ring γ] {s : set R} [is_subring s] (f : γ → R)
[is_ring_hom f] (h : ∀ x, f x ∈ s) : is_ring_hom (λ x, (⟨f x, h x⟩ : s)) :=
{ ..subtype_mk.is_add_group_hom f h, ..subtype_mk.is_monoid_hom f h }
instance set_inclusion.is_ring_hom {s t : set R} [is_subring s] [is_subring t] (h : s ⊆ t) :
is_ring_hom (set.inclusion h) :=
subtype_mk.is_ring_hom _ _
variables {cR : Type u} [comm_ring cR]
instance subset.comm_ring {S : set cR} [is_subring S] : comm_ring S :=
by subtype_instance
instance subtype.comm_ring {S : set cR} [is_subring S] : comm_ring (subtype S) := subset.comm_ring
instance subring.domain {D : Type*} [integral_domain D] (S : set D) [is_subring S] : integral_domain S :=
by subtype_instance
lemma is_subring_Union_of_directed {ι : Type*} [hι : nonempty ι]
(s : ι → set R) [∀ i, is_subring (s i)]
(directed : ∀ i j, ∃ k, s i ⊆ s k ∧ s j ⊆ s k) :
is_subring (⋃i, s i) :=
{ to_is_add_subgroup := is_add_subgroup_Union_of_directed s directed,
to_is_submonoid := is_submonoid_Union_of_directed s directed }
namespace ring
def closure (s : set R) := add_group.closure (monoid.closure s)
variable {s : set R}
local attribute [reducible] closure
theorem exists_list_of_mem_closure {a : R} (h : a ∈ closure s) :
(∃ L : list (list R), (∀ l ∈ L, ∀ x ∈ l, x ∈ s ∨ x = (-1:R)) ∧ (L.map list.prod).sum = a) :=
add_group.in_closure.rec_on h
(λ x hx, match x, monoid.exists_list_of_mem_closure hx with
| _, ⟨L, h1, rfl⟩ := ⟨[L], list.forall_mem_singleton.2 (λ r hr, or.inl (h1 r hr)), zero_add _⟩
end)
⟨[], list.forall_mem_nil _, rfl⟩
(λ b _ ih, match b, ih with
| _, ⟨L1, h1, rfl⟩ := ⟨L1.map (list.cons (-1)),
λ L2 h2, match L2, list.mem_map.1 h2 with
| _, ⟨L3, h3, rfl⟩ := list.forall_mem_cons.2 ⟨or.inr rfl, h1 L3 h3⟩
end,
by simp only [list.map_map, (∘), list.prod_cons, neg_one_mul];
exact list.rec_on L1 neg_zero.symm (λ hd tl ih,
by rw [list.map_cons, list.sum_cons, ih, list.map_cons, list.sum_cons, neg_add])⟩
end)
(λ r1 r2 hr1 hr2 ih1 ih2, match r1, r2, ih1, ih2 with
| _, _, ⟨L1, h1, rfl⟩, ⟨L2, h2, rfl⟩ := ⟨L1 ++ L2, list.forall_mem_append.2 ⟨h1, h2⟩,
by rw [list.map_append, list.sum_append]⟩
end)
@[elab_as_eliminator]
protected theorem in_closure.rec_on {C : R → Prop} {x : R} (hx : x ∈ closure s)
(h1 : C 1) (hneg1 : C (-1)) (hs : ∀ z ∈ s, ∀ n, C n → C (z * n))
(ha : ∀ {x y}, C x → C y → C (x + y)) : C x :=
begin
have h0 : C 0 := add_neg_self (1:R) ▸ ha h1 hneg1,
rcases exists_list_of_mem_closure hx with ⟨L, HL, rfl⟩, clear hx,
induction L with hd tl ih, { exact h0 },
rw list.forall_mem_cons at HL,
suffices : C (list.prod hd),
{ rw [list.map_cons, list.sum_cons],
exact ha this (ih HL.2) },
replace HL := HL.1, clear ih tl,
suffices : ∃ L : list R, (∀ x ∈ L, x ∈ s) ∧ (list.prod hd = list.prod L ∨ list.prod hd = -list.prod L),
{ rcases this with ⟨L, HL', HP | HP⟩,
{ rw HP, clear HP HL hd, induction L with hd tl ih, { exact h1 },
rw list.forall_mem_cons at HL',
rw list.prod_cons,
exact hs _ HL'.1 _ (ih HL'.2) },
rw HP, clear HP HL hd, induction L with hd tl ih, { exact hneg1 },
rw [list.prod_cons, neg_mul_eq_mul_neg],
rw list.forall_mem_cons at HL',
exact hs _ HL'.1 _ (ih HL'.2) },
induction hd with hd tl ih,
{ exact ⟨[], list.forall_mem_nil _, or.inl rfl⟩ },
rw list.forall_mem_cons at HL,
rcases ih HL.2 with ⟨L, HL', HP | HP⟩; cases HL.1 with hhd hhd,
{ exact ⟨hd :: L, list.forall_mem_cons.2 ⟨hhd, HL'⟩, or.inl $
by rw [list.prod_cons, list.prod_cons, HP]⟩ },
{ exact ⟨L, HL', or.inr $ by rw [list.prod_cons, hhd, neg_one_mul, HP]⟩ },
{ exact ⟨hd :: L, list.forall_mem_cons.2 ⟨hhd, HL'⟩, or.inr $
by rw [list.prod_cons, list.prod_cons, HP, neg_mul_eq_mul_neg]⟩ },
{ exact ⟨L, HL', or.inl $ by rw [list.prod_cons, hhd, HP, neg_one_mul, neg_neg]⟩ }
end
instance : is_subring (closure s) :=
{ one_mem := add_group.mem_closure (is_submonoid.one_mem _),
mul_mem := λ a b ha hb, add_group.in_closure.rec_on hb
(λ b hb, add_group.in_closure.rec_on ha
(λ a ha, add_group.subset_closure (is_submonoid.mul_mem ha hb))
((zero_mul b).symm ▸ is_add_submonoid.zero_mem _)
(λ a ha hab, (neg_mul_eq_neg_mul a b) ▸ is_add_subgroup.neg_mem hab)
(λ a c ha hc hab hcb, (add_mul a c b).symm ▸ is_add_submonoid.add_mem hab hcb))
((mul_zero a).symm ▸ is_add_submonoid.zero_mem _)
(λ b hb hab, (neg_mul_eq_mul_neg a b) ▸ is_add_subgroup.neg_mem hab)
(λ b c hb hc hab hac, (mul_add a b c).symm ▸ is_add_submonoid.add_mem hab hac),
.. add_group.closure.is_add_subgroup _ }
theorem mem_closure {a : R} : a ∈ s → a ∈ closure s :=
add_group.mem_closure ∘ @monoid.subset_closure _ _ _ _
theorem subset_closure : s ⊆ closure s :=
λ _, mem_closure
theorem closure_subset {t : set R} [is_subring t] : s ⊆ t → closure s ⊆ t :=
add_group.closure_subset ∘ monoid.closure_subset
theorem closure_subset_iff (s t : set R) [is_subring t] : closure s ⊆ t ↔ s ⊆ t :=
(add_group.closure_subset_iff _ t).trans
⟨set.subset.trans monoid.subset_closure, monoid.closure_subset⟩
theorem closure_mono {s t : set R} (H : s ⊆ t) : closure s ⊆ closure t :=
closure_subset $ set.subset.trans H subset_closure
end ring
|
6291731e4ae676e1e08368a70acc2ce59872be4a | 968e2f50b755d3048175f176376eff7139e9df70 | /examples/pred_logic/unnamed_826.lean | 84cddb17dec8f0b3af7332261a486322e2552a04 | [] | 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 | 2,033 | lean | import tactic
namespace hidden
def even (a : ℕ) := ∃ b, a = 2 * b
def odd (a : ℕ) := ∃ b, a = 2 * b + 1
def parity : ℕ → ℕ
| 0 := 0
| (nat.succ n) := ite (parity n = 0) 1 0
lemma parity_eq_zero_or_one (n : ℕ) : parity n = 0 ∨ parity n = 1 :=
begin
induction n with k hk,
{ left, refl, },
unfold parity at *,
by_cases h : parity k = 0,
{ rw h, right, refl, },
{ left, exact if_neg h, },
end
lemma parity_eq_zero_of_even (n : ℕ) : even n → parity n = 0 :=
begin
rintro ⟨b, rfl⟩,
induction b with k hk,
{ refl, },
{ rw nat.mul_succ,
unfold parity,
refine if_neg _,
rw [hk, if_pos],
{ contradiction, },
{ refl, }, },
end
lemma parity_eq_one_of_odd (n : ℕ) : odd n → parity n = 1 :=
begin
rintro ⟨b, rfl⟩,
induction b with k hk,
{ refl, },
{ rw nat.mul_succ,
unfold parity at *,
rw if_pos,
rw if_neg,
rw hk,
trivial, },
end
-- BEGIN
theorem not_even_iff_odd (n : ℕ) : ¬even n ↔ odd n :=
begin
induction n with k hk,
{ exact ⟨(λ h, false.elim (h ⟨0, rfl⟩)), (λ ⟨n,hn⟩ _, nat.succ_ne_zero (2*n) hn.symm)⟩, },
{ cases (parity_eq_zero_or_one k) with k₀ k₁,
{ have : even k, from (show ¬odd k → even k, by {contrapose!, exact hk.mp})
((mt (parity_eq_one_of_odd k)) (k₀.symm ▸ nat.zero_ne_one)),
rcases this with ⟨b, rfl⟩,
split,
{ exact λ _, ⟨b, rfl⟩, },
{ have h₃ : parity(nat.succ (2*b)) = 1, from if_pos k₀,
exact (λ _, (mt (parity_eq_zero_of_even _)) (h₃.symm ▸ nat.zero_ne_one.symm )) }, },
{ have h₁ : ¬(parity k = 0), { intro h, rw h at k₁, contradiction, },
rcases (hk.mp) ((mt (parity_eq_zero_of_even k )) h₁) with ⟨b, rfl⟩,
split,
{ exact λ h₂, false.elim (h₂ ⟨b+1, rfl⟩), },
{ have h₃ : parity(nat.succ (2*b+1)) = 0, from if_neg h₁,
exact (λ h₄, false.elim ((nat.zero_ne_one) (h₃ ▸ (parity_eq_one_of_odd _ h₄)))), }, }, },
end
-- END
end hidden |
d8d16e88a487f2f80f2efa4b077dac801c680cb2 | 618003631150032a5676f229d13a079ac875ff77 | /src/category_theory/limits/creates.lean | 36797b4d2dfb6e2b53ed24a7c8ca53232c5030c0 | [
"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 | 14,788 | lean | /-
Copyright (c) 2020 Bhavik Mehta. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Bhavik Mehta
-/
import category_theory.reflect_isomorphisms
open category_theory category_theory.limits
namespace category_theory
universes v u₁ u₂ u₃
variables {C : Type u₁} [category.{v} C]
section creates
variables {D : Type u₂} [category.{v} D]
variables {J : Type v} [small_category J] {K : J ⥤ C}
/--
Define the lift of a cone: For a cone `c` for `K ⋙ F`, give a cone for `K`
which is a lift of `c`, i.e. the image of it under `F` is (iso) to `c`.
We will then use this as part of the definition of creation of limits:
every limit cone has a lift.
Note this definition is really only useful when `c` is a limit already.
-/
structure liftable_cone (K : J ⥤ C) (F : C ⥤ D) (c : cone (K ⋙ F)) :=
(lifted_cone : cone K)
(valid_lift : F.map_cone lifted_cone ≅ c)
/--
Define the lift of a cocone: For a cocone `c` for `K ⋙ F`, give a cocone for
`K` which is a lift of `c`, i.e. the image of it under `F` is (iso) to `c`.
We will then use this as part of the definition of creation of colimits:
every limit cocone has a lift.
Note this definition is really only useful when `c` is a colimit already.
-/
structure liftable_cocone (K : J ⥤ C) (F : C ⥤ D) (c : cocone (K ⋙ F)) :=
(lifted_cocone : cocone K)
(valid_lift : F.map_cocone lifted_cocone ≅ c)
set_option default_priority 100
/--
Definition 3.3.1 of [Riehl].
We say that `F` creates limits of `K` if, given any limit cone `c` for `K ⋙ F`
(i.e. below) we can lift it to a cone "above", and further that `F` reflects
limits for `K`.
If `F` reflects isomorphisms, it suffices to show only that the lifted cone is
a limit - see `creates_limit_of_reflects_iso`.
-/
class creates_limit (K : J ⥤ C) (F : C ⥤ D) extends reflects_limit K F :=
(lifts : Π c, is_limit c → liftable_cone K F c)
/--
`F` creates limits of shape `J` if `F` creates the limit of any diagram
`K : J ⥤ C`.
-/
class creates_limits_of_shape (J : Type v) [small_category J] (F : C ⥤ D) :=
(creates_limit : Π {K : J ⥤ C}, creates_limit K F)
/-- `F` creates limits if it creates limits of shape `J` for any small `J`. -/
class creates_limits (F : C ⥤ D) :=
(creates_limits_of_shape : Π {J : Type v} {𝒥 : small_category J},
by exactI creates_limits_of_shape J F)
/--
Dual of definition 3.3.1 of [Riehl].
We say that `F` creates colimits of `K` if, given any limit cocone `c` for
`K ⋙ F` (i.e. below) we can lift it to a cocone "above", and further that `F`
reflects limits for `K`.
If `F` reflects isomorphisms, it suffices to show only that the lifted cocone is
a limit - see `creates_limit_of_reflects_iso`.
-/
class creates_colimit (K : J ⥤ C) (F : C ⥤ D) extends reflects_colimit K F :=
(lifts : Π c, is_colimit c → liftable_cocone K F c)
/--
`F` creates colimits of shape `J` if `F` creates the colimit of any diagram
`K : J ⥤ C`.
-/
class creates_colimits_of_shape (J : Type v) [small_category J] (F : C ⥤ D) :=
(creates_colimit : Π {K : J ⥤ C}, creates_colimit K F)
/-- `F` creates colimits if it creates colimits of shape `J` for any small `J`. -/
class creates_colimits (F : C ⥤ D) :=
(creates_colimits_of_shape : Π {J : Type v} {𝒥 : small_category J},
by exactI creates_colimits_of_shape J F)
attribute [instance, priority 100] -- see Note [lower instance priority]
creates_limits_of_shape.creates_limit creates_limits.creates_limits_of_shape
creates_colimits_of_shape.creates_colimit creates_colimits.creates_colimits_of_shape
/- Interface to the `creates_limit` class. -/
/-- `lift_limit t` is the cone for `K` given by lifting the limit `t` for `K ⋙ F`. -/
def lift_limit {K : J ⥤ C} {F : C ⥤ D} [creates_limit K F] {c : cone (K ⋙ F)} (t : is_limit c) :
cone K :=
(creates_limit.lifts c t).lifted_cone
/-- The lifted cone has an image isomorphic to the original cone. -/
def lifted_limit_maps_to_original {K : J ⥤ C} {F : C ⥤ D}
[creates_limit K F] {c : cone (K ⋙ F)} (t : is_limit c) :
F.map_cone (lift_limit t) ≅ c :=
(creates_limit.lifts c t).valid_lift
/-- The lifted cone is a limit. -/
def lifted_limit_is_limit {K : J ⥤ C} {F : C ⥤ D}
[creates_limit K F] {c : cone (K ⋙ F)} (t : is_limit c) :
is_limit (lift_limit t) :=
reflects_limit.reflects (is_limit.of_iso_limit t (lifted_limit_maps_to_original t).symm)
/-- If `F` creates the limit of `K` and `K ⋙ F` has a limit, then `K` has a limit. -/
def has_limit_of_created (K : J ⥤ C) (F : C ⥤ D)
[has_limit (K ⋙ F)] [creates_limit K F] : has_limit K :=
{ cone := lift_limit (limit.is_limit (K ⋙ F)),
is_limit := lifted_limit_is_limit _ }
/- Interface to the `creates_colimit` class. -/
/-- `lift_colimit t` is the cocone for `K` given by lifting the colimit `t` for `K ⋙ F`. -/
def lift_colimit {K : J ⥤ C} {F : C ⥤ D} [creates_colimit K F] {c : cocone (K ⋙ F)} (t : is_colimit c) :
cocone K :=
(creates_colimit.lifts c t).lifted_cocone
/-- The lifted cocone has an image isomorphic to the original cocone. -/
def lifted_colimit_maps_to_original {K : J ⥤ C} {F : C ⥤ D}
[creates_colimit K F] {c : cocone (K ⋙ F)} (t : is_colimit c) :
F.map_cocone (lift_colimit t) ≅ c :=
(creates_colimit.lifts c t).valid_lift
/-- The lifted cocone is a colimit. -/
def lifted_colimit_is_colimit {K : J ⥤ C} {F : C ⥤ D}
[creates_colimit K F] {c : cocone (K ⋙ F)} (t : is_colimit c) :
is_colimit (lift_colimit t) :=
reflects_colimit.reflects (is_colimit.of_iso_colimit t (lifted_colimit_maps_to_original t).symm)
/-- If `F` creates the limit of `K` and `K ⋙ F` has a limit, then `K` has a limit. -/
def has_colimit_of_created (K : J ⥤ C) (F : C ⥤ D)
[has_colimit (K ⋙ F)] [creates_colimit K F] : has_colimit K :=
{ cocone := lift_colimit (colimit.is_colimit (K ⋙ F)),
is_colimit := lifted_colimit_is_colimit _ }
/--
A helper to show a functor creates limits. In particular, if we can show
that for any limit cone `c` for `K ⋙ F`, there is a lift of it which is
a limit and `F` reflects isomorphisms, then `F` creates limits.
Usually, `F` creating limits says that _any_ lift of `c` is a limit, but
here we only need to show that our particular lift of `c` is a limit.
-/
structure lifts_to_limit (K : J ⥤ C) (F : C ⥤ D) (c : cone (K ⋙ F)) (t : is_limit c)
extends liftable_cone K F c :=
(makes_limit : is_limit lifted_cone)
/--
A helper to show a functor creates colimits. In particular, if we can show
that for any limit cocone `c` for `K ⋙ F`, there is a lift of it which is
a limit and `F` reflects isomorphisms, then `F` creates colimits.
Usually, `F` creating colimits says that _any_ lift of `c` is a colimit, but
here we only need to show that our particular lift of `c` is a colimit.
-/
structure lifts_to_colimit (K : J ⥤ C) (F : C ⥤ D) (c : cocone (K ⋙ F)) (t : is_colimit c)
extends liftable_cocone K F c :=
(makes_colimit : is_colimit lifted_cocone)
/--
If `F` reflects isomorphisms and we can lift any limit cone to a limit cone,
then `F` creates limits.
In particular here we don't need to assume that F reflects limits.
-/
def creates_limit_of_reflects_iso {K : J ⥤ C} {F : C ⥤ D} [reflects_isomorphisms F]
(h : Π c t, lifts_to_limit K F c t) :
creates_limit K F :=
{ lifts := λ c t, (h c t).to_liftable_cone,
to_reflects_limit :=
{ reflects := λ (d : cone K) (hd : is_limit (F.map_cone d)),
begin
let d' : cone K := (h (F.map_cone d) hd).to_liftable_cone.lifted_cone,
let i : F.map_cone d' ≅ F.map_cone d := (h (F.map_cone d) hd).to_liftable_cone.valid_lift,
let hd' : is_limit d' := (h (F.map_cone d) hd).makes_limit,
let f : d ⟶ d' := hd'.lift_cone_morphism d,
have : (cones.functoriality K F).map f = i.inv := (hd.of_iso_limit i.symm).uniq_cone_morphism,
haveI : is_iso ((cones.functoriality K F).map f) := (by { rw this, apply_instance }),
haveI : is_iso f := is_iso_of_reflects_iso f (cones.functoriality K F),
exact is_limit.of_iso_limit hd' (as_iso f).symm,
end } }
/-- `F` preserves the limit of `K` if it creates the limit and `K ⋙ F` has the limit. -/
instance preserves_limit_of_creates_limit_and_has_limit (K : J ⥤ C) (F : C ⥤ D)
[creates_limit K F] [has_limit (K ⋙ F)] :
preserves_limit K F :=
{ preserves := λ c t, is_limit.of_iso_limit (limit.is_limit _)
((lifted_limit_maps_to_original (limit.is_limit _)).symm ≪≫
((cones.functoriality K F).map_iso ((lifted_limit_is_limit (limit.is_limit _)).unique_up_to_iso t))) }
/-- `F` preserves the limit of shape `J` if it creates these limits and `D` has them. -/
instance preserves_limit_of_shape_of_creates_limits_of_shape_and_has_limits_of_shape (F : C ⥤ D)
[creates_limits_of_shape J F] [has_limits_of_shape J D] :
preserves_limits_of_shape J F :=
{ preserves_limit := λ K, category_theory.preserves_limit_of_creates_limit_and_has_limit K F }
/-- `F` preserves limits if it creates limits and `D` has limits. -/
instance preserves_limits_of_creates_limits_and_has_limits (F : C ⥤ D) [creates_limits F] [has_limits.{v} D] :
preserves_limits F :=
{ preserves_limits_of_shape := λ J 𝒥,
by exactI category_theory.preserves_limit_of_shape_of_creates_limits_of_shape_and_has_limits_of_shape F }
/--
If `F` reflects isomorphisms and we can lift any limit cocone to a limit cocone,
then `F` creates colimits.
In particular here we don't need to assume that F reflects colimits.
-/
def creates_colimit_of_reflects_iso {K : J ⥤ C} {F : C ⥤ D} [reflects_isomorphisms F]
(h : Π c t, lifts_to_colimit K F c t) :
creates_colimit K F :=
{ lifts := λ c t, (h c t).to_liftable_cocone,
to_reflects_colimit :=
{ reflects := λ (d : cocone K) (hd : is_colimit (F.map_cocone d)),
begin
let d' : cocone K := (h (F.map_cocone d) hd).to_liftable_cocone.lifted_cocone,
let i : F.map_cocone d' ≅ F.map_cocone d := (h (F.map_cocone d) hd).to_liftable_cocone.valid_lift,
let hd' : is_colimit d' := (h (F.map_cocone d) hd).makes_colimit,
let f : d' ⟶ d := hd'.desc_cocone_morphism d,
have : (cocones.functoriality K F).map f = i.hom := (hd.of_iso_colimit i.symm).uniq_cocone_morphism,
haveI : is_iso ((cocones.functoriality K F).map f) := (by { rw this, apply_instance }),
haveI := is_iso_of_reflects_iso f (cocones.functoriality K F),
exact is_colimit.of_iso_colimit hd' (as_iso f),
end } }
/-- `F` preserves the colimit of `K` if it creates the colimit and `K ⋙ F` has the colimit. -/
instance preserves_colimit_of_creates_colimit_and_has_colimit (K : J ⥤ C) (F : C ⥤ D)
[creates_colimit K F] [has_colimit (K ⋙ F)] :
preserves_colimit K F :=
{ preserves := λ c t, is_colimit.of_iso_colimit (colimit.is_colimit _)
((lifted_colimit_maps_to_original (colimit.is_colimit _)).symm ≪≫
((cocones.functoriality K F).map_iso ((lifted_colimit_is_colimit (colimit.is_colimit _)).unique_up_to_iso t))) }
/-- `F` preserves the colimit of shape `J` if it creates these colimits and `D` has them. -/
instance preserves_colimit_of_shape_of_creates_colimits_of_shape_and_has_colimits_of_shape (F : C ⥤ D)
[creates_colimits_of_shape J F] [has_colimits_of_shape J D] :
preserves_colimits_of_shape J F :=
{ preserves_colimit := λ K, category_theory.preserves_colimit_of_creates_colimit_and_has_colimit K F }
/-- `F` preserves limits if it creates limits and `D` has limits. -/
instance preserves_colimits_of_creates_colimits_and_has_colimits (F : C ⥤ D) [creates_colimits F] [has_colimits.{v} D] :
preserves_colimits F :=
{ preserves_colimits_of_shape := λ J 𝒥,
by exactI category_theory.preserves_colimit_of_shape_of_creates_colimits_of_shape_and_has_colimits_of_shape F }
-- For the inhabited linter later.
/-- If F creates the limit of K, any cone lifts to a limit. -/
def lifts_to_limit_of_creates (K : J ⥤ C) (F : C ⥤ D)
[creates_limit K F] (c : cone (K ⋙ F)) (t : is_limit c) :
lifts_to_limit K F c t :=
{ lifted_cone := lift_limit t,
valid_lift := lifted_limit_maps_to_original t,
makes_limit := lifted_limit_is_limit t }
-- For the inhabited linter later.
/-- If F creates the colimit of K, any cocone lifts to a colimit. -/
def lifts_to_colimit_of_creates (K : J ⥤ C) (F : C ⥤ D)
[creates_colimit K F] (c : cocone (K ⋙ F)) (t : is_colimit c) :
lifts_to_colimit K F c t :=
{ lifted_cocone := lift_colimit t,
valid_lift := lifted_colimit_maps_to_original t,
makes_colimit := lifted_colimit_is_colimit t }
/-- Any cone lifts through the identity functor. -/
def id_lifts_cone (c : cone (K ⋙ 𝟭 C)) : liftable_cone K (𝟭 C) c :=
{ lifted_cone :=
{ X := c.X,
π := c.π ≫ K.right_unitor.hom },
valid_lift := cones.ext (iso.refl _) (by tidy) }
/-- The identity functor creates all limits. -/
instance id_creates_limits : creates_limits (𝟭 C) :=
{ creates_limits_of_shape := λ J 𝒥, by exactI
{ creates_limit := λ F, { lifts := λ c t, id_lifts_cone c } } }
/-- Any cocone lifts through the identity functor. -/
def id_lifts_cocone (c : cocone (K ⋙ 𝟭 C)) : liftable_cocone K (𝟭 C) c :=
{ lifted_cocone :=
{ X := c.X,
ι := K.right_unitor.inv ≫ c.ι },
valid_lift := cocones.ext (iso.refl _) (by tidy) }
/-- The identity functor creates all colimits. -/
instance id_creates_colimits : creates_colimits (𝟭 C) :=
{ creates_colimits_of_shape := λ J 𝒥, by exactI
{ creates_colimit := λ F, { lifts := λ c t, id_lifts_cocone c } } }
/-- Satisfy the inhabited linter -/
instance inhabited_liftable_cone (c : cone (K ⋙ 𝟭 C)) : inhabited (liftable_cone K (𝟭 C) c) :=
⟨id_lifts_cone c⟩
instance inhabited_liftable_cocone (c : cocone (K ⋙ 𝟭 C)) : inhabited (liftable_cocone K (𝟭 C) c) :=
⟨id_lifts_cocone c⟩
/-- Satisfy the inhabited linter -/
instance inhabited_lifts_to_limit (K : J ⥤ C) (F : C ⥤ D)
[creates_limit K F] (c : cone (K ⋙ F)) (t : is_limit c) :
inhabited (lifts_to_limit _ _ _ t) :=
⟨lifts_to_limit_of_creates K F c t⟩
instance inhabited_lifts_to_colimit (K : J ⥤ C) (F : C ⥤ D)
[creates_colimit K F] (c : cocone (K ⋙ F)) (t : is_colimit c) :
inhabited (lifts_to_colimit _ _ _ t) :=
⟨lifts_to_colimit_of_creates K F c t⟩
section comp
variables {E : Type u₃} [ℰ : category.{v} E]
variables (F : C ⥤ D) (G : D ⥤ E)
instance comp_creates_limit [i₁ : creates_limit K F] [i₂ : creates_limit (K ⋙ F) G] :
creates_limit K (F ⋙ G) :=
{ lifts := λ c t,
{ lifted_cone := lift_limit (lifted_limit_is_limit t),
valid_lift := (cones.functoriality (K ⋙ F) G).map_iso
(lifted_limit_maps_to_original (lifted_limit_is_limit t)) ≪≫
(lifted_limit_maps_to_original t),
} }
end comp
end creates
end category_theory
|
d6ca23c74271d423aab9500e1f5cb23373ab86ae | a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91 | /library/smt/prove.lean | e97b62059c7b4b6359b982eb5e9410b0fbc75c63 | [
"Apache-2.0"
] | permissive | soonhokong/lean-osx | 4a954262c780e404c1369d6c06516161d07fcb40 | 3670278342d2f4faa49d95b46d86642d7875b47c | refs/heads/master | 1,611,410,334,552 | 1,474,425,686,000 | 1,474,425,686,000 | 12,043,103 | 5 | 1 | null | null | null | null | UTF-8 | Lean | false | false | 390 | lean | namespace smt
open tactic
private meta_definition collect_props : list expr → tactic (list expr)
| [] := return []
| (H :: Hs) := do
Eqs ← collect_props Hs,
Htype ← infer_type H >>= whnf,
return $ if Htype = expr.prop then H :: Eqs else Eqs
meta_definition prove : tactic unit :=
do local_context >>= collect_props >>= revert_lst,
simplify_goal failed []
end smt
|
b10a22cb7edd819e94248326c24b79fefe1162fb | 957a80ea22c5abb4f4670b250d55534d9db99108 | /tests/lean/run/bug6.lean | 6e58b339d16dc074aaed99eb9dbb4cc53d46311a | [
"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 | 322 | lean | open eq
section
variable {A : Type}
theorem T {a b : A} (H : a = b) : b = a
:= symm H
variables x y : A
variable H : x = y
#check T H
#check T
end
section
variable {A : Type}
theorem T2 ⦃a b : A⦄ (H : a = b) : b = a
:= symm H
variables x y : A
variable H : x = y
#check T2 H
#check T2
end
|
e126efd3e5139360767b1c1bfb3e4aa5ed0fe6bb | 8930e38ac0fae2e5e55c28d0577a8e44e2639a6d | /data/semiquot.lean | fcea78e267a4c584af36e712f3347e7bbd15ce51 | [
"Apache-2.0"
] | permissive | SG4316/mathlib | 3d64035d02a97f8556ad9ff249a81a0a51a3321a | a7846022507b531a8ab53b8af8a91953fceafd3a | refs/heads/master | 1,584,869,960,527 | 1,530,718,645,000 | 1,530,724,110,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 6,938 | lean | /-
Copyright (c) 2018 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro
A data type for semiquotients, which are classically equivalent to
nonempty sets, but are useful for programming; the idea is that
a semiquotient set `S` represents some (particular but unknown)
element of `S`. This can be used to model nondeterministic functions,
which return something in a range of values (represented by the
predicate `S`) but are not completely determined.
-/
import data.set.lattice data.quot
/-- A member of `semiquot α` is classically a nonempty `set α`,
and in the VM is represented by an element of `α`; the relation
between these is that the VM element is required to be a member
of the set `s`. The specific element of `s` that the VM computes
is hidden by a quotient construction, allowing for the representation
of nondeterministic functions. -/
structure {u} semiquot (α : Type*) := mk' ::
(s : set α)
(val : trunc ↥s)
namespace semiquot
variables {α : Type*} {β : Type*}
instance : has_mem α (semiquot α) := ⟨λ a q, a ∈ q.s⟩
def mk {a : α} {s : set α} (h : a ∈ s) : semiquot α :=
⟨s, trunc.mk ⟨a, h⟩⟩
theorem ext_s {q₁ q₂ : semiquot α} : q₁ = q₂ ↔ q₁.s = q₂.s :=
⟨congr_arg _,
λ h, by cases q₁; cases q₂; congr; exact h⟩
theorem ext {q₁ q₂ : semiquot α} : q₁ = q₂ ↔ ∀ a, a ∈ q₁ ↔ a ∈ q₂ :=
ext_s.trans (set.set_eq_def _ _)
theorem exists_mem (q : semiquot α) : ∃ a, a ∈ q :=
let ⟨⟨a, h⟩, h₂⟩ := q.2.exists_rep in ⟨a, h⟩
theorem eq_mk_of_mem {q : semiquot α} {a : α} (h : a ∈ q) :
q = @mk _ a q.1 h := ext_s.2 rfl
theorem ne_empty (q : semiquot α) : q.s ≠ ∅ :=
let ⟨a, h⟩ := q.exists_mem in set.ne_empty_of_mem h
protected def pure (a : α) : semiquot α := mk (set.mem_singleton a)
@[simp] theorem mem_pure' {a b : α} : a ∈ semiquot.pure b ↔ a = b :=
set.mem_singleton_iff
def blur' (q : semiquot α) {s : set α} (h : q.s ⊆ s) : semiquot α :=
⟨s, trunc.lift (λ a : q.s, trunc.mk ⟨a.1, h a.2⟩)
(λ _ _, trunc.eq _ _) q.2⟩
def blur (s : set α) (q : semiquot α) : semiquot α :=
blur' q (set.subset_union_right s q.s)
theorem blur_eq_blur' (q : semiquot α) (s : set α) (h : q.s ⊆ s) :
blur s q = blur' q h :=
by unfold blur; congr; exact set.union_eq_self_of_subset_right h
@[simp] theorem mem_blur' (q : semiquot α) {s : set α} (h : q.s ⊆ s)
{a : α} : a ∈ blur' q h ↔ a ∈ s := iff.rfl
def of_trunc (q : trunc α) : semiquot α :=
⟨set.univ, q.map (λ a, ⟨a, trivial⟩)⟩
def to_trunc (q : semiquot α) : trunc α :=
q.2.map subtype.val
def lift_on (q : semiquot α) (f : α → β) (h : ∀ a b ∈ q, f a = f b) : β :=
trunc.lift_on q.2 (λ x, f x.1) (λ x y, h _ _ x.2 y.2)
theorem lift_on_of_mem (q : semiquot α)
(f : α → β) (h : ∀ a b ∈ q, f a = f b)
(a : α) (aq : a ∈ q) : lift_on q f h = f a :=
by revert h; rw eq_mk_of_mem aq; intro; refl
def map (f : α → β) (q : semiquot α) : semiquot β :=
⟨f '' q.1, q.2.map (λ x, ⟨f x.1, set.mem_image_of_mem _ x.2⟩)⟩
@[simp] theorem mem_map (f : α → β) (q : semiquot α) (b : β) :
b ∈ map f q ↔ ∃ a, a ∈ q ∧ f a = b := set.mem_image _ _ _
def bind (q : semiquot α) (f : α → semiquot β) : semiquot β :=
⟨⋃ a ∈ q.1, (f a).1,
q.2.bind (λ a, (f a.1).2.map (λ b, ⟨b.1, set.mem_bUnion a.2 b.2⟩))⟩
@[simp] theorem mem_bind (q : semiquot α) (f : α → semiquot β) (b : β) :
b ∈ bind q f ↔ ∃ a, a ∈ q ∧ b ∈ f a := set.mem_bUnion_iff
instance : monad semiquot :=
{ pure := @semiquot.pure,
map := @semiquot.map,
bind := @semiquot.bind }
@[simp] theorem mem_pure {a b : α} : a ∈ (pure b : semiquot α) ↔ a = b :=
set.mem_singleton_iff
theorem mem_pure_self (a : α) : a ∈ (pure a : semiquot α) :=
set.mem_singleton a
@[simp] theorem pure_inj {a b : α} : (pure a : semiquot α) = pure b ↔ a = b :=
ext_s.trans set.singleton_eq_singleton_iff
instance : is_lawful_monad semiquot :=
{ pure_bind := λ α β x f, ext.2 $ by simp,
bind_assoc := λ α β γ s f g, ext.2 $ by simp; exact
λ c, ⟨λ ⟨b, ⟨a, as, bf⟩, cg⟩, ⟨a, as, b, bf, cg⟩,
λ ⟨a, as, b, bf, cg⟩, ⟨b, ⟨a, as, bf⟩, cg⟩⟩,
id_map := λ α q, ext.2 $ by simp,
bind_pure_comp_eq_map := λ α β f s, ext.2 $ by simp [eq_comm] }
instance : has_le (semiquot α) := ⟨λ s t, s.s ⊆ t.s⟩
instance : partial_order (semiquot α) :=
{ le := λ s t, ∀ ⦃x⦄, x ∈ s → x ∈ t,
le_refl := λ s, set.subset.refl _,
le_trans := λ s t u, set.subset.trans,
le_antisymm := λ s t h₁ h₂, ext_s.2 (set.subset.antisymm h₁ h₂) }
instance : lattice.semilattice_sup (semiquot α) :=
{ sup := λ s, blur s.s,
le_sup_left := λ s t, set.subset_union_left _ _,
le_sup_right := λ s t, set.subset_union_right _ _,
sup_le := λ s t u, set.union_subset,
..semiquot.partial_order }
@[simp] theorem pure_le {a : α} {s : semiquot α} : pure a ≤ s ↔ a ∈ s :=
set.singleton_subset_iff
def is_pure (q : semiquot α) := ∀ a b ∈ q, a = b
def get (q) (h : @is_pure α q) : α := lift_on q id h
theorem get_mem {q : semiquot α} (p) : get q p ∈ q :=
let ⟨a, h⟩ := exists_mem q in
by unfold get; rw lift_on_of_mem q _ _ a h; exact h
theorem eq_pure {q : semiquot α} (p) : q = pure (get q p) :=
ext.2 $ λ a, by simp; exact
⟨λ h, p _ _ h (get_mem _), λ e, e.symm ▸ get_mem _⟩
@[simp] theorem pure_is_pure (a : α) : is_pure (pure a)
| b c ab ac := by simp at *; cc
theorem is_pure_iff {s : semiquot α} : is_pure s ↔ ∃ a, s = pure a :=
⟨λ h, ⟨_, eq_pure h⟩, λ ⟨a, e⟩, e.symm ▸ pure_is_pure _⟩
theorem is_pure.mono {s t : semiquot α}
(st : s ≤ t) (h : is_pure t) : is_pure s
| a b as bs := h _ _ (st as) (st bs)
theorem is_pure.min {s t : semiquot α} (h : is_pure t) : s ≤ t ↔ s = t :=
⟨λ st, le_antisymm st $ by rw [eq_pure h, eq_pure (h.mono st)]; simp;
exact h _ _ (get_mem _) (st $ get_mem _),
le_of_eq⟩
theorem is_pure_of_subsingleton [subsingleton α] (q : semiquot α) : is_pure q
| a b aq bq := subsingleton.elim _ _
def univ [inhabited α] : semiquot α :=
mk $ set.mem_univ (default _)
@[simp] theorem mem_univ [inhabited α] : ∀ a, a ∈ @univ α _ :=
@set.mem_univ α
@[congr] theorem univ_unique (I J : inhabited α) : @univ _ I = @univ _ J :=
ext.2 $ by simp
@[simp] theorem is_pure_univ [inhabited α] : @is_pure α univ ↔ subsingleton α :=
⟨λ h, ⟨λ a b, h a b trivial trivial⟩, λ ⟨h⟩ a b _ _, h a b⟩
instance [inhabited α] : lattice.order_top (semiquot α) :=
{ top := univ,
le_top := λ s, set.subset_univ _,
..semiquot.partial_order }
instance [inhabited α] : lattice.semilattice_sup_top (semiquot α) :=
{ ..semiquot.lattice.order_top,
..semiquot.lattice.semilattice_sup }
end semiquot
|
2f65ecf265dd3728881fd894ebf0296579e50c67 | 3446e92e64a5de7ed1f2109cfb024f83cd904c34 | /src/game/world3/level13.lean | 9e9afd806cdeac299def25a3c685f358ea4313bf | [] | no_license | kckennylau/natural_number_game | 019f4a5f419c9681e65234ecd124c564f9a0a246 | ad8c0adaa725975be8a9f978c8494a39311029be | refs/heads/master | 1,598,784,137,722 | 1,571,905,156,000 | 1,571,905,156,000 | 218,354,686 | 0 | 0 | null | 1,572,373,319,000 | 1,572,373,318,000 | null | UTF-8 | Lean | false | false | 869 | lean | import game.world3.level12 -- hide
import game.world2.level13 -- add_left_eq_zero -- hide
namespace mynat -- hide
/-
# Multiplication World
## Level 13: `mul_right_comm`
This is the last of the bonus multiplication levels.
`mul_right_comm` will be useful in power world.
The proof is basically the same as `add_right_comm`.
See how few lines you can do it in.
-/
/- Theorem
For all $a$, $b$, $c$ natural numbers, $(a * b) * c = (a * c) * b$.
-/
theorem mul_right_comm (a b c : mynat) : a * b * c = a * c * b :=
begin [less_leaky]
rw mul_assoc,
rw mul_comm b,
rw mul_assoc,
refl,
end
/- To come: Powers! Inequalities! Odd and even numbers! Congruences!
Prime numbers! And any other mathematics with the natural numbers that anyone can think of.
Suggestions welcome to k.buzzard@imperial.ac.uk or find me on the Lean chat at Zulip.
-/
end mynat -- hide
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.