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
6acc166a8836cecd420c8f43c2178aeb876467f7
d8f6c47921aa2f4f02b5272d2ed9c99f396d3858
/lean/src/bv/basic.lean
de780f1054865cd0e19566b1eb62c804f3cdc698
[]
no_license
hongyunnchen/jitterbug
cc94e01483cdb36f9007ab978f174e5df9a65fd2
eb5d50ef17f78c430f9033ff18472972b3588aee
refs/heads/master
1,670,909,198,044
1,599,154,934,000
1,599,154,934,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
6,680
lean
import data.fin import data.fintype.basic import tactic.omega.main /-! # Fixed-size bitvectors This file defines fixed-sized bitvectors following the SMT-LIB standard. ## References * http://smtlib.cs.uiowa.edu/Theories/FixedSizeBitVectors.smt2 * http://smtlib.cs.uiowa.edu/Logics/QF_BV.smt2 -/ /-- The type of bitvectors. -/ def bv (n : ℕ) := fin n → bool namespace bv section fin variable {n : ℕ} def nil : bv 0 := fin.elim0 instance nil_unique : unique (bv 0) := fin.tuple0_unique _ def cons (b : bool) (v : bv n) : bv (n + 1) := fin.cons b v def snoc (v : bv n) (b : bool) : bv (n + 1) := fin.snoc v b def init (v : bv (n + 1)) : bv n := fin.init v def tail (v : bv (n + 1)) : bv n := fin.tail v def lsb (v : bv (n + 1)) : bool := v 0 def msb (v : bv (n + 1)) : bool := v (fin.last n) instance : decidable_eq (bv n) := fintype.decidable_pi_fintype instance : fintype (bv n) := pi.fintype instance : inhabited (bv n) := pi.inhabited _ end fin section list variable {n : ℕ} def to_list {n : ℕ} (v : bv n) : list bool := list.of_fn v instance bv_to_list : has_coe (bv n) (list bool) := ⟨to_list⟩ end list section nat variable {n : ℕ} def of_nat : Π {n : ℕ}, ℕ → bv n | 0 _ := nil | (_ + 1) a := cons a.bodd (of_nat a.div2) def to_nat : Π {n : ℕ}, bv n → ℕ | 0 _ := 0 | (_ + 1) v := nat.bit v.lsb v.tail.to_nat instance bv_to_nat : has_coe (bv n) ℕ := ⟨to_nat⟩ def of_int (a : ℤ) : bv n := bv.of_nat (a % (2^n)).to_nat def to_int (v : bv n) : ℤ := if (v : ℕ) < 2^(n - 1) then (v : ℕ) else (v : ℕ) - 2^n end nat section literals variable {n : ℕ} protected def zero : bv n := λ _, ff instance : has_zero (bv n) := ⟨bv.zero⟩ protected def umax : bv n := λ _, tt protected def one : Π {n : ℕ}, bv n | 0 := nil | (n + 1) := cons tt 0 instance : has_one (bv n) := ⟨bv.one⟩ protected def smin : Π {n : ℕ}, bv n | 0 := nil | (n + 1) := bv.zero.snoc tt protected def smax : Π {n : ℕ}, bv n | 0 := nil | (n + 1) := bv.umax.snoc ff end literals section concatenation def concat {n₁ n₂ : ℕ} (v₁ : bv n₁) (v₂ : bv n₂) : bv (n₁ + n₂) := λ ⟨i, h₁⟩, if h₂ : i < n₂ then v₂ ⟨i, h₂⟩ else v₁ ⟨i - n₂, by omega⟩ def zero_extend {n : ℕ} (i : ℕ) (v : bv n) : bv (i + n) := concat 0 v def sign_extend {n : ℕ} (i : ℕ) (v : bv (n + 1)) : bv (i + (n + 1)) := concat (λ _, v.msb) v end concatenation section extraction def extract {n : ℕ} (i j : ℕ) (h₁ : i < n) (h₂ : j ≤ i) (v : bv n) : bv (i - j + 1) := λ ⟨x, h⟩, v ⟨j + x, by omega⟩ def drop {n₁ : ℕ} (n₂ : ℕ) (v : bv (n₁ + n₂)) : bv n₁ := λ ⟨x, h⟩, v ⟨n₂ + x, by omega⟩ def take {n₁ : ℕ} (n₂ : ℕ) (v : bv (n₁ + n₂)) : bv n₂ := λ ⟨x, h⟩, v ⟨x, by omega⟩ end extraction section bitwise variable {n : ℕ} def map (f : bool → bool) (v : bv n) : bv n := λ i, f (v i) def map₂ (f : bool → bool → bool) (v₁ v₂ : bv n) : bv n := λ i, f (v₁ i) (v₂ i) protected def not : bv n → bv n := map bnot protected def and : bv n → bv n → bv n := map₂ band protected def or : bv n → bv n → bv n := map₂ bor protected def xor : bv n → bv n → bv n := map₂ bxor end bitwise section arithmetic variable {n : ℕ} protected def neg (v : bv n) : bv n := of_nat (2^n - (v : ℕ)) instance : has_neg (bv n) := ⟨bv.neg⟩ protected def add (v₁ v₂ : bv n) : bv n := of_nat ((v₁ : ℕ) + (v₂ : ℕ)) instance : has_add (bv n) := ⟨bv.add⟩ protected def sub (v₁ v₂ : bv n) : bv n := v₁ + (-v₂) instance : has_sub (bv n) := ⟨bv.sub⟩ protected def mul (v₁ v₂ : bv n) : bv n := of_nat ((v₁ : ℕ) * (v₂ : ℕ)) instance : has_mul (bv n) := ⟨bv.mul⟩ protected def udiv (v₁ v₂ : bv n) : bv n := if (v₂ : ℕ) = 0 then bv.umax else of_nat ((v₁ : ℕ) / (v₂ : ℕ)) instance : has_div (bv n) := ⟨bv.udiv⟩ protected def urem (v₁ v₂ : bv n) : bv n := if (v₂ : ℕ) = 0 then v₁ else of_nat ((v₁ : ℕ) % (v₂ : ℕ)) instance : has_mod (bv n) := ⟨bv.urem⟩ end arithmetic section shift variable {n : ℕ} def shl (v₁ v₂ : bv n) : bv n := of_nat ((v₁ : ℕ) * 2^(v₂ : ℕ)) def lshr (v₁ v₂ : bv n) : bv n := of_nat ((v₁ : ℕ) / 2^(v₂ : ℕ)) def ashr (v₁ v₂ : bv (n + 1)) : bv (n + 1) := match v₁.msb with | ff := v₁.lshr v₂ | tt := (v₁.not.lshr v₂).not end end shift section comparison variable {n : ℕ} protected def ult (v₁ v₂ : bv n) : Prop := (v₁ : ℕ) < (v₂ : ℕ) instance : has_lt (bv n) := ⟨bv.ult⟩ protected def ule (v₁ v₂ : bv n) : Prop := v₁ < v₂ ∨ v₁ = v₂ instance : has_le (bv n) := ⟨bv.ule⟩ @[reducible] protected def ugt (v₁ v₂ : bv n) : Prop := v₂ < v₁ @[reducible] protected def uge (v₁ v₂ : bv n) : Prop := v₂ < v₁ ∨ v₁ = v₂ instance decidable_ult : @decidable_rel (bv n) bv.ult := λ _ _, by dsimp [bv.ult]; apply_instance instance decidable_ule : @decidable_rel (bv n) bv.ule := λ _ _, by dsimp [bv.ule]; apply_instance protected def slt (v₁ v₂ : bv (n + 1)) : Prop := (v₁.msb = tt ∧ v₂.msb = ff) ∨ (v₁.msb = v₂.msb ∧ v₁ < v₂) protected def sle (v₁ v₂ : bv (n + 1)) : Prop := (v₁.msb = tt ∧ v₂.msb = ff) ∨ (v₁.msb = v₂.msb ∧ v₁ ≤ v₂) @[reducible] protected def sgt (v₁ v₂ : bv (n + 1)) : Prop := v₂.slt v₁ @[reducible] protected def sge (v₁ v₂ : bv (n + 1)) : Prop := v₂.sle v₁ instance decidable_slt : @decidable_rel (bv (n + 1)) bv.slt := λ _ _, by dsimp [bv.slt]; apply_instance instance decidable_sle : @decidable_rel (bv (n + 1)) bv.sle := λ _ _, by dsimp [bv.sle]; apply_instance end comparison private def bin_repr : Π {n : ℕ}, bv n → string | 0 _ := "" | (n + 1) v := bin_repr v.tail ++ cond v.lsb "1" "0" private def hex_repr : Π {n : ℕ} (h : 4 ∣ n), bv n → string | 0 _ _ := "" | 1 h _ := absurd h dec_trivial | 2 h _ := absurd h dec_trivial | 3 h _ := absurd h dec_trivial | (n + 4) h v := hex_repr (nat.dvd_add_self_right.mp h) (v.drop 4) ++ [(v.take 4 : ℕ).digit_char].as_string private def repr {n : ℕ} (v : bv n) : string := if h : 4 ∣ n then "#x" ++ hex_repr h v else "#b" ++ bin_repr v instance {n : ℕ} : has_repr (bv n) := ⟨repr⟩ end bv
8c6aef20fb5bc2db9dc06e218cbe816a57f1d78e
a7eef317ddec01b9fc6cfbb876fe7ac00f205ac7
/src/algebra/pointwise.lean
8477da68cdeab8172f6c7913f57801d6d2285523
[ "Apache-2.0" ]
permissive
kmill/mathlib
ea5a007b67ae4e9e18dd50d31d8aa60f650425ee
1a419a9fea7b959317eddd556e1bb9639f4dcc05
refs/heads/master
1,668,578,197,719
1,593,629,163,000
1,593,629,163,000
276,482,939
0
0
null
1,593,637,960,000
1,593,637,959,000
null
UTF-8
Lean
false
false
12,439
lean
/- Copyright (c) 2019 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin -/ import algebra.module /-! # Pointwise addition, multiplication, and scalar multiplication of sets. This file defines `pointwise_mul`: for a type `α` with multiplication, multiplication is defined on `set α` by taking `s * t` to be the set of all `x * y` where `x ∈ s` and `y ∈ t`. Pointwise multiplication on `set α` where `α` is a semigroup makes `set α` into a semigroup. If `α` is additionally a (commutative) monoid, `set α` becomes a (commutative) semiring with union as addition. These are given by `pointwise_mul_semigroup` and `pointwise_mul_semiring`. Definitions and results are also transported to the additive theory via `to_additive`. For a type `β` with scalar multiplication by another type `α`, this file defines `pointwise_smul`. Separately it defines `smul_set`, for scalar multiplication of `set β` by a single term of type `α`. ## Implementation notes Elsewhere, one should register local instances to use the definitions in this file. -/ namespace set open function variables {α : Type*} {β : Type*} (f : α → β) @[to_additive] def pointwise_one [has_one α] : has_one (set α) := ⟨{1}⟩ local attribute [instance] pointwise_one @[simp, to_additive] lemma mem_pointwise_one [has_one α] (a : α) : a ∈ (1 : set α) ↔ a = 1 := mem_singleton_iff @[to_additive] def pointwise_mul [has_mul α] : has_mul (set α) := ⟨λ s t, {a | ∃ x ∈ s, ∃ y ∈ t, a = x * y}⟩ local attribute [instance] pointwise_one pointwise_mul pointwise_add @[to_additive] lemma mem_pointwise_mul [has_mul α] {s t : set α} {a : α} : a ∈ s * t ↔ ∃ x ∈ s, ∃ y ∈ t, a = x * y := iff.rfl @[to_additive] lemma mul_mem_pointwise_mul [has_mul α] {s t : set α} {a b : α} (ha : a ∈ s) (hb : b ∈ t) : a * b ∈ s * t := ⟨_, ha, _, hb, rfl⟩ @[to_additive] lemma pointwise_mul_eq_image [has_mul α] {s t : set α} : s * t = (λ x : α × α, x.fst * x.snd) '' s.prod t := set.ext $ λ a, ⟨ by { rintros ⟨_, _, _, _, rfl⟩, exact ⟨(_, _), mem_prod.mpr ⟨‹_›, ‹_›⟩, rfl⟩ }, by { rintros ⟨_, _, rfl⟩, exact ⟨_, (mem_prod.mp ‹_›).1, _, (mem_prod.mp ‹_›).2, rfl⟩ }⟩ @[to_additive] lemma pointwise_mul_finite [has_mul α] {s t : set α} (hs : finite s) (ht : finite t) : finite (s * t) := by { rw pointwise_mul_eq_image, exact (hs.prod ht).image _ } @[to_additive pointwise_add_add_semigroup] def pointwise_mul_semigroup [semigroup α] : semigroup (set α) := { mul_assoc := λ _ _ _, set.ext $ λ _, begin split, { rintros ⟨_, ⟨_, _, _, _, rfl⟩, _, _, rfl⟩, exact ⟨_, ‹_›, _, ⟨_, ‹_›, _, ‹_›, rfl⟩, mul_assoc _ _ _⟩ }, { rintros ⟨_, _, _, ⟨_, _, _, _, rfl⟩, rfl⟩, exact ⟨_, ⟨_, ‹_›, _, ‹_›, rfl⟩, _, ‹_›, (mul_assoc _ _ _).symm⟩ } end, ..pointwise_mul } @[to_additive pointwise_add_add_monoid] def pointwise_mul_monoid [monoid α] : monoid (set α) := { one_mul := λ s, set.ext $ λ a, ⟨by {rintros ⟨_, _, _, _, rfl⟩, simp * at *}, λ h, ⟨1, mem_singleton 1, a, h, (one_mul a).symm⟩⟩, mul_one := λ s, set.ext $ λ a, ⟨by {rintros ⟨_, _, _, _, rfl⟩, simp * at *}, λ h, ⟨a, h, 1, mem_singleton 1, (mul_one a).symm⟩⟩, ..pointwise_mul_semigroup, ..pointwise_one } local attribute [instance] pointwise_mul_monoid @[to_additive] lemma singleton.is_mul_hom [has_mul α] : is_mul_hom (singleton : α → set α) := { map_mul := λ x y, set.ext $ λ a, by simp [mem_singleton_iff, mem_pointwise_mul] } @[to_additive is_add_monoid_hom] lemma singleton.is_monoid_hom [monoid α] : is_monoid_hom (singleton : α → set α) := { map_one := rfl, ..singleton.is_mul_hom } @[to_additive] def pointwise_inv [has_inv α] : has_inv (set α) := ⟨λ s, {a | a⁻¹ ∈ s}⟩ @[simp, to_additive] lemma pointwise_mul_empty [has_mul α] (s : set α) : s * ∅ = ∅ := set.ext $ λ a, ⟨by {rintros ⟨_, _, _, _, rfl⟩, tauto}, false.elim⟩ @[simp, to_additive] lemma empty_pointwise_mul [has_mul α] (s : set α) : ∅ * s = ∅ := set.ext $ λ a, ⟨by {rintros ⟨_, _, _, _, rfl⟩, tauto}, false.elim⟩ @[to_additive] lemma pointwise_mul_subset_mul [has_mul α] {s₁ s₂ t₁ t₂ : set α} (h₁ : s₁ ⊆ t₁) (h₂ : s₂ ⊆ t₂) : s₁ * s₂ ⊆ t₁ * t₂ := by {rintros _ ⟨_, _, _, _, rfl⟩, exact ⟨_, h₁ ‹_›, _, h₂ ‹_›, rfl⟩ } @[to_additive] lemma pointwise_mul_union [has_mul α] (s t u : set α) : s * (t ∪ u) = (s * t) ∪ (s * u) := begin ext a, split, { rintros ⟨_, _, _, H, rfl⟩, cases H; [left, right]; exact ⟨_, ‹_›, _, ‹_›, rfl⟩ }, { intro H, cases H with H H; { rcases H with ⟨_, _, _, _, rfl⟩, refine ⟨_, ‹_›, _, _, rfl⟩, erw mem_union, simp * } } end @[to_additive] lemma union_pointwise_mul [has_mul α] (s t u : set α) : (s ∪ t) * u = (s * u) ∪ (t * u) := begin ext a, split, { rintros ⟨_, H, _, _, rfl⟩, cases H; [left, right]; exact ⟨_, ‹_›, _, ‹_›, rfl⟩ }, { intro H, cases H with H H; { rcases H with ⟨_, _, _, _, rfl⟩; refine ⟨_, _, _, ‹_›, rfl⟩; erw mem_union; simp * } } end @[to_additive] lemma pointwise_mul_eq_Union_mul_left [has_mul α] {s t : set α} : s * t = ⋃a∈s, (λx, a * x) '' t := by { ext y; split; simp only [mem_Union]; rintros ⟨a, ha, x, hx, ax⟩; exact ⟨a, ha, x, hx, ax.symm⟩ } @[to_additive] lemma pointwise_mul_eq_Union_mul_right [has_mul α] {s t : set α} : s * t = ⋃a∈t, (λx, x * a) '' s := by { ext y; split; simp only [mem_Union]; rintros ⟨a, ha, x, hx, ax⟩; exact ⟨x, hx, a, ha, ax.symm⟩ } @[to_additive] lemma nonempty.pointwise_mul [has_mul α] {s t : set α} : s.nonempty → t.nonempty → (s * t).nonempty | ⟨x, hx⟩ ⟨y, hy⟩ := ⟨x * y, ⟨x, hx, y, hy, rfl⟩⟩ @[simp, to_additive] lemma univ_pointwise_mul_univ [monoid α] : (univ : set α) * univ = univ := begin have : ∀x, ∃a b : α, x = a * b := λx, ⟨x, ⟨1, (mul_one x).symm⟩⟩, show {a | ∃ x ∈ univ, ∃ y ∈ univ, a = x * y} = univ, simpa [eq_univ_iff_forall] end def pointwise_mul_fintype [has_mul α] [decidable_eq α] (s t : set α) [hs : fintype s] [ht : fintype t] : fintype (s * t : set α) := by { rw pointwise_mul_eq_image, apply set.fintype_image } def pointwise_add_fintype [has_add α] [decidable_eq α] (s t : set α) [hs : fintype s] [ht : fintype t] : fintype (s + t : set α) := by { rw pointwise_add_eq_image, apply set.fintype_image } attribute [to_additive] set.pointwise_mul_fintype /-- Pointwise scalar multiplication by a set of scalars. -/ def pointwise_smul [has_scalar α β] : has_scalar (set α) (set β) := ⟨λ s t, { x | ∃ a ∈ s, ∃ y ∈ t, x = a • y }⟩ /-- Scaling a set: multiplying every element by a scalar. -/ def smul_set [has_scalar α β] : has_scalar α (set β) := ⟨λ a s, { x | ∃ y ∈ s, x = a • y }⟩ local attribute [instance] pointwise_smul smul_set lemma mem_smul_set [has_scalar α β] (a : α) (s : set β) (x : β) : x ∈ a • s ↔ ∃ y ∈ s, x = a • y := iff.rfl lemma smul_set_eq_image [has_scalar α β] (a : α) (s : set β) : a • s = (λ x, a • x) '' s := set.ext $ λ x, iff.intro (λ ⟨_, hy₁, hy₂⟩, ⟨_, hy₁, hy₂.symm⟩) (λ ⟨_, hy₁, hy₂⟩, ⟨_, hy₁, hy₂.symm⟩) lemma smul_set_eq_pointwise_smul_singleton [has_scalar α β] (a : α) (s : set β) : a • s = ({a} : set α) • s := set.ext $ λ x, iff.intro (λ ⟨_, h⟩, ⟨a, mem_singleton _, _, h⟩) (λ ⟨_, h, y, hy, hx⟩, ⟨_, hy, by { rw mem_singleton_iff at h; rwa h at hx }⟩) lemma smul_mem_smul_set [has_scalar α β] (a : α) {s : set β} {y : β} (hy : y ∈ s) : a • y ∈ a • s := by rw mem_smul_set; use [y, hy] lemma smul_set_union [has_scalar α β] (a : α) (s t : set β) : a • (s ∪ t) = a • s ∪ a • t := by simp only [smul_set_eq_image, image_union] @[simp] lemma smul_set_empty [has_scalar α β] (a : α) : a • (∅ : set β) = ∅ := by rw [smul_set_eq_image, image_empty] lemma smul_set_mono [has_scalar α β] (a : α) {s t : set β} (h : s ⊆ t) : a • s ⊆ a • t := by { rw [smul_set_eq_image, smul_set_eq_image], exact image_subset _ h } section monoid def pointwise_mul_semiring [monoid α] : semiring (set α) := { add := (⊔), zero := ∅, add_assoc := set.union_assoc, zero_add := set.empty_union, add_zero := set.union_empty, add_comm := set.union_comm, zero_mul := empty_pointwise_mul, mul_zero := pointwise_mul_empty, left_distrib := pointwise_mul_union, right_distrib := union_pointwise_mul, ..pointwise_mul_monoid } def pointwise_mul_comm_semiring [comm_monoid α] : comm_semiring (set α) := { mul_comm := λ s t, set.ext $ λ a, by split; { rintros ⟨_, _, _, _, rfl⟩, exact ⟨_, ‹_›, _, ‹_›, mul_comm _ _⟩ }, ..pointwise_mul_semiring } local attribute [instance] pointwise_mul_semiring def comm_monoid [comm_monoid α] : comm_monoid (set α) := @comm_semiring.to_comm_monoid (set α) pointwise_mul_comm_semiring def add_comm_monoid [add_comm_monoid α] : add_comm_monoid (set α) := show @add_comm_monoid (additive (set (multiplicative α))), from @additive.add_comm_monoid _ set.comm_monoid attribute [to_additive set.add_comm_monoid] set.comm_monoid /-- A multiplicative action of a monoid on a type β gives also a multiplicative action on the subsets of β. -/ def smul_set_action [monoid α] [mul_action α β] : mul_action α (set β) := { smul := λ a s, a • s, mul_smul := λ a b s, set.ext $ λ x, iff.intro (λ ⟨_, hy, _⟩, ⟨b • _, smul_mem_smul_set _ hy, by rwa ←mul_smul⟩) (λ ⟨_, hy, _⟩, let ⟨_, hz, h⟩ := (mem_smul_set _ _ _).2 hy in ⟨_, hz, by rwa [mul_smul, ←h]⟩), one_smul := λ b, set.ext $ λ x, iff.intro (λ ⟨_, _, h⟩, by { rw [one_smul] at h; rwa h }) (λ h, ⟨_, h, by rw one_smul⟩) } section is_mul_hom open is_mul_hom variables [has_mul α] [has_mul β] (m : α → β) [is_mul_hom m] @[to_additive] lemma image_pointwise_mul (s t : set α) : m '' (s * t) = m '' s * m '' t := set.ext $ assume y, begin split, { rintros ⟨_, ⟨_, _, _, _, rfl⟩, rfl⟩, refine ⟨_, mem_image_of_mem _ ‹_›, _, mem_image_of_mem _ ‹_›, map_mul _ _ _⟩ }, { rintros ⟨_, ⟨_, _, rfl⟩, _, ⟨_, _, rfl⟩, rfl⟩, refine ⟨_, ⟨_, ‹_›, _, ‹_›, rfl⟩, map_mul _ _ _⟩ } end @[to_additive] lemma preimage_pointwise_mul_preimage_subset (s t : set β) : m ⁻¹' s * m ⁻¹' t ⊆ m ⁻¹' (s * t) := begin rintros _ ⟨_, _, _, _, rfl⟩, exact ⟨_, ‹_›, _, ‹_›, map_mul _ _ _⟩, end end is_mul_hom variables [monoid α] [monoid β] [is_monoid_hom f] /-- The image of a set under function is a ring homomorphism with respect to the pointwise operations on sets. -/ def pointwise_mul_image_ring_hom : set α →+* set β := { to_fun := image f, map_zero' := image_empty _, map_one' := by erw [image_singleton, is_monoid_hom.map_one f]; refl, map_add' := image_union _, map_mul' := image_pointwise_mul _ } end monoid end set section open set variables {α : Type*} {β : Type*} local attribute [instance] set.smul_set /-- A nonempty set in a semimodule is scaled by zero to the singleton containing 0 in the semimodule. -/ lemma zero_smul_set [semiring α] [add_comm_monoid β] [semimodule α β] {s : set β} (h : s.nonempty) : (0 : α) • s = {(0 : β)} := set.ext $ λ x, iff.intro (λ ⟨_, _, hx⟩, mem_singleton_iff.mpr (by { rwa [hx, zero_smul] })) (λ hx, let ⟨_, hs⟩ := h in ⟨_, hs, by { rw mem_singleton_iff at hx; rw [hx, zero_smul] }⟩) lemma mem_inv_smul_set_iff [field α] [mul_action α β] {a : α} (ha : a ≠ 0) (A : set β) (x : β) : x ∈ a⁻¹ • A ↔ a • x ∈ A := iff.intro (λ ⟨y, hy, h⟩, by rwa [h, ←mul_smul, mul_inv_cancel ha, one_smul]) (λ h, ⟨_, h, by rw [←mul_smul, inv_mul_cancel ha, one_smul]⟩) lemma mem_smul_set_iff_inv_smul_mem [field α] [mul_action α β] {a : α} (ha : a ≠ 0) (A : set β) (x : β) : x ∈ a • A ↔ a⁻¹ • x ∈ A := by conv_lhs { rw ← inv_inv' a }; exact (mem_inv_smul_set_iff (inv_ne_zero ha) _ _) end
28c16a779b14ee06a48fa896be2ee2d18422dd67
5fbbd711f9bfc21ee168f46a4be146603ece8835
/lean/natural_number_game/advanced_addition/09.lean
2b17fb099eeebf9ed8d58a8314ead119d5f35ca5
[ "LicenseRef-scancode-warranty-disclaimer" ]
no_license
goedel-gang/maths
22596f71e3fde9c088e59931f128a3b5efb73a2c
a20a6f6a8ce800427afd595c598a5ad43da1408d
refs/heads/master
1,623,055,941,960
1,621,599,441,000
1,621,599,441,000
169,335,840
0
0
null
null
null
null
UTF-8
Lean
false
false
97
lean
theorem succ_ne_zero (a : mynat) : succ a ≠ 0 := begin symmetry, exact zero_ne_succ a, end
b85afa427188117ec061bc32a7b433b740e154b7
4aca55eba10c989f0d58647d3c2f371e7da44355
/src/backup.lean
c7f8ef2d6deceeb0cb298d16ba723a7902ba1603
[]
no_license
eric-wieser/l534zhan-my_project
f9fc75fb5454405e1a2fa9b56cf96c355f6f2336
febc91e76b7b00fe2517f258ca04d27b7f35fcf3
refs/heads/master
1,689,218,910,420
1,630,439,440,000
1,630,439,440,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
6,459
lean
/- /-- `|{a : F // is_quad_residue a}| * 2 = |F| - 1` -/ theorem card_residues_mul_two_eq [decidable_eq F] (hp: p ≠ 2) : fintype.card {a : F // is_quad_residue a} * 2 = q - 1 := by rwa [← card_units, card_units_eq_card_residues_mul_two F hp] -/ /- lemma residues_setcard_eq_fintype_card [decidable_eq F] : set.card {a : F | is_quad_residue a} = fintype.card {a : F // is_quad_residue a} := set.to_finset_card {a : F | is_quad_residue a} lemma non_residues_setcard_eq_fintype_card [decidable_eq F] : set.card {a : F | is_non_residue a} = fintype.card {a : F // is_non_residue a} := set.to_finset_card {a : F | is_non_residue a} lemma disjoint_residues_non_residues [decidable_eq F] : disjoint {a : F | is_quad_residue a} {a : F | is_non_residue a} := begin simp [set.disjoint_iff_inter_eq_empty, is_non_residue, is_quad_residue], ext, simp, rintros h b rfl _, use b, end lemma residues_union_non_residues [decidable_eq F] : {a : F | is_quad_residue a} ∪ {a : F | is_non_residue a} = {a : F | a ≠ 0} := begin ext, simp [is_non_residue, is_quad_residue, ←and_or_distrib_left], intros, convert or_not, simp, end lemma univ_setcard_split [decidable_eq F] : (@set.univ F).card = {a : F | a ≠ 0}.card + ({0} : set F).card := set.card_disjoint_union' (disjoint_units_zero F) (units_union_zero F) lemma zero_setcard_eq_one [decidable_eq F] : ({0} : set F).card = 1 := by simp [set.card] lemma univ_setcard_eq_units_setcard_add_one [decidable_eq F] : (@set.univ F).card = {a : F | a ≠ 0}.card + 1 := by rw [univ_setcard_split,zero_setcard_eq_one] lemma units_setcard_split [decidable_eq F] : {a : F | a ≠ 0}.card = {a : F | is_quad_residue a}.card + {a : F | is_non_residue a}.card := set.card_disjoint_union' (disjoint_residues_non_residues F) (residues_union_non_residues F) @[simp] lemma in_residues_sum_one_eq [decidable_eq F] : ∑ i in {a : F | is_quad_residue a}.to_finset, (1 : ℚ) = {a : F | is_quad_residue a}.card := by simp only [set.card, finset.card_eq_sum_ones_ℚ] @[simp] lemma in_non_residues_sum_neg_one_eq [decidable_eq F] : ∑ i in {a : F | is_non_residue a}.to_finset, (-1 : ℚ) = - {a : F | is_non_residue a}.card := by simp only [set.card, finset.card_eq_sum_ones_ℚ, sum_neg_distrib] -/ /- variable {F} /-- The cardinality of quadratic residues equals that of non-residues. -/ lemma card_residues_eq_card_non_residues_set [decidable_eq F] (hp : p ≠ 2): {a : F | is_quad_residue a}.card = {a : F | is_non_residue a}.card := begin have h:= card_residues_mul_two_eq F hp, rw [card_eq_set_card_of_univ F, ←residues_setcard_eq_fintype_card, univ_setcard_eq_units_setcard_add_one, units_setcard_split] at h, simp [mul_two, *] at *, end /-- `fintype` version of `finite_field.card_residues_eq_card_non_residues_set` . -/ lemma card_residues_eq_card_non_residues_subtpye [decidable_eq F] (hp : p ≠ 2): fintype.card {a : F // is_quad_residue a} = fintype.card {a : F // is_non_residue a} := by rwa [←residues_setcard_eq_fintype_card, ←non_residues_setcard_eq_fintype_card, card_residues_eq_card_non_residues_set hp] -/ /- lemma quad_char.sum_in_units_eq_zero (hp : p ≠ 2): ∑ (b : F) in univ.filter (λ b, b ≠ (0 : F)), χ b = 0 := begin rw [finset.sum_split _ (λ b : F, is_quad_residue b)], have h1 : ∑ (j : F) in filter (λ (b : F), is_quad_residue b) (filter (λ (b : F), b ≠ 0) univ), χ j = ∑ (j : F) in {a : F | is_quad_residue a}.to_finset, 1, { apply finset.sum_congr, {ext, split, all_goals {intro h, simp* at *}, use h.1}, intros x hx, simp* at * }, have h2 : ∑ (j : F) in filter (λ (x : F), ¬is_quad_residue x) (filter (λ (b : F), b ≠ 0) univ), χ j = ∑ (j : F) in {a : F | is_non_residue a}.to_finset, -1, { apply finset.sum_congr, {ext, split, all_goals {intro h, simp [*, is_non_residue, is_quad_residue] at *}}, intros x hx, simp* at * }, simp at h1 h2, simp [h1, h2], end -/ /- /-- helper of `quad_char.sum_mul'`: reindex the terms in the summation -/ lemma quad_char.sum_mul'_aux {c : F} (hc : c ≠ 0) : ∑ (b : F) in filter (λ (b : F), ¬b = 0) univ, χ (b⁻¹ * (b + c)) = ∑ (z : F) in filter (λ (z : F), ¬z = 1) univ, χ (z) := begin refine finset.sum_bij (λ b hb, b⁻¹ * (b + c)) (λ b hb, _) (λ b hb, rfl) (λ b₁ b₂ h1 h2 h, _) (λ z hz, _), { simp at hb, simp [*, mul_add] at * }, { simp at h1 h2, rw mul_add at h, rw mul_add at h, simp* at h, assumption}, { use c * (z - 1)⁻¹, simp, simp at hz, push_neg, refine ⟨⟨hc, sub_ne_zero.mpr hz⟩, _⟩, simp [*, mul_inv_rev', mul_add, mul_assoc, sub_ne_zero.mpr hz] } end -/ /- theorem quad_char.sum_mul' {c : F} (hc : c ≠ 0) (hp : p ≠ 2): ∑ b : F, χ (b) * χ (b + c) = -1 := begin rw [finset.sum_split _ (λ b, b ≠ (0 : F))], simp, have h: ∑ (b : F) in filter (λ (b : F), ¬b = 0) univ, χ b * χ (b + c) = ∑ (b : F) in filter (λ (b : F), ¬b = 0) univ, χ b * χ b * χ (b⁻¹ * (b + c)), { apply finset.sum_congr rfl, intros b hb, simp at hb, have : b * b * (b⁻¹ * (b + c)) = b * (b + c), {field_simp, ring}, repeat {rw ←(quad_char_mul hp)}, rw ← this, all_goals {assumption} }, have h': ∑ (b : F) in filter (λ (b : F), ¬b = 0) univ, χ b * χ b * χ (b⁻¹ * (b + c)) = ∑ (b : F) in filter (λ (b : F), ¬b = 0) univ, χ (b⁻¹ * (b + c)), { apply finset.sum_congr rfl, intros b hb, simp* at *}, rw [h, h', quad_char.sum_mul'_aux hc], have g:= @finset.sum_split _ _ _ (@finset.univ F _) (χ) (λ b : F, b ≠ (1 : F)) _, simp [quad_char.sum_eq_zero F hp] at g, rw [← sub_zero (∑ (z : F) in filter (λ (b : F), ¬b = 1) univ, χ z), g], ring, end -/ /- Can keep this. variables (F) /-- The subtype of `F` containing quadratic residues. -/ def quad_residues := {a : F // is_quad_residue a} /-- The set containing quadratic residues of `F`. -/ def quad_residues_set [decidable_eq F] := {a : F | is_quad_residue a} /-- The subtype of `F` containing quadratic non-residues. -/ def non_residues := {a : F // is_non_residue a} /-- The set containing quadratic non-residues of `F`. -/ def non_residues_set [decidable_eq F] := {a : F | is_non_residue a} instance [decidable_eq F] : fintype (quad_residues F) := by {unfold quad_residues, apply_instance} instance [decidable_eq F] : fintype (non_residues F) := by {unfold non_residues, apply_instance} -/
986fca081ba4ee4c7c2b85e518f6378d645f5e19
b70031c8e2c5337b91d7e70f1e0c5f528f7b0e77
/src/category_theory/abelian/non_preadditive.lean
4b3c1c21aa4d03dabd9bd1e65034cc20196bb28d
[ "Apache-2.0" ]
permissive
molodiuc/mathlib
cae2ba3ef1601c1f42ca0b625c79b061b63fef5b
98ebe5a6739fbe254f9ee9d401882d4388f91035
refs/heads/master
1,674,237,127,059
1,606,353,533,000
1,606,353,533,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
32,109
lean
/- Copyright (c) 2020 Markus Himmel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Markus Himmel -/ import category_theory.limits.shapes.finite_products import category_theory.limits.shapes.kernels import category_theory.limits.shapes.pullbacks import category_theory.limits.shapes.regular_mono import category_theory.preadditive /-! # Every non_preadditive_abelian category is preadditive In mathlib, we define an abelian category as a preadditive category with a zero object, kernels and cokernels, products and coproducts and in which every monomorphism and epimorphis is normal. While virtually every interesting abelian category has a natural preadditive structure (which is why it is included in the definition), preadditivity is not actually needed: Every category that has all of the other properties appearing in the definition of an abelian category admits a preadditive structure. This is the construction we carry out in this file. The proof proceeds in roughly five steps: 1. Prove some results (for example that all equalizers exist) that would be trivial if we already had the preadditive structure but are a bit of work without it. 2. Develop images and coimages to show that every monomorphism is the kernel of its cokernel. The results of the first two steps are also useful for the "normal" development of abelian categories, and will be used there. 3. For every object `A`, define a "subtraction" morphism `σ : A ⨯ A ⟶ A` and use it to define subtraction on morphisms as `f - g := prod.lift f g ≫ σ`. 4. Prove a small number of identities about this subtraction from the definition of `σ`. 5. From these identities, prove a large number of other identities that imply that defining `f + g := f - (0 - g)` indeed gives an abelian group structure on morphisms such that composition is bilinear. The construction is non-trivial and it is quite remarkable that this abelian group structure can be constructed purely from the existence of a few limits and colimits. What's even more impressive is that all additive structures on a category are in some sense isomorphic, so for abelian categories with a natural preadditive structure, this construction manages to "almost" reconstruct this natural structure. However, we have not formalized this isomorphism. ## References * [F. Borceux, *Handbook of Categorical Algebra 2*][borceux-vol2] -/ noncomputable theory open category_theory open category_theory.limits namespace category_theory section universes v u variables (C : Type u) [category.{v} C] /-- We call a category `non_preadditive_abelian` if it has a zero object, kernels, cokernels, binary products and coproducts, and every monomorphism and every epimorphism is normal. -/ class non_preadditive_abelian := [has_zero_object : has_zero_object C] [has_zero_morphisms : has_zero_morphisms C] [has_kernels : has_kernels C] [has_cokernels : has_cokernels C] [has_finite_products : has_finite_products C] [has_finite_coproducts : has_finite_coproducts C] (normal_mono : Π {X Y : C} (f : X ⟶ Y) [mono f], normal_mono f) (normal_epi : Π {X Y : C} (f : X ⟶ Y) [epi f], normal_epi f) set_option default_priority 100 attribute [instance] non_preadditive_abelian.has_zero_object attribute [instance] non_preadditive_abelian.has_zero_morphisms attribute [instance] non_preadditive_abelian.has_kernels attribute [instance] non_preadditive_abelian.has_cokernels attribute [instance] non_preadditive_abelian.has_finite_products attribute [instance] non_preadditive_abelian.has_finite_coproducts end end category_theory open category_theory namespace category_theory.non_preadditive_abelian universes v u variables {C : Type u} [category.{v} C] section variables [non_preadditive_abelian C] section strong local attribute [instance] non_preadditive_abelian.normal_epi /-- In a `non_preadditive_abelian` category, every epimorphism is strong. -/ lemma strong_epi_of_epi {P Q : C} (f : P ⟶ Q) [epi f] : strong_epi f := by apply_instance end strong section mono_epi_iso variables {X Y : C} (f : X ⟶ Y) local attribute [instance] strong_epi_of_epi /-- In a `non_preadditive_abelian` category, a monomorphism which is also an epimorphism is an isomorphism. -/ def is_iso_of_mono_of_epi [mono f] [epi f] : is_iso f := is_iso_of_mono_of_strong_epi _ end mono_epi_iso /-- The pullback of two monomorphisms exists. -/ @[irreducible] lemma pullback_of_mono {X Y Z : C} (a : X ⟶ Z) (b : Y ⟶ Z) [mono a] [mono b] : has_limit (cospan a b) := let ⟨P, f, haf, i⟩ := non_preadditive_abelian.normal_mono a in let ⟨Q, g, hbg, i'⟩ := non_preadditive_abelian.normal_mono b in let ⟨a', ha'⟩ := kernel_fork.is_limit.lift' i (kernel.ι (prod.lift f g)) $ calc kernel.ι (prod.lift f g) ≫ f = kernel.ι (prod.lift f g) ≫ prod.lift f g ≫ limits.prod.fst : by rw prod.lift_fst ... = (0 : kernel (prod.lift f g) ⟶ P ⨯ Q) ≫ limits.prod.fst : by rw kernel.condition_assoc ... = 0 : zero_comp in let ⟨b', hb'⟩ := kernel_fork.is_limit.lift' i' (kernel.ι (prod.lift f g)) $ calc kernel.ι (prod.lift f g) ≫ g = kernel.ι (prod.lift f g) ≫ (prod.lift f g) ≫ limits.prod.snd : by rw prod.lift_snd ... = (0 : kernel (prod.lift f g) ⟶ P ⨯ Q) ≫ limits.prod.snd : by rw kernel.condition_assoc ... = 0 : zero_comp in has_limit.mk { cone := pullback_cone.mk a' b' $ by { simp at ha' hb', rw [ha', hb'] }, is_limit := pullback_cone.is_limit.mk _ _ _ (λ s, kernel.lift (prod.lift f g) (pullback_cone.snd s ≫ b) $ prod.hom_ext (calc ((pullback_cone.snd s ≫ b) ≫ prod.lift f g) ≫ limits.prod.fst = pullback_cone.snd s ≫ b ≫ f : by simp only [prod.lift_fst, category.assoc] ... = pullback_cone.fst s ≫ a ≫ f : by rw pullback_cone.condition_assoc ... = pullback_cone.fst s ≫ 0 : by rw haf ... = 0 ≫ limits.prod.fst : by rw [comp_zero, zero_comp]) (calc ((pullback_cone.snd s ≫ b) ≫ prod.lift f g) ≫ limits.prod.snd = pullback_cone.snd s ≫ b ≫ g : by simp only [prod.lift_snd, category.assoc] ... = pullback_cone.snd s ≫ 0 : by rw hbg ... = 0 ≫ limits.prod.snd : by rw [comp_zero, zero_comp])) (λ s, (cancel_mono a).1 $ by { rw kernel_fork.ι_of_ι at ha', simp [ha', pullback_cone.condition s] }) (λ s, (cancel_mono b).1 $ by { rw kernel_fork.ι_of_ι at hb', simp [hb'] }) (λ s m h₁ h₂, (cancel_mono (kernel.ι (prod.lift f g))).1 $ calc m ≫ kernel.ι (prod.lift f g) = m ≫ a' ≫ a : by { congr, exact ha'.symm } ... = pullback_cone.fst s ≫ a : by rw [←category.assoc, h₁] ... = pullback_cone.snd s ≫ b : pullback_cone.condition s ... = kernel.lift (prod.lift f g) (pullback_cone.snd s ≫ b) _ ≫ kernel.ι (prod.lift f g) : by rw kernel.lift_ι) } /-- The pushout of two epimorphisms exists. -/ @[irreducible] lemma pushout_of_epi {X Y Z : C} (a : X ⟶ Y) (b : X ⟶ Z) [epi a] [epi b] : has_colimit (span a b) := let ⟨P, f, hfa, i⟩ := non_preadditive_abelian.normal_epi a in let ⟨Q, g, hgb, i'⟩ := non_preadditive_abelian.normal_epi b in let ⟨a', ha'⟩ := cokernel_cofork.is_colimit.desc' i (cokernel.π (coprod.desc f g)) $ calc f ≫ cokernel.π (coprod.desc f g) = coprod.inl ≫ coprod.desc f g ≫ cokernel.π (coprod.desc f g) : by rw coprod.inl_desc_assoc ... = coprod.inl ≫ (0 : P ⨿ Q ⟶ cokernel (coprod.desc f g)) : by rw cokernel.condition ... = 0 : has_zero_morphisms.comp_zero _ _ in let ⟨b', hb'⟩ := cokernel_cofork.is_colimit.desc' i' (cokernel.π (coprod.desc f g)) $ calc g ≫ cokernel.π (coprod.desc f g) = coprod.inr ≫ coprod.desc f g ≫ cokernel.π (coprod.desc f g) : by rw coprod.inr_desc_assoc ... = coprod.inr ≫ (0 : P ⨿ Q ⟶ cokernel (coprod.desc f g)) : by rw cokernel.condition ... = 0 : has_zero_morphisms.comp_zero _ _ in has_colimit.mk { cocone := pushout_cocone.mk a' b' $ by { simp only [cofork.π_of_π] at ha' hb', rw [ha', hb'] }, is_colimit := pushout_cocone.is_colimit.mk _ _ _ (λ s, cokernel.desc (coprod.desc f g) (b ≫ pushout_cocone.inr s) $ coprod.hom_ext (calc coprod.inl ≫ coprod.desc f g ≫ b ≫ pushout_cocone.inr s = f ≫ b ≫ pushout_cocone.inr s : by rw coprod.inl_desc_assoc ... = f ≫ a ≫ pushout_cocone.inl s : by rw pushout_cocone.condition ... = 0 ≫ pushout_cocone.inl s : by rw reassoc_of hfa ... = coprod.inl ≫ 0 : by rw [comp_zero, zero_comp]) (calc coprod.inr ≫ coprod.desc f g ≫ b ≫ pushout_cocone.inr s = g ≫ b ≫ pushout_cocone.inr s : by rw coprod.inr_desc_assoc ... = 0 ≫ pushout_cocone.inr s : by rw reassoc_of hgb ... = coprod.inr ≫ 0 : by rw [comp_zero, zero_comp])) (λ s, (cancel_epi a).1 $ by { rw cokernel_cofork.π_of_π at ha', simp [reassoc_of ha', pushout_cocone.condition s] }) (λ s, (cancel_epi b).1 $ by { rw cokernel_cofork.π_of_π at hb', simp [reassoc_of hb'] }) (λ s m h₁ h₂, (cancel_epi (cokernel.π (coprod.desc f g))).1 $ calc cokernel.π (coprod.desc f g) ≫ m = (a ≫ a') ≫ m : by { congr, exact ha'.symm } ... = a ≫ pushout_cocone.inl s : by rw [category.assoc, h₁] ... = b ≫ pushout_cocone.inr s : pushout_cocone.condition s ... = cokernel.π (coprod.desc f g) ≫ cokernel.desc (coprod.desc f g) (b ≫ pushout_cocone.inr s) _ : by rw cokernel.π_desc) } section local attribute [instance] pullback_of_mono /-- The pullback of `(𝟙 X, f)` and `(𝟙 X, g)` -/ private abbreviation P {X Y : C} (f g : X ⟶ Y) [mono (prod.lift (𝟙 X) f)] [mono (prod.lift (𝟙 X) g)] : C := pullback (prod.lift (𝟙 X) f) (prod.lift (𝟙 X) g) /-- The equalizer of `f` and `g` exists. -/ @[irreducible] lemma has_limit_parallel_pair {X Y : C} (f g : X ⟶ Y) : has_limit (parallel_pair f g) := have huv : (pullback.fst : P f g ⟶ X) = pullback.snd, from calc (pullback.fst : P f g ⟶ X) = pullback.fst ≫ 𝟙 _ : eq.symm $ category.comp_id _ ... = pullback.fst ≫ prod.lift (𝟙 X) f ≫ limits.prod.fst : by rw prod.lift_fst ... = pullback.snd ≫ prod.lift (𝟙 X) g ≫ limits.prod.fst : by rw pullback.condition_assoc ... = pullback.snd : by rw [prod.lift_fst, category.comp_id], have hvu : (pullback.fst : P f g ⟶ X) ≫ f = pullback.snd ≫ g, from calc (pullback.fst : P f g ⟶ X) ≫ f = pullback.fst ≫ prod.lift (𝟙 X) f ≫ limits.prod.snd : by rw prod.lift_snd ... = pullback.snd ≫ prod.lift (𝟙 X) g ≫ limits.prod.snd : by rw pullback.condition_assoc ... = pullback.snd ≫ g : by rw prod.lift_snd, have huu : (pullback.fst : P f g ⟶ X) ≫ f = pullback.fst ≫ g, by rw [hvu, ←huv], has_limit.mk { cone := fork.of_ι pullback.fst huu, is_limit := fork.is_limit.mk _ (λ s, pullback.lift (fork.ι s) (fork.ι s) $ prod.hom_ext (by simp only [prod.lift_fst, category.assoc]) (by simp only [fork.app_zero_right, fork.app_zero_left, prod.lift_snd, category.assoc])) (λ s, by simp only [fork.ι_of_ι, pullback.lift_fst]) (λ s m h, pullback.hom_ext (by simpa only [pullback.lift_fst] using h walking_parallel_pair.zero) (by simpa only [huv.symm, pullback.lift_fst] using h walking_parallel_pair.zero)) } end section local attribute [instance] pushout_of_epi /-- The pushout of `(𝟙 Y, f)` and `(𝟙 Y, g)`. -/ private abbreviation Q {X Y : C} (f g : X ⟶ Y) [epi (coprod.desc (𝟙 Y) f)] [epi (coprod.desc (𝟙 Y) g)] : C := pushout (coprod.desc (𝟙 Y) f) (coprod.desc (𝟙 Y) g) /-- The coequalizer of `f` and `g` exists. -/ @[irreducible] lemma has_colimit_parallel_pair {X Y : C} (f g : X ⟶ Y) : has_colimit (parallel_pair f g) := have huv : (pushout.inl : Y ⟶ Q f g) = pushout.inr, from calc (pushout.inl : Y ⟶ Q f g) = 𝟙 _ ≫ pushout.inl : eq.symm $ category.id_comp _ ... = (coprod.inl ≫ coprod.desc (𝟙 Y) f) ≫ pushout.inl : by rw coprod.inl_desc ... = (coprod.inl ≫ coprod.desc (𝟙 Y) g) ≫ pushout.inr : by simp only [category.assoc, pushout.condition] ... = pushout.inr : by rw [coprod.inl_desc, category.id_comp], have hvu : f ≫ (pushout.inl : Y ⟶ Q f g) = g ≫ pushout.inr, from calc f ≫ (pushout.inl : Y ⟶ Q f g) = (coprod.inr ≫ coprod.desc (𝟙 Y) f) ≫ pushout.inl : by rw coprod.inr_desc ... = (coprod.inr ≫ coprod.desc (𝟙 Y) g) ≫ pushout.inr : by simp only [category.assoc, pushout.condition] ... = g ≫ pushout.inr : by rw coprod.inr_desc, have huu : f ≫ (pushout.inl : Y ⟶ Q f g) = g ≫ pushout.inl, by rw [hvu, huv], has_colimit.mk { cocone := cofork.of_π pushout.inl huu, is_colimit := cofork.is_colimit.mk _ (λ s, pushout.desc (cofork.π s) (cofork.π s) $ coprod.hom_ext (by simp only [coprod.inl_desc_assoc]) (by simp only [cofork.right_app_one, coprod.inr_desc_assoc, cofork.left_app_one])) (λ s, by simp only [pushout.inl_desc, cofork.π_of_π]) (λ s m h, pushout.hom_ext (by simpa only [pushout.inl_desc] using h walking_parallel_pair.one) (by simpa only [huv.symm, pushout.inl_desc] using h walking_parallel_pair.one)) } end section local attribute [instance] has_limit_parallel_pair /-- A `non_preadditive_abelian` category has all equalizers. -/ @[priority 100] instance has_equalizers : has_equalizers C := has_equalizers_of_has_limit_parallel_pair _ end section local attribute [instance] has_colimit_parallel_pair /-- A `non_preadditive_abelian` category has all coequalizers. -/ @[priority 100] instance has_coequalizers : has_coequalizers C := has_coequalizers_of_has_colimit_parallel_pair _ end section /-- If a zero morphism is a kernel of `f`, then `f` is a monomorphism. -/ lemma mono_of_zero_kernel {X Y : C} (f : X ⟶ Y) (Z : C) (l : is_limit (kernel_fork.of_ι (0 : Z ⟶ X) (show 0 ≫ f = 0, by simp))) : mono f := ⟨λ P u v huv, begin obtain ⟨W, w, hw, hl⟩ := non_preadditive_abelian.normal_epi (coequalizer.π u v), obtain ⟨m, hm⟩ := coequalizer.desc' f huv, have hwf : w ≫ f = 0, { rw [←hm, reassoc_of hw, zero_comp] }, obtain ⟨n, hn⟩ := kernel_fork.is_limit.lift' l _ hwf, rw [fork.ι_of_ι, has_zero_morphisms.comp_zero] at hn, haveI : is_iso (coequalizer.π u v) := by apply is_iso_colimit_cocone_parallel_pair_of_eq hn.symm hl, apply (cancel_mono (coequalizer.π u v)).1, exact coequalizer.condition _ _ end⟩ /-- If a zero morphism is a cokernel of `f`, then `f` is an epimorphism. -/ lemma epi_of_zero_cokernel {X Y : C} (f : X ⟶ Y) (Z : C) (l : is_colimit (cokernel_cofork.of_π (0 : Y ⟶ Z) (show f ≫ 0 = 0, by simp))) : epi f := ⟨λ P u v huv, begin obtain ⟨W, w, hw, hl⟩ := non_preadditive_abelian.normal_mono (equalizer.ι u v), obtain ⟨m, hm⟩ := equalizer.lift' f huv, have hwf : f ≫ w = 0, { rw [←hm, category.assoc, hw, comp_zero] }, obtain ⟨n, hn⟩ := cokernel_cofork.is_colimit.desc' l _ hwf, rw [cofork.π_of_π, zero_comp] at hn, haveI : is_iso (equalizer.ι u v) := by apply is_iso_limit_cone_parallel_pair_of_eq hn.symm hl, apply (cancel_epi (equalizer.ι u v)).1, exact equalizer.condition _ _ end⟩ local attribute [instance] has_zero_object.has_zero /-- If `g ≫ f = 0` implies `g = 0` for all `g`, then `0 : 0 ⟶ X` is a kernel of `f`. -/ def zero_kernel_of_cancel_zero {X Y : C} (f : X ⟶ Y) (hf : ∀ (Z : C) (g : Z ⟶ X) (hgf : g ≫ f = 0), g = 0) : is_limit (kernel_fork.of_ι (0 : 0 ⟶ X) (show 0 ≫ f = 0, by simp)) := fork.is_limit.mk _ (λ s, 0) (λ s, by rw [hf _ _ (kernel_fork.condition s), zero_comp]) (λ s m h, by ext) /-- If `f ≫ g = 0` implies `g = 0` for all `g`, then `0 : Y ⟶ 0` is a cokernel of `f`. -/ def zero_cokernel_of_zero_cancel {X Y : C} (f : X ⟶ Y) (hf : ∀ (Z : C) (g : Y ⟶ Z) (hgf : f ≫ g = 0), g = 0) : is_colimit (cokernel_cofork.of_π (0 : Y ⟶ 0) (show f ≫ 0 = 0, by simp)) := cofork.is_colimit.mk _ (λ s, 0) (λ s, by rw [hf _ _ (cokernel_cofork.condition s), comp_zero]) (λ s m h, by ext) /-- If `g ≫ f = 0` implies `g = 0` for all `g`, then `f` is a monomorphism. -/ lemma mono_of_cancel_zero {X Y : C} (f : X ⟶ Y) (hf : ∀ (Z : C) (g : Z ⟶ X) (hgf : g ≫ f = 0), g = 0) : mono f := mono_of_zero_kernel f 0 $ zero_kernel_of_cancel_zero f hf /-- If `f ≫ g = 0` implies `g = 0` for all `g`, then `g` is a monomorphism. -/ lemma epi_of_zero_cancel {X Y : C} (f : X ⟶ Y) (hf : ∀ (Z : C) (g : Y ⟶ Z) (hgf : f ≫ g = 0), g = 0) : epi f := epi_of_zero_cokernel f 0 $ zero_cokernel_of_zero_cancel f hf end section factor variables {P Q : C} (f : P ⟶ Q) /-- The kernel of the cokernel of `f` is called the image of `f`. -/ protected abbreviation image : C := kernel (cokernel.π f) /-- The inclusion of the image into the codomain. -/ protected abbreviation image.ι : non_preadditive_abelian.image f ⟶ Q := kernel.ι (cokernel.π f) /-- There is a canonical epimorphism `p : P ⟶ image f` for every `f`. -/ protected abbreviation factor_thru_image : P ⟶ non_preadditive_abelian.image f := kernel.lift (cokernel.π f) f $ cokernel.condition f /-- `f` factors through its image via the canonical morphism `p`. -/ @[simp, reassoc] protected lemma image.fac : non_preadditive_abelian.factor_thru_image f ≫ image.ι f = f := kernel.lift_ι _ _ _ /-- The map `p : P ⟶ image f` is an epimorphism -/ instance : epi (non_preadditive_abelian.factor_thru_image f) := let I := non_preadditive_abelian.image f, p := non_preadditive_abelian.factor_thru_image f, i := kernel.ι (cokernel.π f) in -- It will suffice to consider some g : I ⟶ R such that p ≫ g = 0 and show that g = 0. epi_of_zero_cancel _ $ λ R (g : I ⟶ R) (hpg : p ≫ g = 0), begin -- Since C is abelian, u := ker g ≫ i is the kernel of some morphism h. let u := kernel.ι g ≫ i, haveI : mono u := mono_comp _ _, haveI hu := non_preadditive_abelian.normal_mono u, let h := hu.g, -- By hypothesis, p factors through the kernel of g via some t. obtain ⟨t, ht⟩ := kernel.lift' g p hpg, have fh : f ≫ h = 0, calc f ≫ h = (p ≫ i) ≫ h : (image.fac f).symm ▸ rfl ... = ((t ≫ kernel.ι g) ≫ i) ≫ h : ht ▸ rfl ... = t ≫ u ≫ h : by simp only [category.assoc]; conv_lhs { congr, skip, rw ←category.assoc } ... = t ≫ 0 : hu.w ▸ rfl ... = 0 : has_zero_morphisms.comp_zero _ _, -- h factors through the cokernel of f via some l. obtain ⟨l, hl⟩ := cokernel.desc' f h fh, have hih : i ≫ h = 0, calc i ≫ h = i ≫ cokernel.π f ≫ l : hl ▸ rfl ... = 0 ≫ l : by rw [←category.assoc, kernel.condition] ... = 0 : zero_comp, -- i factors through u = ker h via some s. obtain ⟨s, hs⟩ := normal_mono.lift' u i hih, have hs' : (s ≫ kernel.ι g) ≫ i = 𝟙 I ≫ i, by rw [category.assoc, hs, category.id_comp], haveI : epi (kernel.ι g) := epi_of_epi_fac ((cancel_mono _).1 hs'), -- ker g is an epimorphism, but ker g ≫ g = 0 = ker g ≫ 0, so g = 0 as required. exact zero_of_epi_comp _ (kernel.condition g) end instance mono_factor_thru_image [mono f] : mono (non_preadditive_abelian.factor_thru_image f) := mono_of_mono_fac $ image.fac f instance is_iso_factor_thru_image [mono f] : is_iso (non_preadditive_abelian.factor_thru_image f) := is_iso_of_mono_of_epi _ /-- The cokernel of the kernel of `f` is called the coimage of `f`. -/ protected abbreviation coimage : C := cokernel (kernel.ι f) /-- The projection onto the coimage. -/ protected abbreviation coimage.π : P ⟶ non_preadditive_abelian.coimage f := cokernel.π (kernel.ι f) /-- There is a canonical monomorphism `i : coimage f ⟶ Q`. -/ protected abbreviation factor_thru_coimage : non_preadditive_abelian.coimage f ⟶ Q := cokernel.desc (kernel.ι f) f $ kernel.condition f /-- `f` factors through its coimage via the canonical morphism `p`. -/ protected lemma coimage.fac : coimage.π f ≫ non_preadditive_abelian.factor_thru_coimage f = f := cokernel.π_desc _ _ _ /-- The canonical morphism `i : coimage f ⟶ Q` is a monomorphism -/ instance : mono (non_preadditive_abelian.factor_thru_coimage f) := let I := non_preadditive_abelian.coimage f, i := non_preadditive_abelian.factor_thru_coimage f, p := cokernel.π (kernel.ι f) in mono_of_cancel_zero _ $ λ R (g : R ⟶ I) (hgi : g ≫ i = 0), begin -- Since C is abelian, u := p ≫ coker g is the cokernel of some morphism h. let u := p ≫ cokernel.π g, haveI : epi u := epi_comp _ _, haveI hu := non_preadditive_abelian.normal_epi u, let h := hu.g, -- By hypothesis, i factors through the cokernel of g via some t. obtain ⟨t, ht⟩ := cokernel.desc' g i hgi, have hf : h ≫ f = 0, calc h ≫ f = h ≫ (p ≫ i) : (coimage.fac f).symm ▸ rfl ... = h ≫ (p ≫ (cokernel.π g ≫ t)) : ht ▸ rfl ... = h ≫ u ≫ t : by simp only [category.assoc]; conv_lhs { congr, skip, rw ←category.assoc } ... = 0 ≫ t : by rw [←category.assoc, hu.w] ... = 0 : zero_comp, -- h factors through the kernel of f via some l. obtain ⟨l, hl⟩ := kernel.lift' f h hf, have hhp : h ≫ p = 0, calc h ≫ p = (l ≫ kernel.ι f) ≫ p : hl ▸ rfl ... = l ≫ 0 : by rw [category.assoc, cokernel.condition] ... = 0 : comp_zero, -- p factors through u = coker h via some s. obtain ⟨s, hs⟩ := normal_epi.desc' u p hhp, have hs' : p ≫ cokernel.π g ≫ s = p ≫ 𝟙 I, by rw [←category.assoc, hs, category.comp_id], haveI : mono (cokernel.π g) := mono_of_mono_fac ((cancel_epi _).1 hs'), -- coker g is a monomorphism, but g ≫ coker g = 0 = 0 ≫ coker g, so g = 0 as required. exact zero_of_comp_mono _ (cokernel.condition g) end instance epi_factor_thru_coimage [epi f] : epi (non_preadditive_abelian.factor_thru_coimage f) := epi_of_epi_fac $ coimage.fac f instance is_iso_factor_thru_coimage [epi f] : is_iso (non_preadditive_abelian.factor_thru_coimage f) := is_iso_of_mono_of_epi _ end factor section cokernel_of_kernel variables {X Y : C} {f : X ⟶ Y} /-- In a `non_preadditive_abelian` category, an epi is the cokernel of its kernel. More precisely: If `f` is an epimorphism and `s` is some limit kernel cone on `f`, then `f` is a cokernel of `fork.ι s`. -/ def epi_is_cokernel_of_kernel [epi f] (s : fork f 0) (h : is_limit s) : is_colimit (cokernel_cofork.of_π f (kernel_fork.condition s)) := is_cokernel.cokernel_iso _ _ (cokernel.of_iso_comp _ _ (limits.is_limit.cone_point_unique_up_to_iso (limit.is_limit _) h) (cone_morphism.w (limits.is_limit.unique_up_to_iso (limit.is_limit _) h).hom _)) (as_iso $ non_preadditive_abelian.factor_thru_coimage f) (coimage.fac f) /-- In a `non_preadditive_abelian` category, a mono is the kernel of its cokernel. More precisely: If `f` is a monomorphism and `s` is some colimit cokernel cocone on `f`, then `f` is a kernel of `cofork.π s`. -/ def mono_is_kernel_of_cokernel [mono f] (s : cofork f 0) (h : is_colimit s) : is_limit (kernel_fork.of_ι f (cokernel_cofork.condition s)) := is_kernel.iso_kernel _ _ (kernel.of_comp_iso _ _ (limits.is_colimit.cocone_point_unique_up_to_iso h (colimit.is_colimit _)) (cocone_morphism.w (limits.is_colimit.unique_up_to_iso h $ colimit.is_colimit _).hom _)) (as_iso $ non_preadditive_abelian.factor_thru_image f) (image.fac f) end cokernel_of_kernel section /-- The composite `A ⟶ A ⨯ A ⟶ cokernel (Δ A)`, where the first map is `(𝟙 A, 0)` and the second map is the canonical projection into the cokernel. -/ abbreviation r (A : C) : A ⟶ cokernel (diag A) := prod.lift (𝟙 A) 0 ≫ cokernel.π (diag A) instance mono_Δ {A : C} : mono (diag A) := mono_of_mono_fac $ prod.lift_fst _ _ instance mono_r {A : C} : mono (r A) := begin let hl : is_limit (kernel_fork.of_ι (diag A) (cokernel.condition (diag A))), { exact mono_is_kernel_of_cokernel _ (colimit.is_colimit _) }, apply mono_of_cancel_zero, intros Z x hx, have hxx : (x ≫ prod.lift (𝟙 A) (0 : A ⟶ A)) ≫ cokernel.π (diag A) = 0, { rw [category.assoc, hx] }, obtain ⟨y, hy⟩ := kernel_fork.is_limit.lift' hl _ hxx, rw kernel_fork.ι_of_ι at hy, have hyy : y = 0, { erw [←category.comp_id y, ←limits.prod.lift_snd (𝟙 A) (𝟙 A), ←category.assoc, hy, category.assoc, prod.lift_snd, has_zero_morphisms.comp_zero] }, haveI : mono (prod.lift (𝟙 A) (0 : A ⟶ A)) := mono_of_mono_fac (prod.lift_fst _ _), apply (cancel_mono (prod.lift (𝟙 A) (0 : A ⟶ A))).1, rw [←hy, hyy, zero_comp, zero_comp] end instance epi_r {A : C} : epi (r A) := begin have hlp : prod.lift (𝟙 A) (0 : A ⟶ A) ≫ limits.prod.snd = 0 := prod.lift_snd _ _, let hp1 : is_limit (kernel_fork.of_ι (prod.lift (𝟙 A) (0 : A ⟶ A)) hlp), { refine fork.is_limit.mk _ (λ s, fork.ι s ≫ limits.prod.fst) _ _, { intro s, ext; simp, erw category.comp_id }, { intros s m h, haveI : mono (prod.lift (𝟙 A) (0 : A ⟶ A)) := mono_of_mono_fac (prod.lift_fst _ _), apply (cancel_mono (prod.lift (𝟙 A) (0 : A ⟶ A))).1, convert h walking_parallel_pair.zero, ext; simp } }, let hp2 : is_colimit (cokernel_cofork.of_π (limits.prod.snd : A ⨯ A ⟶ A) hlp), { exact epi_is_cokernel_of_kernel _ hp1 }, apply epi_of_zero_cancel, intros Z z hz, have h : prod.lift (𝟙 A) (0 : A ⟶ A) ≫ cokernel.π (diag A) ≫ z = 0, { rw [←category.assoc, hz] }, obtain ⟨t, ht⟩ := cokernel_cofork.is_colimit.desc' hp2 _ h, rw cokernel_cofork.π_of_π at ht, have htt : t = 0, { rw [←category.id_comp t], change 𝟙 A ≫ t = 0, rw [←limits.prod.lift_snd (𝟙 A) (𝟙 A), category.assoc, ht, ←category.assoc, cokernel.condition, zero_comp] }, apply (cancel_epi (cokernel.π (diag A))).1, rw [←ht, htt, comp_zero, comp_zero] end instance is_iso_r {A : C} : is_iso (r A) := is_iso_of_mono_of_epi _ /-- The composite `A ⨯ A ⟶ cokernel (diag A) ⟶ A` given by the natural projection into the cokernel followed by the inverse of `r`. In the category of modules, using the normal kernels and cokernels, this map is equal to the map `(a, b) ↦ a - b`, hence the name `σ` for "subtraction". -/ abbreviation σ {A : C} : A ⨯ A ⟶ A := cokernel.π (diag A) ≫ is_iso.inv (r A) end @[simp, reassoc] lemma diag_σ {X : C} : diag X ≫ σ = 0 := by rw [cokernel.condition_assoc, zero_comp] @[simp, reassoc] lemma lift_σ {X : C} : prod.lift (𝟙 X) 0 ≫ σ = 𝟙 X := by rw [←category.assoc, is_iso.hom_inv_id] @[reassoc] lemma lift_map {X Y : C} (f : X ⟶ Y) : prod.lift (𝟙 X) 0 ≫ limits.prod.map f f = f ≫ prod.lift (𝟙 Y) 0 := by simp /-- σ is a cokernel of Δ X. -/ def is_colimit_σ {X : C} : is_colimit (cokernel_cofork.of_π σ diag_σ) := cokernel.cokernel_iso _ σ (as_iso (r X)).symm (by rw [iso.symm_hom, as_iso_inv]) /-- This is the key identity satisfied by `σ`. -/ lemma σ_comp {X Y : C} (f : X ⟶ Y) : σ ≫ f = limits.prod.map f f ≫ σ := begin obtain ⟨g, hg⟩ := cokernel_cofork.is_colimit.desc' is_colimit_σ (limits.prod.map f f ≫ σ) (by simp), suffices hfg : f = g, { rw [←hg, cofork.π_of_π, hfg] }, calc f = f ≫ prod.lift (𝟙 Y) 0 ≫ σ : by rw [lift_σ, category.comp_id] ... = prod.lift (𝟙 X) 0 ≫ limits.prod.map f f ≫ σ : by rw lift_map_assoc ... = prod.lift (𝟙 X) 0 ≫ σ ≫ g : by rw [←hg, cokernel_cofork.π_of_π] ... = g : by rw [←category.assoc, lift_σ, category.id_comp] end section /- We write `f - g` for `prod.lift f g ≫ σ`. -/ /-- Subtraction of morphisms in a `non_preadditive_abelian` category. -/ def has_sub {X Y : C} : has_sub (X ⟶ Y) := ⟨λ f g, prod.lift f g ≫ σ⟩ local attribute [instance] has_sub /- We write `-f` for `0 - f`. -/ /-- Negation of morphisms in a `non_preadditive_abelian` category. -/ def has_neg {X Y : C} : has_neg (X ⟶ Y) := ⟨λ f, 0 - f⟩ local attribute [instance] has_neg /- We write `f + g` for `f - (-g)`. -/ /-- Addition of morphisms in a `non_preadditive_abelian` category. -/ def has_add {X Y : C} : has_add (X ⟶ Y) := ⟨λ f g, f - (-g)⟩ local attribute [instance] has_add lemma sub_def {X Y : C} (a b : X ⟶ Y) : a - b = prod.lift a b ≫ σ := rfl lemma add_def {X Y : C} (a b : X ⟶ Y) : a + b = a - (-b) := rfl lemma neg_def {X Y : C} (a : X ⟶ Y) : -a = 0 - a := rfl lemma sub_zero {X Y : C} (a : X ⟶ Y) : a - 0 = a := begin rw sub_def, conv_lhs { congr, congr, rw ←category.comp_id a, skip, rw (show 0 = a ≫ (0 : Y ⟶ Y), by simp)}, rw [← prod.comp_lift, category.assoc, lift_σ, category.comp_id] end lemma sub_self {X Y : C} (a : X ⟶ Y) : a - a = 0 := by rw [sub_def, ←category.comp_id a, ← prod.comp_lift, category.assoc, diag_σ, comp_zero] lemma lift_sub_lift {X Y : C} (a b c d : X ⟶ Y) : prod.lift a b - prod.lift c d = prod.lift (a - c) (b - d) := begin simp only [sub_def], ext, { rw [category.assoc, σ_comp, prod.lift_map_assoc, prod.lift_fst, prod.lift_fst, prod.lift_fst] }, { rw [category.assoc, σ_comp, prod.lift_map_assoc, prod.lift_snd, prod.lift_snd, prod.lift_snd] } end lemma sub_sub_sub {X Y : C} (a b c d : X ⟶ Y) : (a - c) - (b - d) = (a - b) - (c - d) := begin rw [sub_def, ←lift_sub_lift, sub_def, category.assoc, σ_comp, prod.lift_map_assoc], refl end lemma neg_sub {X Y : C} (a b : X ⟶ Y) : (-a) - b = (-b) - a := by conv_lhs { rw [neg_def, ←sub_zero b, sub_sub_sub, sub_zero, ←neg_def] } lemma neg_neg {X Y : C} (a : X ⟶ Y) : -(-a) = a := begin rw [neg_def, neg_def], conv_lhs { congr, rw ←sub_self a }, rw [sub_sub_sub, sub_zero, sub_self, sub_zero] end lemma add_comm {X Y : C} (a b : X ⟶ Y) : a + b = b + a := begin rw [add_def], conv_lhs { rw ←neg_neg a }, rw [neg_def, neg_def, neg_def, sub_sub_sub], conv_lhs {congr, skip, rw [←neg_def, neg_sub] }, rw [sub_sub_sub, add_def, ←neg_def, neg_neg b, neg_def] end lemma add_neg {X Y : C} (a b : X ⟶ Y) : a + (-b) = a - b := by rw [add_def, neg_neg] lemma add_neg_self {X Y : C} (a : X ⟶ Y) : a + (-a) = 0 := by rw [add_neg, sub_self] lemma neg_add_self {X Y : C} (a : X ⟶ Y) : (-a) + a = 0 := by rw [add_comm, add_neg_self] lemma neg_sub' {X Y : C} (a b : X ⟶ Y) : -(a - b) = (-a) + b := begin rw [neg_def, neg_def], conv_lhs { rw ←sub_self (0 : X ⟶ Y) }, rw [sub_sub_sub, add_def, neg_def] end lemma neg_add {X Y : C} (a b : X ⟶ Y) : -(a + b) = (-a) - b := by rw [add_def, neg_sub', add_neg] lemma sub_add {X Y : C} (a b c : X ⟶ Y) : (a - b) + c = a - (b - c) := by rw [add_def, neg_def, sub_sub_sub, sub_zero] lemma add_assoc {X Y : C} (a b c : X ⟶ Y) : (a + b) + c = a + (b + c) := begin conv_lhs { congr, rw add_def }, rw [sub_add, ←add_neg, neg_sub', neg_neg] end lemma add_zero {X Y : C} (a : X ⟶ Y) : a + 0 = a := by rw [add_def, neg_def, sub_self, sub_zero] lemma comp_sub {X Y Z : C} (f : X ⟶ Y) (g h : Y ⟶ Z) : f ≫ (g - h) = f ≫ g - f ≫ h := by rw [sub_def, ←category.assoc, prod.comp_lift, sub_def] lemma sub_comp {X Y Z : C} (f g : X ⟶ Y) (h : Y ⟶ Z) : (f - g) ≫ h = f ≫ h - g ≫ h := by rw [sub_def, category.assoc, σ_comp, ←category.assoc, prod.lift_map, sub_def] lemma comp_add (X Y Z : C) (f : X ⟶ Y) (g h : Y ⟶ Z) : f ≫ (g + h) = f ≫ g + f ≫ h := by rw [add_def, comp_sub, neg_def, comp_sub, comp_zero, add_def, neg_def] lemma add_comp (X Y Z : C) (f g : X ⟶ Y) (h : Y ⟶ Z) : (f + g) ≫ h = f ≫ h + g ≫ h := by rw [add_def, sub_comp, neg_def, sub_comp, zero_comp, add_def, neg_def] /-- Every `non_preadditive_abelian` category is preadditive. -/ def preadditive : preadditive C := { hom_group := λ X Y, { add := (+), add_assoc := add_assoc, zero := 0, zero_add := neg_neg, add_zero := add_zero, neg := λ f, -f, add_left_neg := neg_add_self, add_comm := add_comm }, add_comp' := add_comp, comp_add' := comp_add } end end end category_theory.non_preadditive_abelian
876d15db27445d0a89e73fab976d429bc442e757
947fa6c38e48771ae886239b4edce6db6e18d0fb
/src/order/complete_lattice.lean
b82d56608ee027814159d8b38243f43af09f9518
[ "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
55,643
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.bool.set import data.nat.basic import order.bounds /-! # Theory of complete lattices ## Main definitions * `Sup` and `Inf` are the supremum and the infimum of a set; * `supr (f : ι → α)` and `infi (f : ι → α)` are indexed supremum and infimum of a function, defined as `Sup` and `Inf` of the range of this function; * `class complete_lattice`: a bounded lattice such that `Sup s` is always the least upper boundary of `s` and `Inf s` is always the greatest lower boundary of `s`; * `class complete_linear_order`: a linear ordered complete lattice. ## Naming conventions In lemma names, * `Sup` is called `Sup` * `Inf` is called `Inf` * `⨆ i, s i` is called `supr` * `⨅ i, s i` is called `infi` * `⨆ i j, s i j` is called `supr₂`. This is a `supr` inside a `supr`. * `⨅ i j, s i j` is called `infi₂`. This is an `infi` inside an `infi`. * `⨆ i ∈ s, t i` is called `bsupr` for "bounded `supr`". This is the special case of `supr₂` where `j : i ∈ s`. * `⨅ i ∈ s, t i` is called `binfi` for "bounded `infi`". This is the special case of `infi₂` where `j : i ∈ s`. ## Notation * `⨆ i, f i` : `supr f`, the supremum of the range of `f`; * `⨅ i, f i` : `infi f`, the infimum of the range of `f`. -/ set_option old_structure_cmd true open set function variables {α β β₂ γ : Type*} {ι ι' : Sort*} {κ : ι → Sort*} {κ' : ι' → Sort*} /-- class for the `Sup` operator -/ class has_Sup (α : Type*) := (Sup : set α → α) /-- class for the `Inf` operator -/ class has_Inf (α : Type*) := (Inf : set α → α) export has_Sup (Sup) has_Inf (Inf) /-- Supremum of a set -/ add_decl_doc has_Sup.Sup /-- Infimum of a set -/ add_decl_doc has_Inf.Inf /-- Indexed supremum -/ def supr [has_Sup α] {ι} (s : ι → α) : α := Sup (range s) /-- Indexed infimum -/ def infi [has_Inf α] {ι} (s : ι → α) : α := Inf (range s) @[priority 50] instance has_Inf_to_nonempty (α) [has_Inf α] : nonempty α := ⟨Inf ∅⟩ @[priority 50] instance has_Sup_to_nonempty (α) [has_Sup α] : nonempty α := ⟨Sup ∅⟩ notation `⨆` binders `, ` r:(scoped f, supr f) := r notation `⨅` binders `, ` r:(scoped f, infi f) := r instance (α) [has_Inf α] : has_Sup αᵒᵈ := ⟨(Inf : set α → α)⟩ instance (α) [has_Sup α] : has_Inf αᵒᵈ := ⟨(Sup : set α → α)⟩ /-- Note that we rarely use `complete_semilattice_Sup` (in fact, any such object is always a `complete_lattice`, so it's usually best to start there). Nevertheless it is sometimes a useful intermediate step in constructions. -/ @[ancestor partial_order has_Sup] class complete_semilattice_Sup (α : Type*) extends partial_order α, has_Sup α := (le_Sup : ∀ s, ∀ a ∈ s, a ≤ Sup s) (Sup_le : ∀ s a, (∀ b ∈ s, b ≤ a) → Sup s ≤ a) section variables [complete_semilattice_Sup α] {s t : set α} {a b : α} @[ematch] theorem le_Sup : a ∈ s → a ≤ Sup s := complete_semilattice_Sup.le_Sup s a theorem Sup_le : (∀ b ∈ s, b ≤ a) → Sup s ≤ a := complete_semilattice_Sup.Sup_le s a lemma is_lub_Sup (s : set α) : is_lub s (Sup s) := ⟨λ x, le_Sup, λ x, Sup_le⟩ lemma is_lub.Sup_eq (h : is_lub s a) : Sup s = a := (is_lub_Sup s).unique h theorem le_Sup_of_le (hb : b ∈ s) (h : a ≤ b) : a ≤ Sup s := le_trans h (le_Sup hb) theorem Sup_le_Sup (h : s ⊆ t) : Sup s ≤ Sup t := (is_lub_Sup s).mono (is_lub_Sup t) h @[simp] theorem Sup_le_iff : Sup s ≤ a ↔ ∀ b ∈ s, b ≤ a := is_lub_le_iff (is_lub_Sup s) lemma le_Sup_iff : a ≤ Sup s ↔ ∀ b ∈ upper_bounds s, a ≤ b := ⟨λ h b hb, le_trans h (Sup_le hb), λ hb, hb _ (λ x, le_Sup)⟩ lemma le_supr_iff {s : ι → α} : a ≤ supr s ↔ ∀ b, (∀ i, s i ≤ b) → a ≤ b := by simp [supr, le_Sup_iff, upper_bounds] theorem Sup_le_Sup_of_forall_exists_le (h : ∀ x ∈ s, ∃ y ∈ t, x ≤ y) : Sup s ≤ Sup t := le_Sup_iff.2 $ λ b hb, Sup_le $ λ a ha, let ⟨c, hct, hac⟩ := h a ha in hac.trans (hb hct) -- We will generalize this to conditionally complete lattices in `cSup_singleton`. theorem Sup_singleton {a : α} : Sup {a} = a := is_lub_singleton.Sup_eq end /-- Note that we rarely use `complete_semilattice_Inf` (in fact, any such object is always a `complete_lattice`, so it's usually best to start there). Nevertheless it is sometimes a useful intermediate step in constructions. -/ @[ancestor partial_order has_Inf] class complete_semilattice_Inf (α : Type*) extends partial_order α, has_Inf α := (Inf_le : ∀ s, ∀ a ∈ s, Inf s ≤ a) (le_Inf : ∀ s a, (∀ b ∈ s, a ≤ b) → a ≤ Inf s) section variables [complete_semilattice_Inf α] {s t : set α} {a b : α} @[ematch] theorem Inf_le : a ∈ s → Inf s ≤ a := complete_semilattice_Inf.Inf_le s a theorem le_Inf : (∀ b ∈ s, a ≤ b) → a ≤ Inf s := complete_semilattice_Inf.le_Inf s a lemma is_glb_Inf (s : set α) : is_glb s (Inf s) := ⟨λ a, Inf_le, λ a, le_Inf⟩ lemma is_glb.Inf_eq (h : is_glb s a) : Inf s = a := (is_glb_Inf s).unique h theorem Inf_le_of_le (hb : b ∈ s) (h : b ≤ a) : Inf s ≤ a := le_trans (Inf_le hb) h theorem Inf_le_Inf (h : s ⊆ t) : Inf t ≤ Inf s := (is_glb_Inf s).mono (is_glb_Inf t) h @[simp] theorem le_Inf_iff : a ≤ Inf s ↔ ∀ b ∈ s, a ≤ b := le_is_glb_iff (is_glb_Inf s) lemma Inf_le_iff : Inf s ≤ a ↔ ∀ b ∈ lower_bounds s, b ≤ a := ⟨λ h b hb, le_trans (le_Inf hb) h, λ hb, hb _ (λ x, Inf_le)⟩ lemma infi_le_iff {s : ι → α} : infi s ≤ a ↔ ∀ b, (∀ i, b ≤ s i) → b ≤ a := by simp [infi, Inf_le_iff, lower_bounds] theorem Inf_le_Inf_of_forall_exists_le (h : ∀ x ∈ s, ∃ y ∈ t, y ≤ x) : Inf t ≤ Inf s := le_of_forall_le begin simp only [le_Inf_iff], introv h₀ h₁, rcases h _ h₁ with ⟨y, hy, hy'⟩, solve_by_elim [le_trans _ hy'] end -- We will generalize this to conditionally complete lattices in `cInf_singleton`. theorem Inf_singleton {a : α} : Inf {a} = a := is_glb_singleton.Inf_eq end /-- A complete lattice is a bounded lattice which has suprema and infima for every subset. -/ @[protect_proj, ancestor lattice complete_semilattice_Sup complete_semilattice_Inf has_top has_bot] class complete_lattice (α : Type*) extends lattice α, complete_semilattice_Sup α, complete_semilattice_Inf α, has_top α, has_bot α := (le_top : ∀ x : α, x ≤ ⊤) (bot_le : ∀ x : α, ⊥ ≤ x) @[priority 100] -- see Note [lower instance priority] instance complete_lattice.to_bounded_order [h : complete_lattice α] : bounded_order α := { ..h } /-- Create a `complete_lattice` from a `partial_order` and `Inf` function that returns the greatest lower bound of a set. Usually this constructor provides poor definitional equalities. If other fields are known explicitly, they should be provided; for example, if `inf` is known explicitly, construct the `complete_lattice` instance as ``` instance : complete_lattice my_T := { inf := better_inf, le_inf := ..., inf_le_right := ..., inf_le_left := ... -- don't care to fix sup, Sup, bot, top ..complete_lattice_of_Inf my_T _ } ``` -/ def complete_lattice_of_Inf (α : Type*) [H1 : partial_order α] [H2 : has_Inf α] (is_glb_Inf : ∀ s : set α, is_glb s (Inf s)) : complete_lattice α := { bot := Inf univ, bot_le := λ x, (is_glb_Inf univ).1 trivial, top := Inf ∅, le_top := λ a, (is_glb_Inf ∅).2 $ by simp, sup := λ a b, Inf {x | a ≤ x ∧ b ≤ x}, inf := λ a b, Inf {a, b}, le_inf := λ a b c hab hac, by { apply (is_glb_Inf _).2, simp [*] }, inf_le_right := λ a b, (is_glb_Inf _).1 $ mem_insert_of_mem _ $ mem_singleton _, inf_le_left := λ a b, (is_glb_Inf _).1 $ mem_insert _ _, sup_le := λ a b c hac hbc, (is_glb_Inf _).1 $ by simp [*], le_sup_left := λ a b, (is_glb_Inf _).2 $ λ x, and.left, le_sup_right := λ a b, (is_glb_Inf _).2 $ λ x, and.right, le_Inf := λ s a ha, (is_glb_Inf s).2 ha, Inf_le := λ s a ha, (is_glb_Inf s).1 ha, Sup := λ s, Inf (upper_bounds s), le_Sup := λ s a ha, (is_glb_Inf (upper_bounds s)).2 $ λ b hb, hb ha, Sup_le := λ s a ha, (is_glb_Inf (upper_bounds s)).1 ha, .. H1, .. H2 } /-- Any `complete_semilattice_Inf` is in fact a `complete_lattice`. Note that this construction has bad definitional properties: see the doc-string on `complete_lattice_of_Inf`. -/ def complete_lattice_of_complete_semilattice_Inf (α : Type*) [complete_semilattice_Inf α] : complete_lattice α := complete_lattice_of_Inf α (λ s, is_glb_Inf s) /-- Create a `complete_lattice` from a `partial_order` and `Sup` function that returns the least upper bound of a set. Usually this constructor provides poor definitional equalities. If other fields are known explicitly, they should be provided; for example, if `inf` is known explicitly, construct the `complete_lattice` instance as ``` instance : complete_lattice my_T := { inf := better_inf, le_inf := ..., inf_le_right := ..., inf_le_left := ... -- don't care to fix sup, Inf, bot, top ..complete_lattice_of_Sup my_T _ } ``` -/ def complete_lattice_of_Sup (α : Type*) [H1 : partial_order α] [H2 : has_Sup α] (is_lub_Sup : ∀ s : set α, is_lub s (Sup s)) : complete_lattice α := { top := Sup univ, le_top := λ x, (is_lub_Sup univ).1 trivial, bot := Sup ∅, bot_le := λ x, (is_lub_Sup ∅).2 $ by simp, sup := λ a b, Sup {a, b}, sup_le := λ a b c hac hbc, (is_lub_Sup _).2 (by simp [*]), le_sup_left := λ a b, (is_lub_Sup _).1 $ mem_insert _ _, le_sup_right := λ a b, (is_lub_Sup _).1 $ mem_insert_of_mem _ $ mem_singleton _, inf := λ a b, Sup {x | x ≤ a ∧ x ≤ b}, le_inf := λ a b c hab hac, (is_lub_Sup _).1 $ by simp [*], inf_le_left := λ a b, (is_lub_Sup _).2 (λ x, and.left), inf_le_right := λ a b, (is_lub_Sup _).2 (λ x, and.right), Inf := λ s, Sup (lower_bounds s), Sup_le := λ s a ha, (is_lub_Sup s).2 ha, le_Sup := λ s a ha, (is_lub_Sup s).1 ha, Inf_le := λ s a ha, (is_lub_Sup (lower_bounds s)).2 (λ b hb, hb ha), le_Inf := λ s a ha, (is_lub_Sup (lower_bounds s)).1 ha, .. H1, .. H2 } /-- Any `complete_semilattice_Sup` is in fact a `complete_lattice`. Note that this construction has bad definitional properties: see the doc-string on `complete_lattice_of_Sup`. -/ def complete_lattice_of_complete_semilattice_Sup (α : Type*) [complete_semilattice_Sup α] : complete_lattice α := complete_lattice_of_Sup α (λ s, is_lub_Sup s) /-- A complete linear order is a linear order whose lattice structure is complete. -/ class complete_linear_order (α : Type*) extends complete_lattice α, linear_order α renaming max → sup min → inf namespace order_dual variable (α) instance [complete_lattice α] : complete_lattice αᵒᵈ := { le_Sup := @complete_lattice.Inf_le α _, Sup_le := @complete_lattice.le_Inf α _, Inf_le := @complete_lattice.le_Sup α _, le_Inf := @complete_lattice.Sup_le α _, .. order_dual.lattice α, ..order_dual.has_Sup α, ..order_dual.has_Inf α, .. order_dual.bounded_order α } instance [complete_linear_order α] : complete_linear_order αᵒᵈ := { .. order_dual.complete_lattice α, .. order_dual.linear_order α } end order_dual section variables [complete_lattice α] {s t : set α} {a b : α} theorem Inf_le_Sup (hs : s.nonempty) : Inf s ≤ Sup s := is_glb_le_is_lub (is_glb_Inf s) (is_lub_Sup s) hs theorem Sup_union {s t : set α} : Sup (s ∪ t) = Sup s ⊔ Sup t := ((is_lub_Sup s).union (is_lub_Sup t)).Sup_eq theorem Inf_union {s t : set α} : Inf (s ∪ t) = Inf s ⊓ Inf t := ((is_glb_Inf s).union (is_glb_Inf t)).Inf_eq theorem Sup_inter_le {s t : set α} : Sup (s ∩ t) ≤ Sup s ⊓ Sup t := Sup_le $ λ b hb, le_inf (le_Sup hb.1) (le_Sup hb.2) theorem le_Inf_inter {s t : set α} : Inf s ⊔ Inf t ≤ Inf (s ∩ t) := @Sup_inter_le αᵒᵈ _ _ _ @[simp] theorem Sup_empty : Sup ∅ = (⊥ : α) := (@is_lub_empty α _ _).Sup_eq @[simp] theorem Inf_empty : Inf ∅ = (⊤ : α) := (@is_glb_empty α _ _).Inf_eq @[simp] theorem Sup_univ : Sup univ = (⊤ : α) := (@is_lub_univ α _ _).Sup_eq @[simp] theorem Inf_univ : Inf univ = (⊥ : α) := (@is_glb_univ α _ _).Inf_eq -- TODO(Jeremy): get this automatically @[simp] theorem Sup_insert {a : α} {s : set α} : Sup (insert a s) = a ⊔ Sup s := ((is_lub_Sup s).insert a).Sup_eq @[simp] theorem Inf_insert {a : α} {s : set α} : Inf (insert a s) = a ⊓ Inf s := ((is_glb_Inf s).insert a).Inf_eq theorem Sup_le_Sup_of_subset_insert_bot (h : s ⊆ insert ⊥ t) : Sup s ≤ Sup t := le_trans (Sup_le_Sup h) (le_of_eq (trans Sup_insert bot_sup_eq)) theorem Inf_le_Inf_of_subset_insert_top (h : s ⊆ insert ⊤ t) : Inf t ≤ Inf s := le_trans (le_of_eq (trans top_inf_eq.symm Inf_insert.symm)) (Inf_le_Inf h) @[simp] theorem Sup_diff_singleton_bot (s : set α) : Sup (s \ {⊥}) = Sup s := (Sup_le_Sup (diff_subset _ _)).antisymm $ Sup_le_Sup_of_subset_insert_bot $ subset_insert_diff_singleton _ _ @[simp] theorem Inf_diff_singleton_top (s : set α) : Inf (s \ {⊤}) = Inf s := @Sup_diff_singleton_bot αᵒᵈ _ s theorem Sup_pair {a b : α} : Sup {a, b} = a ⊔ b := (@is_lub_pair α _ a b).Sup_eq theorem Inf_pair {a b : α} : Inf {a, b} = a ⊓ b := (@is_glb_pair α _ a b).Inf_eq @[simp] lemma Sup_eq_bot : Sup s = ⊥ ↔ ∀ a ∈ s, a = ⊥ := ⟨λ h a ha, bot_unique $ h ▸ le_Sup ha, λ h, bot_unique $ Sup_le $ λ a ha, le_bot_iff.2 $ h a ha⟩ @[simp] lemma Inf_eq_top : Inf s = ⊤ ↔ ∀ a ∈ s, a = ⊤ := @Sup_eq_bot αᵒᵈ _ _ lemma eq_singleton_bot_of_Sup_eq_bot_of_nonempty {s : set α} (h_sup : Sup s = ⊥) (hne : s.nonempty) : s = {⊥} := by { rw set.eq_singleton_iff_nonempty_unique_mem, rw Sup_eq_bot at h_sup, exact ⟨hne, h_sup⟩, } lemma eq_singleton_top_of_Inf_eq_top_of_nonempty : Inf s = ⊤ → s.nonempty → s = {⊤} := @eq_singleton_bot_of_Sup_eq_bot_of_nonempty αᵒᵈ _ _ /--Introduction rule to prove that `b` is the supremum of `s`: it suffices to check that `b` is larger than all elements of `s`, and that this is not the case of any `w < b`. See `cSup_eq_of_forall_le_of_forall_lt_exists_gt` for a version in conditionally complete lattices. -/ theorem Sup_eq_of_forall_le_of_forall_lt_exists_gt (h₁ : ∀ a ∈ s, a ≤ b) (h₂ : ∀ w, w < b → ∃ a ∈ s, w < a) : Sup s = b := (Sup_le h₁).eq_of_not_lt $ λ h, let ⟨a, ha, ha'⟩ := h₂ _ h in ((le_Sup ha).trans_lt ha').false /--Introduction rule to prove that `b` is the infimum of `s`: it suffices to check that `b` is smaller than all elements of `s`, and that this is not the case of any `w > b`. See `cInf_eq_of_forall_ge_of_forall_gt_exists_lt` for a version in conditionally complete lattices. -/ theorem Inf_eq_of_forall_ge_of_forall_gt_exists_lt : (∀ a ∈ s, b ≤ a) → (∀ w, b < w → ∃ a ∈ s, a < w) → Inf s = b := @Sup_eq_of_forall_le_of_forall_lt_exists_gt αᵒᵈ _ _ _ end section complete_linear_order variables [complete_linear_order α] {s t : set α} {a b : α} lemma lt_Sup_iff : b < Sup s ↔ ∃ a ∈ s, b < a := lt_is_lub_iff $ is_lub_Sup s lemma Inf_lt_iff : Inf s < b ↔ ∃ a ∈ s, a < b := is_glb_lt_iff $ is_glb_Inf s lemma Sup_eq_top : Sup s = ⊤ ↔ ∀ b < ⊤, ∃ a ∈ s, b < a := ⟨λ h b hb, lt_Sup_iff.1 $ hb.trans_eq h.symm, λ h, top_unique $ le_of_not_gt $ λ h', let ⟨a, ha, h⟩ := h _ h' in (h.trans_le $ le_Sup ha).false⟩ lemma Inf_eq_bot : Inf s = ⊥ ↔ ∀ b > ⊥, ∃ a ∈ s, a < b := @Sup_eq_top αᵒᵈ _ _ lemma lt_supr_iff {f : ι → α} : a < supr f ↔ ∃ i, a < f i := lt_Sup_iff.trans exists_range_iff lemma infi_lt_iff {f : ι → α} : infi f < a ↔ ∃ i, f i < a := Inf_lt_iff.trans exists_range_iff end complete_linear_order /- ### supr & infi -/ section has_Sup variables [has_Sup α] {f g : ι → α} lemma Sup_range : Sup (range f) = supr f := rfl lemma Sup_eq_supr' (s : set α) : Sup s = ⨆ a : s, a := by rw [supr, subtype.range_coe] lemma supr_congr (h : ∀ i, f i = g i) : (⨆ i, f i) = ⨆ i, g i := congr_arg _ $ funext h lemma function.surjective.supr_comp {f : ι → ι'} (hf : surjective f) (g : ι' → α) : (⨆ x, g (f x)) = ⨆ y, g y := by simp only [supr, hf.range_comp] lemma equiv.supr_comp {g : ι' → α} (e : ι ≃ ι') : (⨆ x, g (e x)) = ⨆ y, g y := e.surjective.supr_comp _ protected lemma function.surjective.supr_congr {g : ι' → α} (h : ι → ι') (h1 : surjective h) (h2 : ∀ x, g (h x) = f x) : (⨆ x, f x) = ⨆ y, g y := by { convert h1.supr_comp g, exact (funext h2).symm } protected lemma equiv.supr_congr {g : ι' → α} (e : ι ≃ ι') (h : ∀ x, g (e x) = f x) : (⨆ x, f x) = ⨆ y, g y := e.surjective.supr_congr _ h @[congr] lemma supr_congr_Prop {p q : Prop} {f₁ : p → α} {f₂ : q → α} (pq : p ↔ q) (f : ∀ x, f₁ (pq.mpr x) = f₂ x) : supr f₁ = supr f₂ := by { obtain rfl := propext pq, congr' with x, apply f } lemma supr_range' (g : β → α) (f : ι → β) : (⨆ b : range f, g b) = ⨆ i, g (f i) := by rw [supr, supr, ← image_eq_range, ← range_comp] lemma Sup_image' {s : set β} {f : β → α} : Sup (f '' s) = ⨆ a : s, f a := by rw [supr, image_eq_range] end has_Sup section has_Inf variables [has_Inf α] {f g : ι → α} lemma Inf_range : Inf (range f) = infi f := rfl lemma Inf_eq_infi' (s : set α) : Inf s = ⨅ a : s, a := @Sup_eq_supr' αᵒᵈ _ _ lemma infi_congr (h : ∀ i, f i = g i) : (⨅ i, f i) = ⨅ i, g i := congr_arg _ $ funext h lemma function.surjective.infi_comp {f : ι → ι'} (hf : surjective f) (g : ι' → α) : (⨅ x, g (f x)) = ⨅ y, g y := @function.surjective.supr_comp αᵒᵈ _ _ _ f hf g lemma equiv.infi_comp {g : ι' → α} (e : ι ≃ ι') : (⨅ x, g (e x)) = ⨅ y, g y := @equiv.supr_comp αᵒᵈ _ _ _ _ e protected lemma function.surjective.infi_congr {g : ι' → α} (h : ι → ι') (h1 : surjective h) (h2 : ∀ x, g (h x) = f x) : (⨅ x, f x) = ⨅ y, g y := @function.surjective.supr_congr αᵒᵈ _ _ _ _ _ h h1 h2 protected lemma equiv.infi_congr {g : ι' → α} (e : ι ≃ ι') (h : ∀ x, g (e x) = f x) : (⨅ x, f x) = ⨅ y, g y := @equiv.supr_congr αᵒᵈ _ _ _ _ _ e h @[congr]lemma infi_congr_Prop {p q : Prop} {f₁ : p → α} {f₂ : q → α} (pq : p ↔ q) (f : ∀ x, f₁ (pq.mpr x) = f₂ x) : infi f₁ = infi f₂ := @supr_congr_Prop αᵒᵈ _ p q f₁ f₂ pq f lemma infi_range' (g : β → α) (f : ι → β) : (⨅ b : range f, g b) = ⨅ i, g (f i) := @supr_range' αᵒᵈ _ _ _ _ _ lemma Inf_image' {s : set β} {f : β → α} : Inf (f '' s) = ⨅ a : s, f a := @Sup_image' αᵒᵈ _ _ _ _ end has_Inf section variables [complete_lattice α] {f g s t : ι → α} {a b : α} -- TODO: this declaration gives error when starting smt state --@[ematch] lemma le_supr (f : ι → α) (i : ι) : f i ≤ supr f := le_Sup ⟨i, rfl⟩ lemma infi_le (f : ι → α) (i : ι) : infi f ≤ f i := Inf_le ⟨i, rfl⟩ @[ematch] lemma le_supr' (f : ι → α) (i : ι) : (: f i ≤ supr f :) := le_Sup ⟨i, rfl⟩ @[ematch] lemma infi_le' (f : ι → α) (i : ι) : (: infi f ≤ f i :) := Inf_le ⟨i, rfl⟩ /- TODO: this version would be more powerful, but, alas, the pattern matcher doesn't accept it. @[ematch] lemma le_supr' (f : ι → α) (i : ι) : (: f i :) ≤ (: supr f :) := le_Sup ⟨i, rfl⟩ -/ lemma is_lub_supr : is_lub (range f) (⨆ j, f j) := is_lub_Sup _ lemma is_glb_infi : is_glb (range f) (⨅ j, f j) := is_glb_Inf _ lemma is_lub.supr_eq (h : is_lub (range f) a) : (⨆ j, f j) = a := h.Sup_eq lemma is_glb.infi_eq (h : is_glb (range f) a) : (⨅ j, f j) = a := h.Inf_eq lemma le_supr_of_le (i : ι) (h : a ≤ f i) : a ≤ supr f := h.trans $ le_supr _ i lemma infi_le_of_le (i : ι) (h : f i ≤ a) : infi f ≤ a := (infi_le _ i).trans h lemma le_supr₂ {f : Π i, κ i → α} (i : ι) (j : κ i) : f i j ≤ ⨆ i j, f i j := le_supr_of_le i $ le_supr (f i) j lemma infi₂_le {f : Π i, κ i → α} (i : ι) (j : κ i) : (⨅ i j, f i j) ≤ f i j := infi_le_of_le i $ infi_le (f i) j lemma le_supr₂_of_le {f : Π i, κ i → α} (i : ι) (j : κ i) (h : a ≤ f i j) : a ≤ ⨆ i j, f i j := h.trans $ le_supr₂ i j lemma infi₂_le_of_le {f : Π i, κ i → α} (i : ι) (j : κ i) (h : f i j ≤ a) : (⨅ i j, f i j) ≤ a := (infi₂_le i j).trans h lemma supr_le (h : ∀ i, f i ≤ a) : supr f ≤ a := Sup_le $ λ b ⟨i, eq⟩, eq ▸ h i lemma le_infi (h : ∀ i, a ≤ f i) : a ≤ infi f := le_Inf $ λ b ⟨i, eq⟩, eq ▸ h i lemma supr₂_le {f : Π i, κ i → α} (h : ∀ i j, f i j ≤ a) : (⨆ i j, f i j) ≤ a := supr_le $ λ i, supr_le $ h i lemma le_infi₂ {f : Π i, κ i → α} (h : ∀ i j, a ≤ f i j) : a ≤ ⨅ i j, f i j := le_infi $ λ i, le_infi $ h i lemma supr₂_le_supr (κ : ι → Sort*) (f : ι → α) : (⨆ i (j : κ i), f i) ≤ ⨆ i, f i := supr₂_le $ λ i j, le_supr f i lemma infi_le_infi₂ (κ : ι → Sort*) (f : ι → α) : (⨅ i, f i) ≤ ⨅ i (j : κ i), f i := le_infi₂ $ λ i j, infi_le f i lemma supr_mono (h : ∀ i, f i ≤ g i) : supr f ≤ supr g := supr_le $ λ i, le_supr_of_le i $ h i lemma infi_mono (h : ∀ i, f i ≤ g i) : infi f ≤ infi g := le_infi $ λ i, infi_le_of_le i $ h i lemma supr₂_mono {f g : Π i, κ i → α} (h : ∀ i j, f i j ≤ g i j) : (⨆ i j, f i j) ≤ ⨆ i j, g i j := supr_mono $ λ i, supr_mono $ h i lemma infi₂_mono {f g : Π i, κ i → α} (h : ∀ i j, f i j ≤ g i j) : (⨅ i j, f i j) ≤ ⨅ i j, g i j := infi_mono $ λ i, infi_mono $ h i lemma supr_mono' {g : ι' → α} (h : ∀ i, ∃ i', f i ≤ g i') : supr f ≤ supr g := supr_le $ λ i, exists.elim (h i) le_supr_of_le lemma infi_mono' {g : ι' → α} (h : ∀ i', ∃ i, f i ≤ g i') : infi f ≤ infi g := le_infi $ λ i', exists.elim (h i') infi_le_of_le lemma supr₂_mono' {f : Π i, κ i → α} {g : Π i', κ' i' → α} (h : ∀ i j, ∃ i' j', f i j ≤ g i' j') : (⨆ i j, f i j) ≤ ⨆ i j, g i j := supr₂_le $ λ i j, let ⟨i', j', h⟩ := h i j in le_supr₂_of_le i' j' h lemma infi₂_mono' {f : Π i, κ i → α} {g : Π i', κ' i' → α} (h : ∀ i j, ∃ i' j', f i' j' ≤ g i j) : (⨅ i j, f i j) ≤ ⨅ i j, g i j := le_infi₂ $ λ i j, let ⟨i', j', h⟩ := h i j in infi₂_le_of_le i' j' h lemma supr_const_mono (h : ι → ι') : (⨆ i : ι, a) ≤ ⨆ j : ι', a := supr_le $ le_supr _ ∘ h lemma infi_const_mono (h : ι' → ι) : (⨅ i : ι, a) ≤ ⨅ j : ι', a := le_infi $ infi_le _ ∘ h lemma supr_infi_le_infi_supr (f : ι → ι' → α) : (⨆ i, ⨅ j, f i j) ≤ (⨅ j, ⨆ i, f i j) := supr_le $ λ i, infi_mono $ λ j, le_supr _ i lemma bsupr_mono {p q : ι → Prop} (hpq : ∀ i, p i → q i) : (⨆ i (h : p i), f i) ≤ ⨆ i (h : q i), f i := supr_mono $ λ i, supr_const_mono (hpq i) lemma binfi_mono {p q : ι → Prop} (hpq : ∀ i, p i → q i) : (⨅ i (h : q i), f i) ≤ ⨅ i (h : p i), f i := infi_mono $ λ i, infi_const_mono (hpq i) @[simp] lemma supr_le_iff : supr f ≤ a ↔ ∀ i, f i ≤ a := (is_lub_le_iff is_lub_supr).trans forall_range_iff @[simp] lemma le_infi_iff : a ≤ infi f ↔ ∀ i, a ≤ f i := (le_is_glb_iff is_glb_infi).trans forall_range_iff @[simp] lemma supr₂_le_iff {f : Π i, κ i → α} : (⨆ i j, f i j) ≤ a ↔ ∀ i j, f i j ≤ a := by simp_rw supr_le_iff @[simp] lemma le_infi₂_iff {f : Π i, κ i → α} : a ≤ (⨅ i j, f i j) ↔ ∀ i j, a ≤ f i j := by simp_rw le_infi_iff lemma supr_lt_iff : supr f < a ↔ ∃ b, b < a ∧ ∀ i, f i ≤ b := ⟨λ h, ⟨supr f, h, le_supr f⟩, λ ⟨b, h, hb⟩, (supr_le hb).trans_lt h⟩ lemma lt_infi_iff : a < infi f ↔ ∃ b, a < b ∧ ∀ i, b ≤ f i := ⟨λ h, ⟨infi f, h, infi_le f⟩, λ ⟨b, h, hb⟩, h.trans_le $ le_infi hb⟩ lemma Sup_eq_supr {s : set α} : Sup s = ⨆ a ∈ s, a := le_antisymm (Sup_le le_supr₂) (supr₂_le $ λ b, le_Sup) lemma Inf_eq_infi {s : set α} : Inf s = ⨅ a ∈ s, a := @Sup_eq_supr αᵒᵈ _ _ lemma monotone.le_map_supr [complete_lattice β] {f : α → β} (hf : monotone f) : (⨆ i, f (s i)) ≤ f (supr s) := supr_le $ λ i, hf $ le_supr _ _ lemma antitone.le_map_infi [complete_lattice β] {f : α → β} (hf : antitone f) : (⨆ i, f (s i)) ≤ f (infi s) := hf.dual_left.le_map_supr lemma monotone.le_map_supr₂ [complete_lattice β] {f : α → β} (hf : monotone f) (s : Π i, κ i → α) : (⨆ i j, f (s i j)) ≤ f (⨆ i j, s i j) := supr₂_le $ λ i j, hf $ le_supr₂ _ _ lemma antitone.le_map_infi₂ [complete_lattice β] {f : α → β} (hf : antitone f) (s : Π i, κ i → α) : (⨆ i j, f (s i j)) ≤ f (⨅ i j, s i j) := hf.dual_left.le_map_supr₂ _ lemma monotone.le_map_Sup [complete_lattice β] {s : set α} {f : α → β} (hf : monotone f) : (⨆ a ∈ s, f a) ≤ f (Sup s) := by rw [Sup_eq_supr]; exact hf.le_map_supr₂ _ lemma antitone.le_map_Inf [complete_lattice β] {s : set α} {f : α → β} (hf : antitone f) : (⨆ a ∈ s, f a) ≤ f (Inf s) := hf.dual_left.le_map_Sup lemma order_iso.map_supr [complete_lattice β] (f : α ≃o β) (x : ι → α) : f (⨆ i, x i) = ⨆ i, f (x i) := eq_of_forall_ge_iff $ f.surjective.forall.2 $ λ x, by simp only [f.le_iff_le, supr_le_iff] lemma order_iso.map_infi [complete_lattice β] (f : α ≃o β) (x : ι → α) : f (⨅ i, x i) = ⨅ i, f (x i) := order_iso.map_supr f.dual _ lemma order_iso.map_Sup [complete_lattice β] (f : α ≃o β) (s : set α) : f (Sup s) = ⨆ a ∈ s, f a := by simp only [Sup_eq_supr, order_iso.map_supr] lemma order_iso.map_Inf [complete_lattice β] (f : α ≃o β) (s : set α) : f (Inf s) = ⨅ a ∈ s, f a := order_iso.map_Sup f.dual _ lemma supr_comp_le {ι' : Sort*} (f : ι' → α) (g : ι → ι') : (⨆ x, f (g x)) ≤ ⨆ y, f y := supr_mono' $ λ x, ⟨_, le_rfl⟩ lemma le_infi_comp {ι' : Sort*} (f : ι' → α) (g : ι → ι') : (⨅ y, f y) ≤ ⨅ x, f (g x) := infi_mono' $ λ x, ⟨_, le_rfl⟩ lemma monotone.supr_comp_eq [preorder β] {f : β → α} (hf : monotone f) {s : ι → β} (hs : ∀ x, ∃ i, x ≤ s i) : (⨆ x, f (s x)) = ⨆ y, f y := le_antisymm (supr_comp_le _ _) (supr_mono' $ λ x, (hs x).imp $ λ i hi, hf hi) lemma monotone.infi_comp_eq [preorder β] {f : β → α} (hf : monotone f) {s : ι → β} (hs : ∀ x, ∃ i, s i ≤ x) : (⨅ x, f (s x)) = ⨅ y, f y := le_antisymm (infi_mono' $ λ x, (hs x).imp $ λ i hi, hf hi) (le_infi_comp _ _) lemma antitone.map_supr_le [complete_lattice β] {f : α → β} (hf : antitone f) : f (supr s) ≤ ⨅ i, f (s i) := le_infi $ λ i, hf $ le_supr _ _ lemma monotone.map_infi_le [complete_lattice β] {f : α → β} (hf : monotone f) : f (infi s) ≤ (⨅ i, f (s i)) := hf.dual_left.map_supr_le lemma antitone.map_supr₂_le [complete_lattice β] {f : α → β} (hf : antitone f) (s : Π i, κ i → α) : f (⨆ i j, s i j) ≤ ⨅ i j, f (s i j) := hf.dual.le_map_infi₂ _ lemma monotone.map_infi₂_le [complete_lattice β] {f : α → β} (hf : monotone f) (s : Π i, κ i → α) : f (⨅ i j, s i j) ≤ ⨅ i j, f (s i j) := hf.dual.le_map_supr₂ _ lemma antitone.map_Sup_le [complete_lattice β] {s : set α} {f : α → β} (hf : antitone f) : f (Sup s) ≤ ⨅ a ∈ s, f a := by { rw Sup_eq_supr, exact hf.map_supr₂_le _ } lemma monotone.map_Inf_le [complete_lattice β] {s : set α} {f : α → β} (hf : monotone f) : f (Inf s) ≤ ⨅ a ∈ s, f a := hf.dual_left.map_Sup_le lemma supr_const_le : (⨆ i : ι, a) ≤ a := supr_le $ λ _, le_rfl lemma le_infi_const : a ≤ ⨅ i : ι, a := le_infi $ λ _, le_rfl /- We generalize this to conditionally complete lattices in `csupr_const` and `cinfi_const`. -/ theorem supr_const [nonempty ι] : (⨆ b : ι, a) = a := by rw [supr, range_const, Sup_singleton] theorem infi_const [nonempty ι] : (⨅ b : ι, a) = a := @supr_const αᵒᵈ _ _ a _ @[simp] lemma supr_bot : (⨆ i : ι, ⊥ : α) = ⊥ := bot_unique supr_const_le @[simp] lemma infi_top : (⨅ i : ι, ⊤ : α) = ⊤ := top_unique le_infi_const @[simp] lemma supr_eq_bot : supr s = ⊥ ↔ ∀ i, s i = ⊥ := Sup_eq_bot.trans forall_range_iff @[simp] lemma infi_eq_top : infi s = ⊤ ↔ ∀ i, s i = ⊤ := Inf_eq_top.trans forall_range_iff @[simp] lemma supr₂_eq_bot {f : Π i, κ i → α} : (⨆ i j, f i j) = ⊥ ↔ ∀ i j, f i j = ⊥ := by simp_rw supr_eq_bot @[simp] lemma infi₂_eq_top {f : Π i, κ i → α} : (⨅ i j, f i j) = ⊤ ↔ ∀ i j, f i j = ⊤ := by simp_rw infi_eq_top @[simp] lemma supr_pos {p : Prop} {f : p → α} (hp : p) : (⨆ h : p, f h) = f hp := le_antisymm (supr_le $ λ h, le_rfl) (le_supr _ _) @[simp] lemma infi_pos {p : Prop} {f : p → α} (hp : p) : (⨅ h : p, f h) = f hp := le_antisymm (infi_le _ _) (le_infi $ λ h, le_rfl) @[simp] lemma supr_neg {p : Prop} {f : p → α} (hp : ¬ p) : (⨆ h : p, f h) = ⊥ := le_antisymm (supr_le $ λ h, (hp h).elim) bot_le @[simp] lemma infi_neg {p : Prop} {f : p → α} (hp : ¬ p) : (⨅ h : p, f h) = ⊤ := le_antisymm le_top $ le_infi $ λ h, (hp h).elim /--Introduction rule to prove that `b` is the supremum of `f`: it suffices to check that `b` is larger than `f i` for all `i`, and that this is not the case of any `w<b`. See `csupr_eq_of_forall_le_of_forall_lt_exists_gt` for a version in conditionally complete lattices. -/ theorem supr_eq_of_forall_le_of_forall_lt_exists_gt {f : ι → α} (h₁ : ∀ i, f i ≤ b) (h₂ : ∀ w, w < b → (∃ i, w < f i)) : (⨆ (i : ι), f i) = b := Sup_eq_of_forall_le_of_forall_lt_exists_gt (forall_range_iff.mpr h₁) (λ w hw, exists_range_iff.mpr $ h₂ w hw) /--Introduction rule to prove that `b` is the infimum of `f`: it suffices to check that `b` is smaller than `f i` for all `i`, and that this is not the case of any `w>b`. See `cinfi_eq_of_forall_ge_of_forall_gt_exists_lt` for a version in conditionally complete lattices. -/ theorem infi_eq_of_forall_ge_of_forall_gt_exists_lt : (∀ i, b ≤ f i) → (∀ w, b < w → ∃ i, f i < w) → (⨅ i, f i) = b := @supr_eq_of_forall_le_of_forall_lt_exists_gt αᵒᵈ _ _ _ _ lemma supr_eq_dif {p : Prop} [decidable p] (a : p → α) : (⨆ h : p, a h) = if h : p then a h else ⊥ := by by_cases p; simp [h] lemma supr_eq_if {p : Prop} [decidable p] (a : α) : (⨆ h : p, a) = if p then a else ⊥ := supr_eq_dif (λ _, a) lemma infi_eq_dif {p : Prop} [decidable p] (a : p → α) : (⨅ h : p, a h) = if h : p then a h else ⊤ := @supr_eq_dif αᵒᵈ _ _ _ _ lemma infi_eq_if {p : Prop} [decidable p] (a : α) : (⨅ h : p, a) = if p then a else ⊤ := infi_eq_dif (λ _, a) lemma supr_comm {f : ι → ι' → α} : (⨆ i j, f i j) = ⨆ j i, f i j := le_antisymm (supr_le $ λ i, supr_mono $ λ j, le_supr _ i) (supr_le $ λ j, supr_mono $ λ i, le_supr _ _) lemma infi_comm {f : ι → ι' → α} : (⨅ i j, f i j) = ⨅ j i, f i j := @supr_comm αᵒᵈ _ _ _ _ lemma supr₂_comm {ι₁ ι₂ : Sort*} {κ₁ : ι₁ → Sort*} {κ₂ : ι₂ → Sort*} (f : Π i₁, κ₁ i₁ → Π i₂, κ₂ i₂ → α) : (⨆ i₁ j₁ i₂ j₂, f i₁ j₁ i₂ j₂) = ⨆ i₂ j₂ i₁ j₁, f i₁ j₁ i₂ j₂ := by simp only [@supr_comm _ (κ₁ _), @supr_comm _ ι₁] lemma infi₂_comm {ι₁ ι₂ : Sort*} {κ₁ : ι₁ → Sort*} {κ₂ : ι₂ → Sort*} (f : Π i₁, κ₁ i₁ → Π i₂, κ₂ i₂ → α) : (⨅ i₁ j₁ i₂ j₂, f i₁ j₁ i₂ j₂) = ⨅ i₂ j₂ i₁ j₁, f i₁ j₁ i₂ j₂ := by simp only [@infi_comm _ (κ₁ _), @infi_comm _ ι₁] /- TODO: this is strange. In the proof below, we get exactly the desired among the equalities, but close does not get it. begin apply @le_antisymm, simp, intros, begin [smt] ematch, ematch, ematch, trace_state, have := le_refl (f i_1 i), trace_state, close end end -/ @[simp] theorem supr_supr_eq_left {b : β} {f : Π x : β, x = b → α} : (⨆ x, ⨆ h : x = b, f x h) = f b rfl := (@le_supr₂ _ _ _ _ f b rfl).antisymm' (supr_le $ λ c, supr_le $ by { rintro rfl, refl }) @[simp] theorem infi_infi_eq_left {b : β} {f : Π x : β, x = b → α} : (⨅ x, ⨅ h : x = b, f x h) = f b rfl := @supr_supr_eq_left αᵒᵈ _ _ _ _ @[simp] theorem supr_supr_eq_right {b : β} {f : Π x : β, b = x → α} : (⨆ x, ⨆ h : b = x, f x h) = f b rfl := (le_supr₂ b rfl).antisymm' (supr₂_le $ λ c, by { rintro rfl, refl }) @[simp] theorem infi_infi_eq_right {b : β} {f : Π x : β, b = x → α} : (⨅ x, ⨅ h : b = x, f x h) = f b rfl := @supr_supr_eq_right αᵒᵈ _ _ _ _ attribute [ematch] le_refl theorem supr_subtype {p : ι → Prop} {f : subtype p → α} : supr f = (⨆ i (h : p i), f ⟨i, h⟩) := le_antisymm (supr_le $ λ ⟨i, h⟩, le_supr₂ i h) (supr₂_le $ λ i h, le_supr _ _) theorem infi_subtype : ∀ {p : ι → Prop} {f : subtype p → α}, infi f = (⨅ i (h : p i), f ⟨i, h⟩) := @supr_subtype αᵒᵈ _ _ lemma supr_subtype' {p : ι → Prop} {f : Π i, p i → α} : (⨆ i h, f i h) = ⨆ x : subtype p, f x x.property := (@supr_subtype _ _ _ p (λ x, f x.val x.property)).symm lemma infi_subtype' {p : ι → Prop} {f : ∀ i, p i → α} : (⨅ i (h : p i), f i h) = (⨅ x : subtype p, f x x.property) := (@infi_subtype _ _ _ p (λ x, f x.val x.property)).symm lemma supr_subtype'' {ι} (s : set ι) (f : ι → α) : (⨆ i : s, f i) = ⨆ (t : ι) (H : t ∈ s), f t := supr_subtype lemma infi_subtype'' {ι} (s : set ι) (f : ι → α) : (⨅ i : s, f i) = ⨅ (t : ι) (H : t ∈ s), f t := infi_subtype theorem supr_sup_eq : (⨆ x, f x ⊔ g x) = (⨆ x, f x) ⊔ (⨆ x, g x) := le_antisymm (supr_le $ λ i, sup_le_sup (le_supr _ _) $ le_supr _ _) (sup_le (supr_mono $ λ i, le_sup_left) $ supr_mono $ λ i, le_sup_right) theorem infi_inf_eq : (⨅ x, f x ⊓ g x) = (⨅ x, f x) ⊓ (⨅ x, g x) := @supr_sup_eq αᵒᵈ _ _ _ _ /- TODO: here is another example where more flexible pattern matching might help. begin apply @le_antisymm, safe, pose h := f a ⊓ g a, begin [smt] ematch, ematch end end -/ lemma supr_sup [nonempty ι] {f : ι → α} {a : α} : (⨆ x, f x) ⊔ a = ⨆ x, f x ⊔ a := by rw [supr_sup_eq, supr_const] lemma infi_inf [nonempty ι] {f : ι → α} {a : α} : (⨅ x, f x) ⊓ a = ⨅ x, f x ⊓ a := by rw [infi_inf_eq, infi_const] lemma sup_supr [nonempty ι] {f : ι → α} {a : α} : a ⊔ (⨆ x, f x) = ⨆ x, a ⊔ f x := by rw [supr_sup_eq, supr_const] lemma inf_infi [nonempty ι] {f : ι → α} {a : α} : a ⊓ (⨅ x, f x) = ⨅ x, a ⊓ f x := by rw [infi_inf_eq, infi_const] lemma binfi_inf {p : ι → Prop} {f : Π i (hi : p i), α} {a : α} (h : ∃ i, p i) : (⨅ i (h : p i), f i h) ⊓ a = ⨅ i (h : p i), f i h ⊓ a := by haveI : nonempty {i // p i} := (let ⟨i, hi⟩ := h in ⟨⟨i, hi⟩⟩); rw [infi_subtype', infi_subtype', infi_inf] lemma inf_binfi {p : ι → Prop} {f : Π i (hi : p i), α} {a : α} (h : ∃ i, p i) : a ⊓ (⨅ i (h : p i), f i h) = ⨅ i (h : p i), a ⊓ f i h := by simpa only [inf_comm] using binfi_inf h /-! ### `supr` and `infi` under `Prop` -/ @[simp] theorem supr_false {s : false → α} : supr s = ⊥ := le_antisymm (supr_le $ λ i, false.elim i) bot_le @[simp] theorem infi_false {s : false → α} : infi s = ⊤ := le_antisymm le_top (le_infi $ λ i, false.elim i) lemma supr_true {s : true → α} : supr s = s trivial := supr_pos trivial lemma infi_true {s : true → α} : infi s = s trivial := infi_pos trivial @[simp] lemma supr_exists {p : ι → Prop} {f : Exists p → α} : (⨆ x, f x) = ⨆ i h, f ⟨i, h⟩ := le_antisymm (supr_le $ λ ⟨i, h⟩, le_supr₂ i h) (supr₂_le $ λ i h, le_supr _ _) @[simp] lemma infi_exists {p : ι → Prop} {f : Exists p → α} : (⨅ x, f x) = ⨅ i h, f ⟨i, h⟩ := @supr_exists αᵒᵈ _ _ _ _ lemma supr_and {p q : Prop} {s : p ∧ q → α} : supr s = ⨆ h₁ h₂, s ⟨h₁, h₂⟩ := le_antisymm (supr_le $ λ ⟨i, h⟩, le_supr₂ i h) (supr₂_le $ λ i h, le_supr _ _) lemma infi_and {p q : Prop} {s : p ∧ q → α} : infi s = ⨅ h₁ h₂, s ⟨h₁, h₂⟩ := @supr_and αᵒᵈ _ _ _ _ /-- The symmetric case of `supr_and`, useful for rewriting into a supremum over a conjunction -/ lemma supr_and' {p q : Prop} {s : p → q → α} : (⨆ (h₁ : p) (h₂ : q), s h₁ h₂) = ⨆ (h : p ∧ q), s h.1 h.2 := eq.symm supr_and /-- The symmetric case of `infi_and`, useful for rewriting into a infimum over a conjunction -/ lemma infi_and' {p q : Prop} {s : p → q → α} : (⨅ (h₁ : p) (h₂ : q), s h₁ h₂) = ⨅ (h : p ∧ q), s h.1 h.2 := eq.symm infi_and theorem supr_or {p q : Prop} {s : p ∨ q → α} : (⨆ x, s x) = (⨆ i, s (or.inl i)) ⊔ (⨆ j, s (or.inr j)) := le_antisymm (supr_le $ λ i, match i with | or.inl i := le_sup_of_le_left $ le_supr _ i | or.inr j := le_sup_of_le_right $ le_supr _ j end) (sup_le (supr_comp_le _ _) (supr_comp_le _ _)) theorem infi_or {p q : Prop} {s : p ∨ q → α} : (⨅ x, s x) = (⨅ i, s (or.inl i)) ⊓ (⨅ j, s (or.inr j)) := @supr_or αᵒᵈ _ _ _ _ section variables (p : ι → Prop) [decidable_pred p] lemma supr_dite (f : Π i, p i → α) (g : Π i, ¬p i → α) : (⨆ i, if h : p i then f i h else g i h) = (⨆ i (h : p i), f i h) ⊔ (⨆ i (h : ¬ p i), g i h) := begin rw ←supr_sup_eq, congr' 1 with i, split_ifs with h; simp [h], end lemma infi_dite (f : Π i, p i → α) (g : Π i, ¬p i → α) : (⨅ i, if h : p i then f i h else g i h) = (⨅ i (h : p i), f i h) ⊓ (⨅ i (h : ¬ p i), g i h) := supr_dite p (show Π i, p i → αᵒᵈ, from f) g lemma supr_ite (f g : ι → α) : (⨆ i, if p i then f i else g i) = (⨆ i (h : p i), f i) ⊔ (⨆ i (h : ¬ p i), g i) := supr_dite _ _ _ lemma infi_ite (f g : ι → α) : (⨅ i, if p i then f i else g i) = (⨅ i (h : p i), f i) ⊓ (⨅ i (h : ¬ p i), g i) := infi_dite _ _ _ end lemma supr_range {g : β → α} {f : ι → β} : (⨆ b ∈ range f, g b) = ⨆ i, g (f i) := by rw [← supr_subtype'', supr_range'] lemma infi_range : ∀ {g : β → α} {f : ι → β}, (⨅ b ∈ range f, g b) = ⨅ i, g (f i) := @supr_range αᵒᵈ _ _ _ theorem Sup_image {s : set β} {f : β → α} : Sup (f '' s) = ⨆ a ∈ s, f a := by rw [← supr_subtype'', Sup_image'] theorem Inf_image {s : set β} {f : β → α} : Inf (f '' s) = ⨅ a ∈ s, f a := @Sup_image αᵒᵈ _ _ _ _ /- ### supr and infi under set constructions -/ theorem supr_emptyset {f : β → α} : (⨆ x ∈ (∅ : set β), f x) = ⊥ := by simp theorem infi_emptyset {f : β → α} : (⨅ x ∈ (∅ : set β), f x) = ⊤ := by simp theorem supr_univ {f : β → α} : (⨆ x ∈ (univ : set β), f x) = ⨆ x, f x := by simp theorem infi_univ {f : β → α} : (⨅ x ∈ (univ : set β), f x) = ⨅ x, f x := by simp theorem supr_union {f : β → α} {s t : set β} : (⨆ x ∈ s ∪ t, f x) = (⨆ x ∈ s, f x) ⊔ (⨆ x ∈ t, f x) := by simp_rw [mem_union, supr_or, supr_sup_eq] theorem infi_union {f : β → α} {s t : set β} : (⨅ x ∈ s ∪ t, f x) = (⨅ x ∈ s, f x) ⊓ (⨅ x ∈ t, f x) := @supr_union αᵒᵈ _ _ _ _ _ lemma supr_split (f : β → α) (p : β → Prop) : (⨆ i, f i) = (⨆ i (h : p i), f i) ⊔ (⨆ i (h : ¬ p i), f i) := by simpa [classical.em] using @supr_union _ _ _ f {i | p i} {i | ¬ p i} lemma infi_split : ∀ (f : β → α) (p : β → Prop), (⨅ i, f i) = (⨅ i (h : p i), f i) ⊓ (⨅ i (h : ¬ p i), f i) := @supr_split αᵒᵈ _ _ lemma supr_split_single (f : β → α) (i₀ : β) : (⨆ i, f i) = f i₀ ⊔ ⨆ i (h : i ≠ i₀), f i := by { convert supr_split _ _, simp } lemma infi_split_single (f : β → α) (i₀ : β) : (⨅ i, f i) = f i₀ ⊓ ⨅ i (h : i ≠ i₀), f i := @supr_split_single αᵒᵈ _ _ _ _ lemma supr_le_supr_of_subset {f : β → α} {s t : set β} : s ⊆ t → (⨆ x ∈ s, f x) ≤ ⨆ x ∈ t, f x := bsupr_mono lemma infi_le_infi_of_subset {f : β → α} {s t : set β} : s ⊆ t → (⨅ x ∈ t, f x) ≤ ⨅ x ∈ s, f x := binfi_mono theorem supr_insert {f : β → α} {s : set β} {b : β} : (⨆ x ∈ insert b s, f x) = f b ⊔ (⨆ x ∈ s, f x) := eq.trans supr_union $ congr_arg (λ x, x ⊔ (⨆ x ∈ s, f x)) supr_supr_eq_left theorem infi_insert {f : β → α} {s : set β} {b : β} : (⨅ x ∈ insert b s, f x) = f b ⊓ (⨅ x ∈ s, f x) := eq.trans infi_union $ congr_arg (λ x, x ⊓ (⨅ x ∈ s, f x)) infi_infi_eq_left theorem supr_singleton {f : β → α} {b : β} : (⨆ x ∈ (singleton b : set β), f x) = f b := by simp theorem infi_singleton {f : β → α} {b : β} : (⨅ x ∈ (singleton b : set β), f x) = f b := by simp theorem supr_pair {f : β → α} {a b : β} : (⨆ x ∈ ({a, b} : set β), f x) = f a ⊔ f b := by rw [supr_insert, supr_singleton] theorem infi_pair {f : β → α} {a b : β} : (⨅ x ∈ ({a, b} : set β), f x) = f a ⊓ f b := by rw [infi_insert, infi_singleton] lemma supr_image {γ} {f : β → γ} {g : γ → α} {t : set β} : (⨆ c ∈ f '' t, g c) = (⨆ b ∈ t, g (f b)) := by rw [← Sup_image, ← Sup_image, ← image_comp] lemma infi_image : ∀ {γ} {f : β → γ} {g : γ → α} {t : set β}, (⨅ c ∈ f '' t, g c) = (⨅ b ∈ t, g (f b)) := @supr_image αᵒᵈ _ _ theorem supr_extend_bot {e : ι → β} (he : injective e) (f : ι → α) : (⨆ j, extend e f ⊥ j) = ⨆ i, f i := begin rw supr_split _ (λ j, ∃ i, e i = j), simp [extend_apply he, extend_apply', @supr_comm _ β ι] { contextual := tt } end lemma infi_extend_top {e : ι → β} (he : injective e) (f : ι → α) : (⨅ j, extend e f ⊤ j) = infi f := @supr_extend_bot αᵒᵈ _ _ _ _ he _ /-! ### `supr` and `infi` under `Type` -/ theorem supr_of_empty' {α ι} [has_Sup α] [is_empty ι] (f : ι → α) : supr f = Sup (∅ : set α) := congr_arg Sup (range_eq_empty f) theorem infi_of_empty' {α ι} [has_Inf α] [is_empty ι] (f : ι → α) : infi f = Inf (∅ : set α) := congr_arg Inf (range_eq_empty f) theorem supr_of_empty [is_empty ι] (f : ι → α) : supr f = ⊥ := (supr_of_empty' f).trans Sup_empty theorem infi_of_empty [is_empty ι] (f : ι → α) : infi f = ⊤ := @supr_of_empty αᵒᵈ _ _ _ f lemma supr_bool_eq {f : bool → α} : (⨆b:bool, f b) = f tt ⊔ f ff := by rw [supr, bool.range_eq, Sup_pair, sup_comm] lemma infi_bool_eq {f : bool → α} : (⨅b:bool, f b) = f tt ⊓ f ff := @supr_bool_eq αᵒᵈ _ _ lemma sup_eq_supr (x y : α) : x ⊔ y = ⨆ b : bool, cond b x y := by rw [supr_bool_eq, bool.cond_tt, bool.cond_ff] lemma inf_eq_infi (x y : α) : x ⊓ y = ⨅ b : bool, cond b x y := @sup_eq_supr αᵒᵈ _ _ _ lemma is_glb_binfi {s : set β} {f : β → α} : is_glb (f '' s) (⨅ x ∈ s, f x) := by simpa only [range_comp, subtype.range_coe, infi_subtype'] using @is_glb_infi α s _ (f ∘ coe) lemma is_lub_bsupr {s : set β} {f : β → α} : is_lub (f '' s) (⨆ x ∈ s, f x) := by simpa only [range_comp, subtype.range_coe, supr_subtype'] using @is_lub_supr α s _ (f ∘ coe) theorem supr_sigma {p : β → Type*} {f : sigma p → α} : (⨆ x, f x) = ⨆ i j, f ⟨i, j⟩ := eq_of_forall_ge_iff $ λ c, by simp only [supr_le_iff, sigma.forall] theorem infi_sigma {p : β → Type*} {f : sigma p → α} : (⨅ x, f x) = ⨅ i j, f ⟨i, j⟩ := @supr_sigma αᵒᵈ _ _ _ _ theorem supr_prod {f : β × γ → α} : (⨆ x, f x) = ⨆ i j, f (i, j) := eq_of_forall_ge_iff $ λ c, by simp only [supr_le_iff, prod.forall] theorem infi_prod {f : β × γ → α} : (⨅ x, f x) = ⨅ i j, f (i, j) := @supr_prod αᵒᵈ _ _ _ _ lemma bsupr_prod {f : β × γ → α} {s : set β} {t : set γ} : (⨆ x ∈ s ×ˢ t, f x) = ⨆ (a ∈ s) (b ∈ t), f (a, b) := by { simp_rw [supr_prod, mem_prod, supr_and], exact supr_congr (λ _, supr_comm) } lemma binfi_prod {f : β × γ → α} {s : set β} {t : set γ} : (⨅ x ∈ s ×ˢ t, f x) = ⨅ (a ∈ s) (b ∈ t), f (a, b) := @bsupr_prod αᵒᵈ _ _ _ _ _ _ theorem supr_sum {f : β ⊕ γ → α} : (⨆ x, f x) = (⨆ i, f (sum.inl i)) ⊔ (⨆ j, f (sum.inr j)) := eq_of_forall_ge_iff $ λ c, by simp only [sup_le_iff, supr_le_iff, sum.forall] theorem infi_sum {f : β ⊕ γ → α} : (⨅ x, f x) = (⨅ i, f (sum.inl i)) ⊓ (⨅ j, f (sum.inr j)) := @supr_sum αᵒᵈ _ _ _ _ theorem supr_option (f : option β → α) : (⨆ o, f o) = f none ⊔ ⨆ b, f (option.some b) := eq_of_forall_ge_iff $ λ c, by simp only [supr_le_iff, sup_le_iff, option.forall] theorem infi_option (f : option β → α) : (⨅ o, f o) = f none ⊓ ⨅ b, f (option.some b) := @supr_option αᵒᵈ _ _ _ /-- A version of `supr_option` useful for rewriting right-to-left. -/ lemma supr_option_elim (a : α) (f : β → α) : (⨆ o : option β, o.elim a f) = a ⊔ ⨆ b, f b := by simp [supr_option] /-- A version of `infi_option` useful for rewriting right-to-left. -/ lemma infi_option_elim (a : α) (f : β → α) : (⨅ o : option β, o.elim a f) = a ⊓ ⨅ b, f b := @supr_option_elim αᵒᵈ _ _ _ _ /-- When taking the supremum of `f : ι → α`, the elements of `ι` on which `f` gives `⊥` can be dropped, without changing the result. -/ lemma supr_ne_bot_subtype (f : ι → α) : (⨆ i : {i // f i ≠ ⊥}, f i) = ⨆ i, f i := begin by_cases htriv : ∀ i, f i = ⊥, { simp only [supr_bot, (funext htriv : f = _)] }, refine (supr_comp_le f _).antisymm (supr_mono' $ λ i, _), by_cases hi : f i = ⊥, { rw hi, obtain ⟨i₀, hi₀⟩ := not_forall.mp htriv, exact ⟨⟨i₀, hi₀⟩, bot_le⟩ }, { exact ⟨⟨i, hi⟩, rfl.le⟩ }, end /-- When taking the infimum of `f : ι → α`, the elements of `ι` on which `f` gives `⊤` can be dropped, without changing the result. -/ lemma infi_ne_top_subtype (f : ι → α) : (⨅ i : {i // f i ≠ ⊤}, f i) = ⨅ i, f i := @supr_ne_bot_subtype αᵒᵈ ι _ f lemma Sup_image2 {f : β → γ → α} {s : set β} {t : set γ} : Sup (image2 f s t) = ⨆ (a ∈ s) (b ∈ t), f a b := by rw [←image_prod, Sup_image, bsupr_prod] lemma Inf_image2 {f : β → γ → α} {s : set β} {t : set γ} : Inf (image2 f s t) = ⨅ (a ∈ s) (b ∈ t), f a b := by rw [←image_prod, Inf_image, binfi_prod] /-! ### `supr` and `infi` under `ℕ` -/ lemma supr_ge_eq_supr_nat_add (u : ℕ → α) (n : ℕ) : (⨆ i ≥ n, u i) = ⨆ i, u (i + n) := begin apply le_antisymm; simp only [supr_le_iff], { exact λ i hi, le_Sup ⟨i - n, by { dsimp only, rw tsub_add_cancel_of_le hi }⟩ }, { exact λ i, le_Sup ⟨i + n, supr_pos (nat.le_add_left _ _)⟩ } end lemma infi_ge_eq_infi_nat_add (u : ℕ → α) (n : ℕ) : (⨅ i ≥ n, u i) = ⨅ i, u (i + n) := @supr_ge_eq_supr_nat_add αᵒᵈ _ _ _ lemma monotone.supr_nat_add {f : ℕ → α} (hf : monotone f) (k : ℕ) : (⨆ n, f (n + k)) = ⨆ n, f n := le_antisymm (supr_le $ λ i, le_supr _ (i + k)) $ supr_mono $ λ i, hf $ nat.le_add_right i k lemma antitone.infi_nat_add {f : ℕ → α} (hf : antitone f) (k : ℕ) : (⨅ n, f (n + k)) = ⨅ n, f n := hf.dual_right.supr_nat_add k @[simp] lemma supr_infi_ge_nat_add (f : ℕ → α) (k : ℕ) : (⨆ n, ⨅ i ≥ n, f (i + k)) = ⨆ n, ⨅ i ≥ n, f i := begin have hf : monotone (λ n, ⨅ i ≥ n, f i) := λ n m h, binfi_mono (λ i, h.trans), rw ←monotone.supr_nat_add hf k, { simp_rw [infi_ge_eq_infi_nat_add, ←nat.add_assoc], }, end @[simp] lemma infi_supr_ge_nat_add : ∀ (f : ℕ → α) (k : ℕ), (⨅ n, ⨆ i ≥ n, f (i + k)) = ⨅ n, ⨆ i ≥ n, f i := @supr_infi_ge_nat_add αᵒᵈ _ lemma sup_supr_nat_succ (u : ℕ → α) : u 0 ⊔ (⨆ i, u (i + 1)) = ⨆ i, u i := begin refine eq_of_forall_ge_iff (λ c, _), simp only [sup_le_iff, supr_le_iff], refine ⟨λ h, _, λ h, ⟨h _, λ i, h _⟩⟩, rintro (_|i), exacts [h.1, h.2 i] end lemma inf_infi_nat_succ (u : ℕ → α) : u 0 ⊓ (⨅ i, u (i + 1)) = ⨅ i, u i := @sup_supr_nat_succ αᵒᵈ _ u end section complete_linear_order variables [complete_linear_order α] lemma supr_eq_top (f : ι → α) : supr f = ⊤ ↔ ∀ b < ⊤, ∃ i, b < f i := by simp only [← Sup_range, Sup_eq_top, set.exists_range_iff] lemma infi_eq_bot (f : ι → α) : infi f = ⊥ ↔ ∀ b > ⊥, ∃ i, f i < b := by simp only [← Inf_range, Inf_eq_bot, set.exists_range_iff] end complete_linear_order /-! ### Instances -/ instance Prop.complete_lattice : complete_lattice Prop := { Sup := λ s, ∃ a ∈ s, a, le_Sup := λ s a h p, ⟨a, h, p⟩, Sup_le := λ s a h ⟨b, h', p⟩, h b h' p, Inf := λ s, ∀ a, a ∈ s → a, Inf_le := λ s a h p, p a h, le_Inf := λ s a h p b hb, h b hb p, .. Prop.bounded_order, .. Prop.distrib_lattice } noncomputable instance Prop.complete_linear_order : complete_linear_order Prop := { ..Prop.complete_lattice, ..Prop.linear_order } @[simp] lemma Sup_Prop_eq {s : set Prop} : Sup s = ∃ p ∈ s, p := rfl @[simp] lemma Inf_Prop_eq {s : set Prop} : Inf s = ∀ p ∈ s, p := rfl @[simp] lemma supr_Prop_eq {p : ι → Prop} : (⨆ i, p i) = ∃ i, p i := le_antisymm (λ ⟨q, ⟨i, (eq : p i = q)⟩, hq⟩, ⟨i, eq.symm ▸ hq⟩) (λ ⟨i, hi⟩, ⟨p i, ⟨i, rfl⟩, hi⟩) @[simp] lemma infi_Prop_eq {p : ι → Prop} : (⨅ i, p i) = ∀ i, p i := le_antisymm (λ h i, h _ ⟨i, rfl⟩ ) (λ h p ⟨i, eq⟩, eq ▸ h i) instance pi.has_Sup {α : Type*} {β : α → Type*} [Π i, has_Sup (β i)] : has_Sup (Π i, β i) := ⟨λ s i, ⨆ f : s, (f : Π i, β i) i⟩ instance pi.has_Inf {α : Type*} {β : α → Type*} [Π i, has_Inf (β i)] : has_Inf (Π i, β i) := ⟨λ s i, ⨅ f : s, (f : Π i, β i) i⟩ instance pi.complete_lattice {α : Type*} {β : α → Type*} [∀ i, complete_lattice (β i)] : complete_lattice (Π i, β i) := { Sup := Sup, Inf := Inf, le_Sup := λ s f hf i, le_supr (λ f : s, (f : Π i, β i) i) ⟨f, hf⟩, Inf_le := λ s f hf i, infi_le (λ f : s, (f : Π i, β i) i) ⟨f, hf⟩, Sup_le := λ s f hf i, supr_le $ λ g, hf g g.2 i, le_Inf := λ s f hf i, le_infi $ λ g, hf g g.2 i, .. pi.bounded_order, .. pi.lattice } lemma Sup_apply {α : Type*} {β : α → Type*} [Π i, has_Sup (β i)] {s : set (Π a, β a)} {a : α} : (Sup s) a = ⨆ f : s, (f : Π a, β a) a := rfl lemma Inf_apply {α : Type*} {β : α → Type*} [Π i, has_Inf (β i)] {s : set (Π a, β a)} {a : α} : Inf s a = ⨅ f : s, (f : Π a, β a) a := rfl @[simp] lemma supr_apply {α : Type*} {β : α → Type*} {ι : Sort*} [Π i, has_Sup (β i)] {f : ι → Π a, β a} {a : α} : (⨆ i, f i) a = ⨆ i, f i a := by rw [supr, Sup_apply, supr, supr, ← image_eq_range (λ f : Π i, β i, f a) (range f), ← range_comp] @[simp] lemma infi_apply {α : Type*} {β : α → Type*} {ι : Sort*} [Π i, has_Inf (β i)] {f : ι → Π a, β a} {a : α} : (⨅ i, f i) a = ⨅ i, f i a := @supr_apply α (λ i, (β i)ᵒᵈ) _ _ _ _ lemma unary_relation_Sup_iff {α : Type*} (s : set (α → Prop)) {a : α} : Sup s a ↔ ∃ r : α → Prop, r ∈ s ∧ r a := by { unfold Sup, simp [←eq_iff_iff] } lemma unary_relation_Inf_iff {α : Type*} (s : set (α → Prop)) {a : α} : Inf s a ↔ ∀ r : α → Prop, r ∈ s → r a := by { unfold Inf, simp [←eq_iff_iff] } lemma binary_relation_Sup_iff {α β : Type*} (s : set (α → β → Prop)) {a : α} {b : β} : Sup s a b ↔ ∃ r : α → β → Prop, r ∈ s ∧ r a b := by { unfold Sup, simp [←eq_iff_iff] } lemma binary_relation_Inf_iff {α β : Type*} (s : set (α → β → Prop)) {a : α} {b : β} : Inf s a b ↔ ∀ r : α → β → Prop, r ∈ s → r a b := by { unfold Inf, simp [←eq_iff_iff] } section complete_lattice variables [preorder α] [complete_lattice β] theorem monotone_Sup_of_monotone {s : set (α → β)} (m_s : ∀ f ∈ s, monotone f) : monotone (Sup s) := λ x y h, supr_mono $ λ f, m_s f f.2 h theorem monotone_Inf_of_monotone {s : set (α → β)} (m_s : ∀ f ∈ s, monotone f) : monotone (Inf s) := λ x y h, infi_mono $ λ f, m_s f f.2 h end complete_lattice namespace prod variables (α β) instance [has_Sup α] [has_Sup β] : has_Sup (α × β) := ⟨λ s, (Sup (prod.fst '' s), Sup (prod.snd '' s))⟩ instance [has_Inf α] [has_Inf β] : has_Inf (α × β) := ⟨λ s, (Inf (prod.fst '' s), Inf (prod.snd '' s))⟩ instance [complete_lattice α] [complete_lattice β] : complete_lattice (α × β) := { le_Sup := λ s p hab, ⟨le_Sup $ mem_image_of_mem _ hab, le_Sup $ mem_image_of_mem _ hab⟩, Sup_le := λ s p h, ⟨ Sup_le $ ball_image_of_ball $ λ p hp, (h p hp).1, Sup_le $ ball_image_of_ball $ λ p hp, (h p hp).2⟩, Inf_le := λ s p hab, ⟨Inf_le $ mem_image_of_mem _ hab, Inf_le $ mem_image_of_mem _ hab⟩, le_Inf := λ s p h, ⟨ le_Inf $ ball_image_of_ball $ λ p hp, (h p hp).1, le_Inf $ ball_image_of_ball $ λ p hp, (h p hp).2⟩, .. prod.lattice α β, .. prod.bounded_order α β, .. prod.has_Sup α β, .. prod.has_Inf α β } end prod section complete_lattice variables [complete_lattice α] {a : α} {s : set α} /-- This is a weaker version of `sup_Inf_eq` -/ lemma sup_Inf_le_infi_sup : a ⊔ Inf s ≤ ⨅ b ∈ s, a ⊔ b := le_infi₂ $ λ i h, sup_le_sup_left (Inf_le h) _ /-- This is a weaker version of `inf_Sup_eq` -/ lemma supr_inf_le_inf_Sup : (⨆ b ∈ s, a ⊓ b) ≤ a ⊓ Sup s := @sup_Inf_le_infi_sup αᵒᵈ _ _ _ /-- This is a weaker version of `Inf_sup_eq` -/ lemma Inf_sup_le_infi_sup : Inf s ⊔ a ≤ ⨅ b ∈ s, b ⊔ a := le_infi₂ $ λ i h, sup_le_sup_right (Inf_le h) _ /-- This is a weaker version of `Sup_inf_eq` -/ lemma supr_inf_le_Sup_inf : (⨆ b ∈ s, b ⊓ a) ≤ Sup s ⊓ a := @Inf_sup_le_infi_sup αᵒᵈ _ _ _ lemma le_supr_inf_supr (f g : ι → α) : (⨆ i, f i ⊓ g i) ≤ (⨆ i, f i) ⊓ (⨆ i, g i) := le_inf (supr_mono $ λ i, inf_le_left) (supr_mono $ λ i, inf_le_right) lemma infi_sup_infi_le (f g : ι → α) : (⨅ i, f i) ⊔ (⨅ i, g i) ≤ ⨅ i, f i ⊔ g i := @le_supr_inf_supr αᵒᵈ ι _ f g lemma disjoint_Sup_left {a : set α} {b : α} (d : disjoint (Sup a) b) {i} (hi : i ∈ a) : disjoint i b := (supr₂_le_iff.1 (supr_inf_le_Sup_inf.trans d) i hi : _) lemma disjoint_Sup_right {a : set α} {b : α} (d : disjoint b (Sup a)) {i} (hi : i ∈ a) : disjoint b i := (supr₂_le_iff.mp (supr_inf_le_inf_Sup.trans d) i hi : _) end complete_lattice /-- Pullback a `complete_lattice` along an injection. -/ @[reducible] -- See note [reducible non-instances] protected def function.injective.complete_lattice [has_sup α] [has_inf α] [has_Sup α] [has_Inf α] [has_top α] [has_bot α] [complete_lattice β] (f : α → β) (hf : function.injective f) (map_sup : ∀ a b, f (a ⊔ b) = f a ⊔ f b) (map_inf : ∀ a b, f (a ⊓ b) = f a ⊓ f b) (map_Sup : ∀ s, f (Sup s) = ⨆ a ∈ s, f a) (map_Inf : ∀ s, f (Inf s) = ⨅ a ∈ s, f a) (map_top : f ⊤ = ⊤) (map_bot : f ⊥ = ⊥) : complete_lattice α := { Sup := Sup, le_Sup := λ s a h, (le_supr₂ a h).trans (map_Sup _).ge, Sup_le := λ s a h, (map_Sup _).trans_le $ supr₂_le h, Inf := Inf, Inf_le := λ s a h, (map_Inf _).trans_le $ infi₂_le a h, le_Inf := λ s a h, (le_infi₂ h).trans (map_Inf _).ge, -- we cannot use bounded_order.lift here as the `has_le` instance doesn't exist yet top := ⊤, le_top := λ a, (@le_top β _ _ _).trans map_top.ge, bot := ⊥, bot_le := λ a, map_bot.le.trans bot_le, ..hf.lattice f map_sup map_inf }
75b4269c2848a787532244b8d61b10f08f325f6e
a4673261e60b025e2c8c825dfa4ab9108246c32e
/src/Lean/Parser/Module.lean
af25a9f9730bab9120502485dd4b93085cac7ea5
[ "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
6,551
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, Sebastian Ullrich -/ import Lean.Message import Lean.Parser.Command namespace Lean namespace Parser namespace Module def «prelude» := parser! "prelude" def «import» := parser! "import " >> optional "runtime" >> ident def header := parser! optional («prelude» >> ppLine) >> many («import» >> ppLine) >> ppLine /-- Parser for a Lean module. We never actually run this parser but instead use the imperative definitions below that return the same syntax tree structure, but add error recovery. Still, it is helpful to have a `Parser` definition for it in order to auto-generate helpers such as the pretty printer. -/ @[runBuiltinParserAttributeHooks] def module := parser! header >> many (commandParser >> ppLine >> ppLine) def updateTokens (c : ParserContext) : ParserContext := { c with tokens := match addParserTokens c.tokens header.info with | Except.ok tables => tables | Except.error _ => unreachable! } end Module structure ModuleParserState := (pos : String.Pos := 0) (recovering : Bool := false) instance : Inhabited ModuleParserState := ⟨{}⟩ private def mkErrorMessage (c : ParserContext) (pos : String.Pos) (errorMsg : String) : Message := let pos := c.fileMap.toPosition pos { fileName := c.fileName, pos := pos, data := errorMsg } def parseHeader (inputCtx : InputContext) : IO (Syntax × ModuleParserState × MessageLog) := do let dummyEnv ← mkEmptyEnvironment let ctx := mkParserContext dummyEnv inputCtx let ctx := Module.updateTokens ctx let s := mkParserState ctx.input let s := whitespace ctx s let s := Module.header.fn ctx s let stx := s.stxStack.back match s.errorMsg with | some errorMsg => let msg := mkErrorMessage ctx s.pos (toString errorMsg) pure (stx, { pos := s.pos, recovering := true }, { : MessageLog }.add msg) | none => pure (stx, { pos := s.pos }, {}) private def mkEOI (pos : String.Pos) : Syntax := let atom := mkAtom { pos := pos, trailing := "".toSubstring, leading := "".toSubstring } "" Syntax.node `Lean.Parser.Module.eoi #[atom] def isEOI (s : Syntax) : Bool := s.isOfKind `Lean.Parser.Module.eoi def isExitCommand (s : Syntax) : Bool := s.isOfKind `Lean.Parser.Command.exit private def consumeInput (c : ParserContext) (pos : String.Pos) : String.Pos := let s : ParserState := { cache := initCacheForInput c.input, pos := pos } let s := tokenFn c s match s.errorMsg with | some _ => pos + 1 | none => s.pos def topLevelCommandParserFn : ParserFn := orelseFnCore commandParser.fn (andthenFn (lookaheadFn termParser.fn) (errorFn "expected command, but found term; this error may be due to parsing precedence levels, consider parenthesizing the term")) false /- do not merge errors -/ partial def parseCommand (env : Environment) (inputCtx : InputContext) (s : ModuleParserState) (messages : MessageLog) : Syntax × ModuleParserState × MessageLog := let rec parse (s : ModuleParserState) (messages : MessageLog) := let { pos := pos, recovering := recovering } := s if inputCtx.input.atEnd pos then (mkEOI pos, s, messages) else let c := mkParserContext env inputCtx let s := { cache := initCacheForInput c.input, pos := pos : ParserState } let s := whitespace c s let s := topLevelCommandParserFn c s let stx := s.stxStack.back match s.errorMsg with | none => (stx, { pos := s.pos }, messages) | some errorMsg => -- advance at least one token to prevent infinite loops let pos := if s.pos == pos then consumeInput c s.pos else s.pos if recovering then parse { pos := pos, recovering := true } messages else let msg := mkErrorMessage c s.pos (toString errorMsg) let messages := messages.add msg -- We should replace the following line with commented one if we want to elaborate commands containing Syntax errors. -- This is useful for implementing features such as autocompletion. -- Right now, it is disabled since `match_syntax` fails on "partial" `Syntax` objects. parse { pos := pos, recovering := true } messages -- (stx, { pos := pos, recovering := true }, messages) parse s messages private partial def testModuleParserAux (env : Environment) (inputCtx : InputContext) (displayStx : Bool) (s : ModuleParserState) (messages : MessageLog) : IO Bool := let rec loop (s : ModuleParserState) (messages : MessageLog) := do match parseCommand env inputCtx s messages with | (stx, s, messages) => if isEOI stx || isExitCommand stx then messages.forM fun msg => msg.toString >>= IO.println pure (!messages.hasErrors) else if displayStx then IO.println stx loop s messages loop s messages @[export lean_test_module_parser] def testModuleParser (env : Environment) (input : String) (fileName := "<input>") (displayStx := false) : IO Bool := timeit (fileName ++ " parser") do let inputCtx := mkInputContext input fileName let (stx, s, messages) ← parseHeader inputCtx if displayStx then IO.println stx testModuleParserAux env inputCtx displayStx s messages partial def parseModuleAux (env : Environment) (inputCtx : InputContext) (s : ModuleParserState) (msgs : MessageLog) (stxs : Array Syntax) : IO (Array Syntax) := let rec parse (state : ModuleParserState) (msgs : MessageLog) (stxs : Array Syntax) := match parseCommand env inputCtx state msgs with | (stx, state, msgs) => if isEOI stx then if msgs.isEmpty then pure stxs else do msgs.forM fun msg => msg.toString >>= IO.println throw (IO.userError "failed to parse file") else parse state msgs (stxs.push stx) parse s msgs stxs def parseModule (env : Environment) (fname contents : String) : IO Syntax := do let fname ← IO.realPath fname let inputCtx := mkInputContext contents fname let (header, state, messages) ← parseHeader inputCtx let cmds ← parseModuleAux env inputCtx state messages #[] let stx := Syntax.node `Lean.Parser.Module.module #[header, mkListNode cmds] pure stx.updateLeading def parseFile (env : Environment) (fname : String) : IO Syntax := do let contents ← IO.FS.readFile fname parseModule env fname contents end Parser end Lean
8b9bfa88216a25c067ad76ba4f5e78798816e534
9c1ad797ec8a5eddb37d34806c543602d9a6bf70
/projects.lean
c680874e16e3182c80273d74f2cf6ec1fc7eef01
[]
no_license
timjb/lean-category-theory
816eefc3a0582c22c05f4ee1c57ed04e57c0982f
12916cce261d08bb8740bc85e0175b75fb2a60f4
refs/heads/master
1,611,078,926,765
1,492,080,000,000
1,492,080,000,000
88,348,246
0
0
null
1,492,262,499,000
1,492,262,498,000
null
UTF-8
Lean
false
false
734
lean
-- PROJECTS -- define Day convolution: the monoidal structure on FunctorCategory C D when D is monoidal. -- is this known: a monoidal structure on monoidal functors from C to D when D is braided? -- transporting structures along equivalences: e.g. given an equivalence of categories, transport a monoidal structure? -- equivalences can be turned into adjoint equivalences -- equivalences in bijection with the fully faithful essentially surjective functors (nonconstructively?) -- Idempotent completion as a left adjoint to the forgetful 2-functor from categories to semicategories. -- enriched categories! -- closed monoidal categories -- additive categories, additive envelopes -- the Yoneda embedding (also for enriched categories)
dc2f289889948e03f1a4bbc424289a001fc04132
74caf7451c921a8d5ab9c6e2b828c9d0a35aae95
/library/init/data/list/instances.lean
ab7dcfb42fdd1d818e34b42663c31359e2ee201d
[ "Apache-2.0" ]
permissive
sakas--/lean
f37b6fad4fd4206f2891b89f0f8135f57921fc3f
570d9052820be1d6442a5cc58ece37397f8a9e4c
refs/heads/master
1,586,127,145,194
1,480,960,018,000
1,480,960,635,000
40,137,176
0
0
null
1,438,621,351,000
1,438,621,351,000
null
UTF-8
Lean
false
false
792
lean
/- Copyright (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura -/ prelude import init.category.monad init.category.alternative init.data.list.basic import init.meta.mk_dec_eq_instance open list universe variables u v @[inline] def list.bind {α : Type u} {β : Type v} (a : list α) (b : α → list β) : list β := join (map b a) @[inline] def list.ret {α : Type u} (a : α) : list α := [a] instance : monad list := ⟨@map, @list.ret, @list.bind⟩ instance : alternative list := ⟨@map, @list.ret, @fapp _ _, @nil, @list.append⟩ instance {α : Type u} [decidable_eq α] : decidable_eq (list α) := by tactic.mk_dec_eq_instance instance : decidable_eq string := list.decidable_eq
293a1148ba933b50e17e5f4193b2c5491e6787c1
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/matchApp.lean
5b9faf42c70b1c6e02fe3df8194d0da5e9eaef26
[ "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
328
lean
def f (xs ys : List α) : Nat := match xs, ys with | [], [] => 0 | _, [] => 1 | _, _ => 2 #check fun {α : Type} (motive : List α → List α → Type) (h1 : Unit → motive [] []) (h2 : (x : List α) → motive x []) (h3 : (x x_1 : List α) → motive x x_1) => f.match_1 (motive := motive) [] [] h1 h2 h3
b1899da77dab0486356e5c493f5c98d9a8a4873f
46125763b4dbf50619e8846a1371029346f4c3db
/src/algebra/category/Module/basic.lean
c6a83b1f52d7c3ff7b2674c477c4fac4df523d50
[ "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
3,940
lean
/- Copyright (c) 2019 Robert A. Spencer. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Robert A. Spencer, Markus Himmel -/ import algebra.module import algebra.punit_instances import category_theory.concrete_category import category_theory.limits.shapes.zero import category_theory.limits.shapes.kernels import linear_algebra.basic open category_theory open category_theory.limits open category_theory.limits.walking_parallel_pair universe u variables (R : Type u) [ring R] /-- The category of R-modules and their morphisms. -/ structure Module := (carrier : Type u) [is_add_comm_group : add_comm_group carrier] [is_module : module R carrier] attribute [instance] Module.is_add_comm_group Module.is_module namespace Module -- TODO revisit this after #1438 merges, to check coercions and instances are handled consistently instance : has_coe_to_sort (Module R) := { S := Type u, coe := Module.carrier } instance : concrete_category (Module.{u} R) := { to_category := { hom := λ M N, M →ₗ[R] N, id := λ M, 1, comp := λ A B C f g, g.comp f }, forget := { obj := λ R, R, map := λ R S f, (f : R → S) }, forget_faithful := { } } /-- The object in the category of R-modules associated to an R-module -/ def of (X : Type u) [add_comm_group X] [module R X] : Module R := ⟨R, X⟩ instance : inhabited (Module R) := ⟨of R punit⟩ lemma of_apply (X : Type u) [add_comm_group X] [module R X] : (of R X : Type u) = X := rfl instance : subsingleton (of R punit) := by { rw of_apply R punit, apply_instance } instance : has_zero_object.{u} (Module R) := { zero := of R punit, unique_to := λ X, { default := (0 : punit →ₗ[R] X), uniq := λ _, linear_map.ext $ λ x, have h : x = 0, from subsingleton.elim _ _, by simp [h] }, unique_from := λ X, { default := (0 : X →ₗ[R] punit), uniq := λ _, linear_map.ext $ λ x, subsingleton.elim _ _ } } variables (M N U : Module R) @[simp] lemma id_apply (m : M) : (𝟙 M : M → M) m = m := rfl @[simp] lemma coe_comp (f : M ⟶ N) (g : N ⟶ U) : ((f ≫ g) : M → U) = g ∘ f := rfl instance hom_is_module_hom {M₁ M₂ : Module R} (f : M₁ ⟶ M₂) : is_linear_map R (f : M₁ → M₂) := linear_map.is_linear _ section kernel variable (f : M ⟶ N) local attribute [instance] has_zero_object.zero_morphisms_of_zero_object /-- The cone on the equalizer diagram of f and 0 induced by the kernel of f -/ def kernel_cone : cone (parallel_pair f 0) := { X := of R f.ker, π := { app := λ j, match j with | zero := f.ker.subtype | one := 0 end, naturality' := λ j j' g, by { cases j; cases j'; cases g; tidy } } } /-- The kernel of a linear map is a kernel in the categorical sense -/ def kernel_is_limit : is_limit (kernel_cone _ _ _ f) := { lift := λ s, linear_map.cod_restrict f.ker (fork.ι s) (λ c, linear_map.mem_ker.2 $ by { erw [←@function.comp_apply _ _ _ f (fork.ι s) c, ←coe_comp, fork.condition, has_zero_morphisms.comp_zero _ (fork.ι s) N], refl }), fac' := λ s j, linear_map.ext $ λ x, begin rw [coe_comp, function.comp_app, ←linear_map.comp_apply], cases j, { erw @linear_map.subtype_comp_cod_restrict _ _ _ _ _ _ _ _ (fork.ι s) f.ker _, refl }, { rw [←cone_parallel_pair_right, ←cone_parallel_pair_right], refl } end, uniq' := λ s m h, linear_map.ext $ λ x, subtype.ext.2 $ have h₁ : (m ≫ (kernel_cone _ _ _ f).π.app zero).to_fun = (s.π.app zero).to_fun, by { congr, exact h zero }, by convert @congr_fun _ _ _ _ h₁ x } end kernel local attribute [instance] has_zero_object.zero_morphisms_of_zero_object instance : has_kernels.{u} (Module R) := ⟨λ _ _ f, ⟨kernel_cone _ _ _ f, kernel_is_limit _ _ _ f⟩⟩ end Module instance (M : Type u) [add_comm_group M] [module R M] : has_coe (submodule R M) (Module R) := ⟨ λ N, Module.of R N ⟩
7039a1701a1196661e12d096410a2b87dc0a73eb
2d2554d724f667419148b06acf724e2702ada7c9
/src/solve_theorems.lean
03faacd4ac2d0c5a195ca5f1a99483e8b315c740
[]
no_license
hediet/lean-linear-integer-equation-solver
64591803a01d38dba8599c5bde3e88446a2dca28
1a83fa7935b4411618c4edcdee7edb5c4a6678a7
refs/heads/master
1,677,680,410,160
1,612,962,170,000
1,612,962,170,000
337,718,062
1
0
null
null
null
null
UTF-8
Lean
false
false
2,027
lean
import .definitions import data.bool import data.int.gcd import tactic import .mod import .solve import .main lemma divide_by_gcd'_correct (eqs eqs': Eqs) (h1: divide_by_gcd' eqs = some eqs') (x: list ℤ) (h2: x ∈ eqs): (x ∈ eqs') ∧ (t eqs' ≤ t eqs) := begin cases eqs, cases eqs', cases eqs_eqs; unfold divide_by_gcd' at h1, { rw Eqs.has_mem_iff at h2, simp at h2, simp at h1, rw Eqs.has_mem_iff, simp [t, ←h1.2], cases (find_min_non_zero_or_default {dim := eqs'_dim, eqs := list.nil}); simp [t._match_1, *], }, { sorry, } end theorem divide_by_gcd_correct (e: Eqs) (r: EqsReduction) (h1: divide_by_gcd e = some r) (x: list ℤ) (h2: x ∈ r.eqs): (r.reduction x ∈ e) ∧ (t r.eqs ≤ t e) := begin unfold divide_by_gcd at h1, sorry, end @[simp] lemma Eq.add_length (eq1 eq2: Eq): (eq1.add eq2).as.length = min eq1.as.length eq2.as.length := by simp [Eq.add] @[simp] lemma Eq.mul_length (eq: Eq) (f: ℤ): (eq.mul f).as.length = eq.as.length := by simp [Eq.mul] lemma annihilate_var_correct (e: Eq) (var_def: Eq) (i: ℕ) (h: (e.as.inth i).nat_abs = 1) (h': var_def.as.length = e.as.length) (x: list ℤ) (h2: x ∈ var_def): x ∈ (annihilate_var e var_def i) ↔ x ∈ e := begin rw Eq.has_mem_iff at h2, rw Eq.has_mem_iff, rw Eq.has_mem_iff, unfold annihilate_var, apply and_congr, { simp [h2, h'], }, simp, split, { assume h2, sorry, }, sorry, end theorem eliminate_unit_var_correct (e: Eqs) (r: EqsReduction) (h1: eliminate_unit_var e = some r) (x: list ℤ) (h2: x ∈ r.eqs): (r.reduction x ∈ e) ∧ (t r.eqs ≤ t e) := begin unfold eliminate_unit_var at h1, cases find_isolated_var e, { unfold eliminate_unit_var._match_1 at h1, finish, }, { cases val, unfold eliminate_unit_var._match_1 at h1, simp at h1, split, { subst h1, simp at h2, simp, sorry, }, sorry, } end theorem fixpoint_of_simplify_terminates (eqs: Eqs) (r: EqsReduction) (h1: simplify eqs = some r): (t r.eqs < t eqs) := begin sorry, end
3d87b5ff58b9b6b0c108f9b91d5f1b61161eeaed
271e26e338b0c14544a889c31c30b39c989f2e0f
/stage0/src/Init/Lean/Meta/LevelDefEq.lean
1e5b1157da32256affecef67747925b1bfeaed1f
[ "Apache-2.0" ]
permissive
dgorokho/lean4
805f99b0b60c545b64ac34ab8237a8504f89d7d4
e949a052bad59b1c7b54a82d24d516a656487d8a
refs/heads/master
1,607,061,363,851
1,578,006,086,000
1,578,006,086,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
8,792
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude import Init.Lean.Meta.Basic namespace Lean namespace Meta private partial def decAux? : Level → MetaM (Option Level) | Level.zero _ => pure none | Level.param _ _ => pure none | Level.mvar mvarId _ => do mctx ← getMCtx; match mctx.getLevelAssignment? mvarId with | some u => decAux? u | none => condM (isReadOnlyLevelMVar mvarId) (pure none) $ do u ← mkFreshLevelMVar; assignLevelMVar mvarId (mkLevelSucc u); pure u | Level.succ u _ => pure u | u => let process (u v : Level) : MetaM (Option Level) := do { u? ← decAux? u; match u? with | none => pure none | some u => do v? ← decAux? v; match v? with | none => pure none | some v => pure $ mkLevelMax u v }; match u with | Level.max u v _ => process u v /- Remark: If `decAux? v` returns `some ...`, then `imax u v` is equivalent to `max u v`. -/ | Level.imax u v _ => process u v | _ => unreachable! partial def decLevel? (u : Level) : MetaM (Option Level) := do mctx ← getMCtx; result? ← decAux? u; match result? with | some v => pure $ some v | none => do modify $ fun s => { mctx := mctx, .. s }; pure none private def strictOccursMaxAux (lvl : Level) : Level → Bool | Level.max u v _ => strictOccursMaxAux u || strictOccursMaxAux v | u => u != lvl && lvl.occurs u /-- Return true iff `lvl` occurs in `max u_1 ... u_n` and `lvl != u_i` for all `i in [1, n]`. That is, `lvl` is a proper level subterm of some `u_i`. -/ private def strictOccursMax (lvl : Level) : Level → Bool | Level.max u v _ => strictOccursMaxAux lvl u || strictOccursMaxAux lvl v | _ => false /-- `mkMaxArgsDiff mvarId (max u_1 ... (mvar mvarId) ... u_n) v` => `max v u_1 ... u_n` -/ private def mkMaxArgsDiff (mvarId : MVarId) : Level → Level → Level | Level.max u v _, acc => mkMaxArgsDiff v $ mkMaxArgsDiff u acc | l@(Level.mvar id _), acc => if id != mvarId then mkLevelMax acc l else acc | l, acc => mkLevelMax acc l /-- Solve `?m =?= max ?m v` by creating a fresh metavariable `?n` and assigning `?m := max ?n v` -/ private def solveSelfMax (mvarId : MVarId) (v : Level) : MetaM Unit := do n ← mkFreshLevelMVar; assignLevelMVar mvarId $ mkMaxArgsDiff mvarId v n private def postponeIsLevelDefEq (lhs : Level) (rhs : Level) : MetaM Unit := modify $ fun s => { postponed := s.postponed.push { lhs := lhs, rhs := rhs }, .. s } inductive LevelConstraintKind | mvarEq -- ?m =?= l where ?m does not occur in l | mvarEqSelfMax -- ?m =?= max ?m l where ?m does not occur in l | other private def getLevelConstraintKind (u v : Level) : MetaM LevelConstraintKind := match u with | Level.mvar mvarId _ => condM (isReadOnlyLevelMVar mvarId) (pure LevelConstraintKind.other) (if !u.occurs v then pure LevelConstraintKind.mvarEq else if !strictOccursMax u v then pure LevelConstraintKind.mvarEqSelfMax else pure LevelConstraintKind.other) | _ => pure LevelConstraintKind.other partial def isLevelDefEqAux : Level → Level → MetaM Bool | Level.succ lhs _, Level.succ rhs _ => isLevelDefEqAux lhs rhs | lhs, rhs => if lhs == rhs then pure true else do trace! `Meta.isLevelDefEq.step (lhs ++ " =?= " ++ rhs); lhs' ← instantiateLevelMVars lhs; let lhs' := lhs'.normalize; rhs' ← instantiateLevelMVars rhs; let rhs' := rhs'.normalize; if lhs != lhs' || rhs != rhs' then isLevelDefEqAux lhs' rhs' else do mctx ← getMCtx; if !mctx.hasAssignableLevelMVar lhs && !mctx.hasAssignableLevelMVar rhs then do ctx ← read; if ctx.config.isDefEqStuckEx && (lhs.isMVar || rhs.isMVar) then throwEx $ Exception.isLevelDefEqStuck lhs rhs else pure false else do k ← getLevelConstraintKind lhs rhs; match k with | LevelConstraintKind.mvarEq => do assignLevelMVar lhs.mvarId! rhs; pure true | LevelConstraintKind.mvarEqSelfMax => do solveSelfMax lhs.mvarId! rhs; pure true | _ => do k ← getLevelConstraintKind rhs lhs; match k with | LevelConstraintKind.mvarEq => do assignLevelMVar rhs.mvarId! lhs; pure true | LevelConstraintKind.mvarEqSelfMax => do solveSelfMax rhs.mvarId! lhs; pure true | _ => if lhs.isMVar || rhs.isMVar then pure false else let isSuccEq (u v : Level) : MetaM Bool := match u with | Level.succ u _ => do v? ← decLevel? v; match v? with | some v => isLevelDefEqAux u v | none => pure false | _ => pure false; condM (isSuccEq lhs rhs) (pure true) $ condM (isSuccEq rhs lhs) (pure true) $ do postponeIsLevelDefEq lhs rhs; pure true def isListLevelDefEqAux : List Level → List Level → MetaM Bool | [], [] => pure true | u::us, v::vs => isLevelDefEqAux u v <&&> isListLevelDefEqAux us vs | _, _ => pure false private def getNumPostponed : MetaM Nat := do s ← get; pure s.postponed.size private def getResetPostponed : MetaM (PersistentArray PostponedEntry) := do s ← get; let ps := s.postponed; modify $ fun s => { postponed := {}, .. s }; pure ps private def processPostponedStep : MetaM Bool := traceCtx `Meta.isLevelDefEq.postponed.step $ do ps ← getResetPostponed; ps.foldlM (fun (r : Bool) (p : PostponedEntry) => if r then isLevelDefEqAux p.lhs p.rhs else pure false) true private partial def processPostponedAux : Unit → MetaM Bool | _ => do numPostponed ← getNumPostponed; if numPostponed == 0 then pure true else do trace! `Meta.isLevelDefEq.postponed ("processing #" ++ toString numPostponed ++ " postponed is-def-eq level constraints"); r ← processPostponedStep; if !r then pure r else do numPostponed' ← getNumPostponed; if numPostponed' == 0 then pure true else if numPostponed' < numPostponed then processPostponedAux () else do trace! `Meta.isLevelDefEq.postponed (format "no progress solving pending is-def-eq level constraints"); pure false private def processPostponed : MetaM Bool := do numPostponed ← getNumPostponed; if numPostponed == 0 then pure true else traceCtx `Meta.isLevelDefEq.postponed $ processPostponedAux () private def restore (env : Environment) (mctx : MetavarContext) (postponed : PersistentArray PostponedEntry) : MetaM Unit := modify $ fun s => { env := env, mctx := mctx, postponed := postponed, .. s } /-- `try x` executes `x` and process all postponed universe level constraints produced by `x`. We keep the modifications only if both return `true`. Remark: postponed universe level constraints must be solved before returning. Otherwise, we don't know whether `x` really succeeded. -/ @[specialize] def try (x : MetaM Bool) : MetaM Bool := do s ← get; let env := s.env; let mctx := s.mctx; let postponed := s.postponed; modify $ fun s => { postponed := {}, .. s }; catch (condM x (condM processPostponed (pure true) (do restore env mctx postponed; pure false)) (do restore env mctx postponed; pure false)) (fun ex => do restore env mctx postponed; throw ex) @[specialize] def tryOpt {α} (x : MetaM (Option α)) : MetaM (Option α) := do s ← get; let env := s.env; let mctx := s.mctx; let postponed := s.postponed; modify $ fun s => { postponed := {}, .. s }; catch (do a? ← x; match a? with | some a => condM processPostponed (pure (some a)) (do restore env mctx postponed; pure none) | none => do restore env mctx postponed; pure none) (fun ex => do restore env mctx postponed; throw ex) /- Public interface -/ def isLevelDefEq (u v : Level) : MetaM Bool := traceCtx `Meta.isLevelDefEq $ do b ← try $ isLevelDefEqAux u v; trace! `Meta.isLevelDefEq (u ++ " =?= " ++ v ++ " ... " ++ if b then "success" else "failure"); pure b def isExprDefEq (t s : Expr) : MetaM Bool := traceCtx `Meta.isDefEq $ do b ← try $ isExprDefEqAux t s; trace! `Meta.isDefEq (t ++ " =?= " ++ s ++ " ... " ++ if b then "success" else "failure"); pure b abbrev isDefEq := @isExprDefEq @[init] private def regTraceClasses : IO Unit := do registerTraceClass `Meta.isLevelDefEq; registerTraceClass `Meta.isLevelDefEq.step; registerTraceClass `Meta.isLevelDefEq.postponed end Meta end Lean
1265e679ceeb75207e3b7a026c0ae3c312f1fbe9
ce6917c5bacabee346655160b74a307b4a5ab620
/src/ch4/ex0501.lean
02b0c46a1c08bc03427668542f9312be45fae6de
[]
no_license
Ailrun/Theorem_Proving_in_Lean
ae6a23f3c54d62d401314d6a771e8ff8b4132db2
2eb1b5caf93c6a5a555c79e9097cf2ba5a66cf68
refs/heads/master
1,609,838,270,467
1,586,846,743,000
1,586,846,743,000
240,967,761
1
0
null
null
null
null
UTF-8
Lean
false
false
216
lean
variable f : ℕ → ℕ variable h : ∀ x : ℕ, f x ≤ f (x + 1) example : f 0 ≤ f 3 := have f 0 ≤ f 1, from h 0, have f 0 ≤ f 2, from le_trans this (h 1), show f 0 ≤ f 3, from le_trans this (h 2)
c6ea78285cc9c79836d592326af6d37a55593fe9
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/data/json.lean
b504379d36475fd00781fc28dd3dc199eb08eda7
[ "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
11,280
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 tactic.core /-! # Json serialization typeclass > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file provides helpers for serializing primitive types to json. `@[derive non_null_json_serializable]` will make any structure json serializable; for instance, ```lean @[derive non_null_json_serializable] structure my_struct := (success : bool) (verbose : ℕ := 0) (extras : option string := none) ``` can parse `{"success": true}` as `my_struct.mk true 0 none`, and reserializing give `{"success": true, "verbose": 0, "extras": null}`. ## Main definitions * `json_serializable`: a typeclass for objects which serialize to json * `json_serializable.to_json x`: convert `x` to json * `json_serializable.of_json α j`: read `j` in as an `α` -/ open exceptional meta instance : has_orelse exceptional := { orelse := λ α f g, match f with | success x := success x | exception msg := g end } /-- A class to indicate that a type is json serializable -/ meta class json_serializable (α : Type) := (to_json : α → json) (of_json [] : json → exceptional α) /-- A class for types which never serialize to null -/ meta class non_null_json_serializable (α : Type) extends json_serializable α export json_serializable (to_json of_json) /-- Describe the type of a json value -/ meta def json.typename : json → string | (json.of_string _) := "string" | (json.of_int _) := "number" | (json.of_float _) := "number" | (json.of_bool _) := "bool" | json.null := "null" | (json.object _) := "object" | (json.array _) := "array" /-! ### Primitive types -/ meta instance : non_null_json_serializable string := { to_json := json.of_string, of_json := λ j, do json.of_string s ← success j | exception (λ _, format!"string expected, got {j.typename}"), pure s } meta instance : non_null_json_serializable ℤ := { to_json := λ z, json.of_int z, of_json := λ j, do json.of_int z ← success j | do { json.of_float f ← success j | exception (λ _, format!"number expected, got {j.typename}"), exception (λ _, format!"number must be integral") }, pure z } meta instance : non_null_json_serializable native.float := { to_json := λ f, json.of_float f, of_json := λ j, do json.of_int z ← success j | do { json.of_float f ← success j | exception (λ _, format!"number expected, got {j.typename}"), pure f }, pure z } meta instance : non_null_json_serializable bool := { to_json := λ b, json.of_bool b, of_json := λ j, do json.of_bool b ← success j | exception (λ _, format!"boolean expected, got {j.typename}"), pure b } meta instance : json_serializable punit := { to_json := λ u, json.null, of_json := λ j, do json.null ← success j | exception (λ _, format!"null expected, got {j.typename}"), pure () } meta instance {α} [json_serializable α] : non_null_json_serializable (list α) := { to_json := λ l, json.array (l.map to_json), of_json := λ j, do json.array l ← success j | exception (λ _, format!"array expected, got {j.typename}"), l.mmap (of_json α) } meta instance {α} [json_serializable α] : non_null_json_serializable (rbmap string α) := { to_json := λ m, json.object (m.to_list.map $ λ x, (x.1, to_json x.2)), of_json := λ j, do json.object l ← success j | exception (λ _, format!"object expected, got {j.typename}"), l ← l.mmap (λ x : string × json, do x2 ← of_json α x.2, pure (x.1, x2)), l.mfoldl (λ m x, do none ← pure (m.find x.1) | exception (λ _, format!"duplicate key {x.1}"), pure (m.insert x.1 x.2)) (mk_rbmap _ _) } /-! ### Basic coercions -/ meta instance : non_null_json_serializable ℕ := { to_json := λ n, to_json (n : ℤ), of_json := λ j, do int.of_nat n ← of_json ℤ j | exception (λ _, format!"must be non-negative"), pure n } meta instance {n : ℕ} : non_null_json_serializable (fin n) := { to_json := λ i, to_json i.val, of_json := λ j, do i ← of_json ℕ j, if h : i < n then pure ⟨i, h⟩ else exception (λ _, format!"must be less than {n}") } meta instance {α : Type} [json_serializable α] (p : α → Prop) [decidable_pred p] : json_serializable (subtype p) := { to_json := λ x, to_json (x : α), of_json := λ j, do i ← of_json α j, if h : p i then pure (subtype.mk i h) else exception (λ _, format!"condition does not hold") } meta instance {α : Type} [non_null_json_serializable α] (p : α → Prop) [decidable_pred p] : non_null_json_serializable (subtype p) := {} /-- Note this only makes sense on types which do not themselves serialize to `null` -/ meta instance {α} [non_null_json_serializable α] : json_serializable (option α) := { to_json := option.elim json.null to_json, of_json := λ j, do (of_json punit j >> pure none) <|> (some <$> of_json α j)} open tactic expr /-- Flatten a list of (p)exprs into a (p)expr forming a list of type `list t`. -/ meta def list.to_expr {elab : bool} (t : expr elab) (l : level) : list (expr elab) → expr elab | [] := expr.app (expr.const `list.nil [l]) t | (x :: xs) := (((expr.const `list.cons [l]).app t).app x).app xs.to_expr /-- Begin parsing fields -/ meta def json_serializable.field_starter (j : json) : exceptional (list (string × json)) := do json.object p ← pure j | exception (λ _, format!"object expected, got {j.typename}"), pure p /-- Check a field exists and is unique -/ meta def json_serializable.field_get (l : list (string × json)) (s : string) : exceptional (option json × list (string × json)) := let (p, n) := l.partition (λ x, prod.fst x = s) in match p with | [] := pure (none, n) | [x] := pure (some x.2, n) | x :: xs := exception (λ _, format!"duplicate {s} field") end /-- Check no fields remain -/ meta def json_serializable.field_terminator (l : list (string × json)) : exceptional unit := do [] ← pure l | exception (λ _, format!"unexpected fields {l.map prod.fst}"), pure () /-- ``((c_name, c_fun), [(p_name, p_fun), ...]) ← get_constructor_and_projections `(struct n)`` gets the names and partial invocations of the constructor and projections of a structure -/ meta def get_constructor_and_projections (t : expr) : tactic (name × (name × expr) × list (name × expr)):= do (const I ls, args) ← pure (get_app_fn_args t), env ← get_env, [ctor] ← pure (env.constructors_of I), ctor ← do { d ← get_decl ctor, let a := @expr.const tt ctor $ d.univ_params.map level.param, pure (ctor, a.mk_app args) }, ctor_type ← infer_type ctor.2, tt ← pure ctor_type.is_pi | pure (I, ctor, []), some fields ← pure (env.structure_fields I) | fail!"Not a structure", projs ← fields.mmap $ λ f, do { d ← get_decl (I ++ f), let a := @expr.const tt (I ++ f) $ d.univ_params.map level.param, pure (f, a.mk_app args) }, pure (I, ctor, projs) /-- Generate an expression that builds a term of type `t` (which is itself a parametrization of the structure `struct_name`) using the expressions resolving to parsed fields in `vars` and the expressions resolving to unparsed `option json` objects in `js`. This can handled dependently-typed and defaulted (via `:=` which for structures is not the same as `opt_param`) fields. -/ meta def of_json_helper (struct_name : name) (t : expr) : Π (vars : list (name × pexpr)) (js : list (name × option expr)), tactic expr | vars [] := do -- allow this partial constructor if `to_expr` allows it let struct := pexpr.mk_structure_instance ⟨some struct_name, vars.map prod.fst, vars.map prod.snd, []⟩, to_expr ``(pure %%struct : exceptional %%t) | vars ((fname, some fj) :: js) := do -- data fields u ← mk_meta_univ, ft : expr ← mk_meta_var (expr.sort u), f_binder ← mk_local' fname binder_info.default ft, let new_vars := vars.concat (fname, to_pexpr f_binder), with_field ← of_json_helper new_vars js >>= tactic.lambdas [f_binder], without_field ← of_json_helper vars js <|> to_expr ``(exception $ λ o, format!"field {%%`(fname)} is required" : exceptional %%t), to_expr ``(option.mmap (of_json _) %%fj >>= option.elim %%without_field %%with_field : exceptional %%t) | vars ((fname, none) :: js) := -- try a default value of_json_helper vars js <|> do { -- otherwise, use decidability u ← mk_meta_univ, ft ← mk_meta_var (expr.sort u), f_binder ← mk_local' fname binder_info.default ft, let new_vars := vars.concat (fname, to_pexpr f_binder), with_field ← of_json_helper new_vars js >>= tactic.lambdas [f_binder], to_expr ``(dite _ %%with_field (λ _, exception $ λ _, format!"condition does not hold")) } /-- A derive handler to serialize structures by their fields. For the following structure: ```lean structure has_default : Type := (x : ℕ := 2) (y : fin x.succ := 3 * fin.of_nat x) (z : ℕ := 3) ``` this generates an `of_json` parser along the lines of ```lean meta def has_default.of_json (j : json) : exceptional (has_default) := do p ← json_serializable.field_starter j, (f_y, p) ← json_serializable.field_get p "y", (f_z, p) ← json_serializable.field_get p "z", f_y.mmap (of_json _) >>= option.elim (f_z.mmap (of_json _) >>= option.elim (pure {has_default.}) (λ z, pure {has_default. z := z}) ) (λ y, f_z.mmap (of_json _) >>= option.elim (pure {has_default.}) (λ z, pure {has_default. y := y, z := z}) ) ``` -/ @[derive_handler, priority 2000] meta def non_null_json_serializable_handler : derive_handler := instance_derive_handler ``non_null_json_serializable $ do intros, `(non_null_json_serializable %%e) ← target >>= whnf, (struct_name, (ctor_name, ctor), fields) ← get_constructor_and_projections e, refine ``(@non_null_json_serializable.mk %%e ⟨λ x, json.object _, λ j, json_serializable.field_starter j >>= _ ⟩), -- the forward direction x ← get_local `x, (projs : list (option expr)) ← fields.mmap (λ ⟨f, a⟩, do let x_e := a.app x, t ← infer_type x_e, s ← infer_type t, expr.sort (level.succ u) ← pure s | pure (none : option expr), level.zero ← pure u | fail!"Only Type 0 is supported", j ← tactic.mk_app `json_serializable.to_json [x_e], pure (some `((%%`(f.to_string), %%j) : string × json)) ), tactic.exact (projs.reduce_option.to_expr `(string × json) level.zero), -- the reverse direction get_local `j >>= tactic.clear, -- check fields are present json_fields ← fields.mmap (λ ⟨f, e⟩, do t ← infer_type e, s ← infer_type t, expr.sort (level.succ u) ← pure s | pure (f, none), -- do nothing for prop fields refine ``(λ p, json_serializable.field_get p %%`(f.to_string) >>= _), tactic.applyc `prod.rec, get_local `p >>= tactic.clear, jf ← tactic.intro (`field ++ f), pure (f, some jf)), refine ``(λ p, json_serializable.field_terminator p >> _), get_local `p >>= tactic.clear, ctor ← of_json_helper struct_name e [] json_fields, exact ctor
e1529290b2b29e85b5d6fa03b687569abef4f6df
976d2334b51721ddc405deb2e1754016d454286e
/src/game_files/sqrt2/sq_eq_zero1.lean
72e929011477a926228baa8cea3f098fd06c8dac
[]
no_license
kbuzzard/lean-at-MC2020
11bb6ac9ec38a6caace9d5d9a1705d6794d9f477
1f7ca65a7ba5cc17eb49f525c02dc6b0e65d6543
refs/heads/master
1,668,496,422,317
1,594,131,838,000
1,594,131,838,000
277,877,735
0
0
null
1,594,142,006,000
1,594,142,005,000
null
UTF-8
Lean
false
false
538
lean
import tactic import data.nat.basic -- Level name : squares_to_zero /- Comment here -/ /- Hint : title_of_the_hint Content of the hint -/ /- Tactic : ring Normalizes expressions in commutative rings by applying lots of distributivity, associativity, commutativity. Can prove equalities. -/ example := nat.pow_two /- Axiom : nat.pow_two statement_of_the_axiom -/ lemma eq_zero_of_sq_eq_zero (m : ℕ) (hm : m^2 = 0) : m = 0 := begin simp only [nat.pow_two] at hm, simp only [nat.mul_eq_zero, or_self] at hm, assumption, end
3538667bf9ede43e9089d1c5af20598d705eb13e
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/measure_theory/lebesgue_measure_auto.lean
5df65794b8ebd14b31158d7d7f91cfe9ebefbdd3
[]
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
9,801
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Yury Kudryashov -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.measure_theory.pi import Mathlib.PostPort universes u_1 namespace Mathlib /-! # Lebesgue measure on the real line and on `ℝⁿ` -/ namespace measure_theory /-! ### Preliminary definitions -/ /-- Length of an interval. This is the largest monotonic function which correctly measures all intervals. -/ def lebesgue_length (s : set ℝ) : ennreal := infi fun (a : ℝ) => infi fun (b : ℝ) => infi fun (h : s ⊆ set.Ico a b) => ennreal.of_real (b - a) @[simp] theorem lebesgue_length_empty : lebesgue_length ∅ = 0 := sorry @[simp] theorem lebesgue_length_Ico (a : ℝ) (b : ℝ) : lebesgue_length (set.Ico a b) = ennreal.of_real (b - a) := sorry theorem lebesgue_length_mono {s₁ : set ℝ} {s₂ : set ℝ} (h : s₁ ⊆ s₂) : lebesgue_length s₁ ≤ lebesgue_length s₂ := sorry theorem lebesgue_length_eq_infi_Ioo (s : set ℝ) : lebesgue_length s = infi fun (a : ℝ) => infi fun (b : ℝ) => infi fun (h : s ⊆ set.Ioo a b) => ennreal.of_real (b - a) := sorry @[simp] theorem lebesgue_length_Ioo (a : ℝ) (b : ℝ) : lebesgue_length (set.Ioo a b) = ennreal.of_real (b - a) := sorry theorem lebesgue_length_eq_infi_Icc (s : set ℝ) : lebesgue_length s = infi fun (a : ℝ) => infi fun (b : ℝ) => infi fun (h : s ⊆ set.Icc a b) => ennreal.of_real (b - a) := sorry @[simp] theorem lebesgue_length_Icc (a : ℝ) (b : ℝ) : lebesgue_length (set.Icc a b) = ennreal.of_real (b - a) := sorry /-- The Lebesgue outer measure, as an outer measure of ℝ. -/ def lebesgue_outer : outer_measure ℝ := outer_measure.of_function lebesgue_length lebesgue_length_empty theorem lebesgue_outer_le_length (s : set ℝ) : coe_fn lebesgue_outer s ≤ lebesgue_length s := outer_measure.of_function_le s theorem lebesgue_length_subadditive {a : ℝ} {b : ℝ} {c : ℕ → ℝ} {d : ℕ → ℝ} (ss : set.Icc a b ⊆ set.Union fun (i : ℕ) => set.Ioo (c i) (d i)) : ennreal.of_real (b - a) ≤ tsum fun (i : ℕ) => ennreal.of_real (d i - c i) := sorry @[simp] theorem lebesgue_outer_Icc (a : ℝ) (b : ℝ) : coe_fn lebesgue_outer (set.Icc a b) = ennreal.of_real (b - a) := sorry @[simp] theorem lebesgue_outer_singleton (a : ℝ) : coe_fn lebesgue_outer (singleton a) = 0 := sorry @[simp] theorem lebesgue_outer_Ico (a : ℝ) (b : ℝ) : coe_fn lebesgue_outer (set.Ico a b) = ennreal.of_real (b - a) := sorry @[simp] theorem lebesgue_outer_Ioo (a : ℝ) (b : ℝ) : coe_fn lebesgue_outer (set.Ioo a b) = ennreal.of_real (b - a) := sorry @[simp] theorem lebesgue_outer_Ioc (a : ℝ) (b : ℝ) : coe_fn lebesgue_outer (set.Ioc a b) = ennreal.of_real (b - a) := sorry theorem is_lebesgue_measurable_Iio {c : ℝ} : measurable_space.is_measurable' (outer_measure.caratheodory lebesgue_outer) (set.Iio c) := sorry theorem lebesgue_outer_trim : outer_measure.trim lebesgue_outer = lebesgue_outer := sorry theorem borel_le_lebesgue_measurable : borel ℝ ≤ outer_measure.caratheodory lebesgue_outer := sorry /-! ### Definition of the Lebesgue measure and lengths of intervals -/ /-- Lebesgue measure on the Borel sets The outer Lebesgue measure is the completion of this measure. (TODO: proof this) -/ protected instance real.measure_space : measure_space ℝ := measure_space.mk (measure.mk lebesgue_outer sorry lebesgue_outer_trim) @[simp] theorem lebesgue_to_outer_measure : measure.to_outer_measure volume = lebesgue_outer := rfl end measure_theory namespace real theorem volume_val (s : set ℝ) : coe_fn volume s = coe_fn measure_theory.lebesgue_outer s := rfl protected instance has_no_atoms_volume : measure_theory.has_no_atoms volume := measure_theory.has_no_atoms.mk measure_theory.lebesgue_outer_singleton @[simp] theorem volume_Ico {a : ℝ} {b : ℝ} : coe_fn volume (set.Ico a b) = ennreal.of_real (b - a) := measure_theory.lebesgue_outer_Ico a b @[simp] theorem volume_Icc {a : ℝ} {b : ℝ} : coe_fn volume (set.Icc a b) = ennreal.of_real (b - a) := measure_theory.lebesgue_outer_Icc a b @[simp] theorem volume_Ioo {a : ℝ} {b : ℝ} : coe_fn volume (set.Ioo a b) = ennreal.of_real (b - a) := measure_theory.lebesgue_outer_Ioo a b @[simp] theorem volume_Ioc {a : ℝ} {b : ℝ} : coe_fn volume (set.Ioc a b) = ennreal.of_real (b - a) := measure_theory.lebesgue_outer_Ioc a b @[simp] theorem volume_singleton {a : ℝ} : coe_fn volume (singleton a) = 0 := measure_theory.lebesgue_outer_singleton a @[simp] theorem volume_interval {a : ℝ} {b : ℝ} : coe_fn volume (set.interval a b) = ennreal.of_real (abs (b - a)) := sorry @[simp] theorem volume_Ioi {a : ℝ} : coe_fn volume (set.Ioi a) = ⊤ := sorry @[simp] theorem volume_Ici {a : ℝ} : coe_fn volume (set.Ici a) = ⊤ := sorry @[simp] theorem volume_Iio {a : ℝ} : coe_fn volume (set.Iio a) = ⊤ := sorry @[simp] theorem volume_Iic {a : ℝ} : coe_fn volume (set.Iic a) = ⊤ := sorry protected instance locally_finite_volume : measure_theory.locally_finite_measure volume := measure_theory.locally_finite_measure.mk fun (x : ℝ) => Exists.intro (set.Ioo (x - 1) (x + 1)) (Exists.intro (mem_nhds_sets is_open_Ioo { left := sub_lt_self x zero_lt_one, right := lt_add_of_pos_right x zero_lt_one }) (eq.mpr (id (Eq.trans ((fun (ᾰ ᾰ_1 : ennreal) (e_2 : ᾰ = ᾰ_1) (ᾰ_2 ᾰ_3 : ennreal) (e_3 : ᾰ_2 = ᾰ_3) => congr (congr_arg Less e_2) e_3) (coe_fn volume (set.Ioo (x - 1) (x + 1))) (ennreal.of_real (x + 1 - (x - 1))) volume_Ioo ⊤ ⊤ (Eq.refl ⊤)) (propext (iff_true_intro ennreal.of_real_lt_top)))) trivial)) /-! ### Volume of a box in `ℝⁿ` -/ theorem volume_Icc_pi {ι : Type u_1} [fintype ι] {a : ι → ℝ} {b : ι → ℝ} : coe_fn volume (set.Icc a b) = finset.prod finset.univ fun (i : ι) => ennreal.of_real (b i - a i) := sorry @[simp] theorem volume_Icc_pi_to_real {ι : Type u_1} [fintype ι] {a : ι → ℝ} {b : ι → ℝ} (h : a ≤ b) : ennreal.to_real (coe_fn volume (set.Icc a b)) = finset.prod finset.univ fun (i : ι) => b i - a i := sorry theorem volume_pi_Ioo {ι : Type u_1} [fintype ι] {a : ι → ℝ} {b : ι → ℝ} : coe_fn volume (set.pi set.univ fun (i : ι) => set.Ioo (a i) (b i)) = finset.prod finset.univ fun (i : ι) => ennreal.of_real (b i - a i) := Eq.trans (measure_theory.measure_congr measure_theory.measure.univ_pi_Ioo_ae_eq_Icc) volume_Icc_pi @[simp] theorem volume_pi_Ioo_to_real {ι : Type u_1} [fintype ι] {a : ι → ℝ} {b : ι → ℝ} (h : a ≤ b) : ennreal.to_real (coe_fn volume (set.pi set.univ fun (i : ι) => set.Ioo (a i) (b i))) = finset.prod finset.univ fun (i : ι) => b i - a i := sorry theorem volume_pi_Ioc {ι : Type u_1} [fintype ι] {a : ι → ℝ} {b : ι → ℝ} : coe_fn volume (set.pi set.univ fun (i : ι) => set.Ioc (a i) (b i)) = finset.prod finset.univ fun (i : ι) => ennreal.of_real (b i - a i) := Eq.trans (measure_theory.measure_congr measure_theory.measure.univ_pi_Ioc_ae_eq_Icc) volume_Icc_pi @[simp] theorem volume_pi_Ioc_to_real {ι : Type u_1} [fintype ι] {a : ι → ℝ} {b : ι → ℝ} (h : a ≤ b) : ennreal.to_real (coe_fn volume (set.pi set.univ fun (i : ι) => set.Ioc (a i) (b i))) = finset.prod finset.univ fun (i : ι) => b i - a i := sorry theorem volume_pi_Ico {ι : Type u_1} [fintype ι] {a : ι → ℝ} {b : ι → ℝ} : coe_fn volume (set.pi set.univ fun (i : ι) => set.Ico (a i) (b i)) = finset.prod finset.univ fun (i : ι) => ennreal.of_real (b i - a i) := Eq.trans (measure_theory.measure_congr measure_theory.measure.univ_pi_Ico_ae_eq_Icc) volume_Icc_pi @[simp] theorem volume_pi_Ico_to_real {ι : Type u_1} [fintype ι] {a : ι → ℝ} {b : ι → ℝ} (h : a ≤ b) : ennreal.to_real (coe_fn volume (set.pi set.univ fun (i : ι) => set.Ico (a i) (b i))) = finset.prod finset.univ fun (i : ι) => b i - a i := sorry /-! ### Images of the Lebesgue measure under translation/multiplication/... -/ theorem map_volume_add_left (a : ℝ) : coe_fn (measure_theory.measure.map (Add.add a)) volume = volume := sorry theorem map_volume_add_right (a : ℝ) : coe_fn (measure_theory.measure.map fun (_x : ℝ) => _x + a) volume = volume := sorry theorem smul_map_volume_mul_left {a : ℝ} (h : a ≠ 0) : ennreal.of_real (abs a) • coe_fn (measure_theory.measure.map (Mul.mul a)) volume = volume := sorry theorem map_volume_mul_left {a : ℝ} (h : a ≠ 0) : coe_fn (measure_theory.measure.map (Mul.mul a)) volume = ennreal.of_real (abs (a⁻¹)) • volume := sorry theorem smul_map_volume_mul_right {a : ℝ} (h : a ≠ 0) : ennreal.of_real (abs a) • coe_fn (measure_theory.measure.map fun (_x : ℝ) => _x * a) volume = volume := sorry theorem map_volume_mul_right {a : ℝ} (h : a ≠ 0) : coe_fn (measure_theory.measure.map fun (_x : ℝ) => _x * a) volume = ennreal.of_real (abs (a⁻¹)) • volume := sorry @[simp] theorem map_volume_neg : coe_fn (measure_theory.measure.map Neg.neg) volume = volume := sorry end real theorem filter.eventually.volume_pos_of_nhds_real {p : ℝ → Prop} {a : ℝ} (h : filter.eventually (fun (x : ℝ) => p x) (nhds a)) : 0 < coe_fn volume (set_of fun (x : ℝ) => p x) := sorry end Mathlib
aac4aca00687ec74b1bebec01f294d51f2ae7754
f1815407acd03d5e25cd9508eb98a28d9b42a66d
/src/helloworld.lean
4fca867ae0ea59a0d14e33e7645422c36cacceb4
[]
no_license
jesse-michael-han/lean-demo
5856ea69873130a91bdc7d39e25e241bdf7c1ba9
4ec7af0d3933470030598cbb1c0c853792bd0b54
refs/heads/master
1,650,492,056,866
1,587,804,047,000
1,587,804,047,000
258,457,256
1
0
null
null
null
null
UTF-8
Lean
false
false
10,538
lean
import tactic import data.nat.parity import system.io section warm_up variables {α β : Type} (p q : α → Prop) (r : α → β → Prop) lemma exercise_1 : (∀ x, p x) ∧ (∀ x, q x) → ∀ x, p x ∧ q x := begin intro H, intro x, refine ⟨_,_⟩, cases H with Hp Hq, exact Hp x, cases H with Hp Hq, exact Hq x end #check exercise_1 #check Prop #check Type #print and -- blast our way to the end example : (∀ x, p x → q x) → (∀ x, p x) → ∀ x, q x := by finish example : (∀ x, p x) ∨ (∀ x, q x) → ∀ x, p x ∨ q x := by finish example : (∃ x, p x ∧ q x) → ∃ x, p x := by finish example : (∃ x, ∀ y, r x y) → ∀ y, ∃ x, r x y := by tidy end warm_up /- We're going to solve a simplified version of the `coffee can problem`, due to David Gries' `The Science of Programming` (note: really good read). Suppose you have a coffee can filled with finitely many white and black beans. You have an infinite supply of white and black beans outside the can. Carry out the following procedure until there is only 1 bean left in the can: - Draw two beans - if their colors are different (i.e. (white, black) or (black, white)), then you discard the white one and return the black one. - if their colors are the same, discard both of them and you add a white bean to the can. Prove that this process terminates with a single white bean iff the number of black beans is even. We're going to solve this problem where the coffee can is a list and we only pop and push beans from the head of the list. -/ /- To state this problem , we need: - [x] a notion of beans - [x] define the "coffee operation" - [ ] a way to count the number of white and black beans - [ ] a notion of evenness (I'm going to import this from mathlib). -/ inductive beans : Type | white : beans | black : beans #print beans.cases_on open beans -- this opens the namespace `beans` so we don't have to qualify the constructors @[simp] def coffee : list beans → list beans | [] := [] | [b] := [b] | (white::white::bs) := coffee (white::bs) | (white::black::bs) := coffee (black::bs) | (black::white::bs) := coffee (black::bs) | (black::black::bs) := coffee (white::bs) def some_beans : list beans := [white, black, white, black, black] instance : has_repr beans := { repr := λ b, beans.cases_on b "◽" "◾" } #eval coffee (some_beans) @[simp] -- by tagging this as simp, make all the equation lemmas generated by Lean -- available to the simplifier def count_beans : beans → list beans → ℕ | b [] := 0 | white (white::bs) := count_beans white bs + 1 | white (black::bs) := count_beans white bs | black (white::bs) := count_beans black bs | black (black::bs) := count_beans black bs + 1 -- Lean has a powerful built-in simplifier tactic that has access to a global library of -- `simp lemmas`. `simp` is essentially a confluent rewriting system. lemma count_beans_is_not_horribly_wrong {xs} : count_beans white xs + count_beans black xs = xs.length := begin induction xs with hd tl IH, { refl }, { cases hd, { simp, rw ← IH, omega }, -- omega will decide linear Presburger arith { simp, rw ← IH, omega } } end open nat -- open nat namespace to avoid qualifying imported defs lemma coffee_lemma_1 {x : beans} {xs : list beans} : even (count_beans black (x::xs)) ↔ even (count_beans black $ coffee (x::xs)) := begin induction xs with hd tl IH generalizing x, { cases x; simp }, { cases x; cases hd, all_goals {try {simp * at *}}, have := @IH white, simp * with parity_simps at *, have := @IH black, simp * with parity_simps at *, have := @IH black, simp * with parity_simps at *, have := @IH white, simp * with parity_simps at * } end lemma coffee_lemma_2 {x : beans} {xs : list beans} : coffee (x::xs) = [white] ∨ coffee (x::xs) = [black] := begin induction xs with hd tl IH generalizing x, { cases x, simp, simp }, { cases x; cases hd, all_goals { simp * at * }} end theorem coffee_can_problem {x : beans} {xs : list beans} : coffee (x::xs) = [white] ↔ even (count_beans black (x::xs)) := begin have H₁ : even (count_beans black (x::xs)) ↔ even (count_beans black $ coffee (x::xs)), by { apply coffee_lemma_1 }, have H₂ : coffee (x::xs) = [white] ∨ coffee (x::xs) = [black], by { apply coffee_lemma_2 }, cases H₂, { refine ⟨_,_⟩, { intro H, rw H₁, rw H, simp }, { intro H, assumption }}, { refine ⟨_,_⟩, { intro H_bad, exfalso, cc }, -- cc is the congruence closure tactic -- chains together equalities and knows -- how to reach simple contradictions -- involving constructors { intro H, exfalso, rw H₁ at H, rw H₂ at H, simp at H, exact H }} end def coffee2 : list beans → list beans := λ bns, match bns with | [] := [] | bns := let num_black_beans := count_beans black bns in if (even num_black_beans) then [white] else [black] end theorem coffee_coffee2 : coffee = coffee2 := begin funext bns, cases bns, { simp[coffee2] }, { by_cases H : even (count_beans black $ bns_hd :: bns_tl), { simp [coffee2, *], rwa ← coffee_can_problem at H }, { simp [coffee2, *], rw ← coffee_can_problem at H, finish using coffee_lemma_2 }} end namespace tactic namespace interactive namespace tactic_parser section metaprogramming @[reducible]meta def tactic_parser : Type → Type := state_t string tactic meta def tactic_parser.run {α} : tactic_parser α → string → tactic α := λ p σ, prod.fst <$> state_t.run p σ meta def parse_char : tactic_parser string := { run := λ s, match s with | ⟨[]⟩ := tactic.failed | ⟨(c::cs)⟩ := prod.mk <$> return ⟨[c]⟩ <*> return ⟨cs⟩ end } meta def failed {α} : tactic_parser α := {run := λ s, tactic.failed} meta def parse_bean : tactic_parser beans := do c ← parse_char, if c = "1" then return white else if c = "0" then return black else failed meta def repeat {α} : tactic_parser α → tactic_parser (list α) := λ p, (list.cons <$> p <*> repeat p) <|> return [] meta instance format_of_repr {α} [has_repr α] : has_to_tactic_format α := { to_tactic_format := λ b, return (let f := (by apply_instance : has_repr α).repr in format.of_string (f b))} run_cmd ((repeat parse_bean).run "101010111001" >>= tactic.trace) -- #eval some_more_beans end metaprogramming end tactic_parser end interactive end tactic /- Some set theory, using Aczel sets (see mathlib's set_theory/zfc.lean for a more thorough development, or Flypitch for a Boolean-valued version) -/ universe u inductive pSet : Type (u+1) -- Aczel sets | mk (α : Type u) (A : α → pSet) namespace pSet def eqv : pSet → pSet → Prop | (⟨α, A⟩) (⟨α', A'⟩) := (∀ a : α, ∃ a' : α', eqv (A a) (A' a')) ∧ (∀ a' : α', ∃ a : α, eqv (A a) (A' a')) def mem : pSet → pSet → Prop | x (⟨α, A⟩) := ∃ a : α, eqv x (A a) infix `∈ˢ`:1024 := pSet.mem infix `=ˢ`:1024 := pSet.eqv end pSet -- this proof actually doesn't use anything and just works for any binary relation -- lemma russell (x : pSet.{u}) (Hx : (∀ y : pSet.{u}, (y ∈ˢ x ↔ (¬ y ∈ˢ y)))): (x ∈ˢ x) ∧ (¬ x ∈ˢ x) := -- begin -- refine ⟨_,_⟩, -- { classical, by_contradiction, have := (Hx x).mpr ‹_›, contradiction }, -- { classical, by_contradiction, have := (Hx x).mp ‹_›, contradiction } -- end -- indeed lemma russell_aux {α : Type*} {mem : α → α → Prop} {x : α} (Hx : (∀ a : α, mem a x ↔ ¬ mem a a)) : mem x x ∧ ¬ mem x x := begin refine ⟨_,_⟩, { classical, by_contradiction, have := (Hx x).mpr ‹_›, contradiction }, { classical, by_contradiction, have := (Hx x).mp ‹_›, contradiction } end lemma russell (x : pSet.{u}) (Hx : (∀ y : pSet.{u}, (y ∈ˢ x ↔ (¬ y ∈ˢ y)))): (x ∈ˢ x) ∧ (¬ x ∈ˢ x) := russell_aux ‹_› @[simp]lemma eqv_refl {x : pSet} : x =ˢ x := by induction x; tidy lemma eqv_trans {x y z : pSet} (H₁ : x =ˢ y) (H₂ : y =ˢ z) : x =ˢ z := begin induction x with α₁ A₁ generalizing y z, induction y with α₂ A₂, induction z with α₃ A₃, cases H₁ with H₁_left H₁_right, cases H₂ with H₂_left H₂_right, refine ⟨_,_⟩; intro i, { cases H₁_left i with j Hj, cases H₂_left j with k Hk, refine ⟨k, _⟩, apply x_ih, exact Hj, exact Hk, }, { cases H₂_right i with j Hj, cases H₁_right j with k Hk, refine ⟨k, _⟩, apply x_ih, exact Hk, exact Hj } end lemma eqv_symm {x y : pSet} (H : x =ˢ y) : y =ˢ x := begin induction x with α A generalizing y, induction y with α' A' generalizing α A, refine ⟨_,_⟩; intro i; cases H with H₁ H₂, { specialize H₂ i, cases H₂ with a Ha, use a, finish }, { specialize H₁ i, cases H₁ with a' Ha', use a', finish } end lemma eqv.symm {x y} : x =ˢ y ↔ y =ˢ x := ⟨eqv_symm, eqv_symm⟩ @[simp]lemma mem_congr_right {x y z : pSet} (H_mem : x ∈ˢ y) (H_eqv : y =ˢ z) : x ∈ˢ z := begin induction y with α A, induction z with β B, cases H_eqv with H₁ H₂, cases H_mem with a Ha, cases H₁ a with b Hb, use b, exact eqv_trans Ha Hb end @[simp]lemma mem_congr_left {x y z : pSet} (H_mem : x ∈ˢ y) (H_eqv : x =ˢ z) : z ∈ˢ y := begin induction y with α A, cases H_mem with a' Ha', use a', exact eqv_trans (eqv_symm H_eqv) ‹_› end @[simp]lemma mem.mk {α : Type u} {a : α} {A : α → pSet.{u}} : A a ∈ˢ (pSet.mk α A : pSet.{u}) := ⟨a, by simp⟩ lemma mem_iff {x y : pSet.{u}} : x ∈ˢ y ↔ ∃ z : pSet.{u}, z ∈ˢ y ∧ x =ˢ z := begin refine ⟨_,_⟩; intro H, { cases y with α A, cases H with a_x H_a_x, refine ⟨A a_x, ⟨_,_⟩⟩, { simp }, { assumption }}, { rcases H with ⟨z, ⟨Hz₁, Hz₂⟩⟩, apply mem_congr_left ‹_›, exact eqv_symm ‹_› } end -- technically a consequence of foundation lemma foundation {x} : x ∈ˢ x → false := begin intro H_mem_self, induction x with α A, rcases H_mem_self with ⟨a, Ha⟩, apply x_ih a, exact mem_congr_right (mem.mk) ‹_› end -- run this file with `lean --run hello_world.lean` def main : io unit := do trace (string.join ((by apply_instance : has_repr beans).repr <$> [white, black, white, black, black, black, white])) (return ()), trace ("Hello world!") (return ())
4ffc5dfa2e6a26203f5143fa41a98c1443bc24b2
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/measure_theory/measure/finite_measure_weak_convergence.lean
0c2cc0f97382c6628d712e3ae29706f3aae8064e
[ "Apache-2.0" ]
permissive
AntoineChambert-Loir/mathlib
64aabb896129885f12296a799818061bc90da1ff
07be904260ab6e36a5769680b6012f03a4727134
refs/heads/master
1,693,187,631,771
1,636,719,886,000
1,636,719,886,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
8,328
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 measure_theory.measure.measure_space /-! # Weak convergence of (finite) measures This file will define the topology of weak convergence of finite measures and probability measures on topological spaces. 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. TODOs: * Define the topologies (the current version only defines the types) via `weak_dual ℝ≥0 (α →ᵇ ℝ≥0)`. * Prove that an equivalent definition of the topologies is obtained requiring continuity of integration of bounded continuous `ℝ`-valued functions instead. * Include the portmanteau theorem on characterizations of weak convergence of (Borel) probability measures. ## Main definitions The main definitions are the types `finite_measure α` and `probability_measure α`. TODO: * Define the topologies on the above types. ## Main results None yet. TODO: * Portmanteau theorem. ## Notations No new notation is introduced. ## Implementation notes The topology of weak convergence of finite Borel measures will be defined using a mapping from `finite_measure α` to `weak_dual ℝ≥0 (α →ᵇ ℝ≥0)`, inheriting the topology from the latter. The current implementation of `finite_measure α` and `probability_measure α` is directly as subtypes of `measure α`, and the coercion to a function is the composition `ennreal.to_nnreal` and the coercion to function of `measure α`. Another alternative would be to use a bijection with `vector_measure α ℝ≥0` as an intermediate step. The choice of implementation should not have drastic downstream effects, so it can be changed later if appropriate. 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 `lintegral` w.r.t. a coercion to `measure α` in any case. ## References * [Billingsley, *Convergence of probability measures*][billingsley1999] ## Tags weak convergence of measures, finite measure, probability measure -/ noncomputable theory open measure_theory open set open filter open_locale topological_space ennreal nnreal namespace measure_theory 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 finite_measure (α : Type*) [measurable_space α] : Type* := {μ : measure α // is_finite_measure μ} namespace 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 /-- 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⟩ } instance : inhabited (finite_measure α) := ⟨0⟩ instance : has_add (finite_measure α) := { add := λ μ ν, ⟨μ + ν, measure_theory.is_finite_measure_add⟩ } instance : has_scalar ℝ≥0 (finite_measure α) := { smul := λ (c : ℝ≥0) μ, ⟨c • μ, measure_theory.is_finite_measure_smul_nnreal⟩, } @[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 : ℝ≥0) (μ : 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 (c : ℝ≥0) (μ : finite_measure α) : (⇑(c • μ) : set α → ℝ≥0) = c • (⇑μ : set α → ℝ≥0) := by { funext, simp [← ennreal.coe_eq_coe], } instance : add_comm_monoid (finite_measure α) := finite_measure.coe_injective.add_comm_monoid (coe : finite_measure α → measure α) finite_measure.coe_zero finite_measure.coe_add /-- 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 finite_measure.coe_injective coe_smul end finite_measure /-- Probability measures are defined as the subtype of measures that have the property of being probability measures (i.e., their total mass is one). -/ def probability_measure (α : Type*) [measurable_space α] : Type* := {μ : measure α // is_probability_measure μ} namespace probability_measure instance [inhabited α] : inhabited (probability_measure α) := ⟨⟨measure.dirac (default α), measure.dirac.is_probability_measure⟩⟩ /-- A probability measure can be interpreted as a measure. -/ instance : has_coe (probability_measure α) (measure_theory.measure α) := coe_subtype instance : has_coe_to_fun (probability_measure α) (λ _, set α → ℝ≥0) := ⟨λ μ s, (μ s).to_nnreal⟩ instance (μ : probability_measure α) : is_probability_measure (μ : measure α) := μ.prop lemma coe_fn_eq_to_nnreal_coe_fn_to_measure (ν : probability_measure α) : (ν : set α → ℝ≥0) = λ s, ((ν : measure α) s).to_nnreal := rfl @[simp] lemma val_eq_to_measure (ν : probability_measure α) : ν.val = (ν : measure α) := rfl lemma coe_injective : function.injective (coe : probability_measure α → measure α) := subtype.coe_injective @[simp] lemma coe_fn_univ (ν : probability_measure α) : ν univ = 1 := congr_arg ennreal.to_nnreal ν.prop.measure_univ /-- A probability measure can be interpreted as a finite measure. -/ def to_finite_measure (μ : probability_measure α) : finite_measure α := ⟨μ, infer_instance⟩ @[simp] lemma coe_comp_to_finite_measure_eq_coe (ν : probability_measure α) : (ν.to_finite_measure : measure α) = (ν : measure α) := rfl @[simp] lemma coe_fn_comp_to_finite_measure_eq_coe_fn (ν : probability_measure α) : (ν.to_finite_measure : set α → ℝ≥0) = (ν : set α → ℝ≥0) := rfl @[simp] lemma ennreal_coe_fn_eq_coe_fn_to_measure (ν : probability_measure α) (s : set α) : (ν s : ℝ≥0∞) = (ν : measure α) s := by { rw [← coe_fn_comp_to_finite_measure_eq_coe_fn, finite_measure.ennreal_coe_fn_eq_coe_fn_to_measure], refl, } @[simp] lemma mass_to_finite_measure (μ : probability_measure α) : μ.to_finite_measure.mass = 1 := μ.coe_fn_univ end probability_measure end measure_theory
169fad6e8849d283b75e6924479b5cedabe945a0
48eee836fdb5c613d9a20741c17db44c8e12e61c
/src/algebra/theories/magma.lean
ebc83622f4ab57ddc3b4f92ebd0b1fc39500bc8a
[ "Apache-2.0" ]
permissive
fgdorais/lean-universal
06430443a4abe51e303e602684c2977d1f5c0834
9259b0f7fb3aa83a9e0a7a3eaa44c262e42cc9b1
refs/heads/master
1,592,479,744,136
1,589,473,399,000
1,589,473,399,000
196,287,552
1
1
null
null
null
null
UTF-8
Lean
false
false
1,964
lean
-- Copyright © 2019 François G. Dorais. All rights reserved. -- Released under Apache 2.0 license as described in the file LICENSE. import .basic import .action namespace algebra signature magma (α : Type*) := (op : α → α → α) namespace magma_sig variables {α : Type*} (s : magma_sig α) @[signature_instance] definition to_left_action : left_action_sig α α := { act := s.op } @[signature_instance] definition to_right_action : right_action_sig α α := { act := s.op } end magma_sig class magma {α} (s : magma_sig α) : Prop := intro [] :: abbreviation magma.infer {α} (s : magma_sig α) : magma s := magma.intro _ @[theory] class cancel_magma {α} (s : magma_sig α) : Prop := intro :: (left_cancellative : identity.op_left_cancellative s.op) (right_cancellative : identity.op_right_cancellative s.op) instance cancel_magma.to_magma {α} (s : magma_sig α) [i : cancel_magma s] : magma s := magma.infer _ @[theory] class comm_magma {α} (s : magma_sig α) : Prop := intro :: (commutative : identity.op_commutative s.op) instance comm_magma.to_magma {α} (s : magma_sig α) [i : comm_magma s] : magma s := magma.infer _ @[theory] class cancel_comm_magma {α} (s : magma_sig α) : Prop := intro :: (commutative : identity.op_commutative s.op) (right_cancellative : identity.op_right_cancellative s.op) instance cancel_comm_magma.to_comm_magma {α} (s : magma_sig α) [i : cancel_comm_magma s] : comm_magma s := comm_magma.infer _ @[identity_instance] theorem cancel_comm_magma.left_cancellative {α} (s : magma_sig α) [i : cancel_comm_magma s] : identity.op_left_cancellative s.op := λ x y z h, have s.op y x = s.op z x, from calc s.op y x = s.op x y : by rw op_commutative s.op ... = s.op x z : by rw h ... = s.op z x : by rw op_commutative s.op, op_right_cancellative s.op this instance cancel_comm_magma.to_cancel_magma {α} (s : magma_sig α) [i : cancel_comm_magma s] : cancel_magma s := cancel_magma.infer _ end algebra
5d6506c331d4aa91e8775a4d5b6098a3b2d157a4
a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91
/tests/lean/elab3.lean
7d5be49ed26bb2634ef55b6413638b92b2e66be0
[ "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
71
lean
open tactic set_option pp.all true check trace_state >> trace_state
3acc91d6ee024dab48345efda0727bdf3d772940
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/data/set/sups.lean
a03506695192e237e5acc02299bea379f2c5863f
[ "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
9,790
lean
/- Copyright (c) 2022 Yaël Dillies. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yaël Dillies -/ import data.set.n_ary import order.upper_lower.basic /-! # Set family operations > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file defines a few binary operations on `set α` for use in set family combinatorics. ## Main declarations * `s ⊻ t`: Set of elements of the form `a ⊔ b` where `a ∈ s`, `b ∈ t`. * `s ⊼ t`: Set of elements of the form `a ⊓ b` where `a ∈ s`, `b ∈ t`. ## Notation We define the following notation in locale `set_family`: * `s ⊻ t` * `s ⊼ t` ## References [B. Bollobás, *Combinatorics*][bollobas1986] -/ open function variables {α : Type*} /-- Notation typeclass for pointwise supremum `⊻`. -/ class has_sups (α : Type*) := (sups : α → α → α) /-- Notation typeclass for pointwise infimum `⊼`. -/ class has_infs (α : Type*) := (infs : α → α → α) -- This notation is meant to have higher precedence than `⊔` and `⊓`, but still within the realm of -- other binary operations infix ` ⊻ `:74 := has_sups.sups infix ` ⊼ `:75 := has_infs.infs namespace set section sups variables [semilattice_sup α] (s s₁ s₂ t t₁ t₂ u v : set α) /-- `s ⊻ t` is the set of elements of the form `a ⊔ b` where `a ∈ s`, `b ∈ t`. -/ protected def has_sups : has_sups (set α) := ⟨image2 (⊔)⟩ localized "attribute [instance] set.has_sups" in set_family variables {s s₁ s₂ t t₁ t₂ u} {a b c : α} @[simp] lemma mem_sups : c ∈ s ⊻ t ↔ ∃ (a ∈ s) (b ∈ t), a ⊔ b = c := by simp [(⊻)] lemma sup_mem_sups : a ∈ s → b ∈ t → a ⊔ b ∈ s ⊻ t := mem_image2_of_mem lemma sups_subset : s₁ ⊆ s₂ → t₁ ⊆ t₂ → s₁ ⊻ t₁ ⊆ s₂ ⊻ t₂ := image2_subset lemma sups_subset_left : t₁ ⊆ t₂ → s ⊻ t₁ ⊆ s ⊻ t₂ := image2_subset_left lemma sups_subset_right : s₁ ⊆ s₂ → s₁ ⊻ t ⊆ s₂ ⊻ t := image2_subset_right lemma image_subset_sups_left : b ∈ t → (λ a, a ⊔ b) '' s ⊆ s ⊻ t := image_subset_image2_left lemma image_subset_sups_right : a ∈ s → (⊔) a '' t ⊆ s ⊻ t := image_subset_image2_right lemma forall_sups_iff {p : α → Prop} : (∀ c ∈ s ⊻ t, p c) ↔ ∀ (a ∈ s) (b ∈ t), p (a ⊔ b) := forall_image2_iff @[simp] lemma sups_subset_iff : s ⊻ t ⊆ u ↔ ∀ (a ∈ s) (b ∈ t), a ⊔ b ∈ u := image2_subset_iff @[simp] lemma sups_nonempty : (s ⊻ t).nonempty ↔ s.nonempty ∧ t.nonempty := image2_nonempty_iff protected lemma nonempty.sups : s.nonempty → t.nonempty → (s ⊻ t).nonempty := nonempty.image2 lemma nonempty.of_sups_left : (s ⊻ t).nonempty → s.nonempty := nonempty.of_image2_left lemma nonempty.of_sups_right : (s ⊻ t).nonempty → t.nonempty := nonempty.of_image2_right @[simp] lemma empty_sups : ∅ ⊻ t = ∅ := image2_empty_left @[simp] lemma sups_empty : s ⊻ ∅ = ∅ := image2_empty_right @[simp] lemma sups_eq_empty : s ⊻ t = ∅ ↔ s = ∅ ∨ t = ∅ := image2_eq_empty_iff @[simp] lemma singleton_sups : {a} ⊻ t = t.image (λ b, a ⊔ b) := image2_singleton_left @[simp] lemma sups_singleton : s ⊻ {b} = s.image (λ a, a ⊔ b) := image2_singleton_right lemma singleton_sups_singleton : ({a} ⊻ {b} : set α) = {a ⊔ b} := image2_singleton lemma sups_union_left : (s₁ ∪ s₂) ⊻ t = s₁ ⊻ t ∪ s₂ ⊻ t := image2_union_left lemma sups_union_right : s ⊻ (t₁ ∪ t₂) = s ⊻ t₁ ∪ s ⊻ t₂ := image2_union_right lemma sups_inter_subset_left : (s₁ ∩ s₂) ⊻ t ⊆ s₁ ⊻ t ∩ s₂ ⊻ t := image2_inter_subset_left lemma sups_inter_subset_right : s ⊻ (t₁ ∩ t₂) ⊆ s ⊻ t₁ ∩ s ⊻ t₂ := image2_inter_subset_right variables (s t u v) lemma Union_image_sup_left : (⋃ a ∈ s, (⊔) a '' t) = s ⊻ t := Union_image_left _ lemma Union_image_sup_right : (⋃ b ∈ t, (⊔ b) '' s) = s ⊻ t := Union_image_right _ @[simp] lemma image_sup_prod (s t : set α) : (s ×ˢ t).image (uncurry (⊔)) = s ⊻ t := image_uncurry_prod _ _ _ lemma sups_assoc : (s ⊻ t) ⊻ u = s ⊻ (t ⊻ u) := image2_assoc $ λ _ _ _, sup_assoc lemma sups_comm : s ⊻ t = t ⊻ s := image2_comm $ λ _ _, sup_comm lemma sups_left_comm : s ⊻ (t ⊻ u) = t ⊻ (s ⊻ u) := image2_left_comm sup_left_comm lemma sups_right_comm : (s ⊻ t) ⊻ u = (s ⊻ u) ⊻ t := image2_right_comm sup_right_comm lemma sups_sups_sups_comm : (s ⊻ t) ⊻ (u ⊻ v) = (s ⊻ u) ⊻ (t ⊻ v) := image2_image2_image2_comm sup_sup_sup_comm end sups section infs variables [semilattice_inf α] (s s₁ s₂ t t₁ t₂ u v : set α) /-- `s ⊼ t` is the set of elements of the form `a ⊓ b` where `a ∈ s`, `b ∈ t`. -/ protected def has_infs : has_infs (set α) := ⟨image2 (⊓)⟩ localized "attribute [instance] set.has_infs" in set_family variables {s s₁ s₂ t t₁ t₂ u} {a b c : α} @[simp] lemma mem_infs : c ∈ s ⊼ t ↔ ∃ (a ∈ s) (b ∈ t), a ⊓ b = c := by simp [(⊼)] lemma inf_mem_infs : a ∈ s → b ∈ t → a ⊓ b ∈ s ⊼ t := mem_image2_of_mem lemma infs_subset : s₁ ⊆ s₂ → t₁ ⊆ t₂ → s₁ ⊼ t₁ ⊆ s₂ ⊼ t₂ := image2_subset lemma infs_subset_left : t₁ ⊆ t₂ → s ⊼ t₁ ⊆ s ⊼ t₂ := image2_subset_left lemma infs_subset_right : s₁ ⊆ s₂ → s₁ ⊼ t ⊆ s₂ ⊼ t := image2_subset_right lemma image_subset_infs_left : b ∈ t → (λ a, a ⊓ b) '' s ⊆ s ⊼ t := image_subset_image2_left lemma image_subset_infs_right : a ∈ s → (⊓) a '' t ⊆ s ⊼ t := image_subset_image2_right lemma forall_infs_iff {p : α → Prop} : (∀ c ∈ s ⊼ t, p c) ↔ ∀ (a ∈ s) (b ∈ t), p (a ⊓ b) := forall_image2_iff @[simp] lemma infs_subset_iff : s ⊼ t ⊆ u ↔ ∀ (a ∈ s) (b ∈ t), a ⊓ b ∈ u := image2_subset_iff @[simp] lemma infs_nonempty : (s ⊼ t).nonempty ↔ s.nonempty ∧ t.nonempty := image2_nonempty_iff protected lemma nonempty.infs : s.nonempty → t.nonempty → (s ⊼ t).nonempty := nonempty.image2 lemma nonempty.of_infs_left : (s ⊼ t).nonempty → s.nonempty := nonempty.of_image2_left lemma nonempty.of_infs_right : (s ⊼ t).nonempty → t.nonempty := nonempty.of_image2_right @[simp] lemma empty_infs : ∅ ⊼ t = ∅ := image2_empty_left @[simp] lemma infs_empty : s ⊼ ∅ = ∅ := image2_empty_right @[simp] lemma infs_eq_empty : s ⊼ t = ∅ ↔ s = ∅ ∨ t = ∅ := image2_eq_empty_iff @[simp] lemma singleton_infs : {a} ⊼ t = t.image (λ b, a ⊓ b) := image2_singleton_left @[simp] lemma infs_singleton : s ⊼ {b} = s.image (λ a, a ⊓ b) := image2_singleton_right lemma singleton_infs_singleton : ({a} ⊼ {b} : set α) = {a ⊓ b} := image2_singleton lemma infs_union_left : (s₁ ∪ s₂) ⊼ t = s₁ ⊼ t ∪ s₂ ⊼ t := image2_union_left lemma infs_union_right : s ⊼ (t₁ ∪ t₂) = s ⊼ t₁ ∪ s ⊼ t₂ := image2_union_right lemma infs_inter_subset_left : (s₁ ∩ s₂) ⊼ t ⊆ s₁ ⊼ t ∩ s₂ ⊼ t := image2_inter_subset_left lemma infs_inter_subset_right : s ⊼ (t₁ ∩ t₂) ⊆ s ⊼ t₁ ∩ s ⊼ t₂ := image2_inter_subset_right variables (s t u v) lemma Union_image_inf_left : (⋃ a ∈ s, (⊓) a '' t) = s ⊼ t := Union_image_left _ lemma Union_image_inf_right : (⋃ b ∈ t, (⊓ b) '' s) = s ⊼ t := Union_image_right _ @[simp] lemma image_inf_prod (s t : set α) : (s ×ˢ t).image (uncurry (⊓)) = s ⊼ t := image_uncurry_prod _ _ _ lemma infs_assoc : (s ⊼ t) ⊼ u = s ⊼ (t ⊼ u) := image2_assoc $ λ _ _ _, inf_assoc lemma infs_comm : s ⊼ t = t ⊼ s := image2_comm $ λ _ _, inf_comm lemma infs_left_comm : s ⊼ (t ⊼ u) = t ⊼ (s ⊼ u) := image2_left_comm inf_left_comm lemma infs_right_comm : (s ⊼ t) ⊼ u = (s ⊼ u) ⊼ t := image2_right_comm inf_right_comm lemma infs_infs_infs_comm : (s ⊼ t) ⊼ (u ⊼ v) = (s ⊼ u) ⊼ (t ⊼ v) := image2_image2_image2_comm inf_inf_inf_comm end infs open_locale set_family section distrib_lattice variables [distrib_lattice α] (s t u : set α) lemma sups_infs_subset_left : s ⊻ (t ⊼ u) ⊆ (s ⊻ t) ⊼ (s ⊻ u) := image2_distrib_subset_left $ λ _ _ _, sup_inf_left lemma sups_infs_subset_right : (t ⊼ u) ⊻ s ⊆ (t ⊻ s) ⊼ (u ⊻ s) := image2_distrib_subset_right $ λ _ _ _, sup_inf_right lemma infs_sups_subset_left : s ⊼ (t ⊻ u) ⊆ (s ⊼ t) ⊻ (s ⊼ u) := image2_distrib_subset_left $ λ _ _ _, inf_sup_left lemma infs_sups_subset_right : (t ⊻ u) ⊼ s ⊆ (t ⊼ s) ⊻ (u ⊼ s) := image2_distrib_subset_right $ λ _ _ _, inf_sup_right end distrib_lattice end set open_locale set_family @[simp] lemma upper_closure_sups [semilattice_sup α] (s t : set α) : upper_closure (s ⊻ t) = upper_closure s ⊔ upper_closure t := begin ext a, simp only [set_like.mem_coe, mem_upper_closure, set.mem_sups, exists_and_distrib_left, exists_prop, upper_set.coe_sup, set.mem_inter_iff], split, { rintro ⟨_, ⟨b, hb, c, hc, rfl⟩, ha⟩, exact ⟨⟨b, hb, le_sup_left.trans ha⟩, c, hc, le_sup_right.trans ha⟩ }, { rintro ⟨⟨b, hb, hab⟩, c, hc, hac⟩, exact ⟨_, ⟨b, hb, c, hc, rfl⟩, sup_le hab hac⟩ } end @[simp] lemma lower_closure_infs [semilattice_inf α] (s t : set α) : lower_closure (s ⊼ t) = lower_closure s ⊓ lower_closure t := begin ext a, simp only [set_like.mem_coe, mem_lower_closure, set.mem_infs, exists_and_distrib_left, exists_prop, lower_set.coe_sup, set.mem_inter_iff], split, { rintro ⟨_, ⟨b, hb, c, hc, rfl⟩, ha⟩, exact ⟨⟨b, hb, ha.trans inf_le_left⟩, c, hc, ha.trans inf_le_right⟩ }, { rintro ⟨⟨b, hb, hab⟩, c, hc, hac⟩, exact ⟨_, ⟨b, hb, c, hc, rfl⟩, le_inf hab hac⟩ } end
677df19251c5e5a95ad2353d16328b522611d92a
54d7e71c3616d331b2ec3845d31deb08f3ff1dea
/library/init/meta/transfer.lean
3d6ca447db4a65b1d9965bc284ba55cfcd3b0be8
[ "Apache-2.0" ]
permissive
pachugupta/lean
6f3305c4292288311cc4ab4550060b17d49ffb1d
0d02136a09ac4cf27b5c88361750e38e1f485a1a
refs/heads/master
1,611,110,653,606
1,493,130,117,000
1,493,167,649,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
7,598
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Johannes Hölzl (CMU) -/ prelude import init.meta.tactic init.meta.match_tactic init.relator init.meta.mk_dec_eq_instance import init.data.list.instances namespace transfer open tactic expr list monad /- Transfer rules are of the shape: rel_t : {u} Πx, R t₁ t₂ where `u` is a list of universe parameters, `x` is a list of dependent variables, and `R` is a relation. Then this rule will translate `t₁` (depending on `u` and `x`) into `t₂`. `u` and `x` will be called parameters. When `R` is a relation on functions lifted from `S` and `R` the variables bound by `S` are called arguments. `R` is generally constructed using `⇒` (i.e. `relator.lift_fun`). As example: rel_eq : (R ⇒ R ⇒ iff) eq t transfer will match this rule when it sees: (@eq α a b) and transfer it to (t a b) Here `α` is a parameter and `a` and `b` are arguments. TODO: add trace statements TODO: currently the used relation must be fixed by the matched rule or through type class inference. Maybe we want to replace this by type inference similar to Isabelle's transfer. -/ private meta structure rel_data := (in_type : expr) (out_type : expr) (relation : expr) meta instance has_to_tactic_format_rel_data : has_to_tactic_format rel_data := ⟨λr, do R ← pp r.relation, α ← pp r.in_type, β ← pp r.out_type, return $ to_fmt "(" ++ R ++ ": rel (" ++ α ++ ") (" ++ β ++ "))" ⟩ private meta structure rule_data := (pr : expr) (uparams : list name) -- levels not in pat (params : list (expr × bool)) -- fst : local constant, snd = tt → param appears in pattern (uargs : list name) -- levels not in pat (args : list (expr × rel_data)) -- fst : local constant (pat : pattern) -- `R c` (out : expr) -- right-hand side `d` of rel equation `R c d` meta instance has_to_tactic_format_rule_data : has_to_tactic_format rule_data := ⟨λr, do pr ← pp r.pr, up ← pp r.uparams, mp ← pp r.params, ua ← pp r.uargs, ma ← pp r.args, pat ← pp r.pat.target, out ← pp r.out, return $ to_fmt "{ ⟨" ++ pat ++ "⟩ pr: " ++ pr ++ " → " ++ out ++ ", " ++ up ++ " " ++ mp ++ " " ++ ua ++ " " ++ ma ++ " }" ⟩ private meta def get_lift_fun : expr → tactic (list rel_data × expr) | e := do { guardb (is_constant_of (get_app_fn e) `relator.lift_fun), [α, β, γ, δ, R, S] ← return $ get_app_args e, (ps, r) ← get_lift_fun S, return (rel_data.mk α β R :: ps, r)} <|> return ([], e) private meta def mark_occurences (e : expr) : list expr → list (expr × bool) | [] := [] | (h :: t) := let xs := mark_occurences t in (h, occurs h e || any xs (λ⟨e, oc⟩, oc && occurs h e)) :: xs private meta def analyse_rule (u' : list name) (pr : expr) : tactic rule_data := do t ← infer_type pr, (params, app (app r f) g) ← mk_local_pis t, (arg_rels, R) ← get_lift_fun r, args ← monad.for (enum arg_rels) (λ⟨n, a⟩, prod.mk <$> mk_local_def (mk_simple_name ("a_" ++ to_string n)) a.in_type <*> pure a), a_vars ← return $ fmap prod.fst args, p ← head_beta (app_of_list f a_vars), p_data ← return $ mark_occurences (app R p) params, p_vars ← return $ list.map prod.fst (list.filter (λx, ↑x.2) p_data), u ← return $ collect_univ_params (app R p) ∩ u', pat ← mk_pattern (fmap level.param u) (p_vars ++ a_vars) (app R p) (fmap level.param u) (p_vars ++ a_vars), return $ rule_data.mk pr (list.remove_all u' u) p_data u args pat g private meta def analyse_decls : list name → tactic (list rule_data) := monad.mapm (λn, do d ← get_decl n, c ← return d.univ_params.length, ls ← monad.for (range c) (λ_, mk_fresh_name), analyse_rule ls (const n (ls.map level.param))) private meta def split_params_args : list (expr × bool) → list expr → list (expr × option expr) × list expr | ((lc, tt) :: ps) (e :: es) := let (ps', es') := split_params_args ps es in ((lc, some e) :: ps', es') | ((lc, ff) :: ps) es := let (ps', es') := split_params_args ps es in ((lc, none) :: ps', es') | _ es := ([], es) private meta def param_substitutions (ctxt : list expr) : list (expr × option expr) → tactic (list (name × expr) × list expr) | (((local_const n _ bi t), s) :: ps) := do (e, m) ← match s with | (some e) := return (e, []) | none := let ctxt' := list.filter (λv, occurs v t) ctxt in let ty := pis ctxt' t in if bi = binder_info.inst_implicit then do guard (bi = binder_info.inst_implicit), e ← instantiate_mvars ty >>= mk_instance, return (e, []) else do mv ← mk_meta_var ty, return (app_of_list mv ctxt', [mv]) end, sb ← return $ instantiate_local n e, ps ← return $ fmap (prod.map sb (fmap sb)) ps, (ms, vs) ← param_substitutions ps, return ((n, e) :: ms, m ++ vs) | _ := return ([], []) /- input expression a type `R a`, it finds a type `b`, s.t. there is a proof of the type `R a b`. It return (`a`, pr : `R a b`) -/ meta def compute_transfer : list rule_data → list expr → expr → tactic (expr × expr × list expr) | rds ctxt e := do -- Select matching rule (i, ps, args, ms, rd) ← first (rds.for (λrd, do (l, m) ← match_pattern_core semireducible rd.pat e, level_map ← monad.for rd.uparams (λl, prod.mk l <$> mk_meta_univ), inst_univ ← return $ (λe, instantiate_univ_params e (level_map ++ zip rd.uargs l)), (ps, args) ← return $ split_params_args (list.map (prod.map inst_univ id) rd.params) m, (ps, ms) ← param_substitutions ctxt ps, /- this checks type class parameters -/ return (instantiate_locals ps ∘ inst_univ, ps, args, ms, rd))), (bs, hs, mss) ← monad.for (zip rd.args args) (λ⟨⟨_, d⟩, e⟩, do -- Argument has function type (args, r) ← get_lift_fun (i d.relation), ((a_vars, b_vars), (R_vars, bnds)) ← monad.for (enum args) (λ⟨n, arg⟩, do a ← mk_local_def (("a" ++ to_string n) : string) arg.in_type, b ← mk_local_def (("b" ++ to_string n) : string) arg.out_type, R ← mk_local_def (("R" ++ to_string n) : string) (arg.relation a b), return ((a, b), (R, [a, b, R]))) >>= (return ∘ prod.map unzip unzip ∘ unzip), rds' ← monad.for R_vars (analyse_rule []), -- Transfer argument a ← return $ i e, a' ← head_beta (app_of_list a a_vars), (b, pr, ms) ← compute_transfer (rds ++ rds') (ctxt ++ a_vars) (app r a'), b' ← head_eta (lambdas b_vars b), return (b', [a, b', lambdas (list.join bnds) pr], ms)) >>= (return ∘ prod.map id unzip ∘ unzip), -- Combine b ← head_beta (app_of_list (i rd.out) bs), pr ← return $ app_of_list (i rd.pr) (fmap prod.snd ps ++ list.join hs), return (b, pr, ms ++ list.join mss) meta def transfer (ds : list name) : tactic unit := do rds ← analyse_decls ds, tgt ← target, (guard (¬ tgt.has_meta_var) <|> fail "Target contains (universe) meta variables. This is not supported by transfer."), (new_tgt, pr, ms) ← compute_transfer rds [] (const `iff [] tgt), new_pr ← mk_meta_var new_tgt, /- Setup final tactic state -/ exact (const `iff.mpr [] tgt new_tgt pr new_pr), ms ← monad.for ms (λm, (get_assignment m >> return []) <|> return [m]), gs ← get_goals, set_goals (list.join ms ++ new_pr :: gs) end transfer
e4654c2cc7407c557f4b36e4243c1d876715a065
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/group_theory/congruence.lean
857995ec743300441fb90e1d20b4a2843cd50b2c
[ "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
52,791
lean
/- Copyright (c) 2019 Amelia Livingston. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Amelia Livingston -/ import algebra.group.prod import algebra.hom.equiv.basic import data.setoid.basic import group_theory.submonoid.operations /-! # Congruence relations > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file defines congruence relations: equivalence relations that preserve a binary operation, which in this case is multiplication or addition. The principal definition is a `structure` extending a `setoid` (an equivalence relation), and the inductive definition of the smallest congruence relation containing a binary relation is also given (see `con_gen`). The file also proves basic properties of the quotient of a type by a congruence relation, and the complete lattice of congruence relations on a type. We then establish an order-preserving bijection between the set of congruence relations containing a congruence relation `c` and the set of congruence relations on the quotient by `c`. The second half of the file concerns congruence relations on monoids, in which case the quotient by the congruence relation is also a monoid. There are results about the universal property of quotients of monoids, and the isomorphism theorems for monoids. ## Implementation notes The inductive definition of a congruence relation could be a nested inductive type, defined using the equivalence closure of a binary relation `eqv_gen`, but the recursor generated does not work. A nested inductive definition could conceivably shorten proofs, because they would allow invocation of the corresponding lemmas about `eqv_gen`. The lemmas `refl`, `symm` and `trans` are not tagged with `@[refl]`, `@[symm]`, and `@[trans]` respectively as these tags do not work on a structure coerced to a binary relation. There is a coercion from elements of a type to the element's equivalence class under a congruence relation. A congruence relation on a monoid `M` can be thought of as a submonoid of `M × M` for which membership is an equivalence relation, but whilst this fact is established in the file, it is not used, since this perspective adds more layers of definitional unfolding. ## Tags congruence, congruence relation, quotient, quotient by congruence relation, monoid, quotient monoid, isomorphism theorems -/ variables (M : Type*) {N : Type*} {P : Type*} open function setoid /-- A congruence relation on a type with an addition is an equivalence relation which preserves addition. -/ structure add_con [has_add M] extends setoid M := (add' : ∀ {w x y z}, r w x → r y z → r (w + y) (x + z)) /-- A congruence relation on a type with a multiplication is an equivalence relation which preserves multiplication. -/ @[to_additive add_con] structure con [has_mul M] extends setoid M := (mul' : ∀ {w x y z}, r w x → r y z → r (w * y) (x * z)) /-- The equivalence relation underlying an additive congruence relation. -/ add_decl_doc add_con.to_setoid /-- The equivalence relation underlying a multiplicative congruence relation. -/ add_decl_doc con.to_setoid variables {M} /-- The inductively defined smallest additive congruence relation containing a given binary relation. -/ inductive add_con_gen.rel [has_add M] (r : M → M → Prop) : M → M → Prop | of : Π x y, r x y → add_con_gen.rel x y | refl : Π x, add_con_gen.rel x x | symm : Π x y, add_con_gen.rel x y → add_con_gen.rel y x | trans : Π x y z, add_con_gen.rel x y → add_con_gen.rel y z → add_con_gen.rel x z | add : Π w x y z, add_con_gen.rel w x → add_con_gen.rel y z → add_con_gen.rel (w + y) (x + z) /-- The inductively defined smallest multiplicative congruence relation containing a given binary relation. -/ @[to_additive add_con_gen.rel] inductive con_gen.rel [has_mul M] (r : M → M → Prop) : M → M → Prop | of : Π x y, r x y → con_gen.rel x y | refl : Π x, con_gen.rel x x | symm : Π x y, con_gen.rel x y → con_gen.rel y x | trans : Π x y z, con_gen.rel x y → con_gen.rel y z → con_gen.rel x z | mul : Π w x y z, con_gen.rel w x → con_gen.rel y z → con_gen.rel (w * y) (x * z) /-- The inductively defined smallest multiplicative congruence relation containing a given binary relation. -/ @[to_additive add_con_gen "The inductively defined smallest additive congruence relation containing a given binary relation."] def con_gen [has_mul M] (r : M → M → Prop) : con M := ⟨⟨con_gen.rel r, ⟨con_gen.rel.refl, con_gen.rel.symm, con_gen.rel.trans⟩⟩, con_gen.rel.mul⟩ namespace con section variables [has_mul M] [has_mul N] [has_mul P] (c : con M) @[to_additive] instance : inhabited (con M) := ⟨con_gen empty_relation⟩ /-- A coercion from a congruence relation to its underlying binary relation. -/ @[to_additive "A coercion from an additive congruence relation to its underlying binary relation."] instance : has_coe_to_fun (con M) (λ _, M → M → Prop) := ⟨λ c, λ x y, @setoid.r _ c.to_setoid x y⟩ @[simp, to_additive] lemma rel_eq_coe (c : con M) : c.r = c := rfl /-- Congruence relations are reflexive. -/ @[to_additive "Additive congruence relations are reflexive."] protected lemma refl (x) : c x x := c.to_setoid.refl' x /-- Congruence relations are symmetric. -/ @[to_additive "Additive congruence relations are symmetric."] protected lemma symm : ∀ {x y}, c x y → c y x := λ _ _ h, c.to_setoid.symm' h /-- Congruence relations are transitive. -/ @[to_additive "Additive congruence relations are transitive."] protected lemma trans : ∀ {x y z}, c x y → c y z → c x z := λ _ _ _ h, c.to_setoid.trans' h /-- Multiplicative congruence relations preserve multiplication. -/ @[to_additive "Additive congruence relations preserve addition."] protected lemma mul : ∀ {w x y z}, c w x → c y z → c (w * y) (x * z) := λ _ _ _ _ h1 h2, c.mul' h1 h2 @[simp, to_additive] lemma rel_mk {s : setoid M} {h a b} : con.mk s h a b ↔ r a b := iff.rfl /-- Given a type `M` with a multiplication, a congruence relation `c` on `M`, and elements of `M` `x, y`, `(x, y) ∈ M × M` iff `x` is related to `y` by `c`. -/ @[to_additive "Given a type `M` with an addition, `x, y ∈ M`, and an additive congruence relation `c` on `M`, `(x, y) ∈ M × M` iff `x` is related to `y` by `c`."] instance : has_mem (M × M) (con M) := ⟨λ x c, c x.1 x.2⟩ variables {c} /-- The map sending a congruence relation to its underlying binary relation is injective. -/ @[to_additive "The map sending an additive congruence relation to its underlying binary relation is injective."] lemma ext' {c d : con M} (H : c.r = d.r) : c = d := by { rcases c with ⟨⟨⟩⟩, rcases d with ⟨⟨⟩⟩, cases H, congr, } /-- Extensionality rule for congruence relations. -/ @[ext, to_additive "Extensionality rule for additive congruence relations."] lemma ext {c d : con M} (H : ∀ x y, c x y ↔ d x y) : c = d := ext' $ by ext; apply H /-- The map sending a congruence relation to its underlying equivalence relation is injective. -/ @[to_additive "The map sending an additive congruence relation to its underlying equivalence relation is injective."] lemma to_setoid_inj {c d : con M} (H : c.to_setoid = d.to_setoid) : c = d := ext $ ext_iff.1 H /-- Iff version of extensionality rule for congruence relations. -/ @[to_additive "Iff version of extensionality rule for additive congruence relations."] lemma ext_iff {c d : con M} : (∀ x y, c x y ↔ d x y) ↔ c = d := ⟨ext, λ h _ _, h ▸ iff.rfl⟩ /-- Two congruence relations are equal iff their underlying binary relations are equal. -/ @[to_additive "Two additive congruence relations are equal iff their underlying binary relations are equal."] lemma ext'_iff {c d : con M} : c.r = d.r ↔ c = d := ⟨ext', λ h, h ▸ rfl⟩ /-- The kernel of a multiplication-preserving function as a congruence relation. -/ @[to_additive "The kernel of an addition-preserving function as an additive congruence relation."] def mul_ker (f : M → P) (h : ∀ x y, f (x * y) = f x * f y) : con M := { to_setoid := setoid.ker f, mul' := λ _ _ _ _ h1 h2, by { dsimp [setoid.ker, on_fun] at *, rw [h, h1, h2, h], } } /-- Given types with multiplications `M, N`, the product of two congruence relations `c` on `M` and `d` on `N`: `(x₁, x₂), (y₁, y₂) ∈ M × N` are related by `c.prod d` iff `x₁` is related to `y₁` by `c` and `x₂` is related to `y₂` by `d`. -/ @[to_additive prod "Given types with additions `M, N`, the product of two congruence relations `c` on `M` and `d` on `N`: `(x₁, x₂), (y₁, y₂) ∈ M × N` are related by `c.prod d` iff `x₁` is related to `y₁` by `c` and `x₂` is related to `y₂` by `d`."] protected def prod (c : con M) (d : con N) : con (M × N) := { mul' := λ _ _ _ _ h1 h2, ⟨c.mul h1.1 h2.1, d.mul h1.2 h2.2⟩, ..c.to_setoid.prod d.to_setoid } /-- The product of an indexed collection of congruence relations. -/ @[to_additive "The product of an indexed collection of additive congruence relations."] def pi {ι : Type*} {f : ι → Type*} [Π i, has_mul (f i)] (C : Π i, con (f i)) : con (Π i, f i) := { mul' := λ _ _ _ _ h1 h2 i, (C i).mul (h1 i) (h2 i), ..@pi_setoid _ _ $ λ i, (C i).to_setoid } variables (c) -- Quotients /-- Defining the quotient by a congruence relation of a type with a multiplication. -/ @[to_additive "Defining the quotient by an additive congruence relation of a type with an addition."] protected def quotient := quotient $ c.to_setoid /-- Coercion from a type with a multiplication to its quotient by a congruence relation. See Note [use has_coe_t]. -/ @[to_additive "Coercion from a type with an addition to its quotient by an additive congruence relation", priority 0] instance : has_coe_t M c.quotient := ⟨@quotient.mk _ c.to_setoid⟩ /-- The quotient by a decidable congruence relation has decidable equality. -/ @[to_additive "The quotient by a decidable additive congruence relation has decidable equality.", priority 500] -- Lower the priority since it unifies with any quotient type. instance [d : ∀ a b, decidable (c a b)] : decidable_eq c.quotient := @quotient.decidable_eq M c.to_setoid d @[simp, to_additive] lemma quot_mk_eq_coe {M : Type*} [has_mul M] (c : con M) (x : M) : quot.mk c x = (x : c.quotient) := rfl /-- The function on the quotient by a congruence relation `c` induced by a function that is constant on `c`'s equivalence classes. -/ @[elab_as_eliminator, to_additive "The function on the quotient by a congruence relation `c` induced by a function that is constant on `c`'s equivalence classes."] protected def lift_on {β} {c : con M} (q : c.quotient) (f : M → β) (h : ∀ a b, c a b → f a = f b) : β := quotient.lift_on' q f h /-- The binary function on the quotient by a congruence relation `c` induced by a binary function that is constant on `c`'s equivalence classes. -/ @[elab_as_eliminator, to_additive "The binary function on the quotient by a congruence relation `c` induced by a binary function that is constant on `c`'s equivalence classes."] protected def lift_on₂ {β} {c : con M} (q r : c.quotient) (f : M → M → β) (h : ∀ a₁ a₂ b₁ b₂, c a₁ b₁ → c a₂ b₂ → f a₁ a₂ = f b₁ b₂) : β := quotient.lift_on₂' q r f h /-- A version of `quotient.hrec_on₂'` for quotients by `con`. -/ @[to_additive "A version of `quotient.hrec_on₂'` for quotients by `add_con`."] protected def hrec_on₂ {cM : con M} {cN : con N} {φ : cM.quotient → cN.quotient → Sort*} (a : cM.quotient) (b : cN.quotient) (f : Π (x : M) (y : N), φ x y) (h : ∀ x y x' y', cM x x' → cN y y' → f x y == f x' y') : φ a b := quotient.hrec_on₂' a b f h @[simp, to_additive] lemma hrec_on₂_coe {cM : con M} {cN : con N} {φ : cM.quotient → cN.quotient → Sort*} (a : M) (b : N) (f : Π (x : M) (y : N), φ x y) (h : ∀ x y x' y', cM x x' → cN y y' → f x y == f x' y') : con.hrec_on₂ ↑a ↑b f h = f a b := rfl variables {c} /-- The inductive principle used to prove propositions about the elements of a quotient by a congruence relation. -/ @[elab_as_eliminator, to_additive "The inductive principle used to prove propositions about the elements of a quotient by an additive congruence relation."] protected lemma induction_on {C : c.quotient → Prop} (q : c.quotient) (H : ∀ x : M, C x) : C q := quotient.induction_on' q H /-- A version of `con.induction_on` for predicates which take two arguments. -/ @[elab_as_eliminator, to_additive "A version of `add_con.induction_on` for predicates which take two arguments."] protected lemma induction_on₂ {d : con N} {C : c.quotient → d.quotient → Prop} (p : c.quotient) (q : d.quotient) (H : ∀ (x : M) (y : N), C x y) : C p q := quotient.induction_on₂' p q H variables (c) /-- Two elements are related by a congruence relation `c` iff they are represented by the same element of the quotient by `c`. -/ @[simp, to_additive "Two elements are related by an additive congruence relation `c` iff they are represented by the same element of the quotient by `c`."] protected lemma eq {a b : M} : (a : c.quotient) = b ↔ c a b := quotient.eq' /-- The multiplication induced on the quotient by a congruence relation on a type with a multiplication. -/ @[to_additive "The addition induced on the quotient by an additive congruence relation on a type with an addition."] instance has_mul : has_mul c.quotient := ⟨quotient.map₂' (*) $ λ _ _ h1 _ _ h2, c.mul h1 h2⟩ /-- The kernel of the quotient map induced by a congruence relation `c` equals `c`. -/ @[simp, to_additive "The kernel of the quotient map induced by an additive congruence relation `c` equals `c`."] lemma mul_ker_mk_eq : mul_ker (coe : M → c.quotient) (λ x y, rfl) = c := ext $ λ x y, quotient.eq' variables {c} /-- The coercion to the quotient of a congruence relation commutes with multiplication (by definition). -/ @[simp, to_additive "The coercion to the quotient of an additive congruence relation commutes with addition (by definition)."] lemma coe_mul (x y : M) : (↑(x * y) : c.quotient) = ↑x * ↑y := rfl /-- Definition of the function on the quotient by a congruence relation `c` induced by a function that is constant on `c`'s equivalence classes. -/ @[simp, to_additive "Definition of the function on the quotient by an additive congruence relation `c` induced by a function that is constant on `c`'s equivalence classes."] protected lemma lift_on_coe {β} (c : con M) (f : M → β) (h : ∀ a b, c a b → f a = f b) (x : M) : con.lift_on (x : c.quotient) f h = f x := rfl /-- Makes an isomorphism of quotients by two congruence relations, given that the relations are equal. -/ @[to_additive "Makes an additive isomorphism of quotients by two additive congruence relations, given that the relations are equal."] protected def congr {c d : con M} (h : c = d) : c.quotient ≃* d.quotient := { map_mul' := λ x y, by rcases x; rcases y; refl, ..quotient.congr (equiv.refl M) $ by apply ext_iff.2 h } -- The complete lattice of congruence relations on a type /-- For congruence relations `c, d` on a type `M` with a multiplication, `c ≤ d` iff `∀ x y ∈ M`, `x` is related to `y` by `d` if `x` is related to `y` by `c`. -/ @[to_additive "For additive congruence relations `c, d` on a type `M` with an addition, `c ≤ d` iff `∀ x y ∈ M`, `x` is related to `y` by `d` if `x` is related to `y` by `c`."] instance : has_le (con M) := ⟨λ c d, ∀ ⦃x y⦄, c x y → d x y⟩ /-- Definition of `≤` for congruence relations. -/ @[to_additive "Definition of `≤` for additive congruence relations."] theorem le_def {c d : con M} : c ≤ d ↔ ∀ {x y}, c x y → d x y := iff.rfl /-- The infimum of a set of congruence relations on a given type with a multiplication. -/ @[to_additive "The infimum of a set of additive congruence relations on a given type with an addition."] instance : has_Inf (con M) := ⟨λ S, ⟨⟨λ x y, ∀ c : con M, c ∈ S → c x y, ⟨λ x c hc, c.refl x, λ _ _ h c hc, c.symm $ h c hc, λ _ _ _ h1 h2 c hc, c.trans (h1 c hc) $ h2 c hc⟩⟩, λ _ _ _ _ h1 h2 c hc, c.mul (h1 c hc) $ h2 c hc⟩⟩ /-- The infimum of a set of congruence relations is the same as the infimum of the set's image under the map to the underlying equivalence relation. -/ @[to_additive "The infimum of a set of additive congruence relations is the same as the infimum of the set's image under the map to the underlying equivalence relation."] lemma Inf_to_setoid (S : set (con M)) : (Inf S).to_setoid = Inf (to_setoid '' S) := setoid.ext' $ λ x y, ⟨λ h r ⟨c, hS, hr⟩, by rw ←hr; exact h c hS, λ h c hS, h c.to_setoid ⟨c, hS, rfl⟩⟩ /-- The infimum of a set of congruence relations is the same as the infimum of the set's image under the map to the underlying binary relation. -/ @[to_additive "The infimum of a set of additive congruence relations is the same as the infimum of the set's image under the map to the underlying binary relation."] lemma Inf_def (S : set (con M)) : ⇑(Inf S) = Inf (@set.image (con M) (M → M → Prop) coe_fn S) := by { ext, simp only [Inf_image, infi_apply, infi_Prop_eq], refl } @[to_additive] instance : partial_order (con M) := { le := (≤), lt := λ c d, c ≤ d ∧ ¬d ≤ c, le_refl := λ c _ _, id, le_trans := λ c1 c2 c3 h1 h2 x y h, h2 $ h1 h, lt_iff_le_not_le := λ _ _, iff.rfl, le_antisymm := λ c d hc hd, ext $ λ x y, ⟨λ h, hc h, λ h, hd h⟩ } /-- The complete lattice of congruence relations on a given type with a multiplication. -/ @[to_additive "The complete lattice of additive congruence relations on a given type with an addition."] instance : complete_lattice (con M) := { inf := λ c d, ⟨(c.to_setoid ⊓ d.to_setoid), λ _ _ _ _ h1 h2, ⟨c.mul h1.1 h2.1, d.mul h1.2 h2.2⟩⟩, inf_le_left := λ _ _ _ _ h, h.1, inf_le_right := λ _ _ _ _ h, h.2, le_inf := λ _ _ _ hb hc _ _ h, ⟨hb h, hc h⟩, top := { mul' := by tauto, ..setoid.complete_lattice.top}, le_top := λ _ _ _ h, trivial, bot := { mul' := λ _ _ _ _ h1 h2, h1 ▸ h2 ▸ rfl, ..setoid.complete_lattice.bot}, bot_le := λ c x y h, h ▸ c.refl x, .. complete_lattice_of_Inf (con M) $ assume s, ⟨λ r hr x y h, (h : ∀ r ∈ s, (r : con M) x y) r hr, λ r hr x y h r' hr', hr hr' h⟩ } /-- The infimum of two congruence relations equals the infimum of the underlying binary operations. -/ @[to_additive "The infimum of two additive congruence relations equals the infimum of the underlying binary operations."] lemma inf_def {c d : con M} : (c ⊓ d).r = c.r ⊓ d.r := rfl /-- Definition of the infimum of two congruence relations. -/ @[to_additive "Definition of the infimum of two additive congruence relations."] theorem inf_iff_and {c d : con M} {x y} : (c ⊓ d) x y ↔ c x y ∧ d x y := iff.rfl /-- The inductively defined smallest congruence relation containing a binary relation `r` equals the infimum of the set of congruence relations containing `r`. -/ @[to_additive add_con_gen_eq "The inductively defined smallest additive congruence relation containing a binary relation `r` equals the infimum of the set of additive congruence relations containing `r`."] theorem con_gen_eq (r : M → M → Prop) : con_gen r = Inf {s : con M | ∀ x y, r x y → s x y} := le_antisymm (λ x y H, con_gen.rel.rec_on H (λ _ _ h _ hs, hs _ _ h) (con.refl _) (λ _ _ _, con.symm _) (λ _ _ _ _ _, con.trans _) $ λ w x y z _ _ h1 h2 c hc, c.mul (h1 c hc) $ h2 c hc) (Inf_le (λ _ _, con_gen.rel.of _ _)) /-- The smallest congruence relation containing a binary relation `r` is contained in any congruence relation containing `r`. -/ @[to_additive add_con_gen_le "The smallest additive congruence relation containing a binary relation `r` is contained in any additive congruence relation containing `r`."] theorem con_gen_le {r : M → M → Prop} {c : con M} (h : ∀ x y, r x y → @setoid.r _ c.to_setoid x y) : con_gen r ≤ c := by rw con_gen_eq; exact Inf_le h /-- Given binary relations `r, s` with `r` contained in `s`, the smallest congruence relation containing `s` contains the smallest congruence relation containing `r`. -/ @[to_additive add_con_gen_mono "Given binary relations `r, s` with `r` contained in `s`, the smallest additive congruence relation containing `s` contains the smallest additive congruence relation containing `r`."] theorem con_gen_mono {r s : M → M → Prop} (h : ∀ x y, r x y → s x y) : con_gen r ≤ con_gen s := con_gen_le $ λ x y hr, con_gen.rel.of _ _ $ h x y hr /-- Congruence relations equal the smallest congruence relation in which they are contained. -/ @[simp, to_additive add_con_gen_of_add_con "Additive congruence relations equal the smallest additive congruence relation in which they are contained."] lemma con_gen_of_con (c : con M) : con_gen c = c := le_antisymm (by rw con_gen_eq; exact Inf_le (λ _ _, id)) con_gen.rel.of /-- The map sending a binary relation to the smallest congruence relation in which it is contained is idempotent. -/ @[simp, to_additive add_con_gen_idem "The map sending a binary relation to the smallest additive congruence relation in which it is contained is idempotent."] lemma con_gen_idem (r : M → M → Prop) : con_gen (con_gen r) = con_gen r := con_gen_of_con _ /-- The supremum of congruence relations `c, d` equals the smallest congruence relation containing the binary relation '`x` is related to `y` by `c` or `d`'. -/ @[to_additive sup_eq_add_con_gen "The supremum of additive congruence relations `c, d` equals the smallest additive congruence relation containing the binary relation '`x` is related to `y` by `c` or `d`'."] lemma sup_eq_con_gen (c d : con M) : c ⊔ d = con_gen (λ x y, c x y ∨ d x y) := begin rw con_gen_eq, apply congr_arg Inf, simp only [le_def, or_imp_distrib, ← forall_and_distrib] end /-- The supremum of two congruence relations equals the smallest congruence relation containing the supremum of the underlying binary operations. -/ @[to_additive "The supremum of two additive congruence relations equals the smallest additive congruence relation containing the supremum of the underlying binary operations."] lemma sup_def {c d : con M} : c ⊔ d = con_gen (c.r ⊔ d.r) := by rw sup_eq_con_gen; refl /-- The supremum of a set of congruence relations `S` equals the smallest congruence relation containing the binary relation 'there exists `c ∈ S` such that `x` is related to `y` by `c`'. -/ @[to_additive Sup_eq_add_con_gen "The supremum of a set of additive congruence relations `S` equals the smallest additive congruence relation containing the binary relation 'there exists `c ∈ S` such that `x` is related to `y` by `c`'."] lemma Sup_eq_con_gen (S : set (con M)) : Sup S = con_gen (λ x y, ∃ c : con M, c ∈ S ∧ c x y) := begin rw con_gen_eq, apply congr_arg Inf, ext, exact ⟨λ h _ _ ⟨r, hr⟩, h hr.1 hr.2, λ h r hS _ _ hr, h _ _ ⟨r, hS, hr⟩⟩, end /-- The supremum of a set of congruence relations is the same as the smallest congruence relation containing the supremum of the set's image under the map to the underlying binary relation. -/ @[to_additive "The supremum of a set of additive congruence relations is the same as the smallest additive congruence relation containing the supremum of the set's image under the map to the underlying binary relation."] lemma Sup_def {S : set (con M)} : Sup S = con_gen (Sup (@set.image (con M) (M → M → Prop) coe_fn S)) := begin rw [Sup_eq_con_gen, Sup_image], congr' with x y, simp only [Sup_image, supr_apply, supr_Prop_eq, exists_prop, rel_eq_coe] end variables (M) /-- There is a Galois insertion of congruence relations on a type with a multiplication `M` into binary relations on `M`. -/ @[to_additive "There is a Galois insertion of additive congruence relations on a type with an addition `M` into binary relations on `M`."] protected def gi : @galois_insertion (M → M → Prop) (con M) _ _ con_gen coe_fn := { choice := λ r h, con_gen r, gc := λ r c, ⟨λ H _ _ h, H $ con_gen.rel.of _ _ h, λ H, con_gen_of_con c ▸ con_gen_mono H⟩, le_l_u := λ x, (con_gen_of_con x).symm ▸ le_refl x, choice_eq := λ _ _, rfl } variables {M} (c) /-- Given a function `f`, the smallest congruence relation containing the binary relation on `f`'s image defined by '`x ≈ y` iff the elements of `f⁻¹(x)` are related to the elements of `f⁻¹(y)` by a congruence relation `c`.' -/ @[to_additive "Given a function `f`, the smallest additive congruence relation containing the binary relation on `f`'s image defined by '`x ≈ y` iff the elements of `f⁻¹(x)` are related to the elements of `f⁻¹(y)` by an additive congruence relation `c`.'"] def map_gen (f : M → N) : con N := con_gen $ λ x y, ∃ a b, f a = x ∧ f b = y ∧ c a b /-- Given a surjective multiplicative-preserving function `f` whose kernel is contained in a congruence relation `c`, the congruence relation on `f`'s codomain defined by '`x ≈ y` iff the elements of `f⁻¹(x)` are related to the elements of `f⁻¹(y)` by `c`.' -/ @[to_additive "Given a surjective addition-preserving function `f` whose kernel is contained in an additive congruence relation `c`, the additive congruence relation on `f`'s codomain defined by '`x ≈ y` iff the elements of `f⁻¹(x)` are related to the elements of `f⁻¹(y)` by `c`.'"] def map_of_surjective (f : M → N) (H : ∀ x y, f (x * y) = f x * f y) (h : mul_ker f H ≤ c) (hf : surjective f) : con N := { mul' := λ w x y z ⟨a, b, hw, hx, h1⟩ ⟨p, q, hy, hz, h2⟩, ⟨a * p, b * q, by rw [H, hw, hy], by rw [H, hx, hz], c.mul h1 h2⟩, ..c.to_setoid.map_of_surjective f h hf } /-- A specialization of 'the smallest congruence relation containing a congruence relation `c` equals `c`'. -/ @[to_additive "A specialization of 'the smallest additive congruence relation containing an additive congruence relation `c` equals `c`'."] lemma map_of_surjective_eq_map_gen {c : con M} {f : M → N} (H : ∀ x y, f (x * y) = f x * f y) (h : mul_ker f H ≤ c) (hf : surjective f) : c.map_gen f = c.map_of_surjective f H h hf := by rw ←con_gen_of_con (c.map_of_surjective f H h hf); refl /-- Given types with multiplications `M, N` and a congruence relation `c` on `N`, a multiplication-preserving map `f : M → N` induces a congruence relation on `f`'s domain defined by '`x ≈ y` iff `f(x)` is related to `f(y)` by `c`.' -/ @[to_additive "Given types with additions `M, N` and an additive congruence relation `c` on `N`, an addition-preserving map `f : M → N` induces an additive congruence relation on `f`'s domain defined by '`x ≈ y` iff `f(x)` is related to `f(y)` by `c`.' "] def comap (f : M → N) (H : ∀ x y, f (x * y) = f x * f y) (c : con N) : con M := { mul' := λ w x y z h1 h2, show c (f (w * y)) (f (x * z)), by rw [H, H]; exact c.mul h1 h2, ..c.to_setoid.comap f } @[simp, to_additive] lemma comap_rel {f : M → N} (H : ∀ x y, f (x * y) = f x * f y) {c : con N} {x y : M} : comap f H c x y ↔ c (f x) (f y) := iff.rfl section open _root_.quotient /-- Given a congruence relation `c` on a type `M` with a multiplication, the order-preserving bijection between the set of congruence relations containing `c` and the congruence relations on the quotient of `M` by `c`. -/ @[to_additive "Given an additive congruence relation `c` on a type `M` with an addition, the order-preserving bijection between the set of additive congruence relations containing `c` and the additive congruence relations on the quotient of `M` by `c`."] def correspondence : {d // c ≤ d} ≃o (con c.quotient) := { to_fun := λ d, d.1.map_of_surjective coe _ (by rw mul_ker_mk_eq; exact d.2) $ @exists_rep _ c.to_setoid, inv_fun := λ d, ⟨comap (coe : M → c.quotient) (λ x y, rfl) d, λ _ _ h, show d _ _, by rw c.eq.2 h; exact d.refl _ ⟩, left_inv := λ d, subtype.ext_iff_val.2 $ ext $ λ _ _, ⟨λ h, let ⟨a, b, hx, hy, H⟩ := h in d.1.trans (d.1.symm $ d.2 $ c.eq.1 hx) $ d.1.trans H $ d.2 $ c.eq.1 hy, λ h, ⟨_, _, rfl, rfl, h⟩⟩, right_inv := λ d, let Hm : mul_ker (coe : M → c.quotient) (λ x y, rfl) ≤ comap (coe : M → c.quotient) (λ x y, rfl) d := λ x y h, show d _ _, by rw mul_ker_mk_eq at h; exact c.eq.2 h ▸ d.refl _ in ext $ λ x y, ⟨λ h, let ⟨a, b, hx, hy, H⟩ := h in hx ▸ hy ▸ H, con.induction_on₂ x y $ λ w z h, ⟨w, z, rfl, rfl, h⟩⟩, map_rel_iff' := λ s t, ⟨λ h _ _ hs, let ⟨a, b, hx, hy, ht⟩ := h ⟨_, _, rfl, rfl, hs⟩ in t.1.trans (t.1.symm $ t.2 $ eq_rel.1 hx) $ t.1.trans ht $ t.2 $ eq_rel.1 hy, λ h _ _ hs, let ⟨a, b, hx, hy, Hs⟩ := hs in ⟨a, b, hx, hy, h Hs⟩⟩ } end end section mul_one_class variables {M} [mul_one_class M] [mul_one_class N] [mul_one_class P] (c : con M) /-- The quotient of a monoid by a congruence relation is a monoid. -/ @[to_additive "The quotient of an `add_monoid` by an additive congruence relation is an `add_monoid`."] instance mul_one_class : mul_one_class c.quotient := { one := ((1 : M) : c.quotient), mul := (*), mul_one := λ x, quotient.induction_on' x $ λ _, congr_arg (coe : M → c.quotient) $ mul_one _, one_mul := λ x, quotient.induction_on' x $ λ _, congr_arg (coe : M → c.quotient) $ one_mul _ } variables {c} /-- The 1 of the quotient of a monoid by a congruence relation is the equivalence class of the monoid's 1. -/ @[simp, to_additive "The 0 of the quotient of an `add_monoid` by an additive congruence relation is the equivalence class of the `add_monoid`'s 0."] lemma coe_one : ((1 : M) : c.quotient) = 1 := rfl variables (M c) /-- The submonoid of `M × M` defined by a congruence relation on a monoid `M`. -/ @[to_additive "The `add_submonoid` of `M × M` defined by an additive congruence relation on an `add_monoid` `M`."] protected def submonoid : submonoid (M × M) := { carrier := { x | c x.1 x.2 }, one_mem' := c.iseqv.1 1, mul_mem' := λ _ _, c.mul } variables {M c} /-- The congruence relation on a monoid `M` from a submonoid of `M × M` for which membership is an equivalence relation. -/ @[to_additive "The additive congruence relation on an `add_monoid` `M` from an `add_submonoid` of `M × M` for which membership is an equivalence relation."] def of_submonoid (N : submonoid (M × M)) (H : equivalence (λ x y, (x, y) ∈ N)) : con M := { r := λ x y, (x, y) ∈ N, iseqv := H, mul' := λ _ _ _ _, N.mul_mem } /-- Coercion from a congruence relation `c` on a monoid `M` to the submonoid of `M × M` whose elements are `(x, y)` such that `x` is related to `y` by `c`. -/ @[to_additive "Coercion from a congruence relation `c` on an `add_monoid` `M` to the `add_submonoid` of `M × M` whose elements are `(x, y)` such that `x` is related to `y` by `c`."] instance to_submonoid : has_coe (con M) (submonoid (M × M)) := ⟨λ c, c.submonoid M⟩ @[to_additive] lemma mem_coe {c : con M} {x y} : (x, y) ∈ (↑c : submonoid (M × M)) ↔ (x, y) ∈ c := iff.rfl @[to_additive] theorem to_submonoid_inj (c d : con M) (H : (c : submonoid (M × M)) = d) : c = d := ext $ λ x y, show (x, y) ∈ (c : submonoid (M × M)) ↔ (x, y) ∈ ↑d, by rw H @[to_additive] lemma le_iff {c d : con M} : c ≤ d ↔ (c : submonoid (M × M)) ≤ d := ⟨λ h x H, h H, λ h x y hc, h $ show (x, y) ∈ c, from hc⟩ /-- The kernel of a monoid homomorphism as a congruence relation. -/ @[to_additive "The kernel of an `add_monoid` homomorphism as an additive congruence relation."] def ker (f : M →* P) : con M := mul_ker f f.3 /-- The definition of the congruence relation defined by a monoid homomorphism's kernel. -/ @[simp, to_additive "The definition of the additive congruence relation defined by an `add_monoid` homomorphism's kernel."] lemma ker_rel (f : M →* P) {x y} : ker f x y ↔ f x = f y := iff.rfl /-- There exists an element of the quotient of a monoid by a congruence relation (namely 1). -/ @[to_additive "There exists an element of the quotient of an `add_monoid` by a congruence relation (namely 0)."] instance quotient.inhabited : inhabited c.quotient := ⟨((1 : M) : c.quotient)⟩ variables (c) /-- The natural homomorphism from a monoid to its quotient by a congruence relation. -/ @[to_additive "The natural homomorphism from an `add_monoid` to its quotient by an additive congruence relation."] def mk' : M →* c.quotient := ⟨coe, rfl, λ _ _, rfl⟩ variables (x y : M) /-- The kernel of the natural homomorphism from a monoid to its quotient by a congruence relation `c` equals `c`. -/ @[simp, to_additive "The kernel of the natural homomorphism from an `add_monoid` to its quotient by an additive congruence relation `c` equals `c`."] lemma mk'_ker : ker c.mk' = c := ext $ λ _ _, c.eq variables {c} /-- The natural homomorphism from a monoid to its quotient by a congruence relation is surjective. -/ @[to_additive "The natural homomorphism from an `add_monoid` to its quotient by a congruence relation is surjective."] lemma mk'_surjective : surjective c.mk' := quotient.surjective_quotient_mk' @[simp, to_additive] lemma coe_mk' : (c.mk' : M → c.quotient) = coe := rfl @[simp, to_additive] lemma mrange_mk' : c.mk'.mrange = ⊤ := monoid_hom.mrange_top_iff_surjective.2 mk'_surjective /-- The elements related to `x ∈ M`, `M` a monoid, by the kernel of a monoid homomorphism are those in the preimage of `f(x)` under `f`. -/ @[to_additive "The elements related to `x ∈ M`, `M` an `add_monoid`, by the kernel of an `add_monoid` homomorphism are those in the preimage of `f(x)` under `f`. "] lemma ker_apply_eq_preimage {f : M →* P} (x) : (ker f) x = f ⁻¹' {f x} := set.ext $ λ x, ⟨λ h, set.mem_preimage.2 $ set.mem_singleton_iff.2 h.symm, λ h, (set.mem_singleton_iff.1 $ set.mem_preimage.1 h).symm⟩ /-- Given a monoid homomorphism `f : N → M` and a congruence relation `c` on `M`, the congruence relation induced on `N` by `f` equals the kernel of `c`'s quotient homomorphism composed with `f`. -/ @[to_additive "Given an `add_monoid` homomorphism `f : N → M` and an additive congruence relation `c` on `M`, the additive congruence relation induced on `N` by `f` equals the kernel of `c`'s quotient homomorphism composed with `f`."] lemma comap_eq {f : N →* M} : comap f f.map_mul c = ker (c.mk'.comp f) := ext $ λ x y, show c _ _ ↔ c.mk' _ = c.mk' _, by rw ←c.eq; refl variables (c) (f : M →* P) /-- The homomorphism on the quotient of a monoid by a congruence relation `c` induced by a homomorphism constant on `c`'s equivalence classes. -/ @[to_additive "The homomorphism on the quotient of an `add_monoid` by an additive congruence relation `c` induced by a homomorphism constant on `c`'s equivalence classes."] def lift (H : c ≤ ker f) : c.quotient →* P := { to_fun := λ x, con.lift_on x f $ λ _ _ h, H h, map_one' := by rw ←f.map_one; refl, map_mul' := λ x y, con.induction_on₂ x y $ λ m n, f.map_mul m n ▸ rfl } variables {c f} /-- The diagram describing the universal property for quotients of monoids commutes. -/ @[to_additive "The diagram describing the universal property for quotients of `add_monoid`s commutes."] lemma lift_mk' (H : c ≤ ker f) (x) : c.lift f H (c.mk' x) = f x := rfl /-- The diagram describing the universal property for quotients of monoids commutes. -/ @[simp, to_additive "The diagram describing the universal property for quotients of `add_monoid`s commutes."] lemma lift_coe (H : c ≤ ker f) (x : M) : c.lift f H x = f x := rfl /-- The diagram describing the universal property for quotients of monoids commutes. -/ @[simp, to_additive "The diagram describing the universal property for quotients of `add_monoid`s commutes."] theorem lift_comp_mk' (H : c ≤ ker f) : (c.lift f H).comp c.mk' = f := by ext; refl /-- Given a homomorphism `f` from the quotient of a monoid by a congruence relation, `f` equals the homomorphism on the quotient induced by `f` composed with the natural map from the monoid to the quotient. -/ @[simp, to_additive "Given a homomorphism `f` from the quotient of an `add_monoid` by an additive congruence relation, `f` equals the homomorphism on the quotient induced by `f` composed with the natural map from the `add_monoid` to the quotient."] lemma lift_apply_mk' (f : c.quotient →* P) : c.lift (f.comp c.mk') (λ x y h, show f ↑x = f ↑y, by rw c.eq.2 h) = f := by ext; rcases x; refl /-- Homomorphisms on the quotient of a monoid by a congruence relation are equal if they are equal on elements that are coercions from the monoid. -/ @[to_additive "Homomorphisms on the quotient of an `add_monoid` by an additive congruence relation are equal if they are equal on elements that are coercions from the `add_monoid`."] lemma lift_funext (f g : c.quotient →* P) (h : ∀ a : M, f a = g a) : f = g := begin rw [←lift_apply_mk' f, ←lift_apply_mk' g], congr' 1, exact monoid_hom.ext_iff.2 h, end /-- The uniqueness part of the universal property for quotients of monoids. -/ @[to_additive "The uniqueness part of the universal property for quotients of `add_monoid`s."] theorem lift_unique (H : c ≤ ker f) (g : c.quotient →* P) (Hg : g.comp c.mk' = f) : g = c.lift f H := lift_funext g (c.lift f H) $ λ x, by { subst f, refl } /-- Given a congruence relation `c` on a monoid and a homomorphism `f` constant on `c`'s equivalence classes, `f` has the same image as the homomorphism that `f` induces on the quotient. -/ @[to_additive "Given an additive congruence relation `c` on an `add_monoid` and a homomorphism `f` constant on `c`'s equivalence classes, `f` has the same image as the homomorphism that `f` induces on the quotient."] theorem lift_range (H : c ≤ ker f) : (c.lift f H).mrange = f.mrange := submonoid.ext $ λ x, ⟨by rintros ⟨⟨y⟩, hy⟩; exact ⟨y, hy⟩, λ ⟨y, hy⟩, ⟨↑y, hy⟩⟩ /-- Surjective monoid homomorphisms constant on a congruence relation `c`'s equivalence classes induce a surjective homomorphism on `c`'s quotient. -/ @[to_additive "Surjective `add_monoid` homomorphisms constant on an additive congruence relation `c`'s equivalence classes induce a surjective homomorphism on `c`'s quotient."] lemma lift_surjective_of_surjective (h : c ≤ ker f) (hf : surjective f) : surjective (c.lift f h) := λ y, exists.elim (hf y) $ λ w hw, ⟨w, (lift_mk' h w).symm ▸ hw⟩ variables (c f) /-- Given a monoid homomorphism `f` from `M` to `P`, the kernel of `f` is the unique congruence relation on `M` whose induced map from the quotient of `M` to `P` is injective. -/ @[to_additive "Given an `add_monoid` homomorphism `f` from `M` to `P`, the kernel of `f` is the unique additive congruence relation on `M` whose induced map from the quotient of `M` to `P` is injective."] lemma ker_eq_lift_of_injective (H : c ≤ ker f) (h : injective (c.lift f H)) : ker f = c := to_setoid_inj $ ker_eq_lift_of_injective f H h variables {c} /-- The homomorphism induced on the quotient of a monoid by the kernel of a monoid homomorphism. -/ @[to_additive "The homomorphism induced on the quotient of an `add_monoid` by the kernel of an `add_monoid` homomorphism."] def ker_lift : (ker f).quotient →* P := (ker f).lift f $ λ _ _, id variables {f} /-- The diagram described by the universal property for quotients of monoids, when the congruence relation is the kernel of the homomorphism, commutes. -/ @[simp, to_additive "The diagram described by the universal property for quotients of `add_monoid`s, when the additive congruence relation is the kernel of the homomorphism, commutes."] lemma ker_lift_mk (x : M) : ker_lift f x = f x := rfl /-- Given a monoid homomorphism `f`, the induced homomorphism on the quotient by `f`'s kernel has the same image as `f`. -/ @[simp, to_additive "Given an `add_monoid` homomorphism `f`, the induced homomorphism on the quotient by `f`'s kernel has the same image as `f`."] lemma ker_lift_range_eq : (ker_lift f).mrange = f.mrange := lift_range $ λ _ _, id /-- A monoid homomorphism `f` induces an injective homomorphism on the quotient by `f`'s kernel. -/ @[to_additive "An `add_monoid` homomorphism `f` induces an injective homomorphism on the quotient by `f`'s kernel."] lemma ker_lift_injective (f : M →* P) : injective (ker_lift f) := λ x y, quotient.induction_on₂' x y $ λ _ _, (ker f).eq.2 /-- Given congruence relations `c, d` on a monoid such that `d` contains `c`, `d`'s quotient map induces a homomorphism from the quotient by `c` to the quotient by `d`. -/ @[to_additive "Given additive congruence relations `c, d` on an `add_monoid` such that `d` contains `c`, `d`'s quotient map induces a homomorphism from the quotient by `c` to the quotient by `d`."] def map (c d : con M) (h : c ≤ d) : c.quotient →* d.quotient := c.lift d.mk' $ λ x y hc, show (ker d.mk') x y, from (mk'_ker d).symm ▸ h hc /-- Given congruence relations `c, d` on a monoid such that `d` contains `c`, the definition of the homomorphism from the quotient by `c` to the quotient by `d` induced by `d`'s quotient map. -/ @[to_additive "Given additive congruence relations `c, d` on an `add_monoid` such that `d` contains `c`, the definition of the homomorphism from the quotient by `c` to the quotient by `d` induced by `d`'s quotient map."] lemma map_apply {c d : con M} (h : c ≤ d) (x) : c.map d h x = c.lift d.mk' (λ x y hc, d.eq.2 $ h hc) x := rfl variables (c) /-- The first isomorphism theorem for monoids. -/ @[to_additive "The first isomorphism theorem for `add_monoid`s."] noncomputable def quotient_ker_equiv_range (f : M →* P) : (ker f).quotient ≃* f.mrange := { map_mul' := monoid_hom.map_mul _, ..equiv.of_bijective ((@mul_equiv.to_monoid_hom (ker_lift f).mrange _ _ _ $ mul_equiv.submonoid_congr ker_lift_range_eq).comp (ker_lift f).mrange_restrict) $ (equiv.bijective _).comp ⟨λ x y h, ker_lift_injective f $ by rcases x; rcases y; injections, λ ⟨w, z, hz⟩, ⟨z, by rcases hz; rcases _x; refl⟩⟩ } /-- The first isomorphism theorem for monoids in the case of a homomorphism with right inverse. -/ @[to_additive "The first isomorphism theorem for `add_monoid`s in the case of a homomorphism with right inverse.", simps] def quotient_ker_equiv_of_right_inverse (f : M →* P) (g : P → M) (hf : function.right_inverse g f) : (ker f).quotient ≃* P := { to_fun := ker_lift f, inv_fun := coe ∘ g, left_inv := λ x, ker_lift_injective _ (by rw [function.comp_app, ker_lift_mk, hf]), right_inv := hf, .. ker_lift f } /-- The first isomorphism theorem for monoids in the case of a surjective homomorphism. For a `computable` version, see `con.quotient_ker_equiv_of_right_inverse`. -/ @[to_additive "The first isomorphism theorem for `add_monoid`s in the case of a surjective homomorphism. For a `computable` version, see `add_con.quotient_ker_equiv_of_right_inverse`. "] noncomputable def quotient_ker_equiv_of_surjective (f : M →* P) (hf : surjective f) : (ker f).quotient ≃* P := quotient_ker_equiv_of_right_inverse _ _ hf.has_right_inverse.some_spec /-- The second isomorphism theorem for monoids. -/ @[to_additive "The second isomorphism theorem for `add_monoid`s."] noncomputable def comap_quotient_equiv (f : N →* M) : (comap f f.map_mul c).quotient ≃* (c.mk'.comp f).mrange := (con.congr comap_eq).trans $ quotient_ker_equiv_range $ c.mk'.comp f /-- The third isomorphism theorem for monoids. -/ @[to_additive "The third isomorphism theorem for `add_monoid`s."] def quotient_quotient_equiv_quotient (c d : con M) (h : c ≤ d) : (ker (c.map d h)).quotient ≃* d.quotient := { map_mul' := λ x y, con.induction_on₂ x y $ λ w z, con.induction_on₂ w z $ λ a b, show _ = d.mk' a * d.mk' b, by rw ←d.mk'.map_mul; refl, ..quotient_quotient_equiv_quotient c.to_setoid d.to_setoid h } end mul_one_class section monoids /-- Multiplicative congruence relations preserve natural powers. -/ @[to_additive add_con.nsmul "Additive congruence relations preserve natural scaling."] protected lemma pow {M : Type*} [monoid M] (c : con M) : ∀ (n : ℕ) {w x}, c w x → c (w ^ n) (x ^ n) | 0 w x h := by simpa using c.refl _ | (nat.succ n) w x h := by simpa [pow_succ] using c.mul h (pow n h) @[to_additive] instance {M : Type*} [mul_one_class M] (c : con M) : has_one c.quotient := { one := ((1 : M) : c.quotient) } @[to_additive] lemma smul {α M : Type*} [mul_one_class M] [has_smul α M] [is_scalar_tower α M M] (c : con M) (a : α) {w x : M} (h : c w x) : c (a • w) (a • x) := by simpa only [smul_one_mul] using c.mul (c.refl' (a • 1 : M)) h instance _root_.add_con.quotient.has_nsmul {M : Type*} [add_monoid M] (c : add_con M) : has_smul ℕ c.quotient := { smul := λ n, quotient.map' ((•) n) $ λ x y, c.nsmul n } @[to_additive add_con.quotient.has_nsmul] instance {M : Type*} [monoid M] (c : con M) : has_pow c.quotient ℕ := { pow := λ x n, quotient.map' (λ x, x ^ n) (λ x y, c.pow n) x } /-- The quotient of a semigroup by a congruence relation is a semigroup. -/ @[to_additive "The quotient of an `add_semigroup` by an additive congruence relation is an `add_semigroup`."] instance semigroup {M : Type*} [semigroup M] (c : con M) : semigroup c.quotient := function.surjective.semigroup _ quotient.surjective_quotient_mk' (λ _ _, rfl) /-- The quotient of a commutative semigroup by a congruence relation is a semigroup. -/ @[to_additive "The quotient of an `add_comm_semigroup` by an additive congruence relation is an `add_semigroup`."] instance comm_semigroup {M : Type*} [comm_semigroup M] (c : con M) : comm_semigroup c.quotient := function.surjective.comm_semigroup _ quotient.surjective_quotient_mk' (λ _ _, rfl) /-- The quotient of a monoid by a congruence relation is a monoid. -/ @[to_additive "The quotient of an `add_monoid` by an additive congruence relation is an `add_monoid`."] instance monoid {M : Type*} [monoid M] (c : con M) : monoid c.quotient := function.surjective.monoid _ quotient.surjective_quotient_mk' rfl (λ _ _, rfl) (λ _ _, rfl) /-- The quotient of a `comm_monoid` by a congruence relation is a `comm_monoid`. -/ @[to_additive "The quotient of an `add_comm_monoid` by an additive congruence relation is an `add_comm_monoid`."] instance comm_monoid {M : Type*} [comm_monoid M] (c : con M) : comm_monoid c.quotient := function.surjective.comm_monoid _ quotient.surjective_quotient_mk' rfl (λ _ _, rfl) (λ _ _, rfl) end monoids section groups variables {M} [group M] [group N] [group P] (c : con M) /-- Multiplicative congruence relations preserve inversion. -/ @[to_additive "Additive congruence relations preserve negation."] protected lemma inv : ∀ {w x}, c w x → c w⁻¹ x⁻¹ := λ x y h, by simpa using c.symm (c.mul (c.mul (c.refl x⁻¹) h) (c.refl y⁻¹)) /-- Multiplicative congruence relations preserve division. -/ @[to_additive "Additive congruence relations preserve subtraction."] protected lemma div : ∀ {w x y z}, c w x → c y z → c (w / y) (x / z) := λ w x y z h1 h2, by simpa only [div_eq_mul_inv] using c.mul h1 (c.inv h2) /-- Multiplicative congruence relations preserve integer powers. -/ @[to_additive add_con.zsmul "Additive congruence relations preserve integer scaling."] protected lemma zpow : ∀ (n : ℤ) {w x}, c w x → c (w ^ n) (x ^ n) | (int.of_nat n) w x h := by simpa only [zpow_of_nat] using c.pow _ h | -[1+ n] w x h := by simpa only [zpow_neg_succ_of_nat] using c.inv (c.pow _ h) /-- The inversion induced on the quotient by a congruence relation on a type with a inversion. -/ @[to_additive "The negation induced on the quotient by an additive congruence relation on a type with an negation."] instance has_inv : has_inv c.quotient := ⟨quotient.map' has_inv.inv $ λ a b, c.inv⟩ /-- The division induced on the quotient by a congruence relation on a type with a division. -/ @[to_additive "The subtraction induced on the quotient by an additive congruence relation on a type with a subtraction."] instance has_div : has_div c.quotient := ⟨quotient.map₂' (/) $ λ _ _ h₁ _ _ h₂, c.div h₁ h₂⟩ /-- The integer scaling induced on the quotient by a congruence relation on a type with a subtraction. -/ instance _root_.add_con.quotient.has_zsmul {M : Type*} [add_group M] (c : add_con M) : has_smul ℤ c.quotient := ⟨λ z, quotient.map' ((•) z) $ λ x y, c.zsmul z⟩ /-- The integer power induced on the quotient by a congruence relation on a type with a division. -/ @[to_additive add_con.quotient.has_zsmul] instance has_zpow : has_pow c.quotient ℤ := ⟨λ x z, quotient.map' (λ x, x ^ z) (λ x y h, c.zpow z h) x⟩ /-- The quotient of a group by a congruence relation is a group. -/ @[to_additive "The quotient of an `add_group` by an additive congruence relation is an `add_group`."] instance group : group c.quotient := function.surjective.group _ quotient.surjective_quotient_mk' rfl (λ _ _, rfl) (λ _, rfl) (λ _ _, rfl) (λ _ _, rfl) (λ _ _, rfl) end groups section units variables {α : Type*} [monoid M] {c : con M} /-- In order to define a function `(con.quotient c)ˣ → α` on the units of `con.quotient c`, where `c : con M` is a multiplicative congruence on a monoid, it suffices to define a function `f` that takes elements `x y : M` with proofs of `c (x * y) 1` and `c (y * x) 1`, and returns an element of `α` provided that `f x y _ _ = f x' y' _ _` whenever `c x x'` and `c y y'`. -/ @[to_additive] def lift_on_units (u : units c.quotient) (f : Π (x y : M), c (x * y) 1 → c (y * x) 1 → α) (Hf : ∀ x y hxy hyx x' y' hxy' hyx', c x x' → c y y' → f x y hxy hyx = f x' y' hxy' hyx') : α := begin refine @con.hrec_on₂ M M _ _ c c (λ x y, x * y = 1 → y * x = 1 → α) (u : c.quotient) (↑u⁻¹ : c.quotient) (λ (x y : M) (hxy : (x * y : c.quotient) = 1) (hyx : (y * x : c.quotient) = 1), f x y (c.eq.1 hxy) (c.eq.1 hyx)) (λ x y x' y' hx hy, _) u.3 u.4, ext1, { rw [c.eq.2 hx, c.eq.2 hy] }, rintro Hxy Hxy' -, ext1, { rw [c.eq.2 hx, c.eq.2 hy] }, rintro Hyx Hyx' -, exact heq_of_eq (Hf _ _ _ _ _ _ _ _ hx hy) end /-- In order to define a function `(con.quotient c)ˣ → α` on the units of `con.quotient c`, where `c : con M` is a multiplicative congruence on a monoid, it suffices to define a function `f` that takes elements `x y : M` with proofs of `c (x * y) 1` and `c (y * x) 1`, and returns an element of `α` provided that `f x y _ _ = f x' y' _ _` whenever `c x x'` and `c y y'`. -/ add_decl_doc add_con.lift_on_add_units @[simp, to_additive] lemma lift_on_units_mk (f : Π (x y : M), c (x * y) 1 → c (y * x) 1 → α) (Hf : ∀ x y hxy hyx x' y' hxy' hyx', c x x' → c y y' → f x y hxy hyx = f x' y' hxy' hyx') (x y : M) (hxy hyx) : lift_on_units ⟨(x : c.quotient), y, hxy, hyx⟩ f Hf = f x y (c.eq.1 hxy) (c.eq.1 hyx) := rfl @[elab_as_eliminator, to_additive] lemma induction_on_units {p : units c.quotient → Prop} (u : units c.quotient) (H : ∀ (x y : M) (hxy : c (x * y) 1) (hyx : c (y * x) 1), p ⟨x, y, c.eq.2 hxy, c.eq.2 hyx⟩) : p u := begin rcases u with ⟨⟨x⟩, ⟨y⟩, h₁, h₂⟩, exact H x y (c.eq.1 h₁) (c.eq.1 h₂) end end units section actions @[to_additive] instance has_smul {α M : Type*} [mul_one_class M] [has_smul α M] [is_scalar_tower α M M] (c : con M) : has_smul α c.quotient := { smul := λ a, quotient.map' ((•) a) $ λ x y, c.smul a } @[to_additive] lemma coe_smul {α M : Type*} [mul_one_class M] [has_smul α M] [is_scalar_tower α M M] (c : con M) (a : α) (x : M) : (↑(a • x) : c.quotient) = a • ↑x := rfl @[to_additive] instance mul_action {α M : Type*} [monoid α] [mul_one_class M] [mul_action α M] [is_scalar_tower α M M] (c : con M) : mul_action α c.quotient := { smul := (•), one_smul := quotient.ind' $ by exact λ x, congr_arg quotient.mk' $ one_smul _ _, mul_smul := λ a₁ a₂, quotient.ind' $ by exact λ x, congr_arg quotient.mk' $ mul_smul _ _ _ } instance mul_distrib_mul_action {α M : Type*} [monoid α] [monoid M] [mul_distrib_mul_action α M] [is_scalar_tower α M M] (c : con M) : mul_distrib_mul_action α c.quotient := { smul := (•), smul_one := λ r, congr_arg quotient.mk' $ smul_one _, smul_mul := λ r, quotient.ind₂' $ by exact λ m₁ m₂, congr_arg quotient.mk' $ smul_mul' _ _ _, .. c.mul_action } end actions end con
319413b5fd56b6c2852b2b2c4b514852219cb7b7
9028d228ac200bbefe3a711342514dd4e4458bff
/src/data/nat/multiplicity.lean
826c15136d5ee0d7a2a2165cefa705ed09a49048
[ "Apache-2.0" ]
permissive
mcncm/mathlib
8d25099344d9d2bee62822cb9ed43aa3e09fa05e
fde3d78cadeec5ef827b16ae55664ef115e66f57
refs/heads/master
1,672,743,316,277
1,602,618,514,000
1,602,618,514,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
9,464
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.choose.dvd import ring_theory.multiplicity import data.nat.modeq import algebra.gcd_monoid import data.finset.intervals /-! # Natural number multiplicity This file contains lemmas about the multiplicity function (the maximum prime power divding a number). # Main results There are natural number versions of some basic lemmas about multiplicity. There are also lemmas about the multiplicity of primes in factorials and in binomial coefficients. -/ open finset nat multiplicity open_locale big_operators nat namespace nat /-- The multiplicity of a divisor `m` of `n`, is the cardinality of the set of positive natural numbers `i` such that `p ^ i` divides `n`. The set is expressed by filtering `Ico 1 b` where `b` is any bound at least `n` -/ lemma multiplicity_eq_card_pow_dvd {m n b : ℕ} (hm1 : m ≠ 1) (hn0 : 0 < n) (hb : n ≤ b): multiplicity m n = ↑((finset.Ico 1 b).filter (λ i, m ^ i ∣ n)).card := calc multiplicity m n = ↑(Ico 1 $ ((multiplicity m n).get (finite_nat_iff.2 ⟨hm1, hn0⟩) + 1)).card : by simp ... = ↑((finset.Ico 1 b).filter (λ i, m ^ i ∣ n)).card : congr_arg coe $ congr_arg card $ finset.ext $ λ i, have hmn : ¬ m ^ n ∣ n, from if hm0 : m = 0 then λ _, by cases n; simp [*, lt_irrefl, pow_succ'] at * else mt (le_of_dvd hn0) (not_le_of_gt $ lt_pow_self (lt_of_le_of_ne (nat.pos_of_ne_zero hm0) hm1.symm) _), ⟨λ hi, begin simp only [Ico.mem, mem_filter, lt_succ_iff] at *, exact ⟨⟨hi.1, lt_of_le_of_lt hi.2 $ lt_of_lt_of_le (by rw [← enat.coe_lt_coe, enat.coe_get, multiplicity_lt_iff_neg_dvd]; exact hmn) hb⟩, by rw [pow_dvd_iff_le_multiplicity]; rw [← @enat.coe_le_coe i, enat.coe_get] at hi; exact hi.2⟩ end, begin simp only [Ico.mem, mem_filter, lt_succ_iff, and_imp, true_and] { contextual := tt }, assume h1i hib hmin, rwa [← enat.coe_le_coe, enat.coe_get, ← pow_dvd_iff_le_multiplicity] end⟩ namespace prime lemma multiplicity_one {p : ℕ} (hp : p.prime) : multiplicity p 1 = 0 := by rw [multiplicity.one_right (mt nat.is_unit_iff.mp (ne_of_gt hp.one_lt))] lemma multiplicity_mul {p m n : ℕ} (hp : p.prime) : multiplicity p (m * n) = multiplicity p m + multiplicity p n := by rw [← int.coe_nat_multiplicity, ← int.coe_nat_multiplicity, ← int.coe_nat_multiplicity, int.coe_nat_mul, multiplicity.mul (nat.prime_iff_prime_int.1 hp)] lemma multiplicity_pow {p m n : ℕ} (hp : p.prime) : multiplicity p (m ^ n) = n •ℕ (multiplicity p m) := by induction n; simp [pow_succ', hp.multiplicity_mul, *, hp.multiplicity_one, succ_nsmul, add_comm] lemma multiplicity_self {p : ℕ} (hp : p.prime) : multiplicity p p = 1 := have h₁ : ¬ is_unit (p : ℤ), from mt is_unit_int.1 (ne_of_gt hp.one_lt), have h₂ : (p : ℤ) ≠ 0, from int.coe_nat_ne_zero.2 hp.ne_zero, by rw [← int.coe_nat_multiplicity, multiplicity_self h₁ h₂] lemma multiplicity_pow_self {p n : ℕ} (hp : p.prime) : multiplicity p (p ^ n) = n := by induction n; simp [hp.multiplicity_one, pow_succ', hp.multiplicity_mul, *, hp.multiplicity_self, succ_eq_add_one] /-- The multiplicity of a prime in `n!` is the sum of the quotients `n / p ^ i`. This sum is expressed over the set `Ico 1 b` where `b` is any bound at least `n` -/ lemma multiplicity_factorial {p : ℕ} (hp : p.prime) : ∀ {n b : ℕ}, n ≤ b → multiplicity p n! = (∑ i in Ico 1 b, n / p ^ i : ℕ) | 0 b hb := by simp [Ico, hp.multiplicity_one] | (n+1) b hb := calc multiplicity p (n+1)! = multiplicity p n! + multiplicity p (n+1) : by rw [factorial_succ, hp.multiplicity_mul, add_comm] ... = (∑ i in Ico 1 b, n / p ^ i : ℕ) + ((finset.Ico 1 b).filter (λ i, p ^ i ∣ n+1)).card : by rw [multiplicity_factorial (le_of_succ_le hb), ← multiplicity_eq_card_pow_dvd (ne_of_gt hp.one_lt) (succ_pos _) hb] ... = (∑ i in Ico 1 b, (n / p ^ i + if p^i ∣ n+1 then 1 else 0) : ℕ) : by rw [sum_add_distrib, sum_boole]; simp ... = (∑ i in Ico 1 b, (n + 1) / p ^ i : ℕ) : congr_arg coe $ finset.sum_congr rfl (by intros; simp [nat.succ_div]; congr) /-- A prime power divides `n!` iff it is at most the sum of the quotients `n / p ^ i`. This sum is expressed over the set `Ico 1 b` where `b` is any bound at least `n` -/ lemma pow_dvd_factorial_iff {p : ℕ} {n r b : ℕ} (hp : p.prime) (hbn : n ≤ b) : p ^ r ∣ n! ↔ r ≤ ∑ i in Ico 1 b, n / p ^ i := by rw [← enat.coe_le_coe, ← hp.multiplicity_factorial hbn, ← pow_dvd_iff_le_multiplicity] lemma multiplicity_choose_aux {p n b k : ℕ} (hp : p.prime) (hkn : k ≤ n) : ∑ i in finset.Ico 1 b, n / p ^ i = ∑ i in finset.Ico 1 b, k / p ^ i + ∑ i in finset.Ico 1 b, (n - k) / p ^ i + ((finset.Ico 1 b).filter (λ i, p ^ i ≤ k % p ^ i + (n - k) % p ^ i)).card := calc ∑ i in finset.Ico 1 b, n / p ^ i = ∑ i in finset.Ico 1 b, (k + (n - k)) / p ^ i : by simp only [nat.add_sub_cancel' hkn] ... = ∑ i in finset.Ico 1 b, (k / p ^ i + (n - k) / p ^ i + if p ^ i ≤ k % p ^ i + (n - k) % p ^ i then 1 else 0) : by simp only [nat.add_div (pow_pos hp.pos _)] ... = _ : begin simp only [sum_add_distrib], simp [sum_boole], end -- we have to use `sum_add_distrib` before `add_ite` fires. /-- The multiplity of `p` in `choose n k` is the number of carries when `k` and `n - k` are added in base `p`. The set is expressed by filtering `Ico 1 b` where `b` is any bound at least `n`. -/ lemma multiplicity_choose {p n k b : ℕ} (hp : p.prime) (hkn : k ≤ n) (hnb : n ≤ b) : multiplicity p (choose n k) = ((Ico 1 b).filter (λ i, p ^ i ≤ k % p ^ i + (n - k) % p ^ i)).card := have h₁ : multiplicity p (choose n k) + multiplicity p (k! * (n - k)!) = ((finset.Ico 1 b).filter (λ i, p ^ i ≤ k % p ^ i + (n - k) % p ^ i)).card + multiplicity p (k! * (n - k)!), begin rw [← hp.multiplicity_mul, ← mul_assoc, choose_mul_factorial_mul_factorial hkn, hp.multiplicity_factorial hnb, hp.multiplicity_mul, hp.multiplicity_factorial (le_trans hkn hnb), hp.multiplicity_factorial (le_trans (nat.sub_le_self _ _) hnb), multiplicity_choose_aux hp hkn], simp [add_comm], end, (enat.add_right_cancel_iff (enat.ne_top_iff_dom.2 $ by exact finite_nat_iff.2 ⟨ne_of_gt hp.one_lt, mul_pos (factorial_pos k) (factorial_pos (n - k))⟩)).1 h₁ /-- A lower bound on the multiplicity of `p` in `choose n k`. -/ lemma multiplicity_le_multiplicity_choose_add {p : ℕ} (hp : p.prime) (n k : ℕ) : multiplicity p n ≤ multiplicity p (choose n k) + multiplicity p k := if hkn : n < k then by simp [choose_eq_zero_of_lt hkn] else if hk0 : k = 0 then by simp [hk0] else if hn0 : n = 0 then by cases k; simp [hn0, *] at * else begin rw [multiplicity_choose hp (le_of_not_gt hkn) (le_refl _), multiplicity_eq_card_pow_dvd (ne_of_gt hp.one_lt) (nat.pos_of_ne_zero hk0) (le_of_not_gt hkn), multiplicity_eq_card_pow_dvd (ne_of_gt hp.one_lt) (nat.pos_of_ne_zero hn0) (le_refl _), ← enat.coe_add, enat.coe_le_coe], calc ((Ico 1 n).filter (λ i, p ^ i ∣ n)).card ≤ ((Ico 1 n).filter (λ i, p ^ i ≤ k % p ^ i + (n - k) % p ^ i) ∪ (Ico 1 n).filter (λ i, p ^ i ∣ k) ).card : card_le_of_subset $ λ i, begin have := @le_mod_add_mod_of_dvd_add_of_not_dvd k (n - k) (p ^ i), simp [nat.add_sub_cancel' (le_of_not_gt hkn)] at * {contextual := tt}, tauto end ... ≤ ((Ico 1 n).filter (λ i, p ^ i ≤ k % p ^ i + (n - k) % p ^ i)).card + ((Ico 1 n).filter (λ i, p ^ i ∣ k)).card : card_union_le _ _ end lemma multiplicity_choose_prime_pow {p n k : ℕ} (hp : p.prime) (hkn : k ≤ p ^ n) (hk0 : 0 < k) : multiplicity p (choose (p ^ n) k) + multiplicity p k = n := le_antisymm (have hdisj : disjoint ((Ico 1 (p ^ n)).filter (λ i, p ^ i ≤ k % p ^ i + (p ^ n - k) % p ^ i)) ((Ico 1 (p ^ n)).filter (λ i, p ^ i ∣ k)), by simp [disjoint_right, *, dvd_iff_mod_eq_zero, nat.mod_lt _ (pow_pos hp.pos _)] {contextual := tt}, have filter_subset_Ico : filter (λ i, p ^ i ≤ k % p ^ i + (p ^ n - k) % p ^ i ∨ p ^ i ∣ k) (Ico 1 (p ^ n)) ⊆ Ico 1 n.succ, from begin simp only [finset.subset_iff, Ico.mem, mem_filter, and_imp, true_and] {contextual := tt}, assume i h1i hip h, refine lt_succ_of_le (le_of_not_gt (λ hin, _)), have hpik : ¬ p ^ i ∣ k, from mt (le_of_dvd hk0) (not_le_of_gt (lt_of_le_of_lt hkn (pow_right_strict_mono hp.two_le hin))), have hpn : k % p ^ i + (p ^ n - k) % p ^ i < p ^ i, from calc k % p ^ i + (p ^ n - k) % p ^ i ≤ k + (p ^ n - k) : add_le_add (mod_le _ _) (mod_le _ _) ... = p ^ n : nat.add_sub_cancel' hkn ... < p ^ i : pow_right_strict_mono hp.two_le hin, simpa [hpik, not_le_of_gt hpn] using h end, begin rw [multiplicity_choose hp hkn (le_refl _), multiplicity_eq_card_pow_dvd (ne_of_gt hp.one_lt) hk0 hkn, ← enat.coe_add, enat.coe_le_coe, ← card_disjoint_union hdisj, filter_union_right], exact le_trans (card_le_of_subset filter_subset_Ico) (by simp) end) (by rw [← hp.multiplicity_pow_self]; exact multiplicity_le_multiplicity_choose_add hp _ _) end prime end nat
3d0ae448e6081d28e717de6115b08de4e95d5035
48eee836fdb5c613d9a20741c17db44c8e12e61c
/src/universal/compactness.lean
2b934f3abede0223953ed03f75d0f2ab80c4feb4
[ "Apache-2.0" ]
permissive
fgdorais/lean-universal
06430443a4abe51e303e602684c2977d1f5c0834
9259b0f7fb3aa83a9e0a7a3eaa44c262e42cc9b1
refs/heads/master
1,592,479,744,136
1,589,473,399,000
1,589,473,399,000
196,287,552
1
1
null
null
null
null
UTF-8
Lean
false
false
3,629
lean
import .basic import .model import .proof namespace universal variables {τ : Type} {σ : Type*} {sig : signature τ σ} {ι : Type} {ax : ι → identity sig} namespace proof variables {ι' : Type} {ax' : ι' → identity sig} (ht : Π (i : ι), proof ax' (ax i).lhs (ax i).rhs) definition transfer {dom} : Π {cod} {t₁ t₂ : term sig dom cod} (p : proof ax t₁ t₂), proof ax' t₁ t₂ | _ _ _ (proof.ax i sub) := proof.subst sub (ht i) | _ _ _ (proof.proj _) := proof.proj _ | _ _ _ (proof.func f ps) := proof.func f (λ i, transfer (ps i)) | _ _ _ (proof.eucl p₁ p₂) := proof.eucl (transfer p₁) (transfer p₂) definition transfer_of_map (f : ι → ι') (hf : ∀ i, ax' (f i) = ax i) (i : ι) : proof ax' (ax i).lhs (ax i).rhs := eq.rec_on (hf i) $ proof.ax_id (f i) end proof definition proof.occurs {dom} : Π {cod} {t₁ t₂ : term sig dom cod}, proof ax t₁ t₂ → ι → Prop | _ _ _ (proof.ax i _) j := i = j | _ _ _ (proof.proj _) _ := false | _ _ _ (proof.func _ ps) j := ∃ i, proof.occurs (ps i) j | _ _ _ (proof.eucl p₁ p₂) j := proof.occurs p₁ j ∨ proof.occurs p₂ j definition proof.use {dom} : Π {cod} {t₁ t₂ : term sig dom cod}, proof ax t₁ t₂ → list ι | _ _ _ (proof.ax i _) := [i] | _ _ _ (proof.proj _) := [] | _ _ _ (proof.func _ ps) := list.join $ index.dtup.to_list (λ i, proof.use (ps i)) | _ _ _ (proof.eucl p₁ p₂) := proof.use p₁ ++ proof.use p₂ theorem proof.mem_use_of_occurs {dom} : Π {cod} {t₁ t₂ : term sig dom cod} {p : proof ax t₁ t₂} {i : ι}, proof.occurs p i → i ∈ proof.use p | _ _ _ (proof.ax i _) j h := eq.rec_on h (or.inl rfl) | _ _ _ (proof.proj _) _ h := absurd h not_false | _ _ _ (proof.func _ ps) j h := exists.elim h $ λ i hi, let i' : index (index.dtup.to_list (λ i, proof.use (ps i))) := index.map _ (index.dtup.enum_index _ i) in have hi' : j ∈ i'.val, by { rw [index.val_map, index.dtup.enum_index_val], exact proof.mem_use_of_occurs hi }, list.mem_join j i' hi' | _ _ _ (proof.eucl p₁ p₂) j h := or.elim h (λ h, list.mem_append_left _ (proof.mem_use_of_occurs h)) (λ h, list.mem_append_right _ (proof.mem_use_of_occurs h)) definition proof.of_use {dom} : Π {cod} {t₁ t₂ : term sig dom cod} (p : proof ax t₁ t₂), proof (λ (i : index p.use), ax i.val) t₁ t₂ | _ t₁ t₂ p@(proof.ax i sub) := proof.subst sub $ proof.ax_id (index.head i []) | _ _ _ (proof.proj _) := proof.proj _ | _ _ _ p@(@proof.func _ _ _ _ _ _ f lhs rhs ps) := let m : Π (i : sig.index f) (j : index (ps i).use), index p.use := λ i j, index.join_map _ (index.dtup.to_list_index _ i) $ eq.rec_on (index.dtup.to_list_index_val (λ i, (ps i).use) i).symm j in let ps : Π (i : sig.index f), proof (λ (i : index p.use), ax i.val) (lhs i) (rhs i) := λ i, proof.transfer (proof.transfer_of_map (m i) (by {intro, simp})) (proof.of_use (ps i)) in proof.func f ps | _ t₁ t₂ p@(@proof.eucl _ _ _ _ _ _ _ t _ _ p₁ p₂) := let p₁ : proof (λ (i : index p.use), ax i.val) t t₁ := proof.transfer (proof.transfer_of_map (index.append_left _ _) (by {intro, rw [index.append_left_val]})) (proof.of_use p₁) in let p₂ : proof (λ (i : index p.use), ax i.val) t t₂ := proof.transfer (proof.transfer_of_map (index.append_right _ _) (by {intro, rw [index.append_right_val]})) (proof.of_use p₂) in proof.eucl p₁ p₂ theorem compactness (e : identity sig) : models ax e → ∃ (as : list ι), models (λ (i : index as), ax i.val) e := begin intros hm, cases completeness ax e hm with hp, existsi hp.use, apply soundness, constructor, exact proof.of_use hp, end end universal
855ab4e92dbe1d75dd9a2d935e654891b8cd388d
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/data/matrix/basis.lean
276ed52bb3a49f47c99c715b3b65fe0d74a95e5d
[ "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,484
lean
/- Copyright (c) 2020 Jalex Stark. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jalex Stark, Scott Morrison, Eric Wieser, Oliver Nash -/ import data.matrix.basic import linear_algebra.matrix.trace /-! # Matrices with a single non-zero element. > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file provides `matrix.std_basis_matrix`. The matrix `matrix.std_basis_matrix i j c` has `c` at position `(i, j)`, and zeroes elsewhere. -/ variables {l m n : Type*} variables {R α : Type*} namespace matrix open_locale matrix open_locale big_operators variables [decidable_eq l] [decidable_eq m] [decidable_eq n] variables [semiring α] /-- `std_basis_matrix i j a` is the matrix with `a` in the `i`-th row, `j`-th column, and zeroes elsewhere. -/ def std_basis_matrix (i : m) (j : n) (a : α) : matrix m n α := (λ i' j', if i = i' ∧ j = j' then a else 0) @[simp] lemma smul_std_basis_matrix (i : m) (j : n) (a b : α) : b • std_basis_matrix i j a = std_basis_matrix i j (b • a) := by { unfold std_basis_matrix, ext, simp } @[simp] lemma std_basis_matrix_zero (i : m) (j : n) : std_basis_matrix i j (0 : α) = 0 := by { unfold std_basis_matrix, ext, simp } lemma std_basis_matrix_add (i : m) (j : n) (a b : α) : std_basis_matrix i j (a + b) = std_basis_matrix i j a + std_basis_matrix i j b := begin unfold std_basis_matrix, ext, split_ifs with h; simp [h], end lemma matrix_eq_sum_std_basis [fintype m] [fintype n] (x : matrix m n α) : x = ∑ (i : m) (j : n), std_basis_matrix i j (x i j) := begin ext, symmetry, iterate 2 { rw finset.sum_apply }, convert fintype.sum_eq_single i _, { simp [std_basis_matrix] }, { intros j hj, simp [std_basis_matrix, hj], } end -- TODO: tie this up with the `basis` machinery of linear algebra -- this is not completely trivial because we are indexing by two types, instead of one -- TODO: add `std_basis_vec` lemma std_basis_eq_basis_mul_basis (i : m) (j : n) : std_basis_matrix i j 1 = vec_mul_vec (λ i', ite (i = i') 1 0) (λ j', ite (j = j') 1 0) := begin ext, norm_num [std_basis_matrix, vec_mul_vec], exact ite_and _ _ _ _, end -- todo: the old proof used fintypes, I don't know `finsupp` but this feels generalizable @[elab_as_eliminator] protected lemma induction_on' [fintype m] [fintype n] {P : matrix m n α → Prop} (M : matrix m n α) (h_zero : P 0) (h_add : ∀ p q, P p → P q → P (p + q)) (h_std_basis : ∀ (i : m) (j : n) (x : α), P (std_basis_matrix i j x)) : P M := begin rw [matrix_eq_sum_std_basis M, ← finset.sum_product'], apply finset.sum_induction _ _ h_add h_zero, { intros, apply h_std_basis, } end @[elab_as_eliminator] protected lemma induction_on [fintype m] [fintype n] [nonempty m] [nonempty n] {P : matrix m n α → Prop} (M : matrix m n α) (h_add : ∀ p q, P p → P q → P (p + q)) (h_std_basis : ∀ i j x, P (std_basis_matrix i j x)) : P M := matrix.induction_on' M begin inhabit m, inhabit n, simpa using h_std_basis default default 0 end h_add h_std_basis namespace std_basis_matrix section variables (i : m) (j : n) (c : α) (i' : m) (j' : n) @[simp] lemma apply_same : std_basis_matrix i j c i j = c := if_pos (and.intro rfl rfl) @[simp] lemma apply_of_ne (h : ¬((i = i') ∧ (j = j'))) : std_basis_matrix i j c i' j' = 0 := by { simp only [std_basis_matrix, and_imp, ite_eq_right_iff], tauto } @[simp] lemma apply_of_row_ne {i i' : m} (hi : i ≠ i') (j j' : n) (a : α) : std_basis_matrix i j a i' j' = 0 := by simp [hi] @[simp] lemma apply_of_col_ne (i i' : m) {j j' : n} (hj : j ≠ j') (a : α) : std_basis_matrix i j a i' j' = 0 := by simp [hj] end section variables (i j : n) (c : α) (i' j' : n) @[simp] lemma diag_zero (h : j ≠ i) : diag (std_basis_matrix i j c) = 0 := funext $ λ k, if_neg $ λ ⟨e₁, e₂⟩, h (e₂.trans e₁.symm) @[simp] lemma diag_same : diag (std_basis_matrix i i c) = pi.single i c := by { ext j, by_cases hij : i = j; try {rw hij}; simp [hij] } variable [fintype n] @[simp] lemma trace_zero (h : j ≠ i) : trace (std_basis_matrix i j c) = 0 := by simp [trace, h] @[simp] lemma trace_eq : trace (std_basis_matrix i i c) = c := by simp [trace] @[simp] lemma mul_left_apply_same (b : n) (M : matrix n n α) : (std_basis_matrix i j c ⬝ M) i b = c * M j b := by simp [mul_apply, std_basis_matrix] @[simp] lemma mul_right_apply_same (a : n) (M : matrix n n α) : (M ⬝ std_basis_matrix i j c) a j = M a i * c := by simp [mul_apply, std_basis_matrix, mul_comm] @[simp] lemma mul_left_apply_of_ne (a b : n) (h : a ≠ i) (M : matrix n n α) : (std_basis_matrix i j c ⬝ M) a b = 0 := by simp [mul_apply, h.symm] @[simp] lemma mul_right_apply_of_ne (a b : n) (hbj : b ≠ j) (M : matrix n n α) : (M ⬝ std_basis_matrix i j c) a b = 0 := by simp [mul_apply, hbj.symm] @[simp] lemma mul_same (k : n) (d : α) : std_basis_matrix i j c ⬝ std_basis_matrix j k d = std_basis_matrix i k (c * d) := begin ext a b, simp only [mul_apply, std_basis_matrix, boole_mul], by_cases h₁ : i = a; by_cases h₂ : k = b; simp [h₁, h₂], end @[simp] lemma mul_of_ne {k l : n} (h : j ≠ k) (d : α) : std_basis_matrix i j c ⬝ std_basis_matrix k l d = 0 := begin ext a b, simp only [mul_apply, boole_mul, std_basis_matrix], by_cases h₁ : i = a; simp [h₁, h, h.symm], end end end std_basis_matrix end matrix
800912adbd7a9c96ea26e8b95becef2f77420397
097294e9b80f0d9893ac160b9c7219aa135b51b9
/instructor/predicate_logic/intro_and_elim_rules/implies.lean
233a882f1a52efdd887651ea2d4a00613f3c58e4
[]
no_license
AbigailCastro17/CS2102-Discrete-Math
cf296251be9418ce90206f5e66bde9163e21abf9
d741e4d2d6a9b2e0c8380e51706218b8f608cee4
refs/heads/main
1,682,891,087,358
1,621,401,341,000
1,621,401,341,000
368,749,959
0
0
null
null
null
null
UTF-8
Lean
false
false
1,894
lean
/- If you understand the introduction and elimination rules for ∀, then you understand these rules for proving, and using proofs of implications. Consider an implication, P → Q. To construct a proof, pq, of P → Q, you simply *assume* you're given an arbitrary but specific value/proof of P and in this context you must show that you can construct and return a proof of Q. What this shows is that *if* P is true (because there is a proof of it) then so is Q. In other words, prove P → Q by showing that you can define a total function of type P → Q! For an example, see the second step (after the ∀ introduction) in our proof of the commutativity of ∨. What's left to prove there is an implication, P ∨ Q → Q ∨ P. The way it is proved is just the way that the overall ∀ proposition is proved: by assuming that we're given a proof/value, but now of type P ∨ Q, and showing that in this context we can construct and return a value of Q ∨ P. In fact, P ∨ Q is really just a shorthand in Lean for ∀ (p : P), Q! You can see it clearly in the following code, where we first assume that P and Q are arbitrary propositions, and then check the type of ∀ (p : P), Q. It's Prop, of course, as ∀ (p : P), Q is a proposition; but what is key here is that Lean uses → notation to print out this proposition! We can even prove that they're exactly the same proposition. -/ axioms P Q : Prop #check ∀ (p : P), Q example : (P → Q) = ∀ (p : P), Q := rfl /- Of course it's now obvious that the elimination rule for → is the same as it is for ∀: *apply* a proof of P → Q to a proof of P to obtain a proof of Q. -/ theorem modus_ponens: (P → Q) → P → Q := λ (pq : P → Q), -- suppose you have a proof of P → Q λ (p : P), -- and that you have a proof of P pq p -- *apply* former to latter; QED.
fd3549aa6b850d8c5fc70e9fd5320614654d67c1
cc060cf567f81c404a13ee79bf21f2e720fa6db0
/lean/list_examples.lean
301d1052906508cbe8f011dac8143b53cf909832
[ "Apache-2.0" ]
permissive
semorrison/proof
cf0a8c6957153bdb206fd5d5a762a75958a82bca
5ee398aa239a379a431190edbb6022b1a0aa2c70
refs/heads/master
1,610,414,502,842
1,518,696,851,000
1,518,696,851,000
78,375,937
2
1
null
null
null
null
UTF-8
Lean
false
false
1,335
lean
namespace hide inductive list (A : Type) : Type := | nil {} : list A | cons : A → list A → list A namespace list notation `[` l:(foldr `,` (h t, cons h t) nil) `]` := l variable {A : Type} notation h :: t := cons h t definition append (s t : list A) : list A := list.rec_on s t (λ x l u, x::u) notation s ++ t := append s t theorem nil_append (t : list A) : nil ++ t = t := rfl theorem cons_append (x : A) (s t : list A) : x::s ++ t = x::(s ++ t) := rfl theorem append_nil (t : list A) : t ++ nil = t := list.induction_on t (show nil ++ nil = nil, from nil_append nil) (take h t, assume IH : t ++ nil = t, show h :: t ++ nil = h :: t, from calc h :: t ++ nil = h :: (t ++ nil) : cons_append h t nil ... = h :: t : IH) theorem append_assoc (r s t : list A) : r ++ s ++ t = r ++ (s ++ t) := list.induction_on r (show nil ++ s ++ t = nil ++ (s ++ t), from calc nil ++ s ++ t = s ++ t : rfl ... = nil ++ (s ++ t) : rfl) (take h r, assume IH : r ++ s ++ t = r ++ (s ++ t), show h :: r ++ s ++ t = h :: r ++ (s ++ t), from calc h :: r ++ s ++ t = h :: (r ++ s) ++ t : cons_append h r s ... = h :: (r ++ s ++ t) : cons_append h (r ++ s) t ... = h :: (r ++ (s ++ t)) : IH ... = h :: r ++ (s ++ t) : cons_append h r (s ++ t)) end list end hide
ed86650bfe5de11b2423c013e2382c681938d8e5
9028d228ac200bbefe3a711342514dd4e4458bff
/src/geometry/euclidean/basic.lean
baabf8dc8f4dc015c992d4d8bab56d081fa5a7f7
[ "Apache-2.0" ]
permissive
mcncm/mathlib
8d25099344d9d2bee62822cb9ed43aa3e09fa05e
fde3d78cadeec5ef827b16ae55664ef115e66f57
refs/heads/master
1,672,743,316,277
1,602,618,514,000
1,602,618,514,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
48,476
lean
/- Copyright (c) 2020 Joseph Myers. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Joseph Myers. -/ import analysis.normed_space.inner_product import algebra.quadratic_discriminant import analysis.normed_space.add_torsor import data.matrix.notation import linear_algebra.affine_space.finite_dimensional import tactic.fin_cases noncomputable theory open_locale big_operators open_locale classical open_locale real open_locale real_inner_product_space /-! # Euclidean spaces This file makes some definitions and proves very basic geometrical results about real inner product spaces and Euclidean affine spaces. Results about real inner product spaces that involve the norm and inner product but not angles generally go in `analysis.normed_space.inner_product`. Results with longer proofs or more geometrical content generally go in separate files. ## Main definitions * `inner_product_geometry.angle` is the undirected angle between two vectors. * `euclidean_geometry.angle`, with notation `∠`, is the undirected angle determined by three points. * `euclidean_geometry.orthogonal_projection` is the orthogonal projection of a point onto an affine subspace. * `euclidean_geometry.reflection` is the reflection of a point in an affine subspace. ## Implementation notes To declare `P` as the type of points in a Euclidean affine space with `V` as the type of vectors, use `[inner_product_space ℝ V] [metric_space P] [normed_add_torsor V P]`. This works better with `out_param` to make `V` implicit in most cases than having a separate type alias for Euclidean affine spaces. Rather than requiring Euclidean affine spaces to be finite-dimensional (as in the definition on Wikipedia), this is specified only for those theorems that need it. ## References * https://en.wikipedia.org/wiki/Euclidean_space -/ namespace inner_product_geometry /-! ### Geometrical results on real inner product spaces This section develops some geometrical definitions and results on real inner product spaces, where those definitions and results can most conveniently be developed in terms of vectors and then used to deduce corresponding results for Euclidean affine spaces. -/ variables {V : Type*} [inner_product_space ℝ V] /-- The undirected angle between two vectors. If either vector is 0, this is π/2. -/ def angle (x y : V) : ℝ := real.arccos (inner x y / (∥x∥ * ∥y∥)) /-- The cosine of the angle between two vectors. -/ lemma cos_angle (x y : V) : real.cos (angle x y) = inner x y / (∥x∥ * ∥y∥) := real.cos_arccos (abs_le.mp (abs_real_inner_div_norm_mul_norm_le_one x y)).1 (abs_le.mp (abs_real_inner_div_norm_mul_norm_le_one x y)).2 /-- The angle between two vectors does not depend on their order. -/ lemma angle_comm (x y : V) : angle x y = angle y x := begin unfold angle, rw [real_inner_comm, mul_comm] end /-- The angle between the negation of two vectors. -/ @[simp] lemma angle_neg_neg (x y : V) : angle (-x) (-y) = angle x y := begin unfold angle, rw [inner_neg_neg, norm_neg, norm_neg] end /-- The angle between two vectors is nonnegative. -/ lemma angle_nonneg (x y : V) : 0 ≤ angle x y := real.arccos_nonneg _ /-- The angle between two vectors is at most π. -/ lemma angle_le_pi (x y : V) : angle x y ≤ π := real.arccos_le_pi _ /-- The angle between a vector and the negation of another vector. -/ lemma angle_neg_right (x y : V) : angle x (-y) = π - angle x y := begin unfold angle, rw [←real.arccos_neg, norm_neg, inner_neg_right, neg_div] end /-- The angle between the negation of a vector and another vector. -/ lemma angle_neg_left (x y : V) : angle (-x) y = π - angle x y := by rw [←angle_neg_neg, neg_neg, angle_neg_right] /-- The angle between the zero vector and a vector. -/ @[simp] lemma angle_zero_left (x : V) : angle 0 x = π / 2 := begin unfold angle, rw [inner_zero_left, zero_div, real.arccos_zero] end /-- The angle between a vector and the zero vector. -/ @[simp] lemma angle_zero_right (x : V) : angle x 0 = π / 2 := begin unfold angle, rw [inner_zero_right, zero_div, real.arccos_zero] end /-- The angle between a nonzero vector and itself. -/ @[simp] lemma angle_self {x : V} (hx : x ≠ 0) : angle x x = 0 := begin unfold angle, rw [←real_inner_self_eq_norm_square, div_self (λ h, hx (inner_self_eq_zero.1 h)), real.arccos_one] end /-- The angle between a nonzero vector and its negation. -/ @[simp] lemma angle_self_neg_of_nonzero {x : V} (hx : x ≠ 0) : angle x (-x) = π := by rw [angle_neg_right, angle_self hx, sub_zero] /-- The angle between the negation of a nonzero vector and that vector. -/ @[simp] lemma angle_neg_self_of_nonzero {x : V} (hx : x ≠ 0) : angle (-x) x = π := by rw [angle_comm, angle_self_neg_of_nonzero hx] /-- The angle between a vector and a positive multiple of a vector. -/ @[simp] lemma angle_smul_right_of_pos (x y : V) {r : ℝ} (hr : 0 < r) : angle x (r • y) = angle x y := begin unfold angle, rw [inner_smul_right, norm_smul, real.norm_eq_abs, abs_of_nonneg (le_of_lt hr), ←mul_assoc, mul_comm _ r, mul_assoc, mul_div_mul_left _ _ (ne_of_gt hr)] end /-- The angle between a positive multiple of a vector and a vector. -/ @[simp] lemma angle_smul_left_of_pos (x y : V) {r : ℝ} (hr : 0 < r) : angle (r • x) y = angle x y := by rw [angle_comm, angle_smul_right_of_pos y x hr, angle_comm] /-- The angle between a vector and a negative multiple of a vector. -/ @[simp] lemma angle_smul_right_of_neg (x y : V) {r : ℝ} (hr : r < 0) : angle x (r • y) = angle x (-y) := by rw [←neg_neg r, neg_smul, angle_neg_right, angle_smul_right_of_pos x y (neg_pos_of_neg hr), angle_neg_right] /-- The angle between a negative multiple of a vector and a vector. -/ @[simp] lemma angle_smul_left_of_neg (x y : V) {r : ℝ} (hr : r < 0) : angle (r • x) y = angle (-x) y := by rw [angle_comm, angle_smul_right_of_neg y x hr, angle_comm] /-- The cosine of the angle between two vectors, multiplied by the product of their norms. -/ lemma cos_angle_mul_norm_mul_norm (x y : V) : real.cos (angle x y) * (∥x∥ * ∥y∥) = inner x y := begin rw cos_angle, by_cases h : (∥x∥ * ∥y∥) = 0, { rw [h, mul_zero], cases eq_zero_or_eq_zero_of_mul_eq_zero h with hx hy, { rw norm_eq_zero at hx, rw [hx, inner_zero_left] }, { rw norm_eq_zero at hy, rw [hy, inner_zero_right] } }, { exact div_mul_cancel _ h } end /-- The sine of the angle between two vectors, multiplied by the product of their norms. -/ lemma sin_angle_mul_norm_mul_norm (x y : V) : real.sin (angle x y) * (∥x∥ * ∥y∥) = real.sqrt (inner x x * inner y y - inner x y * inner x y) := begin unfold angle, rw [real.sin_arccos (abs_le.mp (abs_real_inner_div_norm_mul_norm_le_one x y)).1 (abs_le.mp (abs_real_inner_div_norm_mul_norm_le_one x y)).2, ←real.sqrt_mul_self (mul_nonneg (norm_nonneg x) (norm_nonneg y)), ←real.sqrt_mul' _ (mul_self_nonneg _), pow_two, real.sqrt_mul_self (mul_nonneg (norm_nonneg x) (norm_nonneg y)), real_inner_self_eq_norm_square, real_inner_self_eq_norm_square], by_cases h : (∥x∥ * ∥y∥) = 0, { rw [(show ∥x∥ * ∥x∥ * (∥y∥ * ∥y∥) = (∥x∥ * ∥y∥) * (∥x∥ * ∥y∥), by ring), h, mul_zero, mul_zero, zero_sub], cases eq_zero_or_eq_zero_of_mul_eq_zero h with hx hy, { rw norm_eq_zero at hx, rw [hx, inner_zero_left, zero_mul, neg_zero] }, { rw norm_eq_zero at hy, rw [hy, inner_zero_right, zero_mul, neg_zero] } }, { field_simp [h], ring } end /-- The angle between two vectors is zero if and only if they are nonzero and one is a positive multiple of the other. -/ lemma angle_eq_zero_iff (x y : V) : angle x y = 0 ↔ (x ≠ 0 ∧ ∃ (r : ℝ), 0 < r ∧ y = r • x) := begin unfold angle, rw [←real_inner_div_norm_mul_norm_eq_one_iff, ←real.arccos_one], split, { intro h, exact real.arccos_inj (abs_le.mp (abs_real_inner_div_norm_mul_norm_le_one x y)).1 (abs_le.mp (abs_real_inner_div_norm_mul_norm_le_one x y)).2 (by norm_num) (by norm_num) h }, { intro h, rw h } end /-- The angle between two vectors is π if and only if they are nonzero and one is a negative multiple of the other. -/ lemma angle_eq_pi_iff (x y : V) : angle x y = π ↔ (x ≠ 0 ∧ ∃ (r : ℝ), r < 0 ∧ y = r • x) := begin unfold angle, rw [←real_inner_div_norm_mul_norm_eq_neg_one_iff, ←real.arccos_neg_one], split, { intro h, exact real.arccos_inj (abs_le.mp (abs_real_inner_div_norm_mul_norm_le_one x y)).1 (abs_le.mp (abs_real_inner_div_norm_mul_norm_le_one x y)).2 (by norm_num) (by norm_num) h }, { intro h, rw h } end /-- If the angle between two vectors is π, the angles between those vectors and a third vector add to π. -/ lemma angle_add_angle_eq_pi_of_angle_eq_pi {x y : V} (z : V) (h : angle x y = π) : angle x z + angle y z = π := begin rw angle_eq_pi_iff at h, rcases h with ⟨hx, ⟨r, ⟨hr, hxy⟩⟩⟩, rw [hxy, angle_smul_left_of_neg x z hr, angle_neg_left, add_sub_cancel'_right] end /-- Two vectors have inner product 0 if and only if the angle between them is π/2. -/ lemma inner_eq_zero_iff_angle_eq_pi_div_two (x y : V) : ⟪x, y⟫ = 0 ↔ angle x y = π / 2 := begin split, { intro h, unfold angle, rw [h, zero_div, real.arccos_zero] }, { intro h, unfold angle at h, rw ←real.arccos_zero at h, have h2 : inner x y / (∥x∥ * ∥y∥) = 0 := real.arccos_inj (abs_le.mp (abs_real_inner_div_norm_mul_norm_le_one x y)).1 (abs_le.mp (abs_real_inner_div_norm_mul_norm_le_one x y)).2 (by norm_num) (by norm_num) h, by_cases h : (∥x∥ * ∥y∥) = 0, { cases eq_zero_or_eq_zero_of_mul_eq_zero h with hx hy, { rw norm_eq_zero at hx, rw [hx, inner_zero_left] }, { rw norm_eq_zero at hy, rw [hy, inner_zero_right] } }, { simpa [h, div_eq_zero_iff] using h2 } }, end end inner_product_geometry namespace euclidean_geometry /-! ### Geometrical results on Euclidean affine spaces This section develops some geometrical definitions and results on Euclidean affine spaces. -/ open inner_product_geometry variables {V : Type*} {P : Type*} [inner_product_space ℝ V] [metric_space P] [normed_add_torsor V P] local notation `⟪`x`, `y`⟫` := @inner ℝ V _ x y include V /-- The undirected angle at `p2` between the line segments to `p1` and `p3`. If either of those points equals `p2`, this is π/2. Use `open_locale euclidean_geometry` to access the `∠ p1 p2 p3` notation. -/ def angle (p1 p2 p3 : P) : ℝ := angle (p1 -ᵥ p2 : V) (p3 -ᵥ p2) localized "notation `∠` := euclidean_geometry.angle" in euclidean_geometry /-- The angle at a point does not depend on the order of the other two points. -/ lemma angle_comm (p1 p2 p3 : P) : ∠ p1 p2 p3 = ∠ p3 p2 p1 := angle_comm _ _ /-- The angle at a point is nonnegative. -/ lemma angle_nonneg (p1 p2 p3 : P) : 0 ≤ ∠ p1 p2 p3 := angle_nonneg _ _ /-- The angle at a point is at most π. -/ lemma angle_le_pi (p1 p2 p3 : P) : ∠ p1 p2 p3 ≤ π := angle_le_pi _ _ /-- The angle ∠AAB at a point. -/ lemma angle_eq_left (p1 p2 : P) : ∠ p1 p1 p2 = π / 2 := begin unfold angle, rw vsub_self, exact angle_zero_left _ end /-- The angle ∠ABB at a point. -/ lemma angle_eq_right (p1 p2 : P) : ∠ p1 p2 p2 = π / 2 := by rw [angle_comm, angle_eq_left] /-- The angle ∠ABA at a point. -/ lemma angle_eq_of_ne {p1 p2 : P} (h : p1 ≠ p2) : ∠ p1 p2 p1 = 0 := angle_self (λ he, h (vsub_eq_zero_iff_eq.1 he)) /-- If the angle ∠ABC at a point is π, the angle ∠BAC is 0. -/ lemma angle_eq_zero_of_angle_eq_pi_left {p1 p2 p3 : P} (h : ∠ p1 p2 p3 = π) : ∠ p2 p1 p3 = 0 := begin unfold angle at h, rw angle_eq_pi_iff at h, rcases h with ⟨hp1p2, ⟨r, ⟨hr, hpr⟩⟩⟩, unfold angle, rw angle_eq_zero_iff, rw [←neg_vsub_eq_vsub_rev, neg_ne_zero] at hp1p2, use [hp1p2, -r + 1, add_pos (neg_pos_of_neg hr) zero_lt_one], rw [add_smul, ←neg_vsub_eq_vsub_rev p1 p2, smul_neg], simp [←hpr] end /-- If the angle ∠ABC at a point is π, the angle ∠BCA is 0. -/ lemma angle_eq_zero_of_angle_eq_pi_right {p1 p2 p3 : P} (h : ∠ p1 p2 p3 = π) : ∠ p2 p3 p1 = 0 := begin rw angle_comm at h, exact angle_eq_zero_of_angle_eq_pi_left h end /-- If ∠BCD = π, then ∠ABC = ∠ABD. -/ lemma angle_eq_angle_of_angle_eq_pi (p1 : P) {p2 p3 p4 : P} (h : ∠ p2 p3 p4 = π) : ∠ p1 p2 p3 = ∠ p1 p2 p4 := begin unfold angle at h, rw angle_eq_pi_iff at h, rcases h with ⟨hp2p3, ⟨r, ⟨hr, hpr⟩⟩⟩, unfold angle, symmetry, convert angle_smul_right_of_pos _ _ (add_pos (neg_pos_of_neg hr) zero_lt_one), rw [add_smul, ←neg_vsub_eq_vsub_rev p2 p3, smul_neg], simp [←hpr] end /-- If ∠BCD = π, then ∠ACB + ∠ACD = π. -/ lemma angle_add_angle_eq_pi_of_angle_eq_pi (p1 : P) {p2 p3 p4 : P} (h : ∠ p2 p3 p4 = π) : ∠ p1 p3 p2 + ∠ p1 p3 p4 = π := begin unfold angle at h, rw [angle_comm p1 p3 p2, angle_comm p1 p3 p4], unfold angle, exact angle_add_angle_eq_pi_of_angle_eq_pi _ h end /-- The inner product of two vectors given with `weighted_vsub`, in terms of the pairwise distances. -/ lemma inner_weighted_vsub {ι₁ : Type*} {s₁ : finset ι₁} {w₁ : ι₁ → ℝ} (p₁ : ι₁ → P) (h₁ : ∑ i in s₁, w₁ i = 0) {ι₂ : Type*} {s₂ : finset ι₂} {w₂ : ι₂ → ℝ} (p₂ : ι₂ → P) (h₂ : ∑ i in s₂, w₂ i = 0) : inner (s₁.weighted_vsub p₁ w₁) (s₂.weighted_vsub p₂ w₂) = (-∑ i₁ in s₁, ∑ i₂ in s₂, w₁ i₁ * w₂ i₂ * (dist (p₁ i₁) (p₂ i₂) * dist (p₁ i₁) (p₂ i₂))) / 2 := begin rw [finset.weighted_vsub_apply, finset.weighted_vsub_apply, inner_sum_smul_sum_smul_of_sum_eq_zero _ h₁ _ h₂], simp_rw [vsub_sub_vsub_cancel_right], rcongr i₁ i₂; rw dist_eq_norm_vsub V (p₁ i₁) (p₂ i₂) end /-- The distance between two points given with `affine_combination`, in terms of the pairwise distances between the points in that combination. -/ lemma dist_affine_combination {ι : Type*} {s : finset ι} {w₁ w₂ : ι → ℝ} (p : ι → P) (h₁ : ∑ i in s, w₁ i = 1) (h₂ : ∑ i in s, w₂ i = 1) : dist (s.affine_combination p w₁) (s.affine_combination p w₂) * dist (s.affine_combination p w₁) (s.affine_combination p w₂) = (-∑ i₁ in s, ∑ i₂ in s, (w₁ - w₂) i₁ * (w₁ - w₂) i₂ * (dist (p i₁) (p i₂) * dist (p i₁) (p i₂))) / 2 := begin rw [dist_eq_norm_vsub V (s.affine_combination p w₁) (s.affine_combination p w₂), ←inner_self_eq_norm_square, finset.affine_combination_vsub], have h : ∑ i in s, (w₁ - w₂) i = 0, { simp_rw [pi.sub_apply, finset.sum_sub_distrib, h₁, h₂, sub_self] }, exact inner_weighted_vsub p h p h end /-- Suppose that `c₁` is equidistant from `p₁` and `p₂`, and the same applies to `c₂`. Then the vector between `c₁` and `c₂` is orthogonal to that between `p₁` and `p₂`. (In two dimensions, this says that the diagonals of a kite are orthogonal.) -/ lemma inner_vsub_vsub_of_dist_eq_of_dist_eq {c₁ c₂ p₁ p₂ : P} (hc₁ : dist p₁ c₁ = dist p₂ c₁) (hc₂ : dist p₁ c₂ = dist p₂ c₂) : ⟪c₂ -ᵥ c₁, p₂ -ᵥ p₁⟫ = 0 := begin have h : ⟪(c₂ -ᵥ c₁) + (c₂ -ᵥ c₁), p₂ -ᵥ p₁⟫ = 0, { conv_lhs { congr, congr, rw ←vsub_sub_vsub_cancel_right c₂ c₁ p₁, skip, rw ←vsub_sub_vsub_cancel_right c₂ c₁ p₂ }, rw [←add_sub_comm, inner_sub_left], conv_lhs { congr, rw ←vsub_sub_vsub_cancel_right p₂ p₁ c₂, skip, rw ←vsub_sub_vsub_cancel_right p₂ p₁ c₁ }, rw [dist_comm p₁, dist_comm p₂, dist_eq_norm_vsub V _ p₁, dist_eq_norm_vsub V _ p₂, ←real_inner_add_sub_eq_zero_iff] at hc₁ hc₂, simp_rw [←neg_vsub_eq_vsub_rev c₁, ←neg_vsub_eq_vsub_rev c₂, sub_neg_eq_add, neg_add_eq_sub, hc₁, hc₂, sub_zero] }, simpa [inner_add_left, ←mul_two, (by norm_num : (2 : ℝ) ≠ 0)] using h end /-- The squared distance between points on a line (expressed as a multiple of a fixed vector added to a point) and another point, expressed as a quadratic. -/ lemma dist_smul_vadd_square (r : ℝ) (v : V) (p₁ p₂ : P) : dist (r • v +ᵥ p₁) p₂ * dist (r • v +ᵥ p₁) p₂ = ⟪v, v⟫ * r * r + 2 * ⟪v, p₁ -ᵥ p₂⟫ * r + ⟪p₁ -ᵥ p₂, p₁ -ᵥ p₂⟫ := begin rw [dist_eq_norm_vsub V _ p₂, ←real_inner_self_eq_norm_square, vadd_vsub_assoc, real_inner_add_add_self, real_inner_smul_left, real_inner_smul_left, real_inner_smul_right], ring end /-- The condition for two points on a line to be equidistant from another point. -/ lemma dist_smul_vadd_eq_dist {v : V} (p₁ p₂ : P) (hv : v ≠ 0) (r : ℝ) : dist (r • v +ᵥ p₁) p₂ = dist p₁ p₂ ↔ (r = 0 ∨ r = -2 * ⟪v, p₁ -ᵥ p₂⟫ / ⟪v, v⟫) := begin conv_lhs { rw [←mul_self_inj_of_nonneg dist_nonneg dist_nonneg, dist_smul_vadd_square, ←sub_eq_zero_iff_eq, add_sub_assoc, dist_eq_norm_vsub V p₁ p₂, ←real_inner_self_eq_norm_square, sub_self] }, have hvi : ⟪v, v⟫ ≠ 0, by simpa using hv, have hd : discrim ⟪v, v⟫ (2 * ⟪v, p₁ -ᵥ p₂⟫) 0 = (2 * inner v (p₁ -ᵥ p₂)) * (2 * inner v (p₁ -ᵥ p₂)), { rw discrim, ring }, rw [quadratic_eq_zero_iff hvi hd, add_left_neg, zero_div, neg_mul_eq_neg_mul, ←mul_sub_right_distrib, sub_eq_add_neg, ←mul_two, mul_assoc, mul_div_assoc, mul_div_mul_left, mul_div_assoc], norm_num end open affine_subspace finite_dimensional /-- Distances `r₁` `r₂` of `p` from two different points `c₁` `c₂` determine at most two points `p₁` `p₂` in a two-dimensional subspace containing those points (two circles intersect in at most two points). -/ lemma eq_of_dist_eq_of_dist_eq_of_mem_of_findim_eq_two {s : affine_subspace ℝ P} [finite_dimensional ℝ s.direction] (hd : findim ℝ s.direction = 2) {c₁ c₂ p₁ p₂ p : P} (hc₁s : c₁ ∈ s) (hc₂s : c₂ ∈ s) (hp₁s : p₁ ∈ s) (hp₂s : p₂ ∈ s) (hps : p ∈ s) {r₁ r₂ : ℝ} (hc : c₁ ≠ c₂) (hp : p₁ ≠ p₂) (hp₁c₁ : dist p₁ c₁ = r₁) (hp₂c₁ : dist p₂ c₁ = r₁) (hpc₁ : dist p c₁ = r₁) (hp₁c₂ : dist p₁ c₂ = r₂) (hp₂c₂ : dist p₂ c₂ = r₂) (hpc₂ : dist p c₂ = r₂) : p = p₁ ∨ p = p₂ := begin have ho : ⟪c₂ -ᵥ c₁, p₂ -ᵥ p₁⟫ = 0 := inner_vsub_vsub_of_dist_eq_of_dist_eq (by cc) (by cc), have hop : ⟪c₂ -ᵥ c₁, p -ᵥ p₁⟫ = 0 := inner_vsub_vsub_of_dist_eq_of_dist_eq (by cc) (by cc), let b : fin 2 → V := ![c₂ -ᵥ c₁, p₂ -ᵥ p₁], have hb : linear_independent ℝ b, { refine linear_independent_of_ne_zero_of_inner_eq_zero _ _, { intro i, fin_cases i; simp [b, hc.symm, hp.symm] }, { intros i j hij, fin_cases i; fin_cases j; try { exact false.elim (hij rfl) }, { exact ho }, { rw real_inner_comm, exact ho } } }, have hbs : submodule.span ℝ (set.range b) = s.direction, { refine eq_of_le_of_findim_eq _ _, { rw [submodule.span_le, set.range_subset_iff], intro i, fin_cases i, { exact vsub_mem_direction hc₂s hc₁s }, { exact vsub_mem_direction hp₂s hp₁s } }, { rw [findim_span_eq_card hb, fintype.card_fin, hd] } }, have hv : ∀ v ∈ s.direction, ∃ t₁ t₂ : ℝ, v = t₁ • (c₂ -ᵥ c₁) + t₂ • (p₂ -ᵥ p₁), { intros v hv, have hr : set.range b = {c₂ -ᵥ c₁, p₂ -ᵥ p₁}, { have hu : (finset.univ : finset (fin 2)) = {0, 1}, by dec_trivial, rw [←fintype.coe_image_univ, hu], simp, refl }, rw [←hbs, hr, submodule.mem_span_insert] at hv, rcases hv with ⟨t₁, v', hv', hv⟩, rw submodule.mem_span_singleton at hv', rcases hv' with ⟨t₂, rfl⟩, exact ⟨t₁, t₂, hv⟩ }, rcases hv (p -ᵥ p₁) (vsub_mem_direction hps hp₁s) with ⟨t₁, t₂, hpt⟩, simp only [hpt, inner_add_right, inner_smul_right, ho, mul_zero, add_zero, mul_eq_zero, inner_self_eq_zero, vsub_eq_zero_iff_eq, hc.symm, or_false] at hop, rw [hop, zero_smul, zero_add, ←eq_vadd_iff_vsub_eq] at hpt, subst hpt, have hp' : (p₂ -ᵥ p₁ : V) ≠ 0, { simp [hp.symm] }, have hp₂ : dist ((1 : ℝ) • (p₂ -ᵥ p₁) +ᵥ p₁) c₁ = r₁, { simp [hp₂c₁] }, rw [←hp₁c₁, dist_smul_vadd_eq_dist _ _ hp'] at hpc₁ hp₂, simp only [one_ne_zero, false_or] at hp₂, rw hp₂.symm at hpc₁, cases hpc₁; simp [hpc₁] end /-- Distances `r₁` `r₂` of `p` from two different points `c₁` `c₂` determine at most two points `p₁` `p₂` in two-dimensional space (two circles intersect in at most two points). -/ lemma eq_of_dist_eq_of_dist_eq_of_findim_eq_two [finite_dimensional ℝ V] (hd : findim ℝ V = 2) {c₁ c₂ p₁ p₂ p : P} {r₁ r₂ : ℝ} (hc : c₁ ≠ c₂) (hp : p₁ ≠ p₂) (hp₁c₁ : dist p₁ c₁ = r₁) (hp₂c₁ : dist p₂ c₁ = r₁) (hpc₁ : dist p c₁ = r₁) (hp₁c₂ : dist p₁ c₂ = r₂) (hp₂c₂ : dist p₂ c₂ = r₂) (hpc₂ : dist p c₂ = r₂) : p = p₁ ∨ p = p₂ := begin have hd' : findim ℝ (⊤ : affine_subspace ℝ P).direction = 2, { rw [direction_top, findim_top], exact hd }, exact eq_of_dist_eq_of_dist_eq_of_mem_of_findim_eq_two hd' (mem_top ℝ V _) (mem_top ℝ V _) (mem_top ℝ V _) (mem_top ℝ V _) (mem_top ℝ V _) hc hp hp₁c₁ hp₂c₁ hpc₁ hp₁c₂ hp₂c₂ hpc₂ end variables {V} /-- The orthogonal projection of a point onto a nonempty affine subspace, whose direction is complete, as an unbundled function. This definition is only intended for use in setting up the bundled version `orthogonal_projection` and should not be used once that is defined. -/ def orthogonal_projection_fn {s : affine_subspace ℝ P} (hn : (s : set P).nonempty) (hc : is_complete (s.direction : set V)) (p : P) : P := classical.some $ inter_eq_singleton_of_nonempty_of_is_compl hn (mk'_nonempty p s.direction.orthogonal) ((direction_mk' p s.direction.orthogonal).symm ▸ submodule.is_compl_orthogonal_of_is_complete hc) /-- The intersection of the subspace and the orthogonal subspace through the given point is the `orthogonal_projection_fn` of that point onto the subspace. This lemma is only intended for use in setting up the bundled version and should not be used once that is defined. -/ lemma inter_eq_singleton_orthogonal_projection_fn {s : affine_subspace ℝ P} (hn : (s : set P).nonempty) (hc : is_complete (s.direction : set V)) (p : P) : (s : set P) ∩ (mk' p s.direction.orthogonal) = {orthogonal_projection_fn hn hc p} := classical.some_spec $ inter_eq_singleton_of_nonempty_of_is_compl hn (mk'_nonempty p s.direction.orthogonal) ((direction_mk' p s.direction.orthogonal).symm ▸ submodule.is_compl_orthogonal_of_is_complete hc) /-- The `orthogonal_projection_fn` lies in the given subspace. This lemma is only intended for use in setting up the bundled version and should not be used once that is defined. -/ lemma orthogonal_projection_fn_mem {s : affine_subspace ℝ P} (hn : (s : set P).nonempty) (hc : is_complete (s.direction : set V)) (p : P) : orthogonal_projection_fn hn hc p ∈ s := begin rw [←mem_coe, ←set.singleton_subset_iff, ←inter_eq_singleton_orthogonal_projection_fn], exact set.inter_subset_left _ _ end /-- The `orthogonal_projection_fn` lies in the orthogonal subspace. This lemma is only intended for use in setting up the bundled version and should not be used once that is defined. -/ lemma orthogonal_projection_fn_mem_orthogonal {s : affine_subspace ℝ P} (hn : (s : set P).nonempty) (hc : is_complete (s.direction : set V)) (p : P) : orthogonal_projection_fn hn hc p ∈ mk' p s.direction.orthogonal := begin rw [←mem_coe, ←set.singleton_subset_iff, ←inter_eq_singleton_orthogonal_projection_fn], exact set.inter_subset_right _ _ end /-- Subtracting `p` from its `orthogonal_projection_fn` produces a result in the orthogonal direction. This lemma is only intended for use in setting up the bundled version and should not be used once that is defined. -/ lemma orthogonal_projection_fn_vsub_mem_direction_orthogonal {s : affine_subspace ℝ P} (hn : (s : set P).nonempty) (hc : is_complete (s.direction : set V)) (p : P) : orthogonal_projection_fn hn hc p -ᵥ p ∈ s.direction.orthogonal := direction_mk' p s.direction.orthogonal ▸ vsub_mem_direction (orthogonal_projection_fn_mem_orthogonal hn hc p) (self_mem_mk' _ _) /-- The orthogonal projection of a point onto a nonempty affine subspace, whose direction is complete. The corresponding linear map (mapping a vector to the difference between the projections of two points whose difference is that vector) is the `orthogonal_projection` for real inner product spaces, onto the direction of the affine subspace being projected onto. For most purposes, `orthogonal_projection`, which removes the `nonempty` and `is_complete` hypotheses and is the identity map when either of those hypotheses fails, should be used instead. -/ def orthogonal_projection_of_nonempty_of_complete {s : affine_subspace ℝ P} (hn : (s : set P).nonempty) (hc : is_complete (s.direction : set V)) : affine_map ℝ P P := { to_fun := orthogonal_projection_fn hn hc, linear := orthogonal_projection s.direction, map_vadd' := λ p v, begin have hs : (orthogonal_projection s.direction) v +ᵥ orthogonal_projection_fn hn hc p ∈ s := vadd_mem_of_mem_direction (orthogonal_projection_mem hc _) (orthogonal_projection_fn_mem hn hc p), have ho : (orthogonal_projection s.direction) v +ᵥ orthogonal_projection_fn hn hc p ∈ mk' (v +ᵥ p) s.direction.orthogonal, { rw [←vsub_right_mem_direction_iff_mem (self_mem_mk' _ _) _, direction_mk', vsub_vadd_eq_vsub_sub, vadd_vsub_assoc, add_comm, add_sub_assoc], refine submodule.add_mem _ (orthogonal_projection_fn_vsub_mem_direction_orthogonal hn hc p) _, rw submodule.mem_orthogonal', intros w hw, rw [←neg_sub, inner_neg_left, orthogonal_projection_inner_eq_zero _ _ w hw, neg_zero] }, have hm : (orthogonal_projection s.direction) v +ᵥ orthogonal_projection_fn hn hc p ∈ ({orthogonal_projection_fn hn hc (v +ᵥ p)} : set P), { rw ←inter_eq_singleton_orthogonal_projection_fn hn hc (v +ᵥ p), exact set.mem_inter hs ho }, rw set.mem_singleton_iff at hm, exact hm.symm end } /-- The orthogonal projection of a point onto an affine subspace, which is expected to be nonempty and complete. The corresponding linear map (mapping a vector to the difference between the projections of two points whose difference is that vector) is the `orthogonal_projection` for real inner product spaces, onto the direction of the affine subspace being projected onto. If the subspace is empty or not complete, this uses the identity map instead. -/ def orthogonal_projection (s : affine_subspace ℝ P) : affine_map ℝ P P := if h : (s : set P).nonempty ∧ is_complete (s.direction : set V) then orthogonal_projection_of_nonempty_of_complete h.1 h.2 else affine_map.id ℝ P /-- The definition of `orthogonal_projection` using `if`. -/ lemma orthogonal_projection_def (s : affine_subspace ℝ P) : orthogonal_projection s = if h : (s : set P).nonempty ∧ is_complete (s.direction : set V) then orthogonal_projection_of_nonempty_of_complete h.1 h.2 else affine_map.id ℝ P := rfl @[simp] lemma orthogonal_projection_fn_eq {s : affine_subspace ℝ P} (hn : (s : set P).nonempty) (hc : is_complete (s.direction : set V)) (p : P) : orthogonal_projection_fn hn hc p = orthogonal_projection s p := by { rw [orthogonal_projection_def, dif_pos (and.intro hn hc)], refl } /-- The linear map corresponding to `orthogonal_projection`. -/ @[simp] lemma orthogonal_projection_linear {s : affine_subspace ℝ P} (hn : (s : set P).nonempty) : (orthogonal_projection s).linear = _root_.orthogonal_projection s.direction := begin by_cases hc : is_complete (s.direction : set V), { rw [orthogonal_projection_def, dif_pos (and.intro hn hc)], refl }, { simp [orthogonal_projection_def, _root_.orthogonal_projection_def, hn, hc] } end @[simp] lemma orthogonal_projection_of_nonempty_of_complete_eq {s : affine_subspace ℝ P} (hn : (s : set P).nonempty) (hc : is_complete (s.direction : set V)) (p : P) : orthogonal_projection_of_nonempty_of_complete hn hc p = orthogonal_projection s p := by rw [orthogonal_projection_def, dif_pos (and.intro hn hc)] /-- The intersection of the subspace and the orthogonal subspace through the given point is the `orthogonal_projection` of that point onto the subspace. -/ lemma inter_eq_singleton_orthogonal_projection {s : affine_subspace ℝ P} (hn : (s : set P).nonempty) (hc : is_complete (s.direction : set V)) (p : P) : (s : set P) ∩ (mk' p s.direction.orthogonal) = {orthogonal_projection s p} := begin rw ←orthogonal_projection_fn_eq hn hc, exact inter_eq_singleton_orthogonal_projection_fn hn hc p end /-- The `orthogonal_projection` lies in the given subspace. -/ lemma orthogonal_projection_mem {s : affine_subspace ℝ P} (hn : (s : set P).nonempty) (hc : is_complete (s.direction : set V)) (p : P) : orthogonal_projection s p ∈ s := begin rw ←orthogonal_projection_fn_eq hn hc, exact orthogonal_projection_fn_mem hn hc p end /-- The `orthogonal_projection` lies in the orthogonal subspace. -/ lemma orthogonal_projection_mem_orthogonal (s : affine_subspace ℝ P) (p : P) : orthogonal_projection s p ∈ mk' p s.direction.orthogonal := begin rw orthogonal_projection_def, split_ifs, { exact orthogonal_projection_fn_mem_orthogonal h.1 h.2 p }, { exact self_mem_mk' _ _ } end /-- Subtracting a point in the given subspace from the `orthogonal_projection` produces a result in the direction of the given subspace. -/ lemma orthogonal_projection_vsub_mem_direction {s : affine_subspace ℝ P} (hc : is_complete (s.direction : set V)) {p1 : P} (p2 : P) (hp1 : p1 ∈ s) : orthogonal_projection s p2 -ᵥ p1 ∈ s.direction := vsub_mem_direction (orthogonal_projection_mem ⟨p1, hp1⟩ hc p2) hp1 /-- Subtracting the `orthogonal_projection` from a point in the given subspace produces a result in the direction of the given subspace. -/ lemma vsub_orthogonal_projection_mem_direction {s : affine_subspace ℝ P} (hc : is_complete (s.direction : set V)) {p1 : P} (p2 : P) (hp1 : p1 ∈ s) : p1 -ᵥ orthogonal_projection s p2 ∈ s.direction := vsub_mem_direction hp1 (orthogonal_projection_mem ⟨p1, hp1⟩ hc p2) /-- A point equals its orthogonal projection if and only if it lies in the subspace. -/ lemma orthogonal_projection_eq_self_iff {s : affine_subspace ℝ P} (hn : (s : set P).nonempty) (hc : is_complete (s.direction : set V)) {p : P} : orthogonal_projection s p = p ↔ p ∈ s := begin split, { exact λ h, h ▸ orthogonal_projection_mem hn hc p }, { intro h, have hp : p ∈ ((s : set P) ∩ mk' p s.direction.orthogonal) := ⟨h, self_mem_mk' p _⟩, rw [inter_eq_singleton_orthogonal_projection hn hc p, set.mem_singleton_iff] at hp, exact hp.symm } end /-- Orthogonal projection is idempotent. -/ @[simp] lemma orthogonal_projection_orthogonal_projection (s : affine_subspace ℝ P) (p : P) : orthogonal_projection s (orthogonal_projection s p) = orthogonal_projection s p := begin by_cases h : (s : set P).nonempty ∧ is_complete (s.direction : set V), { rw orthogonal_projection_eq_self_iff h.1 h.2, exact orthogonal_projection_mem h.1 h.2 p }, { simp [orthogonal_projection_def, h] } end /-- The distance to a point's orthogonal projection is 0 iff it lies in the subspace. -/ lemma dist_orthogonal_projection_eq_zero_iff {s : affine_subspace ℝ P} (hn : (s : set P).nonempty) (hc : is_complete (s.direction : set V)) {p : P} : dist p (orthogonal_projection s p) = 0 ↔ p ∈ s := by rw [dist_comm, dist_eq_zero, orthogonal_projection_eq_self_iff hn hc] /-- The distance between a point and its orthogonal projection is nonzero if it does not lie in the subspace. -/ lemma dist_orthogonal_projection_ne_zero_of_not_mem {s : affine_subspace ℝ P} (hn : (s : set P).nonempty) (hc : is_complete (s.direction : set V)) {p : P} (hp : p ∉ s) : dist p (orthogonal_projection s p) ≠ 0 := mt (dist_orthogonal_projection_eq_zero_iff hn hc).mp hp /-- Subtracting `p` from its `orthogonal_projection` produces a result in the orthogonal direction. -/ lemma orthogonal_projection_vsub_mem_direction_orthogonal (s : affine_subspace ℝ P) (p : P) : orthogonal_projection s p -ᵥ p ∈ s.direction.orthogonal := begin rw orthogonal_projection_def, split_ifs, { exact orthogonal_projection_fn_vsub_mem_direction_orthogonal h.1 h.2 p }, { simp } end /-- Subtracting the `orthogonal_projection` from `p` produces a result in the orthogonal direction. -/ lemma vsub_orthogonal_projection_mem_direction_orthogonal (s : affine_subspace ℝ P) (p : P) : p -ᵥ orthogonal_projection s p ∈ s.direction.orthogonal := direction_mk' p s.direction.orthogonal ▸ vsub_mem_direction (self_mem_mk' _ _) (orthogonal_projection_mem_orthogonal s p) /-- Adding a vector to a point in the given subspace, then taking the orthogonal projection, produces the original point if the vector was in the orthogonal direction. -/ lemma orthogonal_projection_vadd_eq_self {s : affine_subspace ℝ P} (hc : is_complete (s.direction : set V)) {p : P} (hp : p ∈ s) {v : V} (hv : v ∈ s.direction.orthogonal) : orthogonal_projection s (v +ᵥ p) = p := begin have h := vsub_orthogonal_projection_mem_direction_orthogonal s (v +ᵥ p), rw [vadd_vsub_assoc, submodule.add_mem_iff_right _ hv] at h, refine (eq_of_vsub_eq_zero _).symm, refine submodule.disjoint_def.1 s.direction.orthogonal_disjoint _ _ h, exact vsub_mem_direction hp (orthogonal_projection_mem ⟨p, hp⟩ hc (v +ᵥ p)) end /-- Adding a vector to a point in the given subspace, then taking the orthogonal projection, produces the original point if the vector is a multiple of the result of subtracting a point's orthogonal projection from that point. -/ lemma orthogonal_projection_vadd_smul_vsub_orthogonal_projection {s : affine_subspace ℝ P} (hc : is_complete (s.direction : set V)) {p1 : P} (p2 : P) (r : ℝ) (hp : p1 ∈ s) : orthogonal_projection s (r • (p2 -ᵥ orthogonal_projection s p2 : V) +ᵥ p1) = p1 := orthogonal_projection_vadd_eq_self hc hp (submodule.smul_mem _ _ (vsub_orthogonal_projection_mem_direction_orthogonal s _)) /-- The square of the distance from a point in `s` to `p2` equals the sum of the squares of the distances of the two points to the `orthogonal_projection`. -/ lemma dist_square_eq_dist_orthogonal_projection_square_add_dist_orthogonal_projection_square {s : affine_subspace ℝ P} {p1 : P} (p2 : P) (hp1 : p1 ∈ s) : dist p1 p2 * dist p1 p2 = dist p1 (orthogonal_projection s p2) * dist p1 (orthogonal_projection s p2) + dist p2 (orthogonal_projection s p2) * dist p2 (orthogonal_projection s p2) := begin rw [metric_space.dist_comm p2 _, dist_eq_norm_vsub V p1 _, dist_eq_norm_vsub V p1 _, dist_eq_norm_vsub V _ p2, ← vsub_add_vsub_cancel p1 (orthogonal_projection s p2) p2, norm_add_square_eq_norm_square_add_norm_square_iff_real_inner_eq_zero], rw orthogonal_projection_def, split_ifs, { rw orthogonal_projection_of_nonempty_of_complete_eq, exact submodule.inner_right_of_mem_orthogonal (vsub_orthogonal_projection_mem_direction h.2 p2 hp1) (orthogonal_projection_vsub_mem_direction_orthogonal s p2) }, { simp } end /-- The square of the distance between two points constructed by adding multiples of the same orthogonal vector to points in the same subspace. -/ lemma dist_square_smul_orthogonal_vadd_smul_orthogonal_vadd {s : affine_subspace ℝ P} {p1 p2 : P} (hp1 : p1 ∈ s) (hp2 : p2 ∈ s) (r1 r2 : ℝ) {v : V} (hv : v ∈ s.direction.orthogonal) : dist (r1 • v +ᵥ p1) (r2 • v +ᵥ p2) * dist (r1 • v +ᵥ p1) (r2 • v +ᵥ p2) = dist p1 p2 * dist p1 p2 + (r1 - r2) * (r1 - r2) * (∥v∥ * ∥v∥) := calc dist (r1 • v +ᵥ p1) (r2 • v +ᵥ p2) * dist (r1 • v +ᵥ p1) (r2 • v +ᵥ p2) = ∥(p1 -ᵥ p2) + (r1 - r2) • v∥ * ∥(p1 -ᵥ p2) + (r1 - r2) • v∥ : by { rw [dist_eq_norm_vsub V (r1 • v +ᵥ p1), vsub_vadd_eq_vsub_sub, vadd_vsub_assoc, sub_smul], abel } ... = ∥p1 -ᵥ p2∥ * ∥p1 -ᵥ p2∥ + ∥(r1 - r2) • v∥ * ∥(r1 - r2) • v∥ : norm_add_square_eq_norm_square_add_norm_square_real (submodule.inner_right_of_mem_orthogonal (vsub_mem_direction hp1 hp2) (submodule.smul_mem _ _ hv)) ... = ∥(p1 -ᵥ p2 : V)∥ * ∥(p1 -ᵥ p2 : V)∥ + abs (r1 - r2) * abs (r1 - r2) * ∥v∥ * ∥v∥ : by { rw [norm_smul, real.norm_eq_abs], ring } ... = dist p1 p2 * dist p1 p2 + (r1 - r2) * (r1 - r2) * (∥v∥ * ∥v∥) : by { rw [dist_eq_norm_vsub V p1, abs_mul_abs_self, mul_assoc] } /-- Reflection in an affine subspace, which is expected to be nonempty and complete. The word "reflection" is sometimes understood to mean specifically reflection in a codimension-one subspace, and sometimes more generally to cover operations such as reflection in a point. The definition here, of reflection in an affine subspace, is a more general sense of the word that includes both those common cases. If the subspace is empty or not complete, `orthogonal_projection` is defined as the identity map, which results in `reflection` being the identity map in that case as well. -/ def reflection (s : affine_subspace ℝ P) : P ≃ᵢ P := { to_fun := λ p, (orthogonal_projection s p -ᵥ p) +ᵥ orthogonal_projection s p, inv_fun := λ p, (orthogonal_projection s p -ᵥ p) +ᵥ orthogonal_projection s p, left_inv := λ p, by simp [vsub_vadd_eq_vsub_sub, -orthogonal_projection_linear], right_inv := λ p, by simp [vsub_vadd_eq_vsub_sub, -orthogonal_projection_linear], isometry_to_fun := begin dsimp only, rw isometry_emetric_iff_metric, intros p₁ p₂, rw [←mul_self_inj_of_nonneg dist_nonneg dist_nonneg, dist_eq_norm_vsub V ((orthogonal_projection s p₁ -ᵥ p₁) +ᵥ orthogonal_projection s p₁), dist_eq_norm_vsub V p₁, ←inner_self_eq_norm_square, ←inner_self_eq_norm_square], by_cases h : (s : set P).nonempty ∧ is_complete (s.direction : set V), { calc ⟪(orthogonal_projection s p₁ -ᵥ p₁ +ᵥ orthogonal_projection s p₁ -ᵥ (orthogonal_projection s p₂ -ᵥ p₂ +ᵥ orthogonal_projection s p₂)), (orthogonal_projection s p₁ -ᵥ p₁ +ᵥ orthogonal_projection s p₁ -ᵥ (orthogonal_projection s p₂ -ᵥ p₂ +ᵥ orthogonal_projection s p₂))⟫ = ⟪(_root_.orthogonal_projection s.direction (p₁ -ᵥ p₂)) + _root_.orthogonal_projection s.direction (p₁ -ᵥ p₂) - (p₁ -ᵥ p₂), _root_.orthogonal_projection s.direction (p₁ -ᵥ p₂) + _root_.orthogonal_projection s.direction (p₁ -ᵥ p₂) - (p₁ -ᵥ p₂)⟫ : by rw [vsub_vadd_eq_vsub_sub, vadd_vsub_assoc, add_comm, add_sub_assoc, ←vsub_vadd_eq_vsub_sub, vsub_vadd_comm, vsub_vadd_eq_vsub_sub, ←add_sub_assoc, ←affine_map.linear_map_vsub, orthogonal_projection_linear h.1] ... = -4 * inner (p₁ -ᵥ p₂ - (_root_.orthogonal_projection s.direction (p₁ -ᵥ p₂))) (_root_.orthogonal_projection s.direction (p₁ -ᵥ p₂)) + ⟪p₁ -ᵥ p₂, p₁ -ᵥ p₂⟫ : by { simp [inner_sub_left, inner_sub_right, inner_add_left, inner_add_right, real_inner_comm (p₁ -ᵥ p₂)], ring } ... = -4 * 0 + ⟪p₁ -ᵥ p₂, p₁ -ᵥ p₂⟫ : by rw orthogonal_projection_inner_eq_zero s.direction _ _ (_root_.orthogonal_projection_mem h.2 _) ... = ⟪p₁ -ᵥ p₂, p₁ -ᵥ p₂⟫ : by simp }, { simp [orthogonal_projection_def, h] } end } /-- The result of reflecting. -/ lemma reflection_apply (s : affine_subspace ℝ P) (p : P) : reflection s p = (orthogonal_projection s p -ᵥ p) +ᵥ orthogonal_projection s p := rfl /-- Reflection is its own inverse. -/ @[simp] lemma reflection_symm (s : affine_subspace ℝ P) : (reflection s).symm = reflection s := rfl /-- Reflecting twice in the same subspace. -/ @[simp] lemma reflection_reflection (s : affine_subspace ℝ P) (p : P) : reflection s (reflection s p) = p := (reflection s).left_inv p /-- Reflection is involutive. -/ lemma reflection_involutive (s : affine_subspace ℝ P) : function.involutive (reflection s) := reflection_reflection s /-- A point is its own reflection if and only if it is in the subspace. -/ lemma reflection_eq_self_iff {s : affine_subspace ℝ P} (hn : (s : set P).nonempty) (hc : is_complete (s.direction : set V)) (p : P) : reflection s p = p ↔ p ∈ s := begin rw [←orthogonal_projection_eq_self_iff hn hc, reflection_apply], split, { intro h, rw [←@vsub_eq_zero_iff_eq V, vadd_vsub_assoc, ←two_smul ℝ (orthogonal_projection s p -ᵥ p), smul_eq_zero] at h, norm_num at h, exact h }, { intro h, simp [h] } end /-- Reflecting a point in two subspaces produces the same result if and only if the point has the same orthogonal projection in each of those subspaces. -/ lemma reflection_eq_iff_orthogonal_projection_eq (s₁ s₂ : affine_subspace ℝ P) (p : P) : reflection s₁ p = reflection s₂ p ↔ orthogonal_projection s₁ p = orthogonal_projection s₂ p := begin rw [reflection_apply, reflection_apply], split, { intro h, rw [←@vsub_eq_zero_iff_eq V, vsub_vadd_eq_vsub_sub, vadd_vsub_assoc, add_comm, add_sub_assoc, vsub_sub_vsub_cancel_right, ←two_smul ℝ (orthogonal_projection s₁ p -ᵥ orthogonal_projection s₂ p), smul_eq_zero] at h, norm_num at h, exact h }, { intro h, rw h } end /-- The distance between `p₁` and the reflection of `p₂` equals that between the reflection of `p₁` and `p₂`. -/ lemma dist_reflection (s : affine_subspace ℝ P) (p₁ p₂ : P) : dist p₁ (reflection s p₂) = dist (reflection s p₁) p₂ := begin conv_lhs { rw ←reflection_reflection s p₁ }, exact (reflection s).dist_eq _ _ end /-- A point in the subspace is equidistant from another point and its reflection. -/ lemma dist_reflection_eq_of_mem (s : affine_subspace ℝ P) {p₁ : P} (hp₁ : p₁ ∈ s) (p₂ : P) : dist p₁ (reflection s p₂) = dist p₁ p₂ := begin by_cases h : (s : set P).nonempty ∧ is_complete (s.direction : set V), { rw ←reflection_eq_self_iff h.1 h.2 p₁ at hp₁, conv_lhs { rw ←hp₁ }, exact (reflection s).dist_eq _ _ }, { simp [reflection_apply, orthogonal_projection_def, h] } end /-- The reflection of a point in a subspace is contained in any larger subspace containing both the point and the subspace reflected in. -/ lemma reflection_mem_of_le_of_mem {s₁ s₂ : affine_subspace ℝ P} (hle : s₁ ≤ s₂) {p : P} (hp : p ∈ s₂) : reflection s₁ p ∈ s₂ := begin rw [reflection_apply], by_cases h : (s₁ : set P).nonempty ∧ is_complete (s₁.direction : set V), { have ho : orthogonal_projection s₁ p ∈ s₂ := hle (orthogonal_projection_mem h.1 h.2 p), exact vadd_mem_of_mem_direction (vsub_mem_direction ho hp) ho }, { simpa [reflection_apply, orthogonal_projection_def, h] } end /-- Reflecting an orthogonal vector plus a point in the subspace produces the negation of that vector plus the point. -/ lemma reflection_orthogonal_vadd {s : affine_subspace ℝ P} (hc : is_complete (s.direction : set V)) {p : P} (hp : p ∈ s) {v : V} (hv : v ∈ s.direction.orthogonal) : reflection s (v +ᵥ p) = -v +ᵥ p := begin rw [reflection_apply, orthogonal_projection_vadd_eq_self hc hp hv, vsub_vadd_eq_vsub_sub], simp end /-- Reflecting a vector plus a point in the subspace produces the negation of that vector plus the point if the vector is a multiple of the result of subtracting a point's orthogonal projection from that point. -/ lemma reflection_vadd_smul_vsub_orthogonal_projection {s : affine_subspace ℝ P} (hc : is_complete (s.direction : set V)) {p₁ : P} (p₂ : P) (r : ℝ) (hp₁ : p₁ ∈ s) : reflection s (r • (p₂ -ᵥ orthogonal_projection s p₂) +ᵥ p₁) = -(r • (p₂ -ᵥ orthogonal_projection s p₂)) +ᵥ p₁ := reflection_orthogonal_vadd hc hp₁ (submodule.smul_mem _ _ (vsub_orthogonal_projection_mem_direction_orthogonal s _)) omit V /-- A set of points is cospherical if they are equidistant from some point. In two dimensions, this is the same thing as being concyclic. -/ def cospherical (ps : set P) : Prop := ∃ (center : P) (radius : ℝ), ∀ p ∈ ps, dist p center = radius /-- The definition of `cospherical`. -/ lemma cospherical_def (ps : set P) : cospherical ps ↔ ∃ (center : P) (radius : ℝ), ∀ p ∈ ps, dist p center = radius := iff.rfl /-- A subset of a cospherical set is cospherical. -/ lemma cospherical_subset {ps₁ ps₂ : set P} (hs : ps₁ ⊆ ps₂) (hc : cospherical ps₂) : cospherical ps₁ := begin rcases hc with ⟨c, r, hcr⟩, exact ⟨c, r, λ p hp, hcr p (hs hp)⟩ end include V /-- The empty set is cospherical. -/ lemma cospherical_empty : cospherical (∅ : set P) := begin use add_torsor.nonempty.some, simp, end omit V /-- A single point is cospherical. -/ lemma cospherical_singleton (p : P) : cospherical ({p} : set P) := begin use p, simp end include V /-- Two points are cospherical. -/ lemma cospherical_insert_singleton (p₁ p₂ : P) : cospherical ({p₁, p₂} : set P) := begin use [(2⁻¹ : ℝ) • (p₂ -ᵥ p₁) +ᵥ p₁, (2⁻¹ : ℝ) * (dist p₂ p₁)], intro p, rw [set.mem_insert_iff, set.mem_singleton_iff], rintro ⟨_|_⟩, { rw [dist_eq_norm_vsub V p₁, vsub_vadd_eq_vsub_sub, vsub_self, zero_sub, norm_neg, norm_smul, dist_eq_norm_vsub V p₂], simp }, { rw [H, dist_eq_norm_vsub V p₂, vsub_vadd_eq_vsub_sub, dist_eq_norm_vsub V p₂], conv_lhs { congr, congr, rw ←one_smul ℝ (p₂ -ᵥ p₁ : V) }, rw [←sub_smul, norm_smul], norm_num } end /-- Any three points in a cospherical set are affinely independent. -/ lemma cospherical.affine_independent {s : set P} (hs : cospherical s) {p : fin 3 → P} (hps : set.range p ⊆ s) (hpi : function.injective p) : affine_independent ℝ p := begin rw affine_independent_iff_not_collinear, intro hc, rw collinear_iff_of_mem ℝ (set.mem_range_self (0 : fin 3)) at hc, rcases hc with ⟨v, hv⟩, rw set.forall_range_iff at hv, have hv0 : v ≠ 0, { intro h, have he : p 1 = p 0, by simpa [h] using hv 1, exact (dec_trivial : (1 : fin 3) ≠ 0) (hpi he) }, rcases hs with ⟨c, r, hs⟩, have hs' := λ i, hs (p i) (set.mem_of_mem_of_subset (set.mem_range_self _) hps), choose f hf using hv, have hsd : ∀ i, dist ((f i • v) +ᵥ p 0) c = r, { intro i, rw ←hf, exact hs' i }, have hf0 : f 0 = 0, { have hf0' := hf 0, rw [eq_comm, ←@vsub_eq_zero_iff_eq V, vadd_vsub, smul_eq_zero] at hf0', simpa [hv0] using hf0' }, have hfi : function.injective f, { intros i j h, have hi := hf i, rw [h, ←hf j] at hi, exact hpi hi }, simp_rw [←hsd 0, hf0, zero_smul, zero_vadd, dist_smul_vadd_eq_dist (p 0) c hv0] at hsd, have hfn0 : ∀ i, i ≠ 0 → f i ≠ 0 := λ i, (hfi.ne_iff' hf0).2, have hfn0' : ∀ i, i ≠ 0 → f i = (-2) * ⟪v, (p 0 -ᵥ c)⟫ / ⟪v, v⟫, { intros i hi, have hsdi := hsd i, simpa [hfn0, hi] using hsdi }, have hf12 : f 1 = f 2, { rw [hfn0' 1 dec_trivial, hfn0' 2 dec_trivial] }, exact (dec_trivial : (1 : fin 3) ≠ 2) (hfi hf12) end end euclidean_geometry
d99bd594a666c1ca879015e9d5de7088a06359b4
6b45072eb2b3db3ecaace2a7a0241ce81f815787
/tools/tactic/tactic.lean
5ef8d06e6aed93424bbe750b20190bc734d8a11d
[]
no_license
avigad/library_dev
27b47257382667b5eb7e6476c4f5b0d685dd3ddc
9d8ac7c7798ca550874e90fed585caad030bbfac
refs/heads/master
1,610,452,468,791
1,500,712,839,000
1,500,713,478,000
69,311,142
1
0
null
1,474,942,903,000
1,474,942,902,000
null
UTF-8
Lean
false
false
735
lean
/- Copyright (c) 2017 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad Some useful tactics. -/ open expr tactic namespace tactic /- call (assert n t) with a fresh name n. -/ meta def assert_fresh (t : expr) : tactic expr := do n ← get_unused_name `h none, assert n t /- call (assertv n t v) with a fresh name n. -/ meta def assertv_fresh (t : expr) (v : expr) : tactic expr := do h ← get_unused_name `h none, assertv h t v -- returns the number of hypotheses reverted meta def revert_all : tactic ℕ := do ctx ← local_context, revert_lst ctx namespace interactive meta def revert_all := tactic.revert_all end interactive end tactic
934021461dcc2bcda5a233c56a61c96d2266f7e5
367134ba5a65885e863bdc4507601606690974c1
/test/pi_simp.lean
84e6bf92780232afef572c13d2f3fa423b065273
[ "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
648
lean
/- Copyright (c) 2020 Yury G. Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Yury G. Kudryashov -/ import algebra.group.pi /-! Test if `simp` can use a lemma about `pi.has_one` to simplify `1` coming from `pi.group` -/ variables {I : Type*} {f : Π i : I, Type*} namespace test def eval_default [inhabited I] (F : Π i, f i) : f (default I) := F (default I) @[simp] lemma eval_default_one [inhabited I] [Π i, has_one (f i)] : eval_default (1 : Π i, f i) = 1 := rfl example [inhabited I] [Π i, group (f i)] (F : Π i, f i) : eval_default (F⁻¹ * F) = 1 := by simp end test
0704e3760cae7ae63826a3c411c36251ce2f7e76
2eab05920d6eeb06665e1a6df77b3157354316ad
/src/topology/uniform_space/uniform_embedding.lean
e3d5d43229cbbe5c77bee93c59664ad22afcc9e7
[ "Apache-2.0" ]
permissive
ayush1801/mathlib
78949b9f789f488148142221606bf15c02b960d2
ce164e28f262acbb3de6281b3b03660a9f744e3c
refs/heads/master
1,692,886,907,941
1,635,270,866,000
1,635,270,866,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
22,508
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, Sébastien Gouëzel, Patrick Massot -/ import topology.uniform_space.cauchy import topology.uniform_space.separation import topology.dense_embedding /-! # Uniform embeddings of uniform spaces. Extension of uniform continuous functions. -/ open filter topological_space set classical open_locale classical uniformity topological_space filter section variables {α : Type*} {β : Type*} {γ : Type*} [uniform_space α] [uniform_space β] [uniform_space γ] universe u structure uniform_inducing (f : α → β) : Prop := (comap_uniformity : comap (λx:α×α, (f x.1, f x.2)) (𝓤 β) = 𝓤 α) lemma uniform_inducing.mk' {f : α → β} (h : ∀ s, s ∈ 𝓤 α ↔ ∃ t ∈ 𝓤 β, ∀ x y : α, (f x, f y) ∈ t → (x, y) ∈ s) : uniform_inducing f := ⟨by simp [eq_comm, filter.ext_iff, subset_def, h]⟩ lemma uniform_inducing.comp {g : β → γ} (hg : uniform_inducing g) {f : α → β} (hf : uniform_inducing f) : uniform_inducing (g ∘ f) := ⟨ by rw [show (λ (x : α × α), ((g ∘ f) x.1, (g ∘ f) x.2)) = (λ y : β × β, (g y.1, g y.2)) ∘ (λ x : α × α, (f x.1, f x.2)), by ext ; simp, ← filter.comap_comap, hg.1, hf.1]⟩ lemma uniform_inducing.basis_uniformity {f : α → β} (hf : uniform_inducing f) {ι : Sort*} {p : ι → Prop} {s : ι → set (β × β)} (H : (𝓤 β).has_basis p s) : (𝓤 α).has_basis p (λ i, prod.map f f ⁻¹' s i) := hf.1 ▸ H.comap _ structure uniform_embedding (f : α → β) extends uniform_inducing f : Prop := (inj : function.injective f) lemma uniform_embedding_subtype_val {p : α → Prop} : uniform_embedding (subtype.val : subtype p → α) := { comap_uniformity := rfl, inj := subtype.val_injective } lemma uniform_embedding_subtype_coe {p : α → Prop} : uniform_embedding (coe : subtype p → α) := uniform_embedding_subtype_val lemma uniform_embedding_set_inclusion {s t : set α} (hst : s ⊆ t) : uniform_embedding (inclusion hst) := { comap_uniformity := by { erw [uniformity_subtype, uniformity_subtype, comap_comap], congr }, inj := inclusion_injective hst } lemma uniform_embedding.comp {g : β → γ} (hg : uniform_embedding g) {f : α → β} (hf : uniform_embedding f) : uniform_embedding (g ∘ f) := { inj := hg.inj.comp hf.inj, ..hg.to_uniform_inducing.comp hf.to_uniform_inducing } theorem uniform_embedding_def {f : α → β} : uniform_embedding f ↔ function.injective f ∧ ∀ s, s ∈ 𝓤 α ↔ ∃ t ∈ 𝓤 β, ∀ x y : α, (f x, f y) ∈ t → (x, y) ∈ s := begin split, { rintro ⟨⟨h⟩, h'⟩, rw [eq_comm, filter.ext_iff] at h, simp [*, subset_def] }, { rintro ⟨h, h'⟩, refine uniform_embedding.mk ⟨_⟩ h, rw [eq_comm, filter.ext_iff], simp [*, subset_def] } end theorem uniform_embedding_def' {f : α → β} : uniform_embedding f ↔ function.injective f ∧ uniform_continuous f ∧ ∀ s, s ∈ 𝓤 α → ∃ t ∈ 𝓤 β, ∀ x y : α, (f x, f y) ∈ t → (x, y) ∈ s := by simp only [uniform_embedding_def, uniform_continuous_def]; exact ⟨λ ⟨I, H⟩, ⟨I, λ s su, (H _).2 ⟨s, su, λ x y, id⟩, λ s, (H s).1⟩, λ ⟨I, H₁, H₂⟩, ⟨I, λ s, ⟨H₂ s, λ ⟨t, tu, h⟩, mem_of_superset (H₁ t tu) (λ ⟨a, b⟩, h a b)⟩⟩⟩ /-- If the domain of a `uniform_inducing` map `f` is a `separated_space`, then `f` is injective, hence it is a `uniform_embedding`. -/ theorem uniform_inducing.uniform_embedding [separated_space α] {f : α → β} (hf : uniform_inducing f) : uniform_embedding f := ⟨hf, λ x y h, eq_of_uniformity_basis (hf.basis_uniformity (𝓤 β).basis_sets) $ λ s hs, mem_preimage.2 $ mem_uniformity_of_eq hs h⟩ /-- If a map `f : α → β` sends any two distinct points to point that are **not** related by a fixed `s ∈ 𝓤 β`, then `f` is uniform inducing with respect to the discrete uniformity on `α`: the preimage of `𝓤 β` under `prod.map f f` is the principal filter generated by the diagonal in `α × α`. -/ lemma comap_uniformity_of_spaced_out {α} {f : α → β} {s : set (β × β)} (hs : s ∈ 𝓤 β) (hf : pairwise (λ x y, (f x, f y) ∉ s)) : comap (prod.map f f) (𝓤 β) = 𝓟 id_rel := begin refine le_antisymm _ (@refl_le_uniformity α (uniform_space.comap f ‹_›)), calc comap (prod.map f f) (𝓤 β) ≤ comap (prod.map f f) (𝓟 s) : comap_mono (le_principal_iff.2 hs) ... = 𝓟 (prod.map f f ⁻¹' s) : comap_principal ... ≤ 𝓟 id_rel : principal_mono.2 _, rintro ⟨x, y⟩, simpa [not_imp_not] using hf x y end /-- If a map `f : α → β` sends any two distinct points to point that are **not** related by a fixed `s ∈ 𝓤 β`, then `f` is a uniform embedding with respect to the discrete uniformity on `α`. -/ lemma uniform_embedding_of_spaced_out {α} {f : α → β} {s : set (β × β)} (hs : s ∈ 𝓤 β) (hf : pairwise (λ x y, (f x, f y) ∉ s)) : @uniform_embedding α β ⊥ ‹_› f := begin letI : uniform_space α := ⊥, haveI : separated_space α := separated_iff_t2.2 infer_instance, exact uniform_inducing.uniform_embedding ⟨comap_uniformity_of_spaced_out hs hf⟩ end lemma uniform_inducing.uniform_continuous {f : α → β} (hf : uniform_inducing f) : uniform_continuous f := by simp [uniform_continuous, hf.comap_uniformity.symm, tendsto_comap] lemma uniform_inducing.uniform_continuous_iff {f : α → β} {g : β → γ} (hg : uniform_inducing g) : uniform_continuous f ↔ uniform_continuous (g ∘ f) := by { dsimp only [uniform_continuous, tendsto], rw [← hg.comap_uniformity, ← map_le_iff_le_comap, filter.map_map] } lemma uniform_inducing.inducing {f : α → β} (h : uniform_inducing f) : inducing f := begin refine ⟨eq_of_nhds_eq_nhds $ assume a, _ ⟩, rw [nhds_induced, nhds_eq_uniformity, nhds_eq_uniformity, ← h.comap_uniformity, comap_lift'_eq, comap_lift'_eq2]; { refl <|> exact monotone_preimage } end lemma uniform_inducing.prod {α' : Type*} {β' : Type*} [uniform_space α'] [uniform_space β'] {e₁ : α → α'} {e₂ : β → β'} (h₁ : uniform_inducing e₁) (h₂ : uniform_inducing e₂) : uniform_inducing (λp:α×β, (e₁ p.1, e₂ p.2)) := ⟨by simp [(∘), uniformity_prod, h₁.comap_uniformity.symm, h₂.comap_uniformity.symm, comap_inf, comap_comap]⟩ lemma uniform_inducing.dense_inducing {f : α → β} (h : uniform_inducing f) (hd : dense_range f) : dense_inducing f := { dense := hd, induced := h.inducing.induced } lemma uniform_embedding.embedding {f : α → β} (h : uniform_embedding f) : embedding f := { induced := h.to_uniform_inducing.inducing.induced, inj := h.inj } lemma uniform_embedding.dense_embedding {f : α → β} (h : uniform_embedding f) (hd : dense_range f) : dense_embedding f := { dense := hd, inj := h.inj, induced := h.embedding.induced } lemma closed_embedding_of_spaced_out {α} [topological_space α] [discrete_topology α] [separated_space β] {f : α → β} {s : set (β × β)} (hs : s ∈ 𝓤 β) (hf : pairwise (λ x y, (f x, f y) ∉ s)) : closed_embedding f := begin unfreezingI { rcases (discrete_topology.eq_bot α) with rfl }, letI : uniform_space α := ⊥, exact { closed_range := is_closed_range_of_spaced_out hs hf, .. (uniform_embedding_of_spaced_out hs hf).embedding } end lemma closure_image_mem_nhds_of_uniform_inducing {s : set (α×α)} {e : α → β} (b : β) (he₁ : uniform_inducing e) (he₂ : dense_inducing e) (hs : s ∈ 𝓤 α) : ∃a, closure (e '' {a' | (a, a') ∈ s}) ∈ 𝓝 b := have s ∈ comap (λp:α×α, (e p.1, e p.2)) (𝓤 β), from he₁.comap_uniformity.symm ▸ hs, let ⟨t₁, ht₁u, ht₁⟩ := this in have ht₁ : ∀p:α×α, (e p.1, e p.2) ∈ t₁ → p ∈ s, from ht₁, let ⟨t₂, ht₂u, ht₂s, ht₂c⟩ := comp_symm_of_uniformity ht₁u in let ⟨t, htu, hts, htc⟩ := comp_symm_of_uniformity ht₂u in have preimage e {b' | (b, b') ∈ t₂} ∈ comap e (𝓝 b), from preimage_mem_comap $ mem_nhds_left b ht₂u, let ⟨a, (ha : (b, e a) ∈ t₂)⟩ := (he₂.comap_nhds_ne_bot _).nonempty_of_mem this in have ∀b' (s' : set (β × β)), (b, b') ∈ t → s' ∈ 𝓤 β → ({y : β | (b', y) ∈ s'} ∩ e '' {a' : α | (a, a') ∈ s}).nonempty, from assume b' s' hb' hs', have preimage e {b'' | (b', b'') ∈ s' ∩ t} ∈ comap e (𝓝 b'), from preimage_mem_comap $ mem_nhds_left b' $ inter_mem hs' htu, let ⟨a₂, ha₂s', ha₂t⟩ := (he₂.comap_nhds_ne_bot _).nonempty_of_mem this in have (e a, e a₂) ∈ t₁, from ht₂c $ prod_mk_mem_comp_rel (ht₂s ha) $ htc $ prod_mk_mem_comp_rel hb' ha₂t, have e a₂ ∈ {b'':β | (b', b'') ∈ s'} ∩ e '' {a' | (a, a') ∈ s}, from ⟨ha₂s', mem_image_of_mem _ $ ht₁ (a, a₂) this⟩, ⟨_, this⟩, have ∀b', (b, b') ∈ t → ne_bot (𝓝 b' ⊓ 𝓟 (e '' {a' | (a, a') ∈ s})), begin intros b' hb', rw [nhds_eq_uniformity, lift'_inf_principal_eq, lift'_ne_bot_iff], exact assume s, this b' s hb', exact monotone_inter monotone_preimage monotone_const end, have ∀b', (b, b') ∈ t → b' ∈ closure (e '' {a' | (a, a') ∈ s}), from assume b' hb', by rw [closure_eq_cluster_pts]; exact this b' hb', ⟨a, (𝓝 b).sets_of_superset (mem_nhds_left b htu) this⟩ lemma uniform_embedding_subtype_emb (p : α → Prop) {e : α → β} (ue : uniform_embedding e) (de : dense_embedding e) : uniform_embedding (dense_embedding.subtype_emb p e) := { comap_uniformity := by simp [comap_comap, (∘), dense_embedding.subtype_emb, uniformity_subtype, ue.comap_uniformity.symm], inj := (de.subtype p).inj } lemma uniform_embedding.prod {α' : Type*} {β' : Type*} [uniform_space α'] [uniform_space β'] {e₁ : α → α'} {e₂ : β → β'} (h₁ : uniform_embedding e₁) (h₂ : uniform_embedding e₂) : uniform_embedding (λp:α×β, (e₁ p.1, e₂ p.2)) := { inj := h₁.inj.prod_map h₂.inj, ..h₁.to_uniform_inducing.prod h₂.to_uniform_inducing } lemma is_complete_of_complete_image {m : α → β} {s : set α} (hm : uniform_inducing m) (hs : is_complete (m '' s)) : is_complete s := begin intros f hf hfs, rw le_principal_iff at hfs, obtain ⟨_, ⟨x, hx, rfl⟩, hyf⟩ : ∃ y ∈ m '' s, map m f ≤ 𝓝 y, from hs (f.map m) (hf.map hm.uniform_continuous) (le_principal_iff.2 (image_mem_map hfs)), rw [map_le_iff_le_comap, ← nhds_induced, ← hm.inducing.induced] at hyf, exact ⟨x, hx, hyf⟩ end lemma is_complete.complete_space_coe {s : set α} (hs : is_complete s) : complete_space s := complete_space_iff_is_complete_univ.2 $ is_complete_of_complete_image uniform_embedding_subtype_coe.to_uniform_inducing $ by simp [hs] /-- A set is complete iff its image under a uniform inducing map is complete. -/ lemma is_complete_image_iff {m : α → β} {s : set α} (hm : uniform_inducing m) : is_complete (m '' s) ↔ is_complete s := begin refine ⟨is_complete_of_complete_image hm, λ c, _⟩, haveI : complete_space s := c.complete_space_coe, set m' : s → β := m ∘ coe, suffices : is_complete (range m'), by rwa [range_comp, subtype.range_coe] at this, have hm' : uniform_inducing m' := hm.comp uniform_embedding_subtype_coe.to_uniform_inducing, intros f hf hfm, rw filter.le_principal_iff at hfm, have cf' : cauchy (comap m' f) := hf.comap' hm'.comap_uniformity.le (ne_bot.comap_of_range_mem hf.1 hfm), rcases complete_space.complete cf' with ⟨x, hx⟩, rw [hm'.inducing.nhds_eq_comap, comap_le_comap_iff hfm] at hx, use [m' x, mem_range_self _, hx] end lemma complete_space_iff_is_complete_range {f : α → β} (hf : uniform_inducing f) : complete_space α ↔ is_complete (range f) := by rw [complete_space_iff_is_complete_univ, ← is_complete_image_iff hf, image_univ] lemma uniform_inducing.is_complete_range [complete_space α] {f : α → β} (hf : uniform_inducing f) : is_complete (range f) := (complete_space_iff_is_complete_range hf).1 ‹_› lemma complete_space_congr {e : α ≃ β} (he : uniform_embedding e) : complete_space α ↔ complete_space β := by rw [complete_space_iff_is_complete_range he.to_uniform_inducing, e.range_eq_univ, complete_space_iff_is_complete_univ] lemma complete_space_coe_iff_is_complete {s : set α} : complete_space s ↔ is_complete s := (complete_space_iff_is_complete_range uniform_embedding_subtype_coe.to_uniform_inducing).trans $ by rw [subtype.range_coe] lemma is_closed.complete_space_coe [complete_space α] {s : set α} (hs : is_closed s) : complete_space s := hs.is_complete.complete_space_coe lemma complete_space_extension {m : β → α} (hm : uniform_inducing m) (dense : dense_range m) (h : ∀f:filter β, cauchy f → ∃x:α, map m f ≤ 𝓝 x) : complete_space α := ⟨assume (f : filter α), assume hf : cauchy f, let p : set (α × α) → set α → set α := λs t, {y : α| ∃x:α, x ∈ t ∧ (x, y) ∈ s}, g := (𝓤 α).lift (λs, f.lift' (p s)) in have mp₀ : monotone p, from assume a b h t s ⟨x, xs, xa⟩, ⟨x, xs, h xa⟩, have mp₁ : ∀{s}, monotone (p s), from assume s a b h x ⟨y, ya, yxs⟩, ⟨y, h ya, yxs⟩, have f ≤ g, from le_infi $ assume s, le_infi $ assume hs, le_infi $ assume t, le_infi $ assume ht, le_principal_iff.mpr $ mem_of_superset ht $ assume x hx, ⟨x, hx, refl_mem_uniformity hs⟩, have ne_bot g, from hf.left.mono this, have ne_bot (comap m g), from comap_ne_bot $ assume t ht, let ⟨t', ht', ht_mem⟩ := (mem_lift_sets $ monotone_lift' monotone_const mp₀).mp ht in let ⟨t'', ht'', ht'_sub⟩ := (mem_lift'_sets mp₁).mp ht_mem in let ⟨x, (hx : x ∈ t'')⟩ := hf.left.nonempty_of_mem ht'' in have h₀ : ne_bot (𝓝[range m] x), from dense.nhds_within_ne_bot x, have h₁ : {y | (x, y) ∈ t'} ∈ 𝓝[range m] x, from @mem_inf_of_left α (𝓝 x) (𝓟 (range m)) _ $ mem_nhds_left x ht', have h₂ : range m ∈ 𝓝[range m] x, from @mem_inf_of_right α (𝓝 x) (𝓟 (range m)) _ $ subset.refl _, have {y | (x, y) ∈ t'} ∩ range m ∈ 𝓝[range m] x, from @inter_mem α (𝓝[range m] x) _ _ h₁ h₂, let ⟨y, xyt', b, b_eq⟩ := h₀.nonempty_of_mem this in ⟨b, b_eq.symm ▸ ht'_sub ⟨x, hx, xyt'⟩⟩, have cauchy g, from ⟨‹ne_bot g›, assume s hs, let ⟨s₁, hs₁, (comp_s₁ : comp_rel s₁ s₁ ⊆ s)⟩ := comp_mem_uniformity_sets hs, ⟨s₂, hs₂, (comp_s₂ : comp_rel s₂ s₂ ⊆ s₁)⟩ := comp_mem_uniformity_sets hs₁, ⟨t, ht, (prod_t : set.prod t t ⊆ s₂)⟩ := mem_prod_same_iff.mp (hf.right hs₂) in have hg₁ : p (preimage prod.swap s₁) t ∈ g, from mem_lift (symm_le_uniformity hs₁) $ @mem_lift' α α f _ t ht, have hg₂ : p s₂ t ∈ g, from mem_lift hs₂ $ @mem_lift' α α f _ t ht, have hg : set.prod (p (preimage prod.swap s₁) t) (p s₂ t) ∈ g ×ᶠ g, from @prod_mem_prod α α _ _ g g hg₁ hg₂, (g ×ᶠ g).sets_of_superset hg (assume ⟨a, b⟩ ⟨⟨c₁, c₁t, hc₁⟩, ⟨c₂, c₂t, hc₂⟩⟩, have (c₁, c₂) ∈ set.prod t t, from ⟨c₁t, c₂t⟩, comp_s₁ $ prod_mk_mem_comp_rel hc₁ $ comp_s₂ $ prod_mk_mem_comp_rel (prod_t this) hc₂)⟩, have cauchy (filter.comap m g), from ‹cauchy g›.comap' (le_of_eq hm.comap_uniformity) ‹_›, let ⟨x, (hx : map m (filter.comap m g) ≤ 𝓝 x)⟩ := h _ this in have cluster_pt x (map m (filter.comap m g)), from (le_nhds_iff_adhp_of_cauchy (this.map hm.uniform_continuous)).mp hx, have cluster_pt x g, from this.mono map_comap_le, ⟨x, calc f ≤ g : by assumption ... ≤ 𝓝 x : le_nhds_of_cauchy_adhp ‹cauchy g› this⟩⟩ lemma totally_bounded_preimage {f : α → β} {s : set β} (hf : uniform_embedding f) (hs : totally_bounded s) : totally_bounded (f ⁻¹' s) := λ t ht, begin rw ← hf.comap_uniformity at ht, rcases mem_comap.2 ht with ⟨t', ht', ts⟩, rcases totally_bounded_iff_subset.1 (totally_bounded_subset (image_preimage_subset f s) hs) _ ht' with ⟨c, cs, hfc, hct⟩, refine ⟨f ⁻¹' c, hfc.preimage (hf.inj.inj_on _), λ x h, _⟩, have := hct (mem_image_of_mem f h), simp at this ⊢, rcases this with ⟨z, zc, zt⟩, rcases cs zc with ⟨y, yc, rfl⟩, exact ⟨y, zc, ts (by exact zt)⟩ end end lemma uniform_embedding_comap {α : Type*} {β : Type*} {f : α → β} [u : uniform_space β] (hf : function.injective f) : @uniform_embedding α β (uniform_space.comap f u) u f := @uniform_embedding.mk _ _ (uniform_space.comap f u) _ _ (@uniform_inducing.mk _ _ (uniform_space.comap f u) _ _ rfl) hf section uniform_extension variables {α : Type*} {β : Type*} {γ : Type*} [uniform_space α] [uniform_space β] [uniform_space γ] {e : β → α} (h_e : uniform_inducing e) (h_dense : dense_range e) {f : β → γ} (h_f : uniform_continuous f) local notation `ψ` := (h_e.dense_inducing h_dense).extend f lemma uniformly_extend_exists [complete_space γ] (a : α) : ∃c, tendsto f (comap e (𝓝 a)) (𝓝 c) := let de := (h_e.dense_inducing h_dense) in have cauchy (𝓝 a), from cauchy_nhds, have cauchy (comap e (𝓝 a)), from this.comap' (le_of_eq h_e.comap_uniformity) (de.comap_nhds_ne_bot _), have cauchy (map f (comap e (𝓝 a))), from this.map h_f, complete_space.complete this lemma uniform_extend_subtype [complete_space γ] {p : α → Prop} {e : α → β} {f : α → γ} {b : β} {s : set α} (hf : uniform_continuous (λx:subtype p, f x.val)) (he : uniform_embedding e) (hd : ∀x:β, x ∈ closure (range e)) (hb : closure (e '' s) ∈ 𝓝 b) (hs : is_closed s) (hp : ∀x∈s, p x) : ∃c, tendsto f (comap e (𝓝 b)) (𝓝 c) := have de : dense_embedding e, from he.dense_embedding hd, have de' : dense_embedding (dense_embedding.subtype_emb p e), by exact de.subtype p, have ue' : uniform_embedding (dense_embedding.subtype_emb p e), from uniform_embedding_subtype_emb _ he de, have b ∈ closure (e '' {x | p x}), from (closure_mono $ monotone_image $ hp) (mem_of_mem_nhds hb), let ⟨c, (hc : tendsto (f ∘ subtype.val) (comap (dense_embedding.subtype_emb p e) (𝓝 ⟨b, this⟩)) (𝓝 c))⟩ := uniformly_extend_exists ue'.to_uniform_inducing de'.dense hf _ in begin rw [nhds_subtype_eq_comap] at hc, simp [comap_comap] at hc, change (tendsto (f ∘ @subtype.val α p) (comap (e ∘ @subtype.val α p) (𝓝 b)) (𝓝 c)) at hc, rw [←comap_comap, tendsto_comap'_iff] at hc, exact ⟨c, hc⟩, exact ⟨_, hb, assume x, begin change e x ∈ (closure (e '' s)) → x ∈ range subtype.val, rw [← closure_induced, mem_closure_iff_cluster_pt, cluster_pt, ne_bot_iff, nhds_induced, ← de.to_dense_inducing.nhds_eq_comap, ← mem_closure_iff_nhds_ne_bot, hs.closure_eq], exact assume hxs, ⟨⟨x, hp x hxs⟩, rfl⟩, end⟩ end variables [separated_space γ] lemma uniformly_extend_of_ind (b : β) : ψ (e b) = f b := dense_inducing.extend_eq_at _ b h_f.continuous.continuous_at lemma uniformly_extend_unique {g : α → γ} (hg : ∀ b, g (e b) = f b) (hc : continuous g) : ψ = g := dense_inducing.extend_unique _ hg hc include h_f lemma uniformly_extend_spec [complete_space γ] (a : α) : tendsto f (comap e (𝓝 a)) (𝓝 (ψ a)) := let de := (h_e.dense_inducing h_dense) in begin by_cases ha : a ∈ range e, { rcases ha with ⟨b, rfl⟩, rw [uniformly_extend_of_ind _ _ h_f, ← de.nhds_eq_comap], exact h_f.continuous.tendsto _ }, { simp only [dense_inducing.extend, dif_neg ha], exact tendsto_nhds_lim (uniformly_extend_exists h_e h_dense h_f _) } end lemma uniform_continuous_uniformly_extend [cγ : complete_space γ] : uniform_continuous ψ := assume d 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 have h_pnt : ∀{a m}, m ∈ 𝓝 a → ∃c, c ∈ f '' preimage e m ∧ (c, ψ a) ∈ s ∧ (ψ a, c) ∈ s, from assume a m hm, have nb : ne_bot (map f (comap e (𝓝 a))), from ((h_e.dense_inducing h_dense).comap_nhds_ne_bot _).map _, have (f '' preimage e m) ∩ ({c | (c, ψ a) ∈ s } ∩ {c | (ψ a, c) ∈ s }) ∈ map f (comap e (𝓝 a)), from inter_mem (image_mem_map $ preimage_mem_comap $ hm) (uniformly_extend_spec h_e h_dense h_f _ (inter_mem (mem_nhds_right _ hs) (mem_nhds_left _ hs))), nb.nonempty_of_mem this, have preimage (λp:β×β, (f p.1, f p.2)) s ∈ 𝓤 β, from h_f hs, have preimage (λp:β×β, (f p.1, f p.2)) s ∈ comap (λx:β×β, (e x.1, e x.2)) (𝓤 α), by rwa [h_e.comap_uniformity.symm] at this, let ⟨t, ht, ts⟩ := this in show preimage (λp:(α×α), (ψ p.1, ψ p.2)) d ∈ 𝓤 α, from (𝓤 α).sets_of_superset (interior_mem_uniformity ht) $ assume ⟨x₁, x₂⟩ hx_t, have 𝓝 (x₁, x₂) ≤ 𝓟 (interior t), from is_open_iff_nhds.mp is_open_interior (x₁, x₂) hx_t, have interior t ∈ 𝓝 x₁ ×ᶠ 𝓝 x₂, by rwa [nhds_prod_eq, le_principal_iff] at this, let ⟨m₁, hm₁, m₂, hm₂, (hm : set.prod m₁ m₂ ⊆ interior t)⟩ := mem_prod_iff.mp this in let ⟨a, ha₁, _, ha₂⟩ := h_pnt hm₁ in let ⟨b, hb₁, hb₂, _⟩ := h_pnt hm₂ in have set.prod (preimage e m₁) (preimage e m₂) ⊆ preimage (λp:(β×β), (f p.1, f p.2)) s, from calc _ ⊆ preimage (λp:(β×β), (e p.1, e p.2)) (interior t) : preimage_mono hm ... ⊆ preimage (λp:(β×β), (e p.1, e p.2)) t : preimage_mono interior_subset ... ⊆ preimage (λp:(β×β), (f p.1, f p.2)) s : ts, have set.prod (f '' preimage e m₁) (f '' preimage e m₂) ⊆ s, from calc set.prod (f '' preimage e m₁) (f '' preimage e m₂) = (λp:(β×β), (f p.1, f p.2)) '' (set.prod (preimage e m₁) (preimage e m₂)) : prod_image_image_eq ... ⊆ (λp:(β×β), (f p.1, f p.2)) '' preimage (λp:(β×β), (f p.1, f p.2)) s : monotone_image this ... ⊆ s : image_subset_iff.mpr $ subset.refl _, have (a, b) ∈ s, from @this (a, b) ⟨ha₁, hb₁⟩, hs_comp $ show (ψ x₁, ψ x₂) ∈ comp_rel s (comp_rel s s), from ⟨a, ha₂, ⟨b, this, hb₂⟩⟩ end uniform_extension
bb909edee0f36d12e30c73540cdd8d9b12ad0c1d
4efff1f47634ff19e2f786deadd394270a59ecd2
/src/number_theory/sum_four_squares.lean
c73110316dd857574e7a4a8ae204ea686d67be7e
[ "Apache-2.0" ]
permissive
agjftucker/mathlib
d634cd0d5256b6325e3c55bb7fb2403548371707
87fe50de17b00af533f72a102d0adefe4a2285e8
refs/heads/master
1,625,378,131,941
1,599,166,526,000
1,599,166,526,000
160,748,509
0
0
Apache-2.0
1,544,141,789,000
1,544,141,789,000
null
UTF-8
Lean
false
false
11,873
lean
/- Copyright (c) 2019 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes ## Lagrange's four square theorem The main result in this file is `sum_four_squares`, a proof that every natural number is the sum of four square numbers. # Implementation Notes The proof used is close to Lagrange's original proof. -/ import data.zmod.basic import field_theory.finite import data.int.parity import data.fintype.card open finset polynomial finite_field equiv open_locale big_operators namespace int lemma sum_two_squares_of_two_mul_sum_two_squares {m x y : ℤ} (h : 2 * m = x^2 + y^2) : m = ((x - y) / 2) ^ 2 + ((x + y) / 2) ^ 2 := have (x^2 + y^2).even, by simp [h.symm, even_mul], have hxaddy : (x + y).even, by simpa [pow_two] with parity_simps, have hxsuby : (x - y).even, by simpa [pow_two] with parity_simps, have (x^2 + y^2) % 2 = 0, by simp [h.symm], (mul_right_inj' (show (2*2 : ℤ) ≠ 0, from dec_trivial)).1 $ calc 2 * 2 * m = (x - y)^2 + (x + y)^2 : by rw [mul_assoc, h]; ring ... = (2 * ((x - y) / 2))^2 + (2 * ((x + y) / 2))^2 : by rw [int.mul_div_cancel' hxsuby, int.mul_div_cancel' hxaddy] ... = 2 * 2 * (((x - y) / 2) ^ 2 + ((x + y) / 2) ^ 2) : by simp [mul_add, pow_succ, mul_comm, mul_assoc, mul_left_comm] lemma exists_sum_two_squares_add_one_eq_k (p : ℕ) [hp : fact p.prime] : ∃ (a b : ℤ) (k : ℕ), a^2 + b^2 + 1 = k * p ∧ k < p := hp.eq_two_or_odd.elim (λ hp2, hp2.symm ▸ ⟨1, 0, 1, rfl, dec_trivial⟩) $ λ hp1, let ⟨a, b, hab⟩ := zmod.sum_two_squares p (-1) in have hab' : (p : ℤ) ∣ a.val_min_abs ^ 2 + b.val_min_abs ^ 2 + 1, from (char_p.int_cast_eq_zero_iff (zmod p) p _).1 $ by simpa [eq_neg_iff_add_eq_zero] using hab, let ⟨k, hk⟩ := hab' in have hk0 : 0 ≤ k, from nonneg_of_mul_nonneg_left (by rw ← hk; exact (add_nonneg (add_nonneg (pow_two_nonneg _) (pow_two_nonneg _)) zero_le_one)) (int.coe_nat_pos.2 hp.pos), ⟨a.val_min_abs, b.val_min_abs, k.nat_abs, by rw [hk, int.nat_abs_of_nonneg hk0, mul_comm], lt_of_mul_lt_mul_left (calc p * k.nat_abs = a.val_min_abs.nat_abs ^ 2 + b.val_min_abs.nat_abs ^ 2 + 1 : by rw [← int.coe_nat_inj', int.coe_nat_add, int.coe_nat_add, int.coe_nat_pow, int.coe_nat_pow, int.nat_abs_pow_two, int.nat_abs_pow_two, int.coe_nat_one, hk, int.coe_nat_mul, int.nat_abs_of_nonneg hk0] ... ≤ (p / 2) ^ 2 + (p / 2)^2 + 1 : add_le_add (add_le_add (nat.pow_le_pow_of_le_left (zmod.nat_abs_val_min_abs_le _) _) (nat.pow_le_pow_of_le_left (zmod.nat_abs_val_min_abs_le _) _)) (le_refl _) ... < (p / 2) ^ 2 + (p / 2)^ 2 + (p % 2)^2 + ((2 * (p / 2)^2 + (4 * (p / 2) * (p % 2)))) : by rw [hp1, nat.one_pow, mul_one]; exact (lt_add_iff_pos_right _).2 (add_pos_of_nonneg_of_pos (nat.zero_le _) (mul_pos dec_trivial (nat.div_pos hp.two_le dec_trivial))) ... = p * p : by { conv_rhs { rw [← nat.mod_add_div p 2] }, ring }) (show 0 ≤ p, from nat.zero_le _)⟩ end int namespace nat open int open_locale classical private lemma sum_four_squares_of_two_mul_sum_four_squares {m a b c d : ℤ} (h : a^2 + b^2 + c^2 + d^2 = 2 * m) : ∃ w x y z : ℤ, w^2 + x^2 + y^2 + z^2 = m := have ∀ f : fin 4 → zmod 2, (f 0)^2 + (f 1)^2 + (f 2)^2 + (f 3)^2 = 0 → ∃ i : (fin 4), (f i)^2 + f (swap i 0 1)^2 = 0 ∧ f (swap i 0 2)^2 + f (swap i 0 3)^2 = 0, from dec_trivial, let f : fin 4 → ℤ := vector.nth (a::b::c::d::vector.nil) in let ⟨i, hσ⟩ := this (coe ∘ f) (by rw [← @zero_mul (zmod 2) _ m, ← show ((2 : ℤ) : zmod 2) = 0, from rfl, ← int.cast_mul, ← h]; simp only [int.cast_add, int.cast_pow]; refl) in let σ := swap i 0 in have h01 : 2 ∣ f (σ 0) ^ 2 + f (σ 1) ^ 2, from (char_p.int_cast_eq_zero_iff (zmod 2) 2 _).1 $ by simpa [σ] using hσ.1, have h23 : 2 ∣ f (σ 2) ^ 2 + f (σ 3) ^ 2, from (char_p.int_cast_eq_zero_iff (zmod 2) 2 _).1 $ by simpa using hσ.2, let ⟨x, hx⟩ := h01 in let ⟨y, hy⟩ := h23 in ⟨(f (σ 0) - f (σ 1)) / 2, (f (σ 0) + f (σ 1)) / 2, (f (σ 2) - f (σ 3)) / 2, (f (σ 2) + f (σ 3)) / 2, begin rw [← int.sum_two_squares_of_two_mul_sum_two_squares hx.symm, add_assoc, ← int.sum_two_squares_of_two_mul_sum_two_squares hy.symm, ← mul_right_inj' (show (2 : ℤ) ≠ 0, from dec_trivial), ← h, mul_add, ← hx, ← hy], have : ∑ x, f (σ x)^2 = ∑ x, f x^2, { conv_rhs { rw ← finset.sum_equiv σ } }, have fin4univ : (univ : finset (fin 4)).1 = 0::1::2::3::0, from dec_trivial, simpa [finset.sum_eq_multiset_sum, fin4univ, multiset.sum_cons, f, add_assoc] end⟩ private lemma prime_sum_four_squares (p : ℕ) [hp : _root_.fact p.prime] : ∃ a b c d : ℤ, a^2 + b^2 + c^2 + d^2 = p := have hm : ∃ m < p, 0 < m ∧ ∃ a b c d : ℤ, a^2 + b^2 + c^2 + d^2 = m * p, from let ⟨a, b, k, hk⟩ := exists_sum_two_squares_add_one_eq_k p in ⟨k, hk.2, nat.pos_of_ne_zero $ (λ hk0, by { rw [hk0, int.coe_nat_zero, zero_mul] at hk, exact ne_of_gt (show a^2 + b^2 + 1 > 0, from add_pos_of_nonneg_of_pos (add_nonneg (pow_two_nonneg _) (pow_two_nonneg _)) zero_lt_one) hk.1 }), a, b, 1, 0, by simpa [_root_.pow_two] using hk.1⟩, let m := nat.find hm in let ⟨a, b, c, d, (habcd : a^2 + b^2 + c^2 + d^2 = m * p)⟩ := (nat.find_spec hm).snd.2 in by haveI hm0 : _root_.fact (0 < m) := (nat.find_spec hm).snd.1; exact have hmp : m < p, from (nat.find_spec hm).fst, m.mod_two_eq_zero_or_one.elim (λ hm2 : m % 2 = 0, let ⟨k, hk⟩ := (nat.dvd_iff_mod_eq_zero _ _).2 hm2 in have hk0 : 0 < k, from nat.pos_of_ne_zero $ λ _, by { simp [*, lt_irrefl] at * }, have hkm : k < m, { rw [hk, two_mul], exact (lt_add_iff_pos_left _).2 hk0 }, false.elim $ nat.find_min hm hkm ⟨lt_trans hkm hmp, hk0, sum_four_squares_of_two_mul_sum_four_squares (show a^2 + b^2 + c^2 + d^2 = 2 * (k * p), by { rw [habcd, hk, int.coe_nat_mul, mul_assoc], simp })⟩) (λ hm2 : m % 2 = 1, if hm1 : m = 1 then ⟨a, b, c, d, by simp only [hm1, habcd, int.coe_nat_one, one_mul]⟩ else let w := (a : zmod m).val_min_abs, x := (b : zmod m).val_min_abs, y := (c : zmod m).val_min_abs, z := (d : zmod m).val_min_abs in have hnat_abs : w^2 + x^2 + y^2 + z^2 = (w.nat_abs^2 + x.nat_abs^2 + y.nat_abs ^2 + z.nat_abs ^ 2 : ℕ), by simp [_root_.pow_two], have hwxyzlt : w^2 + x^2 + y^2 + z^2 < m^2, from calc w^2 + x^2 + y^2 + z^2 = (w.nat_abs^2 + x.nat_abs^2 + y.nat_abs ^2 + z.nat_abs ^ 2 : ℕ) : hnat_abs ... ≤ ((m / 2) ^ 2 + (m / 2) ^ 2 + (m / 2) ^ 2 + (m / 2) ^ 2 : ℕ) : int.coe_nat_le.2 $ add_le_add (add_le_add (add_le_add (nat.pow_le_pow_of_le_left (zmod.nat_abs_val_min_abs_le _) _) (nat.pow_le_pow_of_le_left (zmod.nat_abs_val_min_abs_le _) _)) (nat.pow_le_pow_of_le_left (zmod.nat_abs_val_min_abs_le _) _)) (nat.pow_le_pow_of_le_left (zmod.nat_abs_val_min_abs_le _) _) ... = 4 * (m / 2 : ℕ) ^ 2 : by simp [_root_.pow_two, bit0, bit1, mul_add, add_mul, add_assoc] ... < 4 * (m / 2 : ℕ) ^ 2 + ((4 * (m / 2) : ℕ) * (m % 2 : ℕ) + (m % 2 : ℕ)^2) : (lt_add_iff_pos_right _).2 (by { rw [hm2, int.coe_nat_one, _root_.one_pow, mul_one], exact add_pos_of_nonneg_of_pos (int.coe_nat_nonneg _) zero_lt_one }) ... = m ^ 2 : by { conv_rhs {rw [← nat.mod_add_div m 2]}, simp [-nat.mod_add_div, mul_add, add_mul, bit0, bit1, mul_comm, mul_assoc, mul_left_comm, _root_.pow_add, add_comm, add_left_comm] }, have hwxyzabcd : ((w^2 + x^2 + y^2 + z^2 : ℤ) : zmod m) = ((a^2 + b^2 + c^2 + d^2 : ℤ) : zmod m), by simp [w, x, y, z, pow_two], have hwxyz0 : ((w^2 + x^2 + y^2 + z^2 : ℤ) : zmod m) = 0, by rw [hwxyzabcd, habcd, int.cast_mul, cast_coe_nat, zmod.cast_self, zero_mul], let ⟨n, hn⟩ := ((char_p.int_cast_eq_zero_iff _ m _).1 hwxyz0) in have hn0 : 0 < n.nat_abs, from int.nat_abs_pos_of_ne_zero (λ hn0, have hwxyz0 : (w.nat_abs^2 + x.nat_abs^2 + y.nat_abs^2 + z.nat_abs^2 : ℕ) = 0, by { rw [← int.coe_nat_eq_zero, ← hnat_abs], rwa [hn0, mul_zero] at hn }, have habcd0 : (m : ℤ) ∣ a ∧ (m : ℤ) ∣ b ∧ (m : ℤ) ∣ c ∧ (m : ℤ) ∣ d, by simpa [@add_eq_zero_iff_eq_zero_of_nonneg ℤ _ _ _ (pow_two_nonneg _) (pow_two_nonneg _), nat.pow_two, w, x, y, z, (char_p.int_cast_eq_zero_iff _ m _), and.assoc] using hwxyz0, let ⟨ma, hma⟩ := habcd0.1, ⟨mb, hmb⟩ := habcd0.2.1, ⟨mc, hmc⟩ := habcd0.2.2.1, ⟨md, hmd⟩ := habcd0.2.2.2 in have hmdvdp : m ∣ p, from int.coe_nat_dvd.1 ⟨ma^2 + mb^2 + mc^2 + md^2, (mul_right_inj' (show (m : ℤ) ≠ 0, from int.coe_nat_ne_zero_iff_pos.2 hm0)).1 $ by { rw [← habcd, hma, hmb, hmc, hmd], ring }⟩, (hp.2 _ hmdvdp).elim hm1 (λ hmeqp, by simpa [lt_irrefl, hmeqp] using hmp)), have hawbxcydz : ((m : ℕ) : ℤ) ∣ a * w + b * x + c * y + d * z, from (char_p.int_cast_eq_zero_iff (zmod m) m _).1 $ by { rw [← hwxyz0], simp, ring }, have haxbwczdy : ((m : ℕ) : ℤ) ∣ a * x - b * w - c * z + d * y, from (char_p.int_cast_eq_zero_iff (zmod m) m _).1 $ by { simp [sub_eq_add_neg], ring }, have haybzcwdx : ((m : ℕ) : ℤ) ∣ a * y + b * z - c * w - d * x, from (char_p.int_cast_eq_zero_iff (zmod m) m _).1 $ by { simp [sub_eq_add_neg], ring }, have hazbycxdw : ((m : ℕ) : ℤ) ∣ a * z - b * y + c * x - d * w, from (char_p.int_cast_eq_zero_iff (zmod m) m _).1 $ by { simp [sub_eq_add_neg], ring }, let ⟨s, hs⟩ := hawbxcydz, ⟨t, ht⟩ := haxbwczdy, ⟨u, hu⟩ := haybzcwdx, ⟨v, hv⟩ := hazbycxdw in have hn_nonneg : 0 ≤ n, from nonneg_of_mul_nonneg_left (by { erw [← hn], repeat {try {refine add_nonneg _ _}, try {exact pow_two_nonneg _}} }) (int.coe_nat_pos.2 hm0), have hnm : n.nat_abs < m, from int.coe_nat_lt.1 (lt_of_mul_lt_mul_left (by { rw [int.nat_abs_of_nonneg hn_nonneg, ← hn, ← _root_.pow_two], exact hwxyzlt }) (int.coe_nat_nonneg m)), have hstuv : s^2 + t^2 + u^2 + v^2 = n.nat_abs * p, from (mul_right_inj' (show (m^2 : ℤ) ≠ 0, from pow_ne_zero 2 (int.coe_nat_ne_zero_iff_pos.2 hm0))).1 $ calc (m : ℤ)^2 * (s^2 + t^2 + u^2 + v^2) = ((m : ℕ) * s)^2 + ((m : ℕ) * t)^2 + ((m : ℕ) * u)^2 + ((m : ℕ) * v)^2 : by { simp [_root_.mul_pow], ring } ... = (w^2 + x^2 + y^2 + z^2) * (a^2 + b^2 + c^2 + d^2) : by { simp only [hs.symm, ht.symm, hu.symm, hv.symm], ring } ... = _ : by { rw [hn, habcd, int.nat_abs_of_nonneg hn_nonneg], dsimp [m], ring }, false.elim $ nat.find_min hm hnm ⟨lt_trans hnm hmp, hn0, s, t, u, v, hstuv⟩) lemma sum_four_squares : ∀ n : ℕ, ∃ a b c d : ℕ, a^2 + b^2 + c^2 + d^2 = n | 0 := ⟨0, 0, 0, 0, rfl⟩ | 1 := ⟨1, 0, 0, 0, rfl⟩ | n@(k+2) := have hm : _root_.fact (min_fac (k+2)).prime := min_fac_prime dec_trivial, have n / min_fac n < n := factors_lemma, let ⟨a, b, c, d, h₁⟩ := show ∃ a b c d : ℤ, a^2 + b^2 + c^2 + d^2 = min_fac n, by exactI prime_sum_four_squares (min_fac (k+2)) in let ⟨w, x, y, z, h₂⟩ := sum_four_squares (n / min_fac n) in ⟨(a * x - b * w - c * z + d * y).nat_abs, (a * y + b * z - c * w - d * x).nat_abs, (a * z - b * y + c * x - d * w).nat_abs, (a * w + b * x + c * y + d * z).nat_abs, begin rw [← int.coe_nat_inj', ← nat.mul_div_cancel' (min_fac_dvd (k+2)), int.coe_nat_mul, ← h₁, ← h₂], simp, ring end⟩ end nat
4afdc31863cb9b3542e3453f0402f9eacfaa9ab4
fcf3ffa92a3847189ca669cb18b34ef6b2ec2859
/src/world5/level7.lean
991c65cd9b1b1ab2411cf460412175dfeee46e4d
[ "Apache-2.0" ]
permissive
nomoid/lean-proofs
4a80a97888699dee42b092b7b959b22d9aa0c066
b9f03a24623d1a1d111d6c2bbf53c617e2596d6a
refs/heads/master
1,674,955,317,080
1,607,475,706,000
1,607,475,706,000
314,104,281
0
0
null
null
null
null
UTF-8
Lean
false
false
160
lean
example (P Q F : Type) : (P → Q) → ((Q → F) → (P → F)) := begin intro pq, intro qf, intro p, apply qf, apply pq, exact p, end
4300b716d47a1449727db2fb974f49e457b65727
5fbbd711f9bfc21ee168f46a4be146603ece8835
/lean/natural_number_game/proposition/3.lean
28146a6ab3dcac36b8b47b497991716e4c3273bd
[ "LicenseRef-scancode-warranty-disclaimer" ]
no_license
goedel-gang/maths
22596f71e3fde9c088e59931f128a3b5efb73a2c
a20a6f6a8ce800427afd595c598a5ad43da1408d
refs/heads/master
1,623,055,941,960
1,621,599,441,000
1,621,599,441,000
169,335,840
0
0
null
null
null
null
UTF-8
Lean
false
false
167
lean
lemma maze (P Q R S T U: Prop) (p : P) (h : P → Q) (i : Q → R) (j : Q → T) (k : S → T) (l : T → U) : U := begin cc, -- instead of exact blah blah blah end
33ca6bf83fbb6b1634b46254b893a3e6d5d8c0bb
e0b0b1648286e442507eb62344760d5cd8d13f2d
/tests/lean/rewrite.lean
16d893a646cc70e9672673c4d7fb76725ceba7f6
[ "Apache-2.0" ]
permissive
MULXCODE/lean4
743ed389e05e26e09c6a11d24607ad5a697db39b
4675817a9e89824eca37192364cd47a4027c6437
refs/heads/master
1,682,231,879,857
1,620,423,501,000
1,620,423,501,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,403
lean
axiom appendNil {α} (as : List α) : as ++ [] = as axiom appendAssoc {α} (as bs cs : List α) : (as ++ bs) ++ cs = as ++ (bs ++ cs) axiom reverseEq {α} (as : List α) : as.reverse.reverse = as theorem ex1 {α} (as bs : List α) : as.reverse.reverse ++ [] ++ [] ++ bs ++ bs = as ++ (bs ++ bs) := by rw [appendNil, appendNil, reverseEq]; traceState; rw [←appendAssoc]; theorem ex2 {α} (as bs : List α) : as.reverse.reverse ++ [] ++ [] ++ bs ++ bs = as ++ (bs ++ bs) := by rewrite [reverseEq, reverseEq]; -- Error on second reverseEq done axiom zeroAdd (x : Nat) : 0 + x = x theorem ex2 (x y z) (h₁ : 0 + x = y) (h₂ : 0 + y = z) : x = z := by rewrite [zeroAdd] at h₁ h₂; traceState; subst x; subst y; exact rfl theorem ex3 (x y z) (h₁ : 0 + x = y) (h₂ : 0 + y = z) : x = z := by rewrite [zeroAdd] at *; subst x; subst y; exact rfl theorem ex4 (x y z) (h₁ : 0 + x = y) (h₂ : 0 + y = z) : x = z := by rewrite [appendAssoc] at *; -- Error done theorem ex5 (m n k : Nat) (h : 0 + n = m) (h : k = m) : k = n := by rw [zeroAdd] at *; traceState; -- `h` is still a name for `h : k = m` refine Eq.trans h ?hole; apply Eq.symm; assumption theorem ex6 (p q r : Prop) (h₁ : q → r) (h₂ : p ↔ q) (h₃ : p) : r := by rw [←h₂] at h₁; exact h₁ h₃ theorem ex7 (p q r : Prop) (h₁ : q → r) (h₂ : p ↔ q) (h₃ : p) : r := by rw [h₂] at h₃; exact h₁ h₃
960927993550cc1e72241339accfaf878800f6d1
e0f9ba56b7fedc16ef8697f6caeef5898b435143
/src/tactic/derive_inhabited.lean
c7cd1307e78014f731d862be0a6ce63447408d44
[ "Apache-2.0" ]
permissive
anrddh/mathlib
6a374da53c7e3a35cb0298b0cd67824efef362b4
a4266a01d2dcb10de19369307c986d038c7bb6a6
refs/heads/master
1,656,710,827,909
1,589,560,456,000
1,589,560,456,000
264,271,800
0
0
Apache-2.0
1,589,568,062,000
1,589,568,061,000
null
UTF-8
Lean
false
false
2,327
lean
/- Copyright (c) 2020 Gabriel Ebner. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. -/ import logic.basic /-! # Derive handler for `inhabited` instances This file introduces a derive handle to automatically generate `inhabited` instances for structures and inductives. We also add various `inhabited` instances for types in the core library. -/ namespace tactic /-- Tries to derive an `inhabited` instance for inductives and structures. For example: ``` @[derive inhabited] structure foo := (a : ℕ := 42) (b : list ℕ) ``` Here, `@[derive inhabited]` adds the instance `foo.inhabited`, which is defined as `⟨⟨42, default (list ℕ)⟩⟩`. For inductives, the default value is the first constructor. If the structure/inductive has a type parameter `α`, then the generated instance will have an argument `inhabited α`, even if it is not used. (This is due to the implementation using `instance_derive_handler`.) -/ @[derive_handler] meta def inhabited_instance : derive_handler := instance_derive_handler ``inhabited $ do applyc ``inhabited.mk, `[refine {..}] <|> (constructor >> skip), all_goals $ do applyc ``default <|> (do s ← read, fail $ to_fmt "could not find inhabited instance for:\n" ++ to_fmt s) end tactic attribute [derive inhabited] vm_decl_kind vm_obj_kind tactic.new_goals tactic.transparency tactic.apply_cfg smt_pre_config ematch_config cc_config smt_config rsimp.config tactic.dunfold_config tactic.dsimp_config tactic.unfold_proj_config tactic.simp_intros_config tactic.delta_config tactic.simp_config tactic.rewrite_cfg interactive.loc tactic.unfold_config param_info subsingleton_info fun_info format.color pos environment.projection_info reducibility_hints congr_arg_kind ulift plift string_imp string.iterator_imp rbnode.color ordering unification_constraint pprod unification_hint doc_category tactic_doc_entry instance {α} : inhabited (bin_tree α) := ⟨bin_tree.empty⟩ instance : inhabited unsigned := ⟨0⟩ instance : inhabited string.iterator := string.iterator_imp.inhabited instance {α} : inhabited (rbnode α) := ⟨rbnode.leaf⟩ instance {α lt} : inhabited (rbtree α lt) := ⟨mk_rbtree _ _⟩ instance {α β lt} : inhabited (rbmap α β lt) := ⟨mk_rbmap _ _ _⟩
9073c89dd281625105e75d69e1f41bc5085ca7cf
b7f22e51856f4989b970961f794f1c435f9b8f78
/library/algebra/ordered_ring.lean
c349149dd4dd6d568911070b5636837857f0ed87
[ "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
28,499
lean
/- Copyright (c) 2014 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad Here an "ordered_ring" is partially ordered ring, which is ordered with respect to both a weak order and an associated strict order. Our numeric structures (int, rat, and real) will be instances of "linear_ordered_comm_ring". This development is modeled after Isabelle's library. -/ import algebra.ordered_group algebra.ring open eq eq.ops variable {A : Type} private definition absurd_a_lt_a {B : Type} {a : A} [s : strict_order A] (H : a < a) : B := absurd H (lt.irrefl a) /- semiring structures -/ structure ordered_semiring [class] (A : Type) extends semiring A, ordered_cancel_comm_monoid A := (mul_le_mul_of_nonneg_left: ∀a b c, le a b → le zero c → le (mul c a) (mul c b)) (mul_le_mul_of_nonneg_right: ∀a b c, le a b → le zero c → le (mul a c) (mul b c)) (mul_lt_mul_of_pos_left: ∀a b c, lt a b → lt zero c → lt (mul c a) (mul c b)) (mul_lt_mul_of_pos_right: ∀a b c, lt a b → lt zero c → lt (mul a c) (mul b c)) section variable [s : ordered_semiring A] variables (a b c d e : A) include s theorem mul_le_mul_of_nonneg_left {a b c : A} (Hab : a ≤ b) (Hc : 0 ≤ c) : c * a ≤ c * b := !ordered_semiring.mul_le_mul_of_nonneg_left Hab Hc theorem mul_le_mul_of_nonneg_right {a b c : A} (Hab : a ≤ b) (Hc : 0 ≤ c) : a * c ≤ b * c := !ordered_semiring.mul_le_mul_of_nonneg_right Hab Hc -- TODO: there are four variations, depending on which variables we assume to be nonneg theorem mul_le_mul {a b c d : A} (Hac : a ≤ c) (Hbd : b ≤ d) (nn_b : 0 ≤ b) (nn_c : 0 ≤ c) : a * b ≤ c * d := calc a * b ≤ c * b : mul_le_mul_of_nonneg_right Hac nn_b ... ≤ c * d : mul_le_mul_of_nonneg_left Hbd nn_c theorem mul_nonneg {a b : A} (Ha : a ≥ 0) (Hb : b ≥ 0) : a * b ≥ 0 := begin have H : 0 * b ≤ a * b, from mul_le_mul_of_nonneg_right Ha Hb, rewrite zero_mul at H, exact H end theorem mul_nonpos_of_nonneg_of_nonpos {a b : A} (Ha : a ≥ 0) (Hb : b ≤ 0) : a * b ≤ 0 := begin have H : a * b ≤ a * 0, from mul_le_mul_of_nonneg_left Hb Ha, rewrite mul_zero at H, exact H end theorem mul_nonpos_of_nonpos_of_nonneg {a b : A} (Ha : a ≤ 0) (Hb : b ≥ 0) : a * b ≤ 0 := begin have H : a * b ≤ 0 * b, from mul_le_mul_of_nonneg_right Ha Hb, rewrite zero_mul at H, exact H end theorem mul_lt_mul_of_pos_left {a b c : A} (Hab : a < b) (Hc : 0 < c) : c * a < c * b := !ordered_semiring.mul_lt_mul_of_pos_left Hab Hc theorem mul_lt_mul_of_pos_right {a b c : A} (Hab : a < b) (Hc : 0 < c) : a * c < b * c := !ordered_semiring.mul_lt_mul_of_pos_right Hab Hc -- TODO: once again, there are variations theorem mul_lt_mul {a b c d : A} (Hac : a < c) (Hbd : b ≤ d) (pos_b : 0 < b) (nn_c : 0 ≤ c) : a * b < c * d := calc a * b < c * b : mul_lt_mul_of_pos_right Hac pos_b ... ≤ c * d : mul_le_mul_of_nonneg_left Hbd nn_c theorem mul_lt_mul' {a b c d : A} (H1 : a < c) (H2 : b < d) (H3 : b ≥ 0) (H4 : c > 0) : a * b < c * d := calc a * b ≤ c * b : mul_le_mul_of_nonneg_right (le_of_lt H1) H3 ... < c * d : mul_lt_mul_of_pos_left H2 H4 theorem mul_pos {a b : A} (Ha : a > 0) (Hb : b > 0) : a * b > 0 := begin have H : 0 * b < a * b, from mul_lt_mul_of_pos_right Ha Hb, rewrite zero_mul at H, exact H end theorem mul_neg_of_pos_of_neg {a b : A} (Ha : a > 0) (Hb : b < 0) : a * b < 0 := begin have H : a * b < a * 0, from mul_lt_mul_of_pos_left Hb Ha, rewrite mul_zero at H, exact H end theorem mul_neg_of_neg_of_pos {a b : A} (Ha : a < 0) (Hb : b > 0) : a * b < 0 := begin have H : a * b < 0 * b, from mul_lt_mul_of_pos_right Ha Hb, rewrite zero_mul at H, exact H end theorem mul_self_lt_mul_self {a b : A} (H1 : 0 ≤ a) (H2 : a < b) : a * a < b * b := mul_lt_mul' H2 H2 H1 (lt_of_le_of_lt H1 H2) end structure linear_ordered_semiring [class] (A : Type) extends ordered_semiring A, linear_strong_order_pair A := (zero_lt_one : lt zero one) section variable [s : linear_ordered_semiring A] variables {a b c : A} include s theorem zero_lt_one : 0 < (1:A) := linear_ordered_semiring.zero_lt_one A theorem lt_of_mul_lt_mul_left (H : c * a < c * b) (Hc : c ≥ 0) : a < b := lt_of_not_ge (assume H1 : b ≤ a, have H2 : c * b ≤ c * a, from mul_le_mul_of_nonneg_left H1 Hc, not_lt_of_ge H2 H) theorem lt_of_mul_lt_mul_right (H : a * c < b * c) (Hc : c ≥ 0) : a < b := lt_of_not_ge (assume H1 : b ≤ a, have H2 : b * c ≤ a * c, from mul_le_mul_of_nonneg_right H1 Hc, not_lt_of_ge H2 H) theorem le_of_mul_le_mul_left (H : c * a ≤ c * b) (Hc : c > 0) : a ≤ b := le_of_not_gt (assume H1 : b < a, have H2 : c * b < c * a, from mul_lt_mul_of_pos_left H1 Hc, not_le_of_gt H2 H) theorem le_of_mul_le_mul_right (H : a * c ≤ b * c) (Hc : c > 0) : a ≤ b := le_of_not_gt (assume H1 : b < a, have H2 : b * c < a * c, from mul_lt_mul_of_pos_right H1 Hc, not_le_of_gt H2 H) theorem le_iff_mul_le_mul_left (a b : A) {c : A} (H : c > 0) : a ≤ b ↔ c * a ≤ c * b := iff.intro (assume H', mul_le_mul_of_nonneg_left H' (le_of_lt H)) (assume H', le_of_mul_le_mul_left H' H) theorem le_iff_mul_le_mul_right (a b : A) {c : A} (H : c > 0) : a ≤ b ↔ a * c ≤ b * c := iff.intro (assume H', mul_le_mul_of_nonneg_right H' (le_of_lt H)) (assume H', le_of_mul_le_mul_right H' H) theorem pos_of_mul_pos_left (H : 0 < a * b) (H1 : 0 ≤ a) : 0 < b := lt_of_not_ge (assume H2 : b ≤ 0, have H3 : a * b ≤ 0, from mul_nonpos_of_nonneg_of_nonpos H1 H2, not_lt_of_ge H3 H) theorem pos_of_mul_pos_right (H : 0 < a * b) (H1 : 0 ≤ b) : 0 < a := lt_of_not_ge (assume H2 : a ≤ 0, have H3 : a * b ≤ 0, from mul_nonpos_of_nonpos_of_nonneg H2 H1, not_lt_of_ge H3 H) theorem nonneg_of_mul_nonneg_left (H : 0 ≤ a * b) (H1 : 0 < a) : 0 ≤ b := le_of_not_gt (assume H2 : b < 0, not_le_of_gt (mul_neg_of_pos_of_neg H1 H2) H) theorem nonneg_of_mul_nonneg_right (H : 0 ≤ a * b) (H1 : 0 < b) : 0 ≤ a := le_of_not_gt (assume H2 : a < 0, not_le_of_gt (mul_neg_of_neg_of_pos H2 H1) H) theorem neg_of_mul_neg_left (H : a * b < 0) (H1 : 0 ≤ a) : b < 0 := lt_of_not_ge (assume H2 : b ≥ 0, not_lt_of_ge (mul_nonneg H1 H2) H) theorem neg_of_mul_neg_right (H : a * b < 0) (H1 : 0 ≤ b) : a < 0 := lt_of_not_ge (assume H2 : a ≥ 0, not_lt_of_ge (mul_nonneg H2 H1) H) theorem nonpos_of_mul_nonpos_left (H : a * b ≤ 0) (H1 : 0 < a) : b ≤ 0 := le_of_not_gt (assume H2 : b > 0, not_le_of_gt (mul_pos H1 H2) H) theorem nonpos_of_mul_nonpos_right (H : a * b ≤ 0) (H1 : 0 < b) : a ≤ 0 := le_of_not_gt (assume H2 : a > 0, not_le_of_gt (mul_pos H2 H1) H) end structure decidable_linear_ordered_semiring [class] (A : Type) extends linear_ordered_semiring A, decidable_linear_ordered_cancel_comm_monoid A /- ring structures -/ structure ordered_ring [class] (A : Type) extends ring A, ordered_comm_group A, zero_ne_one_class A := (mul_nonneg : ∀a b, le zero a → le zero b → le zero (mul a b)) (mul_pos : ∀a b, lt zero a → lt zero b → lt zero (mul a b)) theorem ordered_ring.mul_le_mul_of_nonneg_left [s : ordered_ring A] {a b c : A} (Hab : a ≤ b) (Hc : 0 ≤ c) : c * a ≤ c * b := have H1 : 0 ≤ b - a, from iff.elim_right !sub_nonneg_iff_le Hab, have H2 : 0 ≤ c * (b - a), from ordered_ring.mul_nonneg _ _ Hc H1, begin rewrite mul_sub_left_distrib at H2, exact (iff.mp !sub_nonneg_iff_le H2) end theorem ordered_ring.mul_le_mul_of_nonneg_right [s : ordered_ring A] {a b c : A} (Hab : a ≤ b) (Hc : 0 ≤ c) : a * c ≤ b * c := have H1 : 0 ≤ b - a, from iff.elim_right !sub_nonneg_iff_le Hab, have H2 : 0 ≤ (b - a) * c, from ordered_ring.mul_nonneg _ _ H1 Hc, begin rewrite mul_sub_right_distrib at H2, exact (iff.mp !sub_nonneg_iff_le H2) end theorem ordered_ring.mul_lt_mul_of_pos_left [s : ordered_ring A] {a b c : A} (Hab : a < b) (Hc : 0 < c) : c * a < c * b := have H1 : 0 < b - a, from iff.elim_right !sub_pos_iff_lt Hab, have H2 : 0 < c * (b - a), from ordered_ring.mul_pos _ _ Hc H1, begin rewrite mul_sub_left_distrib at H2, exact (iff.mp !sub_pos_iff_lt H2) end theorem ordered_ring.mul_lt_mul_of_pos_right [s : ordered_ring A] {a b c : A} (Hab : a < b) (Hc : 0 < c) : a * c < b * c := have H1 : 0 < b - a, from iff.elim_right !sub_pos_iff_lt Hab, have H2 : 0 < (b - a) * c, from ordered_ring.mul_pos _ _ H1 Hc, begin rewrite mul_sub_right_distrib at H2, exact (iff.mp !sub_pos_iff_lt H2) end definition ordered_ring.to_ordered_semiring [trans_instance] [s : ordered_ring A] : ordered_semiring A := ⦃ ordered_semiring, s, mul_zero := mul_zero, zero_mul := zero_mul, add_left_cancel := @add.left_cancel A _, add_right_cancel := @add.right_cancel A _, le_of_add_le_add_left := @le_of_add_le_add_left A _, mul_le_mul_of_nonneg_left := @ordered_ring.mul_le_mul_of_nonneg_left A _, mul_le_mul_of_nonneg_right := @ordered_ring.mul_le_mul_of_nonneg_right A _, mul_lt_mul_of_pos_left := @ordered_ring.mul_lt_mul_of_pos_left A _, mul_lt_mul_of_pos_right := @ordered_ring.mul_lt_mul_of_pos_right A _, lt_of_add_lt_add_left := @lt_of_add_lt_add_left A _⦄ section variable [s : ordered_ring A] variables {a b c : A} include s theorem mul_le_mul_of_nonpos_left (H : b ≤ a) (Hc : c ≤ 0) : c * a ≤ c * b := have Hc' : -c ≥ 0, from iff.mpr !neg_nonneg_iff_nonpos Hc, have H1 : -c * b ≤ -c * a, from mul_le_mul_of_nonneg_left H Hc', have H2 : -(c * b) ≤ -(c * a), begin rewrite [-*neg_mul_eq_neg_mul at H1], exact H1 end, iff.mp !neg_le_neg_iff_le H2 theorem mul_le_mul_of_nonpos_right (H : b ≤ a) (Hc : c ≤ 0) : a * c ≤ b * c := have Hc' : -c ≥ 0, from iff.mpr !neg_nonneg_iff_nonpos Hc, have H1 : b * -c ≤ a * -c, from mul_le_mul_of_nonneg_right H Hc', have H2 : -(b * c) ≤ -(a * c), begin rewrite [-*neg_mul_eq_mul_neg at H1], exact H1 end, iff.mp !neg_le_neg_iff_le H2 theorem mul_nonneg_of_nonpos_of_nonpos (Ha : a ≤ 0) (Hb : b ≤ 0) : 0 ≤ a * b := begin have H : 0 * b ≤ a * b, from mul_le_mul_of_nonpos_right Ha Hb, rewrite zero_mul at H, exact H end theorem mul_lt_mul_of_neg_left (H : b < a) (Hc : c < 0) : c * a < c * b := have Hc' : -c > 0, from iff.mpr !neg_pos_iff_neg Hc, have H1 : -c * b < -c * a, from mul_lt_mul_of_pos_left H Hc', have H2 : -(c * b) < -(c * a), begin rewrite [-*neg_mul_eq_neg_mul at H1], exact H1 end, iff.mp !neg_lt_neg_iff_lt H2 theorem mul_lt_mul_of_neg_right (H : b < a) (Hc : c < 0) : a * c < b * c := have Hc' : -c > 0, from iff.mpr !neg_pos_iff_neg Hc, have H1 : b * -c < a * -c, from mul_lt_mul_of_pos_right H Hc', have H2 : -(b * c) < -(a * c), begin rewrite [-*neg_mul_eq_mul_neg at H1], exact H1 end, iff.mp !neg_lt_neg_iff_lt H2 theorem mul_pos_of_neg_of_neg (Ha : a < 0) (Hb : b < 0) : 0 < a * b := begin have H : 0 * b < a * b, from mul_lt_mul_of_neg_right Ha Hb, rewrite zero_mul at H, exact H end end -- TODO: we can eliminate mul_pos_of_pos, but now it is not worth the effort to redeclare the -- class instance structure linear_ordered_ring [class] (A : Type) extends ordered_ring A, linear_strong_order_pair A := (zero_lt_one : lt zero one) definition linear_ordered_ring.to_linear_ordered_semiring [trans_instance] [s : linear_ordered_ring A] : linear_ordered_semiring A := ⦃ linear_ordered_semiring, s, mul_zero := mul_zero, zero_mul := zero_mul, add_left_cancel := @add.left_cancel A _, add_right_cancel := @add.right_cancel A _, le_of_add_le_add_left := @le_of_add_le_add_left A _, mul_le_mul_of_nonneg_left := @mul_le_mul_of_nonneg_left A _, mul_le_mul_of_nonneg_right := @mul_le_mul_of_nonneg_right A _, mul_lt_mul_of_pos_left := @mul_lt_mul_of_pos_left A _, mul_lt_mul_of_pos_right := @mul_lt_mul_of_pos_right A _, le_total := linear_ordered_ring.le_total, lt_of_add_lt_add_left := @lt_of_add_lt_add_left A _ ⦄ structure linear_ordered_comm_ring [class] (A : Type) extends linear_ordered_ring A, comm_monoid A theorem linear_ordered_comm_ring.eq_zero_or_eq_zero_of_mul_eq_zero [s : linear_ordered_comm_ring A] {a b : A} (H : a * b = 0) : a = 0 ∨ b = 0 := lt.by_cases (assume Ha : 0 < a, lt.by_cases (assume Hb : 0 < b, begin have H1 : 0 < a * b, from mul_pos Ha Hb, rewrite H at H1, apply absurd_a_lt_a H1 end) (assume Hb : 0 = b, or.inr (Hb⁻¹)) (assume Hb : 0 > b, begin have H1 : 0 > a * b, from mul_neg_of_pos_of_neg Ha Hb, rewrite H at H1, apply absurd_a_lt_a H1 end)) (assume Ha : 0 = a, or.inl (Ha⁻¹)) (assume Ha : 0 > a, lt.by_cases (assume Hb : 0 < b, begin have H1 : 0 > a * b, from mul_neg_of_neg_of_pos Ha Hb, rewrite H at H1, apply absurd_a_lt_a H1 end) (assume Hb : 0 = b, or.inr (Hb⁻¹)) (assume Hb : 0 > b, begin have H1 : 0 < a * b, from mul_pos_of_neg_of_neg Ha Hb, rewrite H at H1, apply absurd_a_lt_a H1 end)) -- Linearity implies no zero divisors. Doesn't need commutativity. definition linear_ordered_comm_ring.to_integral_domain [trans_instance] [s: linear_ordered_comm_ring A] : integral_domain A := ⦃ integral_domain, s, eq_zero_or_eq_zero_of_mul_eq_zero := @linear_ordered_comm_ring.eq_zero_or_eq_zero_of_mul_eq_zero A s ⦄ section variable [s : linear_ordered_ring A] variables (a b c : A) include s theorem mul_self_nonneg : a * a ≥ 0 := or.elim (le.total 0 a) (assume H : a ≥ 0, mul_nonneg H H) (assume H : a ≤ 0, mul_nonneg_of_nonpos_of_nonpos H H) theorem zero_le_one : 0 ≤ (1:A) := one_mul 1 ▸ mul_self_nonneg 1 theorem pos_and_pos_or_neg_and_neg_of_mul_pos {a b : A} (Hab : a * b > 0) : (a > 0 ∧ b > 0) ∨ (a < 0 ∧ b < 0) := lt.by_cases (assume Ha : 0 < a, lt.by_cases (assume Hb : 0 < b, or.inl (and.intro Ha Hb)) (assume Hb : 0 = b, begin rewrite [-Hb at Hab, mul_zero at Hab], apply absurd_a_lt_a Hab end) (assume Hb : b < 0, absurd Hab (lt.asymm (mul_neg_of_pos_of_neg Ha Hb)))) (assume Ha : 0 = a, begin rewrite [-Ha at Hab, zero_mul at Hab], apply absurd_a_lt_a Hab end) (assume Ha : a < 0, lt.by_cases (assume Hb : 0 < b, absurd Hab (lt.asymm (mul_neg_of_neg_of_pos Ha Hb))) (assume Hb : 0 = b, begin rewrite [-Hb at Hab, mul_zero at Hab], apply absurd_a_lt_a Hab end) (assume Hb : b < 0, or.inr (and.intro Ha Hb))) theorem gt_of_mul_lt_mul_neg_left {a b c : A} (H : c * a < c * b) (Hc : c ≤ 0) : a > b := have nhc : -c ≥ 0, from neg_nonneg_of_nonpos Hc, have H2 : -(c * b) < -(c * a), from iff.mpr (neg_lt_neg_iff_lt _ _) H, have H3 : (-c) * b < (-c) * a, from calc (-c) * b = - (c * b) : neg_mul_eq_neg_mul ... < -(c * a) : H2 ... = (-c) * a : neg_mul_eq_neg_mul, lt_of_mul_lt_mul_left H3 nhc theorem zero_gt_neg_one : -1 < (0:A) := neg_zero ▸ (neg_lt_neg zero_lt_one) theorem le_of_mul_le_of_ge_one {a b c : A} (H : a * c ≤ b) (Hb : b ≥ 0) (Hc : c ≥ 1) : a ≤ b := have H' : a * c ≤ b * c, from calc a * c ≤ b : H ... = b * 1 : mul_one ... ≤ b * c : mul_le_mul_of_nonneg_left Hc Hb, le_of_mul_le_mul_right H' (lt_of_lt_of_le zero_lt_one Hc) theorem nonneg_le_nonneg_of_squares_le {a b : A} (Ha : a ≥ 0) (Hb : b ≥ 0) (H : a * a ≤ b * b) : a ≤ b := begin apply le_of_not_gt, intro Hab, note Hposa := lt_of_le_of_lt Hb Hab, note H' := calc b * b ≤ a * b : mul_le_mul_of_nonneg_right (le_of_lt Hab) Hb ... < a * a : mul_lt_mul_of_pos_left Hab Hposa, apply (not_le_of_gt H') H end end /- TODO: Isabelle's library has all kinds of cancelation rules for the simplifier. Search on mult_le_cancel_right1 in Rings.thy. -/ structure decidable_linear_ordered_comm_ring [class] (A : Type) extends linear_ordered_comm_ring A, decidable_linear_ordered_comm_group A definition decidable_linear_ordered_comm_ring.to_decidable_linear_ordered_semiring [trans_instance] [s : decidable_linear_ordered_comm_ring A] : decidable_linear_ordered_semiring A := ⦃decidable_linear_ordered_semiring, s, @linear_ordered_ring.to_linear_ordered_semiring A _⦄ section variable [s : decidable_linear_ordered_comm_ring A] variables {a b c : A} include s definition sign (a : A) : A := lt.cases a 0 (-1) 0 1 theorem sign_of_neg (H : a < 0) : sign a = -1 := lt.cases_of_lt H theorem sign_zero : sign 0 = (0:A) := lt.cases_of_eq rfl theorem sign_of_pos (H : a > 0) : sign a = 1 := lt.cases_of_gt H theorem sign_one : sign 1 = (1:A) := sign_of_pos zero_lt_one theorem sign_neg_one : sign (-1) = -(1:A) := sign_of_neg (neg_neg_of_pos zero_lt_one) theorem sign_sign (a : A) : sign (sign a) = sign a := lt.by_cases (assume H : a > 0, calc sign (sign a) = sign 1 : by rewrite (sign_of_pos H) ... = 1 : by rewrite sign_one ... = sign a : by rewrite (sign_of_pos H)) (assume H : 0 = a, calc sign (sign a) = sign (sign 0) : by rewrite H ... = sign 0 : by rewrite sign_zero at {1} ... = sign a : by rewrite -H) (assume H : a < 0, calc sign (sign a) = sign (-1) : by rewrite (sign_of_neg H) ... = -1 : by rewrite sign_neg_one ... = sign a : by rewrite (sign_of_neg H)) theorem pos_of_sign_eq_one (H : sign a = 1) : a > 0 := lt.by_cases (assume H1 : 0 < a, H1) (assume H1 : 0 = a, begin rewrite [-H1 at H, sign_zero at H], apply absurd H zero_ne_one end) (assume H1 : 0 > a, have H2 : -1 = 1, from (sign_of_neg H1)⁻¹ ⬝ H, absurd ((eq_zero_of_neg_eq H2)⁻¹) zero_ne_one) theorem eq_zero_of_sign_eq_zero (H : sign a = 0) : a = 0 := lt.by_cases (assume H1 : 0 < a, absurd (H⁻¹ ⬝ sign_of_pos H1) zero_ne_one) (assume H1 : 0 = a, H1⁻¹) (assume H1 : 0 > a, have H2 : 0 = -1, from H⁻¹ ⬝ sign_of_neg H1, have H3 : 1 = 0, from eq_neg_of_eq_neg H2 ⬝ neg_zero, absurd (H3⁻¹) zero_ne_one) theorem neg_of_sign_eq_neg_one (H : sign a = -1) : a < 0 := lt.by_cases (assume H1 : 0 < a, have H2 : -1 = 1, from H⁻¹ ⬝ (sign_of_pos H1), absurd ((eq_zero_of_neg_eq H2)⁻¹) zero_ne_one) (assume H1 : 0 = a, have H2 : (0:A) = -1, begin rewrite [-H1 at H, sign_zero at H], exact H end, have H3 : 1 = 0, from eq_neg_of_eq_neg H2 ⬝ neg_zero, absurd (H3⁻¹) zero_ne_one) (assume H1 : 0 > a, H1) theorem sign_neg (a : A) : sign (-a) = -(sign a) := lt.by_cases (assume H1 : 0 < a, calc sign (-a) = -1 : sign_of_neg (neg_neg_of_pos H1) ... = -(sign a) : by rewrite (sign_of_pos H1)) (assume H1 : 0 = a, calc sign (-a) = sign (-0) : by rewrite H1 ... = sign 0 : by rewrite neg_zero ... = 0 : by rewrite sign_zero ... = -0 : by rewrite neg_zero ... = -(sign 0) : by rewrite sign_zero ... = -(sign a) : by rewrite -H1) (assume H1 : 0 > a, calc sign (-a) = 1 : sign_of_pos (neg_pos_of_neg H1) ... = -(-1) : by rewrite neg_neg ... = -(sign a) : sign_of_neg H1) theorem sign_mul (a b : A) : sign (a * b) = sign a * sign b := lt.by_cases (assume z_lt_a : 0 < a, lt.by_cases (assume z_lt_b : 0 < b, by rewrite [sign_of_pos z_lt_a, sign_of_pos z_lt_b, sign_of_pos (mul_pos z_lt_a z_lt_b), one_mul]) (assume z_eq_b : 0 = b, by rewrite [-z_eq_b, mul_zero, *sign_zero, mul_zero]) (assume z_gt_b : 0 > b, by rewrite [sign_of_pos z_lt_a, sign_of_neg z_gt_b, sign_of_neg (mul_neg_of_pos_of_neg z_lt_a z_gt_b), one_mul])) (assume z_eq_a : 0 = a, by rewrite [-z_eq_a, zero_mul, *sign_zero, zero_mul]) (assume z_gt_a : 0 > a, lt.by_cases (assume z_lt_b : 0 < b, by rewrite [sign_of_neg z_gt_a, sign_of_pos z_lt_b, sign_of_neg (mul_neg_of_neg_of_pos z_gt_a z_lt_b), mul_one]) (assume z_eq_b : 0 = b, by rewrite [-z_eq_b, mul_zero, *sign_zero, mul_zero]) (assume z_gt_b : 0 > b, by rewrite [sign_of_neg z_gt_a, sign_of_neg z_gt_b, sign_of_pos (mul_pos_of_neg_of_neg z_gt_a z_gt_b), neg_mul_neg, one_mul])) theorem abs_eq_sign_mul (a : A) : abs a = sign a * a := lt.by_cases (assume H1 : 0 < a, calc abs a = a : abs_of_pos H1 ... = 1 * a : by rewrite one_mul ... = sign a * a : by rewrite (sign_of_pos H1)) (assume H1 : 0 = a, calc abs a = abs 0 : by rewrite H1 ... = 0 : by rewrite abs_zero ... = 0 * a : by rewrite zero_mul ... = sign 0 * a : by rewrite sign_zero ... = sign a * a : by rewrite H1) (assume H1 : a < 0, calc abs a = -a : abs_of_neg H1 ... = -1 * a : by rewrite neg_eq_neg_one_mul ... = sign a * a : by rewrite (sign_of_neg H1)) theorem eq_sign_mul_abs (a : A) : a = sign a * abs a := lt.by_cases (assume H1 : 0 < a, calc a = abs a : abs_of_pos H1 ... = 1 * abs a : by rewrite one_mul ... = sign a * abs a : by rewrite (sign_of_pos H1)) (assume H1 : 0 = a, calc a = 0 : H1⁻¹ ... = 0 * abs a : by rewrite zero_mul ... = sign 0 * abs a : by rewrite sign_zero ... = sign a * abs a : by rewrite H1) (assume H1 : a < 0, calc a = -(-a) : by rewrite neg_neg ... = -abs a : by rewrite (abs_of_neg H1) ... = -1 * abs a : by rewrite neg_eq_neg_one_mul ... = sign a * abs a : by rewrite (sign_of_neg H1)) theorem abs_dvd_iff (a b : A) : abs a ∣ b ↔ a ∣ b := abs.by_cases !iff.refl !neg_dvd_iff_dvd theorem abs_dvd_of_dvd {a b : A} : a ∣ b → abs a ∣ b := iff.mpr !abs_dvd_iff theorem dvd_abs_iff (a b : A) : a ∣ abs b ↔ a ∣ b := abs.by_cases !iff.refl !dvd_neg_iff_dvd theorem dvd_abs_of_dvd {a b : A} : a ∣ b → a ∣ abs b := iff.mpr !dvd_abs_iff theorem abs_mul (a b : A) : abs (a * b) = abs a * abs b := or.elim (le.total 0 a) (assume H1 : 0 ≤ a, or.elim (le.total 0 b) (assume H2 : 0 ≤ b, calc abs (a * b) = a * b : abs_of_nonneg (mul_nonneg H1 H2) ... = abs a * b : by rewrite (abs_of_nonneg H1) ... = abs a * abs b : by rewrite (abs_of_nonneg H2)) (assume H2 : b ≤ 0, calc abs (a * b) = -(a * b) : abs_of_nonpos (mul_nonpos_of_nonneg_of_nonpos H1 H2) ... = a * -b : by rewrite neg_mul_eq_mul_neg ... = abs a * -b : by rewrite (abs_of_nonneg H1) ... = abs a * abs b : by rewrite (abs_of_nonpos H2))) (assume H1 : a ≤ 0, or.elim (le.total 0 b) (assume H2 : 0 ≤ b, calc abs (a * b) = -(a * b) : abs_of_nonpos (mul_nonpos_of_nonpos_of_nonneg H1 H2) ... = -a * b : by rewrite neg_mul_eq_neg_mul ... = abs a * b : by rewrite (abs_of_nonpos H1) ... = abs a * abs b : by rewrite (abs_of_nonneg H2)) (assume H2 : b ≤ 0, calc abs (a * b) = a * b : abs_of_nonneg (mul_nonneg_of_nonpos_of_nonpos H1 H2) ... = -a * -b : by rewrite neg_mul_neg ... = abs a * -b : by rewrite (abs_of_nonpos H1) ... = abs a * abs b : by rewrite (abs_of_nonpos H2))) theorem abs_mul_abs_self (a : A) : abs a * abs a = a * a := abs.by_cases rfl !neg_mul_neg theorem abs_mul_self (a : A) : abs (a * a) = a * a := by rewrite [abs_mul, abs_mul_abs_self] theorem sub_le_of_abs_sub_le_left (H : abs (a - b) ≤ c) : b - c ≤ a := if Hz : 0 ≤ a - b then (calc a ≥ b : (iff.mp !sub_nonneg_iff_le) Hz ... ≥ b - c : sub_le_of_nonneg _ (le.trans !abs_nonneg H)) else (have Habs : b - a ≤ c, by rewrite [abs_of_neg (lt_of_not_ge Hz) at H, neg_sub at H]; apply H, have Habs' : b ≤ c + a, from (iff.mpr !le_add_iff_sub_right_le) Habs, (iff.mp !le_add_iff_sub_left_le) Habs') theorem sub_le_of_abs_sub_le_right (H : abs (a - b) ≤ c) : a - c ≤ b := sub_le_of_abs_sub_le_left (!abs_sub ▸ H) theorem sub_lt_of_abs_sub_lt_left (H : abs (a - b) < c) : b - c < a := if Hz : 0 ≤ a - b then (calc a ≥ b : (iff.mp !sub_nonneg_iff_le) Hz ... > b - c : sub_lt_of_pos _ (lt_of_le_of_lt !abs_nonneg H)) else (have Habs : b - a < c, by rewrite [abs_of_neg (lt_of_not_ge Hz) at H, neg_sub at H]; apply H, have Habs' : b < c + a, from lt_add_of_sub_lt_right Habs, sub_lt_left_of_lt_add Habs') theorem sub_lt_of_abs_sub_lt_right (H : abs (a - b) < c) : a - c < b := sub_lt_of_abs_sub_lt_left (!abs_sub ▸ H) theorem abs_sub_square (a b : A) : abs (a - b) * abs (a - b) = a * a + b * b - (1 + 1) * a * b := begin rewrite [abs_mul_abs_self, *mul_sub_left_distrib, *mul_sub_right_distrib, sub_eq_add_neg (a*b), sub_add_eq_sub_sub, sub_neg_eq_add, *right_distrib, sub_add_eq_sub_sub, *one_mul, *add.assoc, {_ + b * b}add.comm, *sub_eq_add_neg], rewrite [{a*a + b*b}add.comm], rewrite [mul.comm b a, *add.assoc] end theorem abs_abs_sub_abs_le_abs_sub (a b : A) : abs (abs a - abs b) ≤ abs (a - b) := begin apply nonneg_le_nonneg_of_squares_le, repeat apply abs_nonneg, rewrite [*abs_sub_square, *abs_abs, *abs_mul_abs_self], apply sub_le_sub_left, rewrite *mul.assoc, apply mul_le_mul_of_nonneg_left, rewrite -abs_mul, apply le_abs_self, apply le_of_lt, apply add_pos, apply zero_lt_one, apply zero_lt_one end lemma eq_zero_of_mul_self_add_mul_self_eq_zero {x y : A} (H : x * x + y * y = 0) : x = 0 := have x * x ≤ (0 : A), from calc x * x ≤ x * x + y * y : le_add_of_nonneg_right (mul_self_nonneg y) ... = 0 : H, eq_zero_of_mul_self_eq_zero (le.antisymm this (mul_self_nonneg x)) end /- TODO: Multiplication and one, starting with mult_right_le_one_le. -/ namespace norm_num theorem pos_bit0_helper [s : linear_ordered_semiring A] (a : A) (H : a > 0) : bit0 a > 0 := by rewrite ↑bit0; apply add_pos H H theorem nonneg_bit0_helper [s : linear_ordered_semiring A] (a : A) (H : a ≥ 0) : bit0 a ≥ 0 := by rewrite ↑bit0; apply add_nonneg H H theorem pos_bit1_helper [s : linear_ordered_semiring A] (a : A) (H : a ≥ 0) : bit1 a > 0 := begin rewrite ↑bit1, apply add_pos_of_nonneg_of_pos, apply nonneg_bit0_helper _ H, apply zero_lt_one end theorem nonneg_bit1_helper [s : linear_ordered_semiring A] (a : A) (H : a ≥ 0) : bit1 a ≥ 0 := by apply le_of_lt; apply pos_bit1_helper _ H theorem nonzero_of_pos_helper [s : linear_ordered_semiring A] (a : A) (H : a > 0) : a ≠ 0 := ne_of_gt H theorem nonzero_of_neg_helper [s : linear_ordered_ring A] (a : A) (H : a ≠ 0) : -a ≠ 0 := begin intro Ha, apply H, apply eq_of_neg_eq_neg, rewrite neg_zero, exact Ha end end norm_num
dbcb25c9d986b1d15f691405f4ef0fc308ecea33
35b83be3126daae10419b573c55e1fed009d3ae8
/_target/deps/mathlib/algebra/order.lean
2550e482d73a3235c98b309ad0ad2719f1adbfe4
[]
no_license
AHassan1024/Lean_Playground
ccb25b72029d199c0d23d002db2d32a9f2689ebc
a00b004c3a2eb9e3e863c361aa2b115260472414
refs/heads/master
1,586,221,905,125
1,544,951,310,000
1,544,951,310,000
157,934,290
0
0
null
null
null
null
UTF-8
Lean
false
false
8,512
lean
/- Copyright (c) 2017 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ universe u variables {α : Type u} lemma not_le_of_lt [preorder α] {a b : α} (h : a < b) : ¬ b ≤ a := (le_not_le_of_lt h).right lemma not_lt_of_le [preorder α] {a b : α} (h : a ≤ b) : ¬ b < a | hab := not_le_of_gt hab h lemma le_iff_eq_or_lt [partial_order α] {a b : α} : a ≤ b ↔ a = b ∨ a < b := le_iff_lt_or_eq.trans or.comm lemma lt_of_le_of_ne' [partial_order α] {a b : α} (h₁ : a ≤ b) (h₂ : a ≠ b) : a < b := lt_of_le_not_le h₁ $ mt (le_antisymm h₁) h₂ lemma lt_iff_le_and_ne [partial_order α] {a b : α} : a < b ↔ a ≤ b ∧ a ≠ b := ⟨λ h, ⟨le_of_lt h, ne_of_lt h⟩, λ ⟨h1, h2⟩, lt_of_le_of_ne h1 h2⟩ lemma eq_or_lt_of_le [partial_order α] {a b : α} (h : a ≤ b) : a = b ∨ a < b := (lt_or_eq_of_le h).symm lemma lt_of_not_ge' [linear_order α] {a b : α} (h : ¬ b ≤ a) : a < b := lt_of_le_not_le ((le_total _ _).resolve_right h) h lemma lt_iff_not_ge' [linear_order α] {x y : α} : x < y ↔ ¬ y ≤ x := ⟨not_le_of_gt, lt_of_not_ge'⟩ @[simp] lemma not_lt [linear_order α] {a b : α} : ¬ a < b ↔ b ≤ a := ⟨le_of_not_gt, not_lt_of_ge⟩ lemma le_of_not_lt [linear_order α] {a b : α} : ¬ a < b → b ≤ a := not_lt.1 @[simp] lemma not_le [linear_order α] {a b : α} : ¬ a ≤ b ↔ b < a := lt_iff_not_ge'.symm lemma lt_or_le [linear_order α] : ∀ a b : α, a < b ∨ b ≤ a := lt_or_ge lemma le_or_lt [linear_order α] : ∀ a b : α, a ≤ b ∨ b < a := le_or_gt lemma not_lt_iff_eq_or_lt [linear_order α] {a b : α} : ¬ a < b ↔ a = b ∨ b < a := not_lt.trans $ le_iff_eq_or_lt.trans $ or_congr eq_comm iff.rfl lemma exists_ge_of_linear [linear_order α] (a b : α) : ∃ c, a ≤ c ∧ b ≤ c := match le_total a b with | or.inl h := ⟨_, h, le_refl _⟩ | or.inr h := ⟨_, le_refl _, h⟩ end lemma lt_iff_lt_of_strict_mono {β} [linear_order α] [preorder β] (f : α → β) (H : ∀ a b, a < b → f a < f b) {a b} : f a < f b ↔ a < b := ⟨λ h, ((lt_trichotomy b a) .resolve_left $ λ h', lt_asymm h $ H _ _ h') .resolve_left $ λ e, ne_of_gt h $ congr_arg _ e, H _ _⟩ lemma le_iff_le_of_strict_mono {β} [linear_order α] [preorder β] (f : α → β) (H : ∀ a b, a < b → f a < f b) {a b} : f a ≤ f b ↔ a ≤ b := ⟨λ h, le_of_not_gt $ λ h', not_le_of_lt (H b a h') h, λ h, (lt_or_eq_of_le h).elim (λ h', le_of_lt (H _ _ h')) (λ h', h' ▸ le_refl _)⟩ lemma injective_of_strict_mono {β} [linear_order α] [preorder β] (f : α → β) (H : ∀ a b, a < b → f a < f b) : function.injective f | a b e := ((lt_trichotomy a b) .resolve_left $ λ h, ne_of_lt (H _ _ h) e) .resolve_right $ λ h, ne_of_gt (H _ _ h) e lemma lt_imp_lt_of_le_imp_le {β} [linear_order α] [preorder β] {a b : α} {c d : β} (H : a ≤ b → c ≤ d) (h : d < c) : b < a := lt_of_not_ge' $ λ h', not_lt_of_ge (H h') h lemma le_imp_le_of_lt_imp_lt {β} [preorder α] [linear_order β] {a b : α} {c d : β} (H : d < c → b < a) (h : a ≤ b) : c ≤ d := le_of_not_gt $ λ h', not_le_of_gt (H h') h lemma le_imp_le_iff_lt_imp_lt {β} [linear_order α] [linear_order β] {a b : α} {c d : β} : (a ≤ b → c ≤ d) ↔ (d < c → b < a) := ⟨lt_imp_lt_of_le_imp_le, le_imp_le_of_lt_imp_lt⟩ lemma lt_iff_lt_of_le_iff_le' {β} [preorder α] [preorder β] {a b : α} {c d : β} (H : a ≤ b ↔ c ≤ d) (H' : b ≤ a ↔ d ≤ c) : b < a ↔ d < c := lt_iff_le_not_le.trans $ (and_congr H' (not_congr H)).trans lt_iff_le_not_le.symm lemma lt_iff_lt_of_le_iff_le {β} [linear_order α] [linear_order β] {a b : α} {c d : β} (H : a ≤ b ↔ c ≤ d) : b < a ↔ d < c := not_le.symm.trans $ iff.trans (not_congr H) $ not_le lemma le_iff_le_iff_lt_iff_lt {β} [linear_order α] [linear_order β] {a b : α} {c d : β} : (a ≤ b ↔ c ≤ d) ↔ (b < a ↔ d < c) := ⟨lt_iff_lt_of_le_iff_le, λ H, not_lt.symm.trans $ iff.trans (not_congr H) $ not_lt⟩ lemma eq_of_forall_le_iff [partial_order α] {a b : α} (H : ∀ c, c ≤ a ↔ c ≤ b) : a = b := le_antisymm ((H _).1 (le_refl _)) ((H _).2 (le_refl _)) lemma le_of_forall_le [preorder α] {a b : α} (H : ∀ c, c ≤ a → c ≤ b) : a ≤ b := H _ (le_refl _) lemma le_of_forall_lt [linear_order α] {a b : α} (H : ∀ c, c < a → c < b) : a ≤ b := le_of_not_lt $ λ h, lt_irrefl _ (H _ h) lemma eq_of_forall_ge_iff [partial_order α] {a b : α} (H : ∀ c, a ≤ c ↔ b ≤ c) : a = b := le_antisymm ((H _).2 (le_refl _)) ((H _).1 (le_refl _)) namespace decidable lemma lt_or_eq_of_le [partial_order α] [@decidable_rel α (≤)] {a b : α} (hab : a ≤ b) : a < b ∨ a = b := if hba : b ≤ a then or.inr (le_antisymm hab hba) else or.inl (lt_of_le_not_le hab hba) lemma eq_or_lt_of_le [partial_order α] [@decidable_rel α (≤)] {a b : α} (hab : a ≤ b) : a = b ∨ a < b := (lt_or_eq_of_le hab).swap lemma le_iff_lt_or_eq [partial_order α] [@decidable_rel α (≤)] {a b : α} : a ≤ b ↔ a < b ∨ a = b := ⟨lt_or_eq_of_le, le_of_lt_or_eq⟩ lemma le_of_not_lt [decidable_linear_order α] {a b : α} (h : ¬ b < a) : a ≤ b := decidable.by_contradiction $ λ h', h $ lt_of_le_not_le ((le_total _ _).resolve_right h') h' lemma not_lt [decidable_linear_order α] {a b : α} : ¬ a < b ↔ b ≤ a := ⟨le_of_not_lt, not_lt_of_ge⟩ lemma lt_or_le [decidable_linear_order α] (a b : α) : a < b ∨ b ≤ a := if hba : b ≤ a then or.inr hba else or.inl $ not_le.1 hba lemma le_or_lt [decidable_linear_order α] (a b : α) : a ≤ b ∨ b < a := (lt_or_le b a).swap lemma lt_trichotomy [decidable_linear_order α] (a b : α) : a < b ∨ a = b ∨ b < a := (lt_or_le _ _).imp_right $ λ h, (eq_or_lt_of_le h).imp_left eq.symm lemma lt_or_gt_of_ne [decidable_linear_order α] {a b : α} (h : a ≠ b) : a < b ∨ b < a := (lt_trichotomy a b).imp_right $ λ h', h'.resolve_left h lemma ne_iff_lt_or_gt [decidable_linear_order α] {a b : α} : a ≠ b ↔ a < b ∨ a > b := ⟨lt_or_gt_of_ne, λo, o.elim ne_of_lt ne_of_gt⟩ lemma le_imp_le_of_lt_imp_lt {β} [preorder α] [decidable_linear_order β] {a b : α} {c d : β} (H : d < c → b < a) (h : a ≤ b) : c ≤ d := le_of_not_lt $ λ h', not_le_of_gt (H h') h lemma le_imp_le_iff_lt_imp_lt {β} [linear_order α] [decidable_linear_order β] {a b : α} {c d : β} : (a ≤ b → c ≤ d) ↔ (d < c → b < a) := ⟨lt_imp_lt_of_le_imp_le, le_imp_le_of_lt_imp_lt⟩ lemma le_iff_le_iff_lt_iff_lt {β} [decidable_linear_order α] [decidable_linear_order β] {a b : α} {c d : β} : (a ≤ b ↔ c ≤ d) ↔ (b < a ↔ d < c) := ⟨lt_iff_lt_of_le_iff_le, λ H, not_lt.symm.trans $ iff.trans (not_congr H) $ not_lt⟩ end decidable namespace ordering /-- `compares o a b` means that `a` and `b` have the ordering relation `o` between them, assuming that the relation `a < b` is defined -/ @[simp] def compares [has_lt α] : ordering → α → α → Prop | lt a b := a < b | eq a b := a = b | gt a b := a > b theorem compares.eq_lt [preorder α] : ∀ {o} {a b : α}, compares o a b → (o = lt ↔ a < b) | lt a b h := ⟨λ _, h, λ _, rfl⟩ | eq a b h := ⟨λ h, by injection h, λ h', (ne_of_lt h' h).elim⟩ | gt a b h := ⟨λ h, by injection h, λ h', (lt_asymm h h').elim⟩ theorem compares.eq_eq [preorder α] : ∀ {o} {a b : α}, compares o a b → (o = eq ↔ a = b) | lt a b h := ⟨λ h, by injection h, λ h', (ne_of_lt h h').elim⟩ | eq a b h := ⟨λ _, h, λ _, rfl⟩ | gt a b h := ⟨λ h, by injection h, λ h', (ne_of_gt h h').elim⟩ theorem compares.eq_gt [preorder α] : ∀ {o} {a b : α}, compares o a b → (o = gt ↔ a > b) | lt a b h := ⟨λ h, by injection h, λ h', (lt_asymm h h').elim⟩ | eq a b h := ⟨λ h, by injection h, λ h', (ne_of_gt h' h).elim⟩ | gt a b h := ⟨λ _, h, λ _, rfl⟩ theorem compares.inj [preorder α] {o₁} : ∀ {o₂} {a b : α}, compares o₁ a b → compares o₂ a b → o₁ = o₂ | lt a b h₁ h₂ := h₁.eq_lt.2 h₂ | eq a b h₁ h₂ := h₁.eq_eq.2 h₂ | gt a b h₁ h₂ := h₁.eq_gt.2 h₂ theorem compares_of_strict_mono {β} [linear_order α] [preorder β] (f : α → β) (H : ∀ a b, a < b → f a < f b) {a b} : ∀ {o}, compares o (f a) (f b) ↔ compares o a b | lt := lt_iff_lt_of_strict_mono f H | eq := ⟨λ h, injective_of_strict_mono _ H h, congr_arg _⟩ | gt := lt_iff_lt_of_strict_mono f H end ordering
d47c9c80ce77b2cd47d7c21f69d5214065e5f55b
5749d8999a76f3a8fddceca1f6941981e33aaa96
/src/analysis/normed_space/finite_dimension.lean
97d53088e2cbda6d3e5afeee8be4a2750fd52031
[ "Apache-2.0" ]
permissive
jdsalchow/mathlib
13ab43ef0d0515a17e550b16d09bd14b76125276
497e692b946d93906900bb33a51fd243e7649406
refs/heads/master
1,585,819,143,348
1,580,072,892,000
1,580,072,892,000
154,287,128
0
0
Apache-2.0
1,540,281,610,000
1,540,281,609,000
null
UTF-8
Lean
false
false
13,076
lean
/- Copyright (c) 2019 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sébastien Gouëzel -/ import analysis.normed_space.operator_norm linear_algebra.finite_dimensional tactic.omega /-! # Finite dimensional normed spaces over complete fields Over a complete nondiscrete field, in finite dimension, all norms are equivalent and all linear maps are continuous. Moreover, a finite-dimensional subspace is always complete and closed. ## Main results: * `linear_map.continuous_of_finite_dimensional` : a linear map on a finite-dimensional space over a complete field is continuous. * `finite_dimensional.complete` : a finite-dimensional space over a complete field is complete. This is not registered as an instance, as the field would be an unknown metavariable in typeclass resolution. * `submodule.closed_of_finite_dimensional` : a finite-dimensional subspace over a complete field is closed * `finite_dimensional.proper` : a finite-dimensional space over a proper field is proper. This is not registered as an instance, as the field would be an unknown metavariable in typeclass resolution. It is however registered as an instance for `𝕜 = ℝ` and `𝕜 = ℂ`. As properness implies completeness, there is no need to also register `finite_dimensional.complete` on `ℝ` or `ℂ`. ## Implementation notes The fact that all norms are equivalent is not written explicitly, as it would mean having two norms on a single space, which is not the way type classes work. However, if one has a finite-dimensional vector space `E` with a norm, and a copy `E'` of this type with another norm, then the identities from `E` to `E'` and from `E'`to `E` are continuous thanks to `linear_map.continuous_of_finite_dimensional`. This gives the desired norm equivalence. -/ universes u v w open set finite_dimensional open_locale classical -- To get a reasonable compile time for `continuous_equiv_fun_basis`, typeclass inference needs -- to be guided. local attribute [instance, priority 10000] pi.module normed_space.to_module submodule.add_comm_group submodule.module linear_map.finite_dimensional_range Pi.complete nondiscrete_normed_field.to_normed_field set_option class.instance_max_depth 100 /-- A linear map on `ι → 𝕜` (where `ι` is a fintype) is continuous -/ lemma linear_map.continuous_on_pi {ι : Type w} [fintype ι] {𝕜 : Type u} [normed_field 𝕜] {E : Type v} [normed_group E] [normed_space 𝕜 E] (f : (ι → 𝕜) →ₗ[𝕜] E) : continuous f := begin -- for the proof, write `f` in the standard basis, and use that each coordinate is a continuous -- function. have : (f : (ι → 𝕜) → E) = (λx, finset.sum finset.univ (λi:ι, x i • (f (λj, if i = j then 1 else 0)))), by { ext x, exact f.pi_apply_eq_sum_univ x }, rw this, refine continuous_finset_sum _ (λi hi, _), exact (continuous_apply i).smul continuous_const end section complete_field variables {𝕜 : Type u} [nondiscrete_normed_field 𝕜] {E : Type v} [normed_group E] [normed_space 𝕜 E] {F : Type w} [normed_group F] [normed_space 𝕜 F] [complete_space 𝕜] set_option class.instance_max_depth 150 /-- In finite dimension over a complete field, the canonical identification (in terms of a basis) with `𝕜^n` together with its sup norm is continuous. This is the nontrivial part in the fact that all norms are equivalent in finite dimension. Do not use this statement as its formulation is awkward (in terms of the dimension `n`, as the proof is done by induction over `n`) and it is superceded by the fact that every linear map on a finite-dimensional space is continuous, in `linear_map.continuous_of_finite_dimensional`. -/ lemma continuous_equiv_fun_basis {n : ℕ} {ι : Type v} [fintype ι] (ξ : ι → E) (hn : fintype.card ι = n) (hξ : is_basis 𝕜 ξ) : continuous (equiv_fun_basis hξ) := begin unfreezeI, induction n with n IH generalizing ι E, { apply linear_map.continuous_of_bound _ 0 (λx, _), have : equiv_fun_basis hξ x = 0, by { ext i, exact (fintype.card_eq_zero_iff.1 hn i).elim }, change ∥equiv_fun_basis hξ x∥ ≤ 0 * ∥x∥, rw this, simp [norm_nonneg] }, { haveI : finite_dimensional 𝕜 E := of_finite_basis hξ, -- first step: thanks to the inductive assumption, any n-dimensional subspace is equivalent -- to a standard space of dimension n, hence it is complete and therefore closed. have H₁ : ∀s : submodule 𝕜 E, findim 𝕜 s = n → is_closed (s : set E), { assume s s_dim, rcases exists_is_basis_finite 𝕜 s with ⟨b, b_basis, b_finite⟩, letI : fintype b := finite.fintype b_finite, have U : uniform_embedding (equiv_fun_basis b_basis).symm, { have : fintype.card b = n, by { rw ← s_dim, exact (findim_eq_card_basis b_basis).symm }, have : continuous (equiv_fun_basis b_basis) := IH (subtype.val : b → s) this b_basis, exact (equiv_fun_basis b_basis).symm.uniform_embedding (linear_map.continuous_on_pi _) this }, have : is_complete (range ((equiv_fun_basis b_basis).symm)), { rw [← image_univ, is_complete_image_iff U], convert complete_univ, change complete_space (b → 𝕜), apply_instance }, have : is_complete (range (subtype.val : s → E)), { change is_complete (range ((equiv_fun_basis b_basis).symm.to_equiv)) at this, rw equiv.range_eq_univ at this, rwa [← image_univ, is_complete_image_iff], exact isometry_subtype_val.uniform_embedding }, apply is_closed_of_is_complete, rwa subtype.val_range at this }, -- second step: any linear form is continuous, as its kernel is closed by the first step have H₂ : ∀f : E →ₗ[𝕜] 𝕜, continuous f, { assume f, have : findim 𝕜 f.ker = n ∨ findim 𝕜 f.ker = n.succ, { have Z := f.findim_range_add_findim_ker, rw [findim_eq_card_basis hξ, hn] at Z, have : findim 𝕜 f.range = 0 ∨ findim 𝕜 f.range = 1, { have I : ∀(k : ℕ), k ≤ 1 ↔ k = 0 ∨ k = 1, by omega manual, have : findim 𝕜 f.range ≤ findim 𝕜 𝕜 := submodule.findim_le _, rwa [findim_of_field, I] at this }, cases this, { rw this at Z, right, simpa using Z }, { left, rw [this, add_comm, nat.add_one] at Z, exact nat.succ_inj Z } }, have : is_closed (f.ker : set E), { cases this, { exact H₁ _ this }, { have : f.ker = ⊤, by { apply eq_top_of_findim_eq, rw [findim_eq_card_basis hξ, hn, this] }, simp [this] } }, exact linear_map.continuous_iff_is_closed_ker.2 this }, -- third step: applying the continuity to the linear form corresponding to a coefficient in the -- basis decomposition, deduce that all such coefficients are controlled in terms of the norm have : ∀i:ι, ∃C, 0 ≤ C ∧ ∀(x:E), ∥equiv_fun_basis hξ x i∥ ≤ C * ∥x∥, { assume i, let f : E →ₗ[𝕜] 𝕜 := (linear_map.proj i).comp (equiv_fun_basis hξ), let f' : E →L[𝕜] 𝕜 := { cont := H₂ f, ..f }, exact ⟨∥f'∥, norm_nonneg _, λx, continuous_linear_map.le_op_norm f' x⟩ }, -- fourth step: combine the bound on each coefficient to get a global bound and the continuity choose C0 hC0 using this, let C := finset.sum finset.univ C0, have C_nonneg : 0 ≤ C := finset.sum_nonneg (λi hi, (hC0 i).1), have C0_le : ∀i, C0 i ≤ C := λi, finset.single_le_sum (λj hj, (hC0 j).1) (finset.mem_univ _), apply linear_map.continuous_of_bound _ C (λx, _), rw pi_norm_le_iff, { exact λi, le_trans ((hC0 i).2 x) (mul_le_mul_of_nonneg_right (C0_le i) (norm_nonneg _)) }, { exact mul_nonneg C_nonneg (norm_nonneg _) } } end /-- Any linear map on a finite dimensional space over a complete field is continuous. -/ theorem linear_map.continuous_of_finite_dimensional [finite_dimensional 𝕜 E] (f : E →ₗ[𝕜] F) : continuous f := begin -- for the proof, go to a model vector space `b → 𝕜` thanks to `continuous_equiv_fun_basis`, and -- argue that all linear maps there are continuous. rcases exists_is_basis_finite 𝕜 E with ⟨b, b_basis, b_finite⟩, letI : fintype b := finite.fintype b_finite, have A : continuous (equiv_fun_basis b_basis) := continuous_equiv_fun_basis _ rfl b_basis, have B : continuous (f.comp ((equiv_fun_basis b_basis).symm : (b → 𝕜) →ₗ[𝕜] E)) := linear_map.continuous_on_pi _, have : continuous ((f.comp ((equiv_fun_basis b_basis).symm : (b → 𝕜) →ₗ[𝕜] E)) ∘ (equiv_fun_basis b_basis)) := B.comp A, convert this, ext x, simp only [linear_equiv.coe_apply, function.comp_app, coe_fn_coe_base, linear_map.comp_apply], rw linear_equiv.symm_apply_apply end /-- The continuous linear map induced by a linear map on a finite dimensional space -/ def linear_map.to_continuous_linear_map [finite_dimensional 𝕜 E] (f : E →ₗ[𝕜] F) : E →L[𝕜] F := { cont := f.continuous_of_finite_dimensional, ..f } /-- The continuous linear equivalence induced by a linear equivalence on a finite dimensional space. -/ def linear_equiv.to_continuous_linear_equiv [finite_dimensional 𝕜 E] (e : E ≃ₗ[𝕜] F) : E ≃L[𝕜] F := { continuous_to_fun := e.to_linear_map.continuous_of_finite_dimensional, continuous_inv_fun := begin haveI : finite_dimensional 𝕜 F := e.finite_dimensional, exact e.symm.to_linear_map.continuous_of_finite_dimensional end, ..e } /-- Any finite-dimensional vector space over a complete field is complete. We do not register this as an instance to avoid an instance loop when trying to prove the completeness of `𝕜`, and the search for `𝕜` as an unknown metavariable. Declare the instance explicitly when needed. -/ variables (𝕜 E) lemma finite_dimensional.complete [finite_dimensional 𝕜 E] : complete_space E := begin rcases exists_is_basis_finite 𝕜 E with ⟨b, b_basis, b_finite⟩, letI : fintype b := finite.fintype b_finite, have : uniform_embedding (equiv_fun_basis b_basis).symm := linear_equiv.uniform_embedding _ (linear_map.continuous_of_finite_dimensional _) (linear_map.continuous_of_finite_dimensional _), have : is_complete ((equiv_fun_basis b_basis).symm.to_equiv '' univ) := (is_complete_image_iff this).mpr complete_univ, rw [image_univ, equiv.range_eq_univ] at this, exact complete_space_of_is_complete_univ this end variables {𝕜 E} /-- A finite-dimensional subspace is complete. -/ lemma submodule.complete_of_finite_dimensional (s : submodule 𝕜 E) [finite_dimensional 𝕜 s] : is_complete (s : set E) := begin haveI : complete_space s := finite_dimensional.complete 𝕜 s, have : is_complete (range (subtype.val : s → E)), { rw [← image_univ, is_complete_image_iff], { exact complete_univ }, { exact isometry_subtype_val.uniform_embedding } }, rwa subtype.val_range at this end /-- A finite-dimensional subspace is closed. -/ lemma submodule.closed_of_finite_dimensional (s : submodule 𝕜 E) [finite_dimensional 𝕜 s] : is_closed (s : set E) := is_closed_of_is_complete s.complete_of_finite_dimensional end complete_field section proper_field variables (𝕜 : Type u) [nondiscrete_normed_field 𝕜] (E : Type v) [normed_group E] [normed_space 𝕜 E] [proper_space 𝕜] /-- Any finite-dimensional vector space over a proper field is proper. We do not register this as an instance to avoid an instance loop when trying to prove the properness of `𝕜`, and the search for `𝕜` as an unknown metavariable. Declare the instance explicitly when needed. -/ lemma finite_dimensional.proper [finite_dimensional 𝕜 E] : proper_space E := begin rcases exists_is_basis_finite 𝕜 E with ⟨b, b_basis, b_finite⟩, letI : fintype b := finite.fintype b_finite, let e := equiv_fun_basis b_basis, let f : E →L[𝕜] (b → 𝕜) := { cont := linear_map.continuous_of_finite_dimensional _, ..e.to_linear_map }, refine metric.proper_image_of_proper e.symm (linear_map.continuous_of_finite_dimensional _) _ (∥f∥) (λx y, _), { exact equiv.range_eq_univ e.symm.to_equiv }, { have A : e (e.symm x) = x := linear_equiv.apply_symm_apply _ _, have B : e (e.symm y) = y := linear_equiv.apply_symm_apply _ _, conv_lhs { rw [← A, ← B] }, change dist (f (e.symm x)) (f (e.symm y)) ≤ ∥f∥ * dist (e.symm x) (e.symm y), exact f.lipschitz _ _ } end end proper_field /- Over the real numbers, we can register the previous statement as an instance as it will not cause problems in instance resolution since the properness of `ℝ` is already known. -/ instance finite_dimensional.proper_real (E : Type u) [normed_group E] [normed_space ℝ E] [finite_dimensional ℝ E] : proper_space E := finite_dimensional.proper ℝ E attribute [instance, priority 900] finite_dimensional.proper_real
b2bcb072a25d8f57d25e3d46dfa8219b49e73724
5df84495ec6c281df6d26411cc20aac5c941e745
/src/formal_ml/set.lean
6284a43824b9141429adf27df02b81716089ca25
[ "Apache-2.0" ]
permissive
eric-wieser/formal-ml
e278df5a8df78aa3947bc8376650419e1b2b0a14
630011d19fdd9539c8d6493a69fe70af5d193590
refs/heads/master
1,681,491,589,256
1,612,642,743,000
1,612,642,743,000
360,114,136
0
0
Apache-2.0
1,618,998,189,000
1,618,998,188,000
null
UTF-8
Lean
false
false
12,617
lean
/- Copyright 2020 Google LLC Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. -/ import data.set.disjointed data.set.countable import data.set.lattice data.set.finite import formal_ml.nat /- Theorems about sets. The best repository of theorems about sets is /mathlib/src/data/set/basic.lean. -/ --Novel, used: move to mathlib? --Alternately, look into topological_space.lean, and see what is necessary. lemma set.preimage_fst_def {α β:Type*} {Bα:set (set α)}: (@set.preimage (α × β) α (@prod.fst α β) '' Bα) = {U : set (α × β) | ∃ (A : set α) (H : A ∈ Bα), U = @set.prod α β A (@set.univ β)} := begin ext,split;intros A1A, { simp at A1A, cases A1A with A A1A, cases A1A with A1B A1C, subst x, split, simp, split, apply A1B, unfold set.prod, simp, refl, }, { simp at A1A, cases A1A with A A1A, cases A1A with A1B A1C, subst x, split, split, apply A1B, unfold set.prod, simp, refl } end --Novel, used. lemma set.preimage_snd_def {α β:Type*} {Bβ:set (set β)}: (@set.preimage (α × β) β (@prod.snd α β) '' Bβ) = {U : set (α × β) | ∃ (B : set β) (H : B ∈ Bβ), U = @set.prod α β (@set.univ α) B} := begin ext,split;intros A1A, { simp at A1A, cases A1A with A A1A, cases A1A with A1B A1C, subst x, split, simp, split, apply A1B, unfold set.prod, simp, refl, }, { simp at A1A, cases A1A with A A1A, cases A1A with A1B A1C, subst x, split, split, apply A1B, unfold set.prod, simp, refl } end --Novel, used. --Similar, but not identical to set.preimage_sUnion. --Could probably replace it. lemma set.preimage_sUnion' {α β:Type*} (f:α → β) (T:set (set β)): (f ⁻¹' ⋃₀ T)=⋃₀ (set.image (set.preimage f) T) := begin rw set.preimage_sUnion, ext,split;intros A1;simp;simp at A1;apply A1, end --Novel, used. lemma set.prod_sUnion_right {α:Type*} (A:set α) {β:Type*} (B:set (set β)): (set.prod A (⋃₀ B)) = ⋃₀ {C:set (α× β)|∃ b∈ B, C=(set.prod A b)} := begin ext,split;intro A1, { cases A1 with A2 A3, cases A3 with b A4, cases A4 with A5 A6, simp, apply exists.intro (set.prod A b), split, { apply exists.intro b, split, exact A5, refl, }, { split;assumption, } }, { cases A1 with Ab A2, cases A2 with A3 A4, cases A3 with b A5, cases A5 with A6 A7, subst Ab, cases A4 with A8 A9, split, { exact A8, }, { simp, apply exists.intro b, split;assumption, } } end --Novel, used. lemma set.prod_sUnion_left {α:Type*} (A:set (set α)) {β:Type*} (B:set β): (set.prod (⋃₀ A) B) = ⋃₀ {C:set (α× β)|∃ a∈ A, C=(set.prod a B)} := begin ext,split;intro A1, { cases A1 with A2 A3, cases A2 with a A4, cases A4 with A5 A6, simp, apply exists.intro (set.prod a B), split, { apply exists.intro a, split, exact A5, refl, }, { split;assumption, } }, { cases A1 with Ab A2, cases A2 with A3 A4, cases A3 with b A5, cases A5 with A6 A7, subst Ab, cases A4 with A8 A9, split, { simp, apply exists.intro b, split;assumption, }, { exact A9, } } end --Novel, used. lemma union_trichotomy {β:Type*} [decidable_eq β] {b:β} {S S2:finset β}: b∈ (S ∪ S2) ↔ ( ((b∈ S) ∧ (b∉ S2)) ∨ ((b∈ S) ∧ (b ∈ S2)) ∨ ((b∉ S) ∧ (b∈ S2))) := begin have B1:(b∈ S)∨ (b∉ S), { apply classical.em, }, have B2:(b∈ S2)∨ (b∉ S2), { apply classical.em, }, split;intro A1, { simp at A1, cases A1, { cases B2, { right,left, apply and.intro A1 B2, }, { left, apply and.intro A1 B2, }, }, { right, cases B1, { left, apply and.intro B1 A1, }, { right, apply and.intro B1 A1, }, }, }, { simp, cases A1, { left, apply A1.left, }, cases A1, { left, apply A1.left, }, { right, apply A1.right, }, }, end /- There are theorems about disjoint properties, but not about disjoint sets. It would be good to figure out a long-term strategy of dealing with disjointedness, as it is pervasive through measure theory and probability theory. Disjoint is defined on lattices, and sets are basically the canonical complete lattice. However, the relationship between complementary sets and disjointedness is lost, as complementarity doesn't exist in a generic complete lattice. SIDE NOTE: lattice.lean now has a ton of theorems. Follow set.disjoint_compl_right -/ --Replace with disjoint.symm lemma set.disjoint.symm {α:Type*} {A B:set α}:disjoint A B → disjoint B A := begin apply @disjoint.symm (set α) _, end --Unused, but there are parallels in mathlib for finset and list. --Too trivial now. lemma set.disjoint_comm {α:Type*} {A B:set α}:disjoint A B ↔ disjoint B A := begin apply @disjoint.comm (set α) _, end lemma set.disjoint_compl_right {α:Type*} (B:set α):disjoint B Bᶜ := begin rw disjoint_iff, simp, end lemma set.disjoint_inter_compl {α:Type*} (A B C:set α):disjoint (A ∩ B) (C∩ Bᶜ) := begin apply set.disjoint_of_subset_left (set.inter_subset_right A B), apply set.disjoint_of_subset_right (set.inter_subset_right C Bᶜ), simp [disjoint_iff], end --In general, disjoint A C → disjoint (A ⊓ B) C lemma set.disjoint_inter_left {α:Type*} {A B C:set α}: disjoint A C → disjoint (A ∩ B) (C) := begin intros A1, apply set.disjoint_of_subset_left _ A1, apply set.inter_subset_left, end --In general, disjoint A C → disjoint A (B ⊓ C) lemma set.disjoint_inter_right {α:Type*} {A B C:set α}: disjoint A C → disjoint A (B ∩ C) := begin intros A1, apply set.disjoint_of_subset_right _ A1, apply set.inter_subset_right, end /- The connection between Union and supremum comes in useful in measure theory. The next three theorems do this directly. -/ lemma set.le_Union {α:Type*} {f:ℕ → set α} {n:ℕ}: f n ≤ set.Union f := begin rw set.le_eq_subset, rw set.subset_def, intros a A3, simp, apply exists.intro n A3, end lemma set.Union_le {α:Type*} {f:ℕ → set α} {S:set α}: (∀ i, f i ≤ S) → set.Union f ≤ S := begin intro A1, rw set.le_eq_subset, rw set.subset_def, intros x A2, simp at A2, cases A2 with n A2, apply A1 n A2, end lemma supr_eq_Union {α:Type*} {f:ℕ → set α}: supr f = set.Union f := begin apply le_antisymm, { apply @supr_le (set α) _ _, intro i, apply set.le_Union, }, { apply set.Union_le, intros n, apply @le_supr (set α) _ _, }, end lemma empty_of_subset_empty {α:Type*} (X:set α): X ⊆ ∅ → X = ∅ := begin have A1:(∅:set α) = ⊥ := rfl, rw A1, rw ← set.le_eq_subset, intro A2, rw le_bot_iff at A2, apply A2, end lemma subset_empty_iff {α:Type*} (X:set α): X ⊆ ∅ ↔ X = ∅ := begin have A1:(∅:set α) = ⊥ := rfl, rw A1, rw ← set.le_eq_subset, apply le_bot_iff, end lemma set.eq_univ_iff_univ_subset {α:Type*} {S:set α}: set.univ ⊆ S ↔ S = set.univ := begin have A1:@set.univ α = ⊤ := rfl, rw A1, rw ← set.le_eq_subset, apply top_le_iff, end lemma preimage_if {α β:Type*} {E:set α} {D:decidable_pred E} {X Y:α → β} {S:set β}: set.preimage (λ a:α, if (E a) then (X a) else (Y a)) S = (E ∩ set.preimage X S) ∪ (Eᶜ ∩ set.preimage Y S) := begin ext a;split;intros A1, { cases (classical.em (a∈ E)) with A2 A2, { rw set.mem_preimage at A1, rw if_pos at A1, apply set.mem_union_left, apply set.mem_inter A2, rw set.mem_preimage, apply A1, rw set.mem_def at A2, apply A2, }, { rw set.mem_preimage at A1, rw if_neg at A1, apply set.mem_union_right, apply set.mem_inter, apply set.mem_compl, apply A2, rw set.mem_preimage, apply A1, rw set.mem_def at A2, apply A2, }, }, { rw set.mem_preimage, rw set.mem_union at A1, cases A1 with A1 A1; rw set.mem_inter_eq at A1; cases A1 with A2 A3; rw set.mem_preimage at A3; rw set.mem_def at A2, { rw if_pos, apply A3, apply A2, }, { rw if_neg, apply A3, apply A2, }, }, end lemma set.insert_inter_of_not_mem {α:Type*} {A B:set α} {x:α}:(x∉ B) → ((insert x A) ∩ B = A ∩ B) := begin intros A1, ext a, split;intros A2;simp at A2;simp, { cases A2 with A2 A3, cases A2 with A2 A4, { subst A2, exfalso, apply A1 A3, }, { apply and.intro A4 A3, }, }, { apply and.intro (or.inr A2.left) A2.right, }, end lemma set.inter_insert_of_not_mem {α:Type*} {A B:set α} {x:α}:(x∉ A) → (A ∩ (insert x B) = A ∩ B) := begin intros A1, rw set.inter_comm, rw set.insert_inter_of_not_mem A1, rw set.inter_comm, end lemma set.not_mem_of_inter_insert {α:Type*} {A B:set α} {x:α}:(x∉ A) → (A ∩ (insert x B) = A ∩ B) := begin intros A1, rw set.inter_comm, rw set.insert_inter_of_not_mem A1, rw set.inter_comm, end lemma set.inter_insert_of_mem {α:Type*} {A B:set α} {x:α}:(x∈ A) → (A ∩ (insert x B) = insert x (A ∩ B)) := begin intros A1, rw set.insert_inter, rw set.insert_eq_of_mem A1, end lemma set.mem_of_inter_insert {α:Type*} {A B C:set α} {x:α}: (A ∩ (insert x B) = insert x (C)) → (x ∈ A) := begin intros A1, have B1 := set.mem_insert x (C), rw ← A1 at B1, simp at B1, apply B1, end lemma set.eq_of_insert_of_not_mem {α:Type*} {A B:set α} {x:α}:(x∉ A) → (x∉ B) → (insert x A = insert x B) → A = B := begin intros A1 A3 A2, ext a;split;intros B1;have C1 := set.mem_insert_of_mem x B1, { rw A2 at C1, apply set.mem_of_mem_insert_of_ne C1, intros C2, subst a, apply A1 B1, }, { rw ← A2 at C1, apply set.mem_of_mem_insert_of_ne C1, intros C2, subst a, apply A3 B1, }, end lemma directed_superset_of_monotone_dual {α:Type*} {f:ℕ → set α}: (@monotone ℕ (set α) _ (order_dual.preorder (set α)) f) → (directed superset f) := begin intros h_mono, intros i j, cases (le_total i j) with h_i_le_j h_j_le_i, { apply exists.intro j, split, apply h_mono, apply h_i_le_j, apply set.subset.refl }, { apply exists.intro i, split, apply set.subset.refl, apply h_mono, apply h_j_le_i }, end lemma monotone_of_monotone_nat_dual_iff {α:Type*} {f:ℕ → set α}: (@monotone ℕ (set α) _ (order_dual.preorder (set α)) f) ↔ (∀ (n:ℕ), f (n.succ) ⊆ f n) := begin split, { intros h_mono, intros n, apply h_mono, apply le_of_lt (nat.lt_succ_self _) }, { intros h_mono_nat, apply @monotone_of_monotone_nat (set α) (order_dual.preorder (set α)), intros n, apply h_mono_nat }, end lemma directed_superset_of_monotone_nat_dual {α:Type*} {f:ℕ → set α}: (∀ (n:ℕ), f (n.succ) ⊆ f n) → (directed superset f) := begin rw ← monotone_of_monotone_nat_dual_iff, apply directed_superset_of_monotone_dual, end /- Note: monotone is a stronger property than directed. e.g., directed can be increasing or decreasing, or have a single maximal element in the middle. -/ lemma directed_subset_of_monotone {α:Type*} {f:ℕ → set α}: monotone f → (directed set.subset f) := begin intros h_mono, intros i j, cases (le_total i j), { apply exists.intro j, split, apply h_mono h, apply set.subset.refl }, { apply exists.intro i, split, apply set.subset.refl, apply h_mono h }, end
38414108a298384ccf4d2328016fcf9c819b619e
47181b4ef986292573c77e09fcb116584d37ea8a
/src/valuations/bounded.lean
acc0e6c72876c8b26e96046d9c33e3df05f7797f
[ "MIT" ]
permissive
RaitoBezarius/berkovich-spaces
87662a2bdb0ac0beed26e3338b221e3f12107b78
0a49f75a599bcb20333ec86b301f84411f04f7cf
refs/heads/main
1,690,520,666,912
1,629,328,012,000
1,629,328,012,000
332,238,095
4
0
MIT
1,629,312,085,000
1,611,414,506,000
Lean
UTF-8
Lean
false
false
5,759
lean
import data.real.cau_seq import algebra.big_operators.basic import algebra.big_operators.ring import valuations.basic import for_mathlib.specific_limits open is_absolute_value open_locale classical big_operators lemma absolute_value_units_bounded {α} [ring α] [nontrivial α] (abv: α → ℝ) [is_absolute_value abv] (bounded: ∀ a: α, abv a ≤ 1): ∀ u: units α, abv u = 1 := begin intro u, by_contra h, have abvc_lt_one: abv u.val < 1 := lt_of_le_of_ne (bounded u) h, have prod_eq: abv u.val * abv u.inv = 1 * 1, by rw [← abv_mul abv, u.val_inv, abv_one abv, one_mul], have prod_lt: abv u.val * abv u.inv < 1 * 1, { have: u.inv ≠ 0, { intro h, have := u.val_inv, rw [h, mul_zero] at this, exact zero_ne_one this, }, exact mul_lt_mul abvc_lt_one (bounded u.inv) ((abv_pos abv).2 this) zero_le_one, }, exact (ne_of_lt prod_lt) prod_eq, end theorem nonarchimedian_iff_integers_bounded {α} [comm_ring α] [nontrivial α] (abv: α → ℝ) [is_absolute_value abv]: (∃ C: ℝ, 0 < C ∧ ∀ n: ℕ, abv n ≤ C) ↔ (∀ a b: α, abv (a + b) ≤ max (abv a) (abv b)) := begin split, { rintros ⟨ C, h ⟩ a b, have max_nonneg: 0 ≤ max (abv a) (abv b), from le_trans (abv_nonneg abv a) (le_max_left _ _), have: ∀ n: ℕ, abv (a + b) ^ n ≤ C * (n + 1) * (max (abv a) (abv b) ^ n), { intro n, have p₁: ∀ m ≤ n, abv (a^m * b^(n - m) * nat.choose n m) ≤ C * (max (abv a) (abv b) ^ n), { intros m hm, simp only [abv_mul abv, abv_pow abv], have p₁: abv a ^ m ≤ (max (abv a) (abv b)) ^ m, from pow_le_pow_of_le_left (abv_nonneg abv a) (le_max_left _ _) _, have p₂: abv b ^ (n - m) ≤ (max (abv a) (abv b)) ^ (n - m), from pow_le_pow_of_le_left (abv_nonneg abv b) (le_max_right _ _) _, have p₃: abv (nat.choose n m) ≤ C, from h.2 _, calc abv a ^ m * abv b ^ (n - m) * abv (nat.choose n m) ≤ max (abv a) (abv b) ^ m * max (abv a) (abv b) ^ (n - m) * C : by { refine mul_le_mul (mul_le_mul p₁ p₂ (pow_nonneg (abv_nonneg abv _) _) _) p₃ (abv_nonneg abv _) (mul_nonneg _ _); exact pow_nonneg max_nonneg _, } ... = (max (abv a) (abv b) ^ n) * C : by { rw ← pow_add, congr, exact nat.add_sub_cancel' hm, } ... = C * (max (abv a) (abv b) ^ n) : by ring, }, calc abv (a + b) ^ n = abv ((a + b) ^ n) : eq.symm (abv_pow abv _ _) ... = abv (∑ (m: ℕ) in finset.range (n + 1), a^m * b^(n - m) * nat.choose n m) : by { rw add_pow a b n, } ... ≤ ∑ (m: ℕ) in finset.range (n + 1), abv (a^m * b^(n - m) * nat.choose n m) : abv_sum_le_sum_abv _ _ ... ≤ ∑ (m: ℕ) in finset.range (n + 1), C * (max (abv a) (abv b) ^ n) : by { refine finset.sum_le_sum (λ m hm, p₁ m _), rw finset.mem_range at hm, linarith only [hm], } ... = C * ∑ (m: ℕ) in finset.range (n + 1), (max (abv a) (abv b) ^ n) : eq.symm finset.mul_sum ... = C * (n + 1) * (max (abv a) (abv b) ^ n) : by { simp, rw mul_assoc, }, }, suffices h₁: ∀ n: ℕ, (abv (a + b) ^ (n: ℝ)) ^ (1/n: ℝ) ≤ (C * (n + 1) * (max (abv a) (abv b) ^ (n: ℝ))) ^ (1/n: ℝ), { have: ∀ n: ℕ, 0 < n → abv (a + b) ≤ (C * (n + 1)) ^ (1/n: ℝ) * (max (abv a) (abv b)), { intros n hn, specialize h₁ n, rw ← real.rpow_mul (abv_nonneg abv (a + b)) _ _ at h₁, rw real.mul_rpow (mul_nonneg (le_of_lt h.1) (show 0 ≤ (n:ℝ) + 1, by { norm_cast, linarith, })) (real.rpow_nonneg_of_nonneg max_nonneg n) at h₁, rw ← real.rpow_mul max_nonneg _ _ at h₁, rw mul_one_div_cancel (show (n: ℝ) ≠ 0, by { norm_cast, exact ne.symm (ne_of_lt hn), } ) at h₁, repeat { rw real.rpow_one at h₁, }, exact h₁, }, have lim₀: filter.tendsto (λ n: ℕ, (C * (n + 1)) ^ (1/n: ℝ)) filter.at_top (nhds 1) := tendsto_comparison_at_top_nhds_1_of_pos h.1, have lim₁: filter.tendsto (λ n: ℕ, abv (a + b)) filter.at_top (nhds (abv (a + b))), { exact tendsto_const_nhds, }, have lim₂: filter.tendsto (λ n: ℕ, (C * (n + 1)) ^ (1/n: ℝ) * (max (abv a) (abv b))) filter.at_top (nhds (max (abv a) (abv b))), { convert filter.tendsto.mul_const (max (abv a) (abv b)) lim₀, rw one_mul, }, apply le_of_tendsto_of_tendsto lim₁ lim₂, simp only [filter.eventually_le, filter.eventually_at_top], exact ⟨ 1, λ n, this n ⟩, }, intro n, specialize this n, simp only [real.rpow_nat_cast], have low_bound: 0 ≤ C * (n + 1: ℝ) * max (abv a) (abv b) ^ n, from mul_nonneg (mul_nonneg (le_of_lt h.1) (by { norm_cast, simp, })) (pow_nonneg max_nonneg n), apply_fun (λ x: ℝ, (max 0 x) ^ (1/n: ℝ)) at this, simp only [abv_nonneg abv (a + b), low_bound, max_eq_right, pow_nonneg] at this, exact this, intros x y hxy, dsimp, apply real.rpow_le_rpow (le_max_left _ _) (max_le_max (le_refl 0) (hxy)) (one_div_nonneg.2 $ nat.cast_nonneg n), }, { intro h, use [1, zero_lt_one], intro n, induction n with n hn, simp [abv_zero abv, zero_le_one], rw ← nat.add_one, push_cast, calc abv (n + 1) ≤ max (abv n) (abv 1) : h n 1 ... ≤ max 1 1 : max_le_max hn (by { rw abv_one abv, }) ... = 1 : by simp, }, end
2e16aad890a490bc7a730b4e6e8f54e7880bf69d
94e33a31faa76775069b071adea97e86e218a8ee
/src/topology/G_delta.lean
a33ee4ce59df610e9c60efa9cc998f0460624afc
[ "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
6,859
lean
/- Copyright (c) 2019 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sébastien Gouëzel, Yury Kudryashov -/ import topology.uniform_space.basic import topology.separation /-! # `Gδ` sets In this file we define `Gδ` sets and prove their basic properties. ## Main definitions * `is_Gδ`: a set `s` is a `Gδ` set if it can be represented as an intersection of countably many open sets; * `residual`: the filter of residual sets. A set `s` is called *residual* if it includes a dense `Gδ` set. In a Baire space (e.g., in a complete (e)metric space), residual sets form a filter. For technical reasons, we define `residual` in any topological space but the definition agrees with the description above only in Baire spaces. ## Main results We prove that finite or countable intersections of Gδ sets is a Gδ set. We also prove that the continuity set of a function from a topological space to an (e)metric space is a Gδ set. ## Tags Gδ set, residual set -/ noncomputable theory open_locale classical topological_space filter uniformity open filter encodable set variables {α : Type*} {β : Type*} {γ : Type*} {ι : Type*} section is_Gδ variable [topological_space α] /-- A Gδ set is a countable intersection of open sets. -/ def is_Gδ (s : set α) : Prop := ∃T : set (set α), (∀t ∈ T, is_open t) ∧ T.countable ∧ s = (⋂₀ T) /-- An open set is a Gδ set. -/ lemma is_open.is_Gδ {s : set α} (h : is_open s) : is_Gδ s := ⟨{s}, by simp [h], countable_singleton _, (set.sInter_singleton _).symm⟩ @[simp] lemma is_Gδ_empty : is_Gδ (∅ : set α) := is_open_empty.is_Gδ @[simp] lemma is_Gδ_univ : is_Gδ (univ : set α) := is_open_univ.is_Gδ lemma is_Gδ_bInter_of_open {I : set ι} (hI : I.countable) {f : ι → set α} (hf : ∀i ∈ I, is_open (f i)) : is_Gδ (⋂i∈I, f i) := ⟨f '' I, by rwa ball_image_iff, hI.image _, by rw sInter_image⟩ lemma is_Gδ_Inter_of_open [encodable ι] {f : ι → set α} (hf : ∀i, is_open (f i)) : is_Gδ (⋂i, f i) := ⟨range f, by rwa forall_range_iff, countable_range _, by rw sInter_range⟩ /-- The intersection of an encodable family of Gδ sets is a Gδ set. -/ lemma is_Gδ_Inter [encodable ι] {s : ι → set α} (hs : ∀ i, is_Gδ (s i)) : is_Gδ (⋂ i, s i) := begin choose T hTo hTc hTs using hs, obtain rfl : s = λ i, ⋂₀ T i := funext hTs, refine ⟨⋃ i, T i, _, countable_Union hTc, (sInter_Union _).symm⟩, simpa [@forall_swap ι] using hTo end lemma is_Gδ_bInter {s : set ι} (hs : s.countable) {t : Π i ∈ s, set α} (ht : ∀ i ∈ s, is_Gδ (t i ‹_›)) : is_Gδ (⋂ i ∈ s, t i ‹_›) := begin rw [bInter_eq_Inter], haveI := hs.to_encodable, exact is_Gδ_Inter (λ x, ht x x.2) end /-- A countable intersection of Gδ sets is a Gδ set. -/ lemma is_Gδ_sInter {S : set (set α)} (h : ∀s∈S, is_Gδ s) (hS : S.countable) : is_Gδ (⋂₀ S) := by simpa only [sInter_eq_bInter] using is_Gδ_bInter hS h lemma is_Gδ.inter {s t : set α} (hs : is_Gδ s) (ht : is_Gδ t) : is_Gδ (s ∩ t) := by { rw inter_eq_Inter, exact is_Gδ_Inter (bool.forall_bool.2 ⟨ht, hs⟩) } /-- The union of two Gδ sets is a Gδ set. -/ lemma is_Gδ.union {s t : set α} (hs : is_Gδ s) (ht : is_Gδ t) : is_Gδ (s ∪ t) := begin rcases hs with ⟨S, Sopen, Scount, rfl⟩, rcases ht with ⟨T, Topen, Tcount, rfl⟩, rw [sInter_union_sInter], apply is_Gδ_bInter_of_open (Scount.prod Tcount), rintros ⟨a, b⟩ ⟨ha, hb⟩, exact (Sopen a ha).union (Topen b hb) end /-- The union of finitely many Gδ sets is a Gδ set. -/ lemma is_Gδ_bUnion {s : set ι} (hs : s.finite) {f : ι → set α} (h : ∀ i ∈ s, is_Gδ (f i)) : is_Gδ (⋃ i ∈ s, f i) := begin refine finite.induction_on hs (by simp) _ h, simp only [ball_insert_iff, bUnion_insert], exact λ a s _ _ ihs H, H.1.union (ihs H.2) end lemma is_closed.is_Gδ {α} [uniform_space α] [is_countably_generated (𝓤 α)] {s : set α} (hs : is_closed s) : is_Gδ s := begin rcases (@uniformity_has_basis_open α _).exists_antitone_subbasis with ⟨U, hUo, hU, -⟩, rw [← hs.closure_eq, ← hU.bInter_bUnion_ball], refine is_Gδ_bInter (countable_encodable _) (λ n hn, is_open.is_Gδ _), exact is_open_bUnion (λ x hx, uniform_space.is_open_ball _ (hUo _).2) end section t1_space variable [t1_space α] lemma is_Gδ_compl_singleton (a : α) : is_Gδ ({a}ᶜ : set α) := is_open_compl_singleton.is_Gδ lemma set.countable.is_Gδ_compl {s : set α} (hs : s.countable) : is_Gδ sᶜ := begin rw [← bUnion_of_singleton s, compl_Union₂], exact is_Gδ_bInter hs (λ x _, is_Gδ_compl_singleton x) end lemma set.finite.is_Gδ_compl {s : set α} (hs : s.finite) : is_Gδ sᶜ := hs.countable.is_Gδ_compl lemma set.subsingleton.is_Gδ_compl {s : set α} (hs : s.subsingleton) : is_Gδ sᶜ := hs.finite.is_Gδ_compl lemma finset.is_Gδ_compl (s : finset α) : is_Gδ (sᶜ : set α) := s.finite_to_set.is_Gδ_compl open topological_space variables [first_countable_topology α] lemma is_Gδ_singleton (a : α) : is_Gδ ({a} : set α) := begin rcases (nhds_basis_opens a).exists_antitone_subbasis with ⟨U, hU, h_basis⟩, rw [← bInter_basis_nhds h_basis.to_has_basis], exact is_Gδ_bInter (countable_encodable _) (λ n hn, (hU n).2.is_Gδ), end lemma set.finite.is_Gδ {s : set α} (hs : s.finite) : is_Gδ s := finite.induction_on hs is_Gδ_empty $ λ a s _ _ hs, (is_Gδ_singleton a).union hs end t1_space end is_Gδ section continuous_at open topological_space open_locale uniformity variables [topological_space α] /-- The set of points where a function is continuous is a Gδ set. -/ lemma is_Gδ_set_of_continuous_at [uniform_space β] [is_countably_generated (𝓤 β)] (f : α → β) : is_Gδ {x | continuous_at f x} := begin obtain ⟨U, hUo, hU⟩ := (@uniformity_has_basis_open_symmetric β _).exists_antitone_subbasis, simp only [uniform.continuous_at_iff_prod, nhds_prod_eq], simp only [(nhds_basis_opens _).prod_self.tendsto_iff hU.to_has_basis, forall_prop_of_true, set_of_forall, id], refine is_Gδ_Inter (λ k, is_open.is_Gδ $ is_open_iff_mem_nhds.2 $ λ x, _), rintros ⟨s, ⟨hsx, hso⟩, hsU⟩, filter_upwards [is_open.mem_nhds hso hsx] with _ hy using ⟨s, ⟨hy, hso⟩, hsU⟩, end end continuous_at /-- A set `s` is called *residual* if it includes a dense `Gδ` set. If `α` is a Baire space (e.g., a complete metric space), then residual sets form a filter, see `mem_residual`. For technical reasons we define the filter `residual` in any topological space but in a non-Baire space it is not useful because it may contain some non-residual sets. -/ def residual (α : Type*) [topological_space α] : filter α := ⨅ t (ht : is_Gδ t) (ht' : dense t), 𝓟 t
c826854572930d2d6809cf7084a1f09a173de87c
37becf0efe4d7dede56551dfb45910cf3f9f579e
/src/ecff/euler_continued.lean
74530b011652287ab7ddf07bd4bfc524d00362ed
[]
no_license
Pazzaz/lean-math
c66ff4ea9e99d4fbd9c3143e1a055f72a7bb936d
a61df645dcc7d91d1454129dd68833821ff02fb7
refs/heads/master
1,679,198,234,708
1,615,995,023,000
1,615,995,023,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
25,839
lean
import algebra.continued_fractions import data.real.basic import algebra.continued_fractions.convergents_equiv import tactic.unfold_cases open generalized_continued_fraction as gcf -- 1. Skriv ut theorem för \R -- 1. använd convergents' -- `sum_prod a_k n` = ∑_{i=1}^{n} (∏_{j=1}^{i} a_j) def sum_prod {K : Type*} [semiring K] (A : seq K) (n : ℕ) : K := ((list.range n).map (λ (i : ℕ), (A.take (i+1)).prod ) ).sum theorem cons_take_eq_take_cons {X : Type*} (a : X) (A : seq X) (i : ℕ) : (A.cons a).take (i+1) = (A.take i).cons a := begin unfold seq.take, rw seq.destruct_cons a, have hue : seq.take._match_1 (seq.take i) (some (a, A)) = list.cons a (seq.take i A) := rfl, rw hue, end /- Extract the first value from a sum of products Σ_{i=0}^{A.length-1} Π_{j=0}^{i} A.nth j -/ theorem sum_prod_list_tail {K : Type*} [semiring K] (a : K) (A : list K) : ((list.range (a :: A).length).map (λ (i : ℕ), ((a :: A).take (i+1)).prod ) ).sum = a + a * ((list.range A.length).map (λ (i : ℕ), (A.take (i+1)).prod )).sum := begin let f := (λ i, (A.take i).prod ), calc ((list.range (a :: A).length).map (λ i, ((a :: A).take (i+1)).prod ) ).sum = ((list.range (a :: A).length).map (λ i, a * f i ) ).sum : by finish ... = a * ((list.range (a :: A).length).map f ).sum : list.sum_map_mul_left (list.range (a :: A).length) f a ... = a * ((list.range (A.length + 1) ).map f ).sum : rfl ... = a * ((list.cons 0 ((list.range A.length).map (nat.succ))).map f).sum : by rw list.range_succ_eq_map A.length ... = a * (list.cons (f 0) (((list.range A.length).map (nat.succ)).map f)).sum : rfl ... = a * (list.cons (f 0) ((list.range A.length).map (λ i, f (i+1) ))).sum : by rw list.map_map f nat.succ (list.range A.length) ... = a * (list.cons 1 ((list.range A.length).map (λ i, f (i+1) ))).sum : rfl ... = a*1 + a*(((list.range A.length).map (λ i, f (i+1) ))).sum : by { rw list.sum_cons, exact mul_add a 1 _} ... = a + a*(((list.range A.length).map (λ i, f (i+1) ))).sum : by rw mul_one a end theorem sum_prod_tail {K : Type*} [semiring K] (A : seq K) (a : K) (n : ℕ) : sum_prod (seq.cons a A) (n+1) = a + a * sum_prod A n := begin let f := (λ i, (A.take i).prod ), calc sum_prod (A.cons a) (n+1) = ((list.range (n+1)).map (λ i, ((A.cons a).take (i+1)).prod ) ).sum : rfl ... = ((list.range (n+1)).map (λ i, ((A.take i).cons a).prod ) ).sum : by { congr, refine funext _, intro nn, exact congr rfl (cons_take_eq_take_cons a A nn), } ... = ((list.range (n+1)).map (λ i, a * f i)).sum : by { congr, refine funext _, intro _, exact list.prod_cons, } ... = a * ((list.range (n+1)).map f).sum : list.sum_map_mul_left (list.range (n+1)) f a ... = a * ((list.cons 0 ((list.range n).map (nat.succ))).map f).sum : by rw list.range_succ_eq_map n ... = a * (list.cons (f 0) (((list.range n).map (nat.succ)).map f) ).sum : rfl ... = a * (list.cons (f 0) (((list.range n)).map (λ i, f (i+1) )) ).sum : by rw (list.map_map f nat.succ (list.range n)) ... = a * (list.cons 1 (((list.range n)).map (λ i, f (i+1) )) ).sum : rfl ... = a * (1 + (((list.range n)).map (λ i, f (i+1) ) ).sum) : by rw list.sum_cons ... = a*1 + (a * (((list.range n)).map (λ i, f (i+1) ) ).sum) : mul_add a 1 ((list.range n).map (λ i, (A.take (i+1)).prod)).sum ... = a + (a * (((list.range n)).map (λ i, f (i+1) ) ).sum) : by rw mul_one a end def simple_part {X : Type*} [division_ring X] (A : seq X) : gcf X := ⟨0, A.map (λ ai, ⟨-ai, 1 + ai⟩ )⟩ @[simp] theorem simple_part_h {X : Type*} [division_ring X] (A : seq X) : (simple_part A).h = 0 := rfl @[simp] theorem simple_part_s {X : Type*} [division_ring X] (A : seq X) : (simple_part A).s = A.map (λ ai, ⟨-ai, 1 + ai⟩ ) := rfl def gcf_cons {X : Type*} (p : gcf.pair X) (A : gcf X) : gcf X := ⟨A.h, seq.cons p A.s⟩ theorem gcf_cons_def {X : Type*} (p : gcf.pair X) (A : gcf X) : gcf_cons p A = ⟨A.h, seq.cons p A.s⟩ := rfl @[simp] theorem gcf_cons_ignore_int {X : Type*} (p : gcf.pair X) (A : gcf X) : (gcf_cons p A).h = A.h := rfl @[simp] theorem gcf_cons_eq_seq_cons {X : Type*} (p : gcf.pair X) (A : gcf X) : (gcf_cons p A).s = seq.cons p A.s := rfl -- TODO: Är det här rätt definition? Vad händer om det är en väldigt kort sekvens? -- ⟨a0, 1⟩ ⟨-a1, 1+a1⟩ ⟨-a2, 1+a2⟩... def rhs_euler {X : Type*} [division_ring X] (A : seq X) : gcf X := begin let splitted := seq.split_at 1 A, let head := splitted.1.map (λ (a0 : X), gcf.pair.mk a0 1), let head_seq := seq.of_list head, let tail := splitted.2.map (λ (ai : X), gcf.pair.mk (-ai) (1+ai)), let joined := seq.append head_seq tail, exact ⟨0,joined⟩, end -- def map_head -- {X Y : Type*} -- (f_head f : X → Y) -- (A : seq X) -- : seq Y -- := seq.zip_with (λ(n : ℕ) (x : X), ite (n = 0) (f_head x) (f x)) seq.nats A /- Apply one function to the head of the list and one function to the rest-/ def map_head {X Y : Type*} (f_head f : X → Y) (A : seq X) : seq Y := option.get_or_else (option.map ((λ (a : seq1 X), seq1.to_seq ((f_head a.1, a.2.map f)))) (seq.destruct A)) seq.nil theorem option_get_or_else_dist {X Y: Type*} (e : X) (t : option X) (f : X → Y) : f (option.get_or_else t e) = option.get_or_else (t.map f) (f e) := begin cases t, rw option.map_none', exact rfl, simp only [option.get_or_else_some, option.map_some', eq_self_iff_true], end theorem seq_1_to_seq_tail {X : Type*} (a : X) (A : seq X) : (seq1.to_seq (a, A)).tail = A := seq.tail_cons a A @[simp] theorem map_head_tail_eq_map' {X Y : Type*} (f_head f : X → Y) (A : seq X) : (map_head f_head f A).tail = A.tail.map f := begin unfold map_head, rw option_get_or_else_dist seq.nil _ seq.tail, simp only [option.map_map, seq.map_tail, seq.tail_nil], rw function.comp, conv in (λ (a : seq1 X), (seq1.to_seq (f_head a.fst, seq.map f a.snd)).tail) { funext, rw seq_1_to_seq_tail _ _, skip, }, classical, cases decidable.em (A.destruct = none) with hn hs, { rw hn, rw seq.destruct_eq_nil hn, simp only [seq.map_nil, seq.tail_nil, option.map_none'], exact rfl, }, { have a_tail_zero_some : ↥(option.is_some (A.destruct)) := option.ne_none_iff_is_some.mp hs, let dest := option.get a_tail_zero_some, have A_destruct_eq_some_dest : A.destruct = some dest := (option.some_get a_tail_zero_some).symm, rw A_destruct_eq_some_dest, have huehue : option.map (λ (a : seq1 X), seq.map f a.snd) (some dest) = some ((λ (a : seq1 X), seq.map f a.snd) dest) := rfl, rw huehue, simp, have A_destruct_split : A.destruct = some (dest.1, dest.2) := by {rw A_destruct_eq_some_dest, refine congr rfl _, exact prod.ext rfl rfl}, have A_tail_eq_dest := congr_arg seq.tail (seq.destruct_eq_cons A_destruct_split), simp at A_tail_eq_dest, rw A_tail_eq_dest.symm, exact seq.map_tail f A, } end @[simp] theorem map_head_head_eq_map' {X Y : Type*} (f_head f : X → Y) (A : seq X) : (map_head f_head f A).head = A.head.map f_head := begin unfold map_head, rw option_get_or_else_dist seq.nil _ seq.head, simp, sorry, end /-- Extracts the first term of a continued fraction -/ @[simp] theorem cons_convergents'_eq_div_plus_convergents' {K : Type*} [division_ring K] (a b : K) (A : gcf K) {h : A.h = 0} (n : ℕ) : (gcf_cons (gcf.pair.mk a b) A).convergents' (n+1) = (a / (b + A.convergents' n)) := begin unfold gcf_cons at *, unfold gcf.convergents' at *, rw h, simp, unfold gcf.convergents'_aux, simp, unfold gcf.convergents'_aux._match_1, end @[simp] theorem nilling (X : Type*) : seq.split_at 1 seq.nil = ⟨[], (seq.nil : seq X)⟩ := rfl theorem split_at_one_cons_snd_eq_id {X : Type*} [division_ring X] (A : seq X) (a : X) : (seq.split_at 1 (seq.cons a A)).snd = A := begin unfold seq.split_at, rw seq.destruct_cons, exact rfl, end theorem split_at_one_cons_fst_eq_cons {X : Type*} [division_ring X] (A : seq X) (a : X) : (seq.split_at 1 (seq.cons a A)).fst = [a] := begin unfold seq.split_at, rw seq.destruct_cons, exact rfl, end theorem rhs_euler_eq {X : Type*} [division_ring X] (A : seq X) (a : X) (n : ℕ) : (rhs_euler (seq.cons a A)).convergents' n.succ = a / ( 1 + (simple_part A).convergents' n) := begin rw ←cons_convergents'_eq_div_plus_convergents', rw gcf_cons_def, congr, unfold rhs_euler, simp only [], split, exact rfl, rw simple_part_s, rw split_at_one_cons_snd_eq_id, rw split_at_one_cons_fst_eq_cons, simp, exact simple_part_h A, end theorem rhs_euler_nil {X : Type*} [division_ring X] : rhs_euler (seq.nil : seq X) = ⟨0, seq.nil⟩ := begin unfold rhs_euler, simp only [seq.append_nil, list.map_nil, nilling, eq_self_iff_true, seq.map_nil, and_self, seq.of_list_nil], end @[simp] theorem seq_map_head {A B : Type*} (S : seq A) (f : A → B) (nth_zero_some: (↥((S.nth 0).is_some) : Prop)) : option.map f S.head = some (f (option.get nth_zero_some)) := begin have nth_zero_eq_head : S.nth 0 = S.head := rfl, rw nth_zero_eq_head at nth_zero_some, have dkkdk : S.head = some (option.get nth_zero_some) := by norm_num, have duedue : option.map f (some (option.get nth_zero_some)) = some (f (option.get nth_zero_some)) := rfl, rw dkkdk, exact duedue, end theorem sub_div_suc_ne_sub_one {X : Type*} [division_ring X] (a : X) : -a / (1 + a) ≠ -1 := begin classical, rw neg_div (1 + a) a, refine function.injective.ne neg_injective _, by_contra h, simp only [not_not, ne.def] at h, have gkgk : a - a = 1 + a - a := congr (congr_arg has_sub.sub (eq_of_div_eq_one h)) rfl, rw [add_sub_assoc 1 a a, sub_self a, add_zero (1 : X)] at gkgk, exact zero_ne_one gkgk, end theorem jdjdjd {X : Type*} [division_ring X] : (0 : X) ≠ 1 := zero_ne_one theorem hueheeuh2 {X : Type*} [division_ring X] (a b : X) : a ≠ b → -a ≠ -b := begin intro k, exact function.injective.ne neg_injective k, end theorem add_to_denom_of_succ_ne_sub_one {X : Type*} [division_ring X] (a b : X) (h : b ≠ -1) : -a / (1 + a + b) ≠ -1 := begin rw neg_div (1 + a + b) a, apply hueheeuh2, classical, cases decidable.em ((1 + a + b) = 0), rw [h_1, div_zero a], exact zero_ne_one, by_contradiction wack, rw not_not at wack, have huehu := (div_eq_one_iff_eq h_1).mp wack, rw [add_comm 1 a, add_assoc a 1 b] at huehu, have nexter : (1 + b) = 0 := self_eq_add_right.mp huehu, rw [add_comm 1 b, ←sub_neg_eq_add b 1] at nexter, exact h (sub_eq_zero.mp nexter), end --theorem rhs_euler_eq theorem simple_convergents_ne_sub_one {X : Type*} [division_ring X] (A : seq X) (n : ℕ) (h_in : A.nth n ≠ none) : (simple_part A).convergents' n ≠ -1 := begin induction n with h hd generalizing A, { unfold simple_part, simp only [ gcf.zeroth_convergent'_eq_h, ne.def, not_false_iff, one_ne_zero, zero_eq_neg ], }, { have a_zero_some : ↥(option.is_some (A.nth 0)) := option.ne_none_iff_is_some.mp (mt (seq.le_stable A bot_le) h_in), let a0 := option.get a_zero_some, have cons_adder := seq.destruct_eq_cons (seq_map_head A (λ a', (a', A.tail)) a_zero_some), unfold simple_part, rw cons_adder, simp only [seq.map_tail, seq.map_cons], let f := (λ (ai : X), gcf.pair.mk (-ai) (1 + ai)), let thing : gcf X := ⟨0, (seq.map f A).tail⟩, rw ←gcf_cons_def (gcf.pair.mk (-a0) (1 + a0)) thing, have kkkk: thing.h = 0 := rfl, rw @cons_convergents'_eq_div_plus_convergents' _ _ _ _ _ kkkk _, have back_again : thing = simple_part A.tail := by { unfold simple_part, rw (seq.map_tail f A), }, rw back_again, have A_tail_nth_ne_none : A.tail.nth h ≠ none := by {rw (seq.nth_tail A h), exact h_in}, exact add_to_denom_of_succ_ne_sub_one a0 ((simple_part A.tail).convergents' h) (hd A.tail A_tail_nth_ne_none), } end -- gcf.convergents'_aux._match_1 0 (seq.map (λ (ai : ℝ), {a := -ai, b := 1 + ai}) A).head #check gcf.convergents'_aux._match_1 theorem seq_map_eq_list_map (X Y : Type*) [division_ring X] (f : X -> Y) (A : seq ( gcf.pair X)) (n : ℕ) (h1 : (A.nth 0) ≠ none ) (h2 : (A.nth 1) ≠ none ) : gcf.convergents'_aux A 1 = (option.get (option.ne_none_iff_is_some.mp h1)).a / (option.get (option.ne_none_iff_is_some.mp h1)).b := sorry -- theorem test1 -- (a b : Prop) -- : (a -> b) -> (¬b -> ¬a) -- := begin -- library_search, -- end -- theorem euler_b -- (A : seq ℝ) -- (n : ℕ) -- (h : A.nth n ≠ none) -- : ≠ -1 -- := begin -- induction n with h hd, -- unfold rhs_euler, -- simp, -- induction h with h2 hd2, -- unfold rhs_euler, -- simp, -- end -- The rhs has a singularity at x = -1 -a. If it was set to 0 at that point, both sides would be equal then x ≠ -1 theorem move_divs {X : Type*} [division_ring X] (a x : X) (h1 : x ≠ -1) (h2 : x ≠ -1 - a) : (1 / (1 + (-a / (1 + a + x)))) = 1 + (a / (1 + x)) := begin classical, have yepp : (1 + a + x) ≠ 0 := begin by_contradiction, rw not_not at h, have mumu: x = -(1+a) := (neg_eq_of_add_eq_zero h).symm, rw neg_add' 1 a at mumu, exact h1 (absurd mumu h2), end, have yepp2 : 1 + x ≠ 0 := begin by_contradiction, rw not_not at h, have mumu: x = -1 := (neg_eq_of_add_eq_zero h).symm, exact h1 mumu, end, calc 1 / (1 + (-a / (1 + a + x))) = 1 / ((1 + a + x)/(1 + a + x) + (-a / (1 + a + x))) : by {congr, exact (div_self yepp).symm,} ... = 1 / ((1 + a + x + -a) / (1 + a + x)) : by rw div_add_div_same (1 + a + x) (-a) (1 + a + x) ... = 1 / ((1 + a + -a + x) / (1 + a + x)) : by rw add_right_comm (1 + a) x (-a) ... = 1 / ((1 + x) / (1 + a + x)) : by rw add_neg_eq_of_eq_add rfl ... = (1 + a + x) / (1 + x) : one_div_div (1 + x) (1 + a + x) ... = (1 + x + a) / (1 + x) : by rw add_right_comm 1 x a ... = ((1 + x) / (1 + x)) + (a / (1 + x)) : add_div (1 + x) a (1 + x) ... = 1 + (a / (1 + x)) : by rw div_self yepp2 end /- This is **Euler's Continued Fraction Formula**. We have `h2` to avoid division in the continued fraction. These are normally ignored. If you treat the continued fraction as a function then it can be extended to ignore the singularities. These issues can't be ignored when formalizing. -/ theorem euler_cff {X : Type*} [division_ring X] (A : seq X) (n : ℕ) (h : A.nth n ≠ none) (h2 : ∀ n1, n1 < n → 1 ≤ n1 → some ((simple_part (A.drop n1.succ)).convergents' (n-(n1.succ))) ≠ (A.nth n1).map (λ an1, -(1 + an1)) ) : sum_prod A n = (rhs_euler A).convergents' n := begin induction n with hi hdi generalizing A, { unfold sum_prod, unfold rhs_euler, simp only [ list.sum_nil, nat.nat_zero_eq_zero, list.map_nil, eq_self_iff_true, gcf.zeroth_convergent'_eq_h, list.range_zero ], }, { have A_tail_nth_ne_none : A.tail.nth hi ≠ none := by { rw seq.nth_tail A hi, exact h, }, have A_tail_nth_zero_ne_none : A.tail.nth 0 ≠ none := mt (seq.le_stable A.tail (bot_le)) A_tail_nth_ne_none, have a_tail_zero_some : ↥(option.is_some (A.tail.nth 0)) := option.ne_none_iff_is_some.mp A_tail_nth_zero_ne_none, have thingy3 : A.nth 0 ≠ none := mt (seq.le_stable A (bot_le)) h, have a_zero_some : ↥(option.is_some (A.nth 0)) := option.ne_none_iff_is_some.mp thingy3, have cons_adder := seq.destruct_eq_cons (seq_map_head A (λ a', (a', A.tail)) a_zero_some), set a0 := option.get a_zero_some, set a1 := option.get a_tail_zero_some, induction hi with hi hi2, { unfold sum_prod, unfold rhs_euler, have yepp: list.range 1 = [0] := rfl, rw yepp, simp, rw cons_adder, rw split_at_one_cons_fst_eq_cons, rw split_at_one_cons_snd_eq_id, have yepping : seq.take 1 (seq.cons a0 A.tail) = [a0] := begin rw cons_take_eq_take_cons a0 A.tail 0, simp only [true_and, eq_self_iff_true], exact rfl, end, rw yepping, simp only [ seq.nil_append, mul_one, list.map.equations._eqn_2, seq.map_tail, seq.cons_append, list.map_nil, list.prod_cons, list.prod_nil, seq.of_list_nil, seq.of_list_cons ], rw ←gcf_cons_def ⟨a0, 1⟩ ⟨0, (seq.map (λ (ai : X), gcf.pair.mk (-ai) (1 + ai)) A).tail⟩, rw cons_convergents'_eq_div_plus_convergents' _ _ _, simp only [add_zero, eq_self_iff_true, generalized_continued_fraction.zeroth_convergent'_eq_h, div_one], }, { have cons_adder_two : A.tail = (seq.cons a1 A.tail.tail) := seq.destruct_eq_cons (seq_map_head A.tail (λ a', (a', A.tail.tail)) a_tail_zero_some), have gotem := hdi A.tail A_tail_nth_ne_none _, have fkfkfk : A.tail.tail.nth hi ≠ none := by {rw seq.nth_tail _ _, exact A_tail_nth_ne_none,}, calc sum_prod A hi.succ.succ = sum_prod (A.tail.cons a0) hi.succ.succ : by nth_rewrite 0 cons_adder ... = a0 + a0 * sum_prod A.tail hi.succ : sum_prod_tail (A.tail) a0 hi.succ ... = a0 + a0 * ((rhs_euler A.tail).convergents' hi.succ) : by rw gotem ... = a0 * 1 + a0 * ((rhs_euler A.tail).convergents' hi.succ) : by rw mul_one a0 ... = a0 * (1 + ((rhs_euler A.tail).convergents' hi.succ)) : by rw (mul_add a0 1 _).symm ... = a0 * (1 + ((rhs_euler (seq.cons a1 A.tail.tail)).convergents' hi.succ)) : by { congr, exact cons_adder_two, } ... = a0 * (1 + (a1 / ( 1 + (simple_part A.tail.tail).convergents' hi))) : by { congr, exact (rhs_euler_eq A.tail.tail a1 hi),} ... = a0 * (1 /(1 + (-a1 / ( 1 + a1 + (simple_part A.tail.tail).convergents' hi)))) : by { congr, have kdkdkdk := (move_divs a1 ((simple_part A.tail.tail).convergents' hi) _ _).symm, exact kdkdkdk, have kkkkk := simple_convergents_ne_sub_one A.tail.tail hi, exact kkkkk fkfkfk, simp only [ nat.succ_sub_succ_eq_sub, seq.drop.equations._eqn_1, ne.def, nat.sub_zero, seq.drop.equations._eqn_2], have from_hyp : some ((simple_part A.tail.tail).convergents' hi) ≠ option.map (λ (an1 : X), -(1 + an1)) (A.nth 1) := h2 1 _ rfl.ge, have to_tail: (A.nth 1) = A.tail.nth 0 := (seq.nth_tail A 0).symm, have a1er : option.get a_tail_zero_some = a1 := rfl, rw [ to_tail, (option.some_get a_tail_zero_some).symm, a1er, option.map_some', neg_add] at from_hyp, apply ne_of_apply_ne some, rw (sub_eq_add_neg (-1) a1).symm at from_hyp, exact from_hyp, exact (cmp_eq_lt_iff 1 (nat.succ hi).succ).mp rfl, } ... = a0 * (1 / (1 + (simple_part A.tail).convergents' hi.succ)) : by { congr, have kdkdkd := (cons_convergents'_eq_div_plus_convergents' (-a1) (1 + a1) (simple_part A.tail.tail) hi).symm, unfold simple_part at kdkdkd, rw gcf_cons_def _ _ at kdkdkd, simp at kdkdkd, set f := (λ (ai : X), (⟨-ai, 1 + ai⟩ : gcf.pair X)), have bring_in_tail := eq.symm (seq.map_tail f A), rw (seq.map_tail f A ).symm at kdkdkd, rw (seq.map_tail f A.tail).symm at kdkdkd, rw (seq.map_cons f a1 A.tail.tail).symm at kdkdkd, rw cons_adder_two.symm at kdkdkd, exact kdkdkd, exact rfl, } ... = (a0*1) / (1 + (simple_part A.tail).convergents' hi.succ) : by rw mul_div_assoc' a0 1 _ ... = a0 / (1 + (simple_part A.tail).convergents' hi.succ) : by rw mul_one a0 ... = (rhs_euler (seq.cons a0 A.tail)).convergents' hi.succ.succ : (rhs_euler_eq A.tail a0 hi.succ).symm ... = (rhs_euler A).convergents' hi.succ.succ : by rw eq.symm cons_adder, { intros nn nn_lt_hi_succ nn_le_one, have fone : nn + 1 < hi.succ.succ := nat.lt_succ_iff.mpr nn_lt_hi_succ, have ftwo : 1 ≤ nn + 1 := nat.lt.step nn_le_one, have nicer := h2 (nn + 1) fone ftwo, rw (seq.dropn_tail A (nn+1)).symm at nicer, have kdkdkdk : hi.succ.succ - (nn + 1).succ = hi.succ - nn.succ := by norm_num, rw kdkdkdk at nicer, rw (seq.nth_tail A nn).symm at nicer, exact nicer, } },}, end def map_head_list {X Y: Type*} (f_head f : X → Y) (A : list X) : list Y := A.map_with_index (λ i x, ite (i = 0) (f_head x) (f x)) @[simp] theorem map_head_list_tail_eq_map {X Y : Type*} (f_head f : X → Y) (A : list X) : (map_head_list f_head f A).tail = A.tail.map f := sorry theorem euler_cff_list {X : Type*} [division_ring X] (A : list X) (h2 : ∀ n1 (h : n1 < A.length), 1 ≤ n1 → ((⟨0, (A.drop n1.succ).map (λ (ai : X), gcf.pair.mk (-ai) (1+ai)) ⟩ : gcf X ).convergents' (A.length-(n1.succ))) ≠ (λ (an1 : X), -(1 + an1)) (A.nth_le n1 h)) : ((list.range A.length).map (λ (i : ℕ), (A.take (i+1)).prod ) ).sum = (⟨0, (map_head_list (λ (a0 : X), gcf.pair.mk a0 1) (λ ai, gcf.pair.mk (-ai) (1 + ai) ) A)⟩ : gcf X ).convergents' A.length := sorry -- This should be the easiest to work with. Most lists are longer than 1. -- TODO: Should you just have a hypothesis of `0 < A.length`? theorem euler_cff_list_cons {X : Type*} [division_ring X] (A : list X) (a : X) (h2 : ∀ n1 (h : n1 < (a :: A).length), 1 ≤ n1 → ((⟨0, ((a :: A).drop n1.succ).map (λ (ai : X), gcf.pair.mk (-ai) (1+ai)) ⟩ : gcf X ).convergents' ((a :: A).length-(n1.succ))) ≠ (λ (an1 : X), -(1 + an1)) ((a :: A).nth_le n1 h)) : ((list.range (a :: A).length).map (λ (i : ℕ), ((a :: A).take (i+1)).prod ) ).sum = (⟨0, (list.cons (gcf.pair.mk a 1) (A.map (λ ai, gcf.pair.mk (-ai) (1 + ai) )))⟩ : gcf X ).convergents' (a :: A).length := sorry theorem dkdkdk (X : Type*) (hi : ℕ) (nn : ℕ) (A : seq X) : A.nth (nn + 1) = A.tail.nth nn := by { refine eq.symm _, exact seq.nth_tail A nn} -- theorem hueheuhe -- (a : ℝ) -- : (1 / (1 / a)) = a -- := one_div_one_div a, -- 2. Skriv ut de olika delarna av induktionbeviset och bevisa dem -- 1. Bevisa "bla bla \neq -1" som ett separat lemma, fortfarande med induktion. -- 2. Bevisa det vi bryr oss om. -- 3. Sätt ihop dem. -- 1. Man kanske kommer behöva göra något smart för att visa att det gäller i det oändliga fallet -- 4. Generalisera till komplexa tal. -- 5. Generalisera till något annat?
0dd5acd26ad8f342e38b4981cbf2f49e16b1b308
4727251e0cd73359b15b664c3170e5d754078599
/src/measure_theory/group/pointwise.lean
86bbc5f745e233e26f9af8ac1b1d02e1298f8872
[ "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
1,656
lean
/- Copyright (c) 2021 Yury G. Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury G. Kudryashov, Alex J. Best -/ import measure_theory.group.arithmetic /-! # Pointwise set operations on `measurable_set`s In this file we prove several versions of the following fact: if `s` is a measurable set, then so is `a • s`. Note that the pointwise product of two measurable sets need not be measurable, so there is no `measurable_set.mul` etc. -/ open_locale pointwise open set @[to_additive] lemma measurable_set.const_smul {G α : Type*} [group G] [mul_action G α] [measurable_space G] [measurable_space α] [has_measurable_smul G α] {s : set α} (hs : measurable_set s) (a : G) : measurable_set (a • s) := begin rw ← preimage_smul_inv, exact measurable_const_smul _ hs end lemma measurable_set.const_smul_of_ne_zero {G₀ α : Type*} [group_with_zero G₀] [mul_action G₀ α] [measurable_space G₀] [measurable_space α] [has_measurable_smul G₀ α] {s : set α} (hs : measurable_set s) {a : G₀} (ha : a ≠ 0) : measurable_set (a • s) := begin rw ← preimage_smul_inv₀ ha, exact measurable_const_smul _ hs end lemma measurable_set.const_smul₀ {G₀ α : Type*} [group_with_zero G₀] [has_zero α] [mul_action_with_zero G₀ α] [measurable_space G₀] [measurable_space α] [has_measurable_smul G₀ α] [measurable_singleton_class α] {s : set α} (hs : measurable_set s) (a : G₀) : measurable_set (a • s) := begin rcases eq_or_ne a 0 with (rfl|ha), exacts [(subsingleton_zero_smul_set s).measurable_set, hs.const_smul_of_ne_zero ha] end
9ac35aef61260f4079002527647b49043e38dfc8
63abd62053d479eae5abf4951554e1064a4c45b4
/src/ring_theory/algebraic.lean
31e228c7132542522e9b1ad42af9c992ff5977cb
[ "Apache-2.0" ]
permissive
Lix0120/mathlib
0020745240315ed0e517cbf32e738d8f9811dd80
e14c37827456fc6707f31b4d1d16f1f3a3205e91
refs/heads/master
1,673,102,855,024
1,604,151,044,000
1,604,151,044,000
308,930,245
0
0
Apache-2.0
1,604,164,710,000
1,604,163,547,000
null
UTF-8
Lean
false
false
4,699
lean
/- Copyright (c) 2019 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin -/ import linear_algebra.finite_dimensional import ring_theory.integral_closure import data.polynomial.integral_normalization /-! # Algebraic elements and algebraic extensions An element of an R-algebra is algebraic over R if it is the root of a nonzero polynomial. An R-algebra is algebraic over R if and only if all its elements are algebraic over R. The main result in this file proves transitivity of algebraicity: a tower of algebraic field extensions is algebraic. -/ universe variables u v open_locale classical open polynomial section variables (R : Type u) {A : Type v} [comm_ring R] [comm_ring A] [algebra R A] /-- An element of an R-algebra is algebraic over R if it is the root of a nonzero polynomial. -/ def is_algebraic (x : A) : Prop := ∃ p : polynomial R, p ≠ 0 ∧ aeval x p = 0 variables {R} /-- A subalgebra is algebraic if all its elements are algebraic. -/ def subalgebra.is_algebraic (S : subalgebra R A) : Prop := ∀ x ∈ S, is_algebraic R x variables (R A) /-- An algebra is algebraic if all its elements are algebraic. -/ def algebra.is_algebraic : Prop := ∀ x : A, is_algebraic R x variables {R A} /-- A subalgebra is algebraic if and only if it is algebraic an algebra. -/ lemma subalgebra.is_algebraic_iff (S : subalgebra R A) : S.is_algebraic ↔ @algebra.is_algebraic R S _ _ (S.algebra) := begin delta algebra.is_algebraic subalgebra.is_algebraic, rw [subtype.forall'], apply forall_congr, rintro ⟨x, hx⟩, apply exists_congr, intro p, apply and_congr iff.rfl, have h : function.injective (S.val) := subtype.val_injective, conv_rhs { rw [← h.eq_iff, alg_hom.map_zero], }, rw [← aeval_alg_hom_apply, S.val_apply] end /-- An algebra is algebraic if and only if it is algebraic as a subalgebra. -/ lemma algebra.is_algebraic_iff : algebra.is_algebraic R A ↔ (⊤ : subalgebra R A).is_algebraic := begin delta algebra.is_algebraic subalgebra.is_algebraic, simp only [algebra.mem_top, forall_prop_of_true, iff_self], end end section zero_ne_one variables (R : Type u) {A : Type v} [comm_ring R] [nontrivial R] [comm_ring A] [algebra R A] /-- An integral element of an algebra is algebraic.-/ lemma is_integral.is_algebraic {x : A} (h : is_integral R x) : is_algebraic R x := by { rcases h with ⟨p, hp, hpx⟩, exact ⟨p, hp.ne_zero, hpx⟩ } end zero_ne_one section field variables (K : Type u) {A : Type v} [field K] [comm_ring A] [algebra K A] /-- An element of an algebra over a field is algebraic if and only if it is integral.-/ lemma is_algebraic_iff_is_integral {x : A} : is_algebraic K x ↔ is_integral K x := begin refine ⟨_, is_integral.is_algebraic K⟩, rintro ⟨p, hp, hpx⟩, refine ⟨_, monic_mul_leading_coeff_inv hp, _⟩, rw [← aeval_def, alg_hom.map_mul, hpx, zero_mul], end end field namespace algebra variables {K : Type*} {L : Type*} {A : Type*} variables [field K] [field L] [comm_ring A] variables [algebra K L] [algebra L A] [algebra K A] [is_scalar_tower K L A] /-- If L is an algebraic field extension of K and A is an algebraic algebra over L, then A is algebraic over K. -/ lemma is_algebraic_trans (L_alg : is_algebraic K L) (A_alg : is_algebraic L A) : is_algebraic K A := begin simp only [is_algebraic, is_algebraic_iff_is_integral] at L_alg A_alg ⊢, exact is_integral_trans L_alg A_alg, end /-- A field extension is algebraic if it is finite. -/ lemma is_algebraic_of_finite [finite : finite_dimensional K L] : is_algebraic K L := λ x, (is_algebraic_iff_is_integral _).mpr (is_integral_of_submodule_noetherian ⊤ (is_noetherian_of_submodule_of_noetherian _ _ _ finite) x algebra.mem_top) end algebra variables {R S : Type*} [integral_domain R] [comm_ring S] lemma exists_integral_multiple [algebra R S] {z : S} (hz : is_algebraic R z) (inj : ∀ x, algebra_map R S x = 0 → x = 0) : ∃ (x : integral_closure R S) (y ≠ (0 : integral_closure R S)), z * y = x := begin rcases hz with ⟨p, p_ne_zero, px⟩, set n := p.nat_degree with n_def, set a := p.leading_coeff with a_def, have a_ne_zero : a ≠ 0 := mt polynomial.leading_coeff_eq_zero.mp p_ne_zero, have y_integral : is_integral R (algebra_map R S a) := is_integral_algebra_map, have x_integral : is_integral R (z * algebra_map R S a) := ⟨ p.integral_normalization, monic_integral_normalization p_ne_zero, integral_normalization_aeval_eq_zero p_ne_zero px inj ⟩, refine ⟨⟨_, x_integral⟩, ⟨_, y_integral⟩, _, rfl⟩, exact λ h, a_ne_zero (inj _ (subtype.ext_iff_val.mp h)) end
5c776e5ff679da4f2e8757a072051f69e800bc31
4727251e0cd73359b15b664c3170e5d754078599
/src/category_theory/fin_category.lean
da22a25bbb1bd0ff3718ee4ae71cb1095d805e4c
[ "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
4,183
lean
/- Copyright (c) 2019 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import data.fintype.basic import category_theory.discrete_category import category_theory.opposites /-! # Finite categories A category is finite in this sense if it has finitely many objects, and finitely many morphisms. ## Implementation We also ask for decidable equality of objects and morphisms, but it may be reasonable to just go classical in future. -/ universes v u namespace category_theory instance discrete_fintype {α : Type*} [fintype α] : fintype (discrete α) := by { dsimp [discrete], apply_instance } instance discrete_hom_fintype {α : Type*} [decidable_eq α] (X Y : discrete α) : fintype (X ⟶ Y) := by { apply ulift.fintype } /-- A category with a `fintype` of objects, and a `fintype` for each morphism space. -/ class fin_category (J : Type v) [small_category J] := (decidable_eq_obj : decidable_eq J . tactic.apply_instance) (fintype_obj : fintype J . tactic.apply_instance) (decidable_eq_hom : Π (j j' : J), decidable_eq (j ⟶ j') . tactic.apply_instance) (fintype_hom : Π (j j' : J), fintype (j ⟶ j') . tactic.apply_instance) attribute [instance] fin_category.decidable_eq_obj fin_category.fintype_obj fin_category.decidable_eq_hom fin_category.fintype_hom -- We need a `decidable_eq` instance here to construct `fintype` on the morphism spaces. instance fin_category_discrete_of_decidable_fintype (J : Type v) [decidable_eq J] [fintype J] : fin_category (discrete J) := { } namespace fin_category variables (α : Type*) [fintype α] [small_category α] [fin_category α] /-- A fin_category `α` is equivalent to a category with objects in `Type`. -/ @[nolint unused_arguments] abbreviation obj_as_type : Type := induced_category α (fintype.equiv_fin α).symm /-- The constructed category is indeed equivalent to `α`. -/ noncomputable def obj_as_type_equiv : obj_as_type α ≌ α := (induced_functor (fintype.equiv_fin α).symm).as_equivalence /-- A fin_category `α` is equivalent to a fin_category with in `Type`. -/ @[nolint unused_arguments] abbreviation as_type : Type := fin (fintype.card α) @[simps hom id comp (lemmas_only)] noncomputable instance category_as_type : small_category (as_type α) := { hom := λ i j, fin (fintype.card (@quiver.hom (obj_as_type α) _ i j)), id := λ i, fintype.equiv_fin _ (𝟙 i), comp := λ i j k f g, fintype.equiv_fin _ ((fintype.equiv_fin _).symm f ≫ (fintype.equiv_fin _).symm g) } local attribute [simp] category_as_type_hom category_as_type_id category_as_type_comp /-- The "identity" functor from `as_type α` to `obj_as_type α`. -/ @[simps] noncomputable def as_type_to_obj_as_type : as_type α ⥤ obj_as_type α := { obj := id, map := λ i j, (fintype.equiv_fin _).symm } /-- The "identity" functor from `obj_as_type α` to `as_type α`. -/ @[simps] noncomputable def obj_as_type_to_as_type : obj_as_type α ⥤ as_type α := { obj := id, map := λ i j, fintype.equiv_fin _ } /-- The constructed category (`as_type α`) is equivalent to `obj_as_type α`. -/ noncomputable def as_type_equiv_obj_as_type : as_type α ≌ obj_as_type α := equivalence.mk (as_type_to_obj_as_type α) (obj_as_type_to_as_type α) (nat_iso.of_components iso.refl $ λ _ _ _, by { dsimp, simp }) (nat_iso.of_components iso.refl $ λ _ _ _, by { dsimp, simp }) noncomputable instance as_type_fin_category : fin_category (as_type α) := {} /-- The constructed category (`as_type α`) is indeed equivalent to `α`. -/ noncomputable def equiv_as_type : as_type α ≌ α := (as_type_equiv_obj_as_type α).trans (obj_as_type_equiv α) end fin_category open opposite /-- The opposite of a finite category is finite. -/ instance fin_category_opposite {J : Type v} [small_category J] [fin_category J] : fin_category Jᵒᵖ := { decidable_eq_obj := equiv.decidable_eq equiv_to_opposite.symm, fintype_obj := fintype.of_equiv _ equiv_to_opposite, decidable_eq_hom := λ j j', equiv.decidable_eq (op_equiv j j'), fintype_hom := λ j j', fintype.of_equiv _ (op_equiv j j').symm, } end category_theory
8bae974c071c428ab447ebd9a5b53319377afd5e
c777c32c8e484e195053731103c5e52af26a25d1
/archive/miu_language/decision_suf.lean
257bea77baa2e8028183d563f5dbe8759d35d920
[ "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
14,518
lean
/- Copyright (c) 2020 Gihan Marasingha. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Gihan Marasingha -/ import .decision_nec import tactic.linarith /-! # Decision procedure - sufficient condition and decidability We give a sufficient condition for a string to be derivable in the MIU language. Together with the necessary condition, we use this to prove that `derivable` is an instance of `decidable_pred`. Let `count I st` and `count U st` denote the number of `I`s (respectively `U`s) in `st : miustr`. We'll show that `st` is derivable if it has the form `M::x` where `x` is a string of `I`s and `U`s for which `count I x` is congruent to 1 or 2 modulo 3. To prove this, it suffices to show `derivable M::y` where `y` is any `miustr` consisting only of `I`s such that the number of `I`s in `y` is `a+3b`, where `a = count I x` and `b = count U x`. This suffices because Rule 3 permits us to change any string of three consecutive `I`s into a `U`. As `count I y = (count I x) + 3*(count U x) ≡ (count I x) [MOD 3]`, it suffices to show `derivable M::z` where `z` is an `miustr` of `I`s such that `count I z` is congruent to 1 or 2 modulo 3. Let `z` be such an `miustr` and let `c` denote `count I z`, so `c ≡ 1 or 2 [MOD 3]`. To derive such an `miustr`, it suffices to derive an `miustr` `M::w`, where again w is an `miustr` of only `I`s with the additional conditions that `count I w` is a power of 2, that `count I w ≥ c` and that `count I w ≡ c [MOD 3]`. To see that this suffices, note that we can remove triples of `I`s from the end of `M::w`, creating `U`s as we go along. Once the number of `I`s equals `m`, we remove `U`s two at a time until we have no `U`s. The only issue is that we may begin the removal process with an odd number of `U`s. Writing `d = count I w`, we see that this happens if and only if `(d-c)/3` is odd. In this case, we must apply Rule 1 to `z`, prior to removing triples of `I`s. We thereby introduce an additional `U` and ensure that the final number of `U`s will be even. ## Tags miu, decision procedure, decidability, decidable_pred, decidable -/ namespace miu open miu_atom list nat /-- We start by showing that an `miustr` `M::w` can be derived, where `w` consists only of `I`s and where `count I w` is a power of 2. -/ private lemma der_cons_replicate (n : ℕ) : derivable (M::(replicate (2^n) I)) := begin induction n with k hk, { constructor, }, -- base case { rw [succ_eq_add_one, pow_add, pow_one 2, mul_two,replicate_add], -- inductive step exact derivable.r2 hk, }, end /-! ## Converting `I`s to `U`s For any given natural number `c ≡ 1 or 2 [MOD 3]`, we need to show that can derive an `miustr` `M::w` where `w` consists only of `I`s, where `d = count I w` is a power of 2, where `d ≥ c` and where `d ≡ c [MOD 3]`. Given the above lemmas, the desired result reduces to an arithmetic result, given in the file `arithmetic.lean`. We'll use this result to show we can derive an `miustr` of the form `M::z` where `z` is an string consisting only of `I`s such that `count I z ≡ 1 or 2 [MOD 3]`. As an intermediate step, we show that derive `z` from `zt`, where `t` is aN `miustr` consisting of an even number of `U`s and `z` is any `miustr`. -/ /-- Any number of successive occurrences of `"UU"` can be removed from the end of a `derivable` `miustr` to produce another `derivable` `miustr`. -/ lemma der_of_der_append_replicate_U_even {z : miustr} {m : ℕ} (h : derivable (z ++ replicate (m*2) U)) : derivable z := begin induction m with k hk, { revert h, simp only [list.replicate, zero_mul, append_nil, imp_self], }, { apply hk, simp only [succ_mul, replicate_add] at h, change replicate 2 U with [U,U] at h, rw ←(append_nil (z ++ replicate (k*2) U)), apply derivable.r4, simp only [append_nil, append_assoc,h], }, end /-! In fine-tuning my application of `simp`, I issued the following commend to determine which lemmas `simp` uses. `set_option trace.simplify.rewrite true` -/ /-- We may replace several consecutive occurrences of `"III"` with the same number of `"U"`s. In application of the following lemma, `xs` will either be `[]` or `[U]`. -/ lemma der_cons_replicate_I_replicate_U_append_of_der_cons_replicate_I_append (c k : ℕ) (hc : c % 3 = 1 ∨ c % 3 = 2) (xs : miustr) (hder : derivable (M ::(replicate (c+3*k) I) ++ xs)) : derivable (M::(replicate c I ++ replicate k U) ++ xs) := begin revert xs, induction k with a ha, { simp only [list.replicate, mul_zero, add_zero, append_nil, forall_true_iff, imp_self],}, { intro xs, specialize ha (U::xs), intro h₂, simp only [succ_eq_add_one, replicate_add], -- We massage the goal rw [←append_assoc, ←cons_append], -- into a form amenable change replicate 1 U with [U], -- to the application of rw [append_assoc, singleton_append], -- ha. apply ha, apply derivable.r3, change [I,I,I] with replicate 3 I, simp only [cons_append, ←replicate_add], convert h₂, }, end /-! ### Arithmetic We collect purely arithmetic lemmas: `add_mod2` is used to ensure we have an even number of `U`s while `le_pow2_and_pow2_eq_mod3` treats the congruence condition modulo 3. -/ section arithmetic /-- For every `a`, the number `a + a % 2` is even. -/ lemma add_mod2 (a : ℕ) : ∃ t, a + a % 2 = t*2 := begin simp only [mul_comm _ 2], -- write `t*2` as `2*t` apply dvd_of_mod_eq_zero, -- it suffices to prove `(a + a % 2) % 2 = 0` rw [add_mod, mod_mod, ←two_mul, mul_mod_right], end private lemma le_pow2_and_pow2_eq_mod3' (c : ℕ) (x : ℕ) (h : c = 1 ∨ c = 2) : ∃ m : ℕ, c + 3*x ≤ 2^m ∧ 2^m % 3 = c % 3 := begin induction x with k hk, { use (c+1), cases h with hc hc; { rw hc, norm_num }, }, rcases hk with ⟨g, hkg, hgmod⟩, by_cases hp : (c + 3*(k+1) ≤ 2 ^g), { use g, exact ⟨hp, hgmod⟩ }, refine ⟨g + 2, _, _⟩, { rw [mul_succ, ←add_assoc, pow_add], change 2^2 with (1+3), rw [mul_add (2^g) 1 3, mul_one], linarith [hkg, one_le_two_pow g], }, { rw [pow_add, ←mul_one c], exact modeq.mul hgmod rfl } end /-- If `a` is 1 or 2 modulo 3, then exists `k` a power of 2 for which `a ≤ k` and `a ≡ k [MOD 3]`. -/ lemma le_pow2_and_pow2_eq_mod3 (a : ℕ) (h : a % 3 = 1 ∨ a % 3 = 2) : ∃ m : ℕ, a ≤ 2^m ∧ 2^m % 3 = a % 3:= begin cases le_pow2_and_pow2_eq_mod3' (a%3) (a/3) h with m hm, use m, split, { convert hm.1, exact (mod_add_div a 3).symm, }, { rw [hm.2, mod_mod _ 3], }, end end arithmetic lemma replicate_pow_minus_append {m : ℕ} : M :: replicate (2^m - 1) I ++ [I] = M::(replicate (2^m) I) := begin change [I] with replicate 1 I, rw [cons_append, ←replicate_add, tsub_add_cancel_of_le (one_le_pow' m 1)], end /-- `der_replicate_I_of_mod3` states that `M::y` is `derivable` if `y` is any `miustr` consisiting just of `I`s, where `count I y` is 1 or 2 modulo 3. -/ lemma der_replicate_I_of_mod3 (c : ℕ) (h : c % 3 = 1 ∨ c % 3 = 2): derivable (M::(replicate c I)) := begin -- From `der_cons_replicate`, we can derive the `miustr` `M::w` described in the introduction. cases (le_pow2_and_pow2_eq_mod3 c h) with m hm, -- `2^m` will be the number of `I`s in `M::w` have hw₂ : derivable (M::(replicate (2^m) I) ++ replicate ((2^m -c)/3 % 2) U), { cases mod_two_eq_zero_or_one ((2^m -c)/3) with h_zero h_one, { -- `(2^m - c)/3 ≡ 0 [MOD 2]` simp only [der_cons_replicate m, append_nil,list.replicate, h_zero], }, { rw [h_one, ←replicate_pow_minus_append, append_assoc], -- case `(2^m - c)/3 ≡ 1 [MOD 2]` apply derivable.r1, rw replicate_pow_minus_append, exact (der_cons_replicate m), }, }, have hw₃ : derivable (M::(replicate c I) ++ replicate ((2^m-c)/3) U ++ replicate ((2^m-c)/3 % 2) U), { apply der_cons_replicate_I_replicate_U_append_of_der_cons_replicate_I_append c ((2^m-c)/3) h, convert hw₂, -- now we must show `c + 3 * ((2 ^ m - c) / 3) = 2 ^ m` rw nat.mul_div_cancel', { exact add_tsub_cancel_of_le hm.1 }, { exact (modeq_iff_dvd' hm.1).mp hm.2.symm } }, rw [append_assoc, ←replicate_add _ _] at hw₃, cases add_mod2 ((2^m-c)/3) with t ht, rw ht at hw₃, exact der_of_der_append_replicate_U_even hw₃, end example (c : ℕ) (h : c % 3 = 1 ∨ c % 3 = 2): derivable (M::(replicate c I)) := begin -- From `der_cons_replicate`, we can derive the `miustr` `M::w` described in the introduction. cases (le_pow2_and_pow2_eq_mod3 c h) with m hm, -- `2^m` will be the number of `I`s in `M::w` have hw₂ : derivable (M::(replicate (2^m) I) ++ replicate ((2^m -c)/3 % 2) U), { cases mod_two_eq_zero_or_one ((2^m -c)/3) with h_zero h_one, { -- `(2^m - c)/3 ≡ 0 [MOD 2]` simp only [der_cons_replicate m, append_nil, list.replicate, h_zero] }, { rw [h_one, ←replicate_pow_minus_append, append_assoc], -- case `(2^m - c)/3 ≡ 1 [MOD 2]` apply derivable.r1, rw replicate_pow_minus_append, exact (der_cons_replicate m), }, }, have hw₃ : derivable (M::(replicate c I) ++ replicate ((2^m-c)/3) U ++ replicate ((2^m-c)/3 % 2) U), { apply der_cons_replicate_I_replicate_U_append_of_der_cons_replicate_I_append c ((2^m-c)/3) h, convert hw₂, -- now we must show `c + 3 * ((2 ^ m - c) / 3) = 2 ^ m` rw nat.mul_div_cancel', { exact add_tsub_cancel_of_le hm.1 }, { exact (modeq_iff_dvd' hm.1).mp hm.2.symm } }, rw [append_assoc, ←replicate_add _ _] at hw₃, cases add_mod2 ((2^m-c)/3) with t ht, rw ht at hw₃, exact der_of_der_append_replicate_U_even hw₃, end /-! ### `decstr` is a sufficient condition The remainder of this file sets up the proof that `dectstr en` is sufficent to ensure `derivable en`. Decidability of `derivable en` is an easy consequence. The proof proceeds by induction on the `count U` of `en`. We tackle first the base case of the induction. This requires auxiliary results giving conditions under which `count I ys = length ys`. -/ /-- If an `miustr` has a zero `count U` and contains no `M`, then its `count I` is its length. -/ lemma count_I_eq_length_of_count_U_zero_and_neg_mem {ys : miustr} (hu : count U ys = 0) (hm : M ∉ ys) : count I ys = length ys := begin induction ys with x xs hxs, { refl, }, { cases x, { exfalso, exact hm (mem_cons_self M xs), }, -- case `x = M` gives a contradiction. { rw [count_cons, if_pos (rfl), length, succ_eq_add_one, succ_inj'], -- case `x = I` apply hxs, { simpa only [count], }, { simp only [mem_cons_iff,false_or] at hm, exact hm, }, }, { exfalso, simp only [count, countp_cons_of_pos] at hu, -- case `x = U` gives a contradiction. exact succ_ne_zero _ hu, }, }, end /-- `base_case_suf` is the base case of the sufficiency result. -/ lemma base_case_suf (en : miustr) (h : decstr en) (hu : count U en = 0) : derivable en := begin rcases h with ⟨⟨mhead, nmtail⟩, hi ⟩, have : en ≠ nil, { intro k, simp only [k, count, countp, if_false, zero_mod, zero_ne_one, false_or] at hi, contradiction, }, rcases (exists_cons_of_ne_nil this) with ⟨y,ys,rfl⟩, rw head at mhead, rw mhead at *, rsuffices ⟨c, rfl, hc⟩ : ∃ c, replicate c I = ys ∧ (c % 3 = 1 ∨ c % 3 = 2), { exact der_replicate_I_of_mod3 c hc, }, { simp only [count] at *, use (count I ys), refine and.intro _ hi, apply replicate_count_eq_of_count_eq_length, exact count_I_eq_length_of_count_U_zero_and_neg_mem hu nmtail, }, end /-! Before continuing to the proof of the induction step, we need other auxiliary results that relate to `count U`. -/ lemma mem_of_count_U_eq_succ {xs : miustr} {k : ℕ} (h : count U xs = succ k) : U ∈ xs := begin induction xs with z zs hzs, { exfalso, rw count at h, contradiction, }, { simp only [mem_cons_iff], cases z, repeat -- cases `z = M` and `z=I` { right, apply hzs, simp only [count, countp, if_false] at h, rw ←h, refl, }, { left, refl, }, }, -- case `z = U` end lemma eq_append_cons_U_of_count_U_pos {k : ℕ} {zs : miustr} (h : count U zs = succ k) : ∃ (as bs : miustr), (zs = as ++ U :: bs) := mem_split (mem_of_count_U_eq_succ h) /-- `ind_hyp_suf` is the inductive step of the sufficiency result. -/ lemma ind_hyp_suf (k : ℕ) (ys : miustr) (hu : count U ys = succ k) (hdec : decstr ys) : ∃ (as bs : miustr), (ys = M::as ++ U:: bs) ∧ (count U (M::as ++ [I,I,I] ++ bs) = k) ∧ decstr (M::as ++ [I,I,I] ++ bs) := begin rcases hdec with ⟨⟨mhead,nmtail⟩, hic⟩, have : ys ≠ nil, { intro k, simp only [k ,count, countp, zero_mod, false_or, zero_ne_one] at hic, contradiction, }, rcases (exists_cons_of_ne_nil this) with ⟨z,zs,rfl⟩, rw head at mhead, rw mhead at *, simp only [count, countp, cons_append, if_false, countp_append] at *, rcases (eq_append_cons_U_of_count_U_pos hu) with ⟨as,bs,hab⟩, rw hab at *, simp only [countp, cons_append, if_pos, if_false, countp_append] at *, use [as,bs], apply and.intro rfl (and.intro (succ.inj hu) _), split, { apply and.intro rfl, simp only [tail, mem_append, mem_cons_iff, false_or, not_mem_nil, or_false] at *, exact nmtail, }, { simp only [count, countp, cons_append, if_false, countp_append, if_pos], rw [add_right_comm, add_mod_right], exact hic, }, end /-- `der_of_decstr` states that `derivable en` follows from `decstr en`. -/ theorem der_of_decstr {en : miustr} (h : decstr en) : derivable en := begin /- The next three lines have the effect of introducing `count U en` as a variable that can be used for induction -/ have hu : ∃ n, count U en = n := exists_eq', cases hu with n hu, revert en, /- Crucially, we need the induction hypothesis to quantify over `en` -/ induction n with k hk, { exact base_case_suf, }, { intros ys hdec hus, rcases ind_hyp_suf k ys hus hdec with ⟨as, bs, hyab, habuc, hdecab⟩, have h₂ : derivable (M::as ++ [I,I,I] ++ bs) := hk hdecab habuc, rw hyab, exact derivable.r3 h₂, }, end /-! ### Decidability of `derivable` -/ /-- Finally, we have the main result, namely that `derivable` is a decidable predicate. -/ instance : decidable_pred derivable := λ en, decidable_of_iff _ ⟨der_of_decstr, decstr_of_der⟩ /-! By decidability, we can automatically determine whether any given `miustr` is `derivable`. -/ example : ¬(derivable "MU") := dec_trivial example : derivable "MUIUIUIIIIIUUUIUII" := dec_trivial end miu
0a1715d8be3daa9a4a57488c0ec70e946b4db5f5
4727251e0cd73359b15b664c3170e5d754078599
/src/analysis/normed_space/spectrum.lean
10154a20b4e3688f29a61f00a4939ea006d72db6
[ "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
21,546
lean
/- Copyright (c) 2021 Jireh Loreaux. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jireh Loreaux -/ import algebra.algebra.spectrum import analysis.special_functions.pow import analysis.special_functions.exponential import analysis.complex.liouville import analysis.analytic.radius_liminf /-! # The spectrum of elements in a complete normed algebra This file contains the basic theory for the resolvent and spectrum of a Banach algebra. ## Main definitions * `spectral_radius : ℝ≥0∞`: supremum of `∥k∥₊` for all `k ∈ spectrum 𝕜 a` ## Main statements * `spectrum.is_open_resolvent_set`: the resolvent set is open. * `spectrum.is_closed`: the spectrum is closed. * `spectrum.subset_closed_ball_norm`: the spectrum is a subset of closed disk of radius equal to the norm. * `spectrum.is_compact`: the spectrum is compact. * `spectrum.spectral_radius_le_nnnorm`: the spectral radius is bounded above by the norm. * `spectrum.has_deriv_at_resolvent`: the resolvent function is differentiable on the resolvent set. * `spectrum.pow_nnnorm_pow_one_div_tendsto_nhds_spectral_radius`: Gelfand's formula for the spectral radius in Banach algebras over `ℂ`. * `spectrum.nonempty`: the spectrum of any element in a complex Banach algebra is nonempty. * `normed_division_ring.alg_equiv_complex_of_complete`: **Gelfand-Mazur theorem** For a complex Banach division algebra, the natural `algebra_map ℂ A` is an algebra isomorphism whose inverse is given by selecting the (unique) element of `spectrum ℂ a` ## TODO * compute all derivatives of `resolvent a`. -/ open_locale ennreal /-- The *spectral radius* is the supremum of the `nnnorm` (`∥⬝∥₊`) of elements in the spectrum, coerced into an element of `ℝ≥0∞`. Note that it is possible for `spectrum 𝕜 a = ∅`. In this case, `spectral_radius a = 0`. It is also possible that `spectrum 𝕜 a` be unbounded (though not for Banach algebras, see `spectrum.is_bounded`, below). In this case, `spectral_radius a = ∞`. -/ noncomputable def spectral_radius (𝕜 : Type*) {A : Type*} [normed_field 𝕜] [ring A] [algebra 𝕜 A] (a : A) : ℝ≥0∞ := ⨆ k ∈ spectrum 𝕜 a, ∥k∥₊ variables {𝕜 : Type*} {A : Type*} namespace spectrum section spectrum_compact variables [normed_field 𝕜] [normed_ring A] [normed_algebra 𝕜 A] local notation `σ` := spectrum 𝕜 local notation `ρ` := resolvent_set 𝕜 local notation `↑ₐ` := algebra_map 𝕜 A lemma mem_resolvent_set_of_spectral_radius_lt {a : A} {k : 𝕜} (h : spectral_radius 𝕜 a < ∥k∥₊) : k ∈ ρ a := not_not.mp $ λ hn, h.not_le $ le_supr₂ k hn variable [complete_space A] lemma is_open_resolvent_set (a : A) : is_open (ρ a) := units.is_open.preimage ((algebra_map_clm 𝕜 A).continuous.sub continuous_const) lemma is_closed (a : A) : is_closed (σ a) := (is_open_resolvent_set a).is_closed_compl lemma mem_resolvent_of_norm_lt [norm_one_class A] {a : A} {k : 𝕜} (h : ∥a∥ < ∥k∥) : k ∈ ρ a := begin rw [resolvent_set, set.mem_set_of_eq, algebra.algebra_map_eq_smul_one], have hk : k ≠ 0 := ne_zero_of_norm_ne_zero (by linarith [norm_nonneg a]), let ku := units.map (↑ₐ).to_monoid_hom (units.mk0 k hk), have hku : ∥-a∥ < ∥(↑ku⁻¹:A)∥⁻¹ := by simpa [ku, algebra_map_isometry] using h, simpa [ku, sub_eq_add_neg, algebra.algebra_map_eq_smul_one] using (ku.add (-a) hku).is_unit, end lemma norm_le_norm_of_mem [norm_one_class A] {a : A} {k : 𝕜} (hk : k ∈ σ a) : ∥k∥ ≤ ∥a∥ := le_of_not_lt $ mt mem_resolvent_of_norm_lt hk lemma subset_closed_ball_norm [norm_one_class A] (a : A) : σ a ⊆ metric.closed_ball (0 : 𝕜) (∥a∥) := λ k hk, by simp [norm_le_norm_of_mem hk] lemma is_bounded [norm_one_class A] (a : A) : metric.bounded (σ a) := (metric.bounded_iff_subset_ball 0).mpr ⟨∥a∥, subset_closed_ball_norm a⟩ theorem is_compact [norm_one_class A] [proper_space 𝕜] (a : A) : is_compact (σ a) := metric.is_compact_of_is_closed_bounded (is_closed a) (is_bounded a) theorem spectral_radius_le_nnnorm [norm_one_class A] (a : A) : spectral_radius 𝕜 a ≤ ∥a∥₊ := by { refine supr₂_le (λ k hk, _), exact_mod_cast norm_le_norm_of_mem hk } open ennreal polynomial variable (𝕜) theorem spectral_radius_le_pow_nnnorm_pow_one_div [norm_one_class A] (a : A) (n : ℕ) : spectral_radius 𝕜 a ≤ ∥a ^ (n + 1)∥₊ ^ (1 / (n + 1) : ℝ) := begin refine supr₂_le (λ k hk, _), /- apply easy direction of the spectral mapping theorem for polynomials -/ have pow_mem : k ^ (n + 1) ∈ σ (a ^ (n + 1)), by simpa only [one_mul, algebra.algebra_map_eq_smul_one, one_smul, aeval_monomial, one_mul, eval_monomial] using subset_polynomial_aeval a (monomial (n + 1) (1 : 𝕜)) ⟨k, hk, rfl⟩, /- power of the norm is bounded by norm of the power -/ have nnnorm_pow_le : (↑(∥k∥₊ ^ (n + 1)) : ℝ≥0∞) ≤ ↑∥a ^ (n + 1)∥₊, by simpa only [norm_to_nnreal, nnnorm_pow k (n+1)] using coe_mono (real.to_nnreal_mono (norm_le_norm_of_mem pow_mem)), /- take (n + 1)ᵗʰ roots and clean up the left-hand side -/ have hn : 0 < ((n + 1) : ℝ), by exact_mod_cast nat.succ_pos', convert monotone_rpow_of_nonneg (one_div_pos.mpr hn).le nnnorm_pow_le, erw [coe_pow, ←rpow_nat_cast, ←rpow_mul, mul_one_div_cancel hn.ne', rpow_one], end end spectrum_compact section resolvent open filter asymptotics variables [nondiscrete_normed_field 𝕜] [normed_ring A] [normed_algebra 𝕜 A] [complete_space A] local notation `ρ` := resolvent_set 𝕜 local notation `↑ₐ` := algebra_map 𝕜 A theorem has_deriv_at_resolvent {a : A} {k : 𝕜} (hk : k ∈ ρ a) : has_deriv_at (resolvent a) (-(resolvent a k) ^ 2) k := begin have H₁ : has_fderiv_at ring.inverse _ (↑ₐk - a) := has_fderiv_at_ring_inverse hk.unit, have H₂ : has_deriv_at (λ k, ↑ₐk - a) 1 k, { simpa using (algebra.linear_map 𝕜 A).has_deriv_at.sub_const a }, simpa [resolvent, sq, hk.unit_spec, ← ring.inverse_unit hk.unit] using H₁.comp_has_deriv_at k H₂, end /- TODO: Once there is sufficient API for bornology, we should get a nice filter / asymptotics version of this, for example: `tendsto (resolvent a) (cobounded 𝕜) (𝓝 0)` or more specifically `is_O (resolvent a) (λ z, z⁻¹) (cobounded 𝕜)`. -/ lemma norm_resolvent_le_forall (a : A) : ∀ ε > 0, ∃ R > 0, ∀ z : 𝕜, R ≤ ∥z∥ → ∥resolvent a z∥ ≤ ε := begin obtain ⟨c, c_pos, hc⟩ := (@normed_ring.inverse_one_sub_norm A _ _).exists_pos, rw [is_O_with_iff, eventually_iff, metric.mem_nhds_iff] at hc, rcases hc with ⟨δ, δ_pos, hδ⟩, simp only [cstar_ring.norm_one, mul_one] at hδ, intros ε hε, have ha₁ : 0 < ∥a∥ + 1 := lt_of_le_of_lt (norm_nonneg a) (lt_add_one _), have min_pos : 0 < min (δ * (∥a∥ + 1)⁻¹) (ε * c⁻¹), from lt_min (mul_pos δ_pos (inv_pos.mpr ha₁)) (mul_pos hε (inv_pos.mpr c_pos)), refine ⟨(min (δ * (∥a∥ + 1)⁻¹) (ε * c⁻¹))⁻¹, inv_pos.mpr min_pos, (λ z hz, _)⟩, have hnz : z ≠ 0 := norm_pos_iff.mp (lt_of_lt_of_le (inv_pos.mpr min_pos) hz), replace hz := inv_le_of_inv_le min_pos hz, rcases (⟨units.mk0 z hnz, units.coe_mk0 hnz⟩ : is_unit z) with ⟨z, rfl⟩, have lt_δ : ∥z⁻¹ • a∥ < δ, { rw [units.smul_def, norm_smul, units.coe_inv', norm_inv], calc ∥(z : 𝕜)∥⁻¹ * ∥a∥ ≤ δ * (∥a∥ + 1)⁻¹ * ∥a∥ : mul_le_mul_of_nonneg_right (hz.trans (min_le_left _ _)) (norm_nonneg _) ... < δ : by { conv { rw mul_assoc, to_rhs, rw (mul_one δ).symm }, exact mul_lt_mul_of_pos_left ((inv_mul_lt_iff ha₁).mpr ((mul_one (∥a∥ + 1)).symm ▸ (lt_add_one _))) δ_pos } }, rw [←inv_smul_smul z (resolvent a (z : 𝕜)), units_smul_resolvent_self, resolvent, algebra.algebra_map_eq_smul_one, one_smul, units.smul_def, norm_smul, units.coe_inv', norm_inv], calc _ ≤ ε * c⁻¹ * c : mul_le_mul (hz.trans (min_le_right _ _)) (hδ (mem_ball_zero_iff.mpr lt_δ)) (norm_nonneg _) (mul_pos hε (inv_pos.mpr c_pos)).le ... = _ : inv_mul_cancel_right₀ c_pos.ne.symm ε, end end resolvent section one_sub_smul open continuous_multilinear_map ennreal formal_multilinear_series open_locale nnreal ennreal variables [nondiscrete_normed_field 𝕜] [normed_ring A] [normed_algebra 𝕜 A] variable (𝕜) /-- In a Banach algebra `A` over a nondiscrete normed field `𝕜`, for any `a : A` the power series with coefficients `a ^ n` represents the function `(1 - z • a)⁻¹` in a disk of radius `∥a∥₊⁻¹`. -/ lemma has_fpower_series_on_ball_inverse_one_sub_smul [complete_space A] (a : A) : has_fpower_series_on_ball (λ z : 𝕜, ring.inverse (1 - z • a)) (λ n, continuous_multilinear_map.mk_pi_field 𝕜 (fin n) (a ^ n)) 0 (∥a∥₊)⁻¹ := { r_le := begin refine le_of_forall_nnreal_lt (λ r hr, le_radius_of_bound_nnreal _ (max 1 ∥(1 : A)∥₊) (λ n, _)), rw [←norm_to_nnreal, norm_mk_pi_field, norm_to_nnreal], cases n, { simp only [le_refl, mul_one, or_true, le_max_iff, pow_zero] }, { refine le_trans (le_trans (mul_le_mul_right' (nnnorm_pow_le' a n.succ_pos) (r ^ n.succ)) _) (le_max_left _ _), { by_cases ∥a∥₊ = 0, { simp only [h, zero_mul, zero_le', pow_succ], }, { rw [←coe_inv h, coe_lt_coe, nnreal.lt_inv_iff_mul_lt h] at hr, simpa only [←mul_pow, mul_comm] using pow_le_one' hr.le n.succ } } } end, r_pos := ennreal.inv_pos.mpr coe_ne_top, has_sum := λ y hy, begin have norm_lt : ∥y • a∥ < 1, { by_cases h : ∥a∥₊ = 0, { simp only [nnnorm_eq_zero.mp h, norm_zero, zero_lt_one, smul_zero] }, { have nnnorm_lt : ∥y∥₊ < ∥a∥₊⁻¹, by simpa only [←coe_inv h, mem_ball_zero_iff, metric.emetric_ball_nnreal] using hy, rwa [←coe_nnnorm, ←real.lt_to_nnreal_iff_coe_lt, real.to_nnreal_one, nnnorm_smul, ←nnreal.lt_inv_iff_mul_lt h] } }, simpa [←smul_pow, (normed_ring.summable_geometric_of_norm_lt_1 _ norm_lt).has_sum_iff] using (normed_ring.inverse_one_sub _ norm_lt).symm, end } variable {𝕜} lemma is_unit_one_sub_smul_of_lt_inv_radius {a : A} {z : 𝕜} (h : ↑∥z∥₊ < (spectral_radius 𝕜 a)⁻¹) : is_unit (1 - z • a) := begin by_cases hz : z = 0, { simp only [hz, is_unit_one, sub_zero, zero_smul] }, { let u := units.mk0 z hz, suffices hu : is_unit (u⁻¹ • 1 - a), { rwa [is_unit.smul_sub_iff_sub_inv_smul, inv_inv u] at hu }, { rw [units.smul_def, ←algebra.algebra_map_eq_smul_one, ←mem_resolvent_set_iff], refine mem_resolvent_set_of_spectral_radius_lt _, rwa [units.coe_inv', nnnorm_inv, coe_inv (nnnorm_ne_zero_iff.mpr (units.coe_mk0 hz ▸ hz : (u : 𝕜) ≠ 0)), lt_inv_iff_lt_inv] } } end /-- In a Banach algebra `A` over `𝕜`, for `a : A` the function `λ z, (1 - z • a)⁻¹` is differentiable on any closed ball centered at zero of radius `r < (spectral_radius 𝕜 a)⁻¹`. -/ theorem differentiable_on_inverse_one_sub_smul [complete_space A] {a : A} {r : ℝ≥0} (hr : (r : ℝ≥0∞) < (spectral_radius 𝕜 a)⁻¹) : differentiable_on 𝕜 (λ z : 𝕜, ring.inverse (1 - z • a)) (metric.closed_ball 0 r) := begin intros z z_mem, apply differentiable_at.differentiable_within_at, have hu : is_unit (1 - z • a), { refine is_unit_one_sub_smul_of_lt_inv_radius (lt_of_le_of_lt (coe_mono _) hr), simpa only [norm_to_nnreal, real.to_nnreal_coe] using real.to_nnreal_mono (mem_closed_ball_zero_iff.mp z_mem) }, have H₁ : differentiable 𝕜 (λ w : 𝕜, 1 - w • a) := (differentiable_id.smul_const a).const_sub 1, exact differentiable_at.comp z (differentiable_at_inverse hu.unit) (H₁.differentiable_at), end end one_sub_smul section gelfand_formula open filter ennreal continuous_multilinear_map open_locale topological_space variables [normed_ring A] [normed_algebra ℂ A] [complete_space A] /-- The `limsup` relationship for the spectral radius used to prove `spectrum.gelfand_formula`. -/ lemma limsup_pow_nnnorm_pow_one_div_le_spectral_radius (a : A) : limsup at_top (λ n : ℕ, ↑∥a ^ n∥₊ ^ (1 / n : ℝ)) ≤ spectral_radius ℂ a := begin refine ennreal.inv_le_inv.mp (le_of_forall_pos_nnreal_lt (λ r r_pos r_lt, _)), simp_rw [inv_limsup, ←one_div], let p : formal_multilinear_series ℂ ℂ A := λ n, continuous_multilinear_map.mk_pi_field ℂ (fin n) (a ^ n), suffices h : (r : ℝ≥0∞) ≤ p.radius, { convert h, simp only [p.radius_eq_liminf, ←norm_to_nnreal, norm_mk_pi_field], refine congr_arg _ (funext (λ n, congr_arg _ _)), rw [norm_to_nnreal, ennreal.coe_rpow_def (∥a ^ n∥₊) (1 / n : ℝ), if_neg], exact λ ha, by linarith [ha.2, (one_div_nonneg.mpr n.cast_nonneg : 0 ≤ (1 / n : ℝ))], }, { have H₁ := (differentiable_on_inverse_one_sub_smul r_lt).has_fpower_series_on_ball r_pos, exact ((has_fpower_series_on_ball_inverse_one_sub_smul ℂ a).exchange_radius H₁).r_le, } end /-- **Gelfand's formula**: Given an element `a : A` of a complex Banach algebra, the `spectral_radius` of `a` is the limit of the sequence `∥a ^ n∥₊ ^ (1 / n)` -/ theorem pow_nnnorm_pow_one_div_tendsto_nhds_spectral_radius [norm_one_class A] (a : A) : tendsto (λ n : ℕ, ((∥a ^ n∥₊ ^ (1 / n : ℝ)) : ℝ≥0∞)) at_top (𝓝 (spectral_radius ℂ a)) := begin refine tendsto_of_le_liminf_of_limsup_le _ _ (by apply_auto_param) (by apply_auto_param), { rw [←liminf_nat_add _ 1, liminf_eq_supr_infi_of_nat], refine le_trans _ (le_supr _ 0), exact le_infi₂ (λ i hi, spectral_radius_le_pow_nnnorm_pow_one_div ℂ a i) }, { exact limsup_pow_nnnorm_pow_one_div_le_spectral_radius a }, end /- This is the same as `pow_nnnorm_pow_one_div_tendsto_nhds_spectral_radius` but for `norm` instead of `nnnorm`. -/ /-- **Gelfand's formula**: Given an element `a : A` of a complex Banach algebra, the `spectral_radius` of `a` is the limit of the sequence `∥a ^ n∥₊ ^ (1 / n)` -/ theorem pow_norm_pow_one_div_tendsto_nhds_spectral_radius [norm_one_class A] (a : A) : tendsto (λ n : ℕ, ennreal.of_real (∥a ^ n∥ ^ (1 / n : ℝ))) at_top (𝓝 (spectral_radius ℂ a)) := begin convert pow_nnnorm_pow_one_div_tendsto_nhds_spectral_radius a, ext1, rw [←of_real_rpow_of_nonneg (norm_nonneg _) _, ←coe_nnnorm, coe_nnreal_eq], exact one_div_nonneg.mpr (by exact_mod_cast zero_le _), end end gelfand_formula /-- In a (nontrivial) complex Banach algebra, every element has nonempty spectrum. -/ theorem nonempty {A : Type*} [normed_ring A] [normed_algebra ℂ A] [complete_space A] [nontrivial A] (a : A) : (spectrum ℂ a).nonempty := begin /- Suppose `σ a = ∅`, then resolvent set is `ℂ`, any `(z • 1 - a)` is a unit, and `resolvent` is differentiable on `ℂ`. -/ rw ←set.ne_empty_iff_nonempty, by_contra h, have H₀ : resolvent_set ℂ a = set.univ, by rwa [spectrum, set.compl_empty_iff] at h, have H₁ : differentiable ℂ (λ z : ℂ, resolvent a z), from λ z, (has_deriv_at_resolvent (H₀.symm ▸ set.mem_univ z : z ∈ resolvent_set ℂ a)).differentiable_at, /- The norm of the resolvent is small for all sufficently large `z`, and by compactness and continuity it is bounded on the complement of a large ball, thus uniformly bounded on `ℂ`. By Liouville's theorem `λ z, resolvent a z` is constant -/ have H₂ := norm_resolvent_le_forall a, have H₃ : ∀ z : ℂ, resolvent a z = resolvent a (0 : ℂ), { refine λ z, H₁.apply_eq_apply_of_bounded (bounded_iff_exists_norm_le.mpr _) z 0, rcases H₂ 1 zero_lt_one with ⟨R, R_pos, hR⟩, rcases (proper_space.is_compact_closed_ball (0 : ℂ) R).exists_bound_of_continuous_on H₁.continuous.continuous_on with ⟨C, hC⟩, use max C 1, rintros _ ⟨w, rfl⟩, refine or.elim (em (∥w∥ ≤ R)) (λ hw, _) (λ hw, _), { exact (hC w (mem_closed_ball_zero_iff.mpr hw)).trans (le_max_left _ _) }, { exact (hR w (not_le.mp hw).le).trans (le_max_right _ _), }, }, /- `resolvent a 0 = 0`, which is a contradition because it isn't a unit. -/ have H₅ : resolvent a (0 : ℂ) = 0, { refine norm_eq_zero.mp (le_antisymm (le_of_forall_pos_le_add (λ ε hε, _)) (norm_nonneg _)), rcases H₂ ε hε with ⟨R, R_pos, hR⟩, simpa only [H₃ R] using (zero_add ε).symm.subst (hR R (by exact_mod_cast (real.norm_of_nonneg R_pos.lt.le).symm.le)), }, /- `not_is_unit_zero` is where we need `nontrivial A`, it is unavoidable. -/ exact not_is_unit_zero (H₅.subst (is_unit_resolvent.mp (mem_resolvent_set_iff.mp (H₀.symm ▸ set.mem_univ 0)))), end section gelfand_mazur_isomorphism variables [normed_division_ring A] [normed_algebra ℂ A] local notation `σ` := spectrum ℂ lemma algebra_map_eq_of_mem {a : A} {z : ℂ} (h : z ∈ σ a) : algebra_map ℂ A z = a := by rwa [mem_iff, is_unit_iff_ne_zero, not_not, sub_eq_zero] at h /-- **Gelfand-Mazur theorem**: For a complex Banach division algebra, the natural `algebra_map ℂ A` is an algebra isomorphism whose inverse is given by selecting the (unique) element of `spectrum ℂ a`. In addition, `algebra_map_isometry` guarantees this map is an isometry. -/ @[simps] noncomputable def _root_.normed_division_ring.alg_equiv_complex_of_complete [complete_space A] : ℂ ≃ₐ[ℂ] A := { to_fun := algebra_map ℂ A, inv_fun := λ a, (spectrum.nonempty a).some, left_inv := λ z, by simpa only [scalar_eq] using (spectrum.nonempty $ algebra_map ℂ A z).some_mem, right_inv := λ a, algebra_map_eq_of_mem (spectrum.nonempty a).some_mem, ..algebra.of_id ℂ A } end gelfand_mazur_isomorphism section exp_mapping local notation `↑ₐ` := algebra_map 𝕜 A /-- For `𝕜 = ℝ` or `𝕜 = ℂ`, `exp 𝕜` maps the spectrum of `a` into the spectrum of `exp 𝕜 a`. -/ theorem exp_mem_exp [is_R_or_C 𝕜] [normed_ring A] [normed_algebra 𝕜 A] [complete_space A] (a : A) {z : 𝕜} (hz : z ∈ spectrum 𝕜 a) : exp 𝕜 z ∈ spectrum 𝕜 (exp 𝕜 a) := begin have hexpmul : exp 𝕜 a = exp 𝕜 (a - ↑ₐ z) * ↑ₐ (exp 𝕜 z), { rw [algebra_map_exp_comm z, ←exp_add_of_commute (algebra.commutes z (a - ↑ₐz)).symm, sub_add_cancel] }, let b := ∑' n : ℕ, ((n + 1).factorial⁻¹ : 𝕜) • (a - ↑ₐz) ^ n, have hb : summable (λ n : ℕ, ((n + 1).factorial⁻¹ : 𝕜) • (a - ↑ₐz) ^ n), { refine summable_of_norm_bounded_eventually _ (real.summable_pow_div_factorial ∥a - ↑ₐz∥) _, filter_upwards [filter.eventually_cofinite_ne 0] with n hn, rw [norm_smul, mul_comm, norm_inv, is_R_or_C.norm_eq_abs, is_R_or_C.abs_cast_nat, ←div_eq_mul_inv], exact div_le_div (pow_nonneg (norm_nonneg _) n) (norm_pow_le' (a - ↑ₐz) (zero_lt_iff.mpr hn)) (by exact_mod_cast nat.factorial_pos n) (by exact_mod_cast nat.factorial_le (lt_add_one n).le) }, have h₀ : ∑' n : ℕ, ((n + 1).factorial⁻¹ : 𝕜) • (a - ↑ₐz) ^ (n + 1) = (a - ↑ₐz) * b, { simpa only [mul_smul_comm, pow_succ] using hb.tsum_mul_left (a - ↑ₐz) }, have h₁ : ∑' n : ℕ, ((n + 1).factorial⁻¹ : 𝕜) • (a - ↑ₐz) ^ (n + 1) = b * (a - ↑ₐz), { simpa only [pow_succ', algebra.smul_mul_assoc] using hb.tsum_mul_right (a - ↑ₐz) }, have h₃ : exp 𝕜 (a - ↑ₐz) = 1 + (a - ↑ₐz) * b, { rw exp_eq_tsum, convert tsum_eq_zero_add (exp_series_summable' (a - ↑ₐz)), simp only [nat.factorial_zero, nat.cast_one, inv_one, pow_zero, one_smul], exact h₀.symm }, rw [spectrum.mem_iff, is_unit.sub_iff, ←one_mul (↑ₐ(exp 𝕜 z)), hexpmul, ←_root_.sub_mul, commute.is_unit_mul_iff (algebra.commutes (exp 𝕜 z) (exp 𝕜 (a - ↑ₐz) - 1)).symm, sub_eq_iff_eq_add'.mpr h₃, commute.is_unit_mul_iff (h₀ ▸ h₁ : (a - ↑ₐz) * b = b * (a - ↑ₐz))], exact not_and_of_not_left _ (not_and_of_not_left _ ((not_iff_not.mpr is_unit.sub_iff).mp hz)), end end exp_mapping end spectrum namespace alg_hom section normed_field variables [normed_field 𝕜] [normed_ring A] [normed_algebra 𝕜 A] [complete_space A] local notation `↑ₐ` := algebra_map 𝕜 A /-- An algebra homomorphism into the base field, as a continuous linear map (since it is automatically bounded). -/ @[simps] def to_continuous_linear_map [norm_one_class A] (φ : A →ₐ[𝕜] 𝕜) : A →L[𝕜] 𝕜 := φ.to_linear_map.mk_continuous_of_exists_bound $ ⟨1, λ a, (one_mul ∥a∥).symm ▸ spectrum.norm_le_norm_of_mem (φ.apply_mem_spectrum _)⟩ lemma continuous [norm_one_class A] (φ : A →ₐ[𝕜] 𝕜) : continuous φ := φ.to_continuous_linear_map.continuous end normed_field section nondiscrete_normed_field variables [nondiscrete_normed_field 𝕜] [normed_ring A] [normed_algebra 𝕜 A] [complete_space A] local notation `↑ₐ` := algebra_map 𝕜 A @[simp] lemma to_continuous_linear_map_norm [norm_one_class A] (φ : A →ₐ[𝕜] 𝕜) : ∥φ.to_continuous_linear_map∥ = 1 := continuous_linear_map.op_norm_eq_of_bounds zero_le_one (λ a, (one_mul ∥a∥).symm ▸ spectrum.norm_le_norm_of_mem (φ.apply_mem_spectrum _)) (λ _ _ h, by simpa only [to_continuous_linear_map_apply, mul_one, map_one, norm_one] using h 1) end nondiscrete_normed_field end alg_hom
0d83b9232d3246fb7c8f762144c603451d22634d
947fa6c38e48771ae886239b4edce6db6e18d0fb
/src/model_theory/syntax.lean
afa5ab848bd720285c5f0213687c9c06bedbe86b
[ "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
38,622
lean
/- Copyright (c) 2021 Aaron Anderson, Jesse Michael Han, Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Aaron Anderson, Jesse Michael Han, Floris van Doorn -/ import data.list.prod_sigma import data.set.prod import logic.equiv.fin import model_theory.language_map /-! # Basics on First-Order Syntax This file defines first-order terms, formulas, sentences, and theories in a style inspired by the [Flypitch project](https://flypitch.github.io/). ## Main Definitions * A `first_order.language.term` is defined so that `L.term α` is the type of `L`-terms with free variables indexed by `α`. * A `first_order.language.formula` is defined so that `L.formula α` is the type of `L`-formulas with free variables indexed by `α`. * A `first_order.language.sentence` is a formula with no free variables. * A `first_order.language.Theory` is a set of sentences. * The variables of terms and formulas can be relabelled with `first_order.language.term.relabel`, `first_order.language.bounded_formula.relabel`, and `first_order.language.formula.relabel`. * Given an operation on terms and an operation on relations, `first_order.language.bounded_formula.map_term_rel` gives an operation on formulas. * `first_order.language.bounded_formula.cast_le` adds more `fin`-indexed variables. * `first_order.language.bounded_formula.lift_at` raises the indexes of the `fin`-indexed variables above a particular index. * `first_order.language.term.subst` and `first_order.language.bounded_formula.subst` substitute variables with given terms. * Language maps can act on syntactic objects with functions such as `first_order.language.Lhom.on_formula`. * `first_order.language.term.constants_vars_equiv` and `first_order.language.bounded_formula.constants_vars_equiv` switch terms and formulas between having constants in the language and having extra variables indexed by the same type. ## Implementation Notes * Formulas use a modified version of de Bruijn variables. Specifically, a `L.bounded_formula α n` is a formula with some variables indexed by a type `α`, which cannot be quantified over, and some indexed by `fin n`, which can. For any `φ : L.bounded_formula α (n + 1)`, we define the formula `∀' φ : L.bounded_formula α n` by universally quantifying over the variable indexed by `n : fin (n + 1)`. ## References For the Flypitch project: - [J. Han, F. van Doorn, *A formal proof of the independence of the continuum hypothesis*] [flypitch_cpp] - [J. Han, F. van Doorn, *A formalization of forcing and the unprovability of the continuum hypothesis*][flypitch_itp] -/ universes u v w u' v' namespace first_order namespace language variables (L : language.{u v}) {L' : language} variables {M : Type w} {N P : Type*} [L.Structure M] [L.Structure N] [L.Structure P] variables {α : Type u'} {β : Type v'} {γ : Type*} open_locale first_order open Structure fin /-- A term on `α` is either a variable indexed by an element of `α` or a function symbol applied to simpler terms. -/ inductive term (α : Type u') : Type (max u u') | var {} : ∀ (a : α), term | func {} : ∀ {l : ℕ} (f : L.functions l) (ts : fin l → term), term export term variable {L} namespace term open finset /-- The `finset` of variables used in a given term. -/ @[simp] def var_finset [decidable_eq α] : L.term α → finset α | (var i) := {i} | (func f ts) := univ.bUnion (λ i, (ts i).var_finset) /-- The `finset` of variables from the left side of a sum used in a given term. -/ @[simp] def var_finset_left [decidable_eq α] : L.term (α ⊕ β) → finset α | (var (sum.inl i)) := {i} | (var (sum.inr i)) := ∅ | (func f ts) := univ.bUnion (λ i, (ts i).var_finset_left) /-- Relabels a term's variables along a particular function. -/ @[simp] def relabel (g : α → β) : L.term α → L.term β | (var i) := var (g i) | (func f ts) := func f (λ i, (ts i).relabel) lemma relabel_id (t : L.term α) : t.relabel id = t := begin induction t with _ _ _ _ ih, { refl, }, { simp [ih] }, end @[simp] lemma relabel_id_eq_id : (term.relabel id : L.term α → L.term α) = id := funext relabel_id @[simp] lemma relabel_relabel (f : α → β) (g : β → γ) (t : L.term α) : (t.relabel f).relabel g = t.relabel (g ∘ f) := begin induction t with _ _ _ _ ih, { refl, }, { simp [ih] }, end @[simp] lemma relabel_comp_relabel (f : α → β) (g : β → γ) : (term.relabel g ∘ term.relabel f : L.term α → L.term γ) = term.relabel (g ∘ f) := funext (relabel_relabel f g) /-- Relabels a term's variables along a bijection. -/ @[simps] def relabel_equiv (g : α ≃ β) : L.term α ≃ L.term β := ⟨relabel g, relabel g.symm, λ t, by simp, λ t, by simp⟩ /-- Restricts a term to use only a set of the given variables. -/ def restrict_var [decidable_eq α] : Π (t : L.term α) (f : t.var_finset → β), L.term β | (var a) f := var (f ⟨a, mem_singleton_self a⟩) | (func F ts) f := func F (λ i, (ts i).restrict_var (f ∘ set.inclusion (subset_bUnion_of_mem _ (mem_univ i)))) /-- Restricts a term to use only a set of the given variables on the left side of a sum. -/ def restrict_var_left [decidable_eq α] {γ : Type*} : Π (t : L.term (α ⊕ γ)) (f : t.var_finset_left → β), L.term (β ⊕ γ) | (var (sum.inl a)) f := var (sum.inl (f ⟨a, mem_singleton_self a⟩)) | (var (sum.inr a)) f := var (sum.inr a) | (func F ts) f := func F (λ i, (ts i).restrict_var_left (f ∘ set.inclusion (subset_bUnion_of_mem _ (mem_univ i)))) end term /-- The representation of a constant symbol as a term. -/ def constants.term (c : L.constants) : (L.term α) := func c default /-- Applies a unary function to a term. -/ def functions.apply₁ (f : L.functions 1) (t : L.term α) : L.term α := func f ![t] /-- Applies a binary function to two terms. -/ def functions.apply₂ (f : L.functions 2) (t₁ t₂ : L.term α) : L.term α := func f ![t₁, t₂] namespace term /-- Sends a term with constants to a term with extra variables. -/ @[simp] def constants_to_vars : L[[γ]].term α → L.term (γ ⊕ α) | (var a) := var (sum.inr a) | (@func _ _ 0 f ts) := sum.cases_on f (λ f, func f (λ i, (ts i).constants_to_vars)) (λ c, var (sum.inl c)) | (@func _ _ (n + 1) f ts) := sum.cases_on f (λ f, func f (λ i, (ts i).constants_to_vars)) (λ c, is_empty_elim c) /-- Sends a term with extra variables to a term with constants. -/ @[simp] def vars_to_constants : L.term (γ ⊕ α) → L[[γ]].term α | (var (sum.inr a)) := var a | (var (sum.inl c)) := constants.term (sum.inr c) | (func f ts) := func (sum.inl f) (λ i, (ts i).vars_to_constants) /-- A bijection between terms with constants and terms with extra variables. -/ @[simps] def constants_vars_equiv : L[[γ]].term α ≃ L.term (γ ⊕ α) := ⟨constants_to_vars, vars_to_constants, begin intro t, induction t with _ n f _ ih, { refl }, { cases n, { cases f, { simp [constants_to_vars, vars_to_constants, ih] }, { simp [constants_to_vars, vars_to_constants, constants.term] } }, { cases f, { simp [constants_to_vars, vars_to_constants, ih] }, { exact is_empty_elim f } } } end, begin intro t, induction t with x n f _ ih, { cases x; refl }, { cases n; { simp [vars_to_constants, constants_to_vars, ih] } } end⟩ /-- A bijection between terms with constants and terms with extra variables. -/ def constants_vars_equiv_left : L[[γ]].term (α ⊕ β) ≃ L.term ((γ ⊕ α) ⊕ β) := constants_vars_equiv.trans (relabel_equiv (equiv.sum_assoc _ _ _)).symm @[simp] lemma constants_vars_equiv_left_apply (t : L[[γ]].term (α ⊕ β)) : constants_vars_equiv_left t = (constants_to_vars t).relabel (equiv.sum_assoc _ _ _).symm := rfl @[simp] lemma constants_vars_equiv_left_symm_apply (t : L.term ((γ ⊕ α) ⊕ β)) : constants_vars_equiv_left.symm t = vars_to_constants (t.relabel (equiv.sum_assoc _ _ _)) := rfl instance inhabited_of_var [inhabited α] : inhabited (L.term α) := ⟨var default⟩ instance inhabited_of_constant [inhabited L.constants] : inhabited (L.term α) := ⟨(default : L.constants).term⟩ /-- Raises all of the `fin`-indexed variables of a term greater than or equal to `m` by `n'`. -/ def lift_at {n : ℕ} (n' m : ℕ) : L.term (α ⊕ fin n) → L.term (α ⊕ fin (n + n')) := relabel (sum.map id (λ i, if ↑i < m then fin.cast_add n' i else fin.add_nat n' i)) /-- Substitutes the variables in a given term with terms. -/ @[simp] def subst : L.term α → (α → L.term β) → L.term β | (var a) tf := tf a | (func f ts) tf := (func f (λ i, (ts i).subst tf)) end term localized "prefix `&`:max := first_order.language.term.var ∘ sum.inr" in first_order namespace Lhom /-- Maps a term's symbols along a language map. -/ @[simp] def on_term (φ : L →ᴸ L') : L.term α → L'.term α | (var i) := var i | (func f ts) := func (φ.on_function f) (λ i, on_term (ts i)) @[simp] lemma id_on_term : ((Lhom.id L).on_term : L.term α → L.term α) = id := begin ext t, induction t with _ _ _ _ ih, { refl }, { simp_rw [on_term, ih], refl, }, end @[simp] lemma comp_on_term {L'' : language} (φ : L' →ᴸ L'') (ψ : L →ᴸ L') : ((φ.comp ψ).on_term : L.term α → L''.term α) = φ.on_term ∘ ψ.on_term := begin ext t, induction t with _ _ _ _ ih, { refl }, { simp_rw [on_term, ih], refl, }, end end Lhom /-- Maps a term's symbols along a language equivalence. -/ @[simps] def Lequiv.on_term (φ : L ≃ᴸ L') : L.term α ≃ L'.term α := { to_fun := φ.to_Lhom.on_term, inv_fun := φ.inv_Lhom.on_term, left_inv := by rw [function.left_inverse_iff_comp, ← Lhom.comp_on_term, φ.left_inv, Lhom.id_on_term], right_inv := by rw [function.right_inverse_iff_comp, ← Lhom.comp_on_term, φ.right_inv, Lhom.id_on_term] } variables (L) (α) /-- `bounded_formula α n` is the type of formulas with free variables indexed by `α` and up to `n` additional free variables. -/ inductive bounded_formula : ℕ → Type (max u v u') | falsum {} {n} : bounded_formula n | equal {n} (t₁ t₂ : L.term (α ⊕ fin n)) : bounded_formula n | rel {n l : ℕ} (R : L.relations l) (ts : fin l → L.term (α ⊕ fin n)) : bounded_formula n | imp {n} (f₁ f₂ : bounded_formula n) : bounded_formula n | all {n} (f : bounded_formula (n+1)) : bounded_formula n /-- `formula α` is the type of formulas with all free variables indexed by `α`. -/ @[reducible] def formula := L.bounded_formula α 0 /-- A sentence is a formula with no free variables. -/ @[reducible] def sentence := L.formula empty /-- A theory is a set of sentences. -/ @[reducible] def Theory := set L.sentence variables {L} {α} {n : ℕ} /-- Applies a relation to terms as a bounded formula. -/ def relations.bounded_formula {l : ℕ} (R : L.relations n) (ts : fin n → L.term (α ⊕ fin l)) : L.bounded_formula α l := bounded_formula.rel R ts /-- Applies a unary relation to a term as a bounded formula. -/ def relations.bounded_formula₁ (r : L.relations 1) (t : L.term (α ⊕ fin n)) : L.bounded_formula α n := r.bounded_formula ![t] /-- Applies a binary relation to two terms as a bounded formula. -/ def relations.bounded_formula₂ (r : L.relations 2) (t₁ t₂ : L.term (α ⊕ fin n)) : L.bounded_formula α n := r.bounded_formula ![t₁, t₂] /-- The equality of two terms as a bounded formula. -/ def term.bd_equal (t₁ t₂ : L.term (α ⊕ fin n)) : (L.bounded_formula α n) := bounded_formula.equal t₁ t₂ /-- Applies a relation to terms as a bounded formula. -/ def relations.formula (R : L.relations n) (ts : fin n → L.term α) : L.formula α := R.bounded_formula (λ i, (ts i).relabel sum.inl) /-- Applies a unary relation to a term as a formula. -/ def relations.formula₁ (r : L.relations 1) (t : L.term α) : L.formula α := r.formula ![t] /-- Applies a binary relation to two terms as a formula. -/ def relations.formula₂ (r : L.relations 2) (t₁ t₂ : L.term α) : L.formula α := r.formula ![t₁, t₂] /-- The equality of two terms as a first-order formula. -/ def term.equal (t₁ t₂ : L.term α) : (L.formula α) := (t₁.relabel sum.inl).bd_equal (t₂.relabel sum.inl) namespace bounded_formula instance : inhabited (L.bounded_formula α n) := ⟨falsum⟩ instance : has_bot (L.bounded_formula α n) := ⟨falsum⟩ /-- The negation of a bounded formula is also a bounded formula. -/ @[pattern] protected def not (φ : L.bounded_formula α n) : L.bounded_formula α n := φ.imp ⊥ /-- Puts an `∃` quantifier on a bounded formula. -/ @[pattern] protected def ex (φ : L.bounded_formula α (n + 1)) : L.bounded_formula α n := φ.not.all.not instance : has_top (L.bounded_formula α n) := ⟨bounded_formula.not ⊥⟩ instance : has_inf (L.bounded_formula α n) := ⟨λ f g, (f.imp g.not).not⟩ instance : has_sup (L.bounded_formula α n) := ⟨λ f g, f.not.imp g⟩ /-- The biimplication between two bounded formulas. -/ protected def iff (φ ψ : L.bounded_formula α n) := φ.imp ψ ⊓ ψ.imp φ open finset /-- The `finset` of variables used in a given formula. -/ @[simp] def free_var_finset [decidable_eq α] : ∀ {n}, L.bounded_formula α n → finset α | n falsum := ∅ | n (equal t₁ t₂) := t₁.var_finset_left ∪ t₂.var_finset_left | n (rel R ts) := univ.bUnion (λ i, (ts i).var_finset_left) | n (imp f₁ f₂) := f₁.free_var_finset ∪ f₂.free_var_finset | n (all f) := f.free_var_finset /-- Casts `L.bounded_formula α m` as `L.bounded_formula α n`, where `m ≤ n`. -/ @[simp] def cast_le : ∀ {m n : ℕ} (h : m ≤ n), L.bounded_formula α m → L.bounded_formula α n | m n h falsum := falsum | m n h (equal t₁ t₂) := equal (t₁.relabel (sum.map id (fin.cast_le h))) (t₂.relabel (sum.map id (fin.cast_le h))) | m n h (rel R ts) := rel R (term.relabel (sum.map id (fin.cast_le h)) ∘ ts) | m n h (imp f₁ f₂) := (f₁.cast_le h).imp (f₂.cast_le h) | m n h (all f) := (f.cast_le (add_le_add_right h 1)).all @[simp] lemma cast_le_rfl {n} (h : n ≤ n) (φ : L.bounded_formula α n) : φ.cast_le h = φ := begin induction φ with _ _ _ _ _ _ _ _ _ _ _ ih1 ih2 _ _ ih3, { refl }, { simp [fin.cast_le_of_eq], }, { simp [fin.cast_le_of_eq], }, { simp [fin.cast_le_of_eq, ih1, ih2], }, { simp [fin.cast_le_of_eq, ih3], }, end @[simp] lemma cast_le_cast_le {k m n} (km : k ≤ m) (mn : m ≤ n) (φ : L.bounded_formula α k) : (φ.cast_le km).cast_le mn = φ.cast_le (km.trans mn) := begin revert m n, induction φ with _ _ _ _ _ _ _ _ _ _ _ ih1 ih2 _ _ ih3; intros m n km mn, { refl }, { simp }, { simp only [cast_le, eq_self_iff_true, heq_iff_eq, true_and], rw [← function.comp.assoc, relabel_comp_relabel], simp }, { simp [ih1, ih2] }, { simp only [cast_le, ih3] } end @[simp] lemma cast_le_comp_cast_le {k m n} (km : k ≤ m) (mn : m ≤ n) : (bounded_formula.cast_le mn ∘ bounded_formula.cast_le km : L.bounded_formula α k → L.bounded_formula α n) = bounded_formula.cast_le (km.trans mn) := funext (cast_le_cast_le km mn) /-- Restricts a bounded formula to only use a particular set of free variables. -/ def restrict_free_var [decidable_eq α] : Π {n : ℕ} (φ : L.bounded_formula α n) (f : φ.free_var_finset → β), L.bounded_formula β n | n falsum f := falsum | n (equal t₁ t₂) f := equal (t₁.restrict_var_left (f ∘ set.inclusion (subset_union_left _ _))) (t₂.restrict_var_left (f ∘ set.inclusion (subset_union_right _ _))) | n (rel R ts) f := rel R (λ i, (ts i).restrict_var_left (f ∘ set.inclusion (subset_bUnion_of_mem _ (mem_univ i)))) | n (imp φ₁ φ₂) f := (φ₁.restrict_free_var (f ∘ set.inclusion (subset_union_left _ _))).imp (φ₂.restrict_free_var (f ∘ set.inclusion (subset_union_right _ _))) | n (all φ) f := (φ.restrict_free_var f).all /-- Places universal quantifiers on all extra variables of a bounded formula. -/ def alls : ∀ {n}, L.bounded_formula α n → L.formula α | 0 φ := φ | (n + 1) φ := φ.all.alls /-- Places existential quantifiers on all extra variables of a bounded formula. -/ def exs : ∀ {n}, L.bounded_formula α n → L.formula α | 0 φ := φ | (n + 1) φ := φ.ex.exs /-- Maps bounded formulas along a map of terms and a map of relations. -/ def map_term_rel {g : ℕ → ℕ} (ft : ∀ n, L.term (α ⊕ fin n) → L'.term (β ⊕ fin (g n))) (fr : ∀ n, L.relations n → L'.relations n) (h : ∀ n, L'.bounded_formula β (g (n + 1)) → L'.bounded_formula β (g n + 1)) : ∀ {n}, L.bounded_formula α n → L'.bounded_formula β (g n) | n falsum := falsum | n (equal t₁ t₂) := equal (ft _ t₁) (ft _ t₂) | n (rel R ts) := rel (fr _ R) (λ i, ft _ (ts i)) | n (imp φ₁ φ₂) := φ₁.map_term_rel.imp φ₂.map_term_rel | n (all φ) := (h n φ.map_term_rel).all /-- Raises all of the `fin`-indexed variables of a formula greater than or equal to `m` by `n'`. -/ def lift_at : ∀ {n : ℕ} (n' m : ℕ), L.bounded_formula α n → L.bounded_formula α (n + n') := λ n n' m φ, φ.map_term_rel (λ k t, t.lift_at n' m) (λ _, id) (λ _, cast_le (by rw [add_assoc, add_comm 1, add_assoc])) @[simp] lemma map_term_rel_map_term_rel {L'' : language} (ft : ∀ n, L.term (α ⊕ fin n) → L'.term (β ⊕ fin n)) (fr : ∀ n, L.relations n → L'.relations n) (ft' : ∀ n, L'.term (β ⊕ fin n) → L''.term (γ ⊕ fin n)) (fr' : ∀ n, L'.relations n → L''.relations n) {n} (φ : L.bounded_formula α n) : (φ.map_term_rel ft fr (λ _, id)).map_term_rel ft' fr' (λ _, id) = φ.map_term_rel (λ _, (ft' _) ∘ (ft _)) (λ _, (fr' _) ∘ (fr _)) (λ _, id) := begin induction φ with _ _ _ _ _ _ _ _ _ _ _ ih1 ih2 _ _ ih3, { refl }, { simp [map_term_rel] }, { simp [map_term_rel] }, { simp [map_term_rel, ih1, ih2] }, { simp [map_term_rel, ih3], } end @[simp] lemma map_term_rel_id_id_id {n} (φ : L.bounded_formula α n) : φ.map_term_rel (λ _, id) (λ _, id) (λ _, id) = φ := begin induction φ with _ _ _ _ _ _ _ _ _ _ _ ih1 ih2 _ _ ih3, { refl }, { simp [map_term_rel] }, { simp [map_term_rel] }, { simp [map_term_rel, ih1, ih2] }, { simp [map_term_rel, ih3], } end /-- An equivalence of bounded formulas given by an equivalence of terms and an equivalence of relations. -/ @[simps] def map_term_rel_equiv (ft : ∀ n, L.term (α ⊕ fin n) ≃ L'.term (β ⊕ fin n)) (fr : ∀ n, L.relations n ≃ L'.relations n) {n} : L.bounded_formula α n ≃ L'.bounded_formula β n := ⟨map_term_rel (λ n, ft n) (λ n, fr n) (λ _, id), map_term_rel (λ n, (ft n).symm) (λ n, (fr n).symm) (λ _, id), λ φ, by simp, λ φ, by simp⟩ /-- A function to help relabel the variables in bounded formulas. -/ def relabel_aux (g : α → β ⊕ fin n) (k : ℕ) : α ⊕ fin k → β ⊕ fin (n + k) := sum.map id fin_sum_fin_equiv ∘ equiv.sum_assoc _ _ _ ∘ sum.map g id @[simp] lemma sum_elim_comp_relabel_aux {m : ℕ} {g : α → (β ⊕ fin n)} {v : β → M} {xs : fin (n + m) → M} : sum.elim v xs ∘ relabel_aux g m = sum.elim (sum.elim v (xs ∘ cast_add m) ∘ g) (xs ∘ nat_add n) := begin ext x, cases x, { simp only [bounded_formula.relabel_aux, function.comp_app, sum.map_inl, sum.elim_inl], cases g x with l r; simp }, { simp [bounded_formula.relabel_aux] } end @[simp] lemma relabel_aux_sum_inl (k : ℕ) : relabel_aux (sum.inl : α → α ⊕ fin n) k = sum.map id (nat_add n) := begin ext x, cases x; { simp [relabel_aux] }, end /-- Relabels a bounded formula's variables along a particular function. -/ def relabel (g : α → (β ⊕ fin n)) {k} (φ : L.bounded_formula α k) : L.bounded_formula β (n + k) := φ.map_term_rel (λ _ t, t.relabel (relabel_aux g _)) (λ _, id) (λ _, cast_le (ge_of_eq (add_assoc _ _ _))) @[simp] lemma relabel_falsum (g : α → (β ⊕ fin n)) {k} : (falsum : L.bounded_formula α k).relabel g = falsum := rfl @[simp] lemma relabel_bot (g : α → (β ⊕ fin n)) {k} : (⊥ : L.bounded_formula α k).relabel g = ⊥ := rfl @[simp] lemma relabel_imp (g : α → (β ⊕ fin n)) {k} (φ ψ : L.bounded_formula α k) : (φ.imp ψ).relabel g = (φ.relabel g).imp (ψ.relabel g) := rfl @[simp] lemma relabel_not (g : α → (β ⊕ fin n)) {k} (φ : L.bounded_formula α k) : φ.not.relabel g = (φ.relabel g).not := by simp [bounded_formula.not] @[simp] lemma relabel_all (g : α → (β ⊕ fin n)) {k} (φ : L.bounded_formula α (k + 1)) : φ.all.relabel g = (φ.relabel g).all := begin rw [relabel, map_term_rel, relabel], simp, end @[simp] lemma relabel_ex (g : α → (β ⊕ fin n)) {k} (φ : L.bounded_formula α (k + 1)) : φ.ex.relabel g = (φ.relabel g).ex := by simp [bounded_formula.ex] @[simp] lemma relabel_sum_inl (φ : L.bounded_formula α n) : (φ.relabel sum.inl : L.bounded_formula α (0 + n)) = φ.cast_le (ge_of_eq (zero_add n)) := begin simp only [relabel, relabel_aux_sum_inl], induction φ with _ _ _ _ _ _ _ _ _ _ _ ih1 ih2 _ _ ih3, { refl }, { simp [fin.nat_add_zero, cast_le_of_eq, map_term_rel] }, { simp [fin.nat_add_zero, cast_le_of_eq, map_term_rel] }, { simp [map_term_rel, ih1, ih2], }, { simp [map_term_rel, ih3, cast_le], }, end /-- Substitutes the variables in a given formula with terms. -/ @[simp] def subst {n : ℕ} (φ : L.bounded_formula α n) (f : α → L.term β) : L.bounded_formula β n := φ.map_term_rel (λ _ t, t.subst (sum.elim (term.relabel sum.inl ∘ f) (var ∘ sum.inr))) (λ _, id) (λ _, id) /-- A bijection sending formulas with constants to formulas with extra variables. -/ def constants_vars_equiv : L[[γ]].bounded_formula α n ≃ L.bounded_formula (γ ⊕ α) n := map_term_rel_equiv (λ _, term.constants_vars_equiv_left) (λ _, equiv.sum_empty _ _) /-- Turns the extra variables of a bounded formula into free variables. -/ @[simp] def to_formula : ∀ {n : ℕ}, L.bounded_formula α n → L.formula (α ⊕ fin n) | n falsum := falsum | n (equal t₁ t₂) := t₁.equal t₂ | n (rel R ts) := R.formula ts | n (imp φ₁ φ₂) := φ₁.to_formula.imp φ₂.to_formula | n (all φ) := (φ.to_formula.relabel (sum.elim (sum.inl ∘ sum.inl) (sum.map sum.inr id ∘ fin_sum_fin_equiv.symm))).all variables {l : ℕ} {φ ψ : L.bounded_formula α l} {θ : L.bounded_formula α l.succ} variables {v : α → M} {xs : fin l → M} /-- An atomic formula is either equality or a relation symbol applied to terms. Note that `⊥` and `⊤` are not considered atomic in this convention. -/ inductive is_atomic : L.bounded_formula α n → Prop | equal (t₁ t₂ : L.term (α ⊕ fin n)) : is_atomic (bd_equal t₁ t₂) | rel {l : ℕ} (R : L.relations l) (ts : fin l → L.term (α ⊕ fin n)) : is_atomic (R.bounded_formula ts) lemma not_all_is_atomic (φ : L.bounded_formula α (n + 1)) : ¬ φ.all.is_atomic := λ con, by cases con lemma not_ex_is_atomic (φ : L.bounded_formula α (n + 1)) : ¬ φ.ex.is_atomic := λ con, by cases con lemma is_atomic.relabel {m : ℕ} {φ : L.bounded_formula α m} (h : φ.is_atomic) (f : α → β ⊕ (fin n)) : (φ.relabel f).is_atomic := is_atomic.rec_on h (λ _ _, is_atomic.equal _ _) (λ _ _ _, is_atomic.rel _ _) lemma is_atomic.lift_at {k m : ℕ} (h : is_atomic φ) : (φ.lift_at k m).is_atomic := is_atomic.rec_on h (λ _ _, is_atomic.equal _ _) (λ _ _ _, is_atomic.rel _ _) lemma is_atomic.cast_le {h : l ≤ n} (hφ : is_atomic φ) : (φ.cast_le h).is_atomic := is_atomic.rec_on hφ (λ _ _, is_atomic.equal _ _) (λ _ _ _, is_atomic.rel _ _) /-- A quantifier-free formula is a formula defined without quantifiers. These are all equivalent to boolean combinations of atomic formulas. -/ inductive is_qf : L.bounded_formula α n → Prop | falsum : is_qf falsum | of_is_atomic {φ} (h : is_atomic φ) : is_qf φ | imp {φ₁ φ₂} (h₁ : is_qf φ₁) (h₂ : is_qf φ₂) : is_qf (φ₁.imp φ₂) lemma is_atomic.is_qf {φ : L.bounded_formula α n} : is_atomic φ → is_qf φ := is_qf.of_is_atomic lemma is_qf_bot : is_qf (⊥ : L.bounded_formula α n) := is_qf.falsum lemma is_qf.not {φ : L.bounded_formula α n} (h : is_qf φ) : is_qf φ.not := h.imp is_qf_bot lemma is_qf.relabel {m : ℕ} {φ : L.bounded_formula α m} (h : φ.is_qf) (f : α → β ⊕ (fin n)) : (φ.relabel f).is_qf := is_qf.rec_on h is_qf_bot (λ _ h, (h.relabel f).is_qf) (λ _ _ _ _ h1 h2, h1.imp h2) lemma is_qf.lift_at {k m : ℕ} (h : is_qf φ) : (φ.lift_at k m).is_qf := is_qf.rec_on h is_qf_bot (λ _ ih, ih.lift_at.is_qf) (λ _ _ _ _ ih1 ih2, ih1.imp ih2) lemma is_qf.cast_le {h : l ≤ n} (hφ : is_qf φ) : (φ.cast_le h).is_qf := is_qf.rec_on hφ is_qf_bot (λ _ ih, ih.cast_le.is_qf) (λ _ _ _ _ ih1 ih2, ih1.imp ih2) lemma not_all_is_qf (φ : L.bounded_formula α (n + 1)) : ¬ φ.all.is_qf := λ con, begin cases con with _ con, exact (φ.not_all_is_atomic con), end lemma not_ex_is_qf (φ : L.bounded_formula α (n + 1)) : ¬ φ.ex.is_qf := λ con, begin cases con with _ con _ _ con, { exact (φ.not_ex_is_atomic con) }, { exact not_all_is_qf _ con } end /-- Indicates that a bounded formula is in prenex normal form - that is, it consists of quantifiers applied to a quantifier-free formula. -/ inductive is_prenex : ∀ {n}, L.bounded_formula α n → Prop | of_is_qf {n} {φ : L.bounded_formula α n} (h : is_qf φ) : is_prenex φ | all {n} {φ : L.bounded_formula α (n + 1)} (h : is_prenex φ) : is_prenex φ.all | ex {n} {φ : L.bounded_formula α (n + 1)} (h : is_prenex φ) : is_prenex φ.ex lemma is_qf.is_prenex {φ : L.bounded_formula α n} : is_qf φ → is_prenex φ := is_prenex.of_is_qf lemma is_atomic.is_prenex {φ : L.bounded_formula α n} (h : is_atomic φ) : is_prenex φ := h.is_qf.is_prenex lemma is_prenex.induction_on_all_not {P : ∀ {n}, L.bounded_formula α n → Prop} {φ : L.bounded_formula α n} (h : is_prenex φ) (hq : ∀ {m} {ψ : L.bounded_formula α m}, ψ.is_qf → P ψ) (ha : ∀ {m} {ψ : L.bounded_formula α (m + 1)}, P ψ → P ψ.all) (hn : ∀ {m} {ψ : L.bounded_formula α m}, P ψ → P ψ.not) : P φ := is_prenex.rec_on h (λ _ _, hq) (λ _ _ _, ha) (λ _ _ _ ih, hn (ha (hn ih))) lemma is_prenex.relabel {m : ℕ} {φ : L.bounded_formula α m} (h : φ.is_prenex) (f : α → β ⊕ (fin n)) : (φ.relabel f).is_prenex := is_prenex.rec_on h (λ _ _ h, (h.relabel f).is_prenex) (λ _ _ _ h, by simp [h.all]) (λ _ _ _ h, by simp [h.ex]) lemma is_prenex.cast_le (hφ : is_prenex φ) : ∀ {n} {h : l ≤ n}, (φ.cast_le h).is_prenex := is_prenex.rec_on hφ (λ _ _ ih _ _, ih.cast_le.is_prenex) (λ _ _ _ ih _ _, ih.all) (λ _ _ _ ih _ _, ih.ex) lemma is_prenex.lift_at {k m : ℕ} (h : is_prenex φ) : (φ.lift_at k m).is_prenex := is_prenex.rec_on h (λ _ _ ih, ih.lift_at.is_prenex) (λ _ _ _ ih, ih.cast_le.all) (λ _ _ _ ih, ih.cast_le.ex) /-- An auxiliary operation to `first_order.language.bounded_formula.to_prenex`. If `φ` is quantifier-free and `ψ` is in prenex normal form, then `φ.to_prenex_imp_right ψ` is a prenex normal form for `φ.imp ψ`. -/ def to_prenex_imp_right : ∀ {n}, L.bounded_formula α n → L.bounded_formula α n → L.bounded_formula α n | n φ (bounded_formula.ex ψ) := ((φ.lift_at 1 n).to_prenex_imp_right ψ).ex | n φ (all ψ) := ((φ.lift_at 1 n).to_prenex_imp_right ψ).all | n φ ψ := φ.imp ψ lemma is_qf.to_prenex_imp_right {φ : L.bounded_formula α n} : Π {ψ : L.bounded_formula α n}, is_qf ψ → (φ.to_prenex_imp_right ψ = φ.imp ψ) | _ is_qf.falsum := rfl | _ (is_qf.of_is_atomic (is_atomic.equal _ _)) := rfl | _ (is_qf.of_is_atomic (is_atomic.rel _ _)) := rfl | _ (is_qf.imp is_qf.falsum _) := rfl | _ (is_qf.imp (is_qf.of_is_atomic (is_atomic.equal _ _)) _) := rfl | _ (is_qf.imp (is_qf.of_is_atomic (is_atomic.rel _ _)) _) := rfl | _ (is_qf.imp (is_qf.imp _ _) _) := rfl lemma is_prenex_to_prenex_imp_right {φ ψ : L.bounded_formula α n} (hφ : is_qf φ) (hψ : is_prenex ψ) : is_prenex (φ.to_prenex_imp_right ψ) := begin induction hψ with _ _ hψ _ _ _ ih1 _ _ _ ih2, { rw hψ.to_prenex_imp_right, exact (hφ.imp hψ).is_prenex }, { exact (ih1 hφ.lift_at).all }, { exact (ih2 hφ.lift_at).ex } end /-- An auxiliary operation to `first_order.language.bounded_formula.to_prenex`. If `φ` and `ψ` are in prenex normal form, then `φ.to_prenex_imp ψ` is a prenex normal form for `φ.imp ψ`. -/ def to_prenex_imp : ∀ {n}, L.bounded_formula α n → L.bounded_formula α n → L.bounded_formula α n | n (bounded_formula.ex φ) ψ := (φ.to_prenex_imp (ψ.lift_at 1 n)).all | n (all φ) ψ := (φ.to_prenex_imp (ψ.lift_at 1 n)).ex | _ φ ψ := φ.to_prenex_imp_right ψ lemma is_qf.to_prenex_imp : Π {φ ψ : L.bounded_formula α n}, φ.is_qf → φ.to_prenex_imp ψ = φ.to_prenex_imp_right ψ | _ _ is_qf.falsum := rfl | _ _ (is_qf.of_is_atomic (is_atomic.equal _ _)) := rfl | _ _ (is_qf.of_is_atomic (is_atomic.rel _ _)) := rfl | _ _ (is_qf.imp is_qf.falsum _) := rfl | _ _ (is_qf.imp (is_qf.of_is_atomic (is_atomic.equal _ _)) _) := rfl | _ _ (is_qf.imp (is_qf.of_is_atomic (is_atomic.rel _ _)) _) := rfl | _ _ (is_qf.imp (is_qf.imp _ _) _) := rfl lemma is_prenex_to_prenex_imp {φ ψ : L.bounded_formula α n} (hφ : is_prenex φ) (hψ : is_prenex ψ) : is_prenex (φ.to_prenex_imp ψ) := begin induction hφ with _ _ hφ _ _ _ ih1 _ _ _ ih2, { rw hφ.to_prenex_imp, exact is_prenex_to_prenex_imp_right hφ hψ }, { exact (ih1 hψ.lift_at).ex }, { exact (ih2 hψ.lift_at).all } end /-- For any bounded formula `φ`, `φ.to_prenex` is a semantically-equivalent formula in prenex normal form. -/ def to_prenex : ∀ {n}, L.bounded_formula α n → L.bounded_formula α n | _ falsum := ⊥ | _ (equal t₁ t₂) := t₁.bd_equal t₂ | _ (rel R ts) := rel R ts | _ (imp f₁ f₂) := f₁.to_prenex.to_prenex_imp f₂.to_prenex | _ (all f) := f.to_prenex.all lemma to_prenex_is_prenex (φ : L.bounded_formula α n) : φ.to_prenex.is_prenex := bounded_formula.rec_on φ (λ _, is_qf_bot.is_prenex) (λ _ _ _, (is_atomic.equal _ _).is_prenex) (λ _ _ _ _, (is_atomic.rel _ _).is_prenex) (λ _ _ _ h1 h2, is_prenex_to_prenex_imp h1 h2) (λ _ _, is_prenex.all) end bounded_formula namespace Lhom open bounded_formula /-- Maps a bounded formula's symbols along a language map. -/ @[simp] def on_bounded_formula (g : L →ᴸ L') : ∀ {k : ℕ}, L.bounded_formula α k → L'.bounded_formula α k | k falsum := falsum | k (equal t₁ t₂) := (g.on_term t₁).bd_equal (g.on_term t₂) | k (rel R ts) := (g.on_relation R).bounded_formula (g.on_term ∘ ts) | k (imp f₁ f₂) := (on_bounded_formula f₁).imp (on_bounded_formula f₂) | k (all f) := (on_bounded_formula f).all @[simp] lemma id_on_bounded_formula : ((Lhom.id L).on_bounded_formula : L.bounded_formula α n → L.bounded_formula α n) = id := begin ext f, induction f with _ _ _ _ _ _ _ _ _ _ _ ih1 ih2 _ _ ih3, { refl }, { rw [on_bounded_formula, Lhom.id_on_term, id.def, id.def, id.def, bd_equal] }, { rw [on_bounded_formula, Lhom.id_on_term], refl, }, { rw [on_bounded_formula, ih1, ih2, id.def, id.def, id.def] }, { rw [on_bounded_formula, ih3, id.def, id.def] } end @[simp] lemma comp_on_bounded_formula {L'' : language} (φ : L' →ᴸ L'') (ψ : L →ᴸ L') : ((φ.comp ψ).on_bounded_formula : L.bounded_formula α n → L''.bounded_formula α n) = φ.on_bounded_formula ∘ ψ.on_bounded_formula := begin ext f, induction f with _ _ _ _ _ _ _ _ _ _ _ ih1 ih2 _ _ ih3, { refl }, { simp only [on_bounded_formula, comp_on_term, function.comp_app], refl, }, { simp only [on_bounded_formula, comp_on_relation, comp_on_term, function.comp_app], refl }, { simp only [on_bounded_formula, function.comp_app, ih1, ih2, eq_self_iff_true, and_self], }, { simp only [ih3, on_bounded_formula, function.comp_app] } end /-- Maps a formula's symbols along a language map. -/ def on_formula (g : L →ᴸ L') : L.formula α → L'.formula α := g.on_bounded_formula /-- Maps a sentence's symbols along a language map. -/ def on_sentence (g : L →ᴸ L') : L.sentence → L'.sentence := g.on_formula /-- Maps a theory's symbols along a language map. -/ def on_Theory (g : L →ᴸ L') (T : L.Theory) : L'.Theory := g.on_sentence '' T @[simp] lemma mem_on_Theory {g : L →ᴸ L'} {T : L.Theory} {φ : L'.sentence} : φ ∈ g.on_Theory T ↔ ∃ φ₀, φ₀ ∈ T ∧ g.on_sentence φ₀ = φ := set.mem_image _ _ _ end Lhom namespace Lequiv /-- Maps a bounded formula's symbols along a language equivalence. -/ @[simps] def on_bounded_formula (φ : L ≃ᴸ L') : L.bounded_formula α n ≃ L'.bounded_formula α n := { to_fun := φ.to_Lhom.on_bounded_formula, inv_fun := φ.inv_Lhom.on_bounded_formula, left_inv := by rw [function.left_inverse_iff_comp, ← Lhom.comp_on_bounded_formula, φ.left_inv, Lhom.id_on_bounded_formula], right_inv := by rw [function.right_inverse_iff_comp, ← Lhom.comp_on_bounded_formula, φ.right_inv, Lhom.id_on_bounded_formula] } lemma on_bounded_formula_symm (φ : L ≃ᴸ L') : (φ.on_bounded_formula.symm : L'.bounded_formula α n ≃ L.bounded_formula α n) = φ.symm.on_bounded_formula := rfl /-- Maps a formula's symbols along a language equivalence. -/ def on_formula (φ : L ≃ᴸ L') : L.formula α ≃ L'.formula α := φ.on_bounded_formula @[simp] lemma on_formula_apply (φ : L ≃ᴸ L') : (φ.on_formula : L.formula α → L'.formula α) = φ.to_Lhom.on_formula := rfl @[simp] lemma on_formula_symm (φ : L ≃ᴸ L') : (φ.on_formula.symm : L'.formula α ≃ L.formula α) = φ.symm.on_formula := rfl /-- Maps a sentence's symbols along a language equivalence. -/ @[simps] def on_sentence (φ : L ≃ᴸ L') : L.sentence ≃ L'.sentence := φ.on_formula end Lequiv localized "infix ` =' `:88 := first_order.language.term.bd_equal" in first_order -- input \~- or \simeq localized "infixr ` ⟹ `:62 := first_order.language.bounded_formula.imp" in first_order -- input \==> localized "prefix `∀'`:110 := first_order.language.bounded_formula.all" in first_order localized "prefix `∼`:max := first_order.language.bounded_formula.not" in first_order -- input \~, the ASCII character ~ has too low precedence localized "infix ` ⇔ `:61 := first_order.language.bounded_formula.iff" in first_order -- input \<=> localized "prefix `∃'`:110 := first_order.language.bounded_formula.ex" in first_order -- input \ex namespace formula /-- Relabels a formula's variables along a particular function. -/ def relabel (g : α → β) : L.formula α → L.formula β := @bounded_formula.relabel _ _ _ 0 (sum.inl ∘ g) 0 /-- The graph of a function as a first-order formula. -/ def graph (f : L.functions n) : L.formula (fin (n + 1)) := equal (var 0) (func f (λ i, var i.succ)) /-- The negation of a formula. -/ protected def not (φ : L.formula α) : L.formula α := φ.not /-- The implication between formulas, as a formula. -/ protected def imp : L.formula α → L.formula α → L.formula α := bounded_formula.imp /-- The biimplication between formulas, as a formula. -/ protected def iff (φ ψ : L.formula α) : L.formula α := φ.iff ψ lemma is_atomic_graph (f : L.functions n) : (graph f).is_atomic := bounded_formula.is_atomic.equal _ _ end formula namespace relations variable (r : L.relations 2) /-- The sentence indicating that a basic relation symbol is reflexive. -/ protected def reflexive : L.sentence := ∀' r.bounded_formula₂ &0 &0 /-- The sentence indicating that a basic relation symbol is irreflexive. -/ protected def irreflexive : L.sentence := ∀' ∼ (r.bounded_formula₂ &0 &0) /-- The sentence indicating that a basic relation symbol is symmetric. -/ protected def symmetric : L.sentence := ∀' ∀' (r.bounded_formula₂ &0 &1 ⟹ r.bounded_formula₂ &1 &0) /-- The sentence indicating that a basic relation symbol is antisymmetric. -/ protected def antisymmetric : L.sentence := ∀' ∀' (r.bounded_formula₂ &0 &1 ⟹ (r.bounded_formula₂ &1 &0 ⟹ term.bd_equal &0 &1)) /-- The sentence indicating that a basic relation symbol is transitive. -/ protected def transitive : L.sentence := ∀' ∀' ∀' (r.bounded_formula₂ &0 &1 ⟹ r.bounded_formula₂ &1 &2 ⟹ r.bounded_formula₂ &0 &2) /-- The sentence indicating that a basic relation symbol is total. -/ protected def total : L.sentence := ∀' ∀' (r.bounded_formula₂ &0 &1 ⊔ r.bounded_formula₂ &1 &0) end relations section cardinality variable (L) /-- A sentence indicating that a structure has `n` distinct elements. -/ protected def sentence.card_ge (n) : L.sentence := (((((list.fin_range n).product (list.fin_range n)).filter (λ ij : _ × _, ij.1 ≠ ij.2)).map (λ (ij : _ × _), ∼ ((& ij.1).bd_equal (& ij.2)))).foldr (⊓) ⊤).exs /-- A theory indicating that a structure is infinite. -/ def infinite_theory : L.Theory := set.range (sentence.card_ge L) /-- A theory that indicates a structure is nonempty. -/ def nonempty_theory : L.Theory := {sentence.card_ge L 1} /-- A theory indicating that each of a set of constants is distinct. -/ def distinct_constants_theory (s : set α) : L[[α]].Theory := (λ ab : α × α, (((L.con ab.1).term.equal (L.con ab.2).term).not)) '' (s ×ˢ s ∩ (set.diagonal α)ᶜ) variables {L} {α} open set lemma monotone_distinct_constants_theory : monotone (L.distinct_constants_theory : set α → L[[α]].Theory) := λ s t st, (image_subset _ (inter_subset_inter_left _ (prod_mono st st))) lemma directed_distinct_constants_theory : directed (⊆) (L.distinct_constants_theory : set α → L[[α]].Theory) := monotone.directed_le monotone_distinct_constants_theory lemma distinct_constants_theory_eq_Union (s : set α) : L.distinct_constants_theory s = ⋃ (t : finset s), L.distinct_constants_theory (t.map (function.embedding.subtype (λ x, x ∈ s))) := begin classical, simp only [distinct_constants_theory], rw [← image_Union, ← Union_inter], refine congr rfl (congr (congr rfl _) rfl), ext ⟨i, j⟩, simp only [prod_mk_mem_set_prod_eq, finset.coe_map, function.embedding.coe_subtype, mem_Union, mem_image, finset.mem_coe, subtype.exists, subtype.coe_mk, exists_and_distrib_right, exists_eq_right], refine ⟨λ h, ⟨{⟨i, h.1⟩, ⟨j, h.2⟩}, ⟨h.1, _⟩, ⟨h.2, _⟩⟩, _⟩, { simp }, { simp }, { rintros ⟨t, ⟨is, _⟩, ⟨js, _⟩⟩, exact ⟨is, js⟩ } end end cardinality end language end first_order
861164cd9974fa2548d462317e6954fa7fe1bc48
d1a52c3f208fa42c41df8278c3d280f075eb020c
/src/Lean/Data/Lsp/Diagnostics.lean
2f84efe0f1bdd1e5f8714dade74e87ee5ca34197
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
cipher1024/lean4
6e1f98bb58e7a92b28f5364eb38a14c8d0aae393
69114d3b50806264ef35b57394391c3e738a9822
refs/heads/master
1,642,227,983,603
1,642,011,696,000
1,642,011,696,000
228,607,691
0
0
Apache-2.0
1,576,584,269,000
1,576,584,268,000
null
UTF-8
Lean
false
false
3,016
lean
/- Copyright (c) 2020 Marc Huisinga. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Marc Huisinga, Wojciech Nawrocki -/ import Lean.Data.Json import Lean.Data.Lsp.Basic import Lean.Data.Lsp.Utf16 import Lean.Message /-! Definitions and functionality for emitting diagnostic information such as errors, warnings and #command outputs from the LSP server. -/ namespace Lean namespace Lsp open Json inductive DiagnosticSeverity where | error | warning | information | hint deriving Inhabited, BEq instance : FromJson DiagnosticSeverity := ⟨fun j => match j.getNat? with | Except.ok 1 => DiagnosticSeverity.error | Except.ok 2 => DiagnosticSeverity.warning | Except.ok 3 => DiagnosticSeverity.information | Except.ok 4 => DiagnosticSeverity.hint | _ => throw s!"unknown DiagnosticSeverity '{j}'"⟩ instance : ToJson DiagnosticSeverity := ⟨fun | DiagnosticSeverity.error => 1 | DiagnosticSeverity.warning => 2 | DiagnosticSeverity.information => 3 | DiagnosticSeverity.hint => 4⟩ inductive DiagnosticCode where | int (i : Int) | string (s : String) deriving Inhabited, BEq instance : FromJson DiagnosticCode := ⟨fun | num (i : Int) => DiagnosticCode.int i | str s => DiagnosticCode.string s | j => throw s!"expected string or integer diagnostic code, got '{j}'"⟩ instance : ToJson DiagnosticCode := ⟨fun | DiagnosticCode.int i => i | DiagnosticCode.string s => s⟩ inductive DiagnosticTag where | unnecessary | deprecated deriving Inhabited, BEq instance : FromJson DiagnosticTag := ⟨fun j => match j.getNat? with | Except.ok 1 => DiagnosticTag.unnecessary | Except.ok 2 => DiagnosticTag.deprecated | _ => throw "unknown DiagnosticTag"⟩ instance : ToJson DiagnosticTag := ⟨fun | DiagnosticTag.unnecessary => (1 : Nat) | DiagnosticTag.deprecated => (2 : Nat)⟩ structure DiagnosticRelatedInformation where location : Location message : String deriving Inhabited, BEq, ToJson, FromJson structure DiagnosticWith (α : Type) where range : Range /-- Extension: preserve semantic range of errors when truncating them for display purposes. -/ fullRange : Range := range severity? : Option DiagnosticSeverity := none code? : Option DiagnosticCode := none source? : Option String := none /-- Parametrised by the type of message data. LSP diagnostics use `String`, whereas in Lean's interactive diagnostics we use the type of widget-enriched text. See `Lean.Widget.InteractiveDiagnostic`. -/ message : α tags? : Option (Array DiagnosticTag) := none relatedInformation? : Option (Array DiagnosticRelatedInformation) := none deriving Inhabited, BEq, ToJson, FromJson abbrev Diagnostic := DiagnosticWith String structure PublishDiagnosticsParams where uri : DocumentUri version? : Option Int := none diagnostics: Array Diagnostic deriving Inhabited, BEq, ToJson, FromJson end Lsp end Lean
6e2a5f432ae9810ed1652232efe8b48e2370f77f
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/archive/100-theorems-list/57_herons_formula.lean
a0fbf10fc921198818f4da5ef748d417370e7ee0
[ "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
2,831
lean
/- Copyright (c) 2021 Matt Kempster. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Matt Kempster -/ import geometry.euclidean.triangle import analysis.special_functions.trigonometric /-! # Freek № 57: Heron's Formula This file proves Theorem 57 from the [100 Theorems List](https://www.cs.ru.nl/~freek/100/), also known as Heron's formula, which gives the area of a triangle based only on its three sides' lengths. ## References * https://en.wikipedia.org/wiki/Herons_formula -/ open real euclidean_geometry open_locale real euclidean_geometry local notation `√` := real.sqrt variables {V : Type*} {P : Type*} [inner_product_space ℝ V] [metric_space P] [normed_add_torsor V P] include V /-- Heron's formula: The area of a triangle with side lengths `a`, `b`, and `c` is `√(s * (s - a) * (s - b) * (s - c))` where `s = (a + b + c) / 2` is the semiperimeter. We show this by equating this formula to `a * b * sin γ`, where `γ` is the angle opposite the side `c`. -/ theorem heron {p1 p2 p3 : P} (h1 : p1 ≠ p2) (h2 : p3 ≠ p2) : let a := dist p1 p2, b := dist p3 p2, c := dist p1 p3, s := (a + b + c) / 2 in 1/2 * a * b * sin (∠ p1 p2 p3) = √(s * (s - a) * (s - b) * (s - c)) := begin intros a b c s, let γ := ∠ p1 p2 p3, obtain := ⟨(dist_pos.mpr h1).ne', (dist_pos.mpr h2).ne'⟩, have cos_rule : cos γ = (a * a + b * b - c * c) / (2 * a * b) := by field_simp [mul_comm, a, dist_sq_eq_dist_sq_add_dist_sq_sub_two_mul_dist_mul_dist_mul_cos_angle p1 p2 p3], let numerator := (2*a*b)^2 - (a*a + b*b - c*c)^2, let denominator := (2*a*b)^2, have split_to_frac : 1 - cos γ ^ 2 = numerator / denominator := by field_simp [cos_rule], have numerator_nonneg : 0 ≤ numerator, { have frac_nonneg: 0 ≤ numerator / denominator := by linarith [split_to_frac, cos_sq_le_one γ], cases div_nonneg_iff.mp frac_nonneg, { exact h.left }, { simpa [h1, h2] using le_antisymm h.right (sq_nonneg _) } }, have ab2_nonneg : 0 ≤ (2 * a * b) := by norm_num [mul_nonneg, dist_nonneg], calc 1/2 * a * b * sin γ = 1/2 * a * b * (√numerator / √denominator) : by rw [sin_eq_sqrt_one_sub_cos_sq, split_to_frac, sqrt_div numerator_nonneg]; simp [angle_nonneg, angle_le_pi] ... = 1/4 * √((2*a*b)^2 - (a*a + b*b - c*c)^2) : by { field_simp [ab2_nonneg], ring } ... = 1/4 * √(s * (s-a) * (s-b) * (s-c) * 4^2) : by { simp only [s], ring_nf } ... = √(s * (s-a) * (s-b) * (s-c)) : by rw [sqrt_mul', sqrt_sq, div_mul_eq_mul_div, one_mul, mul_div_cancel]; norm_num, end
adba333ee753e4ec96f724fbec8af85cef1a14a3
9dc8cecdf3c4634764a18254e94d43da07142918
/src/measure_theory/function/simple_func_dense.lean
43fbd7037f1a0fca605ae4a4597d93365da99d11
[ "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
7,466
lean
/- Copyright (c) 2019 Zhouhang Zhou. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Zhouhang Zhou, Yury Kudryashov, Heather Macbeth -/ import measure_theory.integral.mean_inequalities import topology.continuous_function.compact import topology.metric_space.metrizable /-! # Density of simple functions Show that each Borel measurable function can be approximated pointwise by a sequence of simple functions. ## Main definitions * `measure_theory.simple_func.nearest_pt (e : ℕ → α) (N : ℕ) : α →ₛ ℕ`: the `simple_func` sending each `x : α` to the point `e k` which is the nearest to `x` among `e 0`, ..., `e N`. * `measure_theory.simple_func.approx_on (f : β → α) (hf : measurable f) (s : set α) (y₀ : α) (h₀ : y₀ ∈ s) [separable_space s] (n : ℕ) : β →ₛ α` : a simple function that takes values in `s` and approximates `f`. ## Main results * `tendsto_approx_on` (pointwise convergence): If `f x ∈ s`, then the sequence of simple approximations `measure_theory.simple_func.approx_on f hf s y₀ h₀ n`, evaluated at `x`, tends to `f x` as `n` tends to `∞`. ## Notations * `α →ₛ β` (local notation): the type of simple functions `α → β`. -/ open set function filter topological_space ennreal emetric finset open_locale classical topological_space ennreal measure_theory big_operators variables {α β ι E F 𝕜 : Type*} noncomputable theory namespace measure_theory local infixr ` →ₛ `:25 := simple_func namespace simple_func /-! ### Pointwise approximation by simple functions -/ variables [measurable_space α] [pseudo_emetric_space α] [opens_measurable_space α] /-- `nearest_pt_ind e N x` is the index `k` such that `e k` is the nearest point to `x` among the points `e 0`, ..., `e N`. If more than one point are at the same distance from `x`, then `nearest_pt_ind e N x` returns the least of their indexes. -/ noncomputable def nearest_pt_ind (e : ℕ → α) : ℕ → α →ₛ ℕ | 0 := const α 0 | (N + 1) := piecewise (⋂ k ≤ N, {x | edist (e (N + 1)) x < edist (e k) x}) (measurable_set.Inter $ λ k, measurable_set.Inter $ λ hk, measurable_set_lt measurable_edist_right measurable_edist_right) (const α $ N + 1) (nearest_pt_ind N) /-- `nearest_pt e N x` is the nearest point to `x` among the points `e 0`, ..., `e N`. If more than one point are at the same distance from `x`, then `nearest_pt e N x` returns the point with the least possible index. -/ noncomputable def nearest_pt (e : ℕ → α) (N : ℕ) : α →ₛ α := (nearest_pt_ind e N).map e @[simp] lemma nearest_pt_ind_zero (e : ℕ → α) : nearest_pt_ind e 0 = const α 0 := rfl @[simp] lemma nearest_pt_zero (e : ℕ → α) : nearest_pt e 0 = const α (e 0) := rfl lemma nearest_pt_ind_succ (e : ℕ → α) (N : ℕ) (x : α) : nearest_pt_ind e (N + 1) x = if ∀ k ≤ N, edist (e (N + 1)) x < edist (e k) x then N + 1 else nearest_pt_ind e N x := by { simp only [nearest_pt_ind, coe_piecewise, set.piecewise], congr, simp } lemma nearest_pt_ind_le (e : ℕ → α) (N : ℕ) (x : α) : nearest_pt_ind e N x ≤ N := begin induction N with N ihN, { simp }, simp only [nearest_pt_ind_succ], split_ifs, exacts [le_rfl, ihN.trans N.le_succ] end lemma edist_nearest_pt_le (e : ℕ → α) (x : α) {k N : ℕ} (hk : k ≤ N) : edist (nearest_pt e N x) x ≤ edist (e k) x := begin induction N with N ihN generalizing k, { simp [nonpos_iff_eq_zero.1 hk, le_refl] }, { simp only [nearest_pt, nearest_pt_ind_succ, map_apply], split_ifs, { rcases hk.eq_or_lt with rfl|hk, exacts [le_rfl, (h k (nat.lt_succ_iff.1 hk)).le] }, { push_neg at h, rcases h with ⟨l, hlN, hxl⟩, rcases hk.eq_or_lt with rfl|hk, exacts [(ihN hlN).trans hxl, ihN (nat.lt_succ_iff.1 hk)] } } end lemma tendsto_nearest_pt {e : ℕ → α} {x : α} (hx : x ∈ closure (range e)) : tendsto (λ N, nearest_pt e N x) at_top (𝓝 x) := begin refine (at_top_basis.tendsto_iff nhds_basis_eball).2 (λ ε hε, _), rcases emetric.mem_closure_iff.1 hx ε hε with ⟨_, ⟨N, rfl⟩, hN⟩, rw [edist_comm] at hN, exact ⟨N, trivial, λ n hn, (edist_nearest_pt_le e x hn).trans_lt hN⟩ end variables [measurable_space β] {f : β → α} /-- Approximate a measurable function by a sequence of simple functions `F n` such that `F n x ∈ s`. -/ noncomputable def approx_on (f : β → α) (hf : measurable f) (s : set α) (y₀ : α) (h₀ : y₀ ∈ s) [separable_space s] (n : ℕ) : β →ₛ α := by haveI : nonempty s := ⟨⟨y₀, h₀⟩⟩; exact comp (nearest_pt (λ k, nat.cases_on k y₀ (coe ∘ dense_seq s) : ℕ → α) n) f hf @[simp] lemma approx_on_zero {f : β → α} (hf : measurable f) {s : set α} {y₀ : α} (h₀ : y₀ ∈ s) [separable_space s] (x : β) : approx_on f hf s y₀ h₀ 0 x = y₀ := rfl lemma approx_on_mem {f : β → α} (hf : measurable f) {s : set α} {y₀ : α} (h₀ : y₀ ∈ s) [separable_space s] (n : ℕ) (x : β) : approx_on f hf s y₀ h₀ n x ∈ s := begin haveI : nonempty s := ⟨⟨y₀, h₀⟩⟩, suffices : ∀ n, (nat.cases_on n y₀ (coe ∘ dense_seq s) : α) ∈ s, { apply this }, rintro (_|n), exacts [h₀, subtype.mem _] end @[simp] lemma approx_on_comp {γ : Type*} [measurable_space γ] {f : β → α} (hf : measurable f) {g : γ → β} (hg : measurable g) {s : set α} {y₀ : α} (h₀ : y₀ ∈ s) [separable_space s] (n : ℕ) : approx_on (f ∘ g) (hf.comp hg) s y₀ h₀ n = (approx_on f hf s y₀ h₀ n).comp g hg := rfl lemma tendsto_approx_on {f : β → α} (hf : measurable f) {s : set α} {y₀ : α} (h₀ : y₀ ∈ s) [separable_space s] {x : β} (hx : f x ∈ closure s) : tendsto (λ n, approx_on f hf s y₀ h₀ n x) at_top (𝓝 $ f x) := begin haveI : nonempty s := ⟨⟨y₀, h₀⟩⟩, rw [← @subtype.range_coe _ s, ← image_univ, ← (dense_range_dense_seq s).closure_eq] at hx, simp only [approx_on, coe_comp], refine tendsto_nearest_pt (closure_minimal _ is_closed_closure hx), simp only [nat.range_cases_on, closure_union, range_comp coe], exact subset.trans (image_closure_subset_closure_image continuous_subtype_coe) (subset_union_right _ _) end lemma edist_approx_on_mono {f : β → α} (hf : measurable f) {s : set α} {y₀ : α} (h₀ : y₀ ∈ s) [separable_space s] (x : β) {m n : ℕ} (h : m ≤ n) : edist (approx_on f hf s y₀ h₀ n x) (f x) ≤ edist (approx_on f hf s y₀ h₀ m x) (f x) := begin dsimp only [approx_on, coe_comp, (∘)], exact edist_nearest_pt_le _ _ ((nearest_pt_ind_le _ _ _).trans h) end lemma edist_approx_on_le {f : β → α} (hf : measurable f) {s : set α} {y₀ : α} (h₀ : y₀ ∈ s) [separable_space s] (x : β) (n : ℕ) : edist (approx_on f hf s y₀ h₀ n x) (f x) ≤ edist y₀ (f x) := edist_approx_on_mono hf h₀ x (zero_le n) lemma edist_approx_on_y0_le {f : β → α} (hf : measurable f) {s : set α} {y₀ : α} (h₀ : y₀ ∈ s) [separable_space s] (x : β) (n : ℕ) : edist y₀ (approx_on f hf s y₀ h₀ n x) ≤ edist y₀ (f x) + edist y₀ (f x) := calc edist y₀ (approx_on f hf s y₀ h₀ n x) ≤ edist y₀ (f x) + edist (approx_on f hf s y₀ h₀ n x) (f x) : edist_triangle_right _ _ _ ... ≤ edist y₀ (f x) + edist y₀ (f x) : add_le_add_left (edist_approx_on_le hf h₀ x n) _ end simple_func end measure_theory
e7d8bec621057d0e522b960bd739acc942ebb8f5
e0f9ba56b7fedc16ef8697f6caeef5898b435143
/src/control/traversable/lemmas.lean
782f17bb9e6b5b4d529f4e5d1ca8623d98b79d0d
[ "Apache-2.0" ]
permissive
anrddh/mathlib
6a374da53c7e3a35cb0298b0cd67824efef362b4
a4266a01d2dcb10de19369307c986d038c7bb6a6
refs/heads/master
1,656,710,827,909
1,589,560,456,000
1,589,560,456,000
264,271,800
0
0
Apache-2.0
1,589,568,062,000
1,589,568,061,000
null
UTF-8
Lean
false
false
3,655
lean
/- Copyright (c) 2018 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Simon Hudon Lemmas about traversing collections. Inspired by: The Essence of the Iterator Pattern Jeremy Gibbons and Bruno César dos Santos Oliveira In Journal of Functional Programming. Vol. 19. No. 3&4. Pages 377−402. 2009. <http://www.cs.ox.ac.uk/jeremy.gibbons/publications/iterator.pdf> -/ import control.traversable.basic universe variables u open is_lawful_traversable open function (hiding comp) open functor attribute [functor_norm] is_lawful_traversable.naturality attribute [simp] is_lawful_traversable.id_traverse namespace traversable variable {t : Type u → Type u} variables [traversable t] [is_lawful_traversable t] variables F G : Type u → Type u variables [applicative F] [is_lawful_applicative F] variables [applicative G] [is_lawful_applicative G] variables {α β γ : Type u} variables g : α → F β variables h : β → G γ variables f : β → γ def pure_transformation : applicative_transformation id F := { app := @pure F _, preserves_pure' := λ α x, rfl, preserves_seq' := λ α β f x, by simp; refl } @[simp] theorem pure_transformation_apply {α} (x : id α) : (pure_transformation F) x = pure x := rfl variables {F G} (x : t β) lemma map_eq_traverse_id : map f = @traverse t _ _ _ _ _ (id.mk ∘ f) := funext $ λ y, (traverse_eq_map_id f y).symm theorem map_traverse (x : t α) : map f <$> traverse g x = traverse (map f ∘ g) x := begin rw @map_eq_traverse_id t _ _ _ _ f, refine (comp_traverse (id.mk ∘ f) g x).symm.trans _, congr, apply comp.applicative_comp_id end theorem traverse_map (f : β → F γ) (g : α → β) (x : t α) : traverse f (g <$> x) = traverse (f ∘ g) x := begin rw @map_eq_traverse_id t _ _ _ _ g, refine (comp_traverse f (id.mk ∘ g) x).symm.trans _, congr, apply comp.applicative_id_comp end lemma pure_traverse (x : t α) : traverse pure x = (pure x : F (t α)) := by have : traverse pure x = pure (traverse id.mk x) := (naturality (pure_transformation F) id.mk x).symm; rwa id_traverse at this lemma id_sequence (x : t α) : sequence (id.mk <$> x) = id.mk x := by simp [sequence, traverse_map, id_traverse]; refl lemma comp_sequence (x : t (F (G α))) : sequence (comp.mk <$> x) = comp.mk (sequence <$> sequence x) := by simp [sequence, traverse_map]; rw ← comp_traverse; simp [map_id] lemma naturality' (η : applicative_transformation F G) (x : t (F α)) : η (sequence x) = sequence (@η _ <$> x) := by simp [sequence, naturality, traverse_map] @[functor_norm] lemma traverse_id : traverse id.mk = (id.mk : t α → id (t α)) := by ext; simp [id_traverse]; refl @[functor_norm] lemma traverse_comp (g : α → F β) (h : β → G γ) : traverse (comp.mk ∘ map h ∘ g) = (comp.mk ∘ map (traverse h) ∘ traverse g : t α → comp F G (t γ)) := by ext; simp [comp_traverse] lemma traverse_eq_map_id' (f : β → γ) : traverse (id.mk ∘ f) = id.mk ∘ (map f : t β → t γ) := by ext;rw traverse_eq_map_id -- @[functor_norm] lemma traverse_map' (g : α → β) (h : β → G γ) : traverse (h ∘ g) = (traverse h ∘ map g : t α → G (t γ)) := by ext; simp [traverse_map] lemma map_traverse' (g : α → G β) (h : β → γ) : traverse (map h ∘ g) = (map (map h) ∘ traverse g : t α → G (t γ)) := by ext; simp [map_traverse] lemma naturality_pf (η : applicative_transformation F G) (f : α → F β) : traverse (@η _ ∘ f) = @η _ ∘ (traverse f : t α → F (t β)) := by ext; simp [naturality] end traversable
8c2b1ca081512d9906742f38279bb69ab0c10d6b
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/doc/BoolExpr.lean
ae9d02cbd4b994623fb018dc1a3c6f51308db282
[ "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
3,605
lean
open Std open Lean inductive BoolExpr where | var (name : String) | val (b : Bool) | or (p q : BoolExpr) | not (p : BoolExpr) deriving Repr, BEq, DecidableEq def BoolExpr.isValue : BoolExpr → Bool | val _ => true | _ => false instance : Inhabited BoolExpr where default := BoolExpr.val false namespace BoolExpr deriving instance DecidableEq for BoolExpr #eval decide (BoolExpr.val true = BoolExpr.val false) #check (a b : BoolExpr) → Decidable (a = b) abbrev Context := AssocList String Bool def denote (ctx : Context) : BoolExpr → Bool | BoolExpr.or p q => denote ctx p || denote ctx q | BoolExpr.not p => !denote ctx p | BoolExpr.val b => b | BoolExpr.var x => if let some b := ctx.find? x then b else false def simplify : BoolExpr → BoolExpr | or p q => mkOr (simplify p) (simplify q) | not p => mkNot (simplify p) | e => e where mkOr : BoolExpr → BoolExpr → BoolExpr | p, val true => val true | p, val false => p | val true, p => val true | val false, p => p | p, q => or p q mkNot : BoolExpr → BoolExpr | val b => val (!b) | p => not p @[simp] theorem denote_not_Eq (ctx : Context) (p : BoolExpr) : denote ctx (not p) = !denote ctx p := rfl @[simp] theorem denote_or_Eq (ctx : Context) (p q : BoolExpr) : denote ctx (or p q) = (denote ctx p || denote ctx q) := rfl @[simp] theorem denote_val_Eq (ctx : Context) (b : Bool) : denote ctx (val b) = b := rfl @[simp] theorem denote_mkNot_Eq (ctx : Context) (p : BoolExpr) : denote ctx (simplify.mkNot p) = denote ctx (not p) := by cases p <;> rfl @[simp] theorem mkOr_p_true (p : BoolExpr) : simplify.mkOr p (val true) = val true := by cases p with | val x => cases x <;> rfl | _ => rfl @[simp] theorem mkOr_p_false (p : BoolExpr) : simplify.mkOr p (val false) = p := by cases p with | val x => cases x <;> rfl | _ => rfl @[simp] theorem mkOr_true_p (p : BoolExpr) : simplify.mkOr (val true) p = val true := by cases p with | val x => cases x <;> rfl | _ => rfl @[simp] theorem mkOr_false_p (p : BoolExpr) : simplify.mkOr (val false) p = p := by cases p with | val x => cases x <;> rfl | _ => rfl @[simp] theorem denote_mkOr (ctx : Context) (p q : BoolExpr) : denote ctx (simplify.mkOr p q) = denote ctx (or p q) := by cases p with | val x => cases q with | val y => cases x <;> cases y <;> simp | _ => cases x <;> simp | _ => cases q with | val y => cases y <;> simp | _ => rfl @[simp] theorem simplify_not (p : BoolExpr) : simplify (not p) = simplify.mkNot (simplify p) := rfl @[simp] theorem simplify_or (p q : BoolExpr) : simplify (or p q) = simplify.mkOr (simplify p) (simplify q) := rfl def denote_simplify_eq (ctx : Context) (b : BoolExpr) : denote ctx (simplify b) = denote ctx b := by induction b with | or p q ih₁ ih₂ => simp [ih₁, ih₂] | not p ih => simp [ih] | _ => rfl syntax "`[BExpr|" term "]" : term macro_rules | `(`[BExpr| true]) => `(val true) | `(`[BExpr| false]) => `(val false) | `(`[BExpr| $x:ident]) => `(var $(quote x.getId.toString)) | `(`[BExpr| $p ∨ $q]) => `(or `[BExpr| $p] `[BExpr| $q]) | `(`[BExpr| ¬ $p]) => `(not `[BExpr| $p]) #check `[BExpr| ¬ p ∨ q] syntax entry := ident " ↦ " term:max syntax entry,* "⊢" term : term macro_rules | `( $[$xs ↦ $vs],* ⊢ $p) => let xs := xs.map fun x => quote x.getId.toString `(denote (List.toAssocList [$[($xs, $vs)],*]) `[BExpr| $p]) #check b ↦ true ⊢ b ∨ b #eval a ↦ false, b ↦ false ⊢ b ∨ a
703feb3310b4ca8d486097d8d9d9ee75a6d2d837
d1a52c3f208fa42c41df8278c3d280f075eb020c
/src/Lean/Compiler/IR/LiveVars.lean
1ef00ff1169469a8496750cc591d107b701d89fb
[ "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
6,963
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.Compiler.IR.Basic import Lean.Compiler.IR.FreeVars namespace Lean.IR /- Remark: in the paper "Counting Immutable Beans" the concepts of free and live variables coincide because the paper does *not* consider join points. For example, consider the function body `B` ``` let x := ctor_0; jmp block_1 x ``` in a context where we have the join point `block_1` defined as ``` block_1 (x : obj) : obj := let z := ctor_0 x y; ret z `` The variable `y` is live in the function body `B` since it occurs in `block_1` which is "invoked" by `B`. -/ namespace IsLive /- We use `State Context` instead of `ReaderT Context Id` because we remove non local joint points from `Context` whenever we visit them instead of maintaining a set of visited non local join points. Remark: we don't need to track local join points because we assume there is no variable or join point shadowing in our IR. -/ abbrev M := StateM LocalContext abbrev visitVar (w : Index) (x : VarId) : M Bool := pure (HasIndex.visitVar w x) abbrev visitJP (w : Index) (x : JoinPointId) : M Bool := pure (HasIndex.visitJP w x) abbrev visitArg (w : Index) (a : Arg) : M Bool := pure (HasIndex.visitArg w a) abbrev visitArgs (w : Index) (as : Array Arg) : M Bool := pure (HasIndex.visitArgs w as) abbrev visitExpr (w : Index) (e : Expr) : M Bool := pure (HasIndex.visitExpr w e) partial def visitFnBody (w : Index) : FnBody → M Bool | FnBody.vdecl x _ v b => visitExpr w v <||> visitFnBody w b | FnBody.jdecl j ys v b => visitFnBody w v <||> visitFnBody w b | FnBody.set x _ y b => visitVar w x <||> visitArg w y <||> visitFnBody w b | FnBody.uset x _ y b => visitVar w x <||> visitVar w y <||> visitFnBody w b | FnBody.sset x _ _ y _ b => visitVar w x <||> visitVar w y <||> visitFnBody w b | FnBody.setTag x _ b => visitVar w x <||> visitFnBody w b | FnBody.inc x _ _ _ b => visitVar w x <||> visitFnBody w b | FnBody.dec x _ _ _ b => visitVar w x <||> visitFnBody w b | FnBody.del x b => visitVar w x <||> visitFnBody w b | FnBody.mdata _ b => visitFnBody w b | FnBody.jmp j ys => visitArgs w ys <||> do let ctx ← get match ctx.getJPBody j with | some b => -- `j` is not a local join point since we assume we cannot shadow join point declarations. -- Instead of marking the join points that we have already been visited, we permanently remove `j` from the context. set (ctx.eraseJoinPointDecl j) *> visitFnBody w b | none => -- `j` must be a local join point. So do nothing since we have already visite its body. pure false | FnBody.ret x => visitArg w x | FnBody.case _ x _ alts => visitVar w x <||> alts.anyM (fun alt => visitFnBody w alt.body) | FnBody.unreachable => pure false end IsLive /- Return true if `x` is live in the function body `b` in the context `ctx`. Remark: the context only needs to contain all (free) join point declarations. Recall that we say that a join point `j` is free in `b` if `b` contains `FnBody.jmp j ys` and `j` is not local. -/ def FnBody.hasLiveVar (b : FnBody) (ctx : LocalContext) (x : VarId) : Bool := (IsLive.visitFnBody x.idx b).run' ctx abbrev LiveVarSet := VarIdSet abbrev JPLiveVarMap := Std.RBMap JoinPointId LiveVarSet (fun j₁ j₂ => compare j₁.idx j₂.idx) instance : Inhabited LiveVarSet where default := {} def mkLiveVarSet (x : VarId) : LiveVarSet := Std.RBTree.empty.insert x namespace LiveVars abbrev Collector := LiveVarSet → LiveVarSet @[inline] private def skip : Collector := fun s => s @[inline] private def collectVar (x : VarId) : Collector := fun s => s.insert x private def collectArg : Arg → Collector | Arg.var x => collectVar x | irrelevant => skip @[specialize] private def collectArray {α : Type} (as : Array α) (f : α → Collector) : Collector := fun s => as.foldl (fun s a => f a s) s private def collectArgs (as : Array Arg) : Collector := collectArray as collectArg private def accumulate (s' : LiveVarSet) : Collector := fun s => s'.fold (fun s x => s.insert x) s private def collectJP (m : JPLiveVarMap) (j : JoinPointId) : Collector := match m.find? j with | some xs => accumulate xs | none => skip -- unreachable for well-formed code private def bindVar (x : VarId) : Collector := fun s => s.erase x private def bindParams (ps : Array Param) : Collector := fun s => ps.foldl (fun s p => s.erase p.x) s def collectExpr : Expr → Collector | Expr.ctor _ ys => collectArgs ys | Expr.reset _ x => collectVar x | Expr.reuse x _ _ ys => collectVar x ∘ collectArgs ys | Expr.proj _ x => collectVar x | Expr.uproj _ x => collectVar x | Expr.sproj _ _ x => collectVar x | Expr.fap _ ys => collectArgs ys | Expr.pap _ ys => collectArgs ys | Expr.ap x ys => collectVar x ∘ collectArgs ys | Expr.box _ x => collectVar x | Expr.unbox x => collectVar x | Expr.lit v => skip | Expr.isShared x => collectVar x | Expr.isTaggedPtr x => collectVar x partial def collectFnBody : FnBody → JPLiveVarMap → Collector | FnBody.vdecl x _ v b, m => collectExpr v ∘ bindVar x ∘ collectFnBody b m | FnBody.jdecl j ys v b, m => let jLiveVars := (bindParams ys ∘ collectFnBody v m) {}; let m := m.insert j jLiveVars; collectFnBody b m | FnBody.set x _ y b, m => collectVar x ∘ collectArg y ∘ collectFnBody b m | FnBody.setTag x _ b, m => collectVar x ∘ collectFnBody b m | FnBody.uset x _ y b, m => collectVar x ∘ collectVar y ∘ collectFnBody b m | FnBody.sset x _ _ y _ b, m => collectVar x ∘ collectVar y ∘ collectFnBody b m | FnBody.inc x _ _ _ b, m => collectVar x ∘ collectFnBody b m | FnBody.dec x _ _ _ b, m => collectVar x ∘ collectFnBody b m | FnBody.del x b, m => collectVar x ∘ collectFnBody b m | FnBody.mdata _ b, m => collectFnBody b m | FnBody.ret x, m => collectArg x | FnBody.case _ x _ alts, m => collectVar x ∘ collectArray alts (fun alt => collectFnBody alt.body m) | FnBody.unreachable, m => skip | FnBody.jmp j xs, m => collectJP m j ∘ collectArgs xs def updateJPLiveVarMap (j : JoinPointId) (ys : Array Param) (v : FnBody) (m : JPLiveVarMap) : JPLiveVarMap := let jLiveVars := (bindParams ys ∘ collectFnBody v m) {}; m.insert j jLiveVars end LiveVars def updateLiveVars (e : Expr) (v : LiveVarSet) : LiveVarSet := LiveVars.collectExpr e v def collectLiveVars (b : FnBody) (m : JPLiveVarMap) (v : LiveVarSet := {}) : LiveVarSet := LiveVars.collectFnBody b m v export LiveVars (updateJPLiveVarMap) end Lean.IR
709614e1b451e14e5eb1f52b8c47e240537a3041
500f65bb93c499cd35c3254d894d762208cae042
/src/data/mv_polynomial.lean
d8b8fd44bf88fdfe4a570aa5189a30309509d48b
[ "Apache-2.0" ]
permissive
PatrickMassot/mathlib
c39dc0ff18bbde42f1c93a1642f6e429adad538c
45df75b3c9da159fe3192fa7f769dfbec0bd6bda
refs/heads/master
1,623,168,646,390
1,566,940,765,000
1,566,940,765,000
115,220,590
0
1
null
1,514,061,524,000
1,514,061,524,000
null
UTF-8
Lean
false
false
42,143
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 Multivariate Polynomial -/ import algebra.ring import data.finsupp data.polynomial data.equiv.algebra open set function finsupp lattice 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 α] := (σ →₀ ℕ) →₀ α namespace mv_polynomial variables {σ : Type*} {a a' a₁ a₂ : α} {e : ℕ} {n m : σ} {s : σ →₀ ℕ} variables [decidable_eq σ] [decidable_eq α] section comm_semiring variables [comm_semiring α] {p q : mv_polynomial σ α} instance : decidable_eq (mv_polynomial σ α) := finsupp.decidable_eq instance : has_zero (mv_polynomial σ α) := finsupp.has_zero instance : has_one (mv_polynomial σ α) := finsupp.has_one instance : has_add (mv_polynomial σ α) := finsupp.has_add instance : has_mul (mv_polynomial σ α) := finsupp.has_mul instance : comm_semiring (mv_polynomial σ α) := finsupp.comm_semiring /-- `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 (a : α) : mv_polynomial σ α := monomial 0 a /-- `X n` is the polynomial with value X_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, *] instance : is_semiring_hom (C : α → mv_polynomial σ α) := { map_zero := C_0, map_one := C_1, map_add := λ a a', C_add, map_mul := λ a a', C_mul } 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] } 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 monomial_eq : monomial s a = C a * (s.prod $ λn e, X n ^ e : mv_polynomial σ α) := begin apply @finsupp.induction σ ℕ _ _ _ _ s, { simp [C, prod_zero_index]; exact (mul_one _).symm }, { assume n e s hns he ih, simp [prod_add_index, prod_single_index, pow_zero, pow_add, (mul_assoc _ _ _).symm, ih.symm, monomial_add_single] } end @[recursor 7] 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 [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) 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 def tmp.coe : has_coe_to_fun (mv_polynomial σ α) := by delta mv_polynomial; apply_instance local attribute [instance] tmp.coe def coeff (m : σ →₀ ℕ) (p : mv_polynomial σ α) : α := p m lemma ext (p q : mv_polynomial σ α) : (∀ m, coeff m p = coeff m q) → p = q := ext lemma ext_iff (p q : mv_polynomial σ α) : (∀ m, coeff m p = coeff m q) ↔ p = q := ⟨ext p q, λ h m, by rw h⟩ @[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 := rfl 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 (s.sum f) = s.sum (λ x, coeff m (f x)) := (finset.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 := single_apply @[simp] lemma coeff_C (m) (a) : coeff m (C a : mv_polynomial σ α) = if 0 = m then a else 0 := 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, C, monomial], simp only [sum_single_index, zero_mul, single_zero, zero_add, sum_zero], 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] } end lemma coeff_mul (p q : mv_polynomial σ α) (n : σ →₀ ℕ) : coeff n (p * q) = finset.sum (antidiagonal n).support (λ x, 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}, exact 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, rw if_neg, exact 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, rw 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 [add_eq_zero_iff] at H, exact one_ne_zero H.2 } end end coeff 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)) @[simp] lemma eval₂_zero : (0 : mv_polynomial σ α).eval₂ f g = 0 := finsupp.sum_zero_index 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 _ _ } 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} @[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 @[simp] lemma eval₂_prod [decidable_eq γ] (s : finset γ) (p : γ → mv_polynomial σ α) : eval₂ f g (s.prod p) = s.prod (λ x, eval₂ f g $ p x) := (finset.prod_hom _).symm @[simp] lemma eval₂_sum [decidable_eq γ] (s : finset γ) (p : γ → mv_polynomial σ α) : eval₂ f g (s.sum p) = s.sum (λ x, eval₂ f g $ p x) := (finset.sum_hom _).symm attribute [to_additive] eval₂_prod lemma eval₂_assoc [decidable_eq γ] (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 @[simp] lemma eval_zero : (0 : mv_polynomial σ α).eval f = 0 := eval₂_zero _ _ @[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 _ _ instance eval.is_semiring_hom : is_semiring_hom (eval f) := eval₂.is_semiring_hom _ _ theorem eval_assoc {τ} [decidable_eq τ] (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 β] [decidable_eq β] variables (f : α → β) [is_semiring_hom f] /-- `map f p` maps a polynomial `p` across a ring hom `f` -/ def map : mv_polynomial σ α → mv_polynomial σ β := eval₂ (C ∘ f) X @[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 γ] [decidable_eq γ] (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₂ [decidable_eq γ] [decidable_eq δ] (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 σ β) := λ p q h, ext _ _ $ λ m, hf $ begin rw ← ext_iff at h, specialize h m, rw [coeff_map, coeff_map] at h, exact h end end map section degrees section comm_semiring 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.singleton_eq_singleton, 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.singleton_eq_singleton, 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 := 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, _), cases finset.mem_union.1 (finsupp.support_add hb), { exact le_sup_left_of_le (finset.le_sup h) }, { exact le_sup_right_of_le (finset.le_sup h) }, end lemma degrees_sum {ι : Type*} [decidable_eq ι] (s : finset ι) (f : ι → mv_polynomial σ α) : (s.sum f).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.singleton_eq_singleton, 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*} [decidable_eq ι] (s : finset ι) (f : ι → mv_polynomial σ α) : (s.prod f).degrees ≤ s.sum (λi, (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 ≤ add_monoid.smul 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 zero_ne_one.symm] 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 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.singleton_eq_singleton, finset.mem_singleton] at this, subst this, exact le_refl _ end lemma total_degree_zero : (0 : mv_polynomial σ α).total_degree = 0 := by rw [← C_0]; exact total_degree_C (0 : α) lemma total_degree_one : (1 : mv_polynomial σ α).total_degree = 0 := total_degree_C (1 : α) 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 rcases finset.mem_union.1 this, { exact le_max_left_of_le (finset.le_sup h) }, { exact le_max_right_of_le (finset.le_sup h) } 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 _ := finsupp.support_mul a b hn, begin simp only [finset.mem_bind, finset.mem_singleton, finset.singleton_eq_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_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 ≤ s.sum (λi, (f i).total_degree) := begin refine le_trans (total_degree_multiset_prod _) _, rw [multiset.map_map], refl end end total_degree end comm_semiring section comm_ring variable [comm_ring α] variables {p q : mv_polynomial σ α} instance : ring (mv_polynomial σ α) := finsupp.ring instance : comm_ring (mv_polynomial σ α) := finsupp.comm_ring instance : has_scalar α (mv_polynomial σ α) := finsupp.has_scalar instance : module α (mv_polynomial σ α) := finsupp.module _ α instance C.is_ring_hom : is_ring_hom (C : α → mv_polynomial σ α) := by apply is_ring_hom.of_semiring variables (σ a a') 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_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 [finsupp.mul_def, finsupp.smul_single, mv_polynomial.C, mv_polynomial.monomial], rw [finsupp.sum_single_index, finsupp.sum_single_index, zero_add, smul_eq_mul], { 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 [comm_ring α] (p : mv_polynomial σ α) : (- p).degrees = p.degrees := by rw [degrees, finsupp.support_neg]; refl lemma degrees_sub [comm_ring α] (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 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 : β) := congr_fun (int.eq_cast' (f ∘ C)) 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} [decidable_eq α] (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, int.eq_cast' c], refl }) (λ 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 }) end eval₂ section eval variables (f : σ → α) instance eval.is_ring_hom : is_ring_hom (eval f) := eval₂.is_ring_hom _ _ 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 [decidable_eq β] [comm_ring β] variables (f : α → β) [is_ring_hom f] instance map.is_ring_hom : is_ring_hom (map f : mv_polynomial σ α → mv_polynomial σ β) := eval₂.is_ring_hom _ _ 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 end comm_ring section rename variables {α} [comm_semiring α] [decidable_eq α] [decidable_eq β] [decidable_eq γ] [decidable_eq δ] 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_sub {α} [comm_ring α] [decidable_eq α] (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 injective_rename (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.injective_map_domain (finsupp.injective_map_domain 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, rcases finset.mem_image.1 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 end rename lemma eval₂_cast_comp {β : Type u} {γ : Type v} [decidable_eq β] [decidable_eq γ] (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 α] [decidable_eq α] [decidable_eq β] [decidable_eq γ] (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_ring α] variables [decidable_eq β] [decidable_eq γ] [decidable_eq δ] set_option class.instance_max_depth 40 def pempty_ring_equiv : mv_polynomial pempty α ≃r α := { 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 _ _ _, hom := eval₂.is_ring_hom _ _ } def punit_ring_equiv : mv_polynomial punit α ≃r 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]), hom := eval₂.is_ring_hom _ _ } def ring_equiv_of_equiv (e : β ≃ γ) : mv_polynomial β α ≃r 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, hom := rename.is_ring_hom e } def ring_equiv_congr [comm_ring γ] (e : α ≃r γ) : mv_polynomial β α ≃r mv_polynomial β γ := { to_fun := map e.to_equiv, inv_fun := map e.symm.to_equiv, left_inv := assume p, have (e.symm.to_equiv ∘ e.to_equiv) = id, { ext a, exact e.to_equiv.symm_apply_apply a }, by simp only [map_map, this, map_id], right_inv := assume p, have (e.to_equiv ∘ e.symm.to_equiv) = id, { ext a, exact e.to_equiv.apply_symm_apply a }, by simp only [map_map, this, map_id], hom := map.is_ring_hom e.to_fun } section variables (β γ δ) instance ring_on_sum : ring (mv_polynomial (β ⊕ γ) α) := by apply_instance instance ring_on_iter : ring (mv_polynomial β (mv_polynomial γ α)) := by apply_instance 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 mv_polynomial.is_semiring_hom _ _ C mv_polynomial.is_semiring_hom 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) def iter_to_sum : mv_polynomial β (mv_polynomial γ α) → mv_polynomial (β ⊕ γ) α := eval₂ (eval₂ C (X ∘ sum.inr)) (X ∘ sum.inl) section instance is_semiring_hom_iter_to_sum : is_semiring_hom (iter_to_sum α β γ) := eval₂.is_semiring_hom _ _ end 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 _ _ _) def mv_polynomial_equiv_mv_polynomial [comm_ring δ] (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 β α ≃r 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, hom := is_ring_hom.of_semiring f } def sum_ring_equiv : mv_polynomial (β ⊕ γ) α ≃r 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 @mv_polynomial.is_semiring_hom }, { apply mv_polynomial.is_semiring_hom_iter_to_sum α β γ }, { apply mv_polynomial.is_semiring_hom_sum_to_iter α β γ } }, { apply mv_polynomial.is_semiring_hom }, { 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 instance option_ring : ring (mv_polynomial (option β) α) := mv_polynomial.ring instance polynomial_ring : ring (polynomial (mv_polynomial β α)) := @comm_ring.to_ring _ polynomial.comm_ring instance polynomial_ring2 : ring (mv_polynomial β (polynomial α)) := by apply_instance def option_equiv_left : mv_polynomial (option β) α ≃r polynomial (mv_polynomial β α) := (ring_equiv_of_equiv α $ (equiv.option_equiv_sum_punit β).trans (equiv.sum_comm _ _)).trans $ (sum_ring_equiv α _ _).trans $ punit_ring_equiv _ def option_equiv_right : mv_polynomial (option β) α ≃r 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 α) end end equiv end mv_polynomial
85fdbc0744675c7017efa903506b16419ded11c1
9be442d9ec2fcf442516ed6e9e1660aa9071b7bd
/tests/lean/run/autoboundIssues.lean
1e88b98747dcb62ab44b0a4e7de0722808f2ac27
[ "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
246
lean
example : n.succ = 1 → n = 0 := by intros h; injection h; assumption example (h : n.succ = 1) : n = 0 := by injection h; assumption opaque T : Type opaque T.Pred : T → T → Prop example {ρ} (hρ : ρ.Pred σ) : T.Pred ρ ρ := sorry
5631bb7fe0cecaed1ee4f3d8706b69bf9625edaf
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/field_theory/fixed.lean
38726f7a0e04ac91255a922066bafb2e2913993a
[ "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
14,456
lean
/- Copyright (c) 2020 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau -/ import algebra.polynomial.group_ring_action import field_theory.normal import field_theory.separable import field_theory.tower /-! # Fixed field under a group action. This is the basis of the Fundamental Theorem of Galois Theory. Given a (finite) group `G` that acts on a field `F`, we define `fixed_points G F`, the subfield consisting of elements of `F` fixed_points by every element of `G`. This subfield is then normal and separable, and in addition (TODO) if `G` acts faithfully on `F` then `finrank (fixed_points G F) F = fintype.card G`. ## Main Definitions - `fixed_points G F`, the subfield consisting of elements of `F` fixed_points by every element of `G`, where `G` is a group that acts on `F`. -/ noncomputable theory open_locale classical big_operators open mul_action finset finite_dimensional universes u v w variables {M : Type u} [monoid M] variables (G : Type u) [group G] variables (F : Type v) [field F] [mul_semiring_action M F] [mul_semiring_action G F] (m : M) /-- The subfield of F fixed by the field endomorphism `m`. -/ def fixed_by.subfield : subfield F := { carrier := fixed_by M F m, zero_mem' := smul_zero m, add_mem' := λ x y hx hy, (smul_add m x y).trans $ congr_arg2 _ hx hy, neg_mem' := λ x hx, (smul_neg m x).trans $ congr_arg _ hx, one_mem' := smul_one m, mul_mem' := λ x y hx hy, (smul_mul' m x y).trans $ congr_arg2 _ hx hy, inv_mem' := λ x hx, (smul_inv'' m x).trans $ congr_arg _ hx } section invariant_subfields variables (M) {F} /-- A typeclass for subrings invariant under a `mul_semiring_action`. -/ class is_invariant_subfield (S : subfield F) : Prop := (smul_mem : ∀ (m : M) {x : F}, x ∈ S → m • x ∈ S) variable (S : subfield F) instance is_invariant_subfield.to_mul_semiring_action [is_invariant_subfield M S] : mul_semiring_action M S := { smul := λ m x, ⟨m • x, is_invariant_subfield.smul_mem m x.2⟩, one_smul := λ s, subtype.eq $ one_smul M s, mul_smul := λ m₁ m₂ s, subtype.eq $ mul_smul m₁ m₂ s, smul_add := λ m s₁ s₂, subtype.eq $ smul_add m s₁ s₂, smul_zero := λ m, subtype.eq $ smul_zero m, smul_one := λ m, subtype.eq $ smul_one m, smul_mul := λ m s₁ s₂, subtype.eq $ smul_mul' m s₁ s₂ } instance [is_invariant_subfield M S] : is_invariant_subring M (S.to_subring) := { smul_mem := is_invariant_subfield.smul_mem } end invariant_subfields namespace fixed_points variable (M) -- we use `subfield.copy` so that the underlying set is `fixed_points M F` /-- The subfield of fixed points by a monoid action. -/ def subfield : subfield F := subfield.copy (⨅ (m : M), fixed_by.subfield F m) (fixed_points M F) (by { ext z, simp [fixed_points, fixed_by.subfield, infi, subfield.mem_Inf] }) instance : is_invariant_subfield M (fixed_points.subfield M F) := { smul_mem := λ g x hx g', by rw [hx, hx] } instance : smul_comm_class M (fixed_points.subfield M F) F := { smul_comm := λ m f f', show m • (↑f * f') = f * (m • f'), by rw [smul_mul', f.prop m] } instance smul_comm_class' : smul_comm_class (fixed_points.subfield M F) M F := smul_comm_class.symm _ _ _ @[simp] theorem smul (m : M) (x : fixed_points.subfield M F) : m • x = x := subtype.eq $ x.2 m -- Why is this so slow? @[simp] theorem smul_polynomial (m : M) (p : polynomial (fixed_points.subfield M F)) : m • p = p := polynomial.induction_on p (λ x, by rw [polynomial.smul_C, smul]) (λ p q ihp ihq, by rw [smul_add, ihp, ihq]) (λ n x ih, by rw [smul_mul', polynomial.smul_C, smul, smul_pow', polynomial.smul_X]) instance : algebra (fixed_points.subfield M F) F := algebra.of_subring (fixed_points.subfield M F).to_subring theorem coe_algebra_map : algebra_map (fixed_points.subfield M F) F = subfield.subtype (fixed_points.subfield M F) := rfl lemma linear_independent_smul_of_linear_independent {s : finset F} : linear_independent (fixed_points.subfield G F) (λ i : (s : set F), (i : F)) → linear_independent F (λ i : (s : set F), mul_action.to_fun G F i) := begin haveI : is_empty ((∅ : finset F) : set F) := ⟨subtype.prop⟩, refine finset.induction_on s (λ _, linear_independent_empty_type) (λ a s has ih hs, _), rw coe_insert at hs ⊢, rw linear_independent_insert (mt mem_coe.1 has) at hs, rw linear_independent_insert' (mt mem_coe.1 has), refine ⟨ih hs.1, λ ha, _⟩, rw finsupp.mem_span_image_iff_total at ha, rcases ha with ⟨l, hl, hla⟩, rw [finsupp.total_apply_of_mem_supported F hl] at hla, suffices : ∀ i ∈ s, l i ∈ fixed_points.subfield G F, { replace hla := (sum_apply _ _ (λ i, l i • to_fun G F i)).symm.trans (congr_fun hla 1), simp_rw [pi.smul_apply, to_fun_apply, one_smul] at hla, refine hs.2 (hla ▸ submodule.sum_mem _ (λ c hcs, _)), change (⟨l c, this c hcs⟩ : fixed_points.subfield G F) • c ∈ _, exact submodule.smul_mem _ _ (submodule.subset_span $ mem_coe.2 hcs) }, intros i his g, refine eq_of_sub_eq_zero (linear_independent_iff'.1 (ih hs.1) s.attach (λ i, g • l i - l i) _ ⟨i, his⟩ (mem_attach _ _) : _), refine (@sum_attach _ _ s _ (λ i, (g • l i - l i) • mul_action.to_fun G F i)).trans _, ext g', dsimp only, conv_lhs { rw sum_apply, congr, skip, funext, rw [pi.smul_apply, sub_smul, smul_eq_mul] }, rw [sum_sub_distrib, pi.zero_apply, sub_eq_zero], conv_lhs { congr, skip, funext, rw [to_fun_apply, ← mul_inv_cancel_left g g', mul_smul, ← smul_mul', ← to_fun_apply _ x] }, show ∑ x in s, g • (λ y, l y • mul_action.to_fun G F y) x (g⁻¹ * g') = ∑ x in s, (λ y, l y • mul_action.to_fun G F y) x g', rw [← smul_sum, ← sum_apply _ _ (λ y, l y • to_fun G F y), ← sum_apply _ _ (λ y, l y • to_fun G F y)], dsimp only, rw [hla, to_fun_apply, to_fun_apply, smul_smul, mul_inv_cancel_left] end variables [fintype G] (x : F) /-- `minpoly G F x` is the minimal polynomial of `(x : F)` over `fixed_points G F`. -/ def minpoly : polynomial (fixed_points.subfield G F) := (prod_X_sub_smul G F x).to_subring (fixed_points.subfield G F).to_subring $ λ c hc g, let ⟨n, hc0, hn⟩ := polynomial.mem_frange_iff.1 hc in hn.symm ▸ prod_X_sub_smul.coeff G F x g n namespace minpoly theorem monic : (minpoly G F x).monic := by { simp only [minpoly, polynomial.monic_to_subring], exact prod_X_sub_smul.monic G F x } theorem eval₂ : polynomial.eval₂ (subring.subtype $ (fixed_points.subfield G F).to_subring) x (minpoly G F x) = 0 := begin rw [← prod_X_sub_smul.eval G F x, polynomial.eval₂_eq_eval_map], simp only [minpoly, polynomial.map_to_subring], end theorem eval₂' : polynomial.eval₂ (subfield.subtype $ (fixed_points.subfield G F)) x (minpoly G F x) = 0 := eval₂ G F x theorem ne_one : minpoly G F x ≠ (1 : polynomial (fixed_points.subfield G F)) := λ H, have _ := eval₂ G F x, (one_ne_zero : (1 : F) ≠ 0) $ by rwa [H, polynomial.eval₂_one] at this theorem of_eval₂ (f : polynomial (fixed_points.subfield G F)) (hf : polynomial.eval₂ (subfield.subtype $ fixed_points.subfield G F) x f = 0) : minpoly G F x ∣ f := begin erw [← polynomial.map_dvd_map' (subfield.subtype $ fixed_points.subfield G F), minpoly, polynomial.map_to_subring _ (subfield G F).to_subring, prod_X_sub_smul], refine fintype.prod_dvd_of_coprime (polynomial.pairwise_coprime_X_sub $ mul_action.injective_of_quotient_stabilizer G x) (λ y, quotient_group.induction_on y $ λ g, _), rw [polynomial.dvd_iff_is_root, polynomial.is_root.def, mul_action.of_quotient_stabilizer_mk, polynomial.eval_smul', ← subfield.to_subring.subtype_eq_subtype, ← is_invariant_subring.coe_subtype_hom' G (fixed_points.subfield G F).to_subring, ← mul_semiring_action_hom.coe_polynomial, ← mul_semiring_action_hom.map_smul, smul_polynomial, mul_semiring_action_hom.coe_polynomial, is_invariant_subring.coe_subtype_hom', polynomial.eval_map, subfield.to_subring.subtype_eq_subtype, hf, smul_zero] end /- Why is this so slow? -/ theorem irreducible_aux (f g : polynomial (fixed_points.subfield G F)) (hf : f.monic) (hg : g.monic) (hfg : f * g = minpoly G F x) : f = 1 ∨ g = 1 := begin have hf2 : f ∣ minpoly G F x, { rw ← hfg, exact dvd_mul_right _ _ }, have hg2 : g ∣ minpoly G F x, { rw ← hfg, exact dvd_mul_left _ _ }, have := eval₂ G F x, rw [← hfg, polynomial.eval₂_mul, mul_eq_zero] at this, cases this, { right, have hf3 : f = minpoly G F x, { exact polynomial.eq_of_monic_of_associated hf (monic G F x) (associated_of_dvd_dvd hf2 $ @of_eval₂ G _ F _ _ _ x f this) }, rwa [← mul_one (minpoly G F x), hf3, mul_right_inj' (monic G F x).ne_zero] at hfg }, { left, have hg3 : g = minpoly G F x, { exact polynomial.eq_of_monic_of_associated hg (monic G F x) (associated_of_dvd_dvd hg2 $ @of_eval₂ G _ F _ _ _ x g this) }, rwa [← one_mul (minpoly G F x), hg3, mul_left_inj' (monic G F x).ne_zero] at hfg } end theorem irreducible : irreducible (minpoly G F x) := (polynomial.irreducible_of_monic (monic G F x) (ne_one G F x)).2 (irreducible_aux G F x) end minpoly theorem is_integral : is_integral (fixed_points.subfield G F) x := ⟨minpoly G F x, minpoly.monic G F x, minpoly.eval₂ G F x⟩ theorem minpoly_eq_minpoly : minpoly G F x = _root_.minpoly (fixed_points.subfield G F) x := minpoly.eq_of_irreducible_of_monic (minpoly.irreducible G F x) (minpoly.eval₂ G F x) (minpoly.monic G F x) instance normal : normal (fixed_points.subfield G F) F := ⟨λ x, is_integral G F x, λ x, (polynomial.splits_id_iff_splits _).1 $ by { rw [← minpoly_eq_minpoly, minpoly, coe_algebra_map, ← subfield.to_subring.subtype_eq_subtype, polynomial.map_to_subring _ (fixed_points.subfield G F).to_subring, prod_X_sub_smul], exact polynomial.splits_prod _ (λ _ _, polynomial.splits_X_sub_C _) }⟩ instance separable : is_separable (fixed_points.subfield G F) F := ⟨λ x, is_integral G F x, λ x, by { -- this was a plain rw when we were using unbundled subrings erw [← minpoly_eq_minpoly, ← polynomial.separable_map (fixed_points.subfield G F).subtype, minpoly, polynomial.map_to_subring _ ((subfield G F).to_subring) ], exact polynomial.separable_prod_X_sub_C_iff.2 (injective_of_quotient_stabilizer G x) }⟩ lemma dim_le_card : module.rank (fixed_points.subfield G F) F ≤ fintype.card G := dim_le $ λ s hs, by simpa only [dim_fun', cardinal.mk_finset, finset.coe_sort_coe, cardinal.lift_nat_cast, cardinal.nat_cast_le] using cardinal_lift_le_dim_of_linear_independent' (linear_independent_smul_of_linear_independent G F hs) instance : finite_dimensional (fixed_points.subfield G F) F := is_noetherian.iff_fg.1 $ is_noetherian.iff_dim_lt_omega.2 $ lt_of_le_of_lt (dim_le_card G F) (cardinal.nat_lt_omega _) lemma finrank_le_card : finrank (fixed_points.subfield G F) F ≤ fintype.card G := begin rw [← cardinal.nat_cast_le, finrank_eq_dim], apply dim_le_card, end end fixed_points lemma linear_independent_to_linear_map (R : Type u) (A : Type v) (B : Type w) [comm_semiring R] [ring A] [algebra R A] [comm_ring B] [is_domain B] [algebra R B] : linear_independent B (alg_hom.to_linear_map : (A →ₐ[R] B) → (A →ₗ[R] B)) := have linear_independent B (linear_map.lto_fun R A B ∘ alg_hom.to_linear_map), from ((linear_independent_monoid_hom A B).comp (coe : (A →ₐ[R] B) → (A →* B)) (λ f g hfg, alg_hom.ext $ monoid_hom.ext_iff.1 hfg) : _), this.of_comp _ lemma cardinal_mk_alg_hom (K : Type u) (V : Type v) (W : Type w) [field K] [field V] [algebra K V] [finite_dimensional K V] [field W] [algebra K W] [finite_dimensional K W] : cardinal.mk (V →ₐ[K] W) ≤ finrank W (V →ₗ[K] W) := cardinal_mk_le_finrank_of_linear_independent $ linear_independent_to_linear_map K V W noncomputable instance alg_hom.fintype (K : Type u) (V : Type v) (W : Type w) [field K] [field V] [algebra K V] [finite_dimensional K V] [field W] [algebra K W] [finite_dimensional K W] : fintype (V →ₐ[K] W) := classical.choice $ cardinal.lt_omega_iff_fintype.1 $ lt_of_le_of_lt (cardinal_mk_alg_hom K V W) (cardinal.nat_lt_omega _) noncomputable instance alg_equiv.fintype (K : Type u) (V : Type v) [field K] [field V] [algebra K V] [finite_dimensional K V] : fintype (V ≃ₐ[K] V) := fintype.of_equiv (V →ₐ[K] V) (alg_equiv_equiv_alg_hom K V).symm lemma finrank_alg_hom (K : Type u) (V : Type v) [field K] [field V] [algebra K V] [finite_dimensional K V] : fintype.card (V →ₐ[K] V) ≤ finrank V (V →ₗ[K] V) := fintype_card_le_finrank_of_linear_independent $ linear_independent_to_linear_map K V V namespace fixed_points theorem finrank_eq_card (G : Type u) (F : Type v) [group G] [field F] [fintype G] [mul_semiring_action G F] [has_faithful_scalar G F] : finrank (fixed_points.subfield G F) F = fintype.card G := le_antisymm (fixed_points.finrank_le_card G F) $ calc fintype.card G ≤ fintype.card (F →ₐ[fixed_points.subfield G F] F) : fintype.card_le_of_injective _ (mul_semiring_action.to_alg_hom_injective _ F) ... ≤ finrank F (F →ₗ[fixed_points.subfield G F] F) : finrank_alg_hom (fixed_points G F) F ... = finrank (fixed_points.subfield G F) F : finrank_linear_map' _ _ _ /-- `mul_semiring_action.to_alg_hom` is bijective. -/ theorem to_alg_hom_bijective (G : Type u) (F : Type v) [group G] [field F] [fintype G] [mul_semiring_action G F] [has_faithful_scalar G F] : function.bijective (mul_semiring_action.to_alg_hom _ _ : G → F →ₐ[subfield G F] F) := begin rw fintype.bijective_iff_injective_and_card, split, { exact mul_semiring_action.to_alg_hom_injective _ F }, { apply le_antisymm, { exact fintype.card_le_of_injective _ (mul_semiring_action.to_alg_hom_injective _ F) }, { rw ← finrank_eq_card G F, exact has_le.le.trans_eq (finrank_alg_hom _ F) (finrank_linear_map' _ _ _) } }, end /-- Bijection between G and algebra homomorphisms that fix the fixed points -/ def to_alg_hom_equiv (G : Type u) (F : Type v) [group G] [field F] [fintype G] [mul_semiring_action G F] [has_faithful_scalar G F] : G ≃ (F →ₐ[fixed_points.subfield G F] F) := equiv.of_bijective _ (to_alg_hom_bijective G F) end fixed_points
b1699a5fdde4b961717e440219d5978a1e56fb9e
a047a4718edfa935d17231e9e6ecec8c7b701e05
/src/category_theory/limits/shapes/binary_products.lean
1fe884d892a7dcb72f5208822e5d949b5181fc82
[ "Apache-2.0" ]
permissive
utensil-contrib/mathlib
bae0c9fafe5e2bdb516efc89d6f8c1502ecc9767
b91909e77e219098a2f8cc031f89d595fe274bd2
refs/heads/master
1,668,048,976,965
1,592,442,701,000
1,592,442,701,000
273,197,855
0
0
null
1,592,472,812,000
1,592,472,811,000
null
UTF-8
Lean
false
false
24,302
lean
/- Copyright (c) 2019 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison, Bhavik Mehta -/ import category_theory.limits.shapes.terminal /-! # Binary (co)products We define a category `walking_pair`, which is the index category for a binary (co)product diagram. A convenience method `pair X Y` constructs the functor from the walking pair, hitting the given objects. We define `prod X Y` and `coprod X Y` as limits and colimits of such functors. Typeclasses `has_binary_products` and `has_binary_coproducts` assert the existence of (co)limits shaped as walking pairs. We include lemmas for simplifying equations involving projections and coprojections, and define braiding and associating isomorphisms, and the product comparison morphism. -/ universes v u u₂ open category_theory namespace category_theory.limits /-- The type of objects for the diagram indexing a binary (co)product. -/ @[derive decidable_eq, derive inhabited] inductive walking_pair : Type v | left | right open walking_pair instance fintype_walking_pair : fintype walking_pair := { elems := {left, right}, complete := λ x, by { cases x; simp } } variables {C : Type u} [category.{v} C] /-- The diagram on the walking pair, sending the two points to `X` and `Y`. -/ def pair (X Y : C) : discrete walking_pair ⥤ C := functor.of_function (λ j, walking_pair.cases_on j X Y) @[simp] lemma pair_obj_left (X Y : C) : (pair X Y).obj left = X := rfl @[simp] lemma pair_obj_right (X Y : C) : (pair X Y).obj right = Y := rfl section variables {F G : discrete walking_pair.{v} ⥤ C} (f : F.obj left ⟶ G.obj left) (g : F.obj right ⟶ G.obj right) /-- The natural transformation between two functors out of the walking pair, specified by its components. -/ def map_pair : F ⟶ G := { app := λ j, match j with | left := f | right := g end } @[simp] lemma map_pair_left : (map_pair f g).app left = f := rfl @[simp] lemma map_pair_right : (map_pair f g).app right = g := rfl /-- The natural isomorphism between two functors out of the walking pair, specified by its components. -/ @[simps] def map_pair_iso (f : F.obj left ≅ G.obj left) (g : F.obj right ≅ G.obj right) : F ≅ G := { hom := map_pair f.hom g.hom, inv := map_pair f.inv g.inv, hom_inv_id' := begin ext ⟨⟩; { dsimp, simp, } end, inv_hom_id' := begin ext ⟨⟩; { dsimp, simp, } end } end section variables {D : Type u} [category.{v} D] /-- The natural isomorphism between `pair X Y ⋙ F` and `pair (F.obj X) (F.obj Y)`. -/ def pair_comp (X Y : C) (F : C ⥤ D) : pair X Y ⋙ F ≅ pair (F.obj X) (F.obj Y) := map_pair_iso (eq_to_iso rfl) (eq_to_iso rfl) end /-- Every functor out of the walking pair is naturally isomorphic (actually, equal) to a `pair` -/ def diagram_iso_pair (F : discrete walking_pair ⥤ C) : F ≅ pair (F.obj walking_pair.left) (F.obj walking_pair.right) := map_pair_iso (eq_to_iso rfl) (eq_to_iso rfl) /-- A binary fan is just a cone on a diagram indexing a product. -/ abbreviation binary_fan (X Y : C) := cone (pair X Y) /-- The first projection of a binary fan. -/ abbreviation binary_fan.fst {X Y : C} (s : binary_fan X Y) := s.π.app walking_pair.left /-- The second projection of a binary fan. -/ abbreviation binary_fan.snd {X Y : C} (s : binary_fan X Y) := s.π.app walking_pair.right lemma binary_fan.is_limit.hom_ext {W X Y : C} {s : binary_fan X Y} (h : is_limit s) {f g : W ⟶ s.X} (h₁ : f ≫ s.fst = g ≫ s.fst) (h₂ : f ≫ s.snd = g ≫ s.snd) : f = g := h.hom_ext $ λ j, walking_pair.cases_on j h₁ h₂ /-- A binary cofan is just a cocone on a diagram indexing a coproduct. -/ abbreviation binary_cofan (X Y : C) := cocone (pair X Y) /-- The first inclusion of a binary cofan. -/ abbreviation binary_cofan.inl {X Y : C} (s : binary_cofan X Y) := s.ι.app walking_pair.left /-- The second inclusion of a binary cofan. -/ abbreviation binary_cofan.inr {X Y : C} (s : binary_cofan X Y) := s.ι.app walking_pair.right lemma binary_cofan.is_colimit.hom_ext {W X Y : C} {s : binary_cofan X Y} (h : is_colimit s) {f g : s.X ⟶ W} (h₁ : s.inl ≫ f = s.inl ≫ g) (h₂ : s.inr ≫ f = s.inr ≫ g) : f = g := h.hom_ext $ λ j, walking_pair.cases_on j h₁ h₂ variables {X Y : C} /-- A binary fan with vertex `P` consists of the two projections `π₁ : P ⟶ X` and `π₂ : P ⟶ Y`. -/ def binary_fan.mk {P : C} (π₁ : P ⟶ X) (π₂ : P ⟶ Y) : binary_fan X Y := { X := P, π := { app := λ j, walking_pair.cases_on j π₁ π₂ }} /-- A binary cofan with vertex `P` consists of the two inclusions `ι₁ : X ⟶ P` and `ι₂ : Y ⟶ P`. -/ def binary_cofan.mk {P : C} (ι₁ : X ⟶ P) (ι₂ : Y ⟶ P) : binary_cofan X Y := { X := P, ι := { app := λ j, walking_pair.cases_on j ι₁ ι₂ }} @[simp] lemma binary_fan.mk_π_app_left {P : C} (π₁ : P ⟶ X) (π₂ : P ⟶ Y) : (binary_fan.mk π₁ π₂).π.app walking_pair.left = π₁ := rfl @[simp] lemma binary_fan.mk_π_app_right {P : C} (π₁ : P ⟶ X) (π₂ : P ⟶ Y) : (binary_fan.mk π₁ π₂).π.app walking_pair.right = π₂ := rfl @[simp] lemma binary_cofan.mk_ι_app_left {P : C} (ι₁ : X ⟶ P) (ι₂ : Y ⟶ P) : (binary_cofan.mk ι₁ ι₂).ι.app walking_pair.left = ι₁ := rfl @[simp] lemma binary_cofan.mk_ι_app_right {P : C} (ι₁ : X ⟶ P) (ι₂ : Y ⟶ P) : (binary_cofan.mk ι₁ ι₂).ι.app walking_pair.right = ι₂ := rfl /-- If `s` is a limit binary fan over `X` and `Y`, then every pair of morphisms `f : W ⟶ X` and `g : W ⟶ Y` induces a morphism `l : W ⟶ s.X` satisfying `l ≫ s.fst = f` and `l ≫ s.snd = g`. -/ def binary_fan.is_limit.lift' {W X Y : C} {s : binary_fan X Y} (h : is_limit s) (f : W ⟶ X) (g : W ⟶ Y) : {l : W ⟶ s.X // l ≫ s.fst = f ∧ l ≫ s.snd = g} := ⟨h.lift $ binary_fan.mk f g, h.fac _ _, h.fac _ _⟩ /-- If `s` is a colimit binary cofan over `X` and `Y`,, then every pair of morphisms `f : X ⟶ W` and `g : Y ⟶ W` induces a morphism `l : s.X ⟶ W` satisfying `s.inl ≫ l = f` and `s.inr ≫ l = g`. -/ def binary_cofan.is_colimit.desc' {W X Y : C} {s : binary_cofan X Y} (h : is_colimit s) (f : X ⟶ W) (g : Y ⟶ W) : {l : s.X ⟶ W // s.inl ≫ l = f ∧ s.inr ≫ l = g} := ⟨h.desc $ binary_cofan.mk f g, h.fac _ _, h.fac _ _⟩ /-- If we have chosen a product of `X` and `Y`, we can access it using `prod X Y` or `X ⨯ Y`. -/ abbreviation prod (X Y : C) [has_limit (pair X Y)] := limit (pair X Y) /-- If we have chosen a coproduct of `X` and `Y`, we can access it using `coprod X Y ` or `X ⨿ Y`. -/ abbreviation coprod (X Y : C) [has_colimit (pair X Y)] := colimit (pair X Y) notation X ` ⨯ `:20 Y:20 := prod X Y notation X ` ⨿ `:20 Y:20 := coprod X Y /-- The projection map to the first component of the product. -/ abbreviation prod.fst {X Y : C} [has_limit (pair X Y)] : X ⨯ Y ⟶ X := limit.π (pair X Y) walking_pair.left /-- The projecton map to the second component of the product. -/ abbreviation prod.snd {X Y : C} [has_limit (pair X Y)] : X ⨯ Y ⟶ Y := limit.π (pair X Y) walking_pair.right /-- The inclusion map from the first component of the coproduct. -/ abbreviation coprod.inl {X Y : C} [has_colimit (pair X Y)] : X ⟶ X ⨿ Y := colimit.ι (pair X Y) walking_pair.left /-- The inclusion map from the second component of the coproduct. -/ abbreviation coprod.inr {X Y : C} [has_colimit (pair X Y)] : Y ⟶ X ⨿ Y := colimit.ι (pair X Y) walking_pair.right @[ext] lemma prod.hom_ext {W X Y : C} [has_limit (pair X Y)] {f g : W ⟶ X ⨯ Y} (h₁ : f ≫ prod.fst = g ≫ prod.fst) (h₂ : f ≫ prod.snd = g ≫ prod.snd) : f = g := binary_fan.is_limit.hom_ext (limit.is_limit _) h₁ h₂ @[ext] lemma coprod.hom_ext {W X Y : C} [has_colimit (pair X Y)] {f g : X ⨿ Y ⟶ W} (h₁ : coprod.inl ≫ f = coprod.inl ≫ g) (h₂ : coprod.inr ≫ f = coprod.inr ≫ g) : f = g := binary_cofan.is_colimit.hom_ext (colimit.is_colimit _) h₁ h₂ /-- If the product of `X` and `Y` exists, then every pair of morphisms `f : W ⟶ X` and `g : W ⟶ Y` induces a morphism `prod.lift f g : W ⟶ X ⨯ Y`. -/ abbreviation prod.lift {W X Y : C} [has_limit (pair X Y)] (f : W ⟶ X) (g : W ⟶ Y) : W ⟶ X ⨯ Y := limit.lift _ (binary_fan.mk f g) /-- If the coproduct of `X` and `Y` exists, then every pair of morphisms `f : X ⟶ W` and `g : Y ⟶ W` induces a morphism `coprod.desc f g : X ⨿ Y ⟶ W`. -/ abbreviation coprod.desc {W X Y : C} [has_colimit (pair X Y)] (f : X ⟶ W) (g : Y ⟶ W) : X ⨿ Y ⟶ W := colimit.desc _ (binary_cofan.mk f g) @[simp, reassoc] lemma prod.lift_fst {W X Y : C} [has_limit (pair X Y)] (f : W ⟶ X) (g : W ⟶ Y) : prod.lift f g ≫ prod.fst = f := limit.lift_π _ _ @[simp, reassoc] lemma prod.lift_snd {W X Y : C} [has_limit (pair X Y)] (f : W ⟶ X) (g : W ⟶ Y) : prod.lift f g ≫ prod.snd = g := limit.lift_π _ _ /- The redundant simp lemma linter says that simp can prove the reassoc version of this lemma. -/ @[reassoc, simp] lemma prod.lift_comp_comp {V W X Y : C} [has_limit (pair X Y)] (f : V ⟶ W) (g : W ⟶ X) (h : W ⟶ Y) : prod.lift (f ≫ g) (f ≫ h) = f ≫ prod.lift g h := by tidy @[simp, reassoc] lemma coprod.inl_desc {W X Y : C} [has_colimit (pair X Y)] (f : X ⟶ W) (g : Y ⟶ W) : coprod.inl ≫ coprod.desc f g = f := colimit.ι_desc _ _ @[simp, reassoc] lemma coprod.inr_desc {W X Y : C} [has_colimit (pair X Y)] (f : X ⟶ W) (g : Y ⟶ W) : coprod.inr ≫ coprod.desc f g = g := colimit.ι_desc _ _ /- The redundant simp lemma linter says that simp can prove the reassoc version of this lemma. -/ @[reassoc, simp] lemma coprod.desc_comp_comp {V W X Y : C} [has_colimit (pair X Y)] (f : V ⟶ W) (g : X ⟶ V) (h : Y ⟶ V) : coprod.desc (g ≫ f) (h ≫ f) = coprod.desc g h ≫ f := by tidy instance prod.mono_lift_of_mono_left {W X Y : C} [has_limit (pair X Y)] (f : W ⟶ X) (g : W ⟶ Y) [mono f] : mono (prod.lift f g) := mono_of_mono_fac $ prod.lift_fst _ _ instance prod.mono_lift_of_mono_right {W X Y : C} [has_limit (pair X Y)] (f : W ⟶ X) (g : W ⟶ Y) [mono g] : mono (prod.lift f g) := mono_of_mono_fac $ prod.lift_snd _ _ instance coprod.epi_desc_of_epi_left {W X Y : C} [has_colimit (pair X Y)] (f : X ⟶ W) (g : Y ⟶ W) [epi f] : epi (coprod.desc f g) := epi_of_epi_fac $ coprod.inl_desc _ _ instance coprod.epi_desc_of_epi_right {W X Y : C} [has_colimit (pair X Y)] (f : X ⟶ W) (g : Y ⟶ W) [epi g] : epi (coprod.desc f g) := epi_of_epi_fac $ coprod.inr_desc _ _ /-- If the product of `X` and `Y` exists, then every pair of morphisms `f : W ⟶ X` and `g : W ⟶ Y` induces a morphism `l : W ⟶ X ⨯ Y` satisfying `l ≫ prod.fst = f` and `l ≫ prod.snd = g`. -/ def prod.lift' {W X Y : C} [has_limit (pair X Y)] (f : W ⟶ X) (g : W ⟶ Y) : {l : W ⟶ X ⨯ Y // l ≫ prod.fst = f ∧ l ≫ prod.snd = g} := ⟨prod.lift f g, prod.lift_fst _ _, prod.lift_snd _ _⟩ /-- If the coproduct of `X` and `Y` exists, then every pair of morphisms `f : X ⟶ W` and `g : Y ⟶ W` induces a morphism `l : X ⨿ Y ⟶ W` satisfying `coprod.inl ≫ l = f` and `coprod.inr ≫ l = g`. -/ def coprod.desc' {W X Y : C} [has_colimit (pair X Y)] (f : X ⟶ W) (g : Y ⟶ W) : {l : X ⨿ Y ⟶ W // coprod.inl ≫ l = f ∧ coprod.inr ≫ l = g} := ⟨coprod.desc f g, coprod.inl_desc _ _, coprod.inr_desc _ _⟩ /-- If the products `W ⨯ X` and `Y ⨯ Z` exist, then every pair of morphisms `f : W ⟶ Y` and `g : X ⟶ Z` induces a morphism `prod.map f g : W ⨯ X ⟶ Y ⨯ Z`. -/ abbreviation prod.map {W X Y Z : C} [has_limits_of_shape.{v} (discrete walking_pair) C] (f : W ⟶ Y) (g : X ⟶ Z) : W ⨯ X ⟶ Y ⨯ Z := lim.map (map_pair f g) /-- If the coproducts `W ⨿ X` and `Y ⨿ Z` exist, then every pair of morphisms `f : W ⟶ Y` and `g : W ⟶ Z` induces a morphism `coprod.map f g : W ⨿ X ⟶ Y ⨿ Z`. -/ abbreviation coprod.map {W X Y Z : C} [has_colimits_of_shape.{v} (discrete walking_pair) C] (f : W ⟶ Y) (g : X ⟶ Z) : W ⨿ X ⟶ Y ⨿ Z := colim.map (map_pair f g) section prod_lemmas variable [has_limits_of_shape.{v} (discrete walking_pair) C] @[reassoc] lemma prod.map_fst {W X Y Z : C} (f : W ⟶ Y) (g : X ⟶ Z) : prod.map f g ≫ prod.fst = prod.fst ≫ f := by simp @[reassoc] lemma prod.map_snd {W X Y Z : C} (f : W ⟶ Y) (g : X ⟶ Z) : prod.map f g ≫ prod.snd = prod.snd ≫ g := by simp @[simp] lemma prod_map_id_id {X Y : C} : prod.map (𝟙 X) (𝟙 Y) = 𝟙 _ := by tidy @[simp] lemma prod_lift_fst_snd {X Y : C} : prod.lift prod.fst prod.snd = 𝟙 (X ⨯ Y) := by tidy -- I don't think it's a good idea to make any of the following simp lemmas. @[reassoc] lemma prod_map_map {A B X Y : C} (f : A ⟶ B) (g : X ⟶ Y) : prod.map (𝟙 X) f ≫ prod.map g (𝟙 B) = prod.map g (𝟙 A) ≫ prod.map (𝟙 Y) f := by tidy @[reassoc] lemma prod_map_comp_id {X Y Z W : C} (f : X ⟶ Y) (g : Y ⟶ Z) : prod.map (f ≫ g) (𝟙 W) = prod.map f (𝟙 W) ≫ prod.map g (𝟙 W) := by tidy @[reassoc] lemma prod_map_id_comp {X Y Z W : C} (f : X ⟶ Y) (g : Y ⟶ Z) : prod.map (𝟙 W) (f ≫ g) = prod.map (𝟙 W) f ≫ prod.map (𝟙 W) g := by tidy @[reassoc] lemma prod.lift_map (V W X Y Z : C) (f : V ⟶ W) (g : V ⟶ X) (h : W ⟶ Y) (k : X ⟶ Z) : prod.lift f g ≫ prod.map h k = prod.lift (f ≫ h) (g ≫ k) := by tidy end prod_lemmas section coprod_lemmas variable [has_colimits_of_shape.{v} (discrete walking_pair) C] @[reassoc] lemma coprod.inl_map {W X Y Z : C} (f : W ⟶ Y) (g : X ⟶ Z) : coprod.inl ≫ coprod.map f g = f ≫ coprod.inl := by simp @[reassoc] lemma coprod.inr_map {W X Y Z : C} (f : W ⟶ Y) (g : X ⟶ Z) : coprod.inr ≫ coprod.map f g = g ≫ coprod.inr := by simp @[simp] lemma coprod_map_id_id {X Y : C} : coprod.map (𝟙 X) (𝟙 Y) = 𝟙 _ := by tidy @[simp] lemma coprod_desc_inl_inr {X Y : C} : coprod.desc coprod.inl coprod.inr = 𝟙 (X ⨿ Y) := by tidy -- I don't think it's a good idea to make any of the following simp lemmas. @[reassoc] lemma coprod_map_map {A B X Y : C} (f : A ⟶ B) (g : X ⟶ Y) : coprod.map (𝟙 X) f ≫ coprod.map g (𝟙 B) = coprod.map g (𝟙 A) ≫ coprod.map (𝟙 Y) f := by tidy @[reassoc] lemma coprod_map_comp_id {X Y Z W : C} (f : X ⟶ Y) (g : Y ⟶ Z) : coprod.map (f ≫ g) (𝟙 W) = coprod.map f (𝟙 W) ≫ coprod.map g (𝟙 W) := by tidy @[reassoc] lemma coprod_map_id_comp {X Y Z W : C} (f : X ⟶ Y) (g : Y ⟶ Z) : coprod.map (𝟙 W) (f ≫ g) = coprod.map (𝟙 W) f ≫ coprod.map (𝟙 W) g := by tidy @[reassoc] lemma coprod.map_desc {S T U V W : C} (f : U ⟶ S) (g : W ⟶ S) (h : T ⟶ U) (k : V ⟶ W) : coprod.map h k ≫ coprod.desc f g = coprod.desc (h ≫ f) (k ≫ g) := by tidy end coprod_lemmas variables (C) /-- `has_binary_products` represents a choice of product for every pair of objects. -/ class has_binary_products := (has_limits_of_shape : has_limits_of_shape.{v} (discrete walking_pair) C) /-- `has_binary_coproducts` represents a choice of coproduct for every pair of objects. -/ class has_binary_coproducts := (has_colimits_of_shape : has_colimits_of_shape.{v} (discrete walking_pair) C) attribute [instance] has_binary_products.has_limits_of_shape has_binary_coproducts.has_colimits_of_shape @[priority 100] -- see Note [lower instance priority] instance [has_finite_products.{v} C] : has_binary_products.{v} C := { has_limits_of_shape := by apply_instance } @[priority 100] -- see Note [lower instance priority] instance [has_finite_coproducts.{v} C] : has_binary_coproducts.{v} C := { has_colimits_of_shape := by apply_instance } /-- If `C` has all limits of diagrams `pair X Y`, then it has all binary products -/ def has_binary_products_of_has_limit_pair [Π {X Y : C}, has_limit (pair X Y)] : has_binary_products.{v} C := { has_limits_of_shape := { has_limit := λ F, has_limit_of_iso (diagram_iso_pair F).symm } } /-- If `C` has all colimits of diagrams `pair X Y`, then it has all binary coproducts -/ def has_binary_coproducts_of_has_colimit_pair [Π {X Y : C}, has_colimit (pair X Y)] : has_binary_coproducts.{v} C := { has_colimits_of_shape := { has_colimit := λ F, has_colimit_of_iso (diagram_iso_pair F) } } section variables {C} [has_binary_products.{v} C] variables {D : Type u₂} [category.{v} D] [has_binary_products.{v} D] -- FIXME deterministic timeout with `-T50000` /-- The binary product functor. -/ @[simps] def prod_functor : C ⥤ C ⥤ C := { obj := λ X, { obj := λ Y, X ⨯ Y, map := λ Y Z, prod.map (𝟙 X) }, map := λ Y Z f, { app := λ T, prod.map f (𝟙 T) }} /-- The braiding isomorphism which swaps a binary product. -/ @[simps] def prod.braiding (P Q : C) : P ⨯ Q ≅ Q ⨯ P := { hom := prod.lift prod.snd prod.fst, inv := prod.lift prod.snd prod.fst } /-- The braiding isomorphism can be passed through a map by swapping the order. -/ @[reassoc] lemma braid_natural {W X Y Z : C} (f : X ⟶ Y) (g : Z ⟶ W) : prod.map f g ≫ (prod.braiding _ _).hom = (prod.braiding _ _).hom ≫ prod.map g f := by tidy @[simp, reassoc] lemma prod.symmetry' (P Q : C) : prod.lift prod.snd prod.fst ≫ prod.lift prod.snd prod.fst = 𝟙 (P ⨯ Q) := by tidy /-- The braiding isomorphism is symmetric. -/ @[reassoc] lemma prod.symmetry (P Q : C) : (prod.braiding P Q).hom ≫ (prod.braiding Q P).hom = 𝟙 _ := by simp /-- The associator isomorphism for binary products. -/ @[simps] def prod.associator (P Q R : C) : (P ⨯ Q) ⨯ R ≅ P ⨯ (Q ⨯ R) := { hom := prod.lift (prod.fst ≫ prod.fst) (prod.lift (prod.fst ≫ prod.snd) prod.snd), inv := prod.lift (prod.lift prod.fst (prod.snd ≫ prod.fst)) (prod.snd ≫ prod.snd) } /-- The product functor can be decomposed. -/ def prod_functor_left_comp (X Y : C) : prod_functor.obj (X ⨯ Y) ≅ prod_functor.obj Y ⋙ prod_functor.obj X := nat_iso.of_components (prod.associator _ _) (by tidy) @[reassoc] lemma prod.pentagon (W X Y Z : C) : prod.map ((prod.associator W X Y).hom) (𝟙 Z) ≫ (prod.associator W (X ⨯ Y) Z).hom ≫ prod.map (𝟙 W) ((prod.associator X Y Z).hom) = (prod.associator (W ⨯ X) Y Z).hom ≫ (prod.associator W X (Y ⨯ Z)).hom := by tidy @[reassoc] lemma prod.associator_naturality {X₁ X₂ X₃ Y₁ Y₂ Y₃ : C} (f₁ : X₁ ⟶ Y₁) (f₂ : X₂ ⟶ Y₂) (f₃ : X₃ ⟶ Y₃) : prod.map (prod.map f₁ f₂) f₃ ≫ (prod.associator Y₁ Y₂ Y₃).hom = (prod.associator X₁ X₂ X₃).hom ≫ prod.map f₁ (prod.map f₂ f₃) := by tidy /-- The product comparison morphism. In `category_theory/limits/preserves` we show this is always an iso iff F preserves binary products. -/ def prod_comparison (F : C ⥤ D) (A B : C) : F.obj (A ⨯ B) ⟶ F.obj A ⨯ F.obj B := prod.lift (F.map prod.fst) (F.map prod.snd) /-- Naturality of the prod_comparison morphism in both arguments. -/ @[reassoc] lemma prod_comparison_natural (F : C ⥤ D) {A A' B B' : C} (f : A ⟶ A') (g : B ⟶ B') : F.map (prod.map f g) ≫ prod_comparison F A' B' = prod_comparison F A B ≫ prod.map (F.map f) (F.map g) := begin rw [prod_comparison, prod_comparison, prod.lift_map], apply prod.hom_ext, { simp only [← F.map_comp, category.assoc, prod.lift_fst, prod.map_fst, category.comp_id] }, { simp only [← F.map_comp, category.assoc, prod.lift_snd, prod.map_snd, prod.lift_snd_assoc] }, end @[reassoc] lemma inv_prod_comparison_map_fst (F : C ⥤ D) (A B : C) [is_iso (prod_comparison F A B)] : inv (prod_comparison F A B) ≫ F.map prod.fst = prod.fst := begin erw (as_iso (prod_comparison F A B)).inv_comp_eq, dsimp [as_iso_hom, prod_comparison], rw prod.lift_fst, end @[reassoc] lemma inv_prod_comparison_map_snd (F : C ⥤ D) (A B : C) [is_iso (prod_comparison F A B)] : inv (prod_comparison F A B) ≫ F.map prod.snd = prod.snd := begin erw (as_iso (prod_comparison F A B)).inv_comp_eq, dsimp [as_iso_hom, prod_comparison], rw prod.lift_snd, end /-- If the product comparison morphism is an iso, its inverse is natural. -/ @[reassoc] lemma prod_comparison_inv_natural (F : C ⥤ D) {A A' B B' : C} (f : A ⟶ A') (g : B ⟶ B') [is_iso (prod_comparison F A B)] [is_iso (prod_comparison F A' B')] : inv (prod_comparison F A B) ≫ F.map (prod.map f g) = prod.map (F.map f) (F.map g) ≫ inv (prod_comparison F A' B') := by { erw [(as_iso (prod_comparison F A' B')).eq_comp_inv, category.assoc, (as_iso (prod_comparison F A B)).inv_comp_eq, prod_comparison_natural], refl } variables [has_terminal.{v} C] /-- The left unitor isomorphism for binary products with the terminal object. -/ @[simps] def prod.left_unitor (P : C) : ⊤_ C ⨯ P ≅ P := { hom := prod.snd, inv := prod.lift (terminal.from P) (𝟙 _) } /-- The right unitor isomorphism for binary products with the terminal object. -/ @[simps] def prod.right_unitor (P : C) : P ⨯ ⊤_ C ≅ P := { hom := prod.fst, inv := prod.lift (𝟙 _) (terminal.from P) } @[reassoc] lemma prod_left_unitor_hom_naturality (f : X ⟶ Y): prod.map (𝟙 _) f ≫ (prod.left_unitor Y).hom = (prod.left_unitor X).hom ≫ f := prod.map_snd _ _ @[reassoc] lemma prod_left_unitor_inv_naturality (f : X ⟶ Y): (prod.left_unitor X).inv ≫ prod.map (𝟙 _) f = f ≫ (prod.left_unitor Y).inv := by rw [iso.inv_comp_eq, ← category.assoc, iso.eq_comp_inv, prod_left_unitor_hom_naturality] @[reassoc] lemma prod_right_unitor_hom_naturality (f : X ⟶ Y): prod.map f (𝟙 _) ≫ (prod.right_unitor Y).hom = (prod.right_unitor X).hom ≫ f := prod.map_fst _ _ @[reassoc] lemma prod_right_unitor_inv_naturality (f : X ⟶ Y): (prod.right_unitor X).inv ≫ prod.map f (𝟙 _) = f ≫ (prod.right_unitor Y).inv := by rw [iso.inv_comp_eq, ← category.assoc, iso.eq_comp_inv, prod_right_unitor_hom_naturality] lemma prod.triangle (X Y : C) : (prod.associator X (⊤_ C) Y).hom ≫ prod.map (𝟙 X) ((prod.left_unitor Y).hom) = prod.map ((prod.right_unitor X).hom) (𝟙 Y) := by tidy end section variables {C} [has_binary_coproducts.{v} C] /-- The braiding isomorphism which swaps a binary coproduct. -/ @[simps] def coprod.braiding (P Q : C) : P ⨿ Q ≅ Q ⨿ P := { hom := coprod.desc coprod.inr coprod.inl, inv := coprod.desc coprod.inr coprod.inl } @[simp] lemma coprod.symmetry' (P Q : C) : coprod.desc coprod.inr coprod.inl ≫ coprod.desc coprod.inr coprod.inl = 𝟙 (P ⨿ Q) := by tidy /-- The braiding isomorphism is symmetric. -/ lemma coprod.symmetry (P Q : C) : (coprod.braiding P Q).hom ≫ (coprod.braiding Q P).hom = 𝟙 _ := by simp /-- The associator isomorphism for binary coproducts. -/ @[simps] def coprod.associator (P Q R : C) : (P ⨿ Q) ⨿ R ≅ P ⨿ (Q ⨿ R) := { hom := coprod.desc (coprod.desc coprod.inl (coprod.inl ≫ coprod.inr)) (coprod.inr ≫ coprod.inr), inv := coprod.desc (coprod.inl ≫ coprod.inl) (coprod.desc (coprod.inr ≫ coprod.inl) coprod.inr) } lemma coprod.pentagon (W X Y Z : C) : coprod.map ((coprod.associator W X Y).hom) (𝟙 Z) ≫ (coprod.associator W (X ⨿ Y) Z).hom ≫ coprod.map (𝟙 W) ((coprod.associator X Y Z).hom) = (coprod.associator (W ⨿ X) Y Z).hom ≫ (coprod.associator W X (Y ⨿ Z)).hom := by tidy lemma coprod.associator_naturality {X₁ X₂ X₃ Y₁ Y₂ Y₃ : C} (f₁ : X₁ ⟶ Y₁) (f₂ : X₂ ⟶ Y₂) (f₃ : X₃ ⟶ Y₃) : coprod.map (coprod.map f₁ f₂) f₃ ≫ (coprod.associator Y₁ Y₂ Y₃).hom = (coprod.associator X₁ X₂ X₃).hom ≫ coprod.map f₁ (coprod.map f₂ f₃) := by tidy variables [has_initial.{v} C] /-- The left unitor isomorphism for binary coproducts with the initial object. -/ @[simps] def coprod.left_unitor (P : C) : ⊥_ C ⨿ P ≅ P := { hom := coprod.desc (initial.to P) (𝟙 _), inv := coprod.inr } /-- The right unitor isomorphism for binary coproducts with the initial object. -/ @[simps] def coprod.right_unitor (P : C) : P ⨿ ⊥_ C ≅ P := { hom := coprod.desc (𝟙 _) (initial.to P), inv := coprod.inl } lemma coprod.triangle (X Y : C) : (coprod.associator X (⊥_ C) Y).hom ≫ coprod.map (𝟙 X) ((coprod.left_unitor Y).hom) = coprod.map ((coprod.right_unitor X).hom) (𝟙 Y) := by tidy end end category_theory.limits
06f676719a300169a50d4f733345572a62f64137
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/run/bug6.lean
479b942bd3f7dc6490ed3cea0c44a3414910b641
[ "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
314
lean
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
85fc2ce85130192c09ded1e4d2ec78c718b3638d
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/run/empty_set_inside_quotations.lean
915ac13a76b79459ab3732b167034c08f8d41578
[ "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
480
lean
instance {α} : has_union (set α) := ⟨λ s t, {a | a ∈ s ∨ a ∈ t}⟩ constant union_is_assoc {α} : is_associative (set α) (∪) attribute [instance] union_is_assoc #check ({} : set nat) open tactic expr meta def is_assoc_bin_app : expr → tactic (expr × expr) | (app (app op a1) a2) := do h ← to_expr ``(is_associative.assoc %%op), return (op, h) | _ := failed #eval to_expr ``(({} : set nat) ∪ {}) >>= is_assoc_bin_app >>= λ p, trace p.2
2382e98f1b36d314f73b20e8ebb6765147f4ea22
5121e95053e1e1895a377da05d0e2744fce6a5a9
/src/sr.lean
52ff1a56bf64183bbaba42683ac71ac3a5a295fe
[]
no_license
miguelraz/special_relativity
4c9426202493c8c930dc3b8b56d05fa44c915e1b
c918f2a919a0c518d6a3bd2e5e2fa1a4f0307088
refs/heads/master
1,668,480,638,260
1,594,619,371,000
1,594,619,371,000
279,223,829
0
0
null
null
null
null
UTF-8
Lean
false
false
2,495
lean
import data.real.basic tactic noncomputable theory -- v4abs does not need to be computable, don't care about it. local notation `⟨╯°□°⟩╯︵┻━┻` := sorry structure v₄ : Type := (x y z t : ℝ) #check (⟨ 0, 0, 0, 1⟩ : v₄) def v₄abs (v : v₄ ) : ℝ := real.sqrt(v.x^2 + v.y^2 + v.z^2 + v.t^2) notation `|`x`|` := v₄abs x example : |(⟨0,0,0,2⟩)| = 2 := by norm_num [v₄abs] def v₄add (v₁ v₂ : v₄) : v₄ := ⟨v₁.x + v₂.x, v₁.y + v₂.y, v₁.z + v₂.z, v₁.t + v₂.t⟩ def v₄neg (v: v₄) : v₄ := ⟨-v.x, -v.y, -v.z, -v.t⟩ example : v₄add ⟨ 0, 0, 0, 1⟩ ⟨1, 1, 1, 0 ⟩ = ⟨1, 1, 1, 1⟩ := by norm_num [v₄add] def v₄zero : v₄ := ⟨0,0,0,0⟩ -- If we prove that v₄ is an add_comm group, then we get subtraction and infix notation for free -- That's an instance btw. -- To autogenerate the skeleton, place a '_' after the := and then click the lightbulb instance : add_comm_group v₄ := { add := v₄add, add_assoc := begin intros a b c, dsimp only [v₄add], -- unfold definition of equality (definitional simp) -- only tells Lean to only apply that lemma. congr' 1; -- only applie congruence 1 level deep rw add_assoc, end, zero := v₄zero, zero_add := begin intro a, --dsimp only [v₄zero, v₄add, (+)], cases a, -- change is to replace the goal with a goal that is definitionally equal -- () every time you specify a type change (⟨0 + a_x, 0 + a_y, 0 + a_z, 0 + a_t⟩ : v₄) = _, congr' 1; rw zero_add, end, add_zero := begin intro a, -- the cases here is needed because the right hand side is an ⟨_,_,_,_⟩, and needs to -- be unfolded cases a, change (⟨a_x + 0, a_y + 0, a_z + 0, a_t + 0⟩ : v₄) = _, congr' 1; rw add_zero, end, neg := v₄neg, add_left_neg := begin intro a, cases a, change (⟨-a_x + a_x, -a_y + a_y, -a_z + a_z, -a_t + a_t⟩ : v₄) = _, congr' 1; rw add_left_neg, end, add_comm := begin intros a b, cases a, cases b, change (⟨a_x + b_x, a_y + b_y, a_z + b_z, a_t + b_t⟩ : v₄) = _, congr' 1; rw add_comm, end } --smol ? -- trying line 487, v - v = 0 -- because we proved it's an add_comm_group, we have `sub_self`, example (u v : v₄) : u = v ↔ u - v = 0 := begin -- split, -- intro h, -- rw h, -- rw sub_self, -- intro h, -- rwa sub_eq_zero at h, -- Shing FTW! rw sub_eq_zero, end
09ccdbf0af36be5f3d26b1ac76a015d56f43c6ce
4d7079ae603c07560e99d1ce35876f769cbb3e24
/src/monotonicity.lean
6c58f86abf8d01baf27608a7a8459d78a58b765f
[]
no_license
chasenorman/Formalized-Voting
72493a08aa09d98d0fb589731b842e2d08c991d0
de04e630b83525b042db166670ba97f9952b5691
refs/heads/main
1,687,282,160,284
1,627,155,031,000
1,627,155,031,000
370,472,025
13
0
null
null
null
null
UTF-8
Lean
false
false
6,819
lean
import main import split_cycle import algebra.linear_ordered_comm_group_with_zero open_locale classical variables {V X : Type} def simple_lift : Prof V X → Prof V X → X → Prop := λ P' P x, (∀ (a ≠ x) (b ≠ x) i, P i a b ↔ P' i a b) ∧ ∀ a i, ((P i x a → P' i x a) ∧ (P' i a x → P i a x)) def monotonicity (F : VSCC) (P P' : Prof V X) : Prop := ∀ (x ∈ F V X P), simple_lift P' P x → x ∈ F V X P' lemma cardinality_lemma [fintype V] (p q : V → Prop) : (∀ v, (p v → q v)) → ((finset.filter p finset.univ).card ≤ (finset.filter q finset.univ).card) := begin intro pq, have subset : (finset.filter p finset.univ) ⊆ (finset.filter q finset.univ), refine finset.subset_iff.mpr _, simp, exact pq, exact (finset.card_le_of_subset subset), end lemma cardinality_lemma2 [fintype V] (p q : V → Prop) : (∀ v, (p v ↔ q v)) → ((finset.filter p finset.univ).card = (finset.filter q finset.univ).card) := begin intro pq, congr, ext1, simp at *, fsplit, work_on_goal 0 { intros ᾰ }, work_on_goal 1 { intros ᾰ }, specialize pq x, exact pq.mp ᾰ, specialize pq x, exact pq.mpr ᾰ, end lemma margin_lemma (P P' : Prof V X) [fintype V] (a b : X) : (a ≠ b) → (∀ (v : V), (P v a b → P' v a b) ∧ (P' v b a → P v b a)) → margin P a b ≤ margin P' a b := begin intro h, intro lift, unfold margin, have first : ((finset.filter (λ (x_1 : V), P x_1 a b) finset.univ).card) ≤ ((finset.filter (λ (x_1 : V), P' x_1 a b) finset.univ).card), have first_pq : ∀ v, (λ (x_1 : V), P x_1 a b) v → (λ (x_1 : V), P' x_1 a b) v, simp, intro v, specialize lift v, cases lift with lift1 lift2, exact lift1, exact cardinality_lemma (λ (x_1 : V), P x_1 a b) (λ (x_1 : V), P' x_1 a b) first_pq, have second : ((finset.filter (λ (x_1 : V), P' x_1 b a) finset.univ).card) ≤ ((finset.filter (λ (x_1 : V), P x_1 b a) finset.univ).card), have second_pq : ∀ v, (λ (x_1 : V), P' x_1 b a) v → (λ (x_1 : V), P x_1 b a) v, simp, intro v, contrapose, intro npyx, specialize lift v, cases lift with lift1 lift2, contrapose npyx, push_neg, push_neg at npyx, exact lift2 npyx, exact cardinality_lemma (λ (x_1 : V), P' x_1 b a) (λ (x_1 : V), P x_1 b a) second_pq, mono, simp, exact first, simp, exact second, end -- if the elements are the same between the two Profs, the a = b case is still true. lemma margin_lemma' (P P' : Prof V X) [fintype V] [profile_asymmetric P'] (a b : X) : (∀ (v : V), (P v a b → P' v a b) ∧ (P' v b a → P v b a)) → margin P a b ≤ margin P' a b := begin intro pq, by_cases a = b, rw h, rw self_margin_zero, rw self_margin_zero, exact margin_lemma P P' a b h pq, end lemma margin_lt_margin_of_lift (P P' : Prof V X) [fintype V] (y x : X) : simple_lift P' P x → margin P' y x ≤ margin P y x := begin intro lift, unfold simple_lift at lift, cases lift with lift1 lift2, specialize lift2 y, by_cases x = y, rw h, rw self_margin_zero, rw self_margin_zero, have test := margin_lemma P P' x y h lift2, rw margin_antisymmetric, rw margin_antisymmetric P, simp, exact test, end theorem split_cycle_monotonicity [fintype V] (P P' : Prof V X) [profile_asymmetric P'] : monotonicity split_cycle P P' := begin unfold monotonicity, intros x x_won lift, unfold split_cycle, unfold max_el_VSCC, rw split_cycle_definitions, simp, unfold split_cycle_VCCR', intro y, push_neg, use _inst_1, intro m, /- "so suppose margin P'(y,x) > 0." -/ unfold split_cycle at x_won, unfold max_el_VSCC at x_won, rw split_cycle_definitions at x_won, simp at x_won, unfold split_cycle_VCCR' at x_won, simp at x_won, specialize x_won y, -- now we must show that there is a chain from x to y of margin greater than margin y x unfold margin_pos at m, have m' := margin_lt_margin_of_lift P P' y x lift, cases x_won with _ x_won, unfold margin_pos at x_won, rw margin_eq_margin x_won_w _inst_1 at x_won, specialize x_won (lt_of_lt_of_le m m'), cases x_won with l x_won, use l, cases x_won with nodup x_won, cases x_won with nonempty x_won, use nonempty, use nodup, cases x_won with x_nth x_won, use x_nth, cases x_won with y_nth x_won, use y_nth, -- reduced to just the chain. All the properties of the chain have been proven. rw list.chain'_iff_nth_le at x_won, rw list.chain'_iff_nth_le, intro i, intro i_bound, -- for any index i specialize x_won i, specialize x_won i_bound, have test := le_trans m' x_won, apply le_trans test, -- by the transitive property it is sufficient to show that the margins exclusively increased due to the lift. -- problem: if the cycle is not simple and contains x, it may not be a cycle in P'. by_cases i = 0, have eq : (l.nth_le i (nat.lt_of_lt_pred i_bound)) = (l.nth_le 0 (list.length_pos_of_ne_nil nonempty)), congr, exact h, rw eq, rw x_nth, cases lift with lift1 lift2, rw margin_eq_margin x_won_w _inst_1, exact margin_lemma' P P' x (l.nth_le (i + 1) (nat.lt_pred_iff.mp i_bound)) (lift2 (l.nth_le (i + 1) (nat.lt_pred_iff.mp i_bound))), -- we use the second property of lifts to show this since the first element is x. have neq : (l.nth_le i (nat.lt_of_lt_pred i_bound)) ≠ x, change l.pairwise ne at nodup, rw ←x_nth, exact ne.symm (list.pairwise_iff_nth_le.mp nodup 0 i (nat.lt_of_lt_pred i_bound) (zero_lt_iff.mpr h)), have neq2 : (l.nth_le (i + 1) (nat.lt_pred_iff.mp i_bound)) ≠ x, change l.pairwise ne at nodup, rw ←x_nth, exact ne.symm (list.pairwise_iff_nth_le.mp nodup 0 (i + 1) (nat.lt_pred_iff.mp i_bound) (nat.zero_lt_succ i)), have pq : ∀ (v : V), (P v (l.nth_le i (nat.lt_of_lt_pred i_bound)) (l.nth_le (i + 1) (nat.lt_pred_iff.mp i_bound)) → P' v (l.nth_le i (nat.lt_of_lt_pred i_bound)) (l.nth_le (i + 1) (nat.lt_pred_iff.mp i_bound))) ∧ (P' v (l.nth_le (i + 1) (nat.lt_pred_iff.mp i_bound)) (l.nth_le i (nat.lt_of_lt_pred i_bound)) → P v (l.nth_le (i + 1) (nat.lt_pred_iff.mp i_bound)) (l.nth_le i (nat.lt_of_lt_pred i_bound))), intro v, cases lift with lift1 lift2, split, exact (lift1 (l.nth_le i (nat.lt_of_lt_pred i_bound)) neq (l.nth_le (i + 1) (nat.lt_pred_iff.mp i_bound)) neq2 v).mp, exact (lift1 (l.nth_le (i + 1) (nat.lt_pred_iff.mp i_bound)) neq2 (l.nth_le i (nat.lt_of_lt_pred i_bound)) neq v).mpr, rw margin_eq_margin x_won_w _inst_1, exact margin_lemma' P P' (l.nth_le i (nat.lt_of_lt_pred i_bound)) (l.nth_le (i + 1) (nat.lt_pred_iff.mp i_bound)) pq, end
419bf26a8cb2e2c6ef2295fb5365a8ed42a93428
8cb37a089cdb4af3af9d8bf1002b417e407a8e9e
/library/init/data/list/lemmas.lean
406718c0e4eb99a9e89a68037e9cd1068daad9d4
[ "Apache-2.0" ]
permissive
kbuzzard/lean
ae3c3db4bb462d750dbf7419b28bafb3ec983ef7
ed1788fd674bb8991acffc8fca585ec746711928
refs/heads/master
1,620,983,366,617
1,618,937,600,000
1,618,937,600,000
359,886,396
1
0
Apache-2.0
1,618,936,987,000
1,618,936,987,000
null
UTF-8
Lean
false
false
10,525
lean
/- Copyright (c) 2014 Parikshit Khanna. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Parikshit Khanna, Jeremy Avigad, Leonardo de Moura, Floris van Doorn -/ prelude import init.data.list.basic init.function init.meta init.data.nat.lemmas import init.meta.interactive init.meta.smt.rsimp universes u v w w₁ w₂ variables {α : Type u} {β : Type v} {γ : Type w} namespace list open nat /- append -/ @[simp] lemma nil_append (s : list α) : [] ++ s = s := rfl @[simp] lemma cons_append (x : α) (s t : list α) : (x::s) ++ t = x::(s ++ t) := rfl @[simp] lemma append_nil (t : list α) : t ++ [] = t := by induction t; simp [*] @[simp] lemma append_assoc (s t u : list α) : s ++ t ++ u = s ++ (t ++ u) := by induction s; simp [*] /- length -/ lemma length_cons (a : α) (l : list α) : length (a :: l) = length l + 1 := rfl @[simp] lemma length_append (s t : list α) : length (s ++ t) = length s + length t := begin induction s, { show length t = 0 + length t, by rw nat.zero_add }, { simp [*, nat.add_comm, nat.add_left_comm] }, end @[simp] lemma length_repeat (a : α) (n : ℕ) : length (repeat a n) = n := by induction n; simp [*]; refl @[simp] lemma length_tail (l : list α) : length (tail l) = length l - 1 := by cases l; refl -- TODO(Leo): cleanup proof after arith dec proc @[simp] lemma length_drop : ∀ (i : ℕ) (l : list α), length (drop i l) = length l - i | 0 l := rfl | (succ i) [] := eq.symm (nat.zero_sub (succ i)) | (succ i) (x::l) := calc length (drop (succ i) (x::l)) = length l - i : length_drop i l ... = succ (length l) - succ i : (nat.succ_sub_succ_eq_sub (length l) i).symm /- map -/ lemma map_cons (f : α → β) (a l) : map f (a::l) = f a :: map f l := rfl @[simp] lemma map_append (f : α → β) : ∀ l₁ l₂, map f (l₁ ++ l₂) = (map f l₁) ++ (map f l₂) := by intro l₁; induction l₁; intros; simp [*] lemma map_singleton (f : α → β) (a : α) : map f [a] = [f a] := rfl @[simp] lemma map_id (l : list α) : map id l = l := by induction l; simp [*] @[simp] lemma map_map (g : β → γ) (f : α → β) (l : list α) : map g (map f l) = map (g ∘ f) l := by induction l; simp [*] @[simp] lemma length_map (f : α → β) (l : list α) : length (map f l) = length l := by induction l; simp [*] /- bind -/ @[simp] lemma nil_bind (f : α → list β) : list.bind [] f = [] := by simp [join, list.bind] @[simp] lemma cons_bind (x xs) (f : α → list β) : list.bind (x :: xs) f = f x ++ list.bind xs f := by simp [join, list.bind] @[simp] lemma append_bind (xs ys) (f : α → list β) : list.bind (xs ++ ys) f = list.bind xs f ++ list.bind ys f := by induction xs; [refl, simp [*, cons_bind]] /- mem -/ lemma mem_nil_iff (a : α) : a ∈ ([] : list α) ↔ false := iff.rfl @[simp] lemma not_mem_nil (a : α) : a ∉ ([] : list α) := not_false lemma mem_cons_self (a : α) (l : list α) : a ∈ a :: l := or.inl rfl @[simp] lemma mem_cons_iff (a y : α) (l : list α) : a ∈ y :: l ↔ (a = y ∨ a ∈ l) := iff.rfl @[rsimp] lemma mem_cons_eq (a y : α) (l : list α) : (a ∈ y :: l) = (a = y ∨ a ∈ l) := rfl lemma mem_cons_of_mem (y : α) {a : α} {l : list α} : a ∈ l → a ∈ y :: l := assume H, or.inr H lemma eq_or_mem_of_mem_cons {a y : α} {l : list α} : a ∈ y::l → a = y ∨ a ∈ l := assume h, h @[simp] lemma mem_append {a : α} {s t : list α} : a ∈ s ++ t ↔ a ∈ s ∨ a ∈ t := by induction s; simp [*, or_assoc] @[rsimp] lemma mem_append_eq (a : α) (s t : list α) : (a ∈ s ++ t) = (a ∈ s ∨ a ∈ t) := propext mem_append lemma mem_append_left {a : α} {l₁ : list α} (l₂ : list α) (h : a ∈ l₁) : a ∈ l₁ ++ l₂ := mem_append.2 (or.inl h) lemma mem_append_right {a : α} (l₁ : list α) {l₂ : list α} (h : a ∈ l₂) : a ∈ l₁ ++ l₂ := mem_append.2 (or.inr h) lemma not_bex_nil (p : α → Prop) : ¬ (∃ x ∈ @nil α, p x) := λ⟨x, hx, px⟩, hx lemma ball_nil (p : α → Prop) : ∀ x ∈ @nil α, p x := λx, false.elim lemma bex_cons (p : α → Prop) (a : α) (l : list α) : (∃ x ∈ (a :: l), p x) ↔ (p a ∨ ∃ x ∈ l, p x) := ⟨λ⟨x, h, px⟩, by { simp at h, cases h with h h, {cases h, exact or.inl px}, {exact or.inr ⟨x, h, px⟩}}, λo, o.elim (λpa, ⟨a, mem_cons_self _ _, pa⟩) (λ⟨x, h, px⟩, ⟨x, mem_cons_of_mem _ h, px⟩)⟩ lemma ball_cons (p : α → Prop) (a : α) (l : list α) : (∀ x ∈ (a :: l), p x) ↔ (p a ∧ ∀ x ∈ l, p x) := ⟨λal, ⟨al a (mem_cons_self _ _), λx h, al x (mem_cons_of_mem _ h)⟩, λ⟨pa, al⟩ x o, o.elim (λe, e.symm ▸ pa) (al x)⟩ /- list subset -/ protected def subset (l₁ l₂ : list α) := ∀ ⦃a : α⦄, a ∈ l₁ → a ∈ l₂ instance : has_subset (list α) := ⟨list.subset⟩ @[simp] lemma nil_subset (l : list α) : [] ⊆ l := λ b i, false.elim (iff.mp (mem_nil_iff b) i) @[refl, simp] lemma subset.refl (l : list α) : l ⊆ l := λ b i, i @[trans] lemma subset.trans {l₁ l₂ l₃ : list α} (h₁ : l₁ ⊆ l₂) (h₂ : l₂ ⊆ l₃) : l₁ ⊆ l₃ := λ b i, h₂ (h₁ i) @[simp] lemma subset_cons (a : α) (l : list α) : l ⊆ a::l := λ b i, or.inr i lemma subset_of_cons_subset {a : α} {l₁ l₂ : list α} : a::l₁ ⊆ l₂ → l₁ ⊆ l₂ := λ s b i, s (mem_cons_of_mem _ i) lemma cons_subset_cons {l₁ l₂ : list α} (a : α) (s : l₁ ⊆ l₂) : (a::l₁) ⊆ (a::l₂) := λ b hin, or.elim (eq_or_mem_of_mem_cons hin) (λ e : b = a, or.inl e) (λ i : b ∈ l₁, or.inr (s i)) @[simp] lemma subset_append_left (l₁ l₂ : list α) : l₁ ⊆ l₁++l₂ := λ b, mem_append_left _ @[simp] lemma subset_append_right (l₁ l₂ : list α) : l₂ ⊆ l₁++l₂ := λ b, mem_append_right _ lemma subset_cons_of_subset (a : α) {l₁ l₂ : list α} : l₁ ⊆ l₂ → l₁ ⊆ (a::l₂) := λ (s : l₁ ⊆ l₂) (a : α) (i : a ∈ l₁), or.inr (s i) theorem eq_nil_of_length_eq_zero {l : list α} : length l = 0 → l = [] := by {induction l; intros, refl, contradiction} theorem ne_nil_of_length_eq_succ {l : list α} : ∀ {n : nat}, length l = succ n → l ≠ [] := by induction l; intros; contradiction @[simp] theorem length_map₂ (f : α → β → γ) (l₁) : ∀ l₂, length (map₂ f l₁ l₂) = min (length l₁) (length l₂) := by { induction l₁; intro l₂; cases l₂; simp [*, add_one, min_succ_succ, nat.zero_min, nat.min_zero] } @[simp] theorem length_take : ∀ (i : ℕ) (l : list α), length (take i l) = min i (length l) | 0 l := by simp [nat.zero_min] | (succ n) [] := by simp [nat.min_zero] | (succ n) (a::l) := by simp [*, nat.min_succ_succ, add_one] theorem length_take_le (n) (l : list α) : length (take n l) ≤ n := by simp [min_le_left] theorem length_remove_nth : ∀ (l : list α) (i : ℕ), i < length l → length (remove_nth l i) = length l - 1 | [] _ h := rfl | (x::xs) 0 h := by simp [remove_nth] | (x::xs) (i+1) h := have i < length xs, from lt_of_succ_lt_succ h, by dsimp [remove_nth]; rw [length_remove_nth xs i this, nat.sub_add_cancel (lt_of_le_of_lt (nat.zero_le _) this)]; refl @[simp] lemma partition_eq_filter_filter (p : α → Prop) [decidable_pred p] : ∀ (l : list α), partition p l = (filter p l, filter (not ∘ p) l) | [] := rfl | (a::l) := by { by_cases pa : p a; simp [partition, filter, pa, partition_eq_filter_filter l] } /- sublists -/ inductive sublist : list α → list α → Prop | slnil : sublist [] [] | cons (l₁ l₂ a) : sublist l₁ l₂ → sublist l₁ (a::l₂) | cons2 (l₁ l₂ a) : sublist l₁ l₂ → sublist (a::l₁) (a::l₂) infix ` <+ `:50 := sublist lemma length_le_of_sublist : ∀ {l₁ l₂ : list α}, l₁ <+ l₂ → length l₁ ≤ length l₂ | _ _ sublist.slnil := le_refl 0 | _ _ (sublist.cons l₁ l₂ a s) := le_succ_of_le (length_le_of_sublist s) | _ _ (sublist.cons2 l₁ l₂ a s) := succ_le_succ (length_le_of_sublist s) /- filter -/ @[simp] theorem filter_nil (p : α → Prop) [h : decidable_pred p] : filter p [] = [] := rfl @[simp] theorem filter_cons_of_pos {p : α → Prop} [h : decidable_pred p] {a : α} : ∀ l, p a → filter p (a::l) = a :: filter p l := λ l pa, if_pos pa @[simp] theorem filter_cons_of_neg {p : α → Prop} [h : decidable_pred p] {a : α} : ∀ l, ¬ p a → filter p (a::l) = filter p l := λ l pa, if_neg pa @[simp] theorem filter_append {p : α → Prop} [h : decidable_pred p] : ∀ (l₁ l₂ : list α), filter p (l₁++l₂) = filter p l₁ ++ filter p l₂ | [] l₂ := rfl | (a::l₁) l₂ := by by_cases pa : p a; simp [pa, filter_append] @[simp] theorem filter_sublist {p : α → Prop} [h : decidable_pred p] : Π (l : list α), filter p l <+ l | [] := sublist.slnil | (a::l) := if pa : p a then by simp [pa]; apply sublist.cons2; apply filter_sublist l else by simp [pa]; apply sublist.cons; apply filter_sublist l /- map_accumr -/ section map_accumr variables {φ : Type w₁} {σ : Type w₂} -- This runs a function over a list returning the intermediate results and a -- a final result. def map_accumr (f : α → σ → σ × β) : list α → σ → (σ × list β) | [] c := (c, []) | (y::yr) c := let r := map_accumr yr c in let z := f y r.1 in (z.1, z.2 :: r.2) @[simp] theorem length_map_accumr : ∀ (f : α → σ → σ × β) (x : list α) (s : σ), length (map_accumr f x s).2 = length x | f (a::x) s := congr_arg succ (length_map_accumr f x s) | f [] s := rfl end map_accumr section map_accumr₂ variables {φ : Type w₁} {σ : Type w₂} -- This runs a function over two lists returning the intermediate results and a -- a final result. def map_accumr₂ (f : α → β → σ → σ × φ) : list α → list β → σ → σ × list φ | [] _ c := (c,[]) | _ [] c := (c,[]) | (x::xr) (y::yr) c := let r := map_accumr₂ xr yr c in let q := f x y r.1 in (q.1, q.2 :: r.2) @[simp] theorem length_map_accumr₂ : ∀ (f : α → β → σ → σ × φ) x y c, length (map_accumr₂ f x y c).2 = min (length x) (length y) | f (a::x) (b::y) c := calc succ (length (map_accumr₂ f x y c).2) = succ (min (length x) (length y)) : congr_arg succ (length_map_accumr₂ f x y c) ... = min (succ (length x)) (succ (length y)) : eq.symm (min_succ_succ (length x) (length y)) | f (a::x) [] c := rfl | f [] (b::y) c := rfl | f [] [] c := rfl end map_accumr₂ end list
ed8d91fddfeccf17e665046243e8bfb132845bf3
63abd62053d479eae5abf4951554e1064a4c45b4
/src/order/preorder_hom.lean
6719c3fc0cf66181a73a74bc8b935a7a669b3cf3
[ "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
5,483
lean
/- Copyright (c) 2020 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin # Preorder homomorphisms Bundled monotone functions, `x ≤ y → f x ≤ f y`. -/ import order.basic import order.bounded_lattice import order.complete_lattice import tactic.monotonicity /-! # Category of preorders -/ /-- Bundled monotone (aka, increasing) function -/ structure preorder_hom (α β : Type*) [preorder α] [preorder β] := (to_fun : α → β) (monotone' : monotone to_fun) infixr ` →ₘ `:25 := preorder_hom namespace preorder_hom variables {α : Type*} {β : Type*} {γ : Type*} [preorder α] [preorder β] [preorder γ] instance : has_coe_to_fun (preorder_hom α β) := { F := λ f, α → β, coe := preorder_hom.to_fun } @[mono] lemma monotone (f : α →ₘ β) : monotone f := preorder_hom.monotone' f @[simp] lemma coe_fun_mk {f : α → β} (hf : _root_.monotone f) (x : α) : mk f hf x = f x := rfl @[ext] lemma ext (f g : preorder_hom α β) (h : ∀ a, f a = g a) : f = g := by { cases f, cases g, congr, funext, exact h _ } lemma coe_inj (f g : preorder_hom α β) (h : (f : α → β) = g) : f = g := by { ext, rw h } /-- The identity function as bundled monotone function. -/ @[simps] def id : preorder_hom α α := ⟨id, monotone_id⟩ instance : inhabited (preorder_hom α α) := ⟨id⟩ @[simp] lemma coe_id : (@id α _ : α → α) = id := rfl /-- The composition of two bundled monotone functions. -/ @[simps] def comp (g : preorder_hom β γ) (f : preorder_hom α β) : preorder_hom α γ := ⟨g ∘ f, g.monotone.comp f.monotone⟩ @[simp] lemma comp_id (f : preorder_hom α β) : f.comp id = f := by { ext, refl } @[simp] lemma id_comp (f : preorder_hom α β) : id.comp f = f := by { ext, refl } /-- `subtype.val` as a bundled monotone function. -/ def subtype.val (p : α → Prop) : subtype p →ₘ α := ⟨subtype.val, λ x y h, h⟩ /-- The preorder structure of `α →ₘ β` is pointwise inequality: `f ≤ g ↔ ∀ a, f a ≤ g a`. -/ instance : preorder (α →ₘ β) := preorder.lift preorder_hom.to_fun instance {β : Type*} [partial_order β] : partial_order (α →ₘ β) := partial_order.lift preorder_hom.to_fun $ by rintro ⟨⟩ ⟨⟩ h; congr; exact h @[simps] instance {β : Type*} [semilattice_sup β] : has_sup (α →ₘ β) := { sup := λ f g, ⟨λ a, f a ⊔ g a, λ x y h, sup_le_sup (f.monotone h) (g.monotone h)⟩ } instance {β : Type*} [semilattice_sup β] : semilattice_sup (α →ₘ β) := { sup := has_sup.sup, le_sup_left := λ a b x, le_sup_left, le_sup_right := λ a b x, le_sup_right, sup_le := λ a b c h₀ h₁ x, sup_le (h₀ x) (h₁ x), .. (_ : partial_order (α →ₘ β)) } @[simps] instance {β : Type*} [semilattice_inf β] : has_inf (α →ₘ β) := { inf := λ f g, ⟨λ a, f a ⊓ g a, λ x y h, inf_le_inf (f.monotone h) (g.monotone h)⟩ } instance {β : Type*} [semilattice_inf β] : semilattice_inf (α →ₘ β) := { inf := has_inf.inf, inf_le_left := λ a b x, inf_le_left, inf_le_right := λ a b x, inf_le_right, le_inf := λ a b c h₀ h₁ x, le_inf (h₀ x) (h₁ x), .. (_ : partial_order (α →ₘ β)) } instance {β : Type*} [lattice β] : lattice (α →ₘ β) := { .. (_ : semilattice_sup (α →ₘ β)), .. (_ : semilattice_inf (α →ₘ β)) } @[simps] instance {β : Type*} [order_bot β] : has_bot (α →ₘ β) := { bot := ⟨λ a, ⊥, λ a b h, le_refl _⟩ } instance {β : Type*} [order_bot β] : order_bot (α →ₘ β) := { bot := has_bot.bot, bot_le := λ a x, bot_le, .. (_ : partial_order (α →ₘ β)) } @[simps] instance {β : Type*} [order_top β] : has_top (α →ₘ β) := { top := ⟨λ a, ⊤, λ a b h, le_refl _⟩ } instance {β : Type*} [order_top β] : order_top (α →ₘ β) := { top := has_top.top, le_top := λ a x, le_top, .. (_ : partial_order (α →ₘ β)) } @[simps] instance {β : Type*} [complete_lattice β] : has_Inf (α →ₘ β) := { Inf := λ s, ⟨ λ x, Inf ((λ f : _ →ₘ _, f x) '' s), λ x y h, Inf_le_Inf_of_forall_exists_le (by simp only [and_imp, exists_prop, set.mem_image, exists_exists_and_eq_and, exists_imp_distrib]; intros; subst_vars; refine ⟨_,by assumption, monotone _ h⟩) ⟩ } @[simps] instance {β : Type*} [complete_lattice β] : has_Sup (α →ₘ β) := { Sup := λ s, ⟨ λ x, Sup ((λ f : _ →ₘ _, f x) '' s), λ x y h, Sup_le_Sup_of_forall_exists_le (by simp only [and_imp, exists_prop, set.mem_image, exists_exists_and_eq_and, exists_imp_distrib]; intros; subst_vars; refine ⟨_,by assumption, monotone _ h⟩) ⟩ } @[simps Sup Inf] instance {β : Type*} [complete_lattice β] : complete_lattice (α →ₘ β) := { Sup := has_Sup.Sup, le_Sup := λ s f hf x, @le_Sup β _ ((λ f : _ →ₘ _, f x) '' s) (f x) ⟨f, hf, rfl⟩, Sup_le := λ s f hf x, @Sup_le β _ _ _ $ λ b (h : b ∈ (λ (f : α →ₘ β), f x) '' s), by rcases h with ⟨g, h, ⟨ ⟩⟩; apply hf _ h, Inf := has_Inf.Inf, le_Inf := λ s f hf x, @le_Inf β _ _ _ $ λ b (h : b ∈ (λ (f : α →ₘ β), f x) '' s), by rcases h with ⟨g, h, ⟨ ⟩⟩; apply hf _ h, Inf_le := λ s f hf x, @Inf_le β _ ((λ f : _ →ₘ _, f x) '' s) (f x) ⟨f, hf, rfl⟩, .. (_ : lattice (α →ₘ β)), .. (_ : order_top (α →ₘ β)), .. (_ : order_bot (α →ₘ β)) } end preorder_hom
5f95ff59c3202d77b46eedc15f438ff1756de0a7
947b78d97130d56365ae2ec264df196ce769371a
/src/Lean/Elab/ResolveName.lean
856d935fcb2e3929cbcb224ab7dc25317f35ab28
[ "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
5,269
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, Sebastian Ullrich -/ import Lean.Data.OpenDecl import Lean.Hygiene import Lean.Modifiers import Lean.Elab.Alias namespace Lean namespace Elab /- Global name resolution -/ /- Check whether `ns ++ id` is a valid namepace name and/or there are aliases names `ns ++ id`. -/ private def resolveQualifiedName (env : Environment) (ns : Name) (id : Name) : List Name := let resolvedId := ns ++ id; let resolvedIds := getAliases env resolvedId; if env.contains resolvedId && (!id.isAtomic || !isProtected env resolvedId) then resolvedId :: resolvedIds else -- Check whether environment contains the private version. That is, `_private.<module_name>.ns.id`. let resolvedIdPrv := mkPrivateName env resolvedId; if env.contains resolvedIdPrv then resolvedIdPrv :: resolvedIds else resolvedIds /- Check surrounding namespaces -/ private def resolveUsingNamespace (env : Environment) (id : Name) : Name → List Name | ns@(Name.str p _ _) => match resolveQualifiedName env ns id with | [] => resolveUsingNamespace p | resolvedIds => resolvedIds | _ => [] /- Check exact name -/ private def resolveExact (env : Environment) (id : Name) : Option Name := if id.isAtomic then none else let resolvedId := id.replacePrefix rootNamespace Name.anonymous; if env.contains resolvedId then some resolvedId else -- We also allow `_root` when accessing private declarations. -- If we change our minds, we should just replace `resolvedId` with `id` let resolvedIdPrv := mkPrivateName env resolvedId; if env.contains resolvedIdPrv then some resolvedIdPrv else none /- Check open namespaces -/ private def resolveOpenDecls (env : Environment) (id : Name) : List OpenDecl → List Name → List Name | [], resolvedIds => resolvedIds | OpenDecl.simple ns exs :: openDecls, resolvedIds => if exs.elem id then resolveOpenDecls openDecls resolvedIds else let newResolvedIds := resolveQualifiedName env ns id; resolveOpenDecls openDecls (newResolvedIds ++ resolvedIds) | OpenDecl.explicit openedId resolvedId :: openDecls, resolvedIds => let resolvedIds := if id == openedId then resolvedId :: resolvedIds else resolvedIds; resolveOpenDecls openDecls resolvedIds private def resolveGlobalNameAux (env : Environment) (ns : Name) (openDecls : List OpenDecl) (scpView : MacroScopesView) : Name → List String → List (Name × List String) | id@(Name.str p s _), projs => -- NOTE: we assume that macro scopes always belong to the projected constant, not the projections let id := { scpView with name := id }.review; match resolveUsingNamespace env id ns with | resolvedIds@(_ :: _) => resolvedIds.eraseDups.map $ fun id => (id, projs) | [] => match resolveExact env id with | some newId => [(newId, projs)] | none => let resolvedIds := if env.contains id then [id] else []; let idPrv := mkPrivateName env id; let resolvedIds := if env.contains idPrv then [idPrv] ++ resolvedIds else resolvedIds; let resolvedIds := resolveOpenDecls env id openDecls resolvedIds; let resolvedIds := getAliases env id ++ resolvedIds; match resolvedIds with | resolvedIds@(_ :: _) => resolvedIds.eraseDups.map $ fun id => (id, projs) | [] => resolveGlobalNameAux p (s::projs) | _, _ => [] def resolveGlobalName (env : Environment) (ns : Name) (openDecls : List OpenDecl) (id : Name) : List (Name × List String) := -- decode macro scopes from name before recursion let extractionResult := extractMacroScopes id; resolveGlobalNameAux env ns openDecls extractionResult extractionResult.name [] /- Namespace resolution -/ def resolveNamespaceUsingScope (env : Environment) (n : Name) : Name → Option Name | Name.anonymous => none | ns@(Name.str p _ _) => if env.isNamespace (ns ++ n) then some (ns ++ n) else resolveNamespaceUsingScope p | _ => unreachable! def resolveNamespaceUsingOpenDecls (env : Environment) (n : Name) : List OpenDecl → Option Name | [] => none | OpenDecl.simple ns [] :: ds => if env.isNamespace (ns ++ n) then some (ns ++ n) else resolveNamespaceUsingOpenDecls ds | _ :: ds => resolveNamespaceUsingOpenDecls ds /- Given a name `id` try to find namespace it refers to. The resolution procedure works as follows 1- If `id` is the extact name of an existing namespace, then return `id` 2- If `id` is in the scope of `namespace` commands the namespace `s_1. ... . s_n`, then return `s_1 . ... . s_i ++ n` if it is the name of an existing namespace. We search "backwards". 3- Finally, for each command `open N`, return `N ++ n` if it is the name of an existing namespace. We search "backwards" again. That is, we try the most recent `open` command first. We only consider simple `open` commands. -/ def resolveNamespace (env : Environment) (ns : Name) (openDecls : List OpenDecl) (id : Name) : Option Name := if env.isNamespace id then some id else match resolveNamespaceUsingScope env id ns with | some n => some n | none => match resolveNamespaceUsingOpenDecls env id openDecls with | some n => some n | none => none end Elab end Lean
bfa4e55ecc45ef62cf0fd38196192b790a08323e
bbecf0f1968d1fba4124103e4f6b55251d08e9c4
/src/geometry/manifold/whitney_embedding.lean
945d74a4860eeefbd8ad544e0c993aee3403e0ab
[ "Apache-2.0" ]
permissive
waynemunro/mathlib
e3fd4ff49f4cb43d4a8ded59d17be407bc5ee552
065a70810b5480d584033f7bbf8e0409480c2118
refs/heads/master
1,693,417,182,397
1,634,644,781,000
1,634,644,781,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
6,161
lean
/- Copyright (c) 2021 Yury G. Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury G. Kudryashov -/ import geometry.manifold.partition_of_unity /-! # Whitney embedding theorem In this file we prove a version of the Whitney embedding theorem: for any compact real manifold `M`, for sufficiently large `n` there exists a smooth embedding `M → ℝ^n`. ## TODO * Prove the weak Whitney embedding theorem: any `σ`-compact smooth `m`-dimensional manifold can be embedded into `ℝ^(2m+1)`. This requires a version of Sard's theorem: for a locally Lipschitz continuous map `f : ℝ^m → ℝ^n`, `m < n`, the range has Hausdorff dimension at most `m`, hence it has measure zero. ## Tags partition of unity, smooth bump function, whitney theorem -/ universes uι uE uH uM variables {ι : Type uι} {E : Type uE} [normed_group E] [normed_space ℝ E] [finite_dimensional ℝ E] {H : Type uH} [topological_space H] {I : model_with_corners ℝ E H} {M : Type uM} [topological_space M] [charted_space H M] [smooth_manifold_with_corners I M] open function filter finite_dimensional set open_locale topological_space manifold classical filter big_operators noncomputable theory namespace smooth_bump_covering /-! ### Whitney embedding theorem In this section we prove a version of the Whitney embedding theorem: for any compact real manifold `M`, for sufficiently large `n` there exists a smooth embedding `M → ℝ^n`. -/ variables [t2_space M] [fintype ι] {s : set M} (f : smooth_bump_covering ι I M s) /-- Smooth embedding of `M` into `(E × ℝ) ^ ι`. -/ def embedding_pi_tangent : C^∞⟮I, M; 𝓘(ℝ, ι → (E × ℝ)), ι → (E × ℝ)⟯ := { to_fun := λ x i, (f i x • ext_chart_at I (f.c i) x, f i x), times_cont_mdiff_to_fun := times_cont_mdiff_pi_space.2 $ λ i, ((f i).smooth_smul times_cont_mdiff_on_ext_chart_at).prod_mk_space ((f i).smooth) } local attribute [simp] lemma embedding_pi_tangent_coe : ⇑f.embedding_pi_tangent = λ x i, (f i x • ext_chart_at I (f.c i) x, f i x) := rfl lemma embedding_pi_tangent_inj_on : inj_on f.embedding_pi_tangent s := begin intros x hx y hy h, simp only [embedding_pi_tangent_coe, funext_iff] at h, obtain ⟨h₁, h₂⟩ := prod.mk.inj_iff.1 (h (f.ind x hx)), rw [f.apply_ind x hx] at h₂, rw [← h₂, f.apply_ind x hx, one_smul, one_smul] at h₁, have := f.mem_ext_chart_at_source_of_eq_one h₂.symm, exact (ext_chart_at I (f.c _)).inj_on (f.mem_ext_chart_at_ind_source x hx) this h₁ end lemma embedding_pi_tangent_injective (f : smooth_bump_covering ι I M) : injective f.embedding_pi_tangent := injective_iff_inj_on_univ.2 f.embedding_pi_tangent_inj_on lemma comp_embedding_pi_tangent_mfderiv (x : M) (hx : x ∈ s) : ((continuous_linear_map.fst ℝ E ℝ).comp (@continuous_linear_map.proj ℝ _ ι (λ _, E × ℝ) _ _ (λ _, infer_instance) (f.ind x hx))).comp (mfderiv I 𝓘(ℝ, ι → (E × ℝ)) f.embedding_pi_tangent x) = mfderiv I I (chart_at H (f.c (f.ind x hx))) x := begin set L := ((continuous_linear_map.fst ℝ E ℝ).comp (@continuous_linear_map.proj ℝ _ ι (λ _, E × ℝ) _ _ (λ _, infer_instance) (f.ind x hx))), have := L.has_mfderiv_at.comp x f.embedding_pi_tangent.mdifferentiable_at.has_mfderiv_at, convert has_mfderiv_at_unique this _, refine (has_mfderiv_at_ext_chart_at I (f.mem_chart_at_ind_source x hx)).congr_of_eventually_eq _, refine (f.eventually_eq_one x hx).mono (λ y hy, _), simp only [embedding_pi_tangent_coe, continuous_linear_map.coe_comp', (∘), continuous_linear_map.coe_fst', continuous_linear_map.proj_apply], rw [hy, pi.one_apply, one_smul] end lemma embedding_pi_tangent_ker_mfderiv (x : M) (hx : x ∈ s) : (mfderiv I 𝓘(ℝ, ι → (E × ℝ)) f.embedding_pi_tangent x).ker = ⊥ := begin apply bot_unique, rw [← (mdifferentiable_chart I (f.c (f.ind x hx))).ker_mfderiv_eq_bot (f.mem_chart_at_ind_source x hx), ← comp_embedding_pi_tangent_mfderiv], exact linear_map.ker_le_ker_comp _ _ end lemma embedding_pi_tangent_injective_mfderiv (x : M) (hx : x ∈ s) : injective (mfderiv I 𝓘(ℝ, ι → (E × ℝ)) f.embedding_pi_tangent x) := linear_map.ker_eq_bot.1 (f.embedding_pi_tangent_ker_mfderiv x hx) /-- Baby version of the Whitney weak embedding theorem: if `M` admits a finite covering by supports of bump functions, then for some `n` it can be immersed into the `n`-dimensional Euclidean space. -/ lemma exists_immersion_euclidean (f : smooth_bump_covering ι I M) : ∃ (n : ℕ) (e : M → euclidean_space ℝ (fin n)), smooth I (𝓡 n) e ∧ injective e ∧ ∀ x : M, injective (mfderiv I (𝓡 n) e x) := begin set F := euclidean_space ℝ (fin $ finrank ℝ (ι → (E × ℝ))), letI : finite_dimensional ℝ (E × ℝ) := by apply_instance, set eEF : (ι → (E × ℝ)) ≃L[ℝ] F := continuous_linear_equiv.of_finrank_eq finrank_euclidean_space_fin.symm, refine ⟨_, eEF ∘ f.embedding_pi_tangent, eEF.to_diffeomorph.smooth.comp f.embedding_pi_tangent.smooth, eEF.injective.comp f.embedding_pi_tangent_injective, λ x, _⟩, rw [mfderiv_comp _ eEF.differentiable_at.mdifferentiable_at f.embedding_pi_tangent.mdifferentiable_at, eEF.mfderiv_eq], exact eEF.injective.comp (f.embedding_pi_tangent_injective_mfderiv _ trivial) end end smooth_bump_covering /-- Baby version of the Whitney weak embedding theorem: if `M` admits a finite covering by supports of bump functions, then for some `n` it can be embedded into the `n`-dimensional Euclidean space. -/ lemma exists_embedding_euclidean_of_compact [t2_space M] [compact_space M] : ∃ (n : ℕ) (e : M → euclidean_space ℝ (fin n)), smooth I (𝓡 n) e ∧ closed_embedding e ∧ ∀ x : M, injective (mfderiv I (𝓡 n) e x) := begin rcases smooth_bump_covering.exists_is_subordinate I is_closed_univ (λ (x : M) _, univ_mem) with ⟨ι, f, -⟩, haveI := f.fintype, rcases f.exists_immersion_euclidean with ⟨n, e, hsmooth, hinj, hinj_mfderiv⟩, exact ⟨n, e, hsmooth, hsmooth.continuous.closed_embedding hinj, hinj_mfderiv⟩ end
bed32ed189593daa47f4bcdbeb0b1fe3ef01fa3d
f5f7e6fae601a5fe3cac7cc3ed353ed781d62419
/src/linear_algebra/determinant.lean
465e36daf5c81a16c0ced97e2fdf9f1b43c513e5
[ "Apache-2.0" ]
permissive
EdAyers/mathlib
9ecfb2f14bd6caad748b64c9c131befbff0fb4e0
ca5d4c1f16f9c451cf7170b10105d0051db79e1b
refs/heads/master
1,626,189,395,845
1,555,284,396,000
1,555,284,396,000
144,004,030
0
0
Apache-2.0
1,533,727,664,000
1,533,727,663,000
null
UTF-8
Lean
false
false
5,516
lean
/- Copyright (c) 2018 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau, Chris Hughes -/ import data.matrix import group_theory.subgroup group_theory.perm.sign universes u v open equiv equiv.perm finset function namespace matrix variables {n : Type u} [fintype n] [decidable_eq n] {R : Type v} [comm_ring R] local notation `ε` σ:max := ((sign σ : ℤ ) : R) definition det (M : matrix n n R) : R := univ.sum (λ (σ : perm n), ε σ * univ.prod (λ i, M (σ i) i)) @[simp] lemma det_diagonal {d : n → R} : det (diagonal d) = univ.prod d := begin refine (finset.sum_eq_single 1 _ _).trans _, { intros σ h1 h2, cases not_forall.1 (mt (equiv.ext _ _) h2) with x h3, convert ring.mul_zero _, apply finset.prod_eq_zero, { change x ∈ _, simp }, exact if_neg h3 }, { simp }, { simp } end @[simp] lemma det_zero (h : nonempty n) : det (0 : matrix n n R) = 0 := by rw [← diagonal_zero, det_diagonal, finset.prod_const, ← fintype.card, zero_pow (fintype.card_pos_iff.2 h)] @[simp] lemma det_one : det (1 : matrix n n R) = 1 := by rw [← diagonal_one]; simp [-diagonal_one] lemma det_mul_aux {M N : matrix n n R} {p : n → n} (H : ¬bijective p) : univ.sum (λ σ : perm n, (ε σ) * (univ.prod (λ x, M (σ x) (p x) * N (p x) x))) = 0 := let ⟨i, hi⟩ := classical.not_forall.1 (mt fintype.injective_iff_bijective.1 H) in let ⟨j, hij'⟩ := classical.not_forall.1 hi in have hij : p i = p j ∧ i ≠ j, from not_imp.1 hij', sum_involution (λ σ _, σ * swap i j) (λ σ _, have ∀ a, p (swap i j a) = p a := λ a, by simp only [swap_apply_def]; split_ifs; cc, have univ.prod (λ x, M (σ x) (p x)) = univ.prod (λ x, M ((σ * swap i j) x) (p x)), from prod_bij (λ a _, swap i j a) (λ _ _, mem_univ _) (by simp [this]) (λ _ _ _ _ h, (swap i j).injective h) (λ b _, ⟨swap i j b, mem_univ _, by simp⟩), by simp [sign_mul, this, sign_swap hij.2, prod_mul_distrib]) (λ σ _ _ h, hij.2 (σ.injective $ by conv {to_lhs, rw ← h}; simp)) (λ _ _, mem_univ _) (λ _ _, equiv.ext _ _ $ by simp) @[simp] lemma det_mul (M N : matrix n n R) : det (M * N) = det M * det N := calc det (M * N) = univ.sum (λ σ : perm n, (univ.pi (λ a, univ)).sum (λ (p : Π (a : n), a ∈ univ → n), ε σ * univ.attach.prod (λ i, M (σ i.1) (p i.1 (mem_univ _)) * N (p i.1 (mem_univ _)) i.1))) : by simp only [det, mul_val', prod_sum, mul_sum] ... = univ.sum (λ σ : perm n, univ.sum (λ p : n → n, ε σ * univ.prod (λ i, M (σ i) (p i) * N (p i) i))) : sum_congr rfl (λ σ _, sum_bij (λ f h i, f i (mem_univ _)) (λ _ _, mem_univ _) (by simp) (by simp [funext_iff]) (λ b _, ⟨λ i hi, b i, by simp⟩)) ... = univ.sum (λ p : n → n, univ.sum (λ σ : perm n, ε σ * univ.prod (λ i, M (σ i) (p i) * N (p i) i))) : finset.sum_comm ... = ((@univ (n → n) _).filter bijective ∪ univ.filter (λ p : n → n, ¬bijective p)).sum (λ p : n → n, univ.sum (λ σ : perm n, ε σ * univ.prod (λ i, M (σ i) (p i) * N (p i) i))) : finset.sum_congr (finset.ext.2 (by simp; tauto)) (λ _ _, rfl) ... = ((@univ (n → n) _).filter bijective).sum (λ p : n → n, univ.sum (λ σ : perm n, ε σ * univ.prod (λ i, M (σ i) (p i) * N (p i) i))) + (univ.filter (λ p : n → n, ¬bijective p)).sum (λ p : n → n, univ.sum (λ σ : perm n, ε σ * univ.prod (λ i, M (σ i) (p i) * N (p i) i))) : finset.sum_union (by simp [finset.ext]; tauto) ... = ((@univ (n → n) _).filter bijective).sum (λ p : n → n, univ.sum (λ σ : perm n, ε σ * univ.prod (λ i, M (σ i) (p i) * N (p i) i))) + (univ.filter (λ p : n → n, ¬bijective p)).sum (λ p, 0) : (add_left_inj _).2 (finset.sum_congr rfl $ λ p h, det_mul_aux (mem_filter.1 h).2) ... = ((@univ (n → n) _).filter bijective).sum (λ p : n → n, univ.sum (λ σ : perm n, ε σ * univ.prod (λ i, M (σ i) (p i) * N (p i) i))) : by simp ... = (@univ (perm n) _).sum (λ τ, univ.sum (λ σ : perm n, ε σ * univ.prod (λ i, M (σ i) (τ i) * N (τ i) i))) : sum_bij (λ p h, equiv.of_bijective (mem_filter.1 h).2) (λ _ _, mem_univ _) (λ _ _, rfl) (λ _ _ _ _ h, by injection h) (λ b _, ⟨b, mem_filter.2 ⟨mem_univ _, b.bijective⟩, eq_of_to_fun_eq rfl⟩) ... = univ.sum (λ σ : perm n, univ.sum (λ τ : perm n, (univ.prod (λ i, N (σ i) i) * ε τ) * univ.prod (λ j, M (τ j) (σ j)))) : by simp [mul_sum, det, mul_comm, mul_left_comm, prod_mul_distrib, mul_assoc] ... = univ.sum (λ σ : perm n, univ.sum (λ τ : perm n, (univ.prod (λ i, N (σ i) i) * (ε σ * ε τ)) * univ.prod (λ i, M (τ i) i))) : sum_congr rfl (λ σ _, sum_bij (λ τ _, τ * σ⁻¹) (λ _ _, mem_univ _) (λ τ _, have univ.prod (λ j, M (τ j) (σ j)) = univ.prod (λ j, M ((τ * σ⁻¹) j) j), by rw prod_univ_perm σ⁻¹; simp [mul_apply], have h : ε σ * ε (τ * σ⁻¹) = ε τ := calc ε σ * ε (τ * σ⁻¹) = ε ((τ * σ⁻¹) * σ) : by rw [mul_comm, sign_mul (τ * σ⁻¹)]; simp [sign_mul] ... = ε τ : by simp, by rw h; simp [this, mul_comm, mul_assoc, mul_left_comm]) (λ _ _ _ _, (mul_right_inj _).1) (λ τ _, ⟨τ * σ, by simp⟩)) ... = det M * det N : by simp [det, mul_assoc, mul_sum, mul_comm, mul_left_comm] instance : is_monoid_hom (det : matrix n n R → R) := { map_one := det_one, map_mul := det_mul } end matrix
57de94ebdce1ab23eefd8de135feca6e338f4519
d7189ea2ef694124821b033e533f18905b5e87ef
/galois/word.lean
a711485d58c080716a9fe29a986a3b57bdee7c73
[ "Apache-2.0" ]
permissive
digama0/lean-protocol-support
eaa7e6f8b8e0d5bbfff1f7f52bfb79a3b11b0f59
cabfa3abedbdd6fdca6e2da6fbbf91a13ed48dda
refs/heads/master
1,625,421,450,627
1,506,035,462,000
1,506,035,462,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
2,891
lean
/- This defines a simple type for bytes. -/ import data.bitvec -- A byte is a 8-bit bitvecotr definition byte := bitvec 8 instance : has_zero byte := begin unfold byte, apply_instance end instance : has_one byte := begin unfold byte, apply_instance end instance : has_add byte := begin unfold byte, apply_instance end instance : decidable_eq byte := begin unfold byte, apply_instance end protected def byte.as_hex_digit (b:bitvec 4) : string := if b = 0x0 then "0" else if b = 0x1 then "1" else if b = 0x2 then "2" else if b = 0x3 then "3" else if b = 0x4 then "4" else if b = 0x5 then "5" else if b = 0x6 then "6" else if b = 0x7 then "7" else if b = 0x8 then "8" else if b = 0x9 then "9" else if b = 0xA then "a" else if b = 0xB then "b" else if b = 0xC then "c" else if b = 0xD then "d" else if b = 0xE then "e" else "f" -- Print a byte as a pair of hex digits protected def byte.as_hex (b:byte) : string := byte.as_hex_digit (b.take 4) ++ byte.as_hex_digit (b.drop 4) instance : has_to_string byte := ⟨ λb, "0x" ++ b.as_hex ⟩ -- Map a list of bytes to a string protected def byte.list_as_ascii (l : list byte) : string := list.as_string $ list.map (λ(w:byte), char.of_nat w.to_nat) l -- Map a list of bytes to a string protected def byte.list_from_ascii (s : string) : list byte := list.map (λ(w:char), bitvec.of_nat 8 w.to_nat) s.to_list -- Print the list of bytes as a series of hex digits. def byte.list_as_hex : list byte → string := list.foldl (λs b, s ++ b.as_hex) "" definition word16 := bitvec 16 instance : has_zero word16 := begin unfold word16, apply_instance end instance : has_one word16 := begin unfold word16, apply_instance end instance : has_add word16 := begin unfold word16, apply_instance end instance : decidable_eq word16 := begin unfold word16, apply_instance end instance : has_to_string word16 := ⟨ λx, to_string (x.to_nat) ⟩ definition word32 := bitvec 32 instance : has_zero word32 := begin unfold word32, apply_instance end instance : has_one word32 := begin unfold word32, apply_instance end instance : has_add word32 := begin unfold word32, apply_instance end instance : decidable_eq word32 := begin unfold word32, apply_instance end instance : has_to_string word32 := ⟨ λx, to_string (x.to_nat) ⟩ definition word64 := bitvec 64 instance : has_zero word64 := begin unfold word64, apply_instance end instance : has_one word64 := begin unfold word64, apply_instance end instance : has_add word64 := begin unfold word64, apply_instance end instance : decidable_eq word64 := begin unfold word64, apply_instance end instance : has_to_string word64 := ⟨ λx, to_string (x.to_nat) ⟩ def byte_to_word32 (w : byte) : word32 := @bitvec.append 24 8 0 w def byte_to_word64 (w : byte) : word64 := @bitvec.append 56 8 0 w def word16_to_byte (w : word16) : byte := vector.drop 8 w
f451ec5d14e4a6ffae1cde63443db2cd704f4e4d
d1a52c3f208fa42c41df8278c3d280f075eb020c
/src/Lean/Util/OccursCheck.lean
203d26b9ce2af0b65f2b14e6da5c35c9fde244a5
[ "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
1,545
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.MetavarContext namespace Lean /-- Return true if `e` does **not** contain `mvarId` directly or indirectly This function considers assigments and delayed assignments. -/ partial def MetavarContext.occursCheck (mctx : MetavarContext) (mvarId : MVarId) (e : Expr) : Bool := if !e.hasExprMVar then true else match visit e |>.run {} with | EStateM.Result.ok .. => true | EStateM.Result.error .. => false where visitMVar (mvarId' : MVarId) : EStateM Unit ExprSet Unit := do if mvarId == mvarId' then throw () -- found else match mctx.getExprAssignment? mvarId' with | some v => visit v | none => match mctx.getDelayedAssignment? mvarId' with | some d => visit d.val | none => return () visit (e : Expr) : EStateM Unit ExprSet Unit := do if !e.hasExprMVar then return () else if (← get).contains e then return () else modify fun s => s.insert e match e with | Expr.proj _ _ s _ => visit s | 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.mdata _ b _ => visit b | Expr.app f a _ => visit f; visit a | Expr.mvar mvarId _ => visitMVar mvarId | _ => return () end Lean
e75c7dbc8129ba59211ab079d3c632e4c4caa91e
82e44445c70db0f03e30d7be725775f122d72f3e
/src/analysis/convex/exposed.lean
b451f90c60dac6e56cc07ef44ab83ad36894cb2f
[ "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
8,924
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.extreme import analysis.normed_space.basic /-! # Exposed sets This file defines exposed sets and exposed points for sets in a real vector space. An exposed subset of `A` is a subset of `A` that is the set of all maximal points of a functional (a continuous linear map `E → ℝ`) over `A`. By convention, `∅` is an exposed subset of all sets. This allows for better functioriality of the definition (the intersection of two exposed subsets is exposed, faces of a polytope form a bounded lattice). This is an analytic notion of "being on the side of". It is stronger than being extreme (see `is_exposed.is_extreme`), but weaker (for exposed points) than being a vertex. An exposed set of `A` is sometimes called a "face of `A`", but we decided to reserve this terminology to the more specific notion of a face of a polytope (sometimes hopefully soon out on mathlib!). ## Main declarations * `is_exposed A B`: States that `B` is an exposed set of `A` (in the literature, `A` is often implicit). * `is_exposed.is_extreme`: An exposed set is also extreme. ## References See chapter 8 of [Barry Simon, *Convexity*][simon2011] ## TODO * define convex independence, intrinsic frontier/interior and prove the lemmas related to exposed sets and points. * generalise to Locally Convex Topological Vector Spaces™ More not-yet-PRed stuff is available on the branch `sperner_again`. -/ open_locale classical affine big_operators open set variables {E : Type*} [normed_group E] [normed_space ℝ E] {x : E} {A B C : set E} {X : finset E} {l : E →L[ℝ] ℝ} /-- A set `B` is exposed with respect to `A` iff it maximizes some functional over `A` (and contains all points maximizing it). Written `is_exposed A B`. -/ def is_exposed (A B : set E) : Prop := B.nonempty → ∃ l : E →L[ℝ] ℝ, B = {x ∈ A | ∀ y ∈ A, l y ≤ l x} /-- A useful way to build exposed sets from intersecting `A` with halfspaces (modelled by an inequality with a functional). -/ def continuous_linear_map.to_exposed (l : E →L[ℝ] ℝ) (A : set E) : set E := {x ∈ A | ∀ y ∈ A, l y ≤ l x} lemma continuous_linear_map.to_exposed.is_exposed : is_exposed A (l.to_exposed A) := λ h, ⟨l, rfl⟩ lemma is_exposed_empty : is_exposed A ∅ := λ ⟨x, hx⟩, by { exfalso, exact hx } namespace is_exposed protected lemma subset (hAB : is_exposed A B) : B ⊆ A := begin rintro x hx, obtain ⟨_, rfl⟩ := hAB ⟨x, hx⟩, exact hx.1, end @[refl] lemma refl (A : set E) : is_exposed A A := λ ⟨w, hw⟩, ⟨0, subset.antisymm (λ x hx, ⟨hx, λ y hy, by exact le_refl 0⟩) (λ x hx, hx.1)⟩ lemma antisymm (hB : is_exposed A B) (hA : is_exposed B A) : A = B := hA.subset.antisymm hB.subset /- `is_exposed` is *not* transitive: Consider a (topologically) open cube with vertices `A₀₀₀, ..., A₁₁₁` and add to it the triangle `A₀₀₀A₀₀₁A₀₁₀`. Then `A₀₀₁A₀₁₀` is an exposed subset of `A₀₀₀A₀₀₁A₀₁₀` which is an exposed subset of the cube, but `A₀₀₁A₀₁₀` is not itself an exposed subset of the cube. -/ protected lemma mono (hC : is_exposed A C) (hBA : B ⊆ A) (hCB : C ⊆ B) : is_exposed B C := begin rintro ⟨w, hw⟩, obtain ⟨l, rfl⟩ := hC ⟨w, hw⟩, exact ⟨l, subset.antisymm (λ x hx, ⟨hCB hx, λ y hy, hx.2 y (hBA hy)⟩) (λ x hx, ⟨hBA hx.1, λ y hy, (hw.2 y hy).trans (hx.2 w (hCB hw))⟩)⟩, end /-- If `B` is an exposed subset of `A`, then `B` is the intersection of `A` with some closed halfspace. The converse is *not* true. It would require that the corresponding open halfspace doesn't intersect `A`. -/ lemma eq_inter_halfspace (hAB : is_exposed A B) : ∃ l : E →L[ℝ] ℝ, ∃ a, B = {x ∈ A | a ≤ l x} := begin obtain hB | hB := B.eq_empty_or_nonempty, { refine ⟨0, 1, _⟩, rw [hB, eq_comm, eq_empty_iff_forall_not_mem], rintro x ⟨-, h⟩, rw continuous_linear_map.zero_apply at h, linarith }, obtain ⟨l, rfl⟩ := hAB hB, obtain ⟨w, hw⟩ := hB, exact ⟨l, l w, subset.antisymm (λ x hx, ⟨hx.1, hx.2 w hw.1⟩) (λ x hx, ⟨hx.1, λ y hy, (hw.2 y hy).trans hx.2⟩)⟩, end lemma inter (hB : is_exposed A B) (hC : is_exposed A C) : is_exposed A (B ∩ C) := begin rintro ⟨w, hwB, hwC⟩, obtain ⟨l₁, rfl⟩ := hB ⟨w, hwB⟩, obtain ⟨l₂, rfl⟩ := hC ⟨w, hwC⟩, refine ⟨l₁ + l₂, subset.antisymm _ _⟩, { rintro x ⟨⟨hxA, hxB⟩, ⟨-, hxC⟩⟩, exact ⟨hxA, λ z hz, add_le_add (hxB z hz) (hxC z hz)⟩ }, rintro x ⟨hxA, hx⟩, refine ⟨⟨hxA, λ y hy, _⟩, hxA, λ y hy, _⟩, { exact (add_le_add_iff_right (l₂ x)).1 ((add_le_add (hwB.2 y hy) (hwC.2 x hxA)).trans (hx w hwB.1)) }, { exact (add_le_add_iff_left (l₁ x)).1 (le_trans (add_le_add (hwB.2 x hxA) (hwC.2 y hy)) (hx w hwB.1)) } end lemma sInter {F : finset (set E)} (hF : F.nonempty) (hAF : ∀ B ∈ F, is_exposed A B) : is_exposed A (⋂₀ F) := begin revert hF F, refine finset.induction _ _, { rintro h, exfalso, exact empty_not_nonempty h }, rintro C F _ hF _ hCF, rw [finset.coe_insert, sInter_insert], obtain rfl | hFnemp := F.eq_empty_or_nonempty, { rw [finset.coe_empty, sInter_empty, inter_univ], exact hCF C (finset.mem_singleton_self C) }, exact (hCF C (finset.mem_insert_self C F)).inter (hF hFnemp (λ B hB, hCF B(finset.mem_insert_of_mem hB))), end lemma inter_left (hC : is_exposed A C) (hCB : C ⊆ B) : is_exposed (A ∩ B) C := begin rintro ⟨w, hw⟩, obtain ⟨l, rfl⟩ := hC ⟨w, hw⟩, exact ⟨l, subset.antisymm (λ x hx, ⟨⟨hx.1, hCB hx⟩, λ y hy, hx.2 y hy.1⟩) (λ x ⟨⟨hxC, _⟩, hx⟩, ⟨hxC, λ y hy, (hw.2 y hy).trans (hx w ⟨hC.subset hw, hCB hw⟩)⟩)⟩, end lemma inter_right (hC : is_exposed B C) (hCA : C ⊆ A) : is_exposed (A ∩ B) C := begin rw inter_comm, exact hC.inter_left hCA, end protected lemma is_extreme (hAB : is_exposed A B) : is_extreme A B := begin refine ⟨hAB.subset, λ x₁ x₂ hx₁A hx₂A x hxB hx, _⟩, obtain ⟨l, rfl⟩ := hAB ⟨x, hxB⟩, have hl : convex_on univ l := l.to_linear_map.convex_on convex_univ, have hlx₁ := hxB.2 x₁ hx₁A, have hlx₂ := hxB.2 x₂ hx₂A, refine ⟨⟨hx₁A, λ y hy, _⟩, ⟨hx₂A, λ y hy, _⟩⟩, { rw hlx₁.antisymm (hl.le_left_of_right_le (mem_univ _) (mem_univ _) hx hlx₂), exact hxB.2 y hy }, { rw hlx₂.antisymm (hl.le_right_of_left_le (mem_univ _) (mem_univ _) hx hlx₁), exact hxB.2 y hy } end protected lemma is_convex (hAB : is_exposed A B) (hA : convex A) : convex B := begin obtain rfl | hB := B.eq_empty_or_nonempty, { exact convex_empty }, obtain ⟨l, rfl⟩ := hAB hB, exact λ x₁ x₂ hx₁ hx₂ a b ha hb hab, ⟨hA hx₁.1 hx₂.1 ha hb hab, λ y hy, ((l.to_linear_map.concave_on convex_univ).concave_le _ ⟨mem_univ _, hx₁.2 y hy⟩ ⟨mem_univ _, hx₂.2 y hy⟩ ha hb hab).2⟩, end lemma is_closed (hAB : is_exposed A B) (hA : is_closed A) : is_closed B := begin obtain ⟨l, a, rfl⟩ := hAB.eq_inter_halfspace, exact hA.is_closed_le continuous_on_const l.continuous.continuous_on, end lemma is_compact (hAB : is_exposed A B) (hA : is_compact A) : is_compact B := compact_of_is_closed_subset hA (hAB.is_closed hA.is_closed) hAB.subset end is_exposed /-- A point is exposed with respect to `A` iff there exists an hyperplane whose intersection with `A` is exactly that point. -/ def set.exposed_points (A : set E) : set E := {x ∈ A | ∃ l : E →L[ℝ] ℝ, ∀ y ∈ A, l y ≤ l x ∧ (l x ≤ l y → y = x)} lemma exposed_point_def : x ∈ A.exposed_points ↔ x ∈ A ∧ ∃ l : E →L[ℝ] ℝ, ∀ y ∈ A, l y ≤ l x ∧ (l x ≤ l y → y = x) := iff.rfl /-- Exposed points exactly correspond to exposed singletons. -/ lemma mem_exposed_points_iff_exposed_singleton : x ∈ A.exposed_points ↔ is_exposed A {x} := begin use λ ⟨hxA, l, hl⟩ h, ⟨l, eq.symm $ eq_singleton_iff_unique_mem.2 ⟨⟨hxA, λ y hy, (hl y hy).1⟩, λ z hz, (hl z hz.1).2 (hz.2 x hxA)⟩⟩, rintro h, obtain ⟨l, hl⟩ := h ⟨x, mem_singleton _⟩, rw [eq_comm, eq_singleton_iff_unique_mem] at hl, exact ⟨hl.1.1, l, λ y hy, ⟨hl.1.2 y hy, λ hxy, hl.2 y ⟨hy, λ z hz, (hl.1.2 z hz).trans hxy⟩⟩⟩, end lemma exposed_points_subset : A.exposed_points ⊆ A := λ x hx, hx.1 lemma exposed_points_subset_extreme_points : A.exposed_points ⊆ A.extreme_points := λ x hx, mem_extreme_points_iff_extreme_singleton.2 (mem_exposed_points_iff_exposed_singleton.1 hx).is_extreme @[simp] lemma exposed_points_empty : (∅ : set E).exposed_points = ∅ := subset_empty_iff.1 exposed_points_subset
dc1cec7f7376e2b335b08c66c947590a0836f6e9
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/extra/rec.lean
e9b3aaa014cdf22251e5ac435729f7fcea7361b0
[ "Apache-2.0" ]
permissive
leanprover-community/lean
12b87f69d92e614daea8bcc9d4de9a9ace089d0e
cce7990ea86a78bdb383e38ed7f9b5ba93c60ce0
refs/heads/master
1,687,508,156,644
1,684,951,104,000
1,684,951,104,000
169,960,991
457
107
Apache-2.0
1,686,744,372,000
1,549,790,268,000
C++
UTF-8
Lean
false
false
1,449
lean
import data.examples.vector open nat vector definition fib : nat → nat, fib 0 := 1, fib 1 := 1, fib (a+2) := (fib a ↓ lt.step (lt.base a)) + (fib (a+1) ↓ lt.base (a+1)) [wf] lt.wf definition gcd : nat → nat → nat, gcd 0 x := x, gcd x 0 := x, gcd (succ x) (succ y) := if y ≤ x then gcd (x - y) (succ y) ↓ !sigma.lex.left (lt_succ_of_le (sub_le x y)) else gcd (succ x) (y - x) ↓ !sigma.lex.right (lt_succ_of_le (sub_le y x)) [wf] sigma.lex.wf lt.wf (λ x, lt.wf) definition add : nat → nat → nat, add zero b := b, add (succ a) b := succ (add a b) definition map {A B C : Type*} (f : A → B → C) : Π {n}, vector A n → vector B n → vector C n, map nil nil := nil, map (a :: va) (b :: vb) := f a b :: map va vb definition half : nat → nat, half 0 := 0, half 1 := 0, half (x+2) := half x + 1 variables {A B : Type} inductive image_of (f : A → B) : B → Type := mk : Π a, image_of f (f a) definition inv {f : A → B} : Π b, image_of f b → A, inv ⌞f a⌟ (image_of.mk f a) := a namespace tst definition fib : nat → nat, fib 0 := 1, fib 1 := 1, fib (a+2) := fib a + fib (a+1) end tst definition simple : nat → nat → nat, simple x y := x + y definition simple2 : nat → nat → nat, simple2 (x+1) y := x + y, simple2 ⌞y+1⌟ y := y check @vector.brec_on check @vector.cases_on
1ddc5ab35004bc0fe773e527dc629dca20a10890
367134ba5a65885e863bdc4507601606690974c1
/src/category_theory/limits/shapes/finite_products.lean
7c6b9f6cfb31ae94ddcee81df1984235571f4bb0
[ "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
2,514
lean
/- Copyright (c) 2019 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import category_theory.limits.shapes.finite_limits import category_theory.limits.shapes.binary_products import category_theory.limits.shapes.terminal universes v u open category_theory namespace category_theory.limits variables (C : Type u) [category.{v} C] /-- A category has finite products if there is a chosen limit for every diagram with shape `discrete J`, where we have `[decidable_eq J]` and `[fintype J]`. -/ -- We can't simply make this an abbreviation, as we do with other `has_Xs` limits typeclasses, -- because of https://github.com/leanprover-community/lean/issues/429 def has_finite_products : Prop := Π (J : Type v) [decidable_eq J] [fintype J], has_limits_of_shape (discrete J) C attribute [class] has_finite_products instance has_limits_of_shape_discrete (J : Type v) [fintype J] [has_finite_products C] : has_limits_of_shape (discrete J) C := by { classical, exact ‹has_finite_products C› J } /-- If `C` has finite limits then it has finite products. -/ lemma has_finite_products_of_has_finite_limits [has_finite_limits C] : has_finite_products C := λ J 𝒥₁ 𝒥₂, by { resetI, apply_instance } /-- If a category has all products then in particular it has finite products. -/ lemma has_finite_products_of_has_products [has_products C] : has_finite_products C := by { dsimp [has_finite_products], apply_instance } /-- A category has finite coproducts if there is a chosen colimit for every diagram with shape `discrete J`, where we have `[decidable_eq J]` and `[fintype J]`. -/ def has_finite_coproducts : Prop := Π (J : Type v) [decidable_eq J] [fintype J], has_colimits_of_shape (discrete J) C attribute [class] has_finite_coproducts instance has_colimits_of_shape_discrete (J : Type v) [fintype J] [has_finite_coproducts C] : has_colimits_of_shape (discrete J) C := by { classical, exact ‹has_finite_coproducts C› J } /-- If `C` has finite colimits then it has finite coproducts. -/ lemma has_finite_coproducts_of_has_finite_colimits [has_finite_colimits C] : has_finite_coproducts C := λ J 𝒥₁ 𝒥₂, by { resetI, apply_instance } /-- If a category has all coproducts then in particular it has finite coproducts. -/ lemma has_finite_coproducts_of_has_coproducts [has_coproducts C] : has_finite_coproducts C := by { dsimp [has_finite_coproducts], apply_instance } end category_theory.limits
9b479a79dc2b7d55c8ff8cff0429b883295cf956
94e33a31faa76775069b071adea97e86e218a8ee
/src/data/fintype/basic.lean
33a5f9fad2d7367d75f8160916c12c1e29ff6a48
[ "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
97,453
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.array.lemmas import data.finset.fin import data.finset.option import data.finset.pi import data.finset.powerset import data.finset.prod import data.finset.sigma import data.list.nodup_equiv_fin import data.sym.basic import data.ulift import group_theory.perm.basic import order.well_founded import tactic.wlog /-! # Finite types This file defines a typeclass to state that a type is finite. ## Main declarations * `fintype α`: Typeclass saying that a type is finite. It takes as fields a `finset` and a proof that all terms of type `α` are in it. * `finset.univ`: The finset of all elements of a fintype. * `fintype.card α`: Cardinality of a fintype. Equal to `finset.univ.card`. * `perms_of_finset s`: The finset of permutations of the finset `s`. * `fintype.trunc_equiv_fin`: A fintype `α` is computably equivalent to `fin (card α)`. The `trunc`-free, noncomputable version is `fintype.equiv_fin`. * `fintype.trunc_equiv_of_card_eq` `fintype.equiv_of_card_eq`: Two fintypes of same cardinality are equivalent. See above. * `fin.equiv_iff_eq`: `fin m ≃ fin n` iff `m = n`. * `infinite α`: Typeclass saying that a type is infinite. Defined as `fintype α → false`. * `not_fintype`: No `fintype` has an `infinite` instance. * `infinite.nat_embedding`: An embedding of `ℕ` into an infinite type. We also provide the following versions of the pigeonholes principle. * `fintype.exists_ne_map_eq_of_card_lt` and `is_empty_of_card_lt`: Finitely many pigeons and pigeonholes. Weak formulation. * `fintype.exists_ne_map_eq_of_infinite`: Infinitely many pigeons in finitely many pigeonholes. Weak formulation. * `fintype.exists_infinite_fiber`: Infinitely many pigeons in finitely many pigeonholes. Strong formulation. Some more pigeonhole-like statements can be found in `data.fintype.card_embedding`. ## Instances Among others, we provide `fintype` instances for * A `subtype` of a fintype. See `fintype.subtype`. * The `option` of a fintype. * The product of two fintypes. * The sum of two fintypes. * `Prop`. and `infinite` instances for * specific types: `ℕ`, `ℤ` * type constructors: `set α`, `finset α`, `multiset α`, `list α`, `α ⊕ β`, `α × β` along with some machinery * Types which have a surjection from/an injection to a `fintype` are themselves fintypes. See `fintype.of_injective` and `fintype.of_surjective`. * Types which have an injection from/a surjection to an `infinite` type are themselves `infinite`. See `infinite.of_injective` and `infinite.of_surjective`. -/ open function open_locale nat universes u v variables {α β γ : Type*} /-- `fintype α` means that `α` is finite, i.e. there are only finitely many distinct elements of type `α`. The evidence of this is a finset `elems` (a list up to permutation without duplicates), together with a proof that everything of type `α` is in the list. -/ class fintype (α : Type*) := (elems [] : finset α) (complete : ∀ x : α, x ∈ elems) namespace finset variables [fintype α] {s : finset α} /-- `univ` is the universal finite set of type `finset α` implied from the assumption `fintype α`. -/ def univ : finset α := fintype.elems α @[simp] theorem mem_univ (x : α) : x ∈ (univ : finset α) := fintype.complete x @[simp] theorem mem_univ_val : ∀ x, x ∈ (univ : finset α).1 := mem_univ lemma eq_univ_iff_forall : s = univ ↔ ∀ x, x ∈ s := by simp [ext_iff] lemma eq_univ_of_forall : (∀ x, x ∈ s) → s = univ := eq_univ_iff_forall.2 @[simp, norm_cast] lemma coe_univ : ↑(univ : finset α) = (set.univ : set α) := by ext; simp @[simp, norm_cast] lemma coe_eq_univ : (s : set α) = set.univ ↔ s = univ := by rw [←coe_univ, coe_inj] lemma univ_nonempty_iff : (univ : finset α).nonempty ↔ nonempty α := by rw [← coe_nonempty, coe_univ, set.nonempty_iff_univ_nonempty] lemma univ_nonempty [nonempty α] : (univ : finset α).nonempty := univ_nonempty_iff.2 ‹_› lemma univ_eq_empty_iff : (univ : finset α) = ∅ ↔ is_empty α := by rw [← not_nonempty_iff, ← univ_nonempty_iff, not_nonempty_iff_eq_empty] @[simp] lemma univ_eq_empty [is_empty α] : (univ : finset α) = ∅ := univ_eq_empty_iff.2 ‹_› @[simp] lemma univ_unique [unique α] : (univ : finset α) = {default} := finset.ext $ λ x, iff_of_true (mem_univ _) $ mem_singleton.2 $ subsingleton.elim x default @[simp] theorem subset_univ (s : finset α) : s ⊆ univ := λ a _, mem_univ a instance : order_top (finset α) := { top := univ, le_top := subset_univ } section boolean_algebra variables [decidable_eq α] {a : α} instance : boolean_algebra (finset α) := { compl := λ s, univ \ s, inf_compl_le_bot := λ s x hx, by simpa using hx, top_le_sup_compl := λ s x hx, by simp, sdiff_eq := λ s t, by simp [ext_iff, compl], ..finset.order_top, ..finset.order_bot, ..finset.generalized_boolean_algebra } lemma compl_eq_univ_sdiff (s : finset α) : sᶜ = univ \ s := rfl @[simp] lemma mem_compl : a ∈ sᶜ ↔ a ∉ s := by simp [compl_eq_univ_sdiff] lemma not_mem_compl : a ∉ sᶜ ↔ a ∈ s := by rw [mem_compl, not_not] @[simp, norm_cast] lemma coe_compl (s : finset α) : ↑(sᶜ) = (↑s : set α)ᶜ := set.ext $ λ x, mem_compl @[simp] lemma compl_empty : (∅ : finset α)ᶜ = univ := compl_bot @[simp] lemma union_compl (s : finset α) : s ∪ sᶜ = univ := sup_compl_eq_top @[simp] lemma inter_compl (s : finset α) : s ∩ sᶜ = ∅ := inf_compl_eq_bot @[simp] lemma compl_union (s t : finset α) : (s ∪ t)ᶜ = sᶜ ∩ tᶜ := compl_sup @[simp] lemma compl_inter (s t : finset α) : (s ∩ t)ᶜ = sᶜ ∪ tᶜ := compl_inf @[simp] lemma compl_erase : (s.erase a)ᶜ = insert a sᶜ := by { ext, simp only [or_iff_not_imp_left, mem_insert, not_and, mem_compl, mem_erase] } @[simp] lemma compl_insert : (insert a s)ᶜ = sᶜ.erase a := by { ext, simp only [not_or_distrib, mem_insert, iff_self, mem_compl, mem_erase] } @[simp] lemma insert_compl_self (x : α) : insert x ({x}ᶜ : finset α) = univ := by rw [←compl_erase, erase_singleton, compl_empty] @[simp] lemma compl_filter (p : α → Prop) [decidable_pred p] [Π x, decidable (¬p x)] : (univ.filter p)ᶜ = univ.filter (λ x, ¬p x) := (filter_not _ _).symm lemma compl_ne_univ_iff_nonempty (s : finset α) : sᶜ ≠ univ ↔ s.nonempty := by simp [eq_univ_iff_forall, finset.nonempty] lemma compl_singleton (a : α) : ({a} : finset α)ᶜ = univ.erase a := by rw [compl_eq_univ_sdiff, sdiff_singleton_eq_erase] lemma insert_inj_on' (s : finset α) : set.inj_on (λ a, insert a s) (sᶜ : finset α) := by { rw coe_compl, exact s.insert_inj_on } lemma image_univ_of_surjective [fintype β] {f : β → α} (hf : surjective f) : univ.image f = univ := eq_univ_of_forall $ hf.forall.2 $ λ _, mem_image_of_mem _ $ mem_univ _ end boolean_algebra lemma map_univ_of_surjective [fintype β] {f : β ↪ α} (hf : surjective f) : univ.map f = univ := eq_univ_of_forall $ hf.forall.2 $ λ _, mem_map_of_mem _ $ mem_univ _ @[simp] lemma map_univ_equiv [fintype β] (f : β ≃ α) : univ.map f.to_embedding = univ := map_univ_of_surjective f.surjective @[simp] lemma univ_inter [decidable_eq α] (s : finset α) : univ ∩ s = s := ext $ λ a, by simp @[simp] lemma inter_univ [decidable_eq α] (s : finset α) : s ∩ univ = s := by rw [inter_comm, univ_inter] @[simp] lemma piecewise_univ [Π i : α, decidable (i ∈ (univ : finset α))] {δ : α → Sort*} (f g : Π i, δ i) : univ.piecewise f g = f := by { ext i, simp [piecewise] } lemma piecewise_compl [decidable_eq α] (s : finset α) [Π i : α, decidable (i ∈ s)] [Π i : α, decidable (i ∈ sᶜ)] {δ : α → Sort*} (f g : Π i, δ i) : sᶜ.piecewise f g = s.piecewise g f := by { ext i, simp [piecewise] } @[simp] lemma piecewise_erase_univ {δ : α → Sort*} [decidable_eq α] (a : α) (f g : Π a, δ a) : (finset.univ.erase a).piecewise f g = function.update f a (g a) := by rw [←compl_singleton, piecewise_compl, piecewise_singleton] lemma univ_map_equiv_to_embedding {α β : Type*} [fintype α] [fintype β] (e : α ≃ β) : univ.map e.to_embedding = univ := eq_univ_iff_forall.mpr (λ b, mem_map.mpr ⟨e.symm b, mem_univ _, by simp⟩) @[simp] lemma univ_filter_exists (f : α → β) [fintype β] [decidable_pred (λ y, ∃ x, f x = y)] [decidable_eq β] : finset.univ.filter (λ y, ∃ x, f x = y) = finset.univ.image f := by { ext, simp } /-- Note this is a special case of `(finset.image_preimage f univ _).symm`. -/ lemma univ_filter_mem_range (f : α → β) [fintype β] [decidable_pred (λ y, y ∈ set.range f)] [decidable_eq β] : finset.univ.filter (λ y, y ∈ set.range f) = finset.univ.image f := univ_filter_exists f lemma coe_filter_univ (p : α → Prop) [decidable_pred p] : (univ.filter p : set α) = {x | p x} := by rw [coe_filter, coe_univ, set.sep_univ] /-- A special case of `finset.sup_eq_supr` that omits the useless `x ∈ univ` binder. -/ lemma sup_univ_eq_supr [complete_lattice β] (f : α → β) : finset.univ.sup f = supr f := (sup_eq_supr _ f).trans $ congr_arg _ $ funext $ λ a, supr_pos (mem_univ _) /-- A special case of `finset.inf_eq_infi` that omits the useless `x ∈ univ` binder. -/ lemma inf_univ_eq_infi [complete_lattice β] (f : α → β) : finset.univ.inf f = infi f := sup_univ_eq_supr (by exact f : α → βᵒᵈ) @[simp] lemma fold_inf_univ [semilattice_inf α] [order_bot α] (a : α) : finset.univ.fold (⊓) a (λ x, x) = ⊥ := eq_bot_iff.2 $ ((finset.fold_op_rel_iff_and $ @_root_.le_inf_iff α _).1 le_rfl).2 ⊥ $ finset.mem_univ _ @[simp] lemma fold_sup_univ [semilattice_sup α] [order_top α] (a : α) : finset.univ.fold (⊔) a (λ x, x) = ⊤ := @fold_inf_univ αᵒᵈ ‹fintype α› _ _ _ end finset open finset function namespace fintype instance decidable_pi_fintype {α} {β : α → Type*} [∀ a, decidable_eq (β a)] [fintype α] : decidable_eq (Π a, β a) := λ f g, decidable_of_iff (∀ a ∈ fintype.elems α, f a = g a) (by simp [function.funext_iff, fintype.complete]) instance decidable_forall_fintype {p : α → Prop} [decidable_pred p] [fintype α] : decidable (∀ a, p a) := decidable_of_iff (∀ a ∈ @univ α _, p a) (by simp) instance decidable_exists_fintype {p : α → Prop} [decidable_pred p] [fintype α] : decidable (∃ a, p a) := decidable_of_iff (∃ a ∈ @univ α _, p a) (by simp) instance decidable_mem_range_fintype [fintype α] [decidable_eq β] (f : α → β) : decidable_pred (∈ set.range f) := λ x, fintype.decidable_exists_fintype section bundled_homs instance decidable_eq_equiv_fintype [decidable_eq β] [fintype α] : decidable_eq (α ≃ β) := λ a b, decidable_of_iff (a.1 = b.1) equiv.coe_fn_injective.eq_iff instance decidable_eq_embedding_fintype [decidable_eq β] [fintype α] : decidable_eq (α ↪ β) := λ a b, decidable_of_iff ((a : α → β) = b) function.embedding.coe_injective.eq_iff @[to_additive] instance decidable_eq_one_hom_fintype [decidable_eq β] [fintype α] [has_one α] [has_one β]: decidable_eq (one_hom α β) := λ a b, decidable_of_iff ((a : α → β) = b) (injective.eq_iff one_hom.coe_inj) @[to_additive] instance decidable_eq_mul_hom_fintype [decidable_eq β] [fintype α] [has_mul α] [has_mul β]: decidable_eq (α →ₙ* β) := λ a b, decidable_of_iff ((a : α → β) = b) (injective.eq_iff mul_hom.coe_inj) @[to_additive] instance decidable_eq_monoid_hom_fintype [decidable_eq β] [fintype α] [mul_one_class α] [mul_one_class β]: decidable_eq (α →* β) := λ a b, decidable_of_iff ((a : α → β) = b) (injective.eq_iff monoid_hom.coe_inj) instance decidable_eq_monoid_with_zero_hom_fintype [decidable_eq β] [fintype α] [mul_zero_one_class α] [mul_zero_one_class β] : decidable_eq (α →*₀ β) := λ a b, decidable_of_iff ((a : α → β) = b) (injective.eq_iff monoid_with_zero_hom.coe_inj) instance decidable_eq_ring_hom_fintype [decidable_eq β] [fintype α] [semiring α] [semiring β]: decidable_eq (α →+* β) := λ a b, decidable_of_iff ((a : α → β) = b) (injective.eq_iff ring_hom.coe_inj) end bundled_homs instance decidable_injective_fintype [decidable_eq α] [decidable_eq β] [fintype α] : decidable_pred (injective : (α → β) → Prop) := λ x, by unfold injective; apply_instance instance decidable_surjective_fintype [decidable_eq β] [fintype α] [fintype β] : decidable_pred (surjective : (α → β) → Prop) := λ x, by unfold surjective; apply_instance instance decidable_bijective_fintype [decidable_eq α] [decidable_eq β] [fintype α] [fintype β] : decidable_pred (bijective : (α → β) → Prop) := λ x, by unfold bijective; apply_instance instance decidable_right_inverse_fintype [decidable_eq α] [fintype α] (f : α → β) (g : β → α) : decidable (function.right_inverse f g) := show decidable (∀ x, g (f x) = x), by apply_instance instance decidable_left_inverse_fintype [decidable_eq β] [fintype β] (f : α → β) (g : β → α) : decidable (function.left_inverse f g) := show decidable (∀ x, f (g x) = x), by apply_instance lemma exists_max [fintype α] [nonempty α] {β : Type*} [linear_order β] (f : α → β) : ∃ x₀ : α, ∀ x, f x ≤ f x₀ := by simpa using exists_max_image univ f univ_nonempty lemma exists_min [fintype α] [nonempty α] {β : Type*} [linear_order β] (f : α → β) : ∃ x₀ : α, ∀ x, f x₀ ≤ f x := by simpa using exists_min_image univ f univ_nonempty /-- Construct a proof of `fintype α` from a universal multiset -/ def of_multiset [decidable_eq α] (s : multiset α) (H : ∀ x : α, x ∈ s) : fintype α := ⟨s.to_finset, by simpa using H⟩ /-- Construct a proof of `fintype α` from a universal list -/ def of_list [decidable_eq α] (l : list α) (H : ∀ x : α, x ∈ l) : fintype α := ⟨l.to_finset, by simpa using H⟩ theorem exists_univ_list (α) [fintype α] : ∃ l : list α, l.nodup ∧ ∀ x : α, x ∈ l := let ⟨l, e⟩ := quotient.exists_rep (@univ α _).1 in by have := and.intro univ.2 mem_univ_val; exact ⟨_, by rwa ←e at this⟩ /-- `card α` is the number of elements in `α`, defined when `α` is a fintype. -/ def card (α) [fintype α] : ℕ := (@univ α _).card /-- There is (computably) an equivalence between `α` and `fin (card α)`. Since it is not unique and depends on which permutation of the universe list is used, the equivalence is wrapped in `trunc` to preserve computability. See `fintype.equiv_fin` for the noncomputable version, and `fintype.trunc_equiv_fin_of_card_eq` and `fintype.equiv_fin_of_card_eq` for an equiv `α ≃ fin n` given `fintype.card α = n`. See `fintype.trunc_fin_bijection` for a version without `[decidable_eq α]`. -/ def trunc_equiv_fin (α) [decidable_eq α] [fintype α] : trunc (α ≃ fin (card α)) := by { unfold card finset.card, exact quot.rec_on_subsingleton (@univ α _).1 (λ l (h : ∀ x : α, x ∈ l) (nd : l.nodup), trunc.mk (nd.nth_le_equiv_of_forall_mem_list _ h).symm) mem_univ_val univ.2 } /-- There is (noncomputably) an equivalence between `α` and `fin (card α)`. See `fintype.trunc_equiv_fin` for the computable version, and `fintype.trunc_equiv_fin_of_card_eq` and `fintype.equiv_fin_of_card_eq` for an equiv `α ≃ fin n` given `fintype.card α = n`. -/ noncomputable def equiv_fin (α) [fintype α] : α ≃ fin (card α) := by { letI := classical.dec_eq α, exact (trunc_equiv_fin α).out } /-- There is (computably) a bijection between `fin (card α)` and `α`. Since it is not unique and depends on which permutation of the universe list is used, the bijection is wrapped in `trunc` to preserve computability. See `fintype.trunc_equiv_fin` for a version that gives an equivalence given `[decidable_eq α]`. -/ def trunc_fin_bijection (α) [fintype α] : trunc {f : fin (card α) → α // bijective f} := by { dunfold card finset.card, exact quot.rec_on_subsingleton (@univ α _).1 (λ l (h : ∀ x : α, x ∈ l) (nd : l.nodup), trunc.mk (nd.nth_le_bijection_of_forall_mem_list _ h)) mem_univ_val univ.2 } instance (α : Type*) : subsingleton (fintype α) := ⟨λ ⟨s₁, h₁⟩ ⟨s₂, h₂⟩, by congr; simp [finset.ext_iff, h₁, h₂]⟩ /-- Given a predicate that can be represented by a finset, the subtype associated to the predicate is a fintype. -/ protected def subtype {p : α → Prop} (s : finset α) (H : ∀ x : α, x ∈ s ↔ p x) : fintype {x // p x} := ⟨⟨s.1.pmap subtype.mk (λ x, (H x).1), s.nodup.pmap $ λ a _ b _, congr_arg subtype.val⟩, λ ⟨x, px⟩, multiset.mem_pmap.2 ⟨x, (H x).2 px, rfl⟩⟩ theorem subtype_card {p : α → Prop} (s : finset α) (H : ∀ x : α, x ∈ s ↔ p x) : @card {x // p x} (fintype.subtype s H) = s.card := multiset.card_pmap _ _ _ theorem card_of_subtype {p : α → Prop} (s : finset α) (H : ∀ x : α, x ∈ s ↔ p x) [fintype {x // p x}] : card {x // p x} = s.card := by { rw ← subtype_card s H, congr } /-- Construct a fintype from a finset with the same elements. -/ def of_finset {p : set α} (s : finset α) (H : ∀ x, x ∈ s ↔ x ∈ p) : fintype p := fintype.subtype s H @[simp] theorem card_of_finset {p : set α} (s : finset α) (H : ∀ x, x ∈ s ↔ x ∈ p) : @fintype.card p (of_finset s H) = s.card := fintype.subtype_card s H theorem card_of_finset' {p : set α} (s : finset α) (H : ∀ x, x ∈ s ↔ x ∈ p) [fintype p] : fintype.card p = s.card := by rw ←card_of_finset s H; congr /-- If `f : α → β` is a bijection and `α` is a fintype, then `β` is also a fintype. -/ def of_bijective [fintype α] (f : α → β) (H : function.bijective f) : fintype β := ⟨univ.map ⟨f, H.1⟩, λ b, let ⟨a, e⟩ := H.2 b in e ▸ mem_map_of_mem _ (mem_univ _)⟩ /-- If `f : α → β` is a surjection and `α` is a fintype, then `β` is also a fintype. -/ def of_surjective [decidable_eq β] [fintype α] (f : α → β) (H : function.surjective f) : fintype β := ⟨univ.image f, λ b, let ⟨a, e⟩ := H b in e ▸ mem_image_of_mem _ (mem_univ _)⟩ end fintype section inv namespace function variables [fintype α] [decidable_eq β] namespace injective variables {f : α → β} (hf : function.injective f) /-- The inverse of an `hf : injective` function `f : α → β`, of the type `↥(set.range f) → α`. This is the computable version of `function.inv_fun` that requires `fintype α` and `decidable_eq β`, or the function version of applying `(equiv.of_injective f hf).symm`. This function should not usually be used for actual computation because for most cases, an explicit inverse can be stated that has better computational properties. This function computes by checking all terms `a : α` to find the `f a = b`, so it is O(N) where `N = fintype.card α`. -/ def inv_of_mem_range : set.range f → α := λ b, finset.choose (λ a, f a = b) finset.univ ((exists_unique_congr (by simp)).mp (hf.exists_unique_of_mem_range b.property)) lemma left_inv_of_inv_of_mem_range (b : set.range f) : f (hf.inv_of_mem_range b) = b := (finset.choose_spec (λ a, f a = b) _ _).right @[simp] lemma right_inv_of_inv_of_mem_range (a : α) : hf.inv_of_mem_range (⟨f a, set.mem_range_self a⟩) = a := hf (finset.choose_spec (λ a', f a' = f a) _ _).right lemma inv_fun_restrict [nonempty α] : (set.range f).restrict (inv_fun f) = hf.inv_of_mem_range := begin ext ⟨b, h⟩, apply hf, simp [hf.left_inv_of_inv_of_mem_range, @inv_fun_eq _ _ _ f b (set.mem_range.mp h)] end lemma inv_of_mem_range_surjective : function.surjective hf.inv_of_mem_range := λ a, ⟨⟨f a, set.mem_range_self a⟩, by simp⟩ end injective namespace embedding variables (f : α ↪ β) (b : set.range f) /-- The inverse of an embedding `f : α ↪ β`, of the type `↥(set.range f) → α`. This is the computable version of `function.inv_fun` that requires `fintype α` and `decidable_eq β`, or the function version of applying `(equiv.of_injective f f.injective).symm`. This function should not usually be used for actual computation because for most cases, an explicit inverse can be stated that has better computational properties. This function computes by checking all terms `a : α` to find the `f a = b`, so it is O(N) where `N = fintype.card α`. -/ def inv_of_mem_range : α := f.injective.inv_of_mem_range b @[simp] lemma left_inv_of_inv_of_mem_range : f (f.inv_of_mem_range b) = b := f.injective.left_inv_of_inv_of_mem_range b @[simp] lemma right_inv_of_inv_of_mem_range (a : α) : f.inv_of_mem_range ⟨f a, set.mem_range_self a⟩ = a := f.injective.right_inv_of_inv_of_mem_range a lemma inv_fun_restrict [nonempty α] : (set.range f).restrict (inv_fun f) = f.inv_of_mem_range := begin ext ⟨b, h⟩, apply f.injective, simp [f.left_inv_of_inv_of_mem_range, @inv_fun_eq _ _ _ f b (set.mem_range.mp h)] end lemma inv_of_mem_range_surjective : function.surjective f.inv_of_mem_range := λ a, ⟨⟨f a, set.mem_range_self a⟩, by simp⟩ end embedding end function end inv namespace fintype /-- Given an injective function to a fintype, the domain is also a fintype. This is noncomputable because injectivity alone cannot be used to construct preimages. -/ noncomputable def of_injective [fintype β] (f : α → β) (H : function.injective f) : fintype α := by letI := classical.dec; exact if hα : nonempty α then by letI := classical.inhabited_of_nonempty hα; exact of_surjective (inv_fun f) (inv_fun_surjective H) else ⟨∅, λ x, (hα ⟨x⟩).elim⟩ /-- If `f : α ≃ β` and `α` is a fintype, then `β` is also a fintype. -/ def of_equiv (α : Type*) [fintype α] (f : α ≃ β) : fintype β := of_bijective _ f.bijective theorem of_equiv_card [fintype α] (f : α ≃ β) : @card β (of_equiv α f) = card α := multiset.card_map _ _ theorem card_congr {α β} [fintype α] [fintype β] (f : α ≃ β) : card α = card β := by rw ← of_equiv_card f; congr @[congr] lemma card_congr' {α β} [fintype α] [fintype β] (h : α = β) : card α = card β := card_congr (by rw h) section variables [fintype α] [fintype β] /-- If the cardinality of `α` is `n`, there is computably a bijection between `α` and `fin n`. See `fintype.equiv_fin_of_card_eq` for the noncomputable definition, and `fintype.trunc_equiv_fin` and `fintype.equiv_fin` for the bijection `α ≃ fin (card α)`. -/ def trunc_equiv_fin_of_card_eq [decidable_eq α] {n : ℕ} (h : fintype.card α = n) : trunc (α ≃ fin n) := (trunc_equiv_fin α).map (λ e, e.trans (fin.cast h).to_equiv) /-- If the cardinality of `α` is `n`, there is noncomputably a bijection between `α` and `fin n`. See `fintype.trunc_equiv_fin_of_card_eq` for the computable definition, and `fintype.trunc_equiv_fin` and `fintype.equiv_fin` for the bijection `α ≃ fin (card α)`. -/ noncomputable def equiv_fin_of_card_eq {n : ℕ} (h : fintype.card α = n) : α ≃ fin n := by { letI := classical.dec_eq α, exact (trunc_equiv_fin_of_card_eq h).out } /-- Two `fintype`s with the same cardinality are (computably) in bijection. See `fintype.equiv_of_card_eq` for the noncomputable version, and `fintype.trunc_equiv_fin_of_card_eq` and `fintype.equiv_fin_of_card_eq` for the specialization to `fin`. -/ def trunc_equiv_of_card_eq [decidable_eq α] [decidable_eq β] (h : card α = card β) : trunc (α ≃ β) := (trunc_equiv_fin_of_card_eq h).bind (λ e, (trunc_equiv_fin β).map (λ e', e.trans e'.symm)) /-- Two `fintype`s with the same cardinality are (noncomputably) in bijection. See `fintype.trunc_equiv_of_card_eq` for the computable version, and `fintype.trunc_equiv_fin_of_card_eq` and `fintype.equiv_fin_of_card_eq` for the specialization to `fin`. -/ noncomputable def equiv_of_card_eq (h : card α = card β) : α ≃ β := by { letI := classical.dec_eq α, letI := classical.dec_eq β, exact (trunc_equiv_of_card_eq h).out } end theorem card_eq {α β} [F : fintype α] [G : fintype β] : card α = card β ↔ nonempty (α ≃ β) := ⟨λ h, by { haveI := classical.prop_decidable, exact (trunc_equiv_of_card_eq h).nonempty }, λ ⟨f⟩, card_congr f⟩ /-- Any subsingleton type with a witness is a fintype (with one term). -/ def of_subsingleton (a : α) [subsingleton α] : fintype α := ⟨{a}, λ b, finset.mem_singleton.2 (subsingleton.elim _ _)⟩ @[simp] theorem univ_of_subsingleton (a : α) [subsingleton α] : @univ _ (of_subsingleton a) = {a} := rfl /-- Note: this lemma is specifically about `fintype.of_subsingleton`. For a statement about arbitrary `fintype` instances, use either `fintype.card_le_one_iff_subsingleton` or `fintype.card_unique`. -/ @[simp] theorem card_of_subsingleton (a : α) [subsingleton α] : @fintype.card _ (of_subsingleton a) = 1 := rfl @[simp] theorem card_unique [unique α] [h : fintype α] : fintype.card α = 1 := subsingleton.elim (of_subsingleton default) h ▸ card_of_subsingleton _ @[priority 100] -- see Note [lower instance priority] instance of_is_empty [is_empty α] : fintype α := ⟨∅, is_empty_elim⟩ /-- Note: this lemma is specifically about `fintype.of_is_empty`. For a statement about arbitrary `fintype` instances, use `finset.univ_eq_empty`. -/ -- no-lint since while `finset.univ_eq_empty` can prove this, it isn't applicable for `dsimp`. @[simp, nolint simp_nf] theorem univ_of_is_empty [is_empty α] : @univ α _ = ∅ := rfl /-- Note: this lemma is specifically about `fintype.of_is_empty`. For a statement about arbitrary `fintype` instances, use `fintype.card_eq_zero_iff`. -/ @[simp] theorem card_of_is_empty [is_empty α] : fintype.card α = 0 := rfl open_locale classical variables (α) /-- Any subsingleton type is (noncomputably) a fintype (with zero or one term). -/ @[priority 5] -- see Note [lower instance priority] noncomputable instance of_subsingleton' [subsingleton α] : fintype α := if h : nonempty α then of_subsingleton (nonempty.some h) else @fintype.of_is_empty _ $ not_nonempty_iff.mp h end fintype namespace set /-- Construct a finset enumerating a set `s`, given a `fintype` instance. -/ def to_finset (s : set α) [fintype s] : finset α := ⟨(@finset.univ s _).1.map subtype.val, finset.univ.nodup.map $ λ a b, subtype.eq⟩ @[congr] lemma to_finset_congr {s t : set α} [fintype s] [fintype t] (h : s = t) : to_finset s = to_finset t := by cc @[simp] theorem mem_to_finset {s : set α} [fintype s] {a : α} : a ∈ s.to_finset ↔ a ∈ s := by simp [to_finset] @[simp] theorem mem_to_finset_val {s : set α} [fintype s] {a : α} : a ∈ s.to_finset.1 ↔ a ∈ s := mem_to_finset /-- Membership of a set with a `fintype` instance is decidable. Using this as an instance leads to potential loops with `subtype.fintype` under certain decidability assumptions, so it should only be declared a local instance. -/ def decidable_mem_of_fintype [decidable_eq α] (s : set α) [fintype s] (a) : decidable (a ∈ s) := decidable_of_iff _ mem_to_finset -- We use an arbitrary `[fintype s]` instance here, -- not necessarily coming from a `[fintype α]`. @[simp] lemma to_finset_card {α : Type*} (s : set α) [fintype s] : s.to_finset.card = fintype.card s := multiset.card_map subtype.val finset.univ.val @[simp] theorem coe_to_finset (s : set α) [fintype s] : (↑s.to_finset : set α) = s := set.ext $ λ _, mem_to_finset @[simp] theorem to_finset_inj {s t : set α} [fintype s] [fintype t] : s.to_finset = t.to_finset ↔ s = t := ⟨λ h, by rw [←s.coe_to_finset, h, t.coe_to_finset], λ h, by simp [h]; congr⟩ @[simp, mono] theorem to_finset_mono {s t : set α} [fintype s] [fintype t] : s.to_finset ⊆ t.to_finset ↔ s ⊆ t := by simp [finset.subset_iff, set.subset_def] @[simp, mono] theorem to_finset_strict_mono {s t : set α} [fintype s] [fintype t] : s.to_finset ⊂ t.to_finset ↔ s ⊂ t := by simp only [finset.ssubset_def, to_finset_mono, ssubset_def] @[simp] theorem to_finset_disjoint_iff [decidable_eq α] {s t : set α} [fintype s] [fintype t] : disjoint s.to_finset t.to_finset ↔ disjoint s t := by simp only [←disjoint_coe, coe_to_finset] lemma to_finset_inter {α : Type*} [decidable_eq α] (s t : set α) [fintype (s ∩ t : set α)] [fintype s] [fintype t] : (s ∩ t).to_finset = s.to_finset ∩ t.to_finset := by { ext, simp } lemma to_finset_union {α : Type*} [decidable_eq α] (s t : set α) [fintype (s ∪ t : set α)] [fintype s] [fintype t] : (s ∪ t).to_finset = s.to_finset ∪ t.to_finset := by { ext, simp } lemma to_finset_diff {α : Type*} [decidable_eq α] (s t : set α) [fintype s] [fintype t] [fintype (s \ t : set α)] : (s \ t).to_finset = s.to_finset \ t.to_finset := by { ext, simp } lemma to_finset_ne_eq_erase {α : Type*} [decidable_eq α] [fintype α] (a : α) [fintype {x : α | x ≠ a}] : {x : α | x ≠ a}.to_finset = finset.univ.erase a := by { ext, simp } theorem to_finset_compl [decidable_eq α] [fintype α] (s : set α) [fintype s] [fintype ↥sᶜ] : (sᶜ).to_finset = s.to_finsetᶜ := by { ext, simp } /- TODO Without the coercion arrow (`↥`) there is an elaboration bug; it essentially infers `fintype.{v} (set.univ.{u} : set α)` with `v` and `u` distinct. Reported in leanprover-community/lean#672 -/ @[simp] lemma to_finset_univ [fintype ↥(set.univ : set α)] [fintype α] : (set.univ : set α).to_finset = finset.univ := by { ext, simp } @[simp] lemma to_finset_range [decidable_eq α] [fintype β] (f : β → α) [fintype (set.range f)] : (set.range f).to_finset = finset.univ.image f := by { ext, simp } /- TODO The `↥` circumvents an elaboration bug. See comment on `set.to_finset_univ`. -/ lemma to_finset_singleton (a : α) [fintype ↥({a} : set α)] : ({a} : set α).to_finset = {a} := by { ext, simp } /- TODO The `↥` circumvents an elaboration bug. See comment on `set.to_finset_univ`. -/ @[simp] lemma to_finset_insert [decidable_eq α] {a : α} {s : set α} [fintype ↥(insert a s : set α)] [fintype s] : (insert a s).to_finset = insert a s.to_finset := by { ext, simp } lemma filter_mem_univ_eq_to_finset [fintype α] (s : set α) [fintype s] [decidable_pred (∈ s)] : finset.univ.filter (∈ s) = s.to_finset := by { ext, simp only [mem_filter, finset.mem_univ, true_and, mem_to_finset] } end set @[simp] lemma finset.to_finset_coe (s : finset α) [fintype ↥(s : set α)] : (s : set α).to_finset = s := ext $ λ _, set.mem_to_finset lemma finset.card_univ [fintype α] : (finset.univ : finset α).card = fintype.card α := rfl lemma finset.eq_univ_of_card [fintype α] (s : finset α) (hs : s.card = fintype.card α) : s = univ := eq_of_subset_of_card_le (subset_univ _) $ by rw [hs, finset.card_univ] lemma finset.card_eq_iff_eq_univ [fintype α] (s : finset α) : s.card = fintype.card α ↔ s = finset.univ := ⟨s.eq_univ_of_card, by { rintro rfl, exact finset.card_univ, }⟩ lemma finset.card_le_univ [fintype α] (s : finset α) : s.card ≤ fintype.card α := card_le_of_subset (subset_univ s) lemma finset.card_lt_univ_of_not_mem [fintype α] {s : finset α} {x : α} (hx : x ∉ s) : s.card < fintype.card α := card_lt_card ⟨subset_univ s, not_forall.2 ⟨x, λ hx', hx (hx' $ mem_univ x)⟩⟩ lemma finset.card_lt_iff_ne_univ [fintype α] (s : finset α) : s.card < fintype.card α ↔ s ≠ finset.univ := s.card_le_univ.lt_iff_ne.trans (not_iff_not_of_iff s.card_eq_iff_eq_univ) lemma finset.card_compl_lt_iff_nonempty [fintype α] [decidable_eq α] (s : finset α) : sᶜ.card < fintype.card α ↔ s.nonempty := sᶜ.card_lt_iff_ne_univ.trans s.compl_ne_univ_iff_nonempty lemma finset.card_univ_diff [decidable_eq α] [fintype α] (s : finset α) : (finset.univ \ s).card = fintype.card α - s.card := finset.card_sdiff (subset_univ s) lemma finset.card_compl [decidable_eq α] [fintype α] (s : finset α) : sᶜ.card = fintype.card α - s.card := finset.card_univ_diff s lemma fintype.card_compl_set [fintype α] (s : set α) [fintype s] [fintype ↥sᶜ] : fintype.card ↥sᶜ = fintype.card α - fintype.card s := begin classical, rw [← set.to_finset_card, ← set.to_finset_card, ← finset.card_compl, set.to_finset_compl] end instance (n : ℕ) : fintype (fin n) := ⟨finset.fin_range n, finset.mem_fin_range⟩ lemma fin.univ_def (n : ℕ) : (univ : finset (fin n)) = finset.fin_range n := rfl @[simp] theorem fintype.card_fin (n : ℕ) : fintype.card (fin n) = n := list.length_fin_range n @[simp] lemma finset.card_fin (n : ℕ) : finset.card (finset.univ : finset (fin n)) = n := by rw [finset.card_univ, fintype.card_fin] /-- `fin` as a map from `ℕ` to `Type` is injective. Note that since this is a statement about equality of types, using it should be avoided if possible. -/ lemma fin_injective : function.injective fin := λ m n h, (fintype.card_fin m).symm.trans $ (fintype.card_congr $ equiv.cast h).trans (fintype.card_fin n) /-- A reversed version of `fin.cast_eq_cast` that is easier to rewrite with. -/ theorem fin.cast_eq_cast' {n m : ℕ} (h : fin n = fin m) : cast h = ⇑(fin.cast $ fin_injective h) := (fin.cast_eq_cast _).symm lemma card_finset_fin_le {n : ℕ} (s : finset (fin n)) : s.card ≤ n := by simpa only [fintype.card_fin] using s.card_le_univ lemma fin.equiv_iff_eq {m n : ℕ} : nonempty (fin m ≃ fin n) ↔ m = n := ⟨λ ⟨h⟩, by simpa using fintype.card_congr h, λ h, ⟨equiv.cast $ h ▸ rfl ⟩ ⟩ @[simp] lemma fin.image_succ_above_univ {n : ℕ} (i : fin (n + 1)) : univ.image i.succ_above = {i}ᶜ := by { ext m, simp } @[simp] lemma fin.image_succ_univ (n : ℕ) : (univ : finset (fin n)).image fin.succ = {0}ᶜ := by rw [← fin.succ_above_zero, fin.image_succ_above_univ] @[simp] lemma fin.image_cast_succ (n : ℕ) : (univ : finset (fin n)).image fin.cast_succ = {fin.last n}ᶜ := by rw [← fin.succ_above_last, fin.image_succ_above_univ] /- The following three lemmas use `finset.cons` instead of `insert` and `finset.map` instead of `finset.image` to reduce proof obligations downstream. -/ /-- Embed `fin n` into `fin (n + 1)` by prepending zero to the `univ` -/ lemma fin.univ_succ (n : ℕ) : (univ : finset (fin (n + 1))) = cons 0 (univ.map ⟨fin.succ, fin.succ_injective _⟩) (by simp [map_eq_image]) := by simp [map_eq_image] /-- Embed `fin n` into `fin (n + 1)` by appending a new `fin.last n` to the `univ` -/ lemma fin.univ_cast_succ (n : ℕ) : (univ : finset (fin (n + 1))) = cons (fin.last n) (univ.map fin.cast_succ.to_embedding) (by simp [map_eq_image]) := by simp [map_eq_image] /-- Embed `fin n` into `fin (n + 1)` by inserting around a specified pivot `p : fin (n + 1)` into the `univ` -/ lemma fin.univ_succ_above (n : ℕ) (p : fin (n + 1)) : (univ : finset (fin (n + 1))) = cons p (univ.map $ (fin.succ_above p).to_embedding) (by simp) := by simp [map_eq_image] @[instance, priority 10] def unique.fintype {α : Type*} [unique α] : fintype α := fintype.of_subsingleton default /-- Short-circuit instance to decrease search for `unique.fintype`, since that relies on a subsingleton elimination for `unique`. -/ instance fintype.subtype_eq (y : α) : fintype {x // x = y} := fintype.subtype {y} (by simp) /-- Short-circuit instance to decrease search for `unique.fintype`, since that relies on a subsingleton elimination for `unique`. -/ instance fintype.subtype_eq' (y : α) : fintype {x // y = x} := fintype.subtype {y} (by simp [eq_comm]) @[simp] lemma fintype.card_subtype_eq (y : α) [fintype {x // x = y}] : fintype.card {x // x = y} = 1 := fintype.card_unique @[simp] lemma fintype.card_subtype_eq' (y : α) [fintype {x // y = x}] : fintype.card {x // y = x} = 1 := fintype.card_unique @[simp] theorem fintype.univ_empty : @univ empty _ = ∅ := rfl @[simp] theorem fintype.card_empty : fintype.card empty = 0 := rfl @[simp] theorem fintype.univ_pempty : @univ pempty _ = ∅ := rfl @[simp] theorem fintype.card_pempty : fintype.card pempty = 0 := rfl instance : fintype unit := fintype.of_subsingleton () theorem fintype.univ_unit : @univ unit _ = {()} := rfl theorem fintype.card_unit : fintype.card unit = 1 := rfl instance : fintype punit := fintype.of_subsingleton punit.star @[simp] theorem fintype.univ_punit : @univ punit _ = {punit.star} := rfl @[simp] theorem fintype.card_punit : fintype.card punit = 1 := rfl instance : fintype bool := ⟨⟨tt ::ₘ ff ::ₘ 0, by simp⟩, λ x, by cases x; simp⟩ @[simp] theorem fintype.univ_bool : @univ bool _ = {tt, ff} := rfl instance units_int.fintype : fintype ℤˣ := ⟨{1, -1}, λ x, by cases int.units_eq_one_or x; simp *⟩ @[simp] lemma units_int.univ : (finset.univ : finset ℤˣ) = {1, -1} := rfl instance additive.fintype : Π [fintype α], fintype (additive α) := id instance multiplicative.fintype : Π [fintype α], fintype (multiplicative α) := id @[simp] theorem fintype.card_units_int : fintype.card ℤˣ = 2 := rfl @[simp] theorem fintype.card_bool : fintype.card bool = 2 := rfl instance {α : Type*} [fintype α] : fintype (option α) := ⟨univ.insert_none, λ a, by simp⟩ lemma univ_option (α : Type*) [fintype α] : (univ : finset (option α)) = insert_none univ := rfl @[simp] theorem fintype.card_option {α : Type*} [fintype α] : fintype.card (option α) = fintype.card α + 1 := (finset.card_cons _).trans $ congr_arg2 _ (card_map _) rfl /-- If `option α` is a `fintype` then so is `α` -/ def fintype_of_option {α : Type*} [fintype (option α)] : fintype α := ⟨finset.erase_none (fintype.elems (option α)), λ x, mem_erase_none.mpr (fintype.complete (some x))⟩ /-- A type is a `fintype` if its successor (using `option`) is a `fintype`. -/ def fintype_of_option_equiv [fintype α] (f : α ≃ option β) : fintype β := by { haveI := fintype.of_equiv _ f, exact fintype_of_option } instance {α : Type*} (β : α → Type*) [fintype α] [∀ a, fintype (β a)] : fintype (sigma β) := ⟨univ.sigma (λ _, univ), λ ⟨a, b⟩, by simp⟩ @[simp] lemma finset.univ_sigma_univ {α : Type*} {β : α → Type*} [fintype α] [∀ a, fintype (β a)] : (univ : finset α).sigma (λ a, (univ : finset (β a))) = univ := rfl instance (α β : Type*) [fintype α] [fintype β] : fintype (α × β) := ⟨univ.product univ, λ ⟨a, b⟩, by simp⟩ @[simp] lemma finset.univ_product_univ {α β : Type*} [fintype α] [fintype β] : (univ : finset α).product (univ : finset β) = univ := rfl @[simp] theorem fintype.card_prod (α β : Type*) [fintype α] [fintype β] : fintype.card (α × β) = fintype.card α * fintype.card β := card_product _ _ /-- Given that `α × β` is a fintype, `α` is also a fintype. -/ def fintype.prod_left {α β} [decidable_eq α] [fintype (α × β)] [nonempty β] : fintype α := ⟨(fintype.elems (α × β)).image prod.fst, λ a, let ⟨b⟩ := ‹nonempty β› in by simp; exact ⟨b, fintype.complete _⟩⟩ /-- Given that `α × β` is a fintype, `β` is also a fintype. -/ def fintype.prod_right {α β} [decidable_eq β] [fintype (α × β)] [nonempty α] : fintype β := ⟨(fintype.elems (α × β)).image prod.snd, λ b, let ⟨a⟩ := ‹nonempty α› in by simp; exact ⟨a, fintype.complete _⟩⟩ instance (α : Type*) [fintype α] : fintype (ulift α) := fintype.of_equiv _ equiv.ulift.symm @[simp] theorem fintype.card_ulift (α : Type*) [fintype α] : fintype.card (ulift α) = fintype.card α := fintype.of_equiv_card _ instance (α : Type*) [fintype α] : fintype (plift α) := fintype.of_equiv _ equiv.plift.symm @[simp] theorem fintype.card_plift (α : Type*) [fintype α] : fintype.card (plift α) = fintype.card α := fintype.of_equiv_card _ instance (α : Type*) [fintype α] : fintype αᵒᵈ := ‹fintype α› @[simp] lemma fintype.card_order_dual (α : Type*) [fintype α] : fintype.card αᵒᵈ = fintype.card α := rfl instance (α : Type*) [fintype α] : fintype (lex α) := ‹fintype α› @[simp] lemma fintype.card_lex (α : Type*) [fintype α] : fintype.card (lex α) = fintype.card α := rfl lemma univ_sum_type {α β : Type*} [fintype α] [fintype β] [fintype (α ⊕ β)] [decidable_eq (α ⊕ β)] : (univ : finset (α ⊕ β)) = map function.embedding.inl univ ∪ map function.embedding.inr univ := begin rw [eq_comm, eq_univ_iff_forall], simp only [mem_union, mem_map, exists_prop, mem_univ, true_and], rintro (x|y), exacts [or.inl ⟨x, rfl⟩, or.inr ⟨y, rfl⟩] end instance (α : Type u) (β : Type v) [fintype α] [fintype β] : fintype (α ⊕ β) := @fintype.of_equiv _ _ (@sigma.fintype _ (λ b, cond b (ulift α) (ulift.{(max u v) v} β)) _ (λ b, by cases b; apply ulift.fintype)) ((equiv.sum_equiv_sigma_bool _ _).symm.trans (equiv.sum_congr equiv.ulift equiv.ulift)) /-- Given that `α ⊕ β` is a fintype, `α` is also a fintype. This is non-computable as it uses that `sum.inl` is an injection, but there's no clear inverse if `α` is empty. -/ noncomputable def fintype.sum_left {α β} [fintype (α ⊕ β)] : fintype α := fintype.of_injective (sum.inl : α → α ⊕ β) sum.inl_injective /-- Given that `α ⊕ β` is a fintype, `β` is also a fintype. This is non-computable as it uses that `sum.inr` is an injection, but there's no clear inverse if `β` is empty. -/ noncomputable def fintype.sum_right {α β} [fintype (α ⊕ β)] : fintype β := fintype.of_injective (sum.inr : β → α ⊕ β) sum.inr_injective @[simp] theorem fintype.card_sum [fintype α] [fintype β] : fintype.card (α ⊕ β) = fintype.card α + fintype.card β := begin classical, rw [←finset.card_univ, univ_sum_type, finset.card_union_eq], { simp [finset.card_univ] }, { intros x hx, suffices : (∃ (a : α), sum.inl a = x) ∧ ∃ (b : β), sum.inr b = x, { obtain ⟨⟨a, rfl⟩, ⟨b, hb⟩⟩ := this, simpa using hb }, simpa using hx } end /-- If the subtype of all-but-one elements is a `fintype` then the type itself is a `fintype`. -/ def fintype_of_fintype_ne (a : α) (h : fintype {b // b ≠ a}) : fintype α := fintype.of_bijective (sum.elim (coe : {b // b = a} → α) (coe : {b // b ≠ a} → α)) $ by { classical, exact (equiv.sum_compl (= a)).bijective } section finset /-! ### `fintype (s : finset α)` -/ instance finset.fintype_coe_sort {α : Type u} (s : finset α) : fintype s := ⟨s.attach, s.mem_attach⟩ @[simp] lemma finset.univ_eq_attach {α : Type u} (s : finset α) : (univ : finset s) = s.attach := rfl end finset namespace fintype variables [fintype α] [fintype β] lemma card_le_of_injective (f : α → β) (hf : function.injective f) : card α ≤ card β := finset.card_le_card_of_inj_on f (λ _ _, finset.mem_univ _) (λ _ _ _ _ h, hf h) lemma card_le_of_embedding (f : α ↪ β) : card α ≤ card β := card_le_of_injective f f.2 lemma card_lt_of_injective_of_not_mem (f : α → β) (h : function.injective f) {b : β} (w : b ∉ set.range f) : card α < card β := calc card α = (univ.map ⟨f, h⟩).card : (card_map _).symm ... < card β : finset.card_lt_univ_of_not_mem $ by rwa [← mem_coe, coe_map, coe_univ, set.image_univ] lemma card_lt_of_injective_not_surjective (f : α → β) (h : function.injective f) (h' : ¬function.surjective f) : card α < card β := let ⟨y, hy⟩ := not_forall.1 h' in card_lt_of_injective_of_not_mem f h hy lemma card_le_of_surjective (f : α → β) (h : function.surjective f) : card β ≤ card α := card_le_of_injective _ (function.injective_surj_inv h) lemma card_range_le {α β : Type*} (f : α → β) [fintype α] [fintype (set.range f)] : fintype.card (set.range f) ≤ fintype.card α := fintype.card_le_of_surjective (λ a, ⟨f a, by simp⟩) (λ ⟨_, a, ha⟩, ⟨a, by simpa using ha⟩) lemma card_range {α β F : Type*} [embedding_like F α β] (f : F) [fintype α] [fintype (set.range f)] : fintype.card (set.range f) = fintype.card α := eq.symm $ fintype.card_congr $ equiv.of_injective _ $ embedding_like.injective f /-- The pigeonhole principle for finitely many pigeons and pigeonholes. This is the `fintype` version of `finset.exists_ne_map_eq_of_card_lt_of_maps_to`. -/ lemma exists_ne_map_eq_of_card_lt (f : α → β) (h : fintype.card β < fintype.card α) : ∃ x y, x ≠ y ∧ f x = f y := let ⟨x, _, y, _, h⟩ := finset.exists_ne_map_eq_of_card_lt_of_maps_to h (λ x _, mem_univ (f x)) in ⟨x, y, h⟩ lemma card_eq_one_iff : card α = 1 ↔ (∃ x : α, ∀ y, y = x) := by rw [←card_unit, card_eq]; exact ⟨λ ⟨a⟩, ⟨a.symm (), λ y, a.injective (subsingleton.elim _ _)⟩, λ ⟨x, hx⟩, ⟨⟨λ _, (), λ _, x, λ _, (hx _).trans (hx _).symm, λ _, subsingleton.elim _ _⟩⟩⟩ lemma card_eq_zero_iff : card α = 0 ↔ is_empty α := by rw [card, finset.card_eq_zero, univ_eq_empty_iff] lemma card_eq_zero [is_empty α] : card α = 0 := card_eq_zero_iff.2 ‹_› lemma card_eq_one_iff_nonempty_unique : card α = 1 ↔ nonempty (unique α) := ⟨λ h, let ⟨d, h⟩ := fintype.card_eq_one_iff.mp h in ⟨{ default := d, uniq := h}⟩, λ ⟨h⟩, by exactI fintype.card_unique⟩ /-- A `fintype` with cardinality zero is equivalent to `empty`. -/ def card_eq_zero_equiv_equiv_empty : card α = 0 ≃ (α ≃ empty) := (equiv.of_iff card_eq_zero_iff).trans (equiv.equiv_empty_equiv α).symm lemma card_pos_iff : 0 < card α ↔ nonempty α := pos_iff_ne_zero.trans $ not_iff_comm.mp $ not_nonempty_iff.trans card_eq_zero_iff.symm lemma card_pos [h : nonempty α] : 0 < card α := card_pos_iff.mpr h lemma card_ne_zero [nonempty α] : card α ≠ 0 := ne_of_gt card_pos lemma card_le_one_iff : card α ≤ 1 ↔ (∀ a b : α, a = b) := let n := card α in have hn : n = card α := rfl, match n, hn with | 0 := λ ha, ⟨λ h, λ a, (card_eq_zero_iff.1 ha.symm).elim a, λ _, ha ▸ nat.le_succ _⟩ | 1 := λ ha, ⟨λ h, λ a b, let ⟨x, hx⟩ := card_eq_one_iff.1 ha.symm in by rw [hx a, hx b], λ _, ha ▸ le_rfl⟩ | (n+2) := λ ha, ⟨λ h, by rw ← ha at h; exact absurd h dec_trivial, (λ h, card_unit ▸ card_le_of_injective (λ _, ()) (λ _ _ _, h _ _))⟩ end lemma card_le_one_iff_subsingleton : card α ≤ 1 ↔ subsingleton α := card_le_one_iff.trans subsingleton_iff.symm lemma one_lt_card_iff_nontrivial : 1 < card α ↔ nontrivial α := begin classical, rw ←not_iff_not, push_neg, rw [not_nontrivial_iff_subsingleton, card_le_one_iff_subsingleton] end lemma exists_ne_of_one_lt_card (h : 1 < card α) (a : α) : ∃ b : α, b ≠ a := by { haveI : nontrivial α := one_lt_card_iff_nontrivial.1 h, exact exists_ne a } lemma exists_pair_of_one_lt_card (h : 1 < card α) : ∃ (a b : α), a ≠ b := by { haveI : nontrivial α := one_lt_card_iff_nontrivial.1 h, exact exists_pair_ne α } lemma card_eq_one_of_forall_eq {i : α} (h : ∀ j, j = i) : card α = 1 := fintype.card_eq_one_iff.2 ⟨i,h⟩ lemma one_lt_card [h : nontrivial α] : 1 < fintype.card α := fintype.one_lt_card_iff_nontrivial.mpr h lemma one_lt_card_iff : 1 < card α ↔ ∃ a b : α, a ≠ b := one_lt_card_iff_nontrivial.trans nontrivial_iff lemma two_lt_card_iff : 2 < card α ↔ ∃ a b c : α, a ≠ b ∧ a ≠ c ∧ b ≠ c := by simp_rw [←finset.card_univ, two_lt_card_iff, mem_univ, true_and] lemma injective_iff_surjective {f : α → α} : injective f ↔ surjective f := by haveI := classical.prop_decidable; exact have ∀ {f : α → α}, injective f → surjective f, from λ f hinj x, have h₁ : image f univ = univ := eq_of_subset_of_card_le (subset_univ _) ((card_image_of_injective univ hinj).symm ▸ le_rfl), have h₂ : x ∈ image f univ := h₁.symm ▸ mem_univ _, exists_of_bex (mem_image.1 h₂), ⟨this, λ hsurj, has_left_inverse.injective ⟨surj_inv hsurj, left_inverse_of_surjective_of_right_inverse (this (injective_surj_inv _)) (right_inverse_surj_inv _)⟩⟩ lemma injective_iff_bijective {f : α → α} : injective f ↔ bijective f := by simp [bijective, injective_iff_surjective] lemma surjective_iff_bijective {f : α → α} : surjective f ↔ bijective f := by simp [bijective, injective_iff_surjective] lemma injective_iff_surjective_of_equiv {β : Type*} {f : α → β} (e : α ≃ β) : injective f ↔ surjective f := have injective (e.symm ∘ f) ↔ surjective (e.symm ∘ f), from injective_iff_surjective, ⟨λ hinj, by simpa [function.comp] using e.surjective.comp (this.1 (e.symm.injective.comp hinj)), λ hsurj, by simpa [function.comp] using e.injective.comp (this.2 (e.symm.surjective.comp hsurj))⟩ alias fintype.injective_iff_surjective_of_equiv ↔ _root_.function.injective.surjective_of_fintype _root_.function.surjective.injective_of_fintype lemma card_of_bijective {f : α → β} (hf : bijective f) : card α = card β := card_congr (equiv.of_bijective f hf) lemma bijective_iff_injective_and_card (f : α → β) : bijective f ↔ injective f ∧ card α = card β := ⟨λ h, ⟨h.1, card_of_bijective h⟩, λ h, ⟨h.1, h.1.surjective_of_fintype $ equiv_of_card_eq h.2⟩⟩ lemma bijective_iff_surjective_and_card (f : α → β) : bijective f ↔ surjective f ∧ card α = card β := ⟨λ h, ⟨h.2, card_of_bijective h⟩, λ h, ⟨h.1.injective_of_fintype $ equiv_of_card_eq h.2, h.1⟩⟩ lemma _root_.function.left_inverse.right_inverse_of_card_le {f : α → β} {g : β → α} (hfg : left_inverse f g) (hcard : card α ≤ card β) : right_inverse f g := have hsurj : surjective f, from surjective_iff_has_right_inverse.2 ⟨g, hfg⟩, right_inverse_of_injective_of_left_inverse ((bijective_iff_surjective_and_card _).2 ⟨hsurj, le_antisymm hcard (card_le_of_surjective f hsurj)⟩ ).1 hfg lemma _root_.function.right_inverse.left_inverse_of_card_le {f : α → β} {g : β → α} (hfg : right_inverse f g) (hcard : card β ≤ card α) : left_inverse f g := function.left_inverse.right_inverse_of_card_le hfg hcard end fintype namespace equiv variables [fintype α] [fintype β] open fintype /-- Construct an equivalence from functions that are inverse to each other. -/ @[simps] def of_left_inverse_of_card_le (hβα : card β ≤ card α) (f : α → β) (g : β → α) (h : left_inverse g f) : α ≃ β := { to_fun := f, inv_fun := g, left_inv := h, right_inv := h.right_inverse_of_card_le hβα } /-- Construct an equivalence from functions that are inverse to each other. -/ @[simps] def of_right_inverse_of_card_le (hαβ : card α ≤ card β) (f : α → β) (g : β → α) (h : right_inverse g f) : α ≃ β := { to_fun := f, inv_fun := g, left_inv := h.left_inverse_of_card_le hαβ, right_inv := h } end equiv lemma fintype.coe_image_univ [fintype α] [decidable_eq β] {f : α → β} : ↑(finset.image f finset.univ) = set.range f := by { ext x, simp } instance list.subtype.fintype [decidable_eq α] (l : list α) : fintype {x // x ∈ l} := fintype.of_list l.attach l.mem_attach instance multiset.subtype.fintype [decidable_eq α] (s : multiset α) : fintype {x // x ∈ s} := fintype.of_multiset s.attach s.mem_attach instance finset.subtype.fintype (s : finset α) : fintype {x // x ∈ s} := ⟨s.attach, s.mem_attach⟩ instance finset_coe.fintype (s : finset α) : fintype (↑s : set α) := finset.subtype.fintype s @[simp] lemma fintype.card_coe (s : finset α) [fintype s] : fintype.card s = s.card := fintype.card_of_finset' s (λ _, iff.rfl) /-- Noncomputable equivalence between a finset `s` coerced to a type and `fin s.card`. -/ noncomputable def finset.equiv_fin (s : finset α) : s ≃ fin s.card := fintype.equiv_fin_of_card_eq (fintype.card_coe _) /-- Noncomputable equivalence between a finset `s` as a fintype and `fin n`, when there is a proof that `s.card = n`. -/ noncomputable def finset.equiv_fin_of_card_eq {s : finset α} {n : ℕ} (h : s.card = n) : s ≃ fin n := fintype.equiv_fin_of_card_eq ((fintype.card_coe _).trans h) /-- Noncomputable equivalence between two finsets `s` and `t` as fintypes when there is a proof that `s.card = t.card`.-/ noncomputable def finset.equiv_of_card_eq {s t : finset α} (h : s.card = t.card) : s ≃ t := fintype.equiv_of_card_eq ((fintype.card_coe _).trans (h.trans (fintype.card_coe _).symm)) lemma finset.attach_eq_univ {s : finset α} : s.attach = finset.univ := rfl instance plift.fintype_Prop (p : Prop) [decidable p] : fintype (plift p) := ⟨if h : p then {⟨h⟩} else ∅, λ ⟨h⟩, by simp [h]⟩ instance Prop.fintype : fintype Prop := ⟨⟨true ::ₘ false ::ₘ 0, by simp [true_ne_false]⟩, classical.cases (by simp) (by simp)⟩ @[simp] lemma fintype.card_Prop : fintype.card Prop = 2 := rfl instance subtype.fintype (p : α → Prop) [decidable_pred p] [fintype α] : fintype {x // p x} := fintype.subtype (univ.filter p) (by simp) @[simp] lemma set.to_finset_eq_empty_iff {s : set α} [fintype s] : s.to_finset = ∅ ↔ s = ∅ := by simp only [ext_iff, set.ext_iff, set.mem_to_finset, not_mem_empty, set.mem_empty_eq] @[simp] lemma set.to_finset_empty : (∅ : set α).to_finset = ∅ := set.to_finset_eq_empty_iff.mpr rfl /-- A set on a fintype, when coerced to a type, is a fintype. -/ def set_fintype [fintype α] (s : set α) [decidable_pred (∈ s)] : fintype s := subtype.fintype (λ x, x ∈ s) lemma set_fintype_card_le_univ [fintype α] (s : set α) [fintype ↥s] : fintype.card ↥s ≤ fintype.card α := fintype.card_le_of_embedding (function.embedding.subtype s) lemma set_fintype_card_eq_univ_iff [fintype α] (s : set α) [fintype ↥s] : fintype.card s = fintype.card α ↔ s = set.univ := by rw [←set.to_finset_card, finset.card_eq_iff_eq_univ, ←set.to_finset_univ, set.to_finset_inj] section variables (α) /-- The `αˣ` type is equivalent to a subtype of `α × α`. -/ @[simps] def _root_.units_equiv_prod_subtype [monoid α] : αˣ ≃ {p : α × α // p.1 * p.2 = 1 ∧ p.2 * p.1 = 1} := { to_fun := λ u, ⟨(u, ↑u⁻¹), u.val_inv, u.inv_val⟩, inv_fun := λ p, units.mk (p : α × α).1 (p : α × α).2 p.prop.1 p.prop.2, left_inv := λ u, units.ext rfl, right_inv := λ p, subtype.ext $ prod.ext rfl rfl} /-- In a `group_with_zero` `α`, the unit group `αˣ` is equivalent to the subtype of nonzero elements. -/ @[simps] def _root_.units_equiv_ne_zero [group_with_zero α] : αˣ ≃ {a : α // a ≠ 0} := ⟨λ a, ⟨a, a.ne_zero⟩, λ a, units.mk0 _ a.prop, λ _, units.ext rfl, λ _, subtype.ext rfl⟩ end instance [monoid α] [fintype α] [decidable_eq α] : fintype αˣ := fintype.of_equiv _ (units_equiv_prod_subtype α).symm lemma fintype.card_units [group_with_zero α] [fintype α] [fintype αˣ] : fintype.card αˣ = fintype.card α - 1 := begin classical, rw [eq_comm, nat.sub_eq_iff_eq_add (fintype.card_pos_iff.2 ⟨(0 : α)⟩), fintype.card_congr (units_equiv_ne_zero α)], have := fintype.card_congr (equiv.sum_compl (= (0 : α))).symm, rwa [fintype.card_sum, add_comm, fintype.card_subtype_eq] at this, end namespace function.embedding /-- An embedding from a `fintype` to itself can be promoted to an equivalence. -/ noncomputable def equiv_of_fintype_self_embedding [fintype α] (e : α ↪ α) : α ≃ α := equiv.of_bijective e (fintype.injective_iff_bijective.1 e.2) @[simp] lemma equiv_of_fintype_self_embedding_to_embedding [fintype α] (e : α ↪ α) : e.equiv_of_fintype_self_embedding.to_embedding = e := by { ext, refl, } /-- If `‖β‖ < ‖α‖` there are no embeddings `α ↪ β`. This is a formulation of the pigeonhole principle. Note this cannot be an instance as it needs `h`. -/ @[simp] lemma is_empty_of_card_lt [fintype α] [fintype β] (h : fintype.card β < fintype.card α) : is_empty (α ↪ β) := ⟨λ f, let ⟨x, y, ne, feq⟩ := fintype.exists_ne_map_eq_of_card_lt f h in ne $ f.injective feq⟩ /-- A constructive embedding of a fintype `α` in another fintype `β` when `card α ≤ card β`. -/ def trunc_of_card_le [fintype α] [fintype β] [decidable_eq α] [decidable_eq β] (h : fintype.card α ≤ fintype.card β) : trunc (α ↪ β) := (fintype.trunc_equiv_fin α).bind $ λ ea, (fintype.trunc_equiv_fin β).map $ λ eb, ea.to_embedding.trans ((fin.cast_le h).to_embedding.trans eb.symm.to_embedding) lemma nonempty_of_card_le [fintype α] [fintype β] (h : fintype.card α ≤ fintype.card β) : nonempty (α ↪ β) := by { classical, exact (trunc_of_card_le h).nonempty } lemma exists_of_card_le_finset [fintype α] {s : finset β} (h : fintype.card α ≤ s.card) : ∃ (f : α ↪ β), set.range f ⊆ s := begin rw ← fintype.card_coe at h, rcases nonempty_of_card_le h with ⟨f⟩, exact ⟨f.trans (embedding.subtype _), by simp [set.range_subset_iff]⟩ end end function.embedding @[simp] lemma finset.univ_map_embedding {α : Type*} [fintype α] (e : α ↪ α) : univ.map e = univ := by rw [←e.equiv_of_fintype_self_embedding_to_embedding, univ_map_equiv_to_embedding] namespace fintype /-- Given `fintype α`, `finset_equiv_set` is the equiv between `finset α` and `set α`. (All sets on a finite type are finite.) -/ noncomputable def finset_equiv_set [fintype α] : finset α ≃ set α := { to_fun := coe, inv_fun := by { classical, exact λ s, s.to_finset }, left_inv := λ s, by convert finset.to_finset_coe s, right_inv := λ s, s.coe_to_finset } @[simp] lemma finset_equiv_set_apply [fintype α] (s : finset α) : finset_equiv_set s = s := rfl @[simp] lemma finset_equiv_set_symm_apply [fintype α] (s : set α) [fintype s] : finset_equiv_set.symm s = s.to_finset := by convert rfl lemma card_lt_of_surjective_not_injective [fintype α] [fintype β] (f : α → β) (h : function.surjective f) (h' : ¬function.injective f) : card β < card α := card_lt_of_injective_not_surjective _ (function.injective_surj_inv h) $ λ hg, have w : function.bijective (function.surj_inv h) := ⟨function.injective_surj_inv h, hg⟩, h' $ h.injective_of_fintype (equiv.of_bijective _ w).symm variables [decidable_eq α] [fintype α] {δ : α → Type*} /-- Given for all `a : α` a finset `t a` of `δ a`, then one can define the finset `fintype.pi_finset t` of all functions taking values in `t a` for all `a`. This is the analogue of `finset.pi` where the base finset is `univ` (but formally they are not the same, as there is an additional condition `i ∈ finset.univ` in the `finset.pi` definition). -/ def pi_finset (t : Π a, finset (δ a)) : finset (Π a, δ a) := (finset.univ.pi t).map ⟨λ f a, f a (mem_univ a), λ _ _, by simp [function.funext_iff]⟩ @[simp] lemma mem_pi_finset {t : Π a, finset (δ a)} {f : Π a, δ a} : f ∈ pi_finset t ↔ ∀ a, f a ∈ t a := begin split, { simp only [pi_finset, mem_map, and_imp, forall_prop_of_true, exists_prop, mem_univ, exists_imp_distrib, mem_pi], rintro g hg hgf a, rw ← hgf, exact hg a }, { simp only [pi_finset, mem_map, forall_prop_of_true, exists_prop, mem_univ, mem_pi], exact λ hf, ⟨λ a ha, f a, hf, rfl⟩ } end @[simp] lemma coe_pi_finset (t : Π a, finset (δ a)) : (pi_finset t : set (Π a, δ a)) = set.pi set.univ (λ a, t a) := set.ext $ λ x, by { rw set.mem_univ_pi, exact fintype.mem_pi_finset } lemma pi_finset_subset (t₁ t₂ : Π a, finset (δ a)) (h : ∀ a, t₁ a ⊆ t₂ a) : pi_finset t₁ ⊆ pi_finset t₂ := λ g hg, mem_pi_finset.2 $ λ a, h a $ mem_pi_finset.1 hg a @[simp] lemma pi_finset_empty [nonempty α] : pi_finset (λ _, ∅ : Π i, finset (δ i)) = ∅ := eq_empty_of_forall_not_mem $ λ _, by simp @[simp] lemma pi_finset_singleton (f : Π i, δ i) : pi_finset (λ i, {f i} : Π i, finset (δ i)) = {f} := ext $ λ _, by simp only [function.funext_iff, fintype.mem_pi_finset, mem_singleton] lemma pi_finset_subsingleton {f : Π i, finset (δ i)} (hf : ∀ i, (f i : set (δ i)).subsingleton) : (fintype.pi_finset f : set (Π i, δ i)).subsingleton := λ a ha b hb, funext $ λ i, hf _ (mem_pi_finset.1 ha _) (mem_pi_finset.1 hb _) lemma pi_finset_disjoint_of_disjoint [∀ a, decidable_eq (δ a)] (t₁ t₂ : Π a, finset (δ a)) {a : α} (h : disjoint (t₁ a) (t₂ a)) : disjoint (pi_finset t₁) (pi_finset t₂) := disjoint_iff_ne.2 $ λ f₁ hf₁ f₂ hf₂ eq₁₂, disjoint_iff_ne.1 h (f₁ a) (mem_pi_finset.1 hf₁ a) (f₂ a) (mem_pi_finset.1 hf₂ a) (congr_fun eq₁₂ a) end fintype /-! ### pi -/ /-- A dependent product of fintypes, indexed by a fintype, is a fintype. -/ instance pi.fintype {α : Type*} {β : α → Type*} [decidable_eq α] [fintype α] [∀ a, fintype (β a)] : fintype (Π a, β a) := ⟨fintype.pi_finset (λ _, univ), by simp⟩ @[simp] lemma fintype.pi_finset_univ {α : Type*} {β : α → Type*} [decidable_eq α] [fintype α] [∀ a, fintype (β a)] : fintype.pi_finset (λ a : α, (finset.univ : finset (β a))) = (finset.univ : finset (Π a, β a)) := rfl instance d_array.fintype {n : ℕ} {α : fin n → Type*} [∀ n, fintype (α n)] : fintype (d_array n α) := fintype.of_equiv _ (equiv.d_array_equiv_fin _).symm instance array.fintype {n : ℕ} {α : Type*} [fintype α] : fintype (array n α) := d_array.fintype instance vector.fintype {α : Type*} [fintype α] {n : ℕ} : fintype (vector α n) := fintype.of_equiv _ (equiv.vector_equiv_fin _ _).symm instance quotient.fintype [fintype α] (s : setoid α) [decidable_rel ((≈) : α → α → Prop)] : fintype (quotient s) := fintype.of_surjective quotient.mk (λ x, quotient.induction_on x (λ x, ⟨x, rfl⟩)) instance finset.fintype [fintype α] : fintype (finset α) := ⟨univ.powerset, λ x, finset.mem_powerset.2 (finset.subset_univ _)⟩ -- irreducible due to this conversation on Zulip: -- https://leanprover.zulipchat.com/#narrow/stream/113488-general/ -- topic/.60simp.60.20ignoring.20lemmas.3F/near/241824115 @[irreducible] instance function.embedding.fintype {α β} [fintype α] [fintype β] [decidable_eq α] [decidable_eq β] : fintype (α ↪ β) := fintype.of_equiv _ (equiv.subtype_injective_equiv_embedding α β) instance [decidable_eq α] [fintype α] {n : ℕ} : fintype (sym.sym' α n) := quotient.fintype _ instance [decidable_eq α] [fintype α] {n : ℕ} : fintype (sym α n) := fintype.of_equiv _ sym.sym_equiv_sym'.symm @[simp] lemma fintype.card_finset [fintype α] : fintype.card (finset α) = 2 ^ (fintype.card α) := finset.card_powerset finset.univ @[simp] lemma finset.powerset_univ [fintype α] : (univ : finset α).powerset = univ := coe_injective $ by simp [-coe_eq_univ] @[simp] lemma finset.powerset_eq_univ [fintype α] {s : finset α} : s.powerset = univ ↔ s = univ := by rw [←finset.powerset_univ, powerset_inj] lemma finset.mem_powerset_len_univ_iff [fintype α] {s : finset α} {k : ℕ} : s ∈ powerset_len k (univ : finset α) ↔ card s = k := mem_powerset_len.trans $ and_iff_right $ subset_univ _ @[simp] lemma finset.univ_filter_card_eq (α : Type*) [fintype α] (k : ℕ) : (finset.univ : finset (finset α)).filter (λ s, s.card = k) = finset.univ.powerset_len k := by { ext, simp [finset.mem_powerset_len] } @[simp] lemma fintype.card_finset_len [fintype α] (k : ℕ) : fintype.card {s : finset α // s.card = k} = nat.choose (fintype.card α) k := by simp [fintype.subtype_card, finset.card_univ] theorem fintype.card_subtype_le [fintype α] (p : α → Prop) [decidable_pred p] : fintype.card {x // p x} ≤ fintype.card α := fintype.card_le_of_embedding (function.embedding.subtype _) theorem fintype.card_subtype_lt [fintype α] {p : α → Prop} [decidable_pred p] {x : α} (hx : ¬ p x) : fintype.card {x // p x} < fintype.card α := fintype.card_lt_of_injective_of_not_mem coe subtype.coe_injective $ by rwa subtype.range_coe_subtype lemma fintype.card_subtype [fintype α] (p : α → Prop) [decidable_pred p] : fintype.card {x // p x} = ((finset.univ : finset α).filter p).card := begin refine fintype.card_of_subtype _ _, simp end lemma fintype.card_subtype_or (p q : α → Prop) [fintype {x // p x}] [fintype {x // q x}] [fintype {x // p x ∨ q x}] : fintype.card {x // p x ∨ q x} ≤ fintype.card {x // p x} + fintype.card {x // q x} := begin classical, convert fintype.card_le_of_embedding (subtype_or_left_embedding p q), rw fintype.card_sum end lemma fintype.card_subtype_or_disjoint (p q : α → Prop) (h : disjoint p q) [fintype {x // p x}] [fintype {x // q x}] [fintype {x // p x ∨ q x}] : fintype.card {x // p x ∨ q x} = fintype.card {x // p x} + fintype.card {x // q x} := begin classical, convert fintype.card_congr (subtype_or_equiv p q h), simp end @[simp] lemma fintype.card_subtype_compl [fintype α] (p : α → Prop) [fintype {x // p x}] [fintype {x // ¬ p x}] : fintype.card {x // ¬ p x} = fintype.card α - fintype.card {x // p x} := begin classical, rw [fintype.card_of_subtype (set.to_finset pᶜ), set.to_finset_compl p, finset.card_compl, fintype.card_of_subtype (set.to_finset p)]; intro; simp only [set.mem_to_finset, set.mem_compl_eq]; refl, end theorem fintype.card_subtype_mono (p q : α → Prop) (h : p ≤ q) [fintype {x // p x}] [fintype {x // q x}] : fintype.card {x // p x} ≤ fintype.card {x // q x} := fintype.card_le_of_embedding (subtype.imp_embedding _ _ h) /-- If two subtypes of a fintype have equal cardinality, so do their complements. -/ lemma fintype.card_compl_eq_card_compl [fintype α] (p q : α → Prop) [fintype {x // p x}] [fintype {x // ¬ p x}] [fintype {x // q x}] [fintype {x // ¬ q x}] (h : fintype.card {x // p x} = fintype.card {x // q x}) : fintype.card {x // ¬ p x} = fintype.card {x // ¬ q x} := by simp only [fintype.card_subtype_compl, h] theorem fintype.card_quotient_le [fintype α] (s : setoid α) [decidable_rel ((≈) : α → α → Prop)] : fintype.card (quotient s) ≤ fintype.card α := fintype.card_le_of_surjective _ (surjective_quotient_mk _) theorem fintype.card_quotient_lt [fintype α] {s : setoid α} [decidable_rel ((≈) : α → α → Prop)] {x y : α} (h1 : x ≠ y) (h2 : x ≈ y) : fintype.card (quotient s) < fintype.card α := fintype.card_lt_of_surjective_not_injective _ (surjective_quotient_mk _) $ λ w, h1 (w $ quotient.eq.mpr h2) instance psigma.fintype {α : Type*} {β : α → Type*} [fintype α] [∀ a, fintype (β a)] : fintype (Σ' a, β a) := fintype.of_equiv _ (equiv.psigma_equiv_sigma _).symm instance psigma.fintype_prop_left {α : Prop} {β : α → Type*} [decidable α] [∀ a, fintype (β a)] : fintype (Σ' a, β a) := if h : α then fintype.of_equiv (β h) ⟨λ x, ⟨h, x⟩, psigma.snd, λ _, rfl, λ ⟨_, _⟩, rfl⟩ else ⟨∅, λ x, h x.1⟩ instance psigma.fintype_prop_right {α : Type*} {β : α → Prop} [∀ a, decidable (β a)] [fintype α] : fintype (Σ' a, β a) := fintype.of_equiv {a // β a} ⟨λ ⟨x, y⟩, ⟨x, y⟩, λ ⟨x, y⟩, ⟨x, y⟩, λ ⟨x, y⟩, rfl, λ ⟨x, y⟩, rfl⟩ instance psigma.fintype_prop_prop {α : Prop} {β : α → Prop} [decidable α] [∀ a, decidable (β a)] : fintype (Σ' a, β a) := if h : ∃ a, β a then ⟨{⟨h.fst, h.snd⟩}, λ ⟨_, _⟩, by simp⟩ else ⟨∅, λ ⟨x, y⟩, h ⟨x, y⟩⟩ instance set.fintype [fintype α] : fintype (set α) := ⟨(@finset.univ α _).powerset.map ⟨coe, coe_injective⟩, λ s, begin classical, refine mem_map.2 ⟨finset.univ.filter s, mem_powerset.2 (subset_univ _), _⟩, apply (coe_filter _ _).trans, rw [coe_univ, set.sep_univ], refl end⟩ @[simp] lemma fintype.card_set [fintype α] : fintype.card (set α) = 2 ^ fintype.card α := (finset.card_map _).trans (finset.card_powerset _) instance pfun_fintype (p : Prop) [decidable p] (α : p → Type*) [Π hp, fintype (α hp)] : fintype (Π hp : p, α hp) := if hp : p then fintype.of_equiv (α hp) ⟨λ a _, a, λ f, f hp, λ _, rfl, λ _, rfl⟩ else ⟨singleton (λ h, (hp h).elim), by simp [hp, function.funext_iff]⟩ @[simp] lemma finset.univ_pi_univ {α : Type*} {β : α → Type*} [decidable_eq α] [fintype α] [∀ a, fintype (β a)] : finset.univ.pi (λ a : α, (finset.univ : finset (β a))) = finset.univ := by { ext, simp } lemma mem_image_univ_iff_mem_range {α β : Type*} [fintype α] [decidable_eq β] {f : α → β} {b : β} : b ∈ univ.image f ↔ b ∈ set.range f := by simp /-- An auxiliary function for `quotient.fin_choice`. Given a collection of setoids indexed by a type `ι`, a (finite) list `l` of indices, and a function that for each `i ∈ l` gives a term of the corresponding quotient type, then there is a corresponding term in the quotient of the product of the setoids indexed by `l`. -/ def quotient.fin_choice_aux {ι : Type*} [decidable_eq ι] {α : ι → Type*} [S : ∀ i, setoid (α i)] : Π (l : list ι), (Π i ∈ l, quotient (S i)) → @quotient (Π i ∈ l, α i) (by apply_instance) | [] f := ⟦λ i, false.elim⟧ | (i :: l) f := begin refine quotient.lift_on₂ (f i (list.mem_cons_self _ _)) (quotient.fin_choice_aux l (λ j h, f j (list.mem_cons_of_mem _ h))) _ _, exact λ a l, ⟦λ j h, if e : j = i then by rw e; exact a else l _ (h.resolve_left e)⟧, refine λ a₁ l₁ a₂ l₂ h₁ h₂, quotient.sound (λ j h, _), by_cases e : j = i; simp [e], { subst j, exact h₁ }, { exact h₂ _ _ } end theorem quotient.fin_choice_aux_eq {ι : Type*} [decidable_eq ι] {α : ι → Type*} [S : ∀ i, setoid (α i)] : ∀ (l : list ι) (f : Π i ∈ l, α i), quotient.fin_choice_aux l (λ i h, ⟦f i h⟧) = ⟦f⟧ | [] f := quotient.sound (λ i h, h.elim) | (i :: l) f := begin simp [quotient.fin_choice_aux, quotient.fin_choice_aux_eq l], refine quotient.sound (λ j h, _), by_cases e : j = i; simp [e], subst j, refl end /-- Given a collection of setoids indexed by a fintype `ι` and a function that for each `i : ι` gives a term of the corresponding quotient type, then there is corresponding term in the quotient of the product of the setoids. -/ def quotient.fin_choice {ι : Type*} [decidable_eq ι] [fintype ι] {α : ι → Type*} [S : ∀ i, setoid (α i)] (f : Π i, quotient (S i)) : @quotient (Π i, α i) (by apply_instance) := quotient.lift_on (@quotient.rec_on _ _ (λ l : multiset ι, @quotient (Π i ∈ l, α i) (by apply_instance)) finset.univ.1 (λ l, quotient.fin_choice_aux l (λ i _, f i)) (λ a b h, begin have := λ a, quotient.fin_choice_aux_eq a (λ i h, quotient.out (f i)), simp [quotient.out_eq] at this, simp [this], let g := λ a:multiset ι, ⟦λ (i : ι) (h : i ∈ a), quotient.out (f i)⟧, refine eq_of_heq ((eq_rec_heq _ _).trans (_ : g a == g b)), congr' 1, exact quotient.sound h, end)) (λ f, ⟦λ i, f i (finset.mem_univ _)⟧) (λ a b h, quotient.sound $ λ i, h _ _) theorem quotient.fin_choice_eq {ι : Type*} [decidable_eq ι] [fintype ι] {α : ι → Type*} [∀ i, setoid (α i)] (f : Π i, α i) : quotient.fin_choice (λ i, ⟦f i⟧) = ⟦f⟧ := begin let q, swap, change quotient.lift_on q _ _ = _, have : q = ⟦λ i h, f i⟧, { dsimp [q], exact quotient.induction_on (@finset.univ ι _).1 (λ l, quotient.fin_choice_aux_eq _ _) }, simp [this], exact setoid.refl _ end section equiv open list equiv equiv.perm variables [decidable_eq α] [decidable_eq β] /-- Given a list, produce a list of all permutations of its elements. -/ def perms_of_list : list α → list (perm α) | [] := [1] | (a :: l) := perms_of_list l ++ l.bind (λ b, (perms_of_list l).map (λ f, swap a b * f)) lemma length_perms_of_list : ∀ l : list α, length (perms_of_list l) = l.length! | [] := rfl | (a :: l) := begin rw [length_cons, nat.factorial_succ], simp [perms_of_list, length_bind, length_perms_of_list, function.comp, nat.succ_mul], cc end lemma mem_perms_of_list_of_mem {l : list α} {f : perm α} (h : ∀ x, f x ≠ x → x ∈ l) : f ∈ perms_of_list l := begin induction l with a l IH generalizing f h, { exact list.mem_singleton.2 (equiv.ext $ λ x, decidable.by_contradiction $ h _) }, by_cases hfa : f a = a, { refine mem_append_left _ (IH (λ x hx, mem_of_ne_of_mem _ (h x hx))), rintro rfl, exact hx hfa }, have hfa' : f (f a) ≠ f a := mt (λ h, f.injective h) hfa, have : ∀ (x : α), (swap a (f a) * f) x ≠ x → x ∈ l, { intros x hx, have hxa : x ≠ a, { rintro rfl, apply hx, simp only [mul_apply, swap_apply_right] }, refine list.mem_of_ne_of_mem hxa (h x (λ h, _)), simp only [h, mul_apply, swap_apply_def, mul_apply, ne.def, apply_eq_iff_eq] at hx; split_ifs at hx, exacts [hxa (h.symm.trans h_1), hx h] }, suffices : f ∈ perms_of_list l ∨ ∃ (b ∈ l) (g ∈ perms_of_list l), swap a b * g = f, { simpa only [perms_of_list, exists_prop, list.mem_map, mem_append, list.mem_bind] }, refine or_iff_not_imp_left.2 (λ hfl, ⟨f a, _, swap a (f a) * f, IH this, _⟩), { exact mem_of_ne_of_mem hfa (h _ hfa') }, { rw [←mul_assoc, mul_def (swap a (f a)) (swap a (f a)), swap_swap, ←perm.one_def, one_mul] } end lemma mem_of_mem_perms_of_list : ∀ {l : list α} {f : perm α}, f ∈ perms_of_list l → ∀ {x}, f x ≠ x → x ∈ l | [] f h := have f = 1 := by simpa [perms_of_list] using h, by rw this; simp | (a :: l) f h := (mem_append.1 h).elim (λ h x hx, mem_cons_of_mem _ (mem_of_mem_perms_of_list h hx)) (λ h x hx, let ⟨y, hy, hy'⟩ := list.mem_bind.1 h in let ⟨g, hg₁, hg₂⟩ := list.mem_map.1 hy' in if hxa : x = a then by simp [hxa] else if hxy : x = y then mem_cons_of_mem _ $ by rwa hxy else mem_cons_of_mem _ $ mem_of_mem_perms_of_list hg₁ $ by rw [eq_inv_mul_iff_mul_eq.2 hg₂, mul_apply, swap_inv, swap_apply_def]; split_ifs; [exact ne.symm hxy, exact ne.symm hxa, exact hx]) lemma mem_perms_of_list_iff {l : list α} {f : perm α} : f ∈ perms_of_list l ↔ ∀ {x}, f x ≠ x → x ∈ l := ⟨mem_of_mem_perms_of_list, mem_perms_of_list_of_mem⟩ lemma nodup_perms_of_list : ∀ {l : list α} (hl : l.nodup), (perms_of_list l).nodup | [] hl := by simp [perms_of_list] | (a :: l) hl := have hl' : l.nodup, from hl.of_cons, have hln' : (perms_of_list l).nodup, from nodup_perms_of_list hl', have hmeml : ∀ {f : perm α}, f ∈ perms_of_list l → f a = a, from λ f hf, not_not.1 (mt (mem_of_mem_perms_of_list hf) (nodup_cons.1 hl).1), by rw [perms_of_list, list.nodup_append, list.nodup_bind, pairwise_iff_nth_le]; exact ⟨hln', ⟨λ _ _, hln'.map $ λ _ _, mul_left_cancel, λ i j hj hij x hx₁ hx₂, let ⟨f, hf⟩ := list.mem_map.1 hx₁ in let ⟨g, hg⟩ := list.mem_map.1 hx₂ in have hix : x a = nth_le l i (lt_trans hij hj), by rw [←hf.2, mul_apply, hmeml hf.1, swap_apply_left], have hiy : x a = nth_le l j hj, by rw [← hg.2, mul_apply, hmeml hg.1, swap_apply_left], absurd (hf.2.trans (hg.2.symm)) $ λ h, ne_of_lt hij $ nodup_iff_nth_le_inj.1 hl' i j (lt_trans hij hj) hj $ by rw [← hix, hiy]⟩, λ f hf₁ hf₂, let ⟨x, hx, hx'⟩ := list.mem_bind.1 hf₂ in let ⟨g, hg⟩ := list.mem_map.1 hx' in have hgxa : g⁻¹ x = a, from f.injective $ by rw [hmeml hf₁, ← hg.2]; simp, have hxa : x ≠ a, from λ h, (list.nodup_cons.1 hl).1 (h ▸ hx), (list.nodup_cons.1 hl).1 $ hgxa ▸ mem_of_mem_perms_of_list hg.1 (by rwa [apply_inv_self, hgxa])⟩ /-- Given a finset, produce the finset of all permutations of its elements. -/ def perms_of_finset (s : finset α) : finset (perm α) := quotient.hrec_on s.1 (λ l hl, ⟨perms_of_list l, nodup_perms_of_list hl⟩) (λ a b hab, hfunext (congr_arg _ (quotient.sound hab)) (λ ha hb _, heq_of_eq $ finset.ext $ by simp [mem_perms_of_list_iff, hab.mem_iff])) s.2 lemma mem_perms_of_finset_iff : ∀ {s : finset α} {f : perm α}, f ∈ perms_of_finset s ↔ ∀ {x}, f x ≠ x → x ∈ s := by rintros ⟨⟨l⟩, hs⟩ f; exact mem_perms_of_list_iff lemma card_perms_of_finset : ∀ (s : finset α), (perms_of_finset s).card = s.card! := by rintros ⟨⟨l⟩, hs⟩; exact length_perms_of_list l /-- The collection of permutations of a fintype is a fintype. -/ def fintype_perm [fintype α] : fintype (perm α) := ⟨perms_of_finset (@finset.univ α _), by simp [mem_perms_of_finset_iff]⟩ instance [fintype α] [fintype β] : fintype (α ≃ β) := if h : fintype.card β = fintype.card α then trunc.rec_on_subsingleton (fintype.trunc_equiv_fin α) (λ eα, trunc.rec_on_subsingleton (fintype.trunc_equiv_fin β) (λ eβ, @fintype.of_equiv _ (perm α) fintype_perm (equiv_congr (equiv.refl α) (eα.trans (eq.rec_on h eβ.symm)) : (α ≃ α) ≃ (α ≃ β)))) else ⟨∅, λ x, false.elim (h (fintype.card_eq.2 ⟨x.symm⟩))⟩ lemma fintype.card_perm [fintype α] : fintype.card (perm α) = (fintype.card α)! := subsingleton.elim (@fintype_perm α _ _) (@equiv.fintype α α _ _ _ _) ▸ card_perms_of_finset _ lemma fintype.card_equiv [fintype α] [fintype β] (e : α ≃ β) : fintype.card (α ≃ β) = (fintype.card α)! := fintype.card_congr (equiv_congr (equiv.refl α) e) ▸ fintype.card_perm lemma univ_eq_singleton_of_card_one {α} [fintype α] (x : α) (h : fintype.card α = 1) : (univ : finset α) = {x} := begin symmetry, apply eq_of_subset_of_card_le (subset_univ ({x})), apply le_of_eq, simp [h, finset.card_univ] end end equiv namespace fintype section choose open fintype equiv variables [fintype α] (p : α → Prop) [decidable_pred p] /-- Given a fintype `α` and a predicate `p`, associate to a proof that there is a unique element of `α` satisfying `p` this unique element, as an element of the corresponding subtype. -/ def choose_x (hp : ∃! a : α, p a) : {a // p a} := ⟨finset.choose p univ (by simp; exact hp), finset.choose_property _ _ _⟩ /-- Given a fintype `α` and a predicate `p`, associate to a proof that there is a unique element of `α` satisfying `p` this unique element, as an element of `α`. -/ def choose (hp : ∃! a, p a) : α := choose_x p hp lemma choose_spec (hp : ∃! a, p a) : p (choose p hp) := (choose_x p hp).property @[simp] lemma choose_subtype_eq {α : Type*} (p : α → Prop) [fintype {a : α // p a}] [decidable_eq α] (x : {a : α // p a}) (h : ∃! (a : {a // p a}), (a : α) = x := ⟨x, rfl, λ y hy, by simpa [subtype.ext_iff] using hy⟩) : fintype.choose (λ (y : {a : α // p a}), (y : α) = x) h = x := by rw [subtype.ext_iff, fintype.choose_spec (λ (y : {a : α // p a}), (y : α) = x) _] end choose section bijection_inverse open function variables [fintype α] [decidable_eq β] {f : α → β} /-- `bij_inv f` is the unique inverse to a bijection `f`. This acts as a computable alternative to `function.inv_fun`. -/ def bij_inv (f_bij : bijective f) (b : β) : α := fintype.choose (λ a, f a = b) begin rcases f_bij.right b with ⟨a', fa_eq_b⟩, rw ← fa_eq_b, exact ⟨a', ⟨rfl, (λ a h, f_bij.left h)⟩⟩ end lemma left_inverse_bij_inv (f_bij : bijective f) : left_inverse (bij_inv f_bij) f := λ a, f_bij.left (choose_spec (λ a', f a' = f a) _) lemma right_inverse_bij_inv (f_bij : bijective f) : right_inverse (bij_inv f_bij) f := λ b, choose_spec (λ a', f a' = b) _ lemma bijective_bij_inv (f_bij : bijective f) : bijective (bij_inv f_bij) := ⟨(right_inverse_bij_inv _).injective, (left_inverse_bij_inv _).surjective⟩ end bijection_inverse lemma well_founded_of_trans_of_irrefl [fintype α] (r : α → α → Prop) [is_trans α r] [is_irrefl α r] : well_founded r := by classical; exact have ∀ x y, r x y → (univ.filter (λ z, r z x)).card < (univ.filter (λ z, r z y)).card, from λ x y hxy, finset.card_lt_card $ by simp only [finset.lt_iff_ssubset.symm, lt_iff_le_not_le, finset.le_iff_subset, finset.subset_iff, mem_filter, true_and, mem_univ, hxy]; exact ⟨λ z hzx, trans hzx hxy, not_forall_of_exists_not ⟨x, not_imp.2 ⟨hxy, irrefl x⟩⟩⟩, subrelation.wf this (measure_wf _) lemma preorder.well_founded_lt [fintype α] [preorder α] : well_founded ((<) : α → α → Prop) := well_founded_of_trans_of_irrefl _ lemma preorder.well_founded_gt [fintype α] [preorder α] : well_founded ((>) : α → α → Prop) := well_founded_of_trans_of_irrefl _ @[instance, priority 10] lemma linear_order.is_well_order_lt [fintype α] [linear_order α] : is_well_order α (<) := { wf := preorder.well_founded_lt } @[instance, priority 10] lemma linear_order.is_well_order_gt [fintype α] [linear_order α] : is_well_order α (>) := { wf := preorder.well_founded_gt } end fintype /-- A type is said to be infinite if it has no fintype instance. Note that `infinite α` is equivalent to `is_empty (fintype α)`. -/ class infinite (α : Type*) : Prop := (not_fintype : fintype α → false) lemma not_fintype (α : Type*) [h1 : infinite α] [h2 : fintype α] : false := infinite.not_fintype h2 protected lemma fintype.false {α : Type*} [infinite α] (h : fintype α) : false := not_fintype α protected lemma infinite.false {α : Type*} [fintype α] (h : infinite α) : false := not_fintype α @[simp] lemma is_empty_fintype {α : Type*} : is_empty (fintype α) ↔ infinite α := ⟨λ ⟨x⟩, ⟨x⟩, λ ⟨x⟩, ⟨x⟩⟩ /-- A non-infinite type is a fintype. -/ noncomputable def fintype_of_not_infinite {α : Type*} (h : ¬ infinite α) : fintype α := nonempty.some $ by rwa [← not_is_empty_iff, is_empty_fintype] section open_locale classical /-- Any type is (classically) either a `fintype`, or `infinite`. One can obtain the relevant typeclasses via `cases fintype_or_infinite α; resetI`. -/ noncomputable def fintype_or_infinite (α : Type*) : psum (fintype α) (infinite α) := if h : infinite α then psum.inr h else psum.inl (fintype_of_not_infinite h) end lemma finset.exists_minimal {α : Type*} [preorder α] (s : finset α) (h : s.nonempty) : ∃ m ∈ s, ∀ x ∈ s, ¬ (x < m) := begin obtain ⟨c, hcs : c ∈ s⟩ := h, have : well_founded (@has_lt.lt {x // x ∈ s} _) := fintype.well_founded_of_trans_of_irrefl _, obtain ⟨⟨m, hms : m ∈ s⟩, -, H⟩ := this.has_min set.univ ⟨⟨c, hcs⟩, trivial⟩, exact ⟨m, hms, λ x hx hxm, H ⟨x, hx⟩ trivial hxm⟩, end lemma finset.exists_maximal {α : Type*} [preorder α] (s : finset α) (h : s.nonempty) : ∃ m ∈ s, ∀ x ∈ s, ¬ (m < x) := @finset.exists_minimal αᵒᵈ _ s h namespace infinite lemma exists_not_mem_finset [infinite α] (s : finset α) : ∃ x, x ∉ s := not_forall.1 $ λ h, fintype.false ⟨s, h⟩ @[priority 100] -- see Note [lower instance priority] instance (α : Type*) [H : infinite α] : nontrivial α := ⟨let ⟨x, hx⟩ := exists_not_mem_finset (∅ : finset α) in let ⟨y, hy⟩ := exists_not_mem_finset ({x} : finset α) in ⟨y, x, by simpa only [mem_singleton] using hy⟩⟩ protected lemma nonempty (α : Type*) [infinite α] : nonempty α := by apply_instance lemma of_injective [infinite β] (f : β → α) (hf : injective f) : infinite α := ⟨λ I, by exactI (fintype.of_injective f hf).false⟩ lemma of_surjective [infinite β] (f : α → β) (hf : surjective f) : infinite α := ⟨λ I, by { classical, exactI (fintype.of_surjective f hf).false }⟩ end infinite instance : infinite ℕ := ⟨λ ⟨s, hs⟩, finset.not_mem_range_self $ s.subset_range_sup_succ (hs _)⟩ instance : infinite ℤ := infinite.of_injective int.of_nat (λ _ _, int.of_nat.inj) instance infinite.set [infinite α] : infinite (set α) := infinite.of_injective singleton (λ a b, set.singleton_eq_singleton_iff.1) instance [infinite α] : infinite (finset α) := infinite.of_injective singleton finset.singleton_injective instance [nonempty α] : infinite (multiset α) := begin inhabit α, exact infinite.of_injective (multiset.repeat default) (multiset.repeat_injective _), end instance [nonempty α] : infinite (list α) := infinite.of_surjective (coe : list α → multiset α) (surjective_quot_mk _) instance [infinite α] : infinite (option α) := infinite.of_injective some (option.some_injective α) instance sum.infinite_of_left [infinite α] : infinite (α ⊕ β) := infinite.of_injective sum.inl sum.inl_injective instance sum.infinite_of_right [infinite β] : infinite (α ⊕ β) := infinite.of_injective sum.inr sum.inr_injective @[simp] lemma infinite_sum : infinite (α ⊕ β) ↔ infinite α ∨ infinite β := begin refine ⟨λ H, _, λ H, H.elim (@sum.infinite_of_left α β) (@sum.infinite_of_right α β)⟩, contrapose! H, haveI := fintype_of_not_infinite H.1, haveI := fintype_of_not_infinite H.2, exact infinite.false end instance prod.infinite_of_right [nonempty α] [infinite β] : infinite (α × β) := infinite.of_surjective prod.snd prod.snd_surjective instance prod.infinite_of_left [infinite α] [nonempty β] : infinite (α × β) := infinite.of_surjective prod.fst prod.fst_surjective @[simp] lemma infinite_prod : infinite (α × β) ↔ infinite α ∧ nonempty β ∨ nonempty α ∧ infinite β := begin refine ⟨λ H, _, λ H, H.elim (and_imp.2 $ @prod.infinite_of_left α β) (and_imp.2 $ @prod.infinite_of_right α β)⟩, rw and.comm, contrapose! H, introI H', rcases infinite.nonempty (α × β) with ⟨a, b⟩, haveI := fintype_of_not_infinite (H.1 ⟨b⟩), haveI := fintype_of_not_infinite (H.2 ⟨a⟩), exact H'.false end namespace infinite private noncomputable def nat_embedding_aux (α : Type*) [infinite α] : ℕ → α | n := by letI := classical.dec_eq α; exact classical.some (exists_not_mem_finset ((multiset.range n).pmap (λ m (hm : m < n), nat_embedding_aux m) (λ _, multiset.mem_range.1)).to_finset) private lemma nat_embedding_aux_injective (α : Type*) [infinite α] : function.injective (nat_embedding_aux α) := begin rintro m n h, letI := classical.dec_eq α, wlog hmlen : m ≤ n using m n, by_contradiction hmn, have hmn : m < n, from lt_of_le_of_ne hmlen hmn, refine (classical.some_spec (exists_not_mem_finset ((multiset.range n).pmap (λ m (hm : m < n), nat_embedding_aux α m) (λ _, multiset.mem_range.1)).to_finset)) _, refine multiset.mem_to_finset.2 (multiset.mem_pmap.2 ⟨m, multiset.mem_range.2 hmn, _⟩), rw [h, nat_embedding_aux] end /-- Embedding of `ℕ` into an infinite type. -/ noncomputable def nat_embedding (α : Type*) [infinite α] : ℕ ↪ α := ⟨_, nat_embedding_aux_injective α⟩ lemma exists_subset_card_eq (α : Type*) [infinite α] (n : ℕ) : ∃ s : finset α, s.card = n := ⟨(range n).map (nat_embedding α), by rw [card_map, card_range]⟩ end infinite /-- If every finset in a type has bounded cardinality, that type is finite. -/ noncomputable def fintype_of_finset_card_le {ι : Type*} (n : ℕ) (w : ∀ s : finset ι, s.card ≤ n) : fintype ι := begin apply fintype_of_not_infinite, introI i, obtain ⟨s, c⟩ := infinite.exists_subset_card_eq ι (n+1), specialize w s, rw c at w, exact nat.not_succ_le_self n w, end lemma not_injective_infinite_fintype [infinite α] [fintype β] (f : α → β) : ¬ injective f := λ hf, (fintype.of_injective f hf).false /-- The pigeonhole principle for infinitely many pigeons in finitely many pigeonholes. If there are infinitely many pigeons in finitely many pigeonholes, then there are at least two pigeons in the same pigeonhole. See also: `fintype.exists_ne_map_eq_of_card_lt`, `fintype.exists_infinite_fiber`. -/ lemma fintype.exists_ne_map_eq_of_infinite [infinite α] [fintype β] (f : α → β) : ∃ x y : α, x ≠ y ∧ f x = f y := begin classical, by_contra' hf, apply not_injective_infinite_fintype f, intros x y, contrapose, apply hf, end -- irreducible due to this conversation on Zulip: -- https://leanprover.zulipchat.com/#narrow/stream/113488-general/ -- topic/.60simp.60.20ignoring.20lemmas.3F/near/241824115 @[irreducible] instance function.embedding.is_empty {α β} [infinite α] [fintype β] : is_empty (α ↪ β) := ⟨λ f, let ⟨x, y, ne, feq⟩ := fintype.exists_ne_map_eq_of_infinite f in ne $ f.injective feq⟩ @[priority 100] noncomputable instance function.embedding.fintype' {α β : Type*} [fintype β] : fintype (α ↪ β) := by casesI fintype_or_infinite α; apply_instance /-- The strong pigeonhole principle for infinitely many pigeons in finitely many pigeonholes. If there are infinitely many pigeons in finitely many pigeonholes, then there is a pigeonhole with infinitely many pigeons. See also: `fintype.exists_ne_map_eq_of_infinite` -/ lemma fintype.exists_infinite_fiber [infinite α] [fintype β] (f : α → β) : ∃ y : β, infinite (f ⁻¹' {y}) := begin classical, by_contra' hf, haveI := λ y, fintype_of_not_infinite $ hf y, let key : fintype α := { elems := univ.bUnion (λ (y : β), (f ⁻¹' {y}).to_finset), complete := by simp }, exact key.false, end lemma not_surjective_fintype_infinite [fintype α] [infinite β] (f : α → β) : ¬ surjective f := assume (hf : surjective f), have H : infinite α := infinite.of_surjective f hf, by exactI not_fintype α section trunc /-- For `s : multiset α`, we can lift the existential statement that `∃ x, x ∈ s` to a `trunc α`. -/ def trunc_of_multiset_exists_mem {α} (s : multiset α) : (∃ x, x ∈ s) → trunc α := quotient.rec_on_subsingleton s $ λ l h, match l, h with | [], _ := false.elim (by tauto) | (a :: _), _ := trunc.mk a end /-- A `nonempty` `fintype` constructively contains an element. -/ def trunc_of_nonempty_fintype (α) [nonempty α] [fintype α] : trunc α := trunc_of_multiset_exists_mem finset.univ.val (by simp) /-- A `fintype` with positive cardinality constructively contains an element. -/ def trunc_of_card_pos {α} [fintype α] (h : 0 < fintype.card α) : trunc α := by { letI := (fintype.card_pos_iff.mp h), exact trunc_of_nonempty_fintype α } /-- By iterating over the elements of a fintype, we can lift an existential statement `∃ a, P a` to `trunc (Σ' a, P a)`, containing data. -/ def trunc_sigma_of_exists {α} [fintype α] {P : α → Prop} [decidable_pred P] (h : ∃ a, P a) : trunc (Σ' a, P a) := @trunc_of_nonempty_fintype (Σ' a, P a) (exists.elim h $ λ a ha, ⟨⟨a, ha⟩⟩) _ end trunc namespace multiset variables [fintype α] [decidable_eq α] @[simp] lemma count_univ (a : α) : count a finset.univ.val = 1 := count_eq_one_of_mem finset.univ.nodup (finset.mem_univ _) end multiset namespace fintype /-- A recursor principle for finite types, analogous to `nat.rec`. It effectively says that every `fintype` is either `empty` or `option α`, up to an `equiv`. -/ def trunc_rec_empty_option {P : Type u → Sort v} (of_equiv : ∀ {α β}, α ≃ β → P α → P β) (h_empty : P pempty) (h_option : ∀ {α} [fintype α] [decidable_eq α], P α → P (option α)) (α : Type u) [fintype α] [decidable_eq α] : trunc (P α) := begin suffices : ∀ n : ℕ, trunc (P (ulift $ fin n)), { apply trunc.bind (this (fintype.card α)), intro h, apply trunc.map _ (fintype.trunc_equiv_fin α), intro e, exact of_equiv (equiv.ulift.trans e.symm) h }, intro n, induction n with n ih, { have : card pempty = card (ulift (fin 0)), { simp only [card_fin, card_pempty, card_ulift] }, apply trunc.bind (trunc_equiv_of_card_eq this), intro e, apply trunc.mk, refine of_equiv e h_empty, }, { have : card (option (ulift (fin n))) = card (ulift (fin n.succ)), { simp only [card_fin, card_option, card_ulift] }, apply trunc.bind (trunc_equiv_of_card_eq this), intro e, apply trunc.map _ ih, intro ih, refine of_equiv e (h_option ih), }, end /-- An induction principle for finite types, analogous to `nat.rec`. It effectively says that every `fintype` is either `empty` or `option α`, up to an `equiv`. -/ @[elab_as_eliminator] lemma induction_empty_option' {P : Π (α : Type u) [fintype α], Prop} (of_equiv : ∀ α β [fintype β] (e : α ≃ β), @P α (@fintype.of_equiv α β ‹_› e.symm) → @P β ‹_›) (h_empty : P pempty) (h_option : ∀ α [fintype α], by exactI P α → P (option α)) (α : Type u) [fintype α] : P α := begin obtain ⟨p⟩ := @trunc_rec_empty_option (λ α, ∀ h, @P α h) (λ α β e hα hβ, @of_equiv α β hβ e (hα _)) (λ _i, by convert h_empty) _ α _ (classical.dec_eq α), { exact p _ }, { rintro α hα - Pα hα', resetI, convert h_option α (Pα _) } end /-- An induction principle for finite types, analogous to `nat.rec`. It effectively says that every `fintype` is either `empty` or `option α`, up to an `equiv`. -/ lemma induction_empty_option {P : Type u → Prop} (of_equiv : ∀ {α β}, α ≃ β → P α → P β) (h_empty : P pempty) (h_option : ∀ {α} [fintype α], P α → P (option α)) (α : Type u) [fintype α] : P α := begin refine induction_empty_option' _ _ _ α, exacts [λ α β _, of_equiv, h_empty, @h_option] end end fintype /-- Auxiliary definition to show `exists_seq_of_forall_finset_exists`. -/ noncomputable def seq_of_forall_finset_exists_aux {α : Type*} [decidable_eq α] (P : α → Prop) (r : α → α → Prop) (h : ∀ (s : finset α), ∃ y, (∀ x ∈ s, P x) → (P y ∧ (∀ x ∈ s, r x y))) : ℕ → α | n := classical.some (h (finset.image (λ (i : fin n), seq_of_forall_finset_exists_aux i) (finset.univ : finset (fin n)))) using_well_founded {dec_tac := `[exact i.2]} /-- Induction principle to build a sequence, by adding one point at a time satisfying a given relation with respect to all the previously chosen points. More precisely, Assume that, for any finite set `s`, one can find another point satisfying some relation `r` with respect to all the points in `s`. Then one may construct a function `f : ℕ → α` such that `r (f m) (f n)` holds whenever `m < n`. We also ensure that all constructed points satisfy a given predicate `P`. -/ lemma exists_seq_of_forall_finset_exists {α : Type*} (P : α → Prop) (r : α → α → Prop) (h : ∀ (s : finset α), (∀ x ∈ s, P x) → ∃ y, P y ∧ (∀ x ∈ s, r x y)) : ∃ (f : ℕ → α), (∀ n, P (f n)) ∧ (∀ m n, m < n → r (f m) (f n)) := begin classical, haveI : nonempty α, { rcases h ∅ (by simp) with ⟨y, hy⟩, exact ⟨y⟩ }, choose! F hF using h, have h' : ∀ (s : finset α), ∃ y, (∀ x ∈ s, P x) → (P y ∧ (∀ x ∈ s, r x y)) := λ s, ⟨F s, hF s⟩, set f := seq_of_forall_finset_exists_aux P r h' with hf, have A : ∀ (n : ℕ), P (f n), { assume n, induction n using nat.strong_induction_on with n IH, have IH' : ∀ (x : fin n), P (f x) := λ n, IH n.1 n.2, rw [hf, seq_of_forall_finset_exists_aux], exact (classical.some_spec (h' (finset.image (λ (i : fin n), f i) (finset.univ : finset (fin n)))) (by simp [IH'])).1 }, refine ⟨f, A, λ m n hmn, _⟩, nth_rewrite 1 hf, rw seq_of_forall_finset_exists_aux, apply (classical.some_spec (h' (finset.image (λ (i : fin n), f i) (finset.univ : finset (fin n)))) (by simp [A])).2, exact finset.mem_image.2 ⟨⟨m, hmn⟩, finset.mem_univ _, rfl⟩, end /-- Induction principle to build a sequence, by adding one point at a time satisfying a given symmetric relation with respect to all the previously chosen points. More precisely, Assume that, for any finite set `s`, one can find another point satisfying some relation `r` with respect to all the points in `s`. Then one may construct a function `f : ℕ → α` such that `r (f m) (f n)` holds whenever `m ≠ n`. We also ensure that all constructed points satisfy a given predicate `P`. -/ lemma exists_seq_of_forall_finset_exists' {α : Type*} (P : α → Prop) (r : α → α → Prop) [is_symm α r] (h : ∀ (s : finset α), (∀ x ∈ s, P x) → ∃ y, P y ∧ (∀ x ∈ s, r x y)) : ∃ (f : ℕ → α), (∀ n, P (f n)) ∧ (∀ m n, m ≠ n → r (f m) (f n)) := begin rcases exists_seq_of_forall_finset_exists P r h with ⟨f, hf, hf'⟩, refine ⟨f, hf, λ m n hmn, _⟩, rcases lt_trichotomy m n with h|rfl|h, { exact hf' m n h }, { exact (hmn rfl).elim }, { apply symm, exact hf' n m h } end /-- A custom induction principle for fintypes. The base case is a subsingleton type, and the induction step is for non-trivial types, and one can assume the hypothesis for smaller types (via `fintype.card`). The major premise is `fintype α`, so to use this with the `induction` tactic you have to give a name to that instance and use that name. -/ @[elab_as_eliminator] lemma fintype.induction_subsingleton_or_nontrivial {P : Π α [fintype α], Prop} (α : Type*) [fintype α] (hbase : ∀ α [fintype α] [subsingleton α], by exactI P α) (hstep : ∀ α [fintype α] [nontrivial α], by exactI ∀ (ih : ∀ β [fintype β], by exactI ∀ (h : fintype.card β < fintype.card α), P β), P α) : P α := begin obtain ⟨ n, hn ⟩ : ∃ n, fintype.card α = n := ⟨fintype.card α, rfl⟩, unfreezingI { induction n using nat.strong_induction_on with n ih generalizing α }, casesI (subsingleton_or_nontrivial α) with hsing hnontriv, { apply hbase, }, { apply hstep, introsI β _ hlt, rw hn at hlt, exact (ih (fintype.card β) hlt _ rfl), } end
67bce0da61833edd59e33d1ecea7ad0ce1d7c89d
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/category_theory/sites/sieves.lean
0b439ab41467ac4d9b49169f8f3ef7ec9c26f0c6
[ "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
25,158
lean
/- Copyright (c) 2020 Bhavik Mehta. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Bhavik Mehta, E. W. Ayers -/ import order.complete_lattice import category_theory.over import category_theory.yoneda import category_theory.limits.shapes.pullbacks import data.set.lattice /-! # Theory of sieves > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. - For an object `X` of a category `C`, a `sieve X` is a set of morphisms to `X` which is closed under left-composition. - The complete lattice structure on sieves is given, as well as the Galois insertion given by downward-closing. - A `sieve X` (functorially) induces a presheaf on `C` together with a monomorphism to the yoneda embedding of `X`. ## Tags sieve, pullback -/ universes v₁ v₂ v₃ u₁ u₂ u₃ namespace category_theory open category limits variables {C : Type u₁} [category.{v₁} C] {D : Type u₂} [category.{v₂} D] (F : C ⥤ D) variables {X Y Z : C} (f : Y ⟶ X) /-- A set of arrows all with codomain `X`. -/ @[derive complete_lattice] def presieve (X : C) := Π ⦃Y⦄, set (Y ⟶ X) namespace presieve instance : inhabited (presieve X) := ⟨⊤⟩ /-- Given a sieve `S` on `X : C`, its associated diagram `S.diagram` is defined to be the natural functor from the full subcategory of the over category `C/X` consisting of arrows in `S` to `C`. -/ abbreviation diagram (S : presieve X) : full_subcategory (λ (f : over X), S f.hom) ⥤ C := full_subcategory_inclusion _ ⋙ over.forget X /-- Given a sieve `S` on `X : C`, its associated cocone `S.cocone` is defined to be the natural cocone over the diagram defined above with cocone point `X`. -/ abbreviation cocone (S : presieve X) : cocone S.diagram := (over.forget_cocone X).whisker (full_subcategory_inclusion _) /-- Given a set of arrows `S` all with codomain `X`, and a set of arrows with codomain `Y` for each `f : Y ⟶ X` in `S`, produce a set of arrows with codomain `X`: `{ g ≫ f | (f : Y ⟶ X) ∈ S, (g : Z ⟶ Y) ∈ R f }`. -/ def bind (S : presieve X) (R : Π ⦃Y⦄ ⦃f : Y ⟶ X⦄, S f → presieve Y) : presieve X := λ Z h, ∃ (Y : C) (g : Z ⟶ Y) (f : Y ⟶ X) (H : S f), R H g ∧ g ≫ f = h @[simp] lemma bind_comp {S : presieve X} {R : Π ⦃Y : C⦄ ⦃f : Y ⟶ X⦄, S f → presieve Y} {g : Z ⟶ Y} (h₁ : S f) (h₂ : R h₁ g) : bind S R (g ≫ f) := ⟨_, _, _, h₁, h₂, rfl⟩ /-- The singleton presieve. -/ -- Note we can't make this into `has_singleton` because of the out-param. inductive singleton : presieve X | mk : singleton f @[simp] lemma singleton_eq_iff_domain (f g : Y ⟶ X) : singleton f g ↔ f = g := begin split, { rintro ⟨a, rfl⟩, refl }, { rintro rfl, apply singleton.mk, } end lemma singleton_self : singleton f f := singleton.mk /-- Pullback a set of arrows with given codomain along a fixed map, by taking the pullback in the category. This is not the same as the arrow set of `sieve.pullback`, but there is a relation between them in `pullback_arrows_comm`. -/ inductive pullback_arrows [has_pullbacks C] (R : presieve X) : presieve Y | mk (Z : C) (h : Z ⟶ X) : R h → pullback_arrows (pullback.snd : pullback h f ⟶ Y) lemma pullback_singleton [has_pullbacks C] (g : Z ⟶ X) : pullback_arrows f (singleton g) = singleton (pullback.snd : pullback g f ⟶ _) := begin ext W h, split, { rintro ⟨W, _, _, _⟩, exact singleton.mk }, { rintro ⟨_⟩, exact pullback_arrows.mk Z g singleton.mk } end /-- Construct the presieve given by the family of arrows indexed by `ι`. -/ inductive of_arrows {ι : Type*} (Y : ι → C) (f : Π i, Y i ⟶ X) : presieve X | mk (i : ι) : of_arrows (f i) lemma of_arrows_punit : of_arrows _ (λ _ : punit, f) = singleton f := begin ext Y g, split, { rintro ⟨_⟩, apply singleton.mk }, { rintro ⟨_⟩, exact of_arrows.mk punit.star }, end lemma of_arrows_pullback [has_pullbacks C] {ι : Type*} (Z : ι → C) (g : Π (i : ι), Z i ⟶ X) : of_arrows (λ i, pullback (g i) f) (λ i, pullback.snd) = pullback_arrows f (of_arrows Z g) := begin ext T h, split, { rintro ⟨hk⟩, exact pullback_arrows.mk _ _ (of_arrows.mk hk) }, { rintro ⟨W, k, hk₁⟩, cases hk₁ with i hi, apply of_arrows.mk }, end lemma of_arrows_bind {ι : Type*} (Z : ι → C) (g : Π (i : ι), Z i ⟶ X) (j : Π ⦃Y⦄ (f : Y ⟶ X), of_arrows Z g f → Type*) (W : Π ⦃Y⦄ (f : Y ⟶ X) H, j f H → C) (k : Π ⦃Y⦄ (f : Y ⟶ X) H i, W f H i ⟶ Y) : (of_arrows Z g).bind (λ Y f H, of_arrows (W f H) (k f H)) = of_arrows (λ (i : Σ i, j _ (of_arrows.mk i)), W (g i.1) _ i.2) (λ ij, k (g ij.1) _ ij.2 ≫ g ij.1) := begin ext Y f, split, { rintro ⟨_, _, _, ⟨i⟩, ⟨i'⟩, rfl⟩, exact of_arrows.mk (sigma.mk _ _) }, { rintro ⟨i⟩, exact bind_comp _ (of_arrows.mk _) (of_arrows.mk _) } end /-- Given a presieve on `F(X)`, we can define a presieve on `X` by taking the preimage via `F`. -/ def functor_pullback (R : presieve (F.obj X)) : presieve X := λ _ f, R (F.map f) @[simp] lemma functor_pullback_mem (R : presieve (F.obj X)) {Y} (f : Y ⟶ X) : R.functor_pullback F f ↔ R (F.map f) := iff.rfl @[simp] lemma functor_pullback_id (R : presieve X) : R.functor_pullback (𝟭 _) = R := rfl section functor_pushforward variables {E : Type u₃} [category.{v₃} E] (G : D ⥤ E) /-- Given a presieve on `X`, we can define a presieve on `F(X)` (which is actually a sieve) by taking the sieve generated by the image via `F`. -/ def functor_pushforward (S : presieve X) : presieve (F.obj X) := λ Y f, ∃ (Z : C) (g : Z ⟶ X) (h : Y ⟶ F.obj Z), S g ∧ f = h ≫ F.map g /-- An auxillary definition in order to fix the choice of the preimages between various definitions. -/ @[nolint has_nonempty_instance] structure functor_pushforward_structure (S : presieve X) {Y} (f : Y ⟶ F.obj X) := (preobj : C) (premap : preobj ⟶ X) (lift : Y ⟶ F.obj preobj) (cover : S premap) (fac : f = lift ≫ F.map premap) /-- The fixed choice of a preimage. -/ noncomputable def get_functor_pushforward_structure {F : C ⥤ D} {S : presieve X} {Y : D} {f : Y ⟶ F.obj X} (h : S.functor_pushforward F f) : functor_pushforward_structure F S f := by { choose Z f' g h₁ h using h, exact ⟨Z, f', g, h₁, h⟩ } lemma functor_pushforward_comp (R : presieve X) : R.functor_pushforward (F ⋙ G) = (R.functor_pushforward F).functor_pushforward G := begin ext x f, split, { rintro ⟨X, f₁, g₁, h₁, rfl⟩, exact ⟨F.obj X, F.map f₁, g₁, ⟨X, f₁, 𝟙 _, h₁, by simp⟩, rfl⟩ }, { rintro ⟨X, f₁, g₁, ⟨X', f₂, g₂, h₁, rfl⟩, rfl⟩, use ⟨X', f₂, g₁ ≫ G.map g₂, h₁, by simp⟩ } end lemma image_mem_functor_pushforward (R : presieve X) {f : Y ⟶ X} (h : R f) : R.functor_pushforward F (F.map f) := ⟨Y, f, 𝟙 _, h, by simp⟩ end functor_pushforward end presieve /-- For an object `X` of a category `C`, a `sieve X` is a set of morphisms to `X` which is closed under left-composition. -/ structure sieve {C : Type u₁} [category.{v₁} C] (X : C) := (arrows : presieve X) (downward_closed' : ∀ {Y Z f} (hf : arrows f) (g : Z ⟶ Y), arrows (g ≫ f)) namespace sieve instance : has_coe_to_fun (sieve X) (λ _, presieve X) := ⟨sieve.arrows⟩ initialize_simps_projections sieve (arrows → apply) variables {S R : sieve X} @[simp, priority 100] lemma downward_closed (S : sieve X) {f : Y ⟶ X} (hf : S f) (g : Z ⟶ Y) : S (g ≫ f) := S.downward_closed' hf g lemma arrows_ext : Π {R S : sieve X}, R.arrows = S.arrows → R = S | ⟨Ra, _⟩ ⟨Sa, _⟩ rfl := rfl @[ext] protected lemma ext {R S : sieve X} (h : ∀ ⦃Y⦄ (f : Y ⟶ X), R f ↔ S f) : R = S := arrows_ext $ funext $ λ x, funext $ λ f, propext $ h f protected lemma ext_iff {R S : sieve X} : R = S ↔ (∀ ⦃Y⦄ (f : Y ⟶ X), R f ↔ S f) := ⟨λ h Y f, h ▸ iff.rfl, sieve.ext⟩ open lattice /-- The supremum of a collection of sieves: the union of them all. -/ protected def Sup (𝒮 : set (sieve X)) : (sieve X) := { arrows := λ Y, {f | ∃ S ∈ 𝒮, sieve.arrows S f}, downward_closed' := λ Y Z f, by { rintro ⟨S, hS, hf⟩ g, exact ⟨S, hS, S.downward_closed hf _⟩ } } /-- The infimum of a collection of sieves: the intersection of them all. -/ protected def Inf (𝒮 : set (sieve X)) : (sieve X) := { arrows := λ Y, {f | ∀ S ∈ 𝒮, sieve.arrows S f}, downward_closed' := λ Y Z f hf g S H, S.downward_closed (hf S H) g } /-- The union of two sieves is a sieve. -/ protected def union (S R : sieve X) : sieve X := { arrows := λ Y f, S f ∨ R f, downward_closed' := by { rintros Y Z f (h | h) g; simp [h] } } /-- The intersection of two sieves is a sieve. -/ protected def inter (S R : sieve X) : sieve X := { arrows := λ Y f, S f ∧ R f, downward_closed' := by { rintros Y Z f ⟨h₁, h₂⟩ g, simp [h₁, h₂] } } /-- Sieves on an object `X` form a complete lattice. We generate this directly rather than using the galois insertion for nicer definitional properties. -/ instance : complete_lattice (sieve X) := { le := λ S R, ∀ ⦃Y⦄ (f : Y ⟶ X), S f → R f, le_refl := λ S f q, id, le_trans := λ S₁ S₂ S₃ S₁₂ S₂₃ Y f h, S₂₃ _ (S₁₂ _ h), le_antisymm := λ S R p q, sieve.ext (λ Y f, ⟨p _, q _⟩), top := { arrows := λ _, set.univ, downward_closed' := λ Y Z f g h, ⟨⟩ }, bot := { arrows := λ _, ∅, downward_closed' := λ _ _ _ p _, false.elim p }, sup := sieve.union, inf := sieve.inter, Sup := sieve.Sup, Inf := sieve.Inf, le_Sup := λ 𝒮 S hS Y f hf, ⟨S, hS, hf⟩, Sup_le := λ ℰ S hS Y f, by { rintro ⟨R, hR, hf⟩, apply hS R hR _ hf }, Inf_le := λ _ _ hS _ _ h, h _ hS, le_Inf := λ _ _ hS _ _ hf _ hR, hS _ hR _ hf, le_sup_left := λ _ _ _ _, or.inl, le_sup_right := λ _ _ _ _, or.inr, sup_le := λ _ _ _ a b _ _ hf, hf.elim (a _) (b _), inf_le_left := λ _ _ _ _, and.left, inf_le_right := λ _ _ _ _, and.right, le_inf := λ _ _ _ p q _ _ z, ⟨p _ z, q _ z⟩, le_top := λ _ _ _ _, trivial, bot_le := λ _ _ _, false.elim } /-- The maximal sieve always exists. -/ instance sieve_inhabited : inhabited (sieve X) := ⟨⊤⟩ @[simp] lemma Inf_apply {Ss : set (sieve X)} {Y} (f : Y ⟶ X) : Inf Ss f ↔ ∀ (S : sieve X) (H : S ∈ Ss), S f := iff.rfl @[simp] lemma Sup_apply {Ss : set (sieve X)} {Y} (f : Y ⟶ X) : Sup Ss f ↔ ∃ (S : sieve X) (H : S ∈ Ss), S f := iff.rfl @[simp] lemma inter_apply {R S : sieve X} {Y} (f : Y ⟶ X) : (R ⊓ S) f ↔ R f ∧ S f := iff.rfl @[simp] lemma union_apply {R S : sieve X} {Y} (f : Y ⟶ X) : (R ⊔ S) f ↔ R f ∨ S f := iff.rfl @[simp] lemma top_apply (f : Y ⟶ X) : (⊤ : sieve X) f := trivial /-- Generate the smallest sieve containing the given set of arrows. -/ @[simps] def generate (R : presieve X) : sieve X := { arrows := λ Z f, ∃ Y (h : Z ⟶ Y) (g : Y ⟶ X), R g ∧ h ≫ g = f, downward_closed' := begin rintro Y Z _ ⟨W, g, f, hf, rfl⟩ h, exact ⟨_, h ≫ g, _, hf, by simp⟩, end } /-- Given a presieve on `X`, and a sieve on each domain of an arrow in the presieve, we can bind to produce a sieve on `X`. -/ @[simps] def bind (S : presieve X) (R : Π ⦃Y⦄ ⦃f : Y ⟶ X⦄, S f → sieve Y) : sieve X := { arrows := S.bind (λ Y f h, R h), downward_closed' := begin rintro Y Z f ⟨W, f, h, hh, hf, rfl⟩ g, exact ⟨_, g ≫ f, _, hh, by simp [hf]⟩, end } open order lattice lemma sets_iff_generate (R : presieve X) (S : sieve X) : generate R ≤ S ↔ R ≤ S := ⟨λ H Y g hg, H _ ⟨_, 𝟙 _, _, hg, id_comp _⟩, λ ss Y f, begin rintro ⟨Z, f, g, hg, rfl⟩, exact S.downward_closed (ss Z hg) f, end⟩ /-- Show that there is a galois insertion (generate, set_over). -/ def gi_generate : galois_insertion (generate : presieve X → sieve X) arrows := { gc := sets_iff_generate, choice := λ 𝒢 _, generate 𝒢, choice_eq := λ _ _, rfl, le_l_u := λ S Y f hf, ⟨_, 𝟙 _, _, hf, id_comp _⟩ } lemma le_generate (R : presieve X) : R ≤ generate R := gi_generate.gc.le_u_l R @[simp] lemma generate_sieve (S : sieve X) : generate S = S := gi_generate.l_u_eq S /-- If the identity arrow is in a sieve, the sieve is maximal. -/ lemma id_mem_iff_eq_top : S (𝟙 X) ↔ S = ⊤ := ⟨λ h, top_unique $ λ Y f _, by simpa using downward_closed _ h f, λ h, h.symm ▸ trivial⟩ /-- If an arrow set contains a split epi, it generates the maximal sieve. -/ lemma generate_of_contains_is_split_epi {R : presieve X} (f : Y ⟶ X) [is_split_epi f] (hf : R f) : generate R = ⊤ := begin rw ← id_mem_iff_eq_top, exact ⟨_, section_ f, f, hf, by simp⟩, end @[simp] lemma generate_of_singleton_is_split_epi (f : Y ⟶ X) [is_split_epi f] : generate (presieve.singleton f) = ⊤ := generate_of_contains_is_split_epi f (presieve.singleton_self _) @[simp] lemma generate_top : generate (⊤ : presieve X) = ⊤ := generate_of_contains_is_split_epi (𝟙 _) ⟨⟩ /-- Given a morphism `h : Y ⟶ X`, send a sieve S on X to a sieve on Y as the inverse image of S with `_ ≫ h`. That is, `sieve.pullback S h := (≫ h) '⁻¹ S`. -/ @[simps] def pullback (h : Y ⟶ X) (S : sieve X) : sieve Y := { arrows := λ Y sl, S (sl ≫ h), downward_closed' := λ Z W f g h, by simp [g] } @[simp] lemma pullback_id : S.pullback (𝟙 _) = S := by simp [sieve.ext_iff] @[simp] lemma pullback_top {f : Y ⟶ X} : (⊤ : sieve X).pullback f = ⊤ := top_unique (λ _ g, id) lemma pullback_comp {f : Y ⟶ X} {g : Z ⟶ Y} (S : sieve X) : S.pullback (g ≫ f) = (S.pullback f).pullback g := by simp [sieve.ext_iff] @[simp] lemma pullback_inter {f : Y ⟶ X} (S R : sieve X) : (S ⊓ R).pullback f = S.pullback f ⊓ R.pullback f := by simp [sieve.ext_iff] lemma pullback_eq_top_iff_mem (f : Y ⟶ X) : S f ↔ S.pullback f = ⊤ := by rw [← id_mem_iff_eq_top, pullback_apply, id_comp] lemma pullback_eq_top_of_mem (S : sieve X) {f : Y ⟶ X} : S f → S.pullback f = ⊤ := (pullback_eq_top_iff_mem f).1 /-- Push a sieve `R` on `Y` forward along an arrow `f : Y ⟶ X`: `gf : Z ⟶ X` is in the sieve if `gf` factors through some `g : Z ⟶ Y` which is in `R`. -/ @[simps] def pushforward (f : Y ⟶ X) (R : sieve Y) : sieve X := { arrows := λ Z gf, ∃ g, g ≫ f = gf ∧ R g, downward_closed' := λ Z₁ Z₂ g ⟨j, k, z⟩ h, ⟨h ≫ j, by simp [k], by simp [z]⟩ } lemma pushforward_apply_comp {R : sieve Y} {Z : C} {g : Z ⟶ Y} (hg : R g) (f : Y ⟶ X) : R.pushforward f (g ≫ f) := ⟨g, rfl, hg⟩ lemma pushforward_comp {f : Y ⟶ X} {g : Z ⟶ Y} (R : sieve Z) : R.pushforward (g ≫ f) = (R.pushforward g).pushforward f := sieve.ext (λ W h, ⟨λ ⟨f₁, hq, hf₁⟩, ⟨f₁ ≫ g, by simpa, f₁, rfl, hf₁⟩, λ ⟨y, hy, z, hR, hz⟩, ⟨z, by rwa reassoc_of hR, hz⟩⟩) lemma galois_connection (f : Y ⟶ X) : galois_connection (sieve.pushforward f) (sieve.pullback f) := λ S R, ⟨λ hR Z g hg, hR _ ⟨g, rfl, hg⟩, λ hS Z g ⟨h, hg, hh⟩, hg ▸ hS h hh⟩ lemma pullback_monotone (f : Y ⟶ X) : monotone (sieve.pullback f) := (galois_connection f).monotone_u lemma pushforward_monotone (f : Y ⟶ X) : monotone (sieve.pushforward f) := (galois_connection f).monotone_l lemma le_pushforward_pullback (f : Y ⟶ X) (R : sieve Y) : R ≤ (R.pushforward f).pullback f := (galois_connection f).le_u_l _ lemma pullback_pushforward_le (f : Y ⟶ X) (R : sieve X) : (R.pullback f).pushforward f ≤ R := (galois_connection f).l_u_le _ lemma pushforward_union {f : Y ⟶ X} (S R : sieve Y) : (S ⊔ R).pushforward f = S.pushforward f ⊔ R.pushforward f := (galois_connection f).l_sup lemma pushforward_le_bind_of_mem (S : presieve X) (R : Π ⦃Y : C⦄ ⦃f : Y ⟶ X⦄, S f → sieve Y) (f : Y ⟶ X) (h : S f) : (R h).pushforward f ≤ bind S R := begin rintro Z _ ⟨g, rfl, hg⟩, exact ⟨_, g, f, h, hg, rfl⟩, end lemma le_pullback_bind (S : presieve X) (R : Π ⦃Y : C⦄ ⦃f : Y ⟶ X⦄, S f → sieve Y) (f : Y ⟶ X) (h : S f) : R h ≤ (bind S R).pullback f := begin rw ← galois_connection f, apply pushforward_le_bind_of_mem, end /-- If `f` is a monomorphism, the pushforward-pullback adjunction on sieves is coreflective. -/ def galois_coinsertion_of_mono (f : Y ⟶ X) [mono f] : galois_coinsertion (sieve.pushforward f) (sieve.pullback f) := begin apply (galois_connection f).to_galois_coinsertion, rintros S Z g ⟨g₁, hf, hg₁⟩, rw cancel_mono f at hf, rwa ← hf, end /-- If `f` is a split epi, the pushforward-pullback adjunction on sieves is reflective. -/ def galois_insertion_of_is_split_epi (f : Y ⟶ X) [is_split_epi f] : galois_insertion (sieve.pushforward f) (sieve.pullback f) := begin apply (galois_connection f).to_galois_insertion, intros S Z g hg, refine ⟨g ≫ section_ f, by simpa⟩, end lemma pullback_arrows_comm [has_pullbacks C] {X Y : C} (f : Y ⟶ X) (R : presieve X) : sieve.generate (R.pullback_arrows f) = (sieve.generate R).pullback f := begin ext Z g, split, { rintro ⟨_, h, k, hk, rfl⟩, cases hk with W g hg, change (sieve.generate R).pullback f (h ≫ pullback.snd), rw [sieve.pullback_apply, assoc, ← pullback.condition, ← assoc], exact sieve.downward_closed _ (sieve.le_generate R W hg) (h ≫ pullback.fst)}, { rintro ⟨W, h, k, hk, comm⟩, exact ⟨_, _, _, presieve.pullback_arrows.mk _ _ hk, pullback.lift_snd _ _ comm⟩ }, end section functor variables {E : Type u₃} [category.{v₃} E] (G : D ⥤ E) /-- If `R` is a sieve, then the `category_theory.presieve.functor_pullback` of `R` is actually a sieve. -/ @[simps] def functor_pullback (R : sieve (F.obj X)) : sieve X := { arrows := presieve.functor_pullback F R, downward_closed' := λ _ _ f hf g, begin unfold presieve.functor_pullback, rw F.map_comp, exact R.downward_closed hf (F.map g), end } @[simp] lemma functor_pullback_arrows (R : sieve (F.obj X)) : (R.functor_pullback F).arrows = R.arrows.functor_pullback F := rfl @[simp] lemma functor_pullback_id (R : sieve X) : R.functor_pullback (𝟭 _) = R := by { ext, refl } lemma functor_pullback_comp (R : sieve ((F ⋙ G).obj X)) : R.functor_pullback (F ⋙ G) = (R.functor_pullback G).functor_pullback F := by { ext, refl } lemma functor_pushforward_extend_eq {R : presieve X} : (generate R).arrows.functor_pushforward F = R.functor_pushforward F := begin ext Y f, split, { rintro ⟨X', g, f', ⟨X'', g', f'', h₁, rfl⟩, rfl⟩, exact ⟨X'', f'', f' ≫ F.map g', h₁, by simp⟩ }, { rintro ⟨X', g, f', h₁, h₂⟩, exact ⟨X', g, f', le_generate R _ h₁, h₂⟩ } end /-- The sieve generated by the image of `R` under `F`. -/ @[simps] def functor_pushforward (R : sieve X) : sieve (F.obj X) := { arrows := R.arrows.functor_pushforward F, downward_closed' := λ Y Z f h g, by { obtain ⟨X, α, β, hα, rfl⟩ := h, exact ⟨X, α, g ≫ β, hα, by simp⟩ } } @[simp] lemma functor_pushforward_id (R : sieve X) : R.functor_pushforward (𝟭 _) = R := begin ext X f, split, { intro hf, obtain ⟨X, g, h, hg, rfl⟩ := hf, exact R.downward_closed hg h, }, { intro hf, exact ⟨X, f, 𝟙 _, hf, by simp⟩ } end lemma functor_pushforward_comp (R : sieve X) : R.functor_pushforward (F ⋙ G) = (R.functor_pushforward F).functor_pushforward G := by { ext, simpa [R.arrows.functor_pushforward_comp F G] } lemma functor_galois_connection (X : C) : _root_.galois_connection (sieve.functor_pushforward F : sieve X → sieve (F.obj X)) (sieve.functor_pullback F) := begin intros R S, split, { intros hle X f hf, apply hle, refine ⟨X, f, 𝟙 _, hf, _⟩, rw id_comp, }, { rintros hle Y f ⟨X, g, h, hg, rfl⟩, apply sieve.downward_closed S, exact hle g hg, } end lemma functor_pullback_monotone (X : C) : monotone (sieve.functor_pullback F : sieve (F.obj X) → sieve X) := (functor_galois_connection F X).monotone_u lemma functor_pushforward_monotone (X : C) : monotone (sieve.functor_pushforward F : sieve X → sieve (F.obj X)) := (functor_galois_connection F X).monotone_l lemma le_functor_pushforward_pullback (R : sieve X) : R ≤ (R.functor_pushforward F).functor_pullback F := (functor_galois_connection F X).le_u_l _ lemma functor_pullback_pushforward_le (R : sieve (F.obj X)) : (R.functor_pullback F).functor_pushforward F ≤ R := (functor_galois_connection F X).l_u_le _ lemma functor_pushforward_union (S R : sieve X) : (S ⊔ R).functor_pushforward F = S.functor_pushforward F ⊔ R.functor_pushforward F := (functor_galois_connection F X).l_sup lemma functor_pullback_union (S R : sieve (F.obj X)) : (S ⊔ R).functor_pullback F = S.functor_pullback F ⊔ R.functor_pullback F := rfl lemma functor_pullback_inter (S R : sieve (F.obj X)) : (S ⊓ R).functor_pullback F = S.functor_pullback F ⊓ R.functor_pullback F := rfl @[simp] lemma functor_pushforward_bot (F : C ⥤ D) (X : C) : (⊥ : sieve X).functor_pushforward F = ⊥ := (functor_galois_connection F X).l_bot @[simp] lemma functor_pushforward_top (F : C ⥤ D) (X : C) : (⊤ : sieve X).functor_pushforward F = ⊤ := begin refine (generate_sieve _).symm.trans _, apply generate_of_contains_is_split_epi (𝟙 (F.obj X)), refine ⟨X, 𝟙 _, 𝟙 _, trivial, by simp⟩ end @[simp] lemma functor_pullback_bot (F : C ⥤ D) (X : C) : (⊥ : sieve (F.obj X)).functor_pullback F = ⊥ := rfl @[simp] lemma functor_pullback_top (F : C ⥤ D) (X : C) : (⊤ : sieve (F.obj X)).functor_pullback F = ⊤ := rfl lemma image_mem_functor_pushforward (R : sieve X) {V} {f : V ⟶ X} (h : R f) : R.functor_pushforward F (F.map f) := ⟨V, f, 𝟙 _, h, by simp⟩ /-- When `F` is essentially surjective and full, the galois connection is a galois insertion. -/ def ess_surj_full_functor_galois_insertion [ess_surj F] [full F] (X : C) : galois_insertion (sieve.functor_pushforward F : sieve X → sieve (F.obj X)) (sieve.functor_pullback F) := begin apply (functor_galois_connection F X).to_galois_insertion, intros S Y f hf, refine ⟨_, F.preimage ((F.obj_obj_preimage_iso Y).hom ≫ f), (F.obj_obj_preimage_iso Y).inv, _⟩, simpa using S.downward_closed hf _, end /-- When `F` is fully faithful, the galois connection is a galois coinsertion. -/ def fully_faithful_functor_galois_coinsertion [full F] [faithful F] (X : C) : galois_coinsertion (sieve.functor_pushforward F : sieve X → sieve (F.obj X)) (sieve.functor_pullback F) := begin apply (functor_galois_connection F X).to_galois_coinsertion, rintros S Y f ⟨Z, g, h, h₁, h₂⟩, rw [←F.image_preimage h, ←F.map_comp] at h₂, rw F.map_injective h₂, exact S.downward_closed h₁ _, end end functor /-- A sieve induces a presheaf. -/ @[simps] def functor (S : sieve X) : Cᵒᵖ ⥤ Type v₁ := { obj := λ Y, {g : Y.unop ⟶ X // S g}, map := λ Y Z f g, ⟨f.unop ≫ g.1, downward_closed _ g.2 _⟩ } /-- If a sieve S is contained in a sieve T, then we have a morphism of presheaves on their induced presheaves. -/ @[simps] def nat_trans_of_le {S T : sieve X} (h : S ≤ T) : S.functor ⟶ T.functor := { app := λ Y f, ⟨f.1, h _ f.2⟩ }. /-- The natural inclusion from the functor induced by a sieve to the yoneda embedding. -/ @[simps] def functor_inclusion (S : sieve X) : S.functor ⟶ yoneda.obj X := { app := λ Y f, f.1 }. lemma nat_trans_of_le_comm {S T : sieve X} (h : S ≤ T) : nat_trans_of_le h ≫ functor_inclusion _ = functor_inclusion _ := rfl /-- The presheaf induced by a sieve is a subobject of the yoneda embedding. -/ instance functor_inclusion_is_mono : mono S.functor_inclusion := ⟨λ Z f g h, by { ext Y y, apply congr_fun (nat_trans.congr_app h Y) y }⟩ /-- A natural transformation to a representable functor induces a sieve. This is the left inverse of `functor_inclusion`, shown in `sieve_of_functor_inclusion`. -/ -- TODO: Show that when `f` is mono, this is right inverse to `functor_inclusion` up to isomorphism. @[simps] def sieve_of_subfunctor {R} (f : R ⟶ yoneda.obj X) : sieve X := { arrows := λ Y g, ∃ t, f.app (opposite.op Y) t = g, downward_closed' := λ Y Z _, begin rintro ⟨t, rfl⟩ g, refine ⟨R.map g.op t, _⟩, rw functor_to_types.naturality _ _ f, simp, end } lemma sieve_of_subfunctor_functor_inclusion : sieve_of_subfunctor S.functor_inclusion = S := begin ext, simp only [functor_inclusion_app, sieve_of_subfunctor_apply, subtype.val_eq_coe], split, { rintro ⟨⟨f, hf⟩, rfl⟩, exact hf }, { intro hf, exact ⟨⟨_, hf⟩, rfl⟩ } end instance functor_inclusion_top_is_iso : is_iso ((⊤ : sieve X).functor_inclusion) := ⟨⟨{ app := λ Y a, ⟨a, ⟨⟩⟩ }, by tidy⟩⟩ end sieve end category_theory
6caaeff1ad51c07f139f5660cf1cd825e7b337de
4efff1f47634ff19e2f786deadd394270a59ecd2
/src/tactic/lint/type_classes.lean
275255a46aa3619624d258dc396ef1e959bdf7e5
[ "Apache-2.0" ]
permissive
agjftucker/mathlib
d634cd0d5256b6325e3c55bb7fb2403548371707
87fe50de17b00af533f72a102d0adefe4a2285e8
refs/heads/master
1,625,378,131,941
1,599,166,526,000
1,599,166,526,000
160,748,509
0
0
Apache-2.0
1,544,141,789,000
1,544,141,789,000
null
UTF-8
Lean
false
false
16,981
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, Robert Y. Lewis, Gabriel Ebner -/ import tactic.lint.basic /-! # Linters about type classes This file defines several linters checking the correct usage of type classes and the appropriate definition of instances: * `instance_priority` ensures that blanket instances have low priority * `has_inhabited_instances` checks that every type has an `inhabited` instance * `impossible_instance` checks that there are no instances which can never apply * `incorrect_type_class_argument` checks that only type classes are used in instance-implicit arguments * `dangerous_instance` checks for instances that generate subproblems with metavariables * `fails_quickly` checks that type class resolution finishes quickly * `has_coe_variable` checks that there is no instance of type `has_coe α t` * `inhabited_nonempty` checks whether `[inhabited α]` arguments could be generalized to `[nonempty α]` * `decidable_classical` checks propositions for `[decidable_... p]` hypotheses that are not used in the statement, and could thus be removed by using `classical` in the proof. -/ open tactic /-- Pretty prints a list of arguments of a declaration. Assumes `l` is a list of argument positions and binders (or any other element that can be pretty printed). `l` can be obtained e.g. by applying `list.indexes_values` to a list obtained by `get_pi_binders`. -/ meta def print_arguments {α} [has_to_tactic_format α] (l : list (ℕ × α)) : tactic string := do fs ← l.mmap (λ ⟨n, b⟩, (λ s, to_fmt "argument " ++ to_fmt (n+1) ++ ": " ++ s) <$> pp b), return $ fs.to_string_aux tt /-- checks whether an instance that always applies has priority ≥ 1000. -/ private meta def instance_priority (d : declaration) : tactic (option string) := do let nm := d.to_name, b ← is_instance nm, /- return `none` if `d` is not an instance -/ if ¬ b then return none else do (is_persistent, prio) ← has_attribute `instance nm, /- return `none` if `d` is has low priority -/ if prio < 1000 then return none else do let (fn, args) := d.type.pi_codomain.get_app_fn_args, cls ← get_decl fn.const_name, let (pi_args, _) := cls.type.pi_binders, guard (args.length = pi_args.length), /- List all the arguments of the class that block type-class inference from firing (if they are metavariables). These are all the arguments except instance-arguments and out-params. -/ let relevant_args := (args.zip pi_args).filter_map $ λ⟨e, ⟨_, info, tp⟩⟩, if info = binder_info.inst_implicit ∨ tp.get_app_fn.is_constant_of `out_param then none else some e, let always_applies := relevant_args.all expr.is_var ∧ relevant_args.nodup, if always_applies then return $ some "set priority below 1000" else return none /-- Certain instances always apply during type-class resolution. For example, the instance `add_comm_group.to_add_group {α} [add_comm_group α] : add_group α` applies to all type-class resolution problems of the form `add_group _`, and type-class inference will then do an exhaustive search to find a commutative group. These instances take a long time to fail. Other instances will only apply if the goal has a certain shape. For example `int.add_group : add_group ℤ` or `add_group.prod {α β} [add_group α] [add_group β] : add_group (α × β)`. Usually these instances will fail quickly, and when they apply, they are almost the desired instance. For this reason, we want the instances of the second type (that only apply in specific cases) to always have higher priority than the instances of the first type (that always apply). See also #1561. Therefore, if we create an instance that always applies, we set the priority of these instances to 100 (or something similar, which is below the default value of 1000). -/ library_note "lower instance priority" /-- Instances that always apply should be applied after instances that only apply in specific cases, see note [lower instance priority] above. Classes that use the `extends` keyword automatically generate instances that always apply. Therefore, we set the priority of these instances to 100 (or something similar, which is below the default value of 1000) using `set_option default_priority 100`. We have to put this option inside a section, so that the default priority is the default 1000 outside the section. -/ library_note "default priority" /-- A linter object for checking instance priorities of instances that always apply. This is in the default linter set. -/ @[linter] meta def linter.instance_priority : linter := { test := instance_priority, no_errors_found := "All instance priorities are good", errors_found := "DANGEROUS INSTANCE PRIORITIES. The following instances always apply, and therefore should have a priority < 1000. If you don't know what priority to choose, use priority 100. If this is an automatically generated instance (using the keywords `class` and `extends`), see note [lower instance priority] and see note [default priority] for instructions to change the priority", auto_decls := tt } /-- Reports declarations of types that do not have an associated `inhabited` instance. -/ private meta def has_inhabited_instance (d : declaration) : tactic (option string) := do tt ← pure d.is_trusted | pure none, ff ← has_attribute' `reducible d.to_name | pure none, ff ← has_attribute' `class d.to_name | pure none, (_, ty) ← open_pis d.type, ty ← whnf ty, if ty = `(Prop) then pure none else do `(Sort _) ← whnf ty | pure none, insts ← attribute.get_instances `instance, insts_tys ← insts.mmap $ λ i, expr.pi_codomain <$> declaration.type <$> get_decl i, let inhabited_insts := insts_tys.filter (λ i, i.app_fn.const_name = ``inhabited ∨ i.app_fn.const_name = `unique), let inhabited_tys := inhabited_insts.map (λ i, i.app_arg.get_app_fn.const_name), if d.to_name ∈ inhabited_tys then pure none else pure "inhabited instance missing" /-- A linter for missing `inhabited` instances. -/ @[linter] meta def linter.has_inhabited_instance : linter := { test := has_inhabited_instance, auto_decls := ff, no_errors_found := "No types have missing inhabited instances", errors_found := "TYPES ARE MISSING INHABITED INSTANCES", is_fast := ff } attribute [nolint has_inhabited_instance] pempty /-- Checks whether an instance can never be applied. -/ private meta def impossible_instance (d : declaration) : tactic (option string) := do tt ← is_instance d.to_name | return none, (binders, _) ← get_pi_binders_nondep d.type, let bad_arguments := binders.filter $ λ nb, nb.2.info ≠ binder_info.inst_implicit, _ :: _ ← return bad_arguments | return none, (λ s, some $ "Impossible to infer " ++ s) <$> print_arguments bad_arguments /-- A linter object for `impossible_instance`. -/ @[linter] meta def linter.impossible_instance : linter := { test := impossible_instance, auto_decls := tt, no_errors_found := "All instances are applicable", errors_found := "IMPOSSIBLE INSTANCES FOUND. These instances have an argument that cannot be found during type-class resolution, and therefore can never succeed. Either mark the arguments with square brackets (if it is a class), or don't make it an instance" } /-- Checks whether an instance can never be applied. -/ private meta def incorrect_type_class_argument (d : declaration) : tactic (option string) := do (binders, _) ← get_pi_binders d.type, let instance_arguments := binders.indexes_values $ λ b : binder, b.info = binder_info.inst_implicit, /- the head of the type should either unfold to a class, or be a local constant. A local constant is allowed, because that could be a class when applied to the proper arguments. -/ bad_arguments ← instance_arguments.mfilter (λ ⟨_, b⟩, do (_, head) ← open_pis b.type, if head.get_app_fn.is_local_constant then return ff else do bnot <$> is_class head), _ :: _ ← return bad_arguments | return none, (λ s, some $ "These are not classes. " ++ s) <$> print_arguments bad_arguments /-- A linter object for `incorrect_type_class_argument`. -/ @[linter] meta def linter.incorrect_type_class_argument : linter := { test := incorrect_type_class_argument, auto_decls := tt, no_errors_found := "All declarations have correct type-class arguments", errors_found := "INCORRECT TYPE-CLASS ARGUMENTS. Some declarations have non-classes between [square brackets]" } /-- Checks whether an instance is dangerous: it creates a new type-class problem with metavariable arguments. -/ private meta def dangerous_instance (d : declaration) : tactic (option string) := do tt ← is_instance d.to_name | return none, (local_constants, target) ← open_pis d.type, let instance_arguments := local_constants.indexes_values $ λ e : expr, e.local_binding_info = binder_info.inst_implicit, let bad_arguments := local_constants.indexes_values $ λ x, !target.has_local_constant x && (x.local_binding_info ≠ binder_info.inst_implicit) && instance_arguments.any (λ nb, nb.2.local_type.has_local_constant x), let bad_arguments : list (ℕ × binder) := bad_arguments.map $ λ ⟨n, e⟩, ⟨n, e.to_binder⟩, _ :: _ ← return bad_arguments | return none, (λ s, some $ "The following arguments become metavariables. " ++ s) <$> print_arguments bad_arguments /-- A linter object for `dangerous_instance`. -/ @[linter] meta def linter.dangerous_instance : linter := { test := dangerous_instance, no_errors_found := "No dangerous instances", errors_found := "DANGEROUS INSTANCES FOUND.\nThese instances are recursive, and create a new type-class problem which will have metavariables. Possible solution: remove the instance attribute or make it a local instance instead. Currently this linter does not check whether the metavariables only occur in arguments marked with `out_param`, in which case this linter gives a false positive.", auto_decls := tt } /-- Applies expression `e` to local constants, but lifts all the arguments that are `Sort`-valued to `Type`-valued sorts. -/ meta def apply_to_fresh_variables (e : expr) : tactic expr := do t ← infer_type e, (xs, b) ← open_pis t, xs.mmap' $ λ x, try $ do { u ← mk_meta_univ, tx ← infer_type x, ttx ← infer_type tx, unify ttx (expr.sort u.succ) }, return $ e.app_of_list xs /-- Tests whether type-class inference search for a class will end quickly when applied to variables. This tactic succeeds if `mk_instance` succeeds quickly or fails quickly with the error message that it cannot find an instance. It fails if the tactic takes too long, or if any other error message is raised. We make sure that we apply the tactic to variables living in `Type u` instead of `Sort u`, because many instances only apply in that special case, and we do want to catch those loops. -/ meta def fails_quickly (max_steps : ℕ) (d : declaration) : tactic (option string) := do e ← mk_const d.to_name, tt ← is_class e | return none, e' ← apply_to_fresh_variables e, sum.inr msg ← retrieve_or_report_error $ tactic.try_for max_steps $ succeeds_or_fails_with_msg (mk_instance e') $ λ s, "tactic.mk_instance failed to generate instance for".is_prefix_of s | return none, return $ some $ if msg = "try_for tactic failed, timeout" then "type-class inference timed out" else msg /-- A linter object for `fails_quickly`. If we want to increase the maximum number of steps type-class inference is allowed to take, we can increase the number `3000` in the definition. As of 5 Mar 2020 the longest trace (for `is_add_hom`) takes 2900-3000 "heartbeats". -/ @[linter] meta def linter.fails_quickly : linter := { test := fails_quickly 3000, auto_decls := tt, no_errors_found := "No type-class searches timed out", errors_found := "TYPE CLASS SEARCHES TIMED OUT. For the following classes, there is an instance that causes a loop, or an excessively long search.", is_fast := ff } /-- Tests whether there is no instance of type `has_coe α t` where `α` is a variable, or `has_coe t α` where `α` does not occur in `t`. See note [use has_coe_t]. -/ private meta def has_coe_variable (d : declaration) : tactic (option string) := do tt ← is_instance d.to_name | return none, `(has_coe %%a %%b) ← return d.type.pi_codomain | return none, if a.is_var then return $ some $ "illegal instance, first argument is variable" else if b.is_var ∧ ¬ b.occurs a then return $ some $ "illegal instance, second argument is variable not occurring in first argument" else return none /-- A linter object for `has_coe_variable`. -/ @[linter] meta def linter.has_coe_variable : linter := { test := has_coe_variable, auto_decls := tt, no_errors_found := "No invalid `has_coe` instances", errors_found := "INVALID `has_coe` INSTANCES. Make the following declarations instances of the class `has_coe_t` instead of `has_coe`." } /-- Checks whether a declaration is prop-valued and takes an `inhabited _` argument that is unused elsewhere in the type. In this case, that argument can be replaced with `nonempty _`. -/ private meta def inhabited_nonempty (d : declaration) : tactic (option string) := do tt ← is_prop d.type | return none, (binders, _) ← get_pi_binders_nondep d.type, let inhd_binders := binders.filter $ λ pr, pr.2.type.is_app_of `inhabited, if inhd_binders.length = 0 then return none else (λ s, some $ "The following `inhabited` instances should be `nonempty`. " ++ s) <$> print_arguments inhd_binders /-- A linter object for `inhabited_nonempty`. -/ @[linter] meta def linter.inhabited_nonempty : linter := { test := inhabited_nonempty, auto_decls := ff, no_errors_found := "No uses of `inhabited` arguments should be replaced with `nonempty`", errors_found := "USES OF `inhabited` SHOULD BE REPLACED WITH `nonempty`." } /-- Checks whether a declaration is `Prop`-valued and takes a `decidable* _` hypothesis that is unused elsewhere in the type. In this case, that hypothesis can be replaced with `classical` in the proof. Theorems in the `decidable` namespace are exempt from the check. -/ private meta def decidable_classical (d : declaration) : tactic (option string) := do tt ← is_prop d.type | return none, ff ← pure $ (`decidable).is_prefix_of d.to_name | return none, (binders, _) ← get_pi_binders_nondep d.type, let deceq_binders := binders.filter $ λ pr, pr.2.type.is_app_of `decidable_eq ∨ pr.2.type.is_app_of `decidable_pred ∨ pr.2.type.is_app_of `decidable_rel ∨ pr.2.type.is_app_of `decidable, if deceq_binders.length = 0 then return none else (λ s, some $ "The following `decidable` hypotheses should be replaced with `classical` in the proof. " ++ s) <$> print_arguments deceq_binders /-- A linter object for `decidable_classical`. -/ @[linter] meta def linter.decidable_classical : linter := { test := decidable_classical, auto_decls := ff, no_errors_found := "No uses of `decidable` arguments should be replaced with `classical`", errors_found := "USES OF `decidable` SHOULD BE REPLACED WITH `classical` IN THE PROOF." } /- The file `logic/basic.lean` emphasizes the differences between what holds under classical and non-classical logic. It makes little sense to make all these lemmas classical, so we add them to the list of lemmas which are not checked by the linter `decidable_classical`. -/ attribute [nolint decidable_classical] dec_em not.decidable_imp_symm private meta def has_coe_to_fun_linter (d : declaration) : tactic (option string) := retrieve $ do mk_meta_var d.type >>= set_goals ∘ pure, args ← unfreezing intros, expr.sort _ ← target | pure none, let ty : expr := (expr.const d.to_name d.univ_levels).mk_app args, some coe_fn_inst ← try_core $ to_expr ``(_root_.has_coe_to_fun %%ty) >>= mk_instance | pure none, some trans_inst@(expr.app (expr.app _ trans_inst_1) trans_inst_2) ← try_core $ to_expr ``(@_root_.coe_fn_trans %%ty _ _ _) | pure none, tt ← succeeds $ unify trans_inst coe_fn_inst transparency.reducible | pure none, set_bool_option `pp.all true, trans_inst_1 ← pp trans_inst_1, trans_inst_2 ← pp trans_inst_2, pure $ format.to_string $ "`has_coe_to_fun` instance is definitionally equal to a transitive instance composed of: " ++ trans_inst_1.group.indent 2 ++ format.line ++ "and" ++ trans_inst_2.group.indent 2 /-- Linter that checks whether `has_coe_to_fun` instances comply with Note [function coercion]. -/ @[linter] meta def linter.has_coe_to_fun : linter := { test := has_coe_to_fun_linter, auto_decls := tt, no_errors_found := "has_coe_to_fun is used correctly", errors_found := "INVALID/MISSING `has_coe_to_fun` instances. You should add a `has_coe_to_fun` instance for the following types. See Note function coercions]." }
31d6267eb8e22a1bc08b345fb8cf74a3b800bdf1
dd4e652c749fea9ac77e404005cb3470e5f75469
/src/array2.lean
06e1f17dd10caaa345be91fa6e35e8d311222d6b
[]
no_license
skbaek/cvx
e32822ad5943541539966a37dee162b0a5495f55
c50c790c9116f9fac8dfe742903a62bdd7292c15
refs/heads/master
1,623,803,010,339
1,618,058,958,000
1,618,058,958,000
176,293,135
3
2
null
null
null
null
UTF-8
Lean
false
false
1,521
lean
import data.rat .string .array .vector variables {α β : Type} variables {k m n : nat} open nat tactic def array₂ (m n : nat) (α : Type) : Type := array m (array n α) namespace array₂ def mk (m n : nat) (a : α) : array₂ m n α := mk_array m (mk_array n a) def read : array₂ m n α → fin m → fin n → α | A i j := array.read (array.read A i) j def write (A : array₂ m n α) (i : fin m) (j : fin n) (a : α) : array₂ m n α := array.write A i ((array.read A i).write j a) def cell_size [has_repr α] (a₂ : array₂ m n α) : nat := a₂.foldl 0 (λ a₁ n, max n a₁.cell_size) def repr_aux [has_repr α] (k : nat) (a₁ : array m α) : string := a₁.foldl "|" (λ a s, s ++ " " ++ (repr a).resize k ++ " |") def repr [has_repr α] (a₂ : array₂ m n α) : string := let k := a₂.cell_size in a₂.foldl "" (λ a₁ s, s ++ "\n" ++ repr_aux k a₁) instance has_repr [has_repr α] : has_repr (array₂ m n α) := ⟨repr⟩ meta instance has_to_format [has_repr α] : has_to_format (array₂ m n α) := ⟨λ x, repr x⟩ end array₂ def vector₂.to_array₂ {m n : nat} (v₂ : vector₂ α m n) : array₂ m n α := (v₂.map (vector.to_array)).to_array /- (mk_meta_array₂ ⌜α⌝ m n) returns the expr of an m × n vector₂, where the expr of each entry is a metavariable. -/ meta def mk_meta_array₂ (αx : expr) (m n : nat) : tactic expr := do v₂x ← mk_meta_vector₂ αx m n, return `(@vector₂.to_array₂ %%αx %%`(m) %%`(n) %%v₂x)
660b7e84c9e30fb052104938d44ca9c5c9d46ecd
122543640bfbfedbcee1318bfdbd466ead2716a7
/src/p1.lean
ba8384d760364b72a35f88ed6bd5cc6b63ba595c
[]
no_license
jsm28/bmo2-2020-lean
f038489093312c97b9cae3cdb9410b2683ccb11f
ff87ce51ed080d462e63c5549d5f2b377ad83204
refs/heads/master
1,692,783,059,184
1,689,807,657,000
1,689,807,657,000
239,362,030
9
0
null
null
null
null
UTF-8
Lean
false
false
8,096
lean
-- BMO2 2020 problem 1. -- Choices made for formalization: the original problem does not -- specify a type for the terms of the sequence; we choose ℤ. We also -- index the sequence starting at 0 rather than at 1 as in the -- original problem. import data.int.parity import tactic.basic import tactic.linarith import tactic.norm_num import tactic.ring import tactic.ring_exp open int -- Next term in sequence. def p1_seq_next (a : ℤ) : ℤ := a * (a - 1) / 2 -- Condition that sequence satisfies recurrence. def p1_recurrence (a : ℕ → ℤ) : Prop := ∀ n : ℕ, a (n + 1) = p1_seq_next (a n) -- Odd numbers. def all_odd (a : ℕ → ℤ) : Prop := ∀ n : ℕ, odd (a n) /-- If an integer is `a` mod `b`, there are corresponding cases for its value mod `c * b`. -/ lemma mod_mul_eq_cases {n a b c : ℤ} (hbpos : 0 < b) (hcpos : 0 < c) (hmod : n % b = a) : ∃ d : ℤ, 0 ≤ d ∧ d < c ∧ n % (c * b) = a + d * b := begin use ((n % (c * b)) / b), split, { exact int.div_nonneg (mod_nonneg _ (mul_ne_zero (ne_of_gt hcpos) (ne_of_gt hbpos))) (int.le_of_lt hbpos) }, split, { rw int.div_lt_iff_lt_mul hbpos, exact mod_lt_of_pos n (mul_pos hcpos hbpos) }, { rw [←hmod, ←mod_mod_of_dvd n (dvd_mul_left b c), mod_def (n % (c * b)) b, mul_comm b (n % (c * b) / b)], simp } end -- If an integer is a mod b, it is a or a + b mod 2b. theorem mod_mul_2 (n : ℤ) (a : ℤ) (b : ℤ) (hbpos : 0 < b) (hmod : n % b = a) : n % (2 * b) = a ∨ n % (2 * b) = a + b := begin rcases mod_mul_eq_cases hbpos (dec_trivial : (0 : ℤ) < 2) hmod with ⟨d, ⟨hd0, ⟨hd2, hdmod⟩⟩⟩, have hd01 : d = 0 ∨ d = 1, { by_cases h : 1 ≤ d, { right, linarith }, { left, linarith } }, cases hd01, { left, rw [hd01, zero_mul, add_zero] at hdmod, exact hdmod }, { right, rw [hd01, one_mul] at hdmod, exact hdmod } end -- Powers of 2 are positive. theorem power_of_2_pos (k : ℕ) : 0 < (2^k : ℤ) := pow_pos dec_trivial k -- The main part of the induction step in the proof. If two -- consecutive terms are 3 mod 2^m, the first must be 3 mod 2^(m+1). -- Note: with (3 % 2^m) the result could be stated in a more -- complicated way meaningful for m = 1 as well. theorem induction_main (m : ℕ) (a : ℤ) (hm : 2 ≤ m) (ha : a % 2^m = 3) (hb : (p1_seq_next a) % 2^m = 3) : a % 2^(m+1) = 3 := begin have h2m1 : (2^(m+1) : ℤ) = (2 * 2^m : ℤ) := rfl, rw h2m1, have hcases : a % (2 * 2^m) = 3 ∨ a % (2 * 2^m) = 3 + 2^m, { exact mod_mul_2 _ _ _ (power_of_2_pos m) ha }, cases hcases with hc1 hc2, { exact hc1 }, { exfalso, unfold p1_seq_next at hb, rw mod_def at hc2, set d := a / (2 * 2^m) with hd, have hc2m : a = 3 + 2^m + 2 * 2^m * d, { rw ← hc2, simp, }, have hc2mm : a = 3 + 2 ^ m * (1 + 2 * d), { rw hc2m, ring }, have hm1 : ∃ m1 : ℕ, m = 1 + m1, { have hm2 : ∃ m2 : ℕ, m = 2 + m2 := nat.exists_eq_add_of_le hm, cases hm2 with m2 hm2_h, use 1 + m2, rw hm2_h, ring }, cases hm1 with m1 hmm1, rw [hc2mm, hmm1, (show (3 + 2 ^ (1 + m1) * (1 + 2 * d)) * (3 + 2 ^ (1 + m1) * (1 + 2 * d) - 1) = 2 * (3 + 2^m1 + 2^(1 + m1) * (2 + 5 * d + 2^m1 * (1 + 2 * d) * (1 + 2 * d))), by ring_exp), int.mul_div_cancel_left _ (show (2 : ℤ) ≠ 0, by norm_num), ← hmm1, ← add_mod_mod, mul_assoc, mul_mod_right, add_zero] at hb, have hbbx : (3 + (2 : ℤ)^m1) % 2^m = 3 % 2^m, { rw [← mod_mod, hb] }, rw [mod_eq_mod_iff_mod_sub_eq_zero, add_comm, add_sub_assoc, sub_self, add_zero, hmm1, add_comm, pow_succ] at hbbx, have hdvd : (2^m1 : ℤ) ∣ 2^m, { use 2, rw [mul_comm, hmm1, add_comm, ← pow_succ], }, have hrdvd : (2^m : ℤ) ∣ 2^m1, { rw [hmm1, add_comm, pow_succ], exact dvd_of_mod_eq_zero hbbx, }, have heq : (2^m1 : ℤ) = 2^m, { exact dvd_antisymm (int.le_of_lt (power_of_2_pos m1)) (int.le_of_lt (power_of_2_pos m)) hdvd hrdvd, }, rw [hmm1, add_comm, pow_succ] at heq, have heqx : (2^m1 : ℤ) - 2^m1 = 2*2^m1 - 2^m1, { conv_lhs { congr, rw heq } }, rw sub_self at heqx, have heqxx : 2 * (2^m1 : ℤ) - 2^m1 = 2^m1, { ring }, rw heqxx at heqx, have heqz : 0 < (2^m1 : ℤ) := power_of_2_pos m1, rw ← heqx at heqz, exact lt_irrefl (0 : ℤ) heqz, }, end -- Base case: if two consecutive terms are odd, the first is 3 mod 4. theorem induction_base (a : ℤ) (ha : odd a) (hb : odd (p1_seq_next a)) : a % 2^2 = 3 := begin rw [odd_iff] at ha hb, rw (show (2^2 : ℤ) = 2 * 2, by norm_num), have hcases : a % (2 * 2) = 1 ∨ a % (2 * 2) = 1 + 2, { exact mod_mul_2 _ _ _ dec_trivial ha }, cases hcases with hc1 hc2, { exfalso, unfold p1_seq_next at hb, rw mod_def at hc1, set d := a / (2 * 2) with hd, have hc1m : a = 1 + 2 * 2 * d, { conv_rhs { congr, rw ←hc1 }, simp }, rw hc1m at hb, conv_lhs at hb { congr, congr, congr, skip, rw [add_comm, add_sub_assoc, sub_self, add_zero] }, rw [mul_comm, mul_assoc, mul_assoc] at hb, have hbm : 2 * (2 * (d * (1 + 2 * 2 * d))) / 2 = 2 * (d * (1 + 2 * 2 * d)) := int.mul_div_cancel_left _ dec_trivial, rw [hbm, mul_mod_right] at hb, norm_num at hb }, { rw hc2, norm_num, }, end -- Base case for whole sequence. theorem induction_base_all (a : ℕ → ℤ) (hodd : all_odd a) (hrec : p1_recurrence a) : ∀ n : ℕ, (a n) % 2^2 = 3 := begin intro n, let an : ℤ := a n, set an1 : ℤ := a (n + 1) with han1, have hrecn : a (n + 1) = p1_seq_next an, { rw hrec n }, rw ← han1 at hrecn, have hanodd : odd an := hodd n, have han1odd : odd an1 := hodd (n + 1), rw hrecn at han1odd, exact induction_base an hanodd han1odd, end -- Induction step for whole sequence. theorem induction_main_all (m : ℕ) (a : ℕ → ℤ) (hm : 2 ≤ m) (hmod : ∀ k : ℕ, (a k) % 2^m = 3) (hrec : p1_recurrence a) : ∀ n : ℕ, (a n) % 2^(m+1) = 3 := begin intro n, let an : ℤ := a n, set an1 : ℤ := a (n + 1) with han1, have hrecn : a (n + 1) = p1_seq_next an, { rw hrec n }, rw ← han1 at hrecn, have hanmod : an % 2^m = 3 := hmod n, have han1mod : an1 % 2^m = 3 := hmod (n + 1), rw hrecn at han1mod, exact induction_main m an hm hanmod han1mod, end -- All terms are 3 mod all powers of 2. theorem three_mod_all_powers (a : ℕ → ℤ) (hodd : all_odd a) (hrec : p1_recurrence a) : ∀ m : ℕ, 2 ≤ m → ∀ n : ℕ, (a n) % 2^m = 3 := begin intro m, induction m with k hk, { intro hx, exfalso, norm_num at hx, }, { by_cases h2k : 2 ≤ k, { intro hsk, exact induction_main_all k a h2k (hk h2k) hrec }, { by_cases hk1 : k = 1, { intro h22, rw hk1, exact induction_base_all a hodd hrec, }, { intro h2sk, exfalso, rw [(show 2 = nat.succ 1, by norm_num), nat.succ_le_iff, nat.lt_add_one_iff] at h2sk, rw not_le at h2k, exact hk1 (le_antisymm (nat.le_of_lt_succ h2k) h2sk) }}}, end -- The first term of the sequence is 3. theorem first_term_three (a : ℕ → ℤ) (hodd : all_odd a) (hrec : p1_recurrence a) : a 0 = 3 := begin set k : ℕ := 2 ^ (2 + nat_abs (a 0 - 3)) with hk, have hltk : 2 + nat_abs (a 0 - 3) < k := nat.lt_two_pow _, have hmod : a 0 % k = 3, { rw hk, push_cast, norm_num, exact three_mod_all_powers a hodd hrec (2 + nat_abs (a 0 + -3)) (by simp) 0 }, rw ←nat_abs_of_nat k at hltk, exact eq_of_mod_eq_of_nat_abs_sub_lt_nat_abs hmod (by linarith) end -- The actual result of the problem. theorem p1_result (a : ℕ → ℤ) (hrec : p1_recurrence a) (ha3 : 2 < a 0) : all_odd a ↔ a 0 = 3 := begin split, { intro hodd, exact first_term_three a hodd hrec, }, { intro h03, have halln : ∀ n : ℕ, a n = 3, { intro n, induction n with k hk, { exact h03, }, { rw hrec k, unfold p1_seq_next, rw hk, norm_num, } }, intro n, rw halln n, norm_num }, end
f8676c5466c526123d6aaff5e0b528f07bcefcf4
19e65f097e49ef249bf10eb0d5cc0075bc4216a2
/src/week08.lean
917b1285d05e3c4fac70fe02bfac12c8fd759b70
[]
no_license
UVM-M52/week-8-fgdorais
6eccbcf373d9a872949d37e434e18b082cf6ae48
251579081a03fadedc1606bcda8004cabf217ac3
refs/heads/master
1,613,424,257,678
1,583,335,096,000
1,583,335,096,000
244,933,167
0
0
null
null
null
null
UTF-8
Lean
false
false
2,268
lean
-- Math 52: Week 8 import .utils open classical definition is_even (n : ℤ) : Prop := ∃ (k : ℤ), n = 2 * k definition is_odd (n : ℤ) : Prop := ∃ (k : ℤ), n = 2 * k + 1 -- We will prove these two basic facts later in the course. axiom is_not_even_iff_is_odd (n : ℤ) : ¬ is_even n ↔ is_odd n axiom is_not_odd_iff_is_even (n : ℤ) : ¬ is_odd n ↔ is_even n -- We proved this one before! theorem even_square : ∀ (n : ℤ), is_even (n * n) ↔ is_even n := begin intro n, split, { by_contrapositive, intro H, rw is_not_even_iff_is_odd at H, rw is_not_even_iff_is_odd, cases H with k H, existsi (2*k*k + 2*k:ℤ), rw H, int_refl [k], }, { intro H, cases H with k H, existsi (2*k*k:ℤ), rw H, int_refl [k], } end -- We proved this fact earlier! theorem zero_or_zero_of_mul_zero : ∀ {a b : ℤ}, a * b = 0 → a = 0 ∨ b = 0 := begin intros a b H, by_trichotomy (a, (0:ℤ)), { intro Hazero, left, assumption, }, { intro Haneg, by_trichotomy (b, (0:ℤ)), { intro Hbzero, right, assumption, }, { intro Hbneg, apply absurd H, apply ne_of_gt, apply mul_pos_of_neg_of_neg, assumption, assumption, }, { intro Hbpos, apply absurd H, apply ne_of_lt, apply mul_neg_of_neg_of_pos, assumption, assumption, } }, { intro Hapos, by_trichotomy (b, (0:ℤ)), { intro Hbzero, right, assumption, }, { intro Hbneg, apply absurd H, apply ne_of_lt, apply mul_neg_of_pos_of_neg, assumption, assumption, }, { intro Hbpos, apply absurd H, apply ne_of_gt, apply mul_pos, assumption, assumption, } }, end -- This fact will be useful to prove the next theorem: -- eq_of_sub_eq_zero (x y : ℤ) : x - y = 0 → x = y theorem mul_left_cancel_of_nonzero {n : ℤ} : n ≠ 0 → (∀ {a b : ℤ}, n * a = n * b ↔ a = b) := begin intros Hpos a b, split, { sorry }, { sorry }, end -- This is the main theorem that shows √2 is irrational. theorem main : ¬ ∃ (m n : ℤ), (is_odd n ∨ is_odd m) ∧ n * n = 2 * m * m := have L2 : (2:ℤ) ≠ 0 := nonzero_trivial 2, begin intro H, cases H with m H, cases H with n H, cases H with Hodd H, have Heven : is_even n, begin sorry, end, cases Hodd, { sorry }, { sorry }, end
231aaccfb5f5dca5ad5bdcbb61af1feb9521feeb
947fa6c38e48771ae886239b4edce6db6e18d0fb
/src/geometry/manifold/instances/sphere.lean
f63a5beffe4c52451fce10f33cb5c360804cebe5
[ "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
20,897
lean
/- Copyright (c) 2021 Heather Macbeth. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Heather Macbeth -/ import analysis.complex.circle import analysis.normed_space.ball_action import analysis.inner_product_space.calculus import analysis.inner_product_space.pi_L2 import geometry.manifold.algebra.lie_group import geometry.manifold.instances.real /-! # Manifold structure on the sphere This file defines stereographic projection from the sphere in an inner product space `E`, and uses it to put a smooth manifold structure on the sphere. ## Main results For a unit vector `v` in `E`, the definition `stereographic` gives the stereographic projection centred at `v`, a local homeomorphism from the sphere to `(ℝ ∙ v)ᗮ` (the orthogonal complement of `v`). For finite-dimensional `E`, we then construct a smooth manifold instance on the sphere; the charts here are obtained by composing the local homeomorphisms `stereographic` with arbitrary isometries from `(ℝ ∙ v)ᗮ` to Euclidean space. We prove two lemmas about smooth maps: * `cont_mdiff_coe_sphere` states that the coercion map from the sphere into `E` is smooth; this is a useful tool for constructing smooth maps *from* the sphere. * `cont_mdiff.cod_restrict_sphere` states that a map from a manifold into the sphere is smooth if its lift to a map to `E` is smooth; this is a useful tool for constructing smooth maps *to* the sphere. As an application we prove `cont_mdiff_neg_sphere`, that the antipodal map is smooth. Finally, we equip the `circle` (defined in `analysis.complex.circle` to be the sphere in `ℂ` centred at `0` of radius `1`) with the following structure: * a charted space with model space `euclidean_space ℝ (fin 1)` (inherited from `metric.sphere`) * a Lie group with model with corners `𝓡 1` We furthermore show that `exp_map_circle` (defined in `analysis.complex.circle` to be the natural map `λ t, exp (t * I)` from `ℝ` to `circle`) is smooth. ## Implementation notes The model space for the charted space instance is `euclidean_space ℝ (fin n)`, where `n` is a natural number satisfying the typeclass assumption `[fact (finrank ℝ E = n + 1)]`. This may seem a little awkward, but it is designed to circumvent the problem that the literal expression for the dimension of the model space (up to definitional equality) determines the type. If one used the naive expression `euclidean_space ℝ (fin (finrank ℝ E - 1))` for the model space, then the sphere in `ℂ` would be a manifold with model space `euclidean_space ℝ (fin (2 - 1))` but not with model space `euclidean_space ℝ (fin 1)`. -/ variables {E : Type*} [inner_product_space ℝ E] noncomputable theory open metric finite_dimensional open_locale manifold local attribute [instance] fact_finite_dimensional_of_finrank_eq_succ section stereographic_projection variables (v : E) /-! ### Construction of the stereographic projection -/ /-- Stereographic projection, forward direction. This is a map from an inner product space `E` to the orthogonal complement of an element `v` of `E`. It is smooth away from the affine hyperplane through `v` parallel to the orthogonal complement. It restricts on the sphere to the stereographic projection. -/ def stereo_to_fun [complete_space E] (x : E) : (ℝ ∙ v)ᗮ := (2 / ((1:ℝ) - innerSL v x)) • orthogonal_projection (ℝ ∙ v)ᗮ x variables {v} @[simp] lemma stereo_to_fun_apply [complete_space E] (x : E) : stereo_to_fun v x = (2 / ((1:ℝ) - innerSL v x)) • orthogonal_projection (ℝ ∙ v)ᗮ x := rfl lemma cont_diff_on_stereo_to_fun [complete_space E] : cont_diff_on ℝ ⊤ (stereo_to_fun v) {x : E | innerSL v x ≠ (1:ℝ)} := begin refine cont_diff_on.smul _ (orthogonal_projection ((ℝ ∙ v)ᗮ)).cont_diff.cont_diff_on, refine cont_diff_const.cont_diff_on.div _ _, { exact (cont_diff_const.sub (innerSL v : E →L[ℝ] ℝ).cont_diff).cont_diff_on }, { intros x h h', exact h (sub_eq_zero.mp h').symm } end lemma continuous_on_stereo_to_fun [complete_space E] : continuous_on (stereo_to_fun v) {x : E | innerSL v x ≠ (1:ℝ)} := (@cont_diff_on_stereo_to_fun E _ v _).continuous_on variables (v) /-- Auxiliary function for the construction of the reverse direction of the stereographic projection. This is a map from the orthogonal complement of a unit vector `v` in an inner product space `E` to `E`; we will later prove that it takes values in the unit sphere. For most purposes, use `stereo_inv_fun`, not `stereo_inv_fun_aux`. -/ def stereo_inv_fun_aux (w : E) : E := (∥w∥ ^ 2 + 4)⁻¹ • ((4:ℝ) • w + (∥w∥ ^ 2 - 4) • v) variables {v} @[simp] lemma stereo_inv_fun_aux_apply (w : E) : stereo_inv_fun_aux v w = (∥w∥ ^ 2 + 4)⁻¹ • ((4:ℝ) • w + (∥w∥ ^ 2 - 4) • v) := rfl lemma stereo_inv_fun_aux_mem (hv : ∥v∥ = 1) {w : E} (hw : w ∈ (ℝ ∙ v)ᗮ) : stereo_inv_fun_aux v w ∈ (sphere (0:E) 1) := begin have h₁ : 0 ≤ ∥w∥ ^ 2 + 4 := by nlinarith, suffices : ∥(4:ℝ) • w + (∥w∥ ^ 2 - 4) • v∥ = ∥w∥ ^ 2 + 4, { have h₂ : ∥w∥ ^ 2 + 4 ≠ 0 := by nlinarith, simp only [mem_sphere_zero_iff_norm, norm_smul, real.norm_eq_abs, abs_inv, this, abs_of_nonneg h₁, stereo_inv_fun_aux_apply], field_simp }, suffices : ∥(4:ℝ) • w + (∥w∥ ^ 2 - 4) • v∥ ^ 2 = (∥w∥ ^ 2 + 4) ^ 2, { have h₃ : 0 ≤ ∥stereo_inv_fun_aux v w∥ := norm_nonneg _, simpa [h₁, h₃, -one_pow] using this }, simp [norm_add_sq_real, norm_smul, inner_smul_left, inner_smul_right, inner_left_of_mem_orthogonal_singleton _ hw, mul_pow, real.norm_eq_abs, hv], ring end lemma cont_diff_stereo_inv_fun_aux : cont_diff ℝ ⊤ (stereo_inv_fun_aux v) := begin have h₀ : cont_diff ℝ ⊤ (λ w : E, ∥w∥ ^ 2) := cont_diff_norm_sq, have h₁ : cont_diff ℝ ⊤ (λ w : E, (∥w∥ ^ 2 + 4)⁻¹), { refine (h₀.add cont_diff_const).inv _, intros x, nlinarith }, have h₂ : cont_diff ℝ ⊤ (λ w, (4:ℝ) • w + (∥w∥ ^ 2 - 4) • v), { refine (cont_diff_const.smul cont_diff_id).add _, refine (h₀.sub cont_diff_const).smul cont_diff_const }, exact h₁.smul h₂ end /-- Stereographic projection, reverse direction. This is a map from the orthogonal complement of a unit vector `v` in an inner product space `E` to the unit sphere in `E`. -/ def stereo_inv_fun (hv : ∥v∥ = 1) (w : (ℝ ∙ v)ᗮ) : sphere (0:E) 1 := ⟨stereo_inv_fun_aux v (w:E), stereo_inv_fun_aux_mem hv w.2⟩ @[simp] lemma stereo_inv_fun_apply (hv : ∥v∥ = 1) (w : (ℝ ∙ v)ᗮ) : (stereo_inv_fun hv w : E) = (∥w∥ ^ 2 + 4)⁻¹ • ((4:ℝ) • w + (∥w∥ ^ 2 - 4) • v) := rfl lemma stereo_inv_fun_ne_north_pole (hv : ∥v∥ = 1) (w : (ℝ ∙ v)ᗮ) : stereo_inv_fun hv w ≠ (⟨v, by simp [hv]⟩ : sphere (0:E) 1) := begin refine subtype.ne_of_val_ne _, rw ← inner_lt_one_iff_real_of_norm_one _ hv, { have hw : ⟪v, w⟫_ℝ = 0 := inner_right_of_mem_orthogonal_singleton v w.2, have hw' : (∥(w:E)∥ ^ 2 + 4)⁻¹ * (∥(w:E)∥ ^ 2 - 4) < 1, { refine (inv_mul_lt_iff' _).mpr _, { nlinarith }, linarith }, simpa [real_inner_comm, inner_add_right, inner_smul_right, real_inner_self_eq_norm_mul_norm, hw, hv] using hw' }, { simpa using stereo_inv_fun_aux_mem hv w.2 } end lemma continuous_stereo_inv_fun (hv : ∥v∥ = 1) : continuous (stereo_inv_fun hv) := continuous_induced_rng.2 (cont_diff_stereo_inv_fun_aux.continuous.comp continuous_subtype_coe) variables [complete_space E] lemma stereo_left_inv (hv : ∥v∥ = 1) {x : sphere (0:E) 1} (hx : (x:E) ≠ v) : stereo_inv_fun hv (stereo_to_fun v x) = x := begin ext, simp only [stereo_to_fun_apply, stereo_inv_fun_apply, smul_add], -- name two frequently-occuring quantities and write down their basic properties set a : ℝ := innerSL v x, set y := orthogonal_projection (ℝ ∙ v)ᗮ x, have split : ↑x = a • v + ↑y, { convert eq_sum_orthogonal_projection_self_orthogonal_complement (ℝ ∙ v) x, exact (orthogonal_projection_unit_singleton ℝ hv x).symm }, have hvy : ⟪v, y⟫_ℝ = 0 := inner_right_of_mem_orthogonal_singleton v y.2, have pythag : 1 = a ^ 2 + ∥y∥ ^ 2, { have hvy' : ⟪a • v, y⟫_ℝ = 0 := by simp [inner_smul_left, hvy], convert norm_add_sq_eq_norm_sq_add_norm_sq_of_inner_eq_zero _ _ hvy' using 2, { simp [← split] }, { simp [norm_smul, hv, ← sq, sq_abs] }, { exact sq _ } }, -- two facts which will be helpful for clearing denominators in the main calculation have ha : 1 - a ≠ 0, { have : a < 1 := (inner_lt_one_iff_real_of_norm_one hv (by simp)).mpr hx.symm, linarith }, have : 2 ^ 2 * ∥y∥ ^ 2 + 4 * (1 - a) ^ 2 ≠ 0, { refine ne_of_gt _, have := norm_nonneg (y:E), have : 0 < (1 - a) ^ 2 := sq_pos_of_ne_zero (1 - a) ha, nlinarith }, -- the core of the problem is these two algebraic identities: have h₁ : (2 ^ 2 / (1 - a) ^ 2 * ∥y∥ ^ 2 + 4)⁻¹ * 4 * (2 / (1 - a)) = 1, { field_simp, simp only [submodule.coe_norm] at *, nlinarith }, have h₂ : (2 ^ 2 / (1 - a) ^ 2 * ∥y∥ ^ 2 + 4)⁻¹ * (2 ^ 2 / (1 - a) ^ 2 * ∥y∥ ^ 2 - 4) = a, { field_simp, transitivity (1 - a) ^ 2 * (a * (2 ^ 2 * ∥y∥ ^ 2 + 4 * (1 - a) ^ 2)), { congr, simp only [submodule.coe_norm] at *, nlinarith }, ring }, -- deduce the result convert congr_arg2 has_add.add (congr_arg (λ t, t • (y:E)) h₁) (congr_arg (λ t, t • v) h₂) using 1, { simp [inner_add_right, inner_smul_right, hvy, real_inner_self_eq_norm_mul_norm, hv, mul_smul, mul_pow, real.norm_eq_abs, sq_abs, norm_smul] }, { simp [split, add_comm] } end lemma stereo_right_inv (hv : ∥v∥ = 1) (w : (ℝ ∙ v)ᗮ) : stereo_to_fun v (stereo_inv_fun hv w) = w := begin have : 2 / (1 - (∥(w:E)∥ ^ 2 + 4)⁻¹ * (∥(w:E)∥ ^ 2 - 4)) * (∥(w:E)∥ ^ 2 + 4)⁻¹ * 4 = 1, { have : ∥(w:E)∥ ^ 2 + 4 ≠ 0 := by nlinarith, have : (4:ℝ) + 4 ≠ 0 := by nlinarith, field_simp, ring }, convert congr_arg (λ c, c • w) this, { have h₁ : orthogonal_projection (ℝ ∙ v)ᗮ v = 0 := orthogonal_projection_orthogonal_complement_singleton_eq_zero v, have h₂ : orthogonal_projection (ℝ ∙ v)ᗮ w = w := orthogonal_projection_mem_subspace_eq_self w, have h₃ : innerSL v w = (0:ℝ) := inner_right_of_mem_orthogonal_singleton v w.2, have h₄ : innerSL v v = (1:ℝ) := by simp [real_inner_self_eq_norm_mul_norm, hv], simp [h₁, h₂, h₃, h₄, continuous_linear_map.map_add, continuous_linear_map.map_smul, mul_smul] }, { simp } end /-- Stereographic projection from the unit sphere in `E`, centred at a unit vector `v` in `E`; this is the version as a local homeomorphism. -/ def stereographic (hv : ∥v∥ = 1) : local_homeomorph (sphere (0:E) 1) (ℝ ∙ v)ᗮ := { to_fun := (stereo_to_fun v) ∘ coe, inv_fun := stereo_inv_fun hv, source := {⟨v, by simp [hv]⟩}ᶜ, target := set.univ, map_source' := by simp, map_target' := λ w _, stereo_inv_fun_ne_north_pole hv w, left_inv' := λ _ hx, stereo_left_inv hv (λ h, hx (subtype.ext h)), right_inv' := λ w _, stereo_right_inv hv w, open_source := is_open_compl_singleton, open_target := is_open_univ, continuous_to_fun := continuous_on_stereo_to_fun.comp continuous_subtype_coe.continuous_on (λ w h, h ∘ subtype.ext ∘ eq.symm ∘ (inner_eq_norm_mul_iff_of_norm_one hv (by simp)).mp), continuous_inv_fun := (continuous_stereo_inv_fun hv).continuous_on } lemma stereographic_apply (hv : ∥v∥ = 1) (x : sphere (0 : E) 1) : stereographic hv x = (2 / ((1:ℝ) - inner v x)) • orthogonal_projection (ℝ ∙ v)ᗮ x := rfl @[simp] lemma stereographic_source (hv : ∥v∥ = 1) : (stereographic hv).source = {⟨v, by simp [hv]⟩}ᶜ := rfl @[simp] lemma stereographic_target (hv : ∥v∥ = 1) : (stereographic hv).target = set.univ := rfl end stereographic_projection section charted_space /-! ### Charted space structure on the sphere In this section we construct a charted space structure on the unit sphere in a finite-dimensional real inner product space `E`; that is, we show that it is locally homeomorphic to the Euclidean space of dimension one less than `E`. The restriction to finite dimension is for convenience. The most natural `charted_space` structure for the sphere uses the stereographic projection from the antipodes of a point as the canonical chart at this point. However, the codomain of the stereographic projection constructed in the previous section is `(ℝ ∙ v)ᗮ`, the orthogonal complement of the vector `v` in `E` which is the "north pole" of the projection, so a priori these charts all have different codomains. So it is necessary to prove that these codomains are all continuously linearly equivalent to a fixed normed space. This could be proved in general by a simple case of Gram-Schmidt orthogonalization, but in the finite-dimensional case it follows more easily by dimension-counting. -/ /-- Variant of the stereographic projection, for the sphere in an `n + 1`-dimensional inner product space `E`. This version has codomain the Euclidean space of dimension `n`, and is obtained by composing the original sterographic projection (`stereographic`) with an arbitrary linear isometry from `(ℝ ∙ v)ᗮ` to the Euclidean space. -/ def stereographic' (n : ℕ) [fact (finrank ℝ E = n + 1)] (v : sphere (0:E) 1) : local_homeomorph (sphere (0:E) 1) (euclidean_space ℝ (fin n)) := (stereographic (norm_eq_of_mem_sphere v)) ≫ₕ (orthonormal_basis.from_orthogonal_span_singleton n (ne_zero_of_mem_unit_sphere v)).repr.to_homeomorph.to_local_homeomorph @[simp] lemma stereographic'_source {n : ℕ} [fact (finrank ℝ E = n + 1)] (v : sphere (0:E) 1) : (stereographic' n v).source = {v}ᶜ := by simp [stereographic'] @[simp] lemma stereographic'_target {n : ℕ} [fact (finrank ℝ E = n + 1)] (v : sphere (0:E) 1) : (stereographic' n v).target = set.univ := by simp [stereographic'] /-- The unit sphere in an `n + 1`-dimensional inner product space `E` is a charted space modelled on the Euclidean space of dimension `n`. -/ instance {n : ℕ} [fact (finrank ℝ E = n + 1)] : charted_space (euclidean_space ℝ (fin n)) (sphere (0:E) 1) := { atlas := {f | ∃ v : (sphere (0:E) 1), f = stereographic' n v}, chart_at := λ v, stereographic' n (-v), mem_chart_source := λ v, by simpa using ne_neg_of_mem_unit_sphere ℝ v, chart_mem_atlas := λ v, ⟨-v, rfl⟩ } end charted_space section smooth_manifold lemma sphere_ext_iff (u v : sphere (0:E) 1) : u = v ↔ ⟪(u:E), v⟫_ℝ = 1 := by simp [subtype.ext_iff, inner_eq_norm_mul_iff_of_norm_one] lemma stereographic'_symm_apply {n : ℕ} [fact (finrank ℝ E = n + 1)] (v : sphere (0:E) 1) (x : euclidean_space ℝ (fin n)) : ((stereographic' n v).symm x : E) = let U : (ℝ ∙ (v:E))ᗮ ≃ₗᵢ[ℝ] euclidean_space ℝ (fin n) := (orthonormal_basis.from_orthogonal_span_singleton n (ne_zero_of_mem_unit_sphere v)).repr in ((∥(U.symm x : E)∥ ^ 2 + 4)⁻¹ • (4 : ℝ) • (U.symm x : E) + (∥(U.symm x : E)∥ ^ 2 + 4)⁻¹ • (∥(U.symm x : E)∥ ^ 2 - 4) • v) := by simp [real_inner_comm, stereographic, stereographic', ← submodule.coe_norm] /-! ### Smooth manifold structure on the sphere -/ /-- The unit sphere in an `n + 1`-dimensional inner product space `E` is a smooth manifold, modelled on the Euclidean space of dimension `n`. -/ instance {n : ℕ} [fact (finrank ℝ E = n + 1)] : smooth_manifold_with_corners (𝓡 n) (sphere (0:E) 1) := smooth_manifold_with_corners_of_cont_diff_on (𝓡 n) (sphere (0:E) 1) begin rintros _ _ ⟨v, rfl⟩ ⟨v', rfl⟩, let U := -- Removed type ascription, and this helped for some reason with timeout issues? (orthonormal_basis.from_orthogonal_span_singleton n (ne_zero_of_mem_unit_sphere v)).repr, let U' :=-- Removed type ascription, and this helped for some reason with timeout issues? (orthonormal_basis.from_orthogonal_span_singleton n (ne_zero_of_mem_unit_sphere v')).repr, have hUv : stereographic' n v = (stereographic (norm_eq_of_mem_sphere v)) ≫ₕ U.to_homeomorph.to_local_homeomorph := rfl, have hU'v' : stereographic' n v' = (stereographic (norm_eq_of_mem_sphere v')).trans U'.to_homeomorph.to_local_homeomorph := rfl, have H₁ := U'.cont_diff.comp_cont_diff_on cont_diff_on_stereo_to_fun, have H₂ := (cont_diff_stereo_inv_fun_aux.comp (ℝ ∙ (v:E))ᗮ.subtypeL.cont_diff).comp U.symm.cont_diff, convert H₁.comp' (H₂.cont_diff_on : cont_diff_on ℝ ⊤ _ set.univ) using 1, ext, simp [sphere_ext_iff, stereographic'_symm_apply, real_inner_comm] end /-- The inclusion map (i.e., `coe`) from the sphere in `E` to `E` is smooth. -/ lemma cont_mdiff_coe_sphere {n : ℕ} [fact (finrank ℝ E = n + 1)] : cont_mdiff (𝓡 n) 𝓘(ℝ, E) ∞ (coe : (sphere (0:E) 1) → E) := begin rw cont_mdiff_iff, split, { exact continuous_subtype_coe }, { intros v _, let U := -- Again, removing type ascription... (orthonormal_basis.from_orthogonal_span_singleton n (ne_zero_of_mem_unit_sphere (-v))).repr, exact ((cont_diff_stereo_inv_fun_aux.comp (ℝ ∙ ((-v):E))ᗮ.subtypeL.cont_diff).comp U.symm.cont_diff).cont_diff_on } end variables {F : Type*} [normed_add_comm_group F] [normed_space ℝ F] variables {H : Type*} [topological_space H] {I : model_with_corners ℝ F H} variables {M : Type*} [topological_space M] [charted_space H M] [smooth_manifold_with_corners I M] /-- If a `cont_mdiff` function `f : M → E`, where `M` is some manifold, takes values in the sphere, then it restricts to a `cont_mdiff` function from `M` to the sphere. -/ lemma cont_mdiff.cod_restrict_sphere {n : ℕ} [fact (finrank ℝ E = n + 1)] {m : with_top ℕ} {f : M → E} (hf : cont_mdiff I 𝓘(ℝ, E) m f) (hf' : ∀ x, f x ∈ sphere (0:E) 1) : cont_mdiff I (𝓡 n) m (set.cod_restrict _ _ hf' : M → (sphere (0:E) 1)) := begin rw cont_mdiff_iff_target, refine ⟨continuous_induced_rng.2 hf.continuous, _⟩, intros v, let U := -- Again, removing type ascription... Weird that this helps! (orthonormal_basis.from_orthogonal_span_singleton n (ne_zero_of_mem_unit_sphere (-v))).repr, have h : cont_diff_on ℝ ⊤ _ set.univ := U.cont_diff.cont_diff_on, have H₁ := (h.comp' cont_diff_on_stereo_to_fun).cont_mdiff_on, have H₂ : cont_mdiff_on _ _ _ _ set.univ := hf.cont_mdiff_on, convert (H₁.of_le le_top).comp' H₂ using 1, ext x, have hfxv : f x = -↑v ↔ ⟪f x, -↑v⟫_ℝ = 1, { have hfx : ∥f x∥ = 1 := by simpa using hf' x, rw inner_eq_norm_mul_iff_of_norm_one hfx, exact norm_eq_of_mem_sphere (-v) }, dsimp [chart_at], simp [not_iff_not, subtype.ext_iff, hfxv, real_inner_comm] end /-- The antipodal map is smooth. -/ lemma cont_mdiff_neg_sphere {n : ℕ} [fact (finrank ℝ E = n + 1)] : cont_mdiff (𝓡 n) (𝓡 n) ∞ (λ x : sphere (0:E) 1, -x) := begin -- this doesn't elaborate well in term mode apply cont_mdiff.cod_restrict_sphere, apply cont_diff_neg.cont_mdiff.comp _, exact cont_mdiff_coe_sphere, end end smooth_manifold section circle open complex local attribute [instance] finrank_real_complex_fact /-- The unit circle in `ℂ` is a charted space modelled on `euclidean_space ℝ (fin 1)`. This follows by definition from the corresponding result for `metric.sphere`. -/ instance : charted_space (euclidean_space ℝ (fin 1)) circle := metric.sphere.charted_space instance : smooth_manifold_with_corners (𝓡 1) circle := metric.sphere.smooth_manifold_with_corners /-- The unit circle in `ℂ` is a Lie group. -/ instance : lie_group (𝓡 1) circle := { smooth_mul := begin apply cont_mdiff.cod_restrict_sphere, let c : circle → ℂ := coe, have h₂ : cont_mdiff (𝓘(ℝ, ℂ).prod 𝓘(ℝ, ℂ)) 𝓘(ℝ, ℂ) ∞ (λ (z : ℂ × ℂ), z.fst * z.snd), { rw cont_mdiff_iff, exact ⟨continuous_mul, λ x y, cont_diff_mul.cont_diff_on⟩ }, suffices h₁ : cont_mdiff _ _ _ (prod.map c c), { apply h₂.comp h₁ }, -- this elaborates much faster with `apply` apply cont_mdiff.prod_map; exact cont_mdiff_coe_sphere, end, smooth_inv := begin apply cont_mdiff.cod_restrict_sphere, simp only [← coe_inv_circle, coe_inv_circle_eq_conj], exact complex.conj_cle.cont_diff.cont_mdiff.comp cont_mdiff_coe_sphere end } /-- The map `λ t, exp (t * I)` from `ℝ` to the unit circle in `ℂ` is smooth. -/ lemma cont_mdiff_exp_map_circle : cont_mdiff 𝓘(ℝ, ℝ) (𝓡 1) ∞ exp_map_circle := ((cont_diff_exp.comp (cont_diff_id.smul cont_diff_const)).cont_mdiff).cod_restrict_sphere _ end circle
fb1d392b1cbbb09542b3f3b420f1d8d6cdf2d11e
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/category_theory/adjunction/over.lean
048eb4e5ac321d315c8e80a5225561d9dde3dc01
[ "Apache-2.0" ]
permissive
alreadydone/mathlib
dc0be621c6c8208c581f5170a8216c5ba6721927
c982179ec21091d3e102d8a5d9f5fe06c8fafb73
refs/heads/master
1,685,523,275,196
1,670,184,141,000
1,670,184,141,000
287,574,545
0
0
Apache-2.0
1,670,290,714,000
1,597,421,623,000
Lean
UTF-8
Lean
false
false
1,626
lean
/- Copyright (c) 2021 Bhavik Mehta. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Bhavik Mehta -/ import category_theory.limits.shapes.binary_products import category_theory.monad.products import category_theory.over /-! # Adjunctions related to the over category Construct the left adjoint `star X` to `over.forget X : over X ⥤ C`. ## TODO Show `star X` itself has a left adjoint provided `C` is locally cartesian closed. -/ noncomputable theory universes v u -- declare the `v`'s first; see `category_theory.category` for an explanation namespace category_theory open category limits comonad variables {C : Type u} [category.{v} C] (X : C) /-- The functor from `C` to `over X` which sends `Y : C` to `π₁ : X ⨯ Y ⟶ X`, sometimes denoted `X*`. -/ @[simps obj_left obj_hom map_left] def star [has_binary_products C] : C ⥤ over X := cofree _ ⋙ coalgebra_to_over X /-- The functor `over.forget X : over X ⥤ C` has a right adjoint given by `star X`. Note that the binary products assumption is necessary: the existence of a right adjoint to `over.forget X` is equivalent to the existence of each binary product `X ⨯ -`. -/ def forget_adj_star [has_binary_products C] : over.forget X ⊣ star X := (coalgebra_equiv_over X).symm.to_adjunction.comp (adj _) /-- Note that the binary products assumption is necessary: the existence of a right adjoint to `over.forget X` is equivalent to the existence of each binary product `X ⨯ -`. -/ instance [has_binary_products C] : is_left_adjoint (over.forget X) := ⟨_, forget_adj_star X⟩ end category_theory
2f7c9bba64b0b98ec2b1606248c0508d84df7cd8
e514e8b939af519a1d5e9b30a850769d058df4e9
/src/tactic/rewrite_search/core/debug.lean
0b0a8f394ff59ad680393670e8620ff202ce59fd
[]
no_license
semorrison/lean-rewrite-search
dca317c5a52e170fb6ffc87c5ab767afb5e3e51a
e804b8f2753366b8957be839908230ee73f9e89f
refs/heads/master
1,624,051,754,485
1,614,160,817,000
1,614,160,817,000
162,660,605
0
1
null
null
null
null
UTF-8
Lean
false
false
2,401
lean
import .types namespace tactic.rewrite_search namespace search_state variables {α β γ δ : Type} (g : search_state α β γ δ) meta def trace_tactic {ε : Type} [has_to_tactic_format ε] (fn : tactic ε) : tactic unit := if g.conf.trace then do ev ← fn, tactic.trace ev else tactic.skip meta def trace {ε : Type} [has_to_tactic_format ε] (s : ε) : tactic unit := g.trace_tactic $ return s meta def tracer_vertex_added (v : vertex) : tactic unit := do g.tr.publish_vertex g.tr_state v, g.trace_tactic $ return format!"addV({v.id.to_string}): {v.pp}" meta def tracer_edge_added (e : edge) : tactic unit := do g.tr.publish_edge g.tr_state e, g.trace_tactic $ return format!"addE: {e.f.to_string}→{e.t.to_string}" meta def tracer_visited (v : vertex) : tactic unit := g.tr.publish_visited g.tr_state v meta def tracer_search_finished (es : list edge) : tactic unit := do g.tr.publish_finished g.tr_state es, g.trace "Done!" meta def tracer_dump {ε : Type} [has_to_tactic_format ε] (s : ε) : tactic unit := do fmt ← has_to_tactic_format.to_tactic_format s, let str := fmt.to_string, g.tr.dump g.tr_state str, g.trace str end search_state namespace inst variables {α β γ δ : Type} (i : inst α β γ δ) meta def dump_rws : list (expr × expr × ℕ × ℕ) → tactic unit | [] := tactic.skip | (a :: rest) := do tactic.trace format!"→{a.1}\nPF:{a.2}", dump_rws rest meta def dump_tokens : list token → tactic unit | [] := tactic.skip | (a :: rest) := do tactic.trace format!"V{a.id.to_string}:{a.str}|{a.freq.get side.L}v{a.freq.get side.R}", dump_tokens rest meta def dump_vertices : list vertex → tactic unit | [] := tactic.skip | (a :: rest) := do let pfx : string := match a.parent with | none := "?" | some p := p.f.to_string end, i.g.tracer_dump (to_string format!"V{a.id.to_string}:{a.pp}<-{pfx}:{a.root}"), dump_vertices rest meta def dump_edges : list edge → tactic unit | [] := tactic.skip | (a :: rest) := do (vf, vt) ← i.g.get_endpoints a, i.g.tracer_dump format!"E{vf.pp}→{vt.pp}", dump_edges rest meta def dump_estimates : list (dist_estimate γ) → tactic unit | [] := tactic.trace "" | (a :: rest) := do (lpp, rpp) ← i.g.get_estimate_verts a, i.g.tracer_dump format!"I{lpp}-{rpp}:{a.bnd.bound}", dump_estimates rest end inst end tactic.rewrite_search
7acb0ffc93f9dc9ca081ffdddf55bdbd8774d993
5ae26df177f810c5006841e9c73dc56e01b978d7
/docs/tutorial/category_theory/calculating_colimits_in_Top.lean
f8fa88aa7150783212defdf65143b7904c25888b
[ "Apache-2.0" ]
permissive
ChrisHughes24/mathlib
98322577c460bc6b1fe5c21f42ce33ad1c3e5558
a2a867e827c2a6702beb9efc2b9282bd801d5f9a
refs/heads/master
1,583,848,251,477
1,565,164,247,000
1,565,164,247,000
129,409,993
0
1
Apache-2.0
1,565,164,817,000
1,523,628,059,000
Lean
UTF-8
Lean
false
false
2,886
lean
import topology.Top.limits import category_theory.limits.shapes import topology.instances.real /- This file contains some demos of using the (co)limits API to do topology. -/ noncomputable theory open category_theory open category_theory.limits def R : Top := Top.of ℝ def I : Top := Top.of (set.Icc 0 1 : set ℝ) def pt : Top := Top.of unit section MappingCylinder -- Let's construct the mapping cylinder. def to_pt (X : Top) : X ⟶ pt := { val := λ _, unit.star, property := continuous_const } def I_0 : pt ⟶ I := { val := λ _, ⟨(0 : ℝ), begin rw [set.left_mem_Icc], norm_num, end⟩, property := continuous_const } def I_1 : pt ⟶ I := { val := λ _, ⟨(1 : ℝ), begin rw [set.right_mem_Icc], norm_num, end⟩, property := continuous_const } def cylinder (X : Top) : Top := limit (pair X I) -- To define a map to the cylinder, we give a map to each factor. -- `binary_fan.mk` is a helper method for constructing a `cone` over `pair X Y`. def cylinder_0 (X : Top) : X ⟶ cylinder X := limit.lift (pair X I) (binary_fan.mk (𝟙 X) (to_pt X ≫ I_0)) def cylinder_1 (X : Top) : X ⟶ cylinder X := limit.lift (pair X I) (binary_fan.mk (𝟙 X) (to_pt X ≫ I_1)) -- The mapping cylinder is the colimit of the diagram -- X -- ↙ ↘ -- Y (X x I) def mapping_cylinder {X Y : Top} (f : X ⟶ Y) : Top := colimit (span f (cylinder_1 X)) -- The mapping cone is the colimit of the diagram -- X X -- ↙ ↘ ↙ ↘ -- Y (X x I) pt -- Here we'll calculate it as an iterated colimit, as the colimit of -- X -- ↙ ↘ -- (Cyl f) pt def mapping_cylinder_0 {X Y : Top} (f : X ⟶ Y) : X ⟶ mapping_cylinder f := cylinder_0 X ≫ colimit.ι (span f (cylinder_1 X)) walking_span.right def mapping_cone {X Y : Top} (f : X ⟶ Y) : Top := colimit (span (mapping_cylinder_0 f) (to_pt X)) -- TODO Hopefully someone will write a nice tactic for generating diagrams quickly, -- and we'll be able to verify that this iterated construction is the same as the colimit -- over a single diagram. end MappingCylinder section Gluing -- Here's two copies of the real line glued together at a point. def f : pt ⟶ R := { val := λ _, (0 : ℝ), property := continuous_const } def X : Top := colimit (span f f) -- To define a map out of it, we define maps out of each copy of the line, -- and check the maps agree at 0. -- `pushout_cocone.mk` is a helper method for constructing cocones over a span. def g : X ⟶ R := colimit.desc (span f f) (pushout_cocone.mk (𝟙 _) (𝟙 _) rfl). end Gluing universes v u w section Products def d : discrete ℕ ⥤ Top := functor.of_function (λ n : ℕ, R) def Y : Top := limit d def w : cone d := fan.mk (λ (n : ℕ), ⟨λ (_ : pt), (n : ℝ), continuous_const⟩) def q : pt ⟶ Y := limit.lift d w example : (q.val ()).val (57 : ℕ) = ((57 : ℕ) : ℝ) := rfl end Products
75ffd4b9ebc4260a356b64caac810beb20cc243a
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/algebra/lie/solvable.lean
a8d3eb045c8937354e1541d2c4b047428a3f34ca
[ "Apache-2.0" ]
permissive
AntoineChambert-Loir/mathlib
64aabb896129885f12296a799818061bc90da1ff
07be904260ab6e36a5769680b6012f03a4727134
refs/heads/master
1,693,187,631,771
1,636,719,886,000
1,636,719,886,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
14,032
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.ideal_operations import algebra.lie.abelian import order.preorder_hom /-! # Solvable Lie algebras Like groups, Lie algebras admit a natural concept of solvability. We define this here via the derived series and prove some related results. We also define the radical of a Lie algebra and prove that it is solvable when the Lie algebra is Noetherian. ## Main definitions * `lie_algebra.derived_series_of_ideal` * `lie_algebra.derived_series` * `lie_algebra.is_solvable` * `lie_algebra.is_solvable_add` * `lie_algebra.radical` * `lie_algebra.radical_is_solvable` * `lie_algebra.derived_length_of_ideal` * `lie_algebra.derived_length` * `lie_algebra.derived_abelian_of_ideal` ## Tags lie algebra, derived series, derived length, solvable, radical -/ universes u v w w₁ w₂ variables (R : Type u) (L : Type v) (M : Type w) {L' : Type w₁} variables [comm_ring R] [lie_ring L] [lie_algebra R L] [lie_ring L'] [lie_algebra R L'] variables (I J : lie_ideal R L) {f : L' →ₗ⁅R⁆ L} namespace lie_algebra /-- A generalisation of the derived series of a Lie algebra, whose zeroth term is a specified ideal. It can be more convenient to work with this generalisation when considering the derived series of an ideal since it provides a type-theoretic expression of the fact that the terms of the ideal's derived series are also ideals of the enclosing algebra. See also `lie_ideal.derived_series_eq_derived_series_of_ideal_comap` and `lie_ideal.derived_series_eq_derived_series_of_ideal_map` below. -/ def derived_series_of_ideal (k : ℕ) : lie_ideal R L → lie_ideal R L := (λ I, ⁅I, I⁆)^[k] @[simp] lemma derived_series_of_ideal_zero : derived_series_of_ideal R L 0 I = I := rfl @[simp] lemma derived_series_of_ideal_succ (k : ℕ) : derived_series_of_ideal R L (k + 1) I = ⁅derived_series_of_ideal R L k I, derived_series_of_ideal R L k I⁆ := function.iterate_succ_apply' (λ I, ⁅I, I⁆) k I /-- The derived series of Lie ideals of a Lie algebra. -/ abbreviation derived_series (k : ℕ) : lie_ideal R L := derived_series_of_ideal R L k ⊤ lemma derived_series_def (k : ℕ) : derived_series R L k = derived_series_of_ideal R L k ⊤ := rfl variables {R L} local notation `D` := derived_series_of_ideal R L lemma derived_series_of_ideal_add (k l : ℕ) : D (k + l) I = D k (D l I) := begin induction k with k ih, { rw [zero_add, derived_series_of_ideal_zero], }, { rw [nat.succ_add k l, derived_series_of_ideal_succ, derived_series_of_ideal_succ, ih], }, end @[mono] lemma derived_series_of_ideal_le {I J : lie_ideal R L} {k l : ℕ} (h₁ : I ≤ J) (h₂ : l ≤ k) : D k I ≤ D l J := begin revert l, induction k with k ih; intros l h₂, { rw nat.le_zero_iff at h₂, rw [h₂, derived_series_of_ideal_zero], exact h₁, }, { have h : l = k.succ ∨ l ≤ k, by rwa [le_iff_eq_or_lt, nat.lt_succ_iff] at h₂, cases h, { rw [h, derived_series_of_ideal_succ, derived_series_of_ideal_succ], exact lie_submodule.mono_lie _ _ _ _ (ih (le_refl k)) (ih (le_refl k)), }, { rw derived_series_of_ideal_succ, exact le_trans (lie_submodule.lie_le_left _ _) (ih h), }, }, end lemma derived_series_of_ideal_succ_le (k : ℕ) : D (k + 1) I ≤ D k I := derived_series_of_ideal_le (le_refl I) k.le_succ lemma derived_series_of_ideal_le_self (k : ℕ) : D k I ≤ I := derived_series_of_ideal_le (le_refl I) (zero_le k) lemma derived_series_of_ideal_mono {I J : lie_ideal R L} (h : I ≤ J) (k : ℕ) : D k I ≤ D k J := derived_series_of_ideal_le h (le_refl k) lemma derived_series_of_ideal_antitone {k l : ℕ} (h : l ≤ k) : D k I ≤ D l I := derived_series_of_ideal_le (le_refl I) h lemma derived_series_of_ideal_add_le_add (J : lie_ideal R L) (k l : ℕ) : D (k + l) (I + J) ≤ (D k I) + (D l J) := begin let D₁ : lie_ideal R L →ₘ lie_ideal R L := { to_fun := λ I, ⁅I, I⁆, monotone' := λ I J h, lie_submodule.mono_lie I J I J h h, }, have h₁ : ∀ (I J : lie_ideal R L), D₁ (I ⊔ J) ≤ (D₁ I) ⊔ J, { simp [lie_submodule.lie_le_right, lie_submodule.lie_le_left, le_sup_of_le_right], }, rw ← D₁.iterate_sup_le_sup_iff at h₁, exact h₁ k l I J, end lemma derived_series_of_bot_eq_bot (k : ℕ) : derived_series_of_ideal R L k ⊥ = ⊥ := by { rw eq_bot_iff, exact derived_series_of_ideal_le_self ⊥ k, } lemma abelian_iff_derived_one_eq_bot : is_lie_abelian I ↔ derived_series_of_ideal R L 1 I = ⊥ := by rw [derived_series_of_ideal_succ, derived_series_of_ideal_zero, lie_submodule.lie_abelian_iff_lie_self_eq_bot] lemma abelian_iff_derived_succ_eq_bot (I : lie_ideal R L) (k : ℕ) : is_lie_abelian (derived_series_of_ideal R L k I) ↔ derived_series_of_ideal R L (k + 1) I = ⊥ := by rw [add_comm, derived_series_of_ideal_add I 1 k, abelian_iff_derived_one_eq_bot] end lie_algebra namespace lie_ideal open lie_algebra variables {R L} lemma derived_series_eq_derived_series_of_ideal_comap (k : ℕ) : derived_series R I k = (derived_series_of_ideal R L k I).comap I.incl := begin induction k with k ih, { simp only [derived_series_def, comap_incl_self, derived_series_of_ideal_zero], }, { simp only [derived_series_def, derived_series_of_ideal_succ] at ⊢ ih, rw ih, exact comap_bracket_incl_of_le I (derived_series_of_ideal_le_self I k) (derived_series_of_ideal_le_self I k), }, end lemma derived_series_eq_derived_series_of_ideal_map (k : ℕ) : (derived_series R I k).map I.incl = derived_series_of_ideal R L k I := by { rw [derived_series_eq_derived_series_of_ideal_comap, map_comap_incl, inf_eq_right], apply derived_series_of_ideal_le_self, } lemma derived_series_eq_bot_iff (k : ℕ) : derived_series R I k = ⊥ ↔ derived_series_of_ideal R L k I = ⊥ := by rw [← derived_series_eq_derived_series_of_ideal_map, map_eq_bot_iff, ker_incl, eq_bot_iff] lemma derived_series_add_eq_bot {k l : ℕ} {I J : lie_ideal R L} (hI : derived_series R I k = ⊥) (hJ : derived_series R J l = ⊥) : derived_series R ↥(I + J) (k + l) = ⊥ := begin rw lie_ideal.derived_series_eq_bot_iff at hI hJ ⊢, rw ← le_bot_iff, let D := derived_series_of_ideal R L, change D k I = ⊥ at hI, change D l J = ⊥ at hJ, calc D (k + l) (I + J) ≤ (D k I) + (D l J) : derived_series_of_ideal_add_le_add I J k l ... ≤ ⊥ : by { rw [hI, hJ], simp, }, end lemma derived_series_map_le (k : ℕ) : (derived_series R L' k).map f ≤ derived_series R L k := begin induction k with k ih, { simp only [derived_series_def, derived_series_of_ideal_zero, le_top], }, { simp only [derived_series_def, derived_series_of_ideal_succ] at ih ⊢, exact le_trans (map_bracket_le f) (lie_submodule.mono_lie _ _ _ _ ih ih), }, end lemma derived_series_map_eq (k : ℕ) (h : function.surjective f) : (derived_series R L' k).map f = derived_series R L k := begin induction k with k ih, { change (⊤ : lie_ideal R L').map f = ⊤, rw ←f.ideal_range_eq_map, exact f.ideal_range_eq_top_of_surjective h, }, { simp only [derived_series_def, map_bracket_eq f h, ih, derived_series_of_ideal_succ], }, end end lie_ideal namespace lie_algebra /-- A Lie algebra is solvable if its derived series reaches 0 (in a finite number of steps). -/ class is_solvable : Prop := (solvable : ∃ k, derived_series R L k = ⊥) instance is_solvable_bot : is_solvable R ↥(⊥ : lie_ideal R L) := ⟨⟨0, @subsingleton.elim _ lie_ideal.subsingleton_of_bot _ ⊥⟩⟩ instance is_solvable_add {I J : lie_ideal R L} [hI : is_solvable R I] [hJ : is_solvable R J] : is_solvable R ↥(I + J) := begin tactic.unfreeze_local_instances, obtain ⟨k, hk⟩ := hI, obtain ⟨l, hl⟩ := hJ, exact ⟨⟨k+l, lie_ideal.derived_series_add_eq_bot hk hl⟩⟩, end end lie_algebra variables {R L} namespace function open lie_algebra lemma injective.lie_algebra_is_solvable [h₁ : is_solvable R L] (h₂ : injective f) : is_solvable R L' := begin tactic.unfreeze_local_instances, obtain ⟨k, hk⟩ := h₁, use k, apply lie_ideal.bot_of_map_eq_bot h₂, rw [eq_bot_iff, ← hk], apply lie_ideal.derived_series_map_le, end lemma surjective.lie_algebra_is_solvable [h₁ : is_solvable R L'] (h₂ : surjective f) : is_solvable R L := begin tactic.unfreeze_local_instances, obtain ⟨k, hk⟩ := h₁, use k, rw [← lie_ideal.derived_series_map_eq k h₂, hk], simp only [lie_ideal.map_eq_bot_iff, bot_le], end end function lemma lie_hom.is_solvable_range (f : L' →ₗ⁅R⁆ L) [h : lie_algebra.is_solvable R L'] : lie_algebra.is_solvable R f.range := f.surjective_range_restrict.lie_algebra_is_solvable namespace lie_algebra lemma solvable_iff_equiv_solvable (e : L' ≃ₗ⁅R⁆ L) : is_solvable R L' ↔ is_solvable R L := begin split; introsI h, { exact e.symm.injective.lie_algebra_is_solvable, }, { exact e.injective.lie_algebra_is_solvable, }, end lemma le_solvable_ideal_solvable {I J : lie_ideal R L} (h₁ : I ≤ J) (h₂ : is_solvable R J) : is_solvable R I := (lie_ideal.hom_of_le_injective h₁).lie_algebra_is_solvable variables (R L) @[priority 100] instance of_abelian_is_solvable [is_lie_abelian L] : is_solvable R L := begin use 1, rw [← abelian_iff_derived_one_eq_bot, lie_abelian_iff_equiv_lie_abelian lie_ideal.top_equiv_self], apply_instance, end /-- The (solvable) radical of Lie algebra is the `Sup` of all solvable ideals. -/ def radical := Sup { I : lie_ideal R L | is_solvable R I } /-- The radical of a Noetherian Lie algebra is solvable. -/ instance radical_is_solvable [is_noetherian R L] : is_solvable R (radical R L) := begin have hwf := lie_submodule.well_founded_of_noetherian R L L, rw ← complete_lattice.is_sup_closed_compact_iff_well_founded at hwf, refine hwf { I : lie_ideal R L | is_solvable R I } _ _, { use ⊥, exact lie_algebra.is_solvable_bot R L, }, { intros I J hI hJ, apply lie_algebra.is_solvable_add R L; [exact hI, exact hJ], }, end /-- The `→` direction of this lemma is actually true without the `is_noetherian` assumption. -/ lemma lie_ideal.solvable_iff_le_radical [is_noetherian R L] (I : lie_ideal R L) : is_solvable R I ↔ I ≤ radical R L := begin split; intros h, { exact le_Sup h, }, { apply le_solvable_ideal_solvable h, apply_instance, }, end lemma center_le_radical : center R L ≤ radical R L := have h : is_solvable R (center R L), { apply_instance, }, le_Sup h /-- Given a solvable Lie ideal `I` with derived series `I = D₀ ≥ D₁ ≥ ⋯ ≥ Dₖ = ⊥`, this is the natural number `k` (the number of inclusions). For a non-solvable ideal, the value is 0. -/ noncomputable def derived_length_of_ideal (I : lie_ideal R L) : ℕ := Inf {k | derived_series_of_ideal R L k I = ⊥} /-- The derived length of a Lie algebra is the derived length of its 'top' Lie ideal. See also `lie_algebra.derived_length_eq_derived_length_of_ideal`. -/ noncomputable abbreviation derived_length : ℕ := derived_length_of_ideal R L ⊤ lemma derived_series_of_derived_length_succ (I : lie_ideal R L) (k : ℕ) : derived_length_of_ideal R L I = k + 1 ↔ is_lie_abelian (derived_series_of_ideal R L k I) ∧ derived_series_of_ideal R L k I ≠ ⊥ := begin rw abelian_iff_derived_succ_eq_bot, let s := {k | derived_series_of_ideal R L k I = ⊥}, change Inf s = k + 1 ↔ k + 1 ∈ s ∧ k ∉ s, have hs : ∀ (k₁ k₂ : ℕ), k₁ ≤ k₂ → k₁ ∈ s → k₂ ∈ s, { intros k₁ k₂ h₁₂ h₁, suffices : derived_series_of_ideal R L k₂ I ≤ ⊥, { exact eq_bot_iff.mpr this, }, change derived_series_of_ideal R L k₁ I = ⊥ at h₁, rw ← h₁, exact derived_series_of_ideal_antitone I h₁₂, }, exact nat.Inf_upward_closed_eq_succ_iff hs k, end lemma derived_length_eq_derived_length_of_ideal (I : lie_ideal R L) : derived_length R I = derived_length_of_ideal R L I := begin let s₁ := {k | derived_series R I k = ⊥}, let s₂ := {k | derived_series_of_ideal R L k I = ⊥}, change Inf s₁ = Inf s₂, congr, ext k, exact I.derived_series_eq_bot_iff k, end variables {R L} /-- Given a solvable Lie ideal `I` with derived series `I = D₀ ≥ D₁ ≥ ⋯ ≥ Dₖ = ⊥`, this is the `k-1`th term in the derived series (and is therefore an Abelian ideal contained in `I`). For a non-solvable ideal, this is the zero ideal, `⊥`. -/ noncomputable def derived_abelian_of_ideal (I : lie_ideal R L) : lie_ideal R L := match derived_length_of_ideal R L I with | 0 := ⊥ | k + 1 := derived_series_of_ideal R L k I end lemma abelian_derived_abelian_of_ideal (I : lie_ideal R L) : is_lie_abelian (derived_abelian_of_ideal I) := begin dunfold derived_abelian_of_ideal, cases h : derived_length_of_ideal R L I with k, { exact is_lie_abelian_bot R L, }, { rw derived_series_of_derived_length_succ at h, exact h.1, }, end lemma derived_length_zero (I : lie_ideal R L) [hI : is_solvable R I] : derived_length_of_ideal R L I = 0 ↔ I = ⊥ := begin let s := {k | derived_series_of_ideal R L k I = ⊥}, change Inf s = 0 ↔ _, have hne : s ≠ ∅, { rw set.ne_empty_iff_nonempty, tactic.unfreeze_local_instances, obtain ⟨k, hk⟩ := hI, use k, rw [derived_series_def, lie_ideal.derived_series_eq_bot_iff] at hk, exact hk, }, simp [hne], end lemma abelian_of_solvable_ideal_eq_bot_iff (I : lie_ideal R L) [h : is_solvable R I] : derived_abelian_of_ideal I = ⊥ ↔ I = ⊥ := begin dunfold derived_abelian_of_ideal, cases h : derived_length_of_ideal R L I with k, { rw derived_length_zero at h, rw h, refl, }, { obtain ⟨h₁, h₂⟩ := (derived_series_of_derived_length_succ R L I k).mp h, have h₃ : I ≠ ⊥, { intros contra, apply h₂, rw contra, apply derived_series_of_bot_eq_bot, }, change derived_series_of_ideal R L k I = ⊥ ↔ I = ⊥, split; contradiction, }, end end lie_algebra
22b3359af05903496963f53a984bb75ff1515917
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/tactic/nth_rewrite/basic_auto.lean
484f7ccf636ef08234fd234efd00b7a90622c645
[]
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
414
lean
/- Copyright (c) 2018 Keeley Hoek. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin, Keeley Hoek, Scott Morrison -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.meta.expr_lens import Mathlib.PostPort namespace Mathlib namespace tactic namespace nth_rewrite /-- Configuration options for nth_rewrite. -/ end Mathlib
f3a4e6f66bbb15f359b04e99ac7efed5ed95802e
6b10c15e653d49d146378acda9f3692e9b5b1950
/examples/logic/unnamed_520.lean
428fab798329975c386317cfc7d0c04f5c970d2b
[]
no_license
gebner/mathematics_in_lean
3cf7f18767208ea6c3307ec3a67c7ac266d8514d
6d1462bba46d66a9b948fc1aef2714fd265cde0b
refs/heads/master
1,655,301,945,565
1,588,697,505,000
1,588,697,505,000
261,523,603
0
0
null
1,588,695,611,000
1,588,695,610,000
null
UTF-8
Lean
false
false
552
lean
import tactic variables A B C : Prop example : A ∧ (A → B) → A ∧ B := sorry example : B → (A → B) := sorry example (h : A ∧ B → C) : A → B → C := sorry example (h : A → B → C) : A ∧ B → C := sorry example : (A → B) ∧ (B → C) ∧ A → C := sorry example : A → (A → B) → (A ∧ B → C) → C := sorry -- use rcases example (h : A ∧ (A → B) ∧ (A ∧ B → C)) : C := sorry example : A → ¬ (¬ A ∧ B) := sorry example : ¬ (A ∧ B) → A → ¬ B := sorry example : A ∧ ¬ A → B := sorry
7c29f4e6753b271199b64d71a1d8eba69504aa6d
aa3f8992ef7806974bc1ffd468baa0c79f4d6643
/tests/lean/inst.lean
6a87d2a7073d8999af95aac12bdbb1c0ab371518
[ "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
568
lean
import logic data.prod priority open priority set_option pp.notation false inductive C [class] (A : Type) := mk : A → C A definition val {A : Type} (c : C A) : A := C.rec (λa, a) c constant magic (A : Type) : A definition C_magic [instance] [priority max] (A : Type) : C A := C.mk (magic A) definition C_prop [instance] : C Prop := C.mk true definition C_prod [instance] {A B : Type} (Ha : C A) (Hb : C B) : C (prod A B) := C.mk (pair (val Ha) (val Hb)) -- C_magic will be used because it has max priority definition test : C (prod Prop Prop) := _ eval test
c077ab8c71af81ee6f61aed25e0fe8483dd78057
367134ba5a65885e863bdc4507601606690974c1
/src/group_theory/perm/fin.lean
7100dc598632b8374a3fde140953d6cbbe18401e
[ "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
2,849
lean
/- Copyright (c) 2021 Eric Wieser. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Eric Wieser -/ import group_theory.perm.option import data.equiv.fin /-! # Permutations of `fin n` -/ open equiv /-- Permutations of `fin (n + 1)` are equivalent to fixing a single `fin (n + 1)` and permuting the remaining with a `perm (fin n)`. The fixed `fin (n + 1)` is swapped with `0`. -/ def equiv.perm.decompose_fin {n : ℕ} : perm (fin n.succ) ≃ fin n.succ × perm (fin n) := ((equiv.perm_congr $ fin_succ_equiv n).trans equiv.perm.decompose_option).trans (equiv.prod_congr (fin_succ_equiv n).symm (equiv.refl _)) @[simp] lemma equiv.perm.decompose_fin_symm_of_refl {n : ℕ} (p : fin (n + 1)) : equiv.perm.decompose_fin.symm (p, equiv.refl _) = swap 0 p := by simp [equiv.perm.decompose_fin, equiv.perm_congr_def] @[simp] lemma equiv.perm.decompose_fin_symm_of_one {n : ℕ} (p : fin (n + 1)) : equiv.perm.decompose_fin.symm (p, 1) = swap 0 p := equiv.perm.decompose_fin_symm_of_refl p @[simp] lemma equiv.perm.decompose_fin_symm_apply_zero {n : ℕ} (p : fin (n + 1)) (e : perm (fin n)) : equiv.perm.decompose_fin.symm (p, e) 0 = p := by simp [equiv.perm.decompose_fin] @[simp] lemma equiv.perm.decompose_fin_symm_apply_succ {n : ℕ} (e : perm (fin n)) (p : fin (n + 1)) (x : fin n) : equiv.perm.decompose_fin.symm (p, e) x.succ = swap 0 p (e x).succ := begin refine fin.cases _ _ p, { simp [equiv.perm.decompose_fin, equiv_functor.map] }, { intros i, by_cases h : i = e x, { simp [h, equiv.perm.decompose_fin, equiv_functor.map] }, { have h' : some (e x) ≠ some i := λ H, h (option.some_injective _ H).symm, have h'' : (e x).succ ≠ i.succ := λ H, h (fin.succ_injective _ H).symm, simp [h, h'', fin.succ_ne_zero, equiv.perm.decompose_fin, equiv_functor.map, swap_apply_of_ne_of_ne, swap_apply_of_ne_of_ne (option.some_ne_none (e x)) h'] } } end @[simp] lemma equiv.perm.decompose_fin_symm_apply_one {n : ℕ} (e : perm (fin (n + 1))) (p : fin (n + 2)) : equiv.perm.decompose_fin.symm (p, e) 1 = swap 0 p (e 0).succ := equiv.perm.decompose_fin_symm_apply_succ e p 0 @[simp] lemma equiv.perm.decompose_fin.symm_sign {n : ℕ} (p : fin (n + 1)) (e : perm (fin n)) : perm.sign (equiv.perm.decompose_fin.symm (p, e)) = ite (p = 0) 1 (-1) * perm.sign e := by { refine fin.cases _ _ p; simp [equiv.perm.decompose_fin, fin.succ_ne_zero] } /-- The set of all permutations of `fin (n + 1)` can be constructed by augmenting the set of permutations of `fin n` by each element of `fin (n + 1)` in turn. -/ lemma finset.univ_perm_fin_succ {n : ℕ} : @finset.univ (perm $ fin n.succ) _ = (finset.univ : finset $ fin n.succ × perm (fin n)).map equiv.perm.decompose_fin.symm.to_embedding := (finset.univ_map_equiv_to_embedding _).symm
b861bc83fa4eba33c26bdc2f7005eadeae809d26
c86b74188c4b7a462728b1abd659ab4e5828dd61
/src/Init/Notation.lean
b99901f18cf817953bc67aff392ae5a31c31b7b4
[ "Apache-2.0" ]
permissive
cwb96/lean4
75e1f92f1ba98bbaa6b34da644b3dfab2ce7bf89
b48831cda76e64f13dd1c0edde7ba5fb172ed57a
refs/heads/master
1,686,347,881,407
1,624,483,842,000
1,624,483,842,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
14,384
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 Notation for operators defined at Prelude.lean -/ prelude import Init.Prelude -- DSL for specifying parser precedences and priorities namespace Lean.Parser.Syntax syntax:65 (name := addPrec) prec " + " prec:66 : prec syntax:65 (name := subPrec) prec " - " prec:66 : prec syntax:65 (name := addPrio) prio " + " prio:66 : prio syntax:65 (name := subPrio) prio " - " prio:66 : prio end Lean.Parser.Syntax macro "max" : prec => `(1024) -- maximum precedence used in term parsers, in particular for terms in function position (`ident`, `paren`, ...) macro "arg" : prec => `(1023) -- precedence used for application arguments (`do`, `by`, ...) macro "lead" : prec => `(1022) -- precedence used for terms not supposed to be used as arguments (`let`, `have`, ...) macro "(" p:prec ")" : prec => p macro "min" : prec => `(10) -- minimum precedence used in term parsers macro "min1" : prec => `(11) -- `(min+1) we can only `min+1` after `Meta.lean` /- `max:prec` as a term. It is equivalent to `eval_prec max` for `eval_prec` defined at `Meta.lean`. We use `max_prec` to workaround bootstrapping issues. -/ macro "max_prec" : term => `(1024) macro "default" : prio => `(1000) macro "low" : prio => `(100) macro "mid" : prio => `(1000) macro "high" : prio => `(10000) macro "(" p:prio ")" : prio => p -- Basic notation for defining parsers syntax stx "+" : stx syntax stx "*" : stx syntax stx "?" : stx syntax:2 stx " <|> " stx:1 : stx macro_rules | `(stx| $p +) => `(stx| many1($p)) | `(stx| $p *) => `(stx| many($p)) | `(stx| $p ?) => `(stx| optional($p)) | `(stx| $p₁ <|> $p₂) => `(stx| orelse($p₁, $p₂)) /- Comma-separated sequence. -/ macro:max x:stx ",*" : stx => `(stx| sepBy($x, ",", ", ")) macro:max x:stx ",+" : stx => `(stx| sepBy1($x, ",", ", ")) /- Comma-separated sequence with optional trailing comma. -/ macro:max x:stx ",*,?" : stx => `(stx| sepBy($x, ",", ", ", allowTrailingSep)) macro:max x:stx ",+,?" : stx => `(stx| sepBy1($x, ",", ", ", allowTrailingSep)) macro "!" x:stx : stx => `(stx| notFollowedBy($x)) syntax (name := rawNatLit) "nat_lit " num : term infixr:90 " ∘ " => Function.comp infixr:35 " × " => Prod infixl:55 " ||| " => HOr.hOr infixl:58 " ^^^ " => HXor.hXor infixl:60 " &&& " => HAnd.hAnd infixl:65 " + " => HAdd.hAdd infixl:65 " - " => HSub.hSub infixl:70 " * " => HMul.hMul infixl:70 " / " => HDiv.hDiv infixl:70 " % " => HMod.hMod infixl:75 " <<< " => HShiftLeft.hShiftLeft infixl:75 " >>> " => HShiftRight.hShiftRight infixr:80 " ^ " => HPow.hPow prefix:100 "-" => Neg.neg prefix:100 "~~~" => Complement.complement /- Remark: the infix commands above ensure a delaborator is generated for each relations. We redefine the macros below to be able to use the auxiliary `binop%` elaboration helper for binary operators. It addresses issue #382. -/ macro_rules | `($x ||| $y) => `(binop% HOr.hOr $x $y) macro_rules | `($x ^^^ $y) => `(binop% HXor.hXor $x $y) macro_rules | `($x &&& $y) => `(binop% HAnd.hAnd $x $y) macro_rules | `($x + $y) => `(binop% HAdd.hAdd $x $y) macro_rules | `($x - $y) => `(binop% HSub.hSub $x $y) macro_rules | `($x * $y) => `(binop% HMul.hMul $x $y) macro_rules | `($x / $y) => `(binop% HDiv.hDiv $x $y) macro_rules | `($x % $y) => `(binop% HMod.hMod $x $y) macro_rules | `($x <<< $y) => `(binop% HShiftLeft.hShiftLeft $x $y) macro_rules | `($x >>> $y) => `(binop% HShiftRight.hShiftRight $x $y) macro_rules | `($x ^ $y) => `(binop% HPow.hPow $x $y) -- declare ASCII alternatives first so that the latter Unicode unexpander wins infix:50 " <= " => LE.le infix:50 " ≤ " => LE.le infix:50 " < " => LT.lt infix:50 " >= " => GE.ge infix:50 " ≥ " => GE.ge infix:50 " > " => GT.gt infix:50 " = " => Eq infix:50 " == " => BEq.beq infix:50 " ~= " => HEq infix:50 " ≅ " => HEq /- Remark: the infix commands above ensure a delaborator is generated for each relations. We redefine the macros below to be able to use the auxiliary `binrel%` elaboration helper for binary relations. It has better support for applying coercions. For example, suppose we have `binrel% Eq n i` where `n : Nat` and `i : Int`. The default elaborator fails because we don't have a coercion from `Int` to `Nat`, but `binrel%` succeeds because it also tries a coercion from `Nat` to `Int` even when the nat occurs before the int. -/ macro_rules | `($x <= $y) => `(binrel% LE.le $x $y) macro_rules | `($x ≤ $y) => `(binrel% LE.le $x $y) macro_rules | `($x < $y) => `(binrel% LT.lt $x $y) macro_rules | `($x > $y) => `(binrel% GT.gt $x $y) macro_rules | `($x >= $y) => `(binrel% GE.ge $x $y) macro_rules | `($x ≥ $y) => `(binrel% GE.ge $x $y) macro_rules | `($x = $y) => `(binrel% Eq $x $y) macro_rules | `($x == $y) => `(binrel% BEq.beq $x $y) infixr:35 " /\\ " => And infixr:35 " ∧ " => And infixr:30 " \\/ " => Or infixr:30 " ∨ " => Or notation:max "¬" p:40 => Not p infixl:35 " && " => and infixl:30 " || " => or notation:max "!" b:40 => not b infixl:65 " ++ " => HAppend.hAppend infixr:67 " :: " => List.cons infixr:20 " <|> " => HOrElse.hOrElse infixr:60 " >> " => HAndThen.hAndThen infixl:55 " >>= " => Bind.bind infixl:60 " <*> " => Seq.seq infixl:60 " <* " => SeqLeft.seqLeft infixr:60 " *> " => SeqRight.seqRight infixr:100 " <$> " => Functor.map syntax (name := termDepIfThenElse) ppGroup(ppDedent("if " ident " : " term " then" ppSpace term ppDedent(ppSpace "else") ppSpace term)) : term macro_rules | `(if $h:ident : $c then $t:term else $e:term) => ``(dite $c (fun $h:ident => $t) (fun $h:ident => $e)) syntax (name := termIfThenElse) ppGroup(ppDedent("if " term " then" ppSpace term ppDedent(ppSpace "else") ppSpace term)) : term macro_rules | `(if $c then $t:term else $e:term) => ``(ite $c $t $e) macro "if " "let " pat:term " := " d:term " then " t:term " else " e:term : term => `(match $d:term with | $pat:term => $t | _ => $e) syntax:min term "<|" term:min : term macro_rules | `($f $args* <| $a) => let args := args.push a; `($f $args*) | `($f <| $a) => `($f $a) syntax:min term "|>" term:min1 : term macro_rules | `($a |> $f $args*) => let args := args.push a; `($f $args*) | `($a |> $f) => `($f $a) -- Haskell-like pipe <| -- Note that we have a whitespace after `$` to avoid an ambiguity with the antiquotations. syntax:min term atomic("$" ws) term:min : term macro_rules | `($f $args* $ $a) => let args := args.push a; `($f $args*) | `($f $ $a) => `($f $a) syntax "{ " ident (" : " term)? " // " term " }" : term macro_rules | `({ $x : $type // $p }) => ``(Subtype (fun ($x:ident : $type) => $p)) | `({ $x // $p }) => ``(Subtype (fun ($x:ident : _) => $p)) /- `without_expected_type t` instructs Lean to elaborate `t` without an expected type. Recall that terms such as `match ... with ...` and `⟨...⟩` will postpone elaboration until expected type is known. So, `without_expected_type` is not effective in this case. -/ macro "without_expected_type " x:term : term => `(let aux := $x; aux) syntax "[" term,* "]" : term syntax "%[" term,* "|" term "]" : term -- auxiliary notation for creating big list literals namespace Lean macro_rules | `([ $elems,* ]) => do let rec expandListLit (i : Nat) (skip : Bool) (result : Syntax) : MacroM Syntax := do match i, skip with | 0, _ => pure result | i+1, true => expandListLit i false result | i+1, false => expandListLit i true (← ``(List.cons $(elems.elemsAndSeps[i]) $result)) if elems.elemsAndSeps.size < 64 then expandListLit elems.elemsAndSeps.size false (← ``(List.nil)) else `(%[ $elems,* | List.nil ]) notation:50 e:51 " matches " p:51 => match e with | p => true | _ => false namespace Parser.Tactic syntax (name := intro) "intro " notFollowedBy("|") (colGt term:max)* : tactic syntax (name := intros) "intros " (colGt (ident <|> "_"))* : tactic syntax (name := rename) "rename " term " => " ident : tactic syntax (name := revert) "revert " (colGt ident)+ : tactic syntax (name := clear) "clear " (colGt ident)+ : tactic syntax (name := subst) "subst " (colGt ident)+ : tactic syntax (name := assumption) "assumption" : tactic syntax (name := contradiction) "contradiction" : tactic syntax (name := apply) "apply " term : tactic syntax (name := exact) "exact " term : tactic syntax (name := refine) "refine " term : tactic syntax (name := refine') "refine' " term : tactic syntax (name := constructor) "constructor" : tactic syntax (name := case) "case " ident (ident <|> "_")* " => " tacticSeq : tactic syntax (name := allGoals) "allGoals " tacticSeq : tactic syntax (name := focus) "focus " tacticSeq : tactic syntax (name := skip) "skip" : tactic syntax (name := done) "done" : tactic syntax (name := traceState) "traceState" : tactic syntax (name := failIfSuccess) "failIfSuccess " tacticSeq : tactic syntax (name := generalize) "generalize " atomic(ident " : ")? term:51 " = " ident : tactic syntax (name := paren) "(" tacticSeq ")" : tactic syntax (name := withReducible) "withReducible " tacticSeq : tactic syntax (name := withReducibleAndInstances) "withReducibleAndInstances " tacticSeq : tactic syntax (name := first) "first " withPosition((group(colGe "|" tacticSeq))+) : tactic syntax (name := rotateLeft) "rotateLeft" (num)? : tactic syntax (name := rotateRight) "rotateRight" (num)? : tactic macro "try " t:tacticSeq : tactic => `(first | $t | skip) macro:1 x:tactic " <;> " y:tactic:0 : tactic => `(tactic| focus ($x:tactic; allGoals $y:tactic)) syntax ("·" <|> ".") tacticSeq : tactic macro_rules | `(tactic| ·%$dot $ts:tacticSeq) => `(tactic| {%$dot ($ts:tacticSeq) }) macro "rfl" : tactic => `(exact rfl) macro "admit" : tactic => `(exact sorry) macro "inferInstance" : tactic => `(exact inferInstance) syntax locationWildcard := "*" syntax locationHyp := (colGt ident)+ ("⊢" <|> "|-")? -- TODO: delete syntax locationTargets := (colGt ident)+ ("⊢" <|> "|-")? syntax location := withPosition("at " locationWildcard <|> locationHyp) syntax (name := change) "change " term (location)? : tactic syntax (name := changeWith) "change " term " with " term (location)? : tactic syntax rwRule := ("←" <|> "<-")? term syntax rwRuleSeq := "[" rwRule,+,? "]" syntax (name := rewriteSeq) "rewrite " rwRuleSeq (location)? : tactic syntax (name := erewriteSeq) "erewrite " rwRuleSeq (location)? : tactic syntax (name := rwSeq) "rw " rwRuleSeq (location)? : tactic syntax (name := erwSeq) "erw " rwRuleSeq (location)? : tactic def rwWithRfl (kind : SyntaxNodeKind) (atom : String) (stx : Syntax) : MacroM Syntax := do -- We show the `rfl` state on `]` let seq := stx[1] let rbrak := seq[2] -- Replace `]` token with one without position information in the expanded tactic let seq := seq.setArg 2 (mkAtom "]") let tac := stx.setKind kind |>.setArg 0 (mkAtomFrom stx atom) |>.setArg 1 seq `(tactic| $tac; try (withReducible rfl%$rbrak)) @[macro rwSeq] def expandRwSeq : Macro := rwWithRfl ``Lean.Parser.Tactic.rewriteSeq "rewrite" @[macro erwSeq] def expandERwSeq : Macro := rwWithRfl ``Lean.Parser.Tactic.erewriteSeq "erewrite" syntax (name := injection) "injection " term (" with " (colGt (ident <|> "_"))+)? : tactic syntax simpPre := "↓" syntax simpPost := "↑" syntax simpLemma := (simpPre <|> simpPost)? term syntax simpErase := "-" ident syntax (name := simp) "simp " ("(" &"config" " := " term ")")? (&"only ")? ("[" (simpErase <|> simpLemma),* "]")? (location)? : tactic syntax (name := simpAll) "simp_all " ("(" &"config" " := " term ")")? (&"only ")? ("[" (simpErase <|> simpLemma),* "]")? : tactic -- Auxiliary macro for lifting have/suffices/let/... -- It makes sure the "continuation" `?_` is the main goal after refining macro "refineLift " e:term : tactic => `(focus (refine noImplicitLambda% $e; rotateRight)) macro "have " d:haveDecl : tactic => `(refineLift have $d:haveDecl; ?_) /- We use a priority > default, to avoid ambiguity with previous `have` notation -/ macro (priority := high) "have" x:ident " := " p:term : tactic => `(have $x:ident : _ := $p) macro "suffices " d:sufficesDecl : tactic => `(refineLift suffices $d:sufficesDecl; ?_) macro "let " d:letDecl : tactic => `(refineLift let $d:letDecl; ?_) macro "show " e:term : tactic => `(refineLift show $e:term from ?_) syntax (name := letrec) withPosition(atomic(group("let " &"rec ")) letRecDecls) : tactic macro_rules | `(tactic| let rec $d:letRecDecls) => `(tactic| refineLift let rec $d:letRecDecls; ?_) -- Similar to `refineLift`, but using `refine'` macro "refineLift' " e:term : tactic => `(focus (refine' noImplicitLambda% $e; rotateRight)) macro "have' " d:haveDecl : tactic => `(refineLift' have $d:haveDecl; ?_) macro (priority := high) "have'" x:ident " := " p:term : tactic => `(have' $x:ident : _ := $p) macro "let' " d:letDecl : tactic => `(refineLift' let $d:letDecl; ?_) syntax inductionAlt := "| " (group("@"? ident) <|> "_") (ident <|> "_")* " => " (hole <|> syntheticHole <|> tacticSeq) syntax inductionAlts := "with " (tactic)? withPosition( (colGe inductionAlt)+) syntax (name := induction) "induction " term,+ (" using " ident)? ("generalizing " ident+)? (inductionAlts)? : tactic syntax casesTarget := atomic(ident " : ")? term syntax (name := cases) "cases " casesTarget,+ (" using " ident)? (inductionAlts)? : tactic syntax (name := existsIntro) "exists " term : tactic syntax "repeat " tacticSeq : tactic macro_rules | `(tactic| repeat $seq) => `(tactic| first | ($seq); repeat $seq | skip) syntax "trivial" : tactic macro_rules | `(tactic| trivial) => `(tactic| assumption) macro_rules | `(tactic| trivial) => `(tactic| rfl) macro_rules | `(tactic| trivial) => `(tactic| contradiction) macro_rules | `(tactic| trivial) => `(tactic| apply True.intro) macro_rules | `(tactic| trivial) => `(tactic| apply And.intro <;> trivial) macro "unhygienic " t:tacticSeq : tactic => `(set_option tactic.hygienic false in $t:tacticSeq) end Tactic namespace Attr -- simp attribute syntax syntax (name := simp) "simp" (Tactic.simpPre <|> Tactic.simpPost)? (prio)? : attr end Attr end Parser end Lean macro "‹" type:term "›" : term => `((by assumption : $type))
fdf84e1573dd1e35c6a630f55a042b8feccb41a8
957a80ea22c5abb4f4670b250d55534d9db99108
/tests/lean/run/smt_array.lean
03aca38f6a45321c176ab8dabfd99c6dfe664dc8
[ "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
481
lean
namespace hide constant array : Type constant read : array → nat → nat constant write : array → nat → nat → array axiom rw1 : ∀ a i v, read (: write a i v :) i = v axiom rw2 : ∀ a i j v, i = j ∨ (: read (write a i v) j :) = read a j attribute [ematch] rw1 rw2 lemma ex3 (a1 a2 a3 a4 a5 : array) (v : nat) : a2 = write a1 0 v → a3 = write a2 1 v → a4 = write a3 2 v → a5 = write a4 3 v → read a5 4 = read a1 4 := begin [smt] intros, eblast end end hide
dc89931020f34c96eec95c983e15d8e94e81099f
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/src/Lean/Elab/ComputedFields.lean
2019d83ee1b388a650309ccb091d93d1918c365c
[ "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
9,623
lean
/- Copyright (c) 2022 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Gabriel Ebner -/ import Lean.Meta.Constructions import Lean.Compiler.ImplementedByAttr import Lean.Elab.PreDefinition.WF.Eqns /-! # Computed fields Inductives can have computed fields which are recursive functions whose value is stored in the constructors, and can be accessed in constant time. ```lean inductive Exp | hole | app (x y : Exp) with f : Exp → Nat | .hole => 42 | .app x y => f x + f y -- `Exp.f x` runs in constant time, even if `x` is a dag-like value ``` This file implements the computed fields feature by simulating it via `implemented_by`. The main function is `setComputedFields`. -/ namespace Lean.Elab.ComputedFields open Meta builtin_initialize computedFieldAttr : TagAttribute ← registerTagAttribute `computed_field "Marks a function as a computed field of an inductive" fun _ => do unless (← getOptions).getBool `elaboratingComputedFields do throwError "The @[computed_field] attribute can only be used in the with-block of an inductive" def mkUnsafeCastTo (expectedType : Expr) (e : Expr) : MetaM Expr := mkAppOptM ``unsafeCast #[none, expectedType, e] def isScalarField (ctor : Name) : CoreM Bool := return (← getConstInfoCtor ctor).numFields == 0 -- TODO structure Context extends InductiveVal where lparams : List Level params : Array Expr compFields : Array Name compFieldVars : Array Expr indices : Array Expr val : Expr abbrev M := ReaderT Context MetaM -- TODO: doesn't work if match contains patterns like `.app (.app a b) c` def getComputedFieldValue (computedField : Name) (ctorTerm : Expr) : MetaM Expr := do let ctorName := ctorTerm.getAppFn.constName! let ind ← getConstInfoInduct (← getConstInfoCtor ctorName).induct let val ← mkAppOptM computedField (mkArray (ind.numParams+ind.numIndices) none ++ #[some ctorTerm]) let val ← if let some wfEqn := WF.eqnInfoExt.find? (← getEnv) computedField then pure <| mkAppN (wfEqn.value.instantiateLevelParams wfEqn.levelParams val.getAppFn.constLevels!) val.getAppArgs else unfoldDefinition val let val ← whnfHeadPred val (return ctorTerm.occurs ·) if !ctorTerm.occurs val then return val throwError "computed field {computedField} does not reduce for constructor {ctorName}" def validateComputedFields : M Unit := do let {compFieldVars, indices, val ..} ← read for cf in compFieldVars do let ty ← inferType cf if ty.containsFVar val.fvarId! then throwError "computed field {cf}'s type must not depend on value{indentExpr ty}" if indices.any (ty.containsFVar ·.fvarId!) then throwError "computed field {cf}'s type must not depend on indices{indentExpr ty}" def mkImplType : M Unit := do let {name, isUnsafe, type, ctors, levelParams, numParams, lparams, params, compFieldVars, ..} ← read addDecl <| .inductDecl levelParams numParams (isUnsafe := isUnsafe) -- Note: inlining is disabled with unsafe inductives [{ name := name ++ `_impl, type, ctors := ← ctors.mapM fun ctor => do forallTelescope (← inferType (mkAppN (mkConst ctor lparams) params)) fun fields retTy => do let retTy := mkAppN (mkConst (name ++ `_impl) lparams) retTy.getAppArgs let type ← mkForallFVars (params ++ (if ← isScalarField ctor then #[] else compFieldVars) ++ fields) retTy return { name := ctor ++ `_impl, type } }] def overrideCasesOn : M Unit := do let {name, numIndices, ctors, lparams, params, compFieldVars, ..} ← read let casesOn ← getConstInfoDefn (mkCasesOnName name) mkCasesOn (name ++ `_impl) let value ← forallTelescope (← instantiateForall casesOn.type params) fun xs constMotive => do let (indices, major, minors) := (xs[1:numIndices+1].toArray, xs[numIndices+1]!, xs[numIndices+2:].toArray) let majorImplTy := mkAppN (mkConst (name ++ `_impl) lparams) (params ++ indices) mkLambdaFVars (params ++ xs) <| mkAppN (mkConst (mkCasesOnName (name ++ `_impl)) (casesOn.levelParams.map mkLevelParam)) <| params ++ #[← withLocalDeclD `a majorImplTy fun majorImpl => do withLetDecl `m (← inferType constMotive) constMotive fun m => do mkLambdaFVars (#[m] ++ indices ++ #[majorImpl]) m] ++ indices ++ #[← mkUnsafeCastTo majorImplTy major] ++ (← (minors.zip ctors.toArray).mapM fun (minor, ctor) => do forallTelescope (← inferType minor) fun args _ => do mkLambdaFVars ((if ← isScalarField ctor then #[] else compFieldVars) ++ args) (← mkUnsafeCastTo constMotive (mkAppN minor args))) let nameOverride := mkCasesOnName name ++ `_override addDecl <| .defnDecl { casesOn with name := nameOverride all := [nameOverride] value hints := .opaque safety := .unsafe } setInlineAttribute (mkCasesOnName name ++ `_override) setImplementedBy (mkCasesOnName name) (mkCasesOnName name ++ `_override) def overrideConstructors : M Unit := do let {ctors, levelParams, lparams, params, compFields, ..} ← read for ctor in ctors do forallTelescope (← inferType (mkAppN (mkConst ctor lparams) params)) fun fields retTy => do let ctorTerm := mkAppN (mkConst ctor lparams) (params ++ fields) let computedFieldVals ← if ← isScalarField ctor then pure #[] else compFields.mapM (getComputedFieldValue · ctorTerm) addDecl <| .defnDecl { name := ctor ++ `_override levelParams type := ← inferType (mkConst ctor lparams) value := ← mkLambdaFVars (params ++ fields) <| ← mkUnsafeCastTo retTy <| mkAppN (mkConst (ctor ++ `_impl) lparams) (params ++ computedFieldVals ++ fields) hints := .opaque safety := .unsafe } setImplementedBy ctor (ctor ++ `_override) if ← isScalarField ctor then setInlineAttribute (ctor ++ `_override) def overrideComputedFields : M Unit := do let {name, levelParams, ctors, compFields, compFieldVars, lparams, params, indices, val ..} ← read withLocalDeclD `x (mkAppN (mkConst (name ++ `_impl) lparams) (params ++ indices)) fun xImpl => do for cfn in compFields, cf in compFieldVars do if isExtern (← getEnv) cfn then compileDecls [cfn] continue let cases ← ctors.toArray.mapM fun ctor => do forallTelescope (← inferType (mkAppN (mkConst ctor lparams) params)) fun fields _ => do if ← isScalarField ctor then mkLambdaFVars fields <| ← getComputedFieldValue cfn (mkAppN (mkConst ctor lparams) (params ++ fields)) else mkLambdaFVars (compFieldVars ++ fields) cf addDecl <| .defnDecl { name := cfn ++ `_override levelParams type := ← mkForallFVars (params ++ indices ++ #[val]) (← inferType cf) value := ← mkLambdaFVars (params ++ indices ++ #[val]) <| ← mkAppOptM (mkCasesOnName (name ++ `_impl)) ((params ++ #[← mkLambdaFVars (indices.push xImpl) (← inferType cf)] ++ indices ++ #[← mkUnsafeCastTo (← inferType xImpl) val] ++ cases).map some) safety := .unsafe hints := .opaque } setImplementedBy cfn (cfn ++ `_override) def mkComputedFieldOverrides (declName : Name) (compFields : Array Name) : MetaM Unit := do let ind ← getConstInfoInduct declName if ind.ctors.length < 2 then throwError "computed fields require at least two constructors" let lparams := ind.levelParams.map mkLevelParam forallTelescope ind.type fun paramsIndices _ => do withLocalDeclD `x (mkAppN (mkConst ind.name lparams) paramsIndices) fun val => do let params := paramsIndices[:ind.numParams].toArray let indices := paramsIndices[ind.numParams:].toArray let compFieldVars := compFields.map fun fieldDeclName => (fieldDeclName.updatePrefix .anonymous, fun _ => do inferType (← mkAppM fieldDeclName (params ++ indices ++ #[val]))) withLocalDeclsD compFieldVars fun compFieldVars => do let ctx := { ind with lparams, params, compFields, compFieldVars, indices, val } ReaderT.run (r := ctx) do validateComputedFields mkImplType overrideCasesOn overrideConstructors overrideComputedFields /-- Sets the computed fields for a block of mutual inductives, adding the implementation via `implemented_by`. The `computedFields` argument contains a pair for every inductive in the mutual block, consisting of the name of the inductive and the names of the associated computed fields. -/ def setComputedFields (computedFields : Array (Name × Array Name)) : MetaM Unit := do for (indName, computedFieldNames) in computedFields do for computedFieldName in computedFieldNames do unless computedFieldAttr.hasTag (← getEnv) computedFieldName do logError m!"'{computedFieldName}' must be tagged with @[computed_field]" mkComputedFieldOverrides indName computedFieldNames -- Once all the implemented_by infrastructure is set up, compile everything. compileDecls <| computedFields.toList.map fun (indName, _) => mkCasesOnName indName ++ `_override let mut toCompile := #[] for (declName, computedFields) in computedFields do let ind ← getConstInfoInduct declName for ctor in ind.ctors do toCompile := toCompile.push (ctor ++ `_override) for fieldName in computedFields do unless isExtern (← getEnv) fieldName do toCompile := toCompile.push <| fieldName ++ `_override compileDecls toCompile.toList
ef8f7c6029807bb0f5f5977938fa7ae19c5a1ee5
022547453607c6244552158ff25ab3bf17361760
/src/analysis/mean_inequalities.lean
4b4854e78f5ce27a7874bcff3d59d2f8ca8dd45a
[ "Apache-2.0" ]
permissive
1293045656/mathlib
5f81741a7c1ff1873440ec680b3680bfb6b7b048
4709e61525a60189733e72a50e564c58d534bed8
refs/heads/master
1,687,010,200,553
1,626,245,646,000
1,626,245,646,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
33,242
lean
/- Copyright (c) 2019 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudryashov, Sébastien Gouëzel, Rémy Degenne -/ import analysis.convex.specific_functions import analysis.special_functions.pow import data.real.conjugate_exponents import tactic.nth_rewrite /-! # Mean value inequalities In this file we prove several inequalities for finite sums, including AM-GM inequality, Young's inequality, Hölder inequality, and Minkowski inequality. Versions for integrals of some of these inequalities are available in `measure_theory.mean_inequalities`. ## Main theorems ### AM-GM inequality: The inequality says that the geometric mean of a tuple of non-negative numbers is less than or equal to their arithmetic mean. We prove the weighted version of this inequality: if $w$ and $z$ are two non-negative vectors and $\sum_{i\in s} w_i=1$, then $$ \prod_{i\in s} z_i^{w_i} ≤ \sum_{i\in s} w_iz_i. $$ The classical version is a special case of this inequality for $w_i=\frac{1}{n}$. We prove a few versions of this inequality. Each of the following lemmas comes in two versions: a version for real-valued non-negative functions is in the `real` namespace, and a version for `nnreal`-valued functions is in the `nnreal` namespace. - `geom_mean_le_arith_mean_weighted` : weighted version for functions on `finset`s; - `geom_mean_le_arith_mean2_weighted` : weighted version for two numbers; - `geom_mean_le_arith_mean3_weighted` : weighted version for three numbers; - `geom_mean_le_arith_mean4_weighted` : weighted version for four numbers. ### Generalized mean inequality The inequality says that for two non-negative vectors $w$ and $z$ with $\sum_{i\in s} w_i=1$ and $p ≤ q$ we have $$ \sqrt[p]{\sum_{i\in s} w_i z_i^p} ≤ \sqrt[q]{\sum_{i\in s} w_i z_i^q}. $$ Currently we only prove this inequality for $p=1$. As in the rest of `mathlib`, we provide different theorems for natural exponents (`pow_arith_mean_le_arith_mean_pow`), integer exponents (`fpow_arith_mean_le_arith_mean_fpow`), and real exponents (`rpow_arith_mean_le_arith_mean_rpow` and `arith_mean_le_rpow_mean`). In the first two cases we prove $$ \left(\sum_{i\in s} w_i z_i\right)^n ≤ \sum_{i\in s} w_i z_i^n $$ in order to avoid using real exponents. For real exponents we prove both this and standard versions. ### Young's inequality Young's inequality says that for non-negative numbers `a`, `b`, `p`, `q` such that $\frac{1}{p}+\frac{1}{q}=1$ we have $$ ab ≤ \frac{a^p}{p} + \frac{b^q}{q}. $$ This inequality is a special case of the AM-GM inequality. It can be used to prove Hölder's inequality (see below) but we use a different proof. ### Hölder's inequality The inequality says that for two conjugate exponents `p` and `q` (i.e., for two positive numbers such that $\frac{1}{p}+\frac{1}{q}=1$) and any two non-negative vectors their inner product is less than or equal to the product of the $L_p$ norm of the first vector and the $L_q$ norm of the second vector: $$ \sum_{i\in s} a_ib_i ≤ \sqrt[p]{\sum_{i\in s} a_i^p}\sqrt[q]{\sum_{i\in s} b_i^q}. $$ We give versions of this result in `ℝ`, `ℝ≥0` and `ℝ≥0∞`. There are at least two short proofs of this inequality. In one proof we prenormalize both vectors, then apply Young's inequality to each $a_ib_i$. We use a different proof deducing this inequality from the generalized mean inequality for well-chosen vectors and weights. ### Minkowski's inequality The inequality says that for `p ≥ 1` the function $$ \|a\|_p=\sqrt[p]{\sum_{i\in s} a_i^p} $$ satisfies the triangle inequality $\|a+b\|_p\le \|a\|_p+\|b\|_p$. We give versions of this result in `real`, `ℝ≥0` and `ℝ≥0∞`. We deduce this inequality from Hölder's inequality. Namely, Hölder inequality implies that $\|a\|_p$ is the maximum of the inner product $\sum_{i\in s}a_ib_i$ over `b` such that $\|b\|_q\le 1$. Now Minkowski's inequality follows from the fact that the maximum value of the sum of two functions is less than or equal to the sum of the maximum values of the summands. ## TODO - each inequality `A ≤ B` should come with a theorem `A = B ↔ _`; one of the ways to prove them is to define `strict_convex_on` functions. - generalized mean inequality with any `p ≤ q`, including negative numbers; - prove that the power mean tends to the geometric mean as the exponent tends to zero. -/ universes u v open finset open_locale classical big_operators nnreal ennreal noncomputable theory variables {ι : Type u} (s : finset ι) namespace real /-- AM-GM inequality: the **geometric mean is less than or equal to the arithmetic mean**, weighted version for real-valued nonnegative functions. -/ theorem geom_mean_le_arith_mean_weighted (w z : ι → ℝ) (hw : ∀ i ∈ s, 0 ≤ w i) (hw' : ∑ i in s, w i = 1) (hz : ∀ i ∈ s, 0 ≤ z i) : (∏ i in s, (z i) ^ (w i)) ≤ ∑ i in s, w i * z i := begin -- If some number `z i` equals zero and has non-zero weight, then LHS is 0 and RHS is nonnegative. by_cases A : ∃ i ∈ s, z i = 0 ∧ w i ≠ 0, { rcases A with ⟨i, his, hzi, hwi⟩, rw [prod_eq_zero his], { exact sum_nonneg (λ j hj, mul_nonneg (hw j hj) (hz j hj)) }, { rw hzi, exact zero_rpow hwi } }, -- If all numbers `z i` with non-zero weight are positive, then we apply Jensen's inequality -- for `exp` and numbers `log (z i)` with weights `w i`. { simp only [not_exists, not_and, ne.def, not_not] at A, have := convex_on_exp.map_sum_le hw hw' (λ i _, set.mem_univ $ log (z i)), simp only [exp_sum, (∘), smul_eq_mul, mul_comm (w _) (log _)] at this, convert this using 1; [apply prod_congr rfl, apply sum_congr rfl]; intros i hi, { cases eq_or_lt_of_le (hz i hi) with hz hz, { simp [A i hi hz.symm] }, { exact rpow_def_of_pos hz _ } }, { cases eq_or_lt_of_le (hz i hi) with hz hz, { simp [A i hi hz.symm] }, { rw [exp_log hz] } } } end theorem pow_arith_mean_le_arith_mean_pow (w z : ι → ℝ) (hw : ∀ i ∈ s, 0 ≤ w i) (hw' : ∑ i in s, w i = 1) (hz : ∀ i ∈ s, 0 ≤ z i) (n : ℕ) : (∑ i in s, w i * z i) ^ n ≤ ∑ i in s, (w i * z i ^ n) := (convex_on_pow n).map_sum_le hw hw' hz theorem pow_arith_mean_le_arith_mean_pow_of_even (w z : ι → ℝ) (hw : ∀ i ∈ s, 0 ≤ w i) (hw' : ∑ i in s, w i = 1) {n : ℕ} (hn : even n) : (∑ i in s, w i * z i) ^ n ≤ ∑ i in s, (w i * z i ^ n) := (convex_on_pow_of_even hn).map_sum_le hw hw' (λ _ _, trivial) theorem fpow_arith_mean_le_arith_mean_fpow (w z : ι → ℝ) (hw : ∀ i ∈ s, 0 ≤ w i) (hw' : ∑ i in s, w i = 1) (hz : ∀ i ∈ s, 0 < z i) (m : ℤ) : (∑ i in s, w i * z i) ^ m ≤ ∑ i in s, (w i * z i ^ m) := (convex_on_fpow m).map_sum_le hw hw' hz theorem rpow_arith_mean_le_arith_mean_rpow (w z : ι → ℝ) (hw : ∀ i ∈ s, 0 ≤ w i) (hw' : ∑ i in s, w i = 1) (hz : ∀ i ∈ s, 0 ≤ z i) {p : ℝ} (hp : 1 ≤ p) : (∑ i in s, w i * z i) ^ p ≤ ∑ i in s, (w i * z i ^ p) := (convex_on_rpow hp).map_sum_le hw hw' hz theorem arith_mean_le_rpow_mean (w z : ι → ℝ) (hw : ∀ i ∈ s, 0 ≤ w i) (hw' : ∑ i in s, w i = 1) (hz : ∀ i ∈ s, 0 ≤ z i) {p : ℝ} (hp : 1 ≤ p) : ∑ i in s, w i * z i ≤ (∑ i in s, (w i * z i ^ p)) ^ (1 / p) := begin have : 0 < p := lt_of_lt_of_le zero_lt_one hp, rw [← rpow_le_rpow_iff _ _ this, ← rpow_mul, one_div_mul_cancel (ne_of_gt this), rpow_one], exact rpow_arith_mean_le_arith_mean_rpow s w z hw hw' hz hp, all_goals { apply_rules [sum_nonneg, rpow_nonneg_of_nonneg], intros i hi, apply_rules [mul_nonneg, rpow_nonneg_of_nonneg, hw i hi, hz i hi] }, end end real namespace nnreal /-- The geometric mean is less than or equal to the arithmetic mean, weighted version for `nnreal`-valued functions. -/ theorem geom_mean_le_arith_mean_weighted (w z : ι → ℝ≥0) (hw' : ∑ i in s, w i = 1) : (∏ i in s, (z i) ^ (w i:ℝ)) ≤ ∑ i in s, w i * z i := by exact_mod_cast real.geom_mean_le_arith_mean_weighted _ _ _ (λ i _, (w i).coe_nonneg) (by assumption_mod_cast) (λ i _, (z i).coe_nonneg) /-- The geometric mean is less than or equal to the arithmetic mean, weighted version for two `nnreal` numbers. -/ theorem geom_mean_le_arith_mean2_weighted (w₁ w₂ p₁ p₂ : ℝ≥0) : w₁ + w₂ = 1 → p₁ ^ (w₁:ℝ) * p₂ ^ (w₂:ℝ) ≤ w₁ * p₁ + w₂ * p₂ := by simpa only [fin.prod_univ_succ, fin.sum_univ_succ, finset.prod_empty, finset.sum_empty, fintype.univ_of_is_empty, fin.cons_succ, fin.cons_zero, add_zero, mul_one] using geom_mean_le_arith_mean_weighted (univ : finset (fin 2)) (fin.cons w₁ $ fin.cons w₂ fin_zero_elim) (fin.cons p₁ $ fin.cons p₂ $ fin_zero_elim) theorem geom_mean_le_arith_mean3_weighted (w₁ w₂ w₃ p₁ p₂ p₃ : ℝ≥0) : w₁ + w₂ + w₃ = 1 → p₁ ^ (w₁:ℝ) * p₂ ^ (w₂:ℝ) * p₃ ^ (w₃:ℝ) ≤ w₁ * p₁ + w₂ * p₂ + w₃ * p₃ := by simpa only [fin.prod_univ_succ, fin.sum_univ_succ, finset.prod_empty, finset.sum_empty, fintype.univ_of_is_empty, fin.cons_succ, fin.cons_zero, add_zero, mul_one, ← add_assoc, mul_assoc] using geom_mean_le_arith_mean_weighted (univ : finset (fin 3)) (fin.cons w₁ $ fin.cons w₂ $ fin.cons w₃ fin_zero_elim) (fin.cons p₁ $ fin.cons p₂ $ fin.cons p₃ fin_zero_elim) theorem geom_mean_le_arith_mean4_weighted (w₁ w₂ w₃ w₄ p₁ p₂ p₃ p₄ : ℝ≥0) : w₁ + w₂ + w₃ + w₄ = 1 → p₁ ^ (w₁:ℝ) * p₂ ^ (w₂:ℝ) * p₃ ^ (w₃:ℝ)* p₄ ^ (w₄:ℝ) ≤ w₁ * p₁ + w₂ * p₂ + w₃ * p₃ + w₄ * p₄ := by simpa only [fin.prod_univ_succ, fin.sum_univ_succ, finset.prod_empty, finset.sum_empty, fintype.univ_of_is_empty, fin.cons_succ, fin.cons_zero, add_zero, mul_one, ← add_assoc, mul_assoc] using geom_mean_le_arith_mean_weighted (univ : finset (fin 4)) (fin.cons w₁ $ fin.cons w₂ $ fin.cons w₃ $ fin.cons w₄ fin_zero_elim) (fin.cons p₁ $ fin.cons p₂ $ fin.cons p₃ $ fin.cons p₄ fin_zero_elim) /-- Weighted generalized mean inequality, version sums over finite sets, with `ℝ≥0`-valued functions and natural exponent. -/ theorem pow_arith_mean_le_arith_mean_pow (w z : ι → ℝ≥0) (hw' : ∑ i in s, w i = 1) (n : ℕ) : (∑ i in s, w i * z i) ^ n ≤ ∑ i in s, (w i * z i ^ n) := by exact_mod_cast real.pow_arith_mean_le_arith_mean_pow s _ _ (λ i _, (w i).coe_nonneg) (by exact_mod_cast hw') (λ i _, (z i).coe_nonneg) n /-- Weighted generalized mean inequality, version for sums over finite sets, with `ℝ≥0`-valued functions and real exponents. -/ theorem rpow_arith_mean_le_arith_mean_rpow (w z : ι → ℝ≥0) (hw' : ∑ i in s, w i = 1) {p : ℝ} (hp : 1 ≤ p) : (∑ i in s, w i * z i) ^ p ≤ ∑ i in s, (w i * z i ^ p) := by exact_mod_cast real.rpow_arith_mean_le_arith_mean_rpow s _ _ (λ i _, (w i).coe_nonneg) (by exact_mod_cast hw') (λ i _, (z i).coe_nonneg) hp /-- Weighted generalized mean inequality, version for two elements of `ℝ≥0` and real exponents. -/ theorem rpow_arith_mean_le_arith_mean2_rpow (w₁ w₂ z₁ z₂ : ℝ≥0) (hw' : w₁ + w₂ = 1) {p : ℝ} (hp : 1 ≤ p) : (w₁ * z₁ + w₂ * z₂) ^ p ≤ w₁ * z₁ ^ p + w₂ * z₂ ^ p := begin have h := rpow_arith_mean_le_arith_mean_rpow (univ : finset (fin 2)) (fin.cons w₁ $ fin.cons w₂ fin_zero_elim) (fin.cons z₁ $ fin.cons z₂ $ fin_zero_elim) _ hp, { simpa [fin.sum_univ_succ, fin.sum_univ_zero, fin.cons_succ, fin.cons_zero] using h, }, { simp [hw', fin.sum_univ_succ, fin.sum_univ_zero, fin.cons_succ, fin.cons_zero], }, end /-- Weighted generalized mean inequality, version for sums over finite sets, with `ℝ≥0`-valued functions and real exponents. -/ theorem arith_mean_le_rpow_mean (w z : ι → ℝ≥0) (hw' : ∑ i in s, w i = 1) {p : ℝ} (hp : 1 ≤ p) : ∑ i in s, w i * z i ≤ (∑ i in s, (w i * z i ^ p)) ^ (1 / p) := by exact_mod_cast real.arith_mean_le_rpow_mean s _ _ (λ i _, (w i).coe_nonneg) (by exact_mod_cast hw') (λ i _, (z i).coe_nonneg) hp end nnreal namespace ennreal /-- Weighted generalized mean inequality, version for sums over finite sets, with `ℝ≥0∞`-valued functions and real exponents. -/ theorem rpow_arith_mean_le_arith_mean_rpow (w z : ι → ℝ≥0∞) (hw' : ∑ i in s, w i = 1) {p : ℝ} (hp : 1 ≤ p) : (∑ i in s, w i * z i) ^ p ≤ ∑ i in s, (w i * z i ^ p) := begin have hp_pos : 0 < p, from lt_of_lt_of_le zero_lt_one hp, have hp_nonneg : 0 ≤ p, from le_of_lt hp_pos, have hp_not_nonpos : ¬ p ≤ 0, by simp [hp_pos], have hp_not_neg : ¬ p < 0, by simp [hp_nonneg], have h_top_iff_rpow_top : ∀ (i : ι) (hi : i ∈ s), w i * z i = ⊤ ↔ w i * (z i) ^ p = ⊤, by simp [hp_pos, hp_nonneg, hp_not_nonpos, hp_not_neg], refine le_of_top_imp_top_of_to_nnreal_le _ _, { -- first, prove `(∑ i in s, w i * z i) ^ p = ⊤ → ∑ i in s, (w i * z i ^ p) = ⊤` rw [rpow_eq_top_iff, sum_eq_top_iff, sum_eq_top_iff], intro h, simp only [and_false, hp_not_neg, false_or] at h, rcases h.left with ⟨a, H, ha⟩, use [a, H], rwa ←h_top_iff_rpow_top a H, }, { -- second, suppose both `(∑ i in s, w i * z i) ^ p ≠ ⊤` and `∑ i in s, (w i * z i ^ p) ≠ ⊤`, -- and prove `((∑ i in s, w i * z i) ^ p).to_nnreal ≤ (∑ i in s, (w i * z i ^ p)).to_nnreal`, -- by using `nnreal.rpow_arith_mean_le_arith_mean_rpow`. intros h_top_rpow_sum _, -- show hypotheses needed to put the `.to_nnreal` inside the sums. have h_top : ∀ (a : ι), a ∈ s → w a * z a < ⊤, { have h_top_sum : ∑ (i : ι) in s, w i * z i < ⊤, { by_contra h, rw [lt_top_iff_ne_top, not_not] at h, rw [h, top_rpow_of_pos hp_pos] at h_top_rpow_sum, exact h_top_rpow_sum rfl, }, rwa sum_lt_top_iff at h_top_sum, }, have h_top_rpow : ∀ (a : ι), a ∈ s → w a * z a ^ p < ⊤, { intros i hi, specialize h_top i hi, rw lt_top_iff_ne_top at h_top ⊢, rwa [ne.def, ←h_top_iff_rpow_top i hi], }, -- put the `.to_nnreal` inside the sums. simp_rw [to_nnreal_sum h_top_rpow, ←to_nnreal_rpow, to_nnreal_sum h_top, to_nnreal_mul, ←to_nnreal_rpow], -- use corresponding nnreal result refine nnreal.rpow_arith_mean_le_arith_mean_rpow s (λ i, (w i).to_nnreal) (λ i, (z i).to_nnreal) _ hp, -- verify the hypothesis `∑ i in s, (w i).to_nnreal = 1`, using `∑ i in s, w i = 1` . have h_sum_nnreal : (∑ i in s, w i) = ↑(∑ i in s, (w i).to_nnreal), { have hw_top : ∑ i in s, w i < ⊤, by { rw hw', exact one_lt_top, }, rw ←to_nnreal_sum, { rw coe_to_nnreal, rwa ←lt_top_iff_ne_top, }, { rwa sum_lt_top_iff at hw_top, }, }, rwa [←coe_eq_coe, ←h_sum_nnreal], }, end /-- Weighted generalized mean inequality, version for two elements of `ℝ≥0∞` and real exponents. -/ theorem rpow_arith_mean_le_arith_mean2_rpow (w₁ w₂ z₁ z₂ : ℝ≥0∞) (hw' : w₁ + w₂ = 1) {p : ℝ} (hp : 1 ≤ p) : (w₁ * z₁ + w₂ * z₂) ^ p ≤ w₁ * z₁ ^ p + w₂ * z₂ ^ p := begin have h := rpow_arith_mean_le_arith_mean_rpow (univ : finset (fin 2)) (fin.cons w₁ $ fin.cons w₂ fin_zero_elim) (fin.cons z₁ $ fin.cons z₂ $ fin_zero_elim) _ hp, { simpa [fin.sum_univ_succ, fin.sum_univ_zero, fin.cons_succ, fin.cons_zero] using h, }, { simp [hw', fin.sum_univ_succ, fin.sum_univ_zero, fin.cons_succ, fin.cons_zero], }, end end ennreal namespace real theorem geom_mean_le_arith_mean2_weighted {w₁ w₂ p₁ p₂ : ℝ} (hw₁ : 0 ≤ w₁) (hw₂ : 0 ≤ w₂) (hp₁ : 0 ≤ p₁) (hp₂ : 0 ≤ p₂) (hw : w₁ + w₂ = 1) : p₁ ^ w₁ * p₂ ^ w₂ ≤ w₁ * p₁ + w₂ * p₂ := nnreal.geom_mean_le_arith_mean2_weighted ⟨w₁, hw₁⟩ ⟨w₂, hw₂⟩ ⟨p₁, hp₁⟩ ⟨p₂, hp₂⟩ $ nnreal.coe_eq.1 $ by assumption theorem geom_mean_le_arith_mean3_weighted {w₁ w₂ w₃ p₁ p₂ p₃ : ℝ} (hw₁ : 0 ≤ w₁) (hw₂ : 0 ≤ w₂) (hw₃ : 0 ≤ w₃) (hp₁ : 0 ≤ p₁) (hp₂ : 0 ≤ p₂) (hp₃ : 0 ≤ p₃) (hw : w₁ + w₂ + w₃ = 1) : p₁ ^ w₁ * p₂ ^ w₂ * p₃ ^ w₃ ≤ w₁ * p₁ + w₂ * p₂ + w₃ * p₃ := nnreal.geom_mean_le_arith_mean3_weighted ⟨w₁, hw₁⟩ ⟨w₂, hw₂⟩ ⟨w₃, hw₃⟩ ⟨p₁, hp₁⟩ ⟨p₂, hp₂⟩ ⟨p₃, hp₃⟩ $ nnreal.coe_eq.1 hw theorem geom_mean_le_arith_mean4_weighted {w₁ w₂ w₃ w₄ p₁ p₂ p₃ p₄ : ℝ} (hw₁ : 0 ≤ w₁) (hw₂ : 0 ≤ w₂) (hw₃ : 0 ≤ w₃) (hw₄ : 0 ≤ w₄) (hp₁ : 0 ≤ p₁) (hp₂ : 0 ≤ p₂) (hp₃ : 0 ≤ p₃) (hp₄ : 0 ≤ p₄) (hw : w₁ + w₂ + w₃ + w₄ = 1) : p₁ ^ w₁ * p₂ ^ w₂ * p₃ ^ w₃ * p₄ ^ w₄ ≤ w₁ * p₁ + w₂ * p₂ + w₃ * p₃ + w₄ * p₄ := nnreal.geom_mean_le_arith_mean4_weighted ⟨w₁, hw₁⟩ ⟨w₂, hw₂⟩ ⟨w₃, hw₃⟩ ⟨w₄, hw₄⟩ ⟨p₁, hp₁⟩ ⟨p₂, hp₂⟩ ⟨p₃, hp₃⟩ ⟨p₄, hp₄⟩ $ nnreal.coe_eq.1 $ by assumption /-- Young's inequality, a version for nonnegative real numbers. -/ theorem young_inequality_of_nonneg {a b p q : ℝ} (ha : 0 ≤ a) (hb : 0 ≤ b) (hpq : p.is_conjugate_exponent q) : a * b ≤ a^p / p + b^q / q := by simpa [← rpow_mul, ha, hb, hpq.ne_zero, hpq.symm.ne_zero, div_eq_inv_mul] using geom_mean_le_arith_mean2_weighted hpq.one_div_nonneg hpq.symm.one_div_nonneg (rpow_nonneg_of_nonneg ha p) (rpow_nonneg_of_nonneg hb q) hpq.inv_add_inv_conj /-- Young's inequality, a version for arbitrary real numbers. -/ theorem young_inequality (a b : ℝ) {p q : ℝ} (hpq : p.is_conjugate_exponent q) : a * b ≤ (abs a)^p / p + (abs b)^q / q := calc a * b ≤ abs (a * b) : le_abs_self (a * b) ... = abs a * abs b : abs_mul a b ... ≤ (abs a)^p / p + (abs b)^q / q : real.young_inequality_of_nonneg (abs_nonneg a) (abs_nonneg b) hpq end real namespace nnreal /-- Young's inequality, `ℝ≥0` version. We use `{p q : ℝ≥0}` in order to avoid constructing witnesses of `0 ≤ p` and `0 ≤ q` for the denominators. -/ theorem young_inequality (a b : ℝ≥0) {p q : ℝ≥0} (hp : 1 < p) (hpq : 1 / p + 1 / q = 1) : a * b ≤ a^(p:ℝ) / p + b^(q:ℝ) / q := real.young_inequality_of_nonneg a.coe_nonneg b.coe_nonneg ⟨hp, nnreal.coe_eq.2 hpq⟩ /-- Young's inequality, `ℝ≥0` version with real conjugate exponents. -/ theorem young_inequality_real (a b : ℝ≥0) {p q : ℝ} (hpq : p.is_conjugate_exponent q) : a * b ≤ a ^ p / real.to_nnreal p + b ^ q / real.to_nnreal q := begin nth_rewrite 0 ← real.coe_to_nnreal p hpq.nonneg, nth_rewrite 0 ← real.coe_to_nnreal q hpq.symm.nonneg, exact young_inequality a b hpq.one_lt_nnreal hpq.inv_add_inv_conj_nnreal, end /-- Hölder inequality: the scalar product of two functions is bounded by the product of their `L^p` and `L^q` norms when `p` and `q` are conjugate exponents. Version for sums over finite sets, with `ℝ≥0`-valued functions. -/ theorem inner_le_Lp_mul_Lq (f g : ι → ℝ≥0) {p q : ℝ} (hpq : p.is_conjugate_exponent q) : ∑ i in s, f i * g i ≤ (∑ i in s, (f i) ^ p) ^ (1 / p) * (∑ i in s, (g i) ^ q) ^ (1 / q) := begin -- Let `G=∥g∥_q` be the `L_q`-norm of `g`. set G := (∑ i in s, (g i) ^ q) ^ (1 / q), have hGq : G ^ q = ∑ i in s, (g i) ^ q, { rw [← rpow_mul, one_div_mul_cancel hpq.symm.ne_zero, rpow_one], }, -- First consider the trivial case `∥g∥_q=0` by_cases hG : G = 0, { rw [hG, sum_eq_zero, mul_zero], intros i hi, simp only [rpow_eq_zero_iff, sum_eq_zero_iff] at hG, simp [(hG.1 i hi).1] }, { -- Move power from right to left rw [← div_le_iff hG, sum_div], -- Now the inequality follows from the weighted generalized mean inequality -- with weights `w_i` and numbers `z_i` given by the following formulas. set w : ι → ℝ≥0 := λ i, (g i) ^ q / G ^ q, set z : ι → ℝ≥0 := λ i, f i * (G / g i) ^ (q / p), -- Show that the sum of weights equals one have A : ∑ i in s, w i = 1, { rw [← sum_div, hGq, div_self], simpa [rpow_eq_zero_iff, hpq.symm.ne_zero] using hG }, -- LHS of the goal equals LHS of the weighted generalized mean inequality calc (∑ i in s, f i * g i / G) = (∑ i in s, w i * z i) : begin refine sum_congr rfl (λ i hi, _), have : q - q / p = 1, by field_simp [hpq.ne_zero, hpq.symm.mul_eq_add], dsimp only [w, z], rw [← div_rpow, mul_left_comm, mul_div_assoc, ← @inv_div _ _ _ G, inv_rpow, ← div_eq_mul_inv, ← rpow_sub']; simp [this] end -- Apply the generalized mean inequality ... ≤ (∑ i in s, w i * (z i) ^ p) ^ (1 / p) : nnreal.arith_mean_le_rpow_mean s w z A (le_of_lt hpq.one_lt) -- Simplify the right hand side. Terms with `g i ≠ 0` are equal to `(f i) ^ p`, -- the others are zeros. ... ≤ (∑ i in s, (f i) ^ p) ^ (1 / p) : begin refine rpow_le_rpow (sum_le_sum (λ i hi, _)) hpq.one_div_nonneg, dsimp only [w, z], rw [mul_rpow, mul_left_comm, ← rpow_mul _ _ p, div_mul_cancel _ hpq.ne_zero, div_rpow, div_mul_div, mul_comm (G ^ q), mul_div_mul_right], { nth_rewrite 1 [← mul_one ((f i) ^ p)], exact canonically_ordered_semiring.mul_le_mul (le_refl _) (div_self_le _) }, { simpa [hpq.symm.ne_zero] using hG } end } end /-- The `L_p` seminorm of a vector `f` is the greatest value of the inner product `∑ i in s, f i * g i` over functions `g` of `L_q` seminorm less than or equal to one. -/ theorem is_greatest_Lp (f : ι → ℝ≥0) {p q : ℝ} (hpq : p.is_conjugate_exponent q) : is_greatest ((λ g : ι → ℝ≥0, ∑ i in s, f i * g i) '' {g | ∑ i in s, (g i)^q ≤ 1}) ((∑ i in s, (f i)^p) ^ (1 / p)) := begin split, { use λ i, ((f i) ^ p / f i / (∑ i in s, (f i) ^ p) ^ (1 / q)), by_cases hf : ∑ i in s, (f i)^p = 0, { simp [hf, hpq.ne_zero, hpq.symm.ne_zero] }, { have A : p + q - q ≠ 0, by simp [hpq.ne_zero], have B : ∀ y : ℝ≥0, y * y^p / y = y^p, { refine λ y, mul_div_cancel_left_of_imp (λ h, _), simpa [h, hpq.ne_zero] }, simp only [set.mem_set_of_eq, div_rpow, ← sum_div, ← rpow_mul, div_mul_cancel _ hpq.symm.ne_zero, rpow_one, div_le_iff hf, one_mul, hpq.mul_eq_add, ← rpow_sub' _ A, _root_.add_sub_cancel, le_refl, true_and, ← mul_div_assoc, B], rw [div_eq_iff, ← rpow_add hf, hpq.inv_add_inv_conj, rpow_one], simpa [hpq.symm.ne_zero] using hf } }, { rintros _ ⟨g, hg, rfl⟩, apply le_trans (inner_le_Lp_mul_Lq s f g hpq), simpa only [mul_one] using canonically_ordered_semiring.mul_le_mul (le_refl _) (nnreal.rpow_le_one hg (le_of_lt hpq.symm.one_div_pos)) } end /-- Minkowski inequality: the `L_p` seminorm of the sum of two vectors is less than or equal to the sum of the `L_p`-seminorms of the summands. A version for `nnreal`-valued functions. -/ theorem Lp_add_le (f g : ι → ℝ≥0) {p : ℝ} (hp : 1 ≤ p) : (∑ i in s, (f i + g i) ^ p) ^ (1 / p) ≤ (∑ i in s, (f i) ^ p) ^ (1 / p) + (∑ i in s, (g i) ^ p) ^ (1 / p) := begin -- The result is trivial when `p = 1`, so we can assume `1 < p`. rcases eq_or_lt_of_le hp with rfl|hp, { simp [finset.sum_add_distrib] }, have hpq := real.is_conjugate_exponent_conjugate_exponent hp, have := is_greatest_Lp s (f + g) hpq, simp only [pi.add_apply, add_mul, sum_add_distrib] at this, rcases this.1 with ⟨φ, hφ, H⟩, rw ← H, exact add_le_add ((is_greatest_Lp s f hpq).2 ⟨φ, hφ, rfl⟩) ((is_greatest_Lp s g hpq).2 ⟨φ, hφ, rfl⟩) end end nnreal namespace real variables (f g : ι → ℝ) {p q : ℝ} /-- Hölder inequality: the scalar product of two functions is bounded by the product of their `L^p` and `L^q` norms when `p` and `q` are conjugate exponents. Version for sums over finite sets, with real-valued functions. -/ theorem inner_le_Lp_mul_Lq (hpq : is_conjugate_exponent p q) : ∑ i in s, f i * g i ≤ (∑ i in s, (abs $ f i)^p) ^ (1 / p) * (∑ i in s, (abs $ g i)^q) ^ (1 / q) := begin have := nnreal.coe_le_coe.2 (nnreal.inner_le_Lp_mul_Lq s (λ i, ⟨_, abs_nonneg (f i)⟩) (λ i, ⟨_, abs_nonneg (g i)⟩) hpq), push_cast at this, refine le_trans (sum_le_sum $ λ i hi, _) this, simp only [← abs_mul, le_abs_self] end /-- Minkowski inequality: the `L_p` seminorm of the sum of two vectors is less than or equal to the sum of the `L_p`-seminorms of the summands. A version for `real`-valued functions. -/ theorem Lp_add_le (hp : 1 ≤ p) : (∑ i in s, (abs $ f i + g i) ^ p) ^ (1 / p) ≤ (∑ i in s, (abs $ f i) ^ p) ^ (1 / p) + (∑ i in s, (abs $ g i) ^ p) ^ (1 / p) := begin have := nnreal.coe_le_coe.2 (nnreal.Lp_add_le s (λ i, ⟨_, abs_nonneg (f i)⟩) (λ i, ⟨_, abs_nonneg (g i)⟩) hp), push_cast at this, refine le_trans (rpow_le_rpow _ (sum_le_sum $ λ i hi, _) _) this; simp [sum_nonneg, rpow_nonneg_of_nonneg, abs_nonneg, le_trans zero_le_one hp, abs_add, rpow_le_rpow] end variables {f g} /-- Hölder inequality: the scalar product of two functions is bounded by the product of their `L^p` and `L^q` norms when `p` and `q` are conjugate exponents. Version for sums over finite sets, with real-valued nonnegative functions. -/ theorem inner_le_Lp_mul_Lq_of_nonneg (hpq : is_conjugate_exponent p q) (hf : ∀ i ∈ s, 0 ≤ f i) (hg : ∀ i ∈ s, 0 ≤ g i) : ∑ i in s, f i * g i ≤ (∑ i in s, (f i)^p) ^ (1 / p) * (∑ i in s, (g i)^q) ^ (1 / q) := by convert inner_le_Lp_mul_Lq s f g hpq using 3; apply sum_congr rfl; intros i hi; simp only [abs_of_nonneg, hf i hi, hg i hi] /-- Minkowski inequality: the `L_p` seminorm of the sum of two vectors is less than or equal to the sum of the `L_p`-seminorms of the summands. A version for `real`-valued nonnegative functions. -/ theorem Lp_add_le_of_nonneg (hp : 1 ≤ p) (hf : ∀ i ∈ s, 0 ≤ f i) (hg : ∀ i ∈ s, 0 ≤ g i) : (∑ i in s, (f i + g i) ^ p) ^ (1 / p) ≤ (∑ i in s, (f i) ^ p) ^ (1 / p) + (∑ i in s, (g i) ^ p) ^ (1 / p) := by convert Lp_add_le s f g hp using 2 ; [skip, congr' 1, congr' 1]; apply sum_congr rfl; intros i hi; simp only [abs_of_nonneg, hf i hi, hg i hi, add_nonneg] end real namespace ennreal /-- Young's inequality, `ℝ≥0∞` version with real conjugate exponents. -/ theorem young_inequality (a b : ℝ≥0∞) {p q : ℝ} (hpq : p.is_conjugate_exponent q) : a * b ≤ a ^ p / ennreal.of_real p + b ^ q / ennreal.of_real q := begin by_cases h : a = ⊤ ∨ b = ⊤, { refine le_trans le_top (le_of_eq _), repeat { rw div_eq_mul_inv }, cases h; rw h; simp [h, hpq.pos, hpq.symm.pos], }, push_neg at h, -- if a ≠ ⊤ and b ≠ ⊤, use the nnreal version: nnreal.young_inequality_real rw [←coe_to_nnreal h.left, ←coe_to_nnreal h.right, ←coe_mul, coe_rpow_of_nonneg _ hpq.nonneg, coe_rpow_of_nonneg _ hpq.symm.nonneg, ennreal.of_real, ennreal.of_real, ←@coe_div (real.to_nnreal p) _ (by simp [hpq.pos]), ←@coe_div (real.to_nnreal q) _ (by simp [hpq.symm.pos]), ←coe_add, coe_le_coe], exact nnreal.young_inequality_real a.to_nnreal b.to_nnreal hpq, end variables (f g : ι → ℝ≥0∞) {p q : ℝ} /-- Hölder inequality: the scalar product of two functions is bounded by the product of their `L^p` and `L^q` norms when `p` and `q` are conjugate exponents. Version for sums over finite sets, with `ℝ≥0∞`-valued functions. -/ theorem inner_le_Lp_mul_Lq (hpq : p.is_conjugate_exponent q) : (∑ i in s, f i * g i) ≤ (∑ i in s, (f i)^p) ^ (1/p) * (∑ i in s, (g i)^q) ^ (1/q) := begin by_cases H : (∑ i in s, (f i)^p) ^ (1/p) = 0 ∨ (∑ i in s, (g i)^q) ^ (1/q) = 0, { replace H : (∀ i ∈ s, f i = 0) ∨ (∀ i ∈ s, g i = 0), by simpa [ennreal.rpow_eq_zero_iff, hpq.pos, hpq.symm.pos, asymm hpq.pos, asymm hpq.symm.pos, sum_eq_zero_iff_of_nonneg] using H, have : ∀ i ∈ s, f i * g i = 0 := λ i hi, by cases H; simp [H i hi], have : (∑ i in s, f i * g i) = (∑ i in s, 0) := sum_congr rfl this, simp [this] }, push_neg at H, by_cases H' : (∑ i in s, (f i)^p) ^ (1/p) = ⊤ ∨ (∑ i in s, (g i)^q) ^ (1/q) = ⊤, { cases H'; simp [H', -one_div, H] }, replace H' : (∀ i ∈ s, f i ≠ ⊤) ∧ (∀ i ∈ s, g i ≠ ⊤), by simpa [ennreal.rpow_eq_top_iff, asymm hpq.pos, asymm hpq.symm.pos, hpq.pos, hpq.symm.pos, ennreal.sum_eq_top_iff, not_or_distrib] using H', have := ennreal.coe_le_coe.2 (@nnreal.inner_le_Lp_mul_Lq _ s (λ i, ennreal.to_nnreal (f i)) (λ i, ennreal.to_nnreal (g i)) _ _ hpq), simp [← ennreal.coe_rpow_of_nonneg, le_of_lt (hpq.pos), le_of_lt (hpq.one_div_pos), le_of_lt (hpq.symm.pos), le_of_lt (hpq.symm.one_div_pos)] at this, convert this using 1; [skip, congr' 2]; [skip, skip, simp, skip, simp]; { apply finset.sum_congr rfl (λ i hi, _), simp [H'.1 i hi, H'.2 i hi, -with_zero.coe_mul, with_top.coe_mul.symm] }, end /-- Minkowski inequality: the `L_p` seminorm of the sum of two vectors is less than or equal to the sum of the `L_p`-seminorms of the summands. A version for `ℝ≥0∞` valued nonnegative functions. -/ theorem Lp_add_le (hp : 1 ≤ p) : (∑ i in s, (f i + g i) ^ p)^(1/p) ≤ (∑ i in s, (f i)^p) ^ (1/p) + (∑ i in s, (g i)^p) ^ (1/p) := begin by_cases H' : (∑ i in s, (f i)^p) ^ (1/p) = ⊤ ∨ (∑ i in s, (g i)^p) ^ (1/p) = ⊤, { cases H'; simp [H', -one_div] }, have pos : 0 < p := lt_of_lt_of_le zero_lt_one hp, replace H' : (∀ i ∈ s, f i ≠ ⊤) ∧ (∀ i ∈ s, g i ≠ ⊤), by simpa [ennreal.rpow_eq_top_iff, asymm pos, pos, ennreal.sum_eq_top_iff, not_or_distrib] using H', have := ennreal.coe_le_coe.2 (@nnreal.Lp_add_le _ s (λ i, ennreal.to_nnreal (f i)) (λ i, ennreal.to_nnreal (g i)) _ hp), push_cast [← ennreal.coe_rpow_of_nonneg, le_of_lt (pos), le_of_lt (one_div_pos.2 pos)] at this, convert this using 2; [skip, congr' 1, congr' 1]; { apply finset.sum_congr rfl (λ i hi, _), simp [H'.1 i hi, H'.2 i hi] } end private lemma add_rpow_le_one_of_add_le_one {p : ℝ} (a b : ℝ≥0∞) (hab : a + b ≤ 1) (hp1 : 1 ≤ p) : a ^ p + b ^ p ≤ 1 := begin have h_le_one : ∀ x : ℝ≥0∞, x ≤ 1 → x ^ p ≤ x, from λ x hx, rpow_le_self_of_le_one hx hp1, have ha : a ≤ 1, from (self_le_add_right a b).trans hab, have hb : b ≤ 1, from (self_le_add_left b a).trans hab, exact (add_le_add (h_le_one a ha) (h_le_one b hb)).trans hab, end lemma add_rpow_le_rpow_add {p : ℝ} (a b : ℝ≥0∞) (hp1 : 1 ≤ p) : a ^ p + b ^ p ≤ (a + b) ^ p := begin have hp_pos : 0 < p := lt_of_lt_of_le zero_lt_one hp1, by_cases h_top : a + b = ⊤, { rw ←@ennreal.rpow_eq_top_iff_of_pos (a + b) p hp_pos at h_top, rw h_top, exact le_top, }, obtain ⟨ha_top, hb_top⟩ := add_ne_top.mp h_top, by_cases h_zero : a + b = 0, { simp [add_eq_zero_iff.mp h_zero, ennreal.zero_rpow_of_pos hp_pos], }, have h_nonzero : ¬(a = 0 ∧ b = 0), by rwa add_eq_zero_iff at h_zero, have h_add : a/(a+b) + b/(a+b) = 1, by rw [div_add_div_same, div_self h_zero h_top], have h := add_rpow_le_one_of_add_le_one (a/(a+b)) (b/(a+b)) h_add.le hp1, rw [div_rpow_of_nonneg a (a+b) hp_pos.le, div_rpow_of_nonneg b (a+b) hp_pos.le] at h, have hab_0 : (a + b)^p ≠ 0, by simp [ha_top, hb_top, hp_pos, h_nonzero], have hab_top : (a + b)^p ≠ ⊤, by simp [ha_top, hb_top, hp_pos, h_nonzero], have h_mul : (a + b)^p * (a ^ p / (a + b) ^ p + b ^ p / (a + b) ^ p) ≤ (a + b)^p, { nth_rewrite 3 ←mul_one ((a + b)^p), exact (mul_le_mul_left hab_0 hab_top).mpr h, }, rwa [div_eq_mul_inv, div_eq_mul_inv, mul_add, mul_comm (a^p), mul_comm (b^p), ←mul_assoc, ←mul_assoc, mul_inv_cancel hab_0 hab_top, one_mul, one_mul] at h_mul, end lemma rpow_add_rpow_le_add {p : ℝ} (a b : ℝ≥0∞) (hp1 : 1 ≤ p) : (a ^ p + b ^ p) ^ (1/p) ≤ a + b := begin rw ←@ennreal.le_rpow_one_div_iff _ _ (1/p) (by simp [lt_of_lt_of_le zero_lt_one hp1]), rw one_div_one_div, exact add_rpow_le_rpow_add _ _ hp1, end theorem rpow_add_rpow_le {p q : ℝ} (a b : ℝ≥0∞) (hp_pos : 0 < p) (hpq : p ≤ q) : (a ^ q + b ^ q) ^ (1/q) ≤ (a ^ p + b ^ p) ^ (1/p) := begin have h_rpow : ∀ a : ℝ≥0∞, a^q = (a^p)^(q/p), from λ a, by rw [←ennreal.rpow_mul, div_eq_inv_mul, ←mul_assoc, _root_.mul_inv_cancel hp_pos.ne.symm, one_mul], have h_rpow_add_rpow_le_add : ((a^p)^(q/p) + (b^p)^(q/p)) ^ (1/(q/p)) ≤ a^p + b^p, { refine rpow_add_rpow_le_add (a^p) (b^p) _, rwa one_le_div hp_pos, }, rw [h_rpow a, h_rpow b, ennreal.le_rpow_one_div_iff hp_pos, ←ennreal.rpow_mul, mul_comm, mul_one_div], rwa one_div_div at h_rpow_add_rpow_le_add, end lemma rpow_add_le_add_rpow {p : ℝ} (a b : ℝ≥0∞) (hp_pos : 0 < p) (hp1 : p ≤ 1) : (a + b) ^ p ≤ a ^ p + b ^ p := begin have h := rpow_add_rpow_le a b hp_pos hp1, rw one_div_one at h, repeat { rw ennreal.rpow_one at h }, exact (ennreal.le_rpow_one_div_iff hp_pos).mp h, end end ennreal
63aa64ea31c85cef70c685044d7e711b098f84af
94e33a31faa76775069b071adea97e86e218a8ee
/src/data/bundle.lean
5f9810be8eca69aefde0ec190120dae4d1aa38b7
[ "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
5,133
lean
/- Copyright © 2021 Nicolò Cavalleri. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Nicolò Cavalleri -/ import tactic.basic import algebra.module.basic /-! # Bundle Basic data structure to implement fiber bundles, vector bundles (maybe fibrations?), etc. This file should contain all possible results that do not involve any topology. We represent a bundle `E` over a base space `B` as a dependent type `E : B → Type*`. We provide a type synonym of `Σ x, E x` as `bundle.total_space E`, to be able to endow it with a topology which is not the disjoint union topology `sigma.topological_space`. In general, the constructions of fiber bundles we will make will be of this form. ## Main Definitions * `bundle.total_space` the total space of a bundle. * `bundle.total_space.proj` the projection from the total space to the base space. * `bundle.total_space_mk` the constructor for the total space. ## References - https://en.wikipedia.org/wiki/Bundle_(mathematics) -/ namespace bundle variables {B : Type*} (E : B → Type*) /-- `bundle.total_space E` is the total space of the bundle `Σ x, E x`. This type synonym is used to avoid conflicts with general sigma types. -/ def total_space := Σ x, E x instance [inhabited B] [inhabited (E default)] : inhabited (total_space E) := ⟨⟨default, default⟩⟩ variables {E} /-- `bundle.total_space.proj` is the canonical projection `bundle.total_space E → B` from the total space to the base space. -/ @[simp, reducible] def total_space.proj : total_space E → B := sigma.fst /-- Constructor for the total space of a bundle. -/ @[simp, reducible] def total_space_mk (b : B) (a : E b) : bundle.total_space E := ⟨b, a⟩ lemma total_space.proj_mk {x : B} {y : E x} : (total_space_mk x y).proj = x := rfl lemma sigma_mk_eq_total_space_mk {x : B} {y : E x} : sigma.mk x y = total_space_mk x y := rfl lemma total_space.mk_cast {x x' : B} (h : x = x') (b : E x) : total_space_mk x' (cast (congr_arg E h) b) = total_space_mk x b := by { subst h, refl } lemma total_space.eta (z : total_space E) : total_space_mk z.proj z.2 = z := sigma.eta z instance {x : B} : has_coe_t (E x) (total_space E) := ⟨total_space_mk x⟩ @[simp] lemma coe_fst (x : B) (v : E x) : (v : total_space E).fst = x := rfl @[simp] lemma coe_snd {x : B} {y : E x} : (y : total_space E).snd = y := rfl lemma to_total_space_coe {x : B} (v : E x) : (v : total_space E) = total_space_mk x v := rfl -- notation for the direct sum of two bundles over the same base notation E₁ `×ᵇ`:100 E₂ := λ x, E₁ x × E₂ x /-- `bundle.trivial B F` is the trivial bundle over `B` of fiber `F`. -/ def trivial (B : Type*) (F : Type*) : B → Type* := function.const B F instance {F : Type*} [inhabited F] {b : B} : inhabited (bundle.trivial B F b) := ⟨(default : F)⟩ /-- The trivial bundle, unlike other bundles, has a canonical projection on the fiber. -/ def trivial.proj_snd (B : Type*) (F : Type*) : total_space (bundle.trivial B F) → F := sigma.snd section pullback variable {B' : Type*} /-- The pullback of a bundle `E` over a base `B` under a map `f : B' → B`, denoted by `pullback f E` or `f *ᵖ E`, is the bundle over `B'` whose fiber over `b'` is `E (f b')`. -/ @[nolint has_inhabited_instance] def pullback (f : B' → B) (E : B → Type*) := λ x, E (f x) notation f ` *ᵖ ` E := pullback f E /-- Natural embedding of the total space of `f *ᵖ E` into `B' × total_space E`. -/ @[simp] def pullback_total_space_embedding (f : B' → B) : total_space (f *ᵖ E) → B' × total_space E := λ z, (z.proj, total_space_mk (f z.proj) z.2) /-- The base map `f : B' → B` lifts to a canonical map on the total spaces. -/ def pullback.lift (f : B' → B) : total_space (f *ᵖ E) → total_space E := λ z, total_space_mk (f z.proj) z.2 @[simp] lemma pullback.proj_lift (f : B' → B) (x : total_space (f *ᵖ E)) : (pullback.lift f x).proj = f x.1 := rfl @[simp] lemma pullback.lift_mk (f : B' → B) (x : B') (y : E (f x)) : pullback.lift f (total_space_mk x y) = total_space_mk (f x) y := rfl lemma pullback_total_space_embedding_snd (f : B' → B) (x : total_space (f *ᵖ E)) : (pullback_total_space_embedding f x).2 = pullback.lift f x := rfl end pullback section fiber_structures variable [∀ x, add_comm_monoid (E x)] @[simp] lemma coe_snd_map_apply (x : B) (v w : E x) : (↑(v + w) : total_space E).snd = (v : total_space E).snd + (w : total_space E).snd := rfl variables (R : Type*) [semiring R] [∀ x, module R (E x)] @[simp] lemma coe_snd_map_smul (x : B) (r : R) (v : E x) : (↑(r • v) : total_space E).snd = r • (v : total_space E).snd := rfl end fiber_structures section trivial_instances variables {F : Type*} {R : Type*} [semiring R] (b : B) instance [add_comm_monoid F] : add_comm_monoid (bundle.trivial B F b) := ‹add_comm_monoid F› instance [add_comm_group F] : add_comm_group (bundle.trivial B F b) := ‹add_comm_group F› instance [add_comm_monoid F] [module R F] : module R (bundle.trivial B F b) := ‹module R F› end trivial_instances end bundle
435c998d5736a07caf55ebebee6b9b1f057940c4
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/analysis/asymptotics/asymptotic_equivalent.lean
16e0f02892359b3bab23e004152932d50f3540e5
[ "Apache-2.0" ]
permissive
jjgarzella/mathlib
96a345378c4e0bf26cf604aed84f90329e4896a2
395d8716c3ad03747059d482090e2bb97db612c8
refs/heads/master
1,686,480,124,379
1,625,163,323,000
1,625,163,323,000
281,190,421
2
0
Apache-2.0
1,595,268,170,000
1,595,268,169,000
null
UTF-8
Lean
false
false
11,042
lean
/- Copyright (c) 2020 Anatole Dedecker. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Anatole Dedecker -/ import analysis.asymptotics.asymptotics import analysis.normed_space.ordered import analysis.normed_space.bounded_linear_maps /-! # Asymptotic equivalence In this file, we define the relation `is_equivalent u v l`, which means that `u-v` is little o of `v` along the filter `l`. Unlike `is_[oO]` relations, this one requires `u` and `v` to have the same codomaine `β`. While the definition only requires `β` to be a `normed_group`, most interesting properties require it to be a `normed_field`. ## Notations We introduce the notation `u ~[l] v := is_equivalent u v l`, which you can use by opening the `asymptotics` locale. ## Main results If `β` is a `normed_group` : - `_ ~[l] _` is an equivalence relation - Equivalent statements for `u ~[l] const _ c` : - If `c ≠ 0`, this is true iff `tendsto u l (𝓝 c)` (see `is_equivalent_const_iff_tendsto`) - For `c = 0`, this is true iff `u =ᶠ[l] 0` (see `is_equivalent_zero_iff_eventually_zero`) If `β` is a `normed_field` : - Alternative characterization of the relation (see `is_equivalent_iff_exists_eq_mul`) : `u ~[l] v ↔ ∃ (φ : α → β) (hφ : tendsto φ l (𝓝 1)), u =ᶠ[l] φ * v` - Provided some non-vanishing hypothesis, this can be seen as `u ~[l] v ↔ tendsto (u/v) l (𝓝 1)` (see `is_equivalent_iff_tendsto_one`) - For any constant `c`, `u ~[l] v` implies `tendsto u l (𝓝 c) ↔ tendsto v l (𝓝 c)` (see `is_equivalent.tendsto_nhds_iff`) - `*` and `/` are compatible with `_ ~[l] _` (see `is_equivalent.mul` and `is_equivalent.div`) If `β` is a `normed_linear_ordered_field` : - If `u ~[l] v`, we have `tendsto u l at_top ↔ tendsto v l at_top` (see `is_equivalent.tendsto_at_top_iff`) -/ namespace asymptotics open filter function open_locale topological_space section normed_group variables {α β : Type*} [normed_group β] /-- Two functions `u` and `v` are said to be asymptotically equivalent along a filter `l` when `u x - v x = o(v x)` as x converges along `l`. -/ def is_equivalent (u v : α → β) (l : filter α) := is_o (u - v) v l localized "notation u ` ~[`:50 l:50 `] `:0 v:50 := asymptotics.is_equivalent u v l" in asymptotics variables {u v w : α → β} {l : filter α} lemma is_equivalent.is_o (h : u ~[l] v) : is_o (u - v) v l := h lemma is_equivalent.is_O (h : u ~[l] v) : is_O u v l := (is_O.congr_of_sub h.is_O.symm).mp (is_O_refl _ _) lemma is_equivalent.is_O_symm (h : u ~[l] v) : is_O v u l := begin convert h.is_o.right_is_O_add, ext, simp end @[refl] lemma is_equivalent.refl : u ~[l] u := begin rw [is_equivalent, sub_self], exact is_o_zero _ _ end @[symm] lemma is_equivalent.symm (h : u ~[l] v) : v ~[l] u := (h.is_o.trans_is_O h.is_O_symm).symm @[trans] lemma is_equivalent.trans (huv : u ~[l] v) (hvw : v ~[l] w) : u ~[l] w := (huv.is_o.trans_is_O hvw.is_O).triangle hvw.is_o lemma is_equivalent.congr_left {u v w : α → β} {l : filter α} (huv : u ~[l] v) (huw : u =ᶠ[l] w) : w ~[l] v := is_o.congr' (huw.sub (eventually_eq.refl _ _)) (eventually_eq.refl _ _) huv lemma is_equivalent.congr_right {u v w : α → β} {l : filter α} (huv : u ~[l] v) (hvw : v =ᶠ[l] w) : u ~[l] w := (huv.symm.congr_left hvw).symm lemma is_equivalent_zero_iff_eventually_zero : u ~[l] 0 ↔ u =ᶠ[l] 0 := begin rw [is_equivalent, sub_zero], exact is_o_zero_right_iff end lemma is_equivalent_zero_iff_is_O_zero : u ~[l] 0 ↔ is_O u (0 : α → β) l := begin refine ⟨is_equivalent.is_O, λ h, _⟩, rw [is_equivalent_zero_iff_eventually_zero, eventually_eq_iff_exists_mem], exact ⟨{x : α | u x = 0}, is_O_zero_right_iff.mp h, λ x hx, hx⟩, end lemma is_equivalent_const_iff_tendsto {c : β} (h : c ≠ 0) : u ~[l] const _ c ↔ tendsto u l (𝓝 c) := begin rw [is_equivalent, is_o_const_iff h], split; intro h; [ { have := h.sub tendsto_const_nhds, rw zero_sub (-c) at this }, { have := h.sub tendsto_const_nhds, rw ← sub_self c} ]; convert this; try { ext }; simp end lemma is_equivalent.tendsto_const {c : β} (hu : u ~[l] const _ c) : tendsto u l (𝓝 c) := begin rcases (em $ c = 0) with ⟨rfl, h⟩, { exact (tendsto_congr' $ is_equivalent_zero_iff_eventually_zero.mp hu).mpr tendsto_const_nhds }, { exact (is_equivalent_const_iff_tendsto h).mp hu } end lemma is_equivalent.tendsto_nhds {c : β} (huv : u ~[l] v) (hu : tendsto u l (𝓝 c)) : tendsto v l (𝓝 c) := begin by_cases h : c = 0, { rw [h, ← is_o_one_iff ℝ] at *, convert (huv.symm.is_o.trans hu).add hu, simp }, { rw ← is_equivalent_const_iff_tendsto h at hu ⊢, exact huv.symm.trans hu } end lemma is_equivalent.tendsto_nhds_iff {c : β} (huv : u ~[l] v) : tendsto u l (𝓝 c) ↔ tendsto v l (𝓝 c) := ⟨huv.tendsto_nhds, huv.symm.tendsto_nhds⟩ lemma is_equivalent.add_is_o (huv : u ~[l] v) (hwv : is_o w v l) : (w + u) ~[l] v := begin rw is_equivalent at *, convert hwv.add huv, ext, simp [add_sub], end lemma is_o.is_equivalent (huv : is_o (u - v) v l) : u ~[l] v := huv lemma is_equivalent.neg (huv : u ~[l] v) : (λ x, - u x) ~[l] (λ x, - v x) := begin rw is_equivalent, convert huv.is_o.neg_left.neg_right, ext, simp, end end normed_group open_locale asymptotics section normed_field variables {α β : Type*} [normed_field β] {t u v w : α → β} {l : filter α} lemma is_equivalent_iff_exists_eq_mul : u ~[l] v ↔ ∃ (φ : α → β) (hφ : tendsto φ l (𝓝 1)), u =ᶠ[l] φ * v := begin rw [is_equivalent, is_o_iff_exists_eq_mul], split; rintros ⟨φ, hφ, h⟩; [use (φ + 1), use (φ - 1)]; split, { conv in (𝓝 _) { rw ← zero_add (1 : β) }, exact hφ.add (tendsto_const_nhds) }, { convert h.add (eventually_eq.refl l v); ext; simp [add_mul] }, { conv in (𝓝 _) { rw ← sub_self (1 : β) }, exact hφ.sub (tendsto_const_nhds) }, { convert h.sub (eventually_eq.refl l v); ext; simp [sub_mul] } end lemma is_equivalent.exists_eq_mul (huv : u ~[l] v) : ∃ (φ : α → β) (hφ : tendsto φ l (𝓝 1)), u =ᶠ[l] φ * v := is_equivalent_iff_exists_eq_mul.mp huv lemma is_equivalent_of_tendsto_one (hz : ∀ᶠ x in l, v x = 0 → u x = 0) (huv : tendsto (u/v) l (𝓝 1)) : u ~[l] v := begin rw is_equivalent_iff_exists_eq_mul, refine ⟨u/v, huv, hz.mono $ λ x hz', (div_mul_cancel_of_imp hz').symm⟩, end lemma is_equivalent_of_tendsto_one' (hz : ∀ x, v x = 0 → u x = 0) (huv : tendsto (u/v) l (𝓝 1)) : u ~[l] v := is_equivalent_of_tendsto_one (eventually_of_forall hz) huv lemma is_equivalent_iff_tendsto_one (hz : ∀ᶠ x in l, v x ≠ 0) : u ~[l] v ↔ tendsto (u/v) l (𝓝 1) := begin split, { intro hequiv, have := hequiv.is_o.tendsto_0, simp only [pi.sub_apply, sub_div] at this, have key : tendsto (λ x, v x / v x) l (𝓝 1), { exact (tendsto_congr' $ hz.mono $ λ x hnz, @div_self _ _ (v x) hnz).mpr tendsto_const_nhds }, convert this.add key, { ext, simp }, { norm_num } }, { exact is_equivalent_of_tendsto_one (hz.mono $ λ x hnvz hz, (hnvz hz).elim) } end end normed_field section smul lemma is_equivalent.smul {α E 𝕜 : Type*} [normed_field 𝕜] [normed_group E] [normed_space 𝕜 E] {a b : α → 𝕜} {u v : α → E} {l : filter α} (hab : a ~[l] b) (huv : u ~[l] v) : (λ x, a x • u x) ~[l] (λ x, b x • v x) := begin rcases hab.exists_eq_mul with ⟨φ, hφ, habφ⟩, have : (λ (x : α), a x • u x) - (λ (x : α), b x • v x) =ᶠ[l] λ x, b x • ((φ x • u x) - v x), { convert (habφ.comp₂ (•) $ eventually_eq.refl _ u).sub (eventually_eq.refl _ (λ x, b x • v x)), ext, rw [pi.mul_apply, mul_comm, mul_smul, ← smul_sub] }, refine (is_o_congr this.symm $ eventually_eq.rfl).mp ((is_O_refl b l).smul_is_o _), rcases huv.is_O.exists_pos with ⟨C, hC, hCuv⟩, rw is_equivalent at *, rw is_o_iff at *, rw is_O_with at hCuv, simp only [metric.tendsto_nhds, dist_eq_norm] at hφ, intros c hc, specialize hφ ((c/2)/C) (div_pos (by linarith) hC), specialize huv (show 0 < c/2, by linarith), refine hφ.mp (huv.mp $ hCuv.mono $ λ x hCuvx huvx hφx, _), have key := calc ∥φ x - 1∥ * ∥u x∥ ≤ (c/2) / C * ∥u x∥ : mul_le_mul_of_nonneg_right hφx.le (norm_nonneg $ u x) ... ≤ (c/2) / C * (C*∥v x∥) : mul_le_mul_of_nonneg_left hCuvx (div_pos (by linarith) hC).le ... = c/2 * ∥v x∥ : by {field_simp [hC.ne.symm], ring}, calc ∥((λ (x : α), φ x • u x) - v) x∥ = ∥(φ x - 1) • u x + (u x - v x)∥ : by simp [sub_smul, sub_add] ... ≤ ∥(φ x - 1) • u x∥ + ∥u x - v x∥ : norm_add_le _ _ ... = ∥φ x - 1∥ * ∥u x∥ + ∥u x - v x∥ : by rw norm_smul ... ≤ c / 2 * ∥v x∥ + ∥u x - v x∥ : add_le_add_right key _ ... ≤ c / 2 * ∥v x∥ + c / 2 * ∥v x∥ : add_le_add_left huvx _ ... = c * ∥v x∥ : by ring, end end smul section mul_inv variables {α β : Type*} [normed_field β] {t u v w : α → β} {l : filter α} lemma is_equivalent.mul (htu : t ~[l] u) (hvw : v ~[l] w) : t * v ~[l] u * w := htu.smul hvw lemma is_equivalent.inv (huv : u ~[l] v) : (λ x, (u x)⁻¹) ~[l] (λ x, (v x)⁻¹) := begin rw is_equivalent_iff_exists_eq_mul at *, rcases huv with ⟨φ, hφ, h⟩, rw ← inv_one, refine ⟨λ x, (φ x)⁻¹, tendsto.inv' hφ (by norm_num) , _⟩, convert h.inv, ext, simp [mul_inv'] end lemma is_equivalent.div (htu : t ~[l] u) (hvw : v ~[l] w) : (λ x, t x / v x) ~[l] (λ x, u x / w x) := by simpa only [div_eq_mul_inv] using htu.mul hvw.inv end mul_inv section normed_linear_ordered_field variables {α β : Type*} [normed_linear_ordered_field β] {u v : α → β} {l : filter α} lemma is_equivalent.tendsto_at_top [order_topology β] (huv : u ~[l] v) (hu : tendsto u l at_top) : tendsto v l at_top := let ⟨φ, hφ, h⟩ := huv.symm.exists_eq_mul in tendsto.congr' h.symm ((mul_comm u φ) ▸ (hu.at_top_mul zero_lt_one hφ)) lemma is_equivalent.tendsto_at_top_iff [order_topology β] (huv : u ~[l] v) : tendsto u l at_top ↔ tendsto v l at_top := ⟨huv.tendsto_at_top, huv.symm.tendsto_at_top⟩ lemma is_equivalent.tendsto_at_bot [order_topology β] (huv : u ~[l] v) (hu : tendsto u l at_bot) : tendsto v l at_bot := begin convert tendsto_neg_at_top_at_bot.comp (huv.neg.tendsto_at_top $ tendsto_neg_at_bot_at_top.comp hu), ext, simp end lemma is_equivalent.tendsto_at_bot_iff [order_topology β] (huv : u ~[l] v) : tendsto u l at_bot ↔ tendsto v l at_bot := ⟨huv.tendsto_at_bot, huv.symm.tendsto_at_bot⟩ end normed_linear_ordered_field end asymptotics open filter asymptotics open_locale asymptotics variables {α β : Type*} [normed_group β] lemma filter.eventually_eq.is_equivalent {u v : α → β} {l : filter α} (h : u =ᶠ[l] v) : u ~[l] v := is_o.congr' h.sub_eq.symm (eventually_eq.refl _ _) (is_o_zero v l)
033e0d59cb85f96a40f9857890e4afc86ed2fe81
f3ab5c6b849dd89e43f1fe3572fbed3fc1baaf0f
/lean/perm.lean
886941b5ab8b9030b172c379f14e6ae7fc63dbc5
[ "Apache-2.0", "BSD-2-Clause", "LicenseRef-scancode-unknown-license-reference" ]
permissive
ekmett/coda
69fa7ac66924ea2cee12f7005b192c22baf9e03e
3309ea70c31b58a3915b0ecc9140985c3a1ac565
refs/heads/master
1,670,616,044,398
1,619,020,702,000
1,619,020,702,000
100,850,826
170
15
NOASSERTION
1,670,434,088,000
1,503,220,814,000
Haskell
UTF-8
Lean
false
false
4,675
lean
open function open nat -- seeking some position i, currently at some position n. -- todo: convert a cursor to a Prop def cursor (n s i k: ℕ) := n + s * k = i ∧ s > 0 -- k = 0 → i = n def start(i: ℕ) : cursor 0 1 i i := begin -- apply (@cursor.mk 0 1 i i), apply and.intro, rw [zero_add, one_mul], from nat.zero_lt_one_add 0, end inductive action :Π (n s i k: ℕ), cursor n s i k → Type | stop: Π (n s i: ℕ) (c : cursor n s i 0), action n s i 0 c | left: Π (n s i k: ℕ) (c : cursor n s i k), (k - 1) % 2 = 0 → cursor (n + s) (s*2) i ((k-1)/2) → action n s i k c | right: Π (n s i k: ℕ) (c : cursor n s i k), (k - 1) % 2 = 1 → cursor (n + 2 * s) (s*2) i ((k-1)/2) → action n s i k c private def lt_not_gt (m n: ℕ) (mn : m < n): ¬ m ≥ n := ((@nat.lt_iff_le_not_le m n).1 mn).2 def step: Π(n s i k : ℕ) (c : cursor n s i k), action n s i k c := begin introv, cases h : c with pi ps, cases k with km1, refine (action.stop n s i _), -- k = 0, stop have ds : s * 2 > 0, by rw [← nat.zero_mul 2]; from mul_lt_mul_of_pos_right ps (nat.zero_lt_one_add 1), have range: km1%2 < 2 := @nat.mod_lt km1 2 (nat.zero_lt_one_add 1), have sp : succ km1 - 1 = km1 := by simp, by_cases h2 : km1 % 2 <= 0, begin -- (k-1) % 2 = 0, go left apply action.left n s i (succ km1), from nat.eq_zero_of_le_zero h2, -- apply @cursor.mk (n+s) (s*2) i (km1/2) refine (and.intro _ ds), begin -- proof rw [sp, ← pi, nat.mul_assoc _ 2,← nat.zero_add (2*_), ← eq_zero_of_le_zero h2, mod_add_div], refine (eq.symm _), rw [← one_add km1, left_distrib, mul_one, ← add_assoc], end end, begin -- (k-1) % 2 = 1, go right have r_equals_1 : km1%2 = 1, begin cases h2 : km1 % 2, let c := nat.le_of_eq h2, contradiction, -- not 0 cases n_1, refl, -- exactly 1 exfalso, refine (lt_not_gt (km1%2) 2 range _), erw [h2], from succ_le_succ (succ_le_succ (zero_le n_1)) -- not 2+ end, apply action.right n s i, from r_equals_1, -- apply @cursor.mk (n+2*s) (s*2) i (km1/2) refine and.intro _ ds, begin -- proof rw [sp, mul_assoc, mul_comm _ s, add_assoc, ← left_distrib], have p11 : 2 + 2 * (km1 / 2) = 1 + 1 + 2 * (km1 / 2), by refl, have p1r : 1 + 1 = 1 + km1%2, by rw [r_equals_1], rw [p11, p1r, add_assoc, mod_add_div, add_comm 1 km1], from pi, end end end inductive T: Π(n s : ℕ) (occ : Prop), Type | tip : Π(n s: ℕ), T n s false | bin : Π (n s j: ℕ) (x y : Prop), n ≠ j ∨ x ∨ y → T (n+s) (2*s) x → T (n+2*s) (2*s) y → T n s true -- better to work with 'steps' that go from some position to another position, and thread a list of them inductive path: (n s i k: ℕ): cursor n s i k → Type | step: action n s i k -> structure tree := (occ : Prop) (content: T 0 1 occ) -- def well_founded.fix_F : Π {α : Sort u} {r : α → α → Prop} {C : α → Sort v}, -- (Π (x : α), (Π (y : α), r y x → C y) → C x) → Π (x : α), acc r x → C x -- nat.well_founded -- C is my path down to a state with 'k' remainining -- def step1 : (Π (x : ℕ), (Π (y : ℕ), y < x → C y) → C x) -- def wat := well_founded.fix lt_wf step1 -- should i use a sub-relation of lt_wf? -- induction on k def set.rec: Π (n s i j k: ℕ) (c: cursor n s i k) (o: Prop) (t : T n s o), Σ p : Prop, T n s p := begin simp_intros n s i j k c o t, let act := step n s i k c, cases hact: act, begin have ni : n = i := c_1.1, cases ht: t, by_cases ij: i = j, -- i = j, stop, tip from sigma.mk false (T.tip n s), -- i /= j, stop, tip apply sigma.mk true, apply (T.bin n s j false false), rw [ni]; from or.inl ij, apply T.tip, apply T.tip, by_cases ij: i = j, -- i = j, stop, bin cases ha_1: a_1, cases ha_2: a_2, apply sigma.mk false, apply T.tip, repeat { apply sigma.mk true, apply T.bin _ _ j _ _ _ a_1 a_2, simp }, rw [ni], from or.inl ij end, begin apply set.rec, end, begin admit end, end -- def set (i j: ℕ) (t0: tree): tree := -- #reduce step 0 11 (start 11) -- simple implicit-heap-like navigation namespace dir @[simp] def u (i:ℕ) := (i-1)/2 @[simp] def l (i:ℕ) := i*2+1 @[simp] def r (i:ℕ) := i*2+2 def ul : left_inverse u l := begin delta u l left_inverse at ⊢, simp_intros i, rw [add_comm, nat.add_sub_cancel, nat.mul_div_cancel i (nat.zero_lt_one_add 1)], end def ur : left_inverse u r := begin delta u r left_inverse at ⊢, simp_intros i, erw [add_comm, nat.add_sub_cancel (i*2+1) 1, add_comm, mul_comm, nat.add_mul_div_left 1 i (nat.zero_lt_one_add 1), zero_add], end end dir
b9b36d6c34a409acf45744d792e44d615e0e45f1
9cba98daa30c0804090f963f9024147a50292fa0
/old/src/classical_time_test.lean
b1f3ff63c6886c52f8ea27f03d90fadb95b082e0
[]
no_license
kevinsullivan/phys
dcb192f7b3033797541b980f0b4a7e75d84cea1a
ebc2df3779d3605ff7a9b47eeda25c2a551e011f
refs/heads/master
1,637,490,575,500
1,629,899,064,000
1,629,899,064,000
168,012,884
0
3
null
1,629,644,436,000
1,548,699,832,000
Lean
UTF-8
Lean
false
false
4,096
lean
import .classical_time /- Instantiate two different physical time spaces, to test that our design meets the requirement we set out in the README file. Two unrelated spaces modeling separate timelines. -/ noncomputable def timeline1 := classicalTime.mk 0 noncomputable def timeline2 := classicalTime.mk 0 /- Get the underlying affine space for each of these timelines. -/ def timeline1_space : real_affine.Algebra := classicalTimeAlgebra timeline1 def timeline2_space : real_affine.Algebra := classicalTimeAlgebra timeline2 /- structure affine_space_type -- parameterized affine space type (dim : ℕ) (X : Type u) (K : Type v) (V : Type w) [ring K] [add_comm_group V] [module K V] [affine_space V X] -- real affine space type parameterized by dimension def real_affine_space (dim : ℕ) : := affine_space_type dim (aff_pt_coord_tuple ℝ dim) ℝ (aff_vec_coord_tuple ℝ dim) -- AFFINE COORDINATE SPACES -- The type of affine vector coordinate tuples @[ext] structure aff_vec_coord_tuple := (l : list k) (len_fixed : l.length = n + 1) (fst_zero : head l = 0) -- The type of affine point coordinate tuples @[ext] structure aff_pt_coord_tuple := (l : list k) (len_fixed : l.length = n + 1) (fst_one : head l = 1) -- Bottom line: such sets of coordinate tuples form affine spaces instance aff_coord_is : affine_space (aff_vec_coord_tuple k n) (aff_pt_coord_tuple k n) := aff_torsor k n Definition 1 : affine_with_frame inductive affine_frame --need proof that "standard" is THE standard basis? | standard (ref_pt : X) (vec : ι → V) (basis : is_basis K vec ) : affine_frame | derived (ref_pt : X) (vec : ι → V) (basis : is_basis K vec ) : affine_frame → affine_frame @[ext] structure vec_with_frame (frame : affine_frame X K V ι) := (vec : V) structure pt_with_frame (frame : affine_frame X K V ι) := (pt : X) instance : affine_space (vec_with_frame X K V ι basis) (pt_with_frame X K V ι basis) := sorry ----------------------- inductive Algebra | aff_space {dim : ℕ} {X : Type} {K : Type} {V : Type} [ring K] [add_comm_group V] [module K V] [affine_space V X] (a : affine_space_type dim X K V) !!! abbreviation real_coordinatized_affine_space {dim : ℕ} (fr : r_fr dim) := affine_space_type dim (real_affine_point_with_frame dim fr) ℝ (real_affine_vector_with_frame dim fr) def to_affine_space (n : ℕ) : real_affine_space n := ⟨⟩ --⟨aff_pt_coord_tuple ℝ n, ℝ, aff_vec_coord_tuple ℝ n, real.ring, aff_comm_group ℝ n, aff_module ℝ n, aff_coord_is ℝ n⟩ to be deleted later following today's convo ↓ def to_coordinatized_affine_space (n : ℕ) (fr : r_fr n) : real_coordinatized_affine_space fr :=--(get_standard_frame_on_Rn n) := ⟨⟩ --⟨real.ring, prf_real_add_comm_grp_n n,prf_vec_module_n n,prf_aff_crd_sp n, get_standard_frame n⟩ -/ -/ -- Lemma: every timeline has the same affine space example : timeline1_space = timeline2_space := rfl def si := measurementSystem.si_measurement_system noncomputable def my_standard_frame := classicalTimeFrame.standard timeline1 si noncomputable def my_standard_frame_algebra := classicalTimeFrameAlgebra my_standard_frame noncomputable def my_vector : classicalTimeVector timeline1 := classicalTimeVector.mk 1 ⟨[2],sorry⟩ noncomputable def my_vector_algebra := classicalTimeVectorAlgebra my_vector noncomputable def std_vector : classicalTimeCoordinateVector timeline1 := {f:=my_standard_frame,..my_vector} noncomputable def my_std_vector_algebra := classicalTimeCoordinateVectorAlgebra std_vector noncomputable def my_Point : classicalTimePoint timeline1 := classicalTimePoint.mk 1 ⟨[0],sorry⟩ noncomputable def my_point_algebra := classicalTimePoint noncomputable def std_point : classicalTimeCoordinatePoint timeline1 := {f:=my_standard_frame,..my_Point} noncomputable def my_derived_frame : classicalTimeFrame timeline1 := classicalTimeFrame.derived timeline1 my_standard_frame my_Point (λone : fin 1,my_vector) si
109bb6bc461ca26909a44e424c8f1eaff6cab800
7cef822f3b952965621309e88eadf618da0c8ae9
/src/order/conditionally_complete_lattice.lean
004138b1974d9c08541bf5de88dd615c3139310c
[ "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
32,373
lean
/- Copyright (c) 2018 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sébastien Gouëzel Adapted from the corresponding theory for complete lattices. Theory of conditionally complete lattices. A conditionally complete lattice is a lattice in which every non-empty bounded subset s has a least upper bound and a greatest lower bound, denoted below by Sup s and Inf s. Typical examples are real, nat, int with their usual orders. The theory is very comparable to the theory of complete lattices, except that suitable boundedness and nonemptiness assumptions have to be added to most statements. We introduce two predicates bdd_above and bdd_below to express this boundedness, prove their basic properties, and then go on to prove most useful properties of Sup and Inf in conditionally complete lattices. To differentiate the statements between complete lattices and conditionally complete lattices, we prefix Inf and Sup in the statements by c, giving cInf and cSup. For instance, Inf_le is a statement in complete lattices ensuring Inf s ≤ x, while cInf_le is the same statement in conditionally complete lattices with an additional assumption that s is bounded below. -/ import order.lattice order.complete_lattice order.bounds tactic.finish data.set.finite set_option old_structure_cmd true open preorder set lattice universes u v w variables {α : Type u} {β : Type v} {ι : Type w} section /-! Extension of Sup and Inf from a preorder `α` to `with_top α` and `with_bot α` -/ open_locale classical noncomputable instance {α : Type*} [preorder α] [has_Sup α] : has_Sup (with_top α) := ⟨λ S, if ⊤ ∈ S then ⊤ else if bdd_above (coe ⁻¹' S : set α) then ↑(Sup (coe ⁻¹' S : set α)) else ⊤⟩ noncomputable instance {α : Type*} [has_Inf α] : has_Inf (with_top α) := ⟨λ S, if S ⊆ {⊤} then ⊤ else ↑(Inf (coe ⁻¹' S : set α))⟩ noncomputable instance {α : Type*} [has_Sup α] : has_Sup (with_bot α) := ⟨(@with_top.lattice.has_Inf (order_dual α) _).Inf⟩ noncomputable instance {α : Type*} [preorder α] [has_Inf α] : has_Inf (with_bot α) := ⟨(@with_top.lattice.has_Sup (order_dual α) _ _).Sup⟩ end -- section namespace lattice section prio set_option default_priority 100 -- see Note [default priority] /-- A conditionally complete lattice is a lattice in which every nonempty subset which is bounded above has a supremum, and every nonempty subset which is bounded below has an infimum. Typical examples are real numbers or natural numbers. To differentiate the statements from the corresponding statements in (unconditional) complete lattices, we prefix Inf and Sup by a c everywhere. The same statements should hold in both worlds, sometimes with additional assumptions of nonemptiness or boundedness.-/ class conditionally_complete_lattice (α : Type u) extends lattice α, has_Sup α, has_Inf α := (le_cSup : ∀s a, bdd_above s → a ∈ s → a ≤ Sup s) (cSup_le : ∀s a, s ≠ ∅ → a ∈ upper_bounds s → Sup s ≤ a) (cInf_le : ∀s a, bdd_below s → a ∈ s → Inf s ≤ a) (le_cInf : ∀s a, s ≠ ∅ → a ∈ lower_bounds s → a ≤ Inf s) class conditionally_complete_linear_order (α : Type u) extends conditionally_complete_lattice α, decidable_linear_order α class conditionally_complete_linear_order_bot (α : Type u) extends conditionally_complete_lattice α, decidable_linear_order α, order_bot α := (cSup_empty : Sup ∅ = ⊥) end prio /- A complete lattice is a conditionally complete lattice, as there are no restrictions on the properties of Inf and Sup in a complete lattice.-/ @[priority 100] -- see Note [lower instance priority] instance conditionally_complete_lattice_of_complete_lattice [complete_lattice α]: conditionally_complete_lattice α := { le_cSup := by intros; apply le_Sup; assumption, cSup_le := by intros; apply Sup_le; assumption, cInf_le := by intros; apply Inf_le; assumption, le_cInf := by intros; apply le_Inf; assumption, ..‹complete_lattice α› } @[priority 100] -- see Note [lower instance priority] instance conditionally_complete_linear_order_of_complete_linear_order [complete_linear_order α]: conditionally_complete_linear_order α := { ..lattice.conditionally_complete_lattice_of_complete_lattice, .. ‹complete_linear_order α› } section conditionally_complete_lattice variables [conditionally_complete_lattice α] {s t : set α} {a b : α} theorem le_cSup (h₁ : bdd_above s) (h₂ : a ∈ s) : a ≤ Sup s := conditionally_complete_lattice.le_cSup s a h₁ h₂ theorem cSup_le (h₁ : s ≠ ∅) (h₂ : ∀b∈s, b ≤ a) : Sup s ≤ a := conditionally_complete_lattice.cSup_le s a h₁ h₂ theorem cInf_le (h₁ : bdd_below s) (h₂ : a ∈ s) : Inf s ≤ a := conditionally_complete_lattice.cInf_le s a h₁ h₂ theorem le_cInf (h₁ : s ≠ ∅) (h₂ : ∀b∈s, a ≤ b) : a ≤ Inf s := conditionally_complete_lattice.le_cInf s a h₁ h₂ theorem le_cSup_of_le (_ : bdd_above s) (hb : b ∈ s) (h : a ≤ b) : a ≤ Sup s := le_trans h (le_cSup ‹bdd_above s› hb) theorem cInf_le_of_le (_ : bdd_below s) (hb : b ∈ s) (h : b ≤ a) : Inf s ≤ a := le_trans (cInf_le ‹bdd_below s› hb) h theorem cSup_le_cSup (_ : bdd_above t) (_ : s ≠ ∅) (h : s ⊆ t) : Sup s ≤ Sup t := cSup_le ‹s ≠ ∅› (assume (a) (ha : a ∈ s), le_cSup ‹bdd_above t› (h ha)) theorem cInf_le_cInf (_ : bdd_below t) (_ :s ≠ ∅) (h : s ⊆ t) : Inf t ≤ Inf s := le_cInf ‹s ≠ ∅› (assume (a) (ha : a ∈ s), cInf_le ‹bdd_below t› (h ha)) theorem cSup_le_iff (_ : bdd_above s) (_ : s ≠ ∅) : Sup s ≤ a ↔ (∀b ∈ s, b ≤ a) := ⟨assume (_ : Sup s ≤ a) (b) (_ : b ∈ s), le_trans (le_cSup ‹bdd_above s› ‹b ∈ s›) ‹Sup s ≤ a›, cSup_le ‹s ≠ ∅›⟩ theorem le_cInf_iff (_ : bdd_below s) (_ : s ≠ ∅) : a ≤ Inf s ↔ (∀b ∈ s, a ≤ b) := ⟨assume (_ : a ≤ Inf s) (b) (_ : b ∈ s), le_trans ‹a ≤ Inf s› (cInf_le ‹bdd_below s› ‹b ∈ s›), le_cInf ‹s ≠ ∅›⟩ lemma cSup_lower_bounds_eq_cInf {s : set α} (h : bdd_below s) (hs : s ≠ ∅) : Sup (lower_bounds s) = Inf s := let ⟨b, hb⟩ := h, ⟨a, ha⟩ := ne_empty_iff_exists_mem.1 hs in le_antisymm (cSup_le (ne_empty_iff_exists_mem.2 ⟨b, hb⟩) $ assume a ha, le_cInf hs ha) (le_cSup ⟨a, assume y hy, hy ha⟩ $ assume x hx, cInf_le h hx) lemma cInf_upper_bounds_eq_cSup {s : set α} (h : bdd_above s) (hs : s ≠ ∅) : Inf (upper_bounds s) = Sup s := let ⟨b, hb⟩ := h, ⟨a, ha⟩ := ne_empty_iff_exists_mem.1 hs in le_antisymm (cInf_le ⟨a, assume y hy, hy ha⟩ $ assume x hx, le_cSup h hx) (le_cInf (ne_empty_iff_exists_mem.2 ⟨b, hb⟩) $ assume a ha, cSup_le hs ha) /--Introduction rule to prove that b is the supremum of s: it suffices to check that b is larger than all elements of s, and that this is not the case of any w<b.-/ theorem cSup_intro (_ : s ≠ ∅) (_ : ∀a∈s, a ≤ b) (H : ∀w, w < b → (∃a∈s, w < a)) : Sup s = b := have bdd_above s := ⟨b, by assumption⟩, have (Sup s < b) ∨ (Sup s = b) := lt_or_eq_of_le (cSup_le ‹s ≠ ∅› ‹∀a∈s, a ≤ b›), have ¬(Sup s < b) := assume: Sup s < b, let ⟨a, _, _⟩ := (H (Sup s) ‹Sup s < b›) in /- a ∈ s, Sup s < a-/ have Sup s < Sup s := lt_of_lt_of_le ‹Sup s < a› (le_cSup ‹bdd_above s› ‹a ∈ s›), show false, by finish [lt_irrefl (Sup s)], show Sup s = b, by finish /--Introduction rule to prove that b is the infimum of s: it suffices to check that b is smaller than all elements of s, and that this is not the case of any w>b.-/ theorem cInf_intro (_ : s ≠ ∅) (_ : ∀a∈s, b ≤ a) (H : ∀w, b < w → (∃a∈s, a < w)) : Inf s = b := have bdd_below s := ⟨b, by assumption⟩, have (b < Inf s) ∨ (b = Inf s) := lt_or_eq_of_le (le_cInf ‹s ≠ ∅› ‹∀a∈s, b ≤ a›), have ¬(b < Inf s) := assume: b < Inf s, let ⟨a, _, _⟩ := (H (Inf s) ‹b < Inf s›) in /- a ∈ s, a < Inf s-/ have Inf s < Inf s := lt_of_le_of_lt (cInf_le ‹bdd_below s› ‹a ∈ s›) ‹a < Inf s› , show false, by finish [lt_irrefl (Inf s)], show Inf s = b, by finish /--When an element a of a set s is larger than all other elements of the set, it is Sup s-/ theorem cSup_of_mem_of_le (_ : a ∈ s) (_ : ∀w∈s, w ≤ a) : Sup s = a := have bdd_above s := ⟨a, by assumption⟩, have s ≠ ∅ := ne_empty_of_mem ‹a ∈ s›, have A : a ≤ Sup s := le_cSup ‹bdd_above s› ‹a ∈ s›, have B : Sup s ≤ a := cSup_le ‹s ≠ ∅› ‹∀w∈s, w ≤ a›, le_antisymm B A /--When an element a of a set s is smaller than all other elements of the set, it is Inf s-/ theorem cInf_of_mem_of_le (_ : a ∈ s) (_ : ∀w∈s, a ≤ w) : Inf s = a := have bdd_below s := ⟨a, by assumption⟩, have s ≠ ∅ := ne_empty_of_mem ‹a ∈ s›, have A : Inf s ≤ a := cInf_le ‹bdd_below s› ‹a ∈ s›, have B : a ≤ Inf s := le_cInf ‹s ≠ ∅› ‹∀w∈s, a ≤ w›, le_antisymm A B /--b < Sup s when there is an element a in s with b < a, when s is bounded above. This is essentially an iff, except that the assumptions for the two implications are slightly different (one needs boundedness above for one direction, nonemptiness and linear order for the other one), so we formulate separately the two implications, contrary to the complete_lattice case.-/ lemma lt_cSup_of_lt (_ : bdd_above s) (_ : a ∈ s) (_ : b < a) : b < Sup s := lt_of_lt_of_le ‹b < a› (le_cSup ‹bdd_above s› ‹a ∈ s›) /--Inf s < b when there is an element a in s with a < b, when s is bounded below. This is essentially an iff, except that the assumptions for the two implications are slightly different (one needs boundedness below for one direction, nonemptiness and linear order for the other one), so we formulate separately the two implications, contrary to the complete_lattice case.-/ lemma cInf_lt_of_lt (_ : bdd_below s) (_ : a ∈ s) (_ : a < b) : Inf s < b := lt_of_le_of_lt (cInf_le ‹bdd_below s› ‹a ∈ s›) ‹a < b› /--The supremum of a singleton is the element of the singleton-/ @[simp] theorem cSup_singleton (a : α) : Sup {a} = a := have A : a ≤ Sup {a} := by apply le_cSup _ _; simp only [set.mem_singleton,bdd_above_singleton], have B : Sup {a} ≤ a := by apply cSup_le _ _; simp only [set.mem_singleton_iff, forall_eq,ne.def, not_false_iff, set.singleton_ne_empty], le_antisymm B A /--The infimum of a singleton is the element of the singleton-/ @[simp] theorem cInf_singleton (a : α) : Inf {a} = a := have A : Inf {a} ≤ a := by apply cInf_le _ _; simp only [set.mem_singleton,bdd_below_singleton], have B : a ≤ Inf {a} := by apply le_cInf _ _; simp only [set.mem_singleton_iff, forall_eq,ne.def, not_false_iff, set.singleton_ne_empty], le_antisymm A B /--If a set is bounded below and above, and nonempty, its infimum is less than or equal to its supremum.-/ theorem cInf_le_cSup (_ : bdd_below s) (_ : bdd_above s) (_ : s ≠ ∅) : Inf s ≤ Sup s := let ⟨w, hw⟩ := exists_mem_of_ne_empty ‹s ≠ ∅› in /-hw : w ∈ s-/ have Inf s ≤ w := cInf_le ‹bdd_below s› ‹w ∈ s›, have w ≤ Sup s := le_cSup ‹bdd_above s› ‹w ∈ s›, le_trans ‹Inf s ≤ w› ‹w ≤ Sup s› /--The sup of a union of two sets is the max of the suprema of each subset, under the assumptions that all sets are bounded above and nonempty.-/ theorem cSup_union (_ : bdd_above s) (_ : s ≠ ∅) (_ : bdd_above t) (_ : t ≠ ∅) : Sup (s ∪ t) = Sup s ⊔ Sup t := have A : Sup (s ∪ t) ≤ Sup s ⊔ Sup t := have s ∪ t ≠ ∅ := by simp only [not_and, set.union_empty_iff, ne.def] at *; finish, have F : ∀b∈ s∪t, b ≤ Sup s ⊔ Sup t := begin intros, cases H, apply le_trans (le_cSup ‹bdd_above s› ‹b ∈ s›) _, simp only [lattice.le_sup_left], apply le_trans (le_cSup ‹bdd_above t› ‹b ∈ t›) _, simp only [lattice.le_sup_right] end, cSup_le this F, have B : Sup s ⊔ Sup t ≤ Sup (s ∪ t) := have Sup s ≤ Sup (s ∪ t) := by apply cSup_le_cSup _ ‹s ≠ ∅›; simp only [bdd_above_union,set.subset_union_left]; finish, have Sup t ≤ Sup (s ∪ t) := by apply cSup_le_cSup _ ‹t ≠ ∅›; simp only [bdd_above_union,set.subset_union_right]; finish, by simp only [lattice.sup_le_iff]; split; assumption; assumption, le_antisymm A B /--The inf of a union of two sets is the min of the infima of each subset, under the assumptions that all sets are bounded below and nonempty.-/ theorem cInf_union (_ : bdd_below s) (_ : s ≠ ∅) (_ : bdd_below t) (_ : t ≠ ∅) : Inf (s ∪ t) = Inf s ⊓ Inf t := have A : Inf s ⊓ Inf t ≤ Inf (s ∪ t) := have s ∪ t ≠ ∅ := by simp only [not_and, set.union_empty_iff, ne.def] at *; finish, have F : ∀b∈ s∪t, Inf s ⊓ Inf t ≤ b := begin intros, cases H, apply le_trans _ (cInf_le ‹bdd_below s› ‹b ∈ s›), simp only [lattice.inf_le_left], apply le_trans _ (cInf_le ‹bdd_below t› ‹b ∈ t›), simp only [lattice.inf_le_right] end, le_cInf this F, have B : Inf (s ∪ t) ≤ Inf s ⊓ Inf t := have Inf (s ∪ t) ≤ Inf s := by apply cInf_le_cInf _ ‹s ≠ ∅›; simp only [bdd_below_union,set.subset_union_left]; finish, have Inf (s ∪ t) ≤ Inf t := by apply cInf_le_cInf _ ‹t ≠ ∅›; simp only [bdd_below_union,set.subset_union_right]; finish, by simp only [lattice.le_inf_iff]; split; assumption; assumption, le_antisymm B A /--The supremum of an intersection of two sets is bounded by the minimum of the suprema of each set, if all sets are bounded above and nonempty.-/ theorem cSup_inter_le (_ : bdd_above s) (_ : bdd_above t) (_ : s ∩ t ≠ ∅) : Sup (s ∩ t) ≤ Sup s ⊓ Sup t := begin apply cSup_le ‹s ∩ t ≠ ∅› _, simp only [lattice.le_inf_iff, and_imp, set.mem_inter_eq], intros b _ _, split, apply le_cSup ‹bdd_above s› ‹b ∈ s›, apply le_cSup ‹bdd_above t› ‹b ∈ t› end /--The infimum of an intersection of two sets is bounded below by the maximum of the infima of each set, if all sets are bounded below and nonempty.-/ theorem le_cInf_inter (_ : bdd_below s) (_ : bdd_below t) (_ : s ∩ t ≠ ∅) : Inf s ⊔ Inf t ≤ Inf (s ∩ t) := begin apply le_cInf ‹s ∩ t ≠ ∅› _, simp only [and_imp, set.mem_inter_eq, lattice.sup_le_iff], intros b _ _, split, apply cInf_le ‹bdd_below s› ‹b ∈ s›, apply cInf_le ‹bdd_below t› ‹b ∈ t› end /-- The supremum of insert a s is the maximum of a and the supremum of s, if s is nonempty and bounded above.-/ theorem cSup_insert (_ : bdd_above s) (_ : s ≠ ∅) : Sup (insert a s) = a ⊔ Sup s := calc Sup (insert a s) = Sup ({a} ∪ s) : by rw [insert_eq] ... = Sup {a} ⊔ Sup s : by apply cSup_union _ _ ‹bdd_above s› ‹s ≠ ∅›; simp only [ne.def, not_false_iff, set.singleton_ne_empty,bdd_above_singleton] ... = a ⊔ Sup s : by simp only [eq_self_iff_true, lattice.cSup_singleton] /-- The infimum of insert a s is the minimum of a and the infimum of s, if s is nonempty and bounded below.-/ theorem cInf_insert (_ : bdd_below s) (_ : s ≠ ∅) : Inf (insert a s) = a ⊓ Inf s := calc Inf (insert a s) = Inf ({a} ∪ s) : by rw [insert_eq] ... = Inf {a} ⊓ Inf s : by apply cInf_union _ _ ‹bdd_below s› ‹s ≠ ∅›; simp only [ne.def, not_false_iff, set.singleton_ne_empty,bdd_below_singleton] ... = a ⊓ Inf s : by simp only [eq_self_iff_true, lattice.cInf_singleton] @[simp] lemma cInf_interval : Inf {b | a ≤ b} = a := cInf_of_mem_of_le (by simp only [set.mem_set_of_eq]) (λw Hw, by simp only [set.mem_set_of_eq] at Hw; apply Hw) @[simp] lemma cSup_interval : Sup {b | b ≤ a} = a := cSup_of_mem_of_le (by simp only [set.mem_set_of_eq]) (λw Hw, by simp only [set.mem_set_of_eq] at Hw; apply Hw) /--The indexed supremum of two functions are comparable if the functions are pointwise comparable-/ lemma csupr_le_csupr {f g : β → α} (B : bdd_above (range g)) (H : ∀x, f x ≤ g x) : supr f ≤ supr g := begin classical, by_cases nonempty β, { have Rf : range f ≠ ∅, { simpa }, apply cSup_le Rf, rintros y ⟨x, rfl⟩, have : g x ∈ range g := ⟨x, rfl⟩, exact le_cSup_of_le B this (H x) }, { have Rf : range f = ∅, { simpa }, have Rg : range g = ∅, { simpa }, unfold supr, rw [Rf, Rg] } end /--The indexed supremum of a function is bounded above by a uniform bound-/ lemma csupr_le [ne : nonempty β] {f : β → α} {c : α} (H : ∀x, f x ≤ c) : supr f ≤ c := cSup_le (by simp [not_not_intro ne]) (by rwa forall_range_iff) /--The indexed supremum of a function is bounded below by the value taken at one point-/ lemma le_csupr {f : β → α} (H : bdd_above (range f)) {c : β} : f c ≤ supr f := le_cSup H (mem_range_self _) /--The indexed infimum of two functions are comparable if the functions are pointwise comparable-/ lemma cinfi_le_cinfi {f g : β → α} (B : bdd_below (range f)) (H : ∀x, f x ≤ g x) : infi f ≤ infi g := begin classical, by_cases nonempty β, { have Rg : range g ≠ ∅, { simpa }, apply le_cInf Rg, rintros y ⟨x, rfl⟩, have : f x ∈ range f := ⟨x, rfl⟩, exact cInf_le_of_le B this (H x) }, { have Rf : range f = ∅, { simpa }, have Rg : range g = ∅, { simpa }, unfold infi, rw [Rf, Rg] } end /--The indexed minimum of a function is bounded below by a uniform lower bound-/ lemma le_cinfi [ne : nonempty β] {f : β → α} {c : α} (H : ∀x, c ≤ f x) : c ≤ infi f := le_cInf (by simp [not_not_intro ne]) (by rwa forall_range_iff) /--The indexed infimum of a function is bounded above by the value taken at one point-/ lemma cinfi_le {f : β → α} (H : bdd_below (range f)) {c : β} : infi f ≤ f c := cInf_le H (mem_range_self _) lemma is_lub_cSup {s : set α} (ne : s ≠ ∅) (H : bdd_above s) : is_lub s (Sup s) := ⟨assume x, le_cSup H, assume x, cSup_le ne⟩ lemma is_glb_cInf {s : set α} (ne : s ≠ ∅) (H : bdd_below s) : is_glb s (Inf s) := ⟨assume x, cInf_le H, assume x, le_cInf ne⟩ @[simp] theorem cinfi_const [nonempty ι] {a : α} : (⨅ b:ι, a) = a := begin rcases exists_mem_of_nonempty ι with ⟨x, _⟩, refine le_antisymm (@cinfi_le _ _ _ _ _ x) (le_cinfi (λi, _root_.le_refl _)), rw range_const, exact bdd_below_singleton end @[simp] theorem csupr_const [nonempty ι] {a : α} : (⨆ b:ι, a) = a := begin rcases exists_mem_of_nonempty ι with ⟨x, _⟩, refine le_antisymm (csupr_le (λi, _root_.le_refl _)) (@le_csupr _ _ _ (λ b:ι, a) _ x), rw range_const, exact bdd_above_singleton end end conditionally_complete_lattice section conditionally_complete_linear_order variables [conditionally_complete_linear_order α] {s t : set α} {a b : α} /-- When b < Sup s, there is an element a in s with b < a, if s is nonempty and the order is a linear order. -/ lemma exists_lt_of_lt_cSup (_ : s ≠ ∅) (_ : b < Sup s) : ∃a∈s, b < a := begin classical, by_contra h, have : Sup s ≤ b := by apply cSup_le ‹s ≠ ∅› _; finish, apply lt_irrefl b (lt_of_lt_of_le ‹b < Sup s› ‹Sup s ≤ b›) end /-- Indexed version of the above lemma `exists_lt_of_lt_cSup`. When `b < supr f`, there is an element `i` such that `b < f i`. -/ lemma exists_lt_of_lt_csupr {ι : Sort*} (ne : nonempty ι) {f : ι → α} (h : b < supr f) : ∃i, b < f i := have h' : range f ≠ ∅ := nonempty.elim ne (λ i, ne_empty_of_mem (mem_range_self i)), let ⟨_, ⟨i, rfl⟩, h⟩ := exists_lt_of_lt_cSup h' h in ⟨i, h⟩ /--When Inf s < b, there is an element a in s with a < b, if s is nonempty and the order is a linear order.-/ lemma exists_lt_of_cInf_lt (_ : s ≠ ∅) (_ : Inf s < b) : ∃a∈s, a < b := begin classical, by_contra h, have : b ≤ Inf s := by apply le_cInf ‹s ≠ ∅› _; finish, apply lt_irrefl b (lt_of_le_of_lt ‹b ≤ Inf s› ‹Inf s < b›) end /-- Indexed version of the above lemma `exists_lt_of_cInf_lt` When `infi f < a`, there is an element `i` such that `f i < a`. -/ lemma exists_lt_of_cinfi_lt {ι : Sort*} (ne : nonempty ι) {f : ι → α} (h : infi f < a) : (∃i, f i < a) := have h' : range f ≠ ∅ := nonempty.elim ne (λ i, ne_empty_of_mem (mem_range_self i)), let ⟨_, ⟨i, rfl⟩, h⟩ := exists_lt_of_cInf_lt h' h in ⟨i, h⟩ /--Introduction rule to prove that b is the supremum of s: it suffices to check that 1) b is an upper bound 2) every other upper bound b' satisfies b ≤ b'.-/ theorem cSup_intro' (_ : s ≠ ∅) (h_is_ub : ∀ a ∈ s, a ≤ b) (h_b_le_ub : ∀ub, (∀ a ∈ s, a ≤ ub) → (b ≤ ub)) : Sup s = b := le_antisymm (show Sup s ≤ b, from cSup_le ‹s ≠ ∅› h_is_ub) (show b ≤ Sup s, from h_b_le_ub _ $ assume a, le_cSup ⟨b, h_is_ub⟩) end conditionally_complete_linear_order section conditionally_complete_linear_order_bot lemma cSup_empty [conditionally_complete_linear_order_bot α] : (Sup ∅ : α) = ⊥ := conditionally_complete_linear_order_bot.cSup_empty α end conditionally_complete_linear_order_bot section open_locale classical noncomputable instance : has_Inf ℕ := ⟨λs, if h : ∃n, n ∈ s then @nat.find (λn, n ∈ s) _ h else 0⟩ noncomputable instance : has_Sup ℕ := ⟨λs, if h : ∃n, ∀a∈s, a ≤ n then @nat.find (λn, ∀a∈s, a ≤ n) _ h else 0⟩ lemma Inf_nat_def {s : set ℕ} (h : ∃n, n ∈ s) : Inf s = @nat.find (λn, n ∈ s) _ h := dif_pos _ lemma Sup_nat_def {s : set ℕ} (h : ∃n, ∀a∈s, a ≤ n) : Sup s = @nat.find (λn, ∀a∈s, a ≤ n) _ h := dif_pos _ /-- This instance is necessary, otherwise the lattice operations would be derived via conditionally_complete_linear_order_bot and marked as noncomputable. -/ instance : lattice ℕ := infer_instance noncomputable instance : conditionally_complete_linear_order_bot ℕ := { Sup := Sup, Inf := Inf, le_cSup := assume s a hb ha, by rw [Sup_nat_def hb]; revert a ha; exact @nat.find_spec _ _ hb, cSup_le := assume s a hs ha, by rw [Sup_nat_def ⟨a, ha⟩]; exact nat.find_min' _ ha, le_cInf := assume s a hs hb, by rw [Inf_nat_def (ne_empty_iff_exists_mem.1 hs)]; exact hb (@nat.find_spec (λn, n ∈ s) _ _), cInf_le := assume s a hb ha, by rw [Inf_nat_def ⟨a, ha⟩]; exact nat.find_min' _ ha, cSup_empty := begin simp only [Sup_nat_def, set.mem_empty_eq, forall_const, forall_prop_of_false, not_false_iff, exists_const], apply bot_unique (nat.find_min' _ _), trivial end, .. (infer_instance : order_bot ℕ), .. (infer_instance : lattice ℕ), .. (infer_instance : decidable_linear_order ℕ) } end end lattice /-end of namespace lattice-/ namespace with_top open lattice open_locale classical variables [conditionally_complete_linear_order_bot α] /-- The Sup of a non-empty set is its least upper bound for a conditionally complete lattice with a top. -/ lemma is_lub_Sup' {β : Type*} [conditionally_complete_lattice β] {s : set (with_top β)} (hs : s ≠ ∅) : is_lub s (Sup s) := begin split, { show ite _ _ _ ∈ _, split_ifs, { intros _ _, exact le_top }, { rintro (⟨⟩|a) ha, { contradiction }, apply some_le_some.2, exact le_cSup h_1 ha }, { intros _ _, exact le_top } }, { show ite _ _ _ ∈ _, split_ifs, { rintro (⟨⟩|a) ha, { exact _root_.le_refl _ }, { exact false.elim (not_top_le_coe a (ha h)) } }, { rintro (⟨⟩|b) hb, { exact le_top }, refine some_le_some.2 (cSup_le _ _), { refine mt _ h, rw ne_empty_iff_exists_mem at hs, intro h2, rcases hs with ⟨⟨⟩|b, hb⟩, { assumption }, { exfalso, revert h2, exact ne_empty_of_mem hb } }, { intros a ha, exact some_le_some.1 (hb ha) } }, { rintro (⟨⟩|b) hb, { exact _root_.le_refl _ }, { exfalso, apply h_1, use b, intros a ha, exact some_le_some.1 (hb ha) } } } end lemma is_lub_Sup (s : set (with_top α)) : is_lub s (Sup s) := begin by_cases hs : s = ∅, { rw hs, show is_lub ∅ (ite _ _ _), split_ifs, { cases h }, { rw [preimage_empty, cSup_empty], exact is_lub_empty }, { exfalso, apply h_1, use ⊥, rintro a ⟨⟩ } }, exact is_lub_Sup' hs, end /-- The Inf of a bounded-below set is its greatest lower bound for a conditionally complete lattice with a top. -/ lemma is_glb_Inf' {β : Type*} [conditionally_complete_lattice β] {s : set (with_top β)} (hs : bdd_below s) : is_glb s (Inf s) := begin split, { show ite _ _ _ ∈ _, split_ifs, { intros a ha, exact top_le_iff.2 (set.mem_singleton_iff.1 (h ha)) }, { rintro (⟨⟩|a) ha, { exact le_top }, refine some_le_some.2 (cInf_le _ ha), rcases hs with ⟨⟨⟩|b, hb⟩, { exfalso, apply h, intros c hc, rw [mem_singleton_iff, ←top_le_iff], exact hb hc }, use b, intros c hc, exact some_le_some.1 (hb hc) } }, { show ite _ _ _ ∈ _, split_ifs, { intros _ _, exact le_top }, { rintro (⟨⟩|a) ha, { exfalso, apply h, intros b hb, exact set.mem_singleton_iff.2 (top_le_iff.1 (ha hb)) }, { refine some_le_some.2 (le_cInf _ _), { refine mt _ h, rintro hs (⟨⟩|b) hb, { exact mem_singleton _ }, { exfalso, apply not_mem_empty b, rwa ←hs } }, { intros b hb, rw ←some_le_some, exact ha hb } } } } end lemma is_glb_Inf (s : set (with_top α)) : is_glb s (Inf s) := begin by_cases hs : bdd_below s, { exact is_glb_Inf' hs }, { exfalso, apply hs, use ⊥, intros _ _, exact bot_le }, end noncomputable instance : complete_linear_order (with_top α) := { Sup := Sup, le_Sup := assume s, (is_lub_Sup s).1, Sup_le := assume s, (is_lub_Sup s).2, Inf := Inf, le_Inf := assume s, (is_glb_Inf s).2, Inf_le := assume s, (is_glb_Inf s).1, decidable_le := classical.dec_rel _, .. with_top.linear_order, ..with_top.lattice, ..with_top.order_top, ..with_top.order_bot } lemma coe_Sup {s : set α} (hb : bdd_above s) : (↑(Sup s) : with_top α) = (⨆a∈s, ↑a) := begin by_cases hs : s = ∅, { rw [hs, cSup_empty], simp only [set.mem_empty_eq, lattice.supr_bot, lattice.supr_false], refl }, apply le_antisymm, { refine ((coe_le_iff _ _).2 $ assume b hb, cSup_le hs $ assume a has, coe_le_coe.1 $ hb ▸ _), exact (le_supr_of_le a $ le_supr_of_le has $ _root_.le_refl _) }, { exact (supr_le $ assume a, supr_le $ assume ha, coe_le_coe.2 $ le_cSup hb ha) } end lemma coe_Inf {s : set α} (hs : s ≠ ∅) : (↑(Inf s) : with_top α) = (⨅a∈s, ↑a) := let ⟨x, hx⟩ := ne_empty_iff_exists_mem.1 hs in have (⨅a∈s, ↑a : with_top α) ≤ x, from infi_le_of_le x $ infi_le_of_le hx $ _root_.le_refl _, let ⟨r, r_eq, hr⟩ := (le_coe_iff _ _).1 this in le_antisymm (le_infi $ assume a, le_infi $ assume ha, coe_le_coe.2 $ cInf_le (bdd_below_bot s) ha) begin refine (r_eq.symm ▸ coe_le_coe.2 $ le_cInf hs $ assume a has, coe_le_coe.1 $ _), refine (r_eq ▸ infi_le_of_le a _), exact (infi_le_of_le has $ _root_.le_refl _), end end with_top namespace enat open_locale classical open lattice noncomputable instance : complete_linear_order enat := { Sup := λ s, with_top_equiv.symm $ Sup (with_top_equiv '' s), Inf := λ s, with_top_equiv.symm $ Inf (with_top_equiv '' s), le_Sup := by intros; rw ← with_top_equiv_le; simp; apply le_Sup _; simpa, Inf_le := by intros; rw ← with_top_equiv_le; simp; apply Inf_le _; simpa, Sup_le := begin intros s a h1, rw [← with_top_equiv_le, with_top_equiv.right_inverse_symm], apply Sup_le _, rintros b ⟨x, h2, rfl⟩, rw with_top_equiv_le, apply h1, assumption end, le_Inf := begin intros s a h1, rw [← with_top_equiv_le, with_top_equiv.right_inverse_symm], apply le_Inf _, rintros b ⟨x, h2, rfl⟩, rw with_top_equiv_le, apply h1, assumption end, ..enat.decidable_linear_order, ..enat.lattice.bounded_lattice } end enat section order_dual open lattice instance (α : Type*) [conditionally_complete_lattice α] : conditionally_complete_lattice (order_dual α) := { le_cSup := @cInf_le α _, cSup_le := @le_cInf α _, le_cInf := @cSup_le α _, cInf_le := @le_cSup α _, ..order_dual.lattice.has_Inf α, ..order_dual.lattice.has_Sup α, ..order_dual.lattice.lattice α } instance (α : Type*) [conditionally_complete_linear_order α] : conditionally_complete_linear_order (order_dual α) := { ..order_dual.lattice.conditionally_complete_lattice α, ..order_dual.decidable_linear_order α } end order_dual section with_top_bot /-! ### Complete lattice structure on `with_top (with_bot α)` If `α` is a `conditionally_complete_lattice`, then we show that `with_top α` and `with_bot α` also inherit the structure of conditionally complete lattices. Furthermore, we show that `with_top (with_bot α)` naturally inherits the structure of a complete lattice. Note that for α a conditionally complete lattice, `Sup` and `Inf` both return junk values for sets which are empty or unbounded. The extension of `Sup` to `with_top α` fixes the unboundedness problem and the extension to `with_bot α` fixes the problem with the empty set. This result can be used to show that the extended reals [-∞, ∞] are a complete lattice. -/ open lattice open_locale classical /-- Adding a top element to a conditionally complete lattice gives a conditionally complete lattice -/ noncomputable instance with_top.conditionally_complete_lattice {α : Type*} [conditionally_complete_lattice α] : conditionally_complete_lattice (with_top α) := { le_cSup := λ S a hS haS, (with_top.is_lub_Sup' (ne_empty_of_mem haS)).1 haS, cSup_le := λ S a hS haS, (with_top.is_lub_Sup' hS).2 haS, cInf_le := λ S a hS haS, (with_top.is_glb_Inf' hS).1 haS, le_cInf := λ S a hS haS, (with_top.is_glb_Inf' ⟨a, haS⟩).2 haS, ..with_top.lattice, ..with_top.lattice.has_Sup, ..with_top.lattice.has_Inf } /-- Adding a bottom element to a conditionally complete lattice gives a conditionally complete lattice -/ noncomputable instance with_bot.conditionally_complete_lattice {α : Type*} [conditionally_complete_lattice α] : conditionally_complete_lattice (with_bot α) := { le_cSup := (@with_top.conditionally_complete_lattice (order_dual α) _).cInf_le, cSup_le := (@with_top.conditionally_complete_lattice (order_dual α) _).le_cInf, cInf_le := (@with_top.conditionally_complete_lattice (order_dual α) _).le_cSup, le_cInf := (@with_top.conditionally_complete_lattice (order_dual α) _).cSup_le, ..with_bot.lattice, ..with_bot.lattice.has_Sup, ..with_bot.lattice.has_Inf } /-- Adding a bottom and a top to a conditionally complete lattice gives a bounded lattice-/ noncomputable instance {α : Type*} [conditionally_complete_lattice α] : bounded_lattice (with_top (with_bot α)) := { ..with_top.order_bot, ..with_top.order_top, ..conditionally_complete_lattice.to_lattice _ } theorem with_bot.cSup_empty {α : Type*} [conditionally_complete_lattice α] : Sup (∅ : set (with_bot α)) = ⊥ := begin show ite _ _ _ = ⊥, split_ifs; finish, end noncomputable instance {α : Type*} [conditionally_complete_lattice α] : complete_lattice (with_top (with_bot α)) := { le_Sup := λ S a haS, (with_top.is_lub_Sup' (ne_empty_of_mem haS)).1 haS, Sup_le := λ S a ha, begin by_cases h : S = ∅, { show ite _ _ _ ≤ a, split_ifs, { rw h at h_1, cases h_1 }, { convert bot_le, convert with_bot.cSup_empty, rw h, refl }, { exfalso, apply h_2, use ⊥, rw h, rintro b ⟨⟩ } }, { refine (with_top.is_lub_Sup' h).2 ha } end, Inf_le := λ S a haS, show ite _ _ _ ≤ a, begin split_ifs, { cases a with a, exact _root_.le_refl _, cases (h haS); tauto }, { cases a, { exact le_top }, { apply with_top.some_le_some.2, refine cInf_le _ haS, use ⊥, intros b hb, exact bot_le } } end, le_Inf := λ S a haS, (with_top.is_glb_Inf' ⟨a, haS⟩).2 haS, ..with_top.lattice.has_Inf, ..with_top.lattice.has_Sup, ..with_top.lattice.bounded_lattice } end with_top_bot
6e47caa038d5d17cba1c474687ae2d58dd314d0f
f29cd213e19220aedf7c72ee6ac95ba61a73f452
/src/pullbacks.lean
96ee08a6a68b5075faf850d6024bc5e3ee60acc8
[]
no_license
EdAyers/topos
1e42c2514272bc53379c6534643c6be0dc28ab9c
349dac256403619869d01bc0f4c55048570cb61d
refs/heads/master
1,610,003,311,636
1,582,115,034,000
1,582,115,034,000
241,615,626
0
0
null
1,582,115,125,000
1,582,115,124,000
null
UTF-8
Lean
false
false
4,224
lean
import category_theory.limits.shapes.pullbacks namespace category_theory.limits open category_theory universes u v variables {C : Type u} [𝒞 : category.{v} C] variables {J K : Type v} [small_category J] [small_category K] include 𝒞 lemma cone.ext {F : J ⥤ C} : Π (c₁ c₂: cone F), (c₁.X = c₂.X) → (c₁.π == c₂.π) → c₁ = c₂ := begin rintros ⟨X₁,π₁⟩ ⟨X₂,π₂⟩ h₁ h₂, cases h₁, cases h₂, refl, end variables {L X Y Z : C} {f : X ⟶ Z} {g : Y ⟶ Z} {lx : L ⟶ X} {ly : L ⟶ Y} {e : lx ≫ f = ly ≫ g} @[simp] def pullback_cone.simp_left : ((pullback_cone.mk lx ly e).π).app walking_cospan.left = lx := by refl @[simp] def pullback_cone.simp_right : ((pullback_cone.mk lx ly e).π).app walking_cospan.right = ly := by refl @[simp] lemma limit.lift_self_id (F : J ⥤ C) [has_limit F] : limit.lift F (limit.cone F) = 𝟙 (limit F) := begin symmetry, refine is_limit.uniq' _ _ _ _, intro j, simp, rw [category.id_comp _ (limit.π F j)] end lemma pullback.hom_ext {X Y Z A : C} {f : X ⟶ Z} {g : Y ⟶ Z} [has_limit (cospan f g)] (a b : A ⟶ pullback f g) (h1 : a ≫ pullback.fst = b ≫ pullback.fst) (h2 : a ≫ pullback.snd = b ≫ pullback.snd) : a = b := begin apply limit.hom_ext, intro j, cases j, apply h1, apply h2, have c, apply @pullback.condition _ _ _ _ _ f g _, have xx : _ ≫ _ = limits.limit.π (cospan f g) walking_cospan.one, apply limits.limit.w (cospan f g) walking_cospan.hom.inl, rw ← xx, rw ← category.assoc, rw h1, simp, end @[simp] lemma pullback.lift_self_id {X Y Z : C} {f : X ⟶ Z} {g : Y ⟶ Z} [has_limit (cospan f g)] : @pullback.lift _ _ _ X Y Z f g _ pullback.fst pullback.snd pullback.condition = 𝟙 _ := begin rw ← limit.lift_self_id (cospan f g), dunfold pullback.lift limits.limit.cone pullback pullback_cone.mk pullback.fst pullback.snd limits.has_limit.cone limits.limit, congr, apply cone.ext, refl, simp, ext, cases x, refl, refl, apply limits.limit.w (cospan f g) walking_cospan.hom.inl, end /- Note that we need `has_pullbacks` even though this particular pullback always exists, because here we are showing that the constructive limit derived using has_pullbacks has to be iso to this simple definition. -/ lemma pullback.with_id_l [@has_pullbacks C 𝒞] {X Y : C} (f : X ⟶ Y) : pullback f (𝟙 Y) ≅ X := begin refine iso.mk (pullback.fst) (pullback.lift (𝟙 X) f (by simp)) _ _, apply pullback.hom_ext, simp, simp, rw pullback.condition, simp, simp, end /- [todo] find a way of showing this is iso to `pullback (𝟙 Y) f` -/ lemma pullback.with_id_r [@has_pullbacks C 𝒞] {X Y : C} (f : X ⟶ Y) : pullback (𝟙 Y) f ≅ X := begin refine iso.mk (pullback.snd) (pullback.lift f (𝟙 X) (by simp)) _ _, apply pullback.hom_ext, simp, rw ←pullback.condition, simp, simp, simp, end lemma pullback.comp_l {W X Y Z : C} {xz : X ⟶ Z} {yz : Y ⟶ Z} {wx : W ⟶ X} [@has_pullbacks C 𝒞]: pullback (wx ≫ xz) yz ≅ pullback wx (@pullback.fst _ _ _ _ _ xz yz _) := begin apply iso.mk _ _ _ _ , { refine pullback.lift pullback.fst (pullback.lift (pullback.fst ≫ wx) pullback.snd _) _, simp, rw pullback.condition, simp}, { refine pullback.lift pullback.fst (pullback.snd ≫ pullback.snd) _, rw ← category.assoc, rw pullback.condition, simp, rw pullback.condition }, {apply pullback.hom_ext, simp, simp }, {apply pullback.hom_ext, simp, simp, apply pullback.hom_ext, simp, apply pullback.condition, simp}, end -- [todo] comp_r; I was hoping there would be a cool way of lifting the isomorphism `(cospan f g).cones ≅ (cospan g f).cones` but can't see it. /-- Pullback of a monic is monic. -/ lemma pullback.preserve_mono [@has_pullbacks C 𝒞] {X Y Z : C} {f : X ⟶ Z} {g : Y ⟶ Z} (hm : @mono _ 𝒞 _ _ f) : @mono C 𝒞 (pullback f g) _ (pullback.snd) := begin split, intros A a b e, have c : pullback.fst ≫ f = pullback.snd ≫ g, apply pullback.condition, apply pullback.hom_ext, show a ≫ pullback.fst = b ≫ pullback.fst, apply hm.1, simp, rw c, rw ← category.assoc, rw e, simp, show a ≫ pullback.snd = b ≫ pullback.snd, assumption, end end category_theory.limits