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
2a756447c7e3c316ab9e21526d58dcc47e65c321
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/category_theory/endomorphism.lean
756d8b225e8fcf1e4de15643ed2c6ea952f9655e
[ "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
3,921
lean
/- Copyright (c) 2019 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudryashov, Scott Morrison, Simon Hudon -/ import category_theory.groupoid import data.equiv.mul_add /-! # Endomorphisms Definition and basic properties of endomorphisms and automorphisms of an object in a category. For each `X : C`, we provide `End X := X ⟶ X` with a monoid structure, and `Aut X := X ≅ X ` with a group structure. -/ universes v v' u u' namespace category_theory /-- Endomorphisms of an object in a category. Arguments order in multiplication agrees with `function.comp`, not with `category.comp`. -/ def End {C : Type u} [category_struct.{v} C] (X : C) := X ⟶ X namespace End section struct variables {C : Type u} [category_struct.{v} C] (X : C) instance has_one : has_one (End X) := ⟨𝟙 X⟩ instance inhabited : inhabited (End X) := ⟨𝟙 X⟩ /-- Multiplication of endomorphisms agrees with `function.comp`, not `category_struct.comp`. -/ instance has_mul : has_mul (End X) := ⟨λ x y, y ≫ x⟩ variable {X} /-- Assist the typechecker by expressing a morphism `X ⟶ X` as a term of `End X`. -/ def of (f : X ⟶ X) : End X := f /-- Assist the typechecker by expressing an endomorphism `f : End X` as a term of `X ⟶ X`. -/ def as_hom (f : End X) : X ⟶ X := f @[simp] lemma one_def : (1 : End X) = 𝟙 X := rfl @[simp] lemma mul_def (xs ys : End X) : xs * ys = ys ≫ xs := rfl end struct /-- Endomorphisms of an object form a monoid -/ instance monoid {C : Type u} [category.{v} C] {X : C} : monoid (End X) := { mul_one := category.id_comp, one_mul := category.comp_id, mul_assoc := λ x y z, (category.assoc z y x).symm, ..End.has_mul X, ..End.has_one X } /-- In a groupoid, endomorphisms form a group -/ instance group {C : Type u} [groupoid.{v} C] (X : C) : group (End X) := { mul_left_inv := groupoid.comp_inv, inv := groupoid.inv, ..End.monoid } end End lemma is_unit_iff_is_iso {C : Type u} [category.{v} C] {X : C} (f : End X) : is_unit (f : End X) ↔ is_iso f := ⟨λ h, { out := ⟨h.unit.inv, ⟨h.unit.inv_val, h.unit.val_inv⟩⟩ }, λ h, by exactI ⟨⟨f, inv f, by simp, by simp⟩, rfl⟩⟩ variables {C : Type u} [category.{v} C] (X : C) /-- Automorphisms of an object in a category. The order of arguments in multiplication agrees with `function.comp`, not with `category.comp`. -/ def Aut (X : C) := X ≅ X attribute [ext Aut] iso.ext namespace Aut instance inhabited : inhabited (Aut X) := ⟨iso.refl X⟩ instance : group (Aut X) := by refine_struct { one := iso.refl X, inv := iso.symm, mul := flip iso.trans, div := _, npow := @npow_rec (Aut X) ⟨iso.refl X⟩ ⟨flip iso.trans⟩, zpow := @zpow_rec (Aut X) ⟨iso.refl X⟩ ⟨flip iso.trans⟩ ⟨iso.symm⟩ }; intros; try { refl }; ext; simp [flip, (*), monoid.mul, mul_one_class.mul, mul_one_class.one, has_one.one, monoid.one, has_inv.inv] /-- Units in the monoid of endomorphisms of an object are (multiplicatively) equivalent to automorphisms of that object. -/ def units_End_equiv_Aut : units (End X) ≃* Aut X := { to_fun := λ f, ⟨f.1, f.2, f.4, f.3⟩, inv_fun := λ f, ⟨f.1, f.2, f.4, f.3⟩, left_inv := λ ⟨f₁, f₂, f₃, f₄⟩, rfl, right_inv := λ ⟨f₁, f₂, f₃, f₄⟩, rfl, map_mul' := λ f g, by rcases f; rcases g; refl } end Aut namespace functor variables {D : Type u'} [category.{v'} D] (f : C ⥤ D) (X) /-- `f.map` as a monoid hom between endomorphism monoids. -/ @[simps] def map_End : End X →* End (f.obj X) := { to_fun := functor.map f, map_mul' := λ x y, f.map_comp y x, map_one' := f.map_id X } /-- `f.map_iso` as a group hom between automorphism groups. -/ def map_Aut : Aut X →* Aut (f.obj X) := { to_fun := f.map_iso, map_mul' := λ x y, f.map_iso_trans y x, map_one' := f.map_iso_refl X } end functor end category_theory
7944016dbee7eb1045d35c4377c70b87e0ff56a6
c8af905dcd8475f414868d303b2eb0e9d3eb32f9
/src/data/cpi/semantics/relation.lean
d0af47dc3b2ea3121518add141b62ac47ac5f529
[ "BSD-3-Clause" ]
permissive
continuouspi/lean-cpi
81480a13842d67ff5f3698643210d8ed5dd08de4
443bf2cb236feadc45a01387099c236ab2b78237
refs/heads/master
1,650,307,316,582
1,587,033,364,000
1,587,033,364,000
207,499,661
1
0
null
null
null
null
UTF-8
Lean
false
false
6,480
lean
import data.cpi.process data.cpi.transition import data.multiset2 namespace cpi /-- Given two equivalent species, there is some isomorphism between species of the same kind and label, such that isomorphic transitions have equivalent productions. -/ @[nolint has_inhabited_instance] def has_iso {ℍ : Type} {ω Γ : context} [∀ Γ, setoid (species ℍ ω Γ)] [∀ Γ b y, setoid (concretion ℍ ω Γ b y)] {A B : species ℍ ω Γ} (ℓ : lookup ℍ ω Γ) : A ≈ B → Type | c := ∀ k (α : label ℍ Γ k) , Σ' (iso : (Σ E, A [ℓ, α]⟶ E) ≃ (Σ E, B [ℓ, α]⟶ E)) , ∀ E (t : A [ℓ, α]⟶ E), E ≈ (iso.to_fun ⟨ E, t ⟩).1 /-- An equivalence class over species and concretions, which allows for a notion of "prime decomposition". -/ class cpi_equiv (ℍ : Type) (ω : context) := [species_equiv {} : ∀ Γ, setoid (species ℍ ω Γ)] [concretion_equiv {} : ∀ Γ b y, setoid (concretion ℍ ω Γ b y)] [decide_species {} : ∀ Γ, decidable_rel (species_equiv Γ).r] [decide_concretion {} : ∀ Γ b y, decidable_rel (concretion_equiv Γ b y).r] /- Decompose a species into primes. -/ (prime_decompose {Γ} : species ℍ ω Γ → multiset (prime_species ℍ ω Γ)) ( prime_decompose_equiv {Γ} {A B : species ℍ ω Γ} : A ≈ B → multiset.map quotient.mk (prime_decompose A) = multiset.map quotient.mk (prime_decompose B) ) /- Prime decomposition of nil, returns an empty set. -/ (prime_decompose_nil {Γ} : prime_decompose (@species.nil ℍ ω Γ) = 0) ( prime_decompose_parallel {Γ} (A B : species ℍ ω Γ) : prime_decompose (A |ₛ B) = prime_decompose A + prime_decompose B ) ( prime_decompose_prime {Γ} (A : prime_species ℍ ω Γ) : prime_decompose A.val = [ A ] ) ( pseudo_apply {Γ} {a b : ℕ} : concretion' ℍ ω Γ a b → concretion' ℍ ω Γ b a → species' ℍ ω Γ ) namespace cpi_equiv instance to_species (ℍ : Type) (ω Γ : context) [r : cpi_equiv ℍ ω] : setoid (species ℍ ω Γ) := species_equiv Γ instance to_concretion (ℍ : Type) (ω Γ : context) (b y : ℕ) [r : cpi_equiv ℍ ω] : setoid (concretion ℍ ω Γ b y) := concretion_equiv Γ b y variables {ℍ : Type} {ω : context} [cpi_equiv ℍ ω] /-- `prime_decompose` lifted to quotients. -/ def prime_decompose' {Γ} : species' ℍ ω Γ → multiset (prime_species' ℍ ω Γ) | A := quot.lift_on A (multiset.map quotient.mk ∘ prime_decompose) (λ A B eq, prime_decompose_equiv eq) lemma prime_decompose_nil' {Γ} : prime_decompose' ⟦ @species.nil ℍ ω Γ ⟧ = 0 := begin show multiset.map quotient.mk (prime_decompose nil) = 0, rw [prime_decompose_nil, multiset.map_zero], end lemma prime_decompose_parallel' {Γ} (A B : species ℍ ω Γ) : prime_decompose' ⟦ A |ₛ B ⟧ = prime_decompose' ⟦ A ⟧ + prime_decompose' ⟦ B ⟧ := begin show multiset.map quotient.mk (prime_decompose (A |ₛ B)) = multiset.map quotient.mk (prime_decompose A) + multiset.map quotient.mk (prime_decompose B), rw [prime_decompose_parallel, multiset.map_add], end lemma prime_decompose_prime' {Γ} (A : prime_species' ℍ ω Γ) : prime_decompose' (prime_species.unwrap A) = [ A ] := quot.rec_on A (λ A, begin show multiset.map quotient.mk (prime_decompose A.val) = [ ⟦ A ⟧ ], simp only [prime_decompose_prime, multiset.coe_map, list.map_nil, multiset.coe_eq_coe, list.map], end) (λ a b _, rfl) end cpi_equiv /-- Additional properties that we need for some lemmas, but nothing else./ -/ class cpi_equiv_prop (ℍ : Type) (ω : context) extends cpi_equiv ℍ ω := /- Show our equivalence relation holds over transitions. Namely the transition sets are isomorphic, and have equivalent productions. -/ ( transition_iso {Γ} (ℓ : lookup ℍ ω Γ) {A B : species ℍ ω Γ} (eq : A ≈ B) : nonempty (has_iso ℓ eq) ) ( pseudo_apply_symm {Γ} {a b : ℕ} (F : concretion' ℍ ω Γ a b) (G : concretion' ℍ ω Γ b a) : pseudo_apply F G = pseudo_apply G F ) /-- Build an equivalent transition in the forward direction. -/ def cpi_equiv.transition_from_fwd {ℍ : Type} {ω Γ : context} [r : cpi_equiv ℍ ω] {A B : species ℍ ω Γ} {ℓ : lookup ℍ ω Γ} {eq : A ≈ B} : has_iso ℓ eq → transition.transition_from ℓ A → transition.transition_from ℓ B | iso ⟨ k, α, p ⟩ := ⟨ k, α, (iso k α).1.to_fun p ⟩ /-- Build an equivalent transition in the reverse direction. -/ def cpi_equiv.transition_from_inv {ℍ : Type} {ω Γ : context} [r : cpi_equiv ℍ ω] {A B : species ℍ ω Γ} {ℓ : lookup ℍ ω Γ} {eq : A ≈ B} : has_iso ℓ eq → transition.transition_from ℓ B → transition.transition_from ℓ A | iso ⟨ k, α, p ⟩ := ⟨ k, α, (iso k α).1.inv_fun p ⟩ /-- cpi_equiv.transition_iso, lifted to transition_from -/ def cpi_equiv_prop.transition_from_iso {ℍ : Type} {ω Γ : context} [r : cpi_equiv ℍ ω] {A B : species ℍ ω Γ} {ℓ : lookup ℍ ω Γ} {eq : A ≈ B} : has_iso ℓ eq → transition.transition_from ℓ A ≃ transition.transition_from ℓ B | iso := { to_fun := cpi_equiv.transition_from_fwd iso, inv_fun := cpi_equiv.transition_from_inv iso, left_inv := λ ⟨ k, α, p ⟩, begin simp only [cpi_equiv.transition_from_fwd, cpi_equiv.transition_from_inv], rw (iso k α).1.left_inv p end, right_inv := λ ⟨ k, α, p ⟩, begin simp only [cpi_equiv.transition_from_fwd, cpi_equiv.transition_from_inv], rw (iso k α).1.right_inv p end } instance species'.decidable_eq {ℍ ω Γ} [r : cpi_equiv ℍ ω] : decidable_eq (species' ℍ ω Γ) := @quotient.decidable_eq _ _ (cpi_equiv.decide_species Γ) instance concretion'.decidable_eq {ℍ ω Γ b y} [r : cpi_equiv ℍ ω] : decidable_eq (concretion' ℍ ω Γ b y) := @quotient.decidable_eq _ _ (cpi_equiv.decide_concretion Γ b y) /-- Determine if two prime species are equal. Effectively a decision procedure structural congruence. -/ instance prime'.decidable_eq {ℍ ω Γ} [r : cpi_equiv ℍ ω] : decidable_eq (prime_species' ℍ ω Γ) | A B := quotient.rec_on_subsingleton₂ A B (λ ⟨ a, _ ⟩ ⟨ b, _ ⟩, match cpi_equiv.decide_species Γ a b with | is_true h := is_true (quot.sound h) | is_false h := is_false (λ h', absurd (quotient.exact h') h) end) end cpi #lint-
1948f2ea90b4b900cf62ffcbddb0358cf90c6d0a
9dd3f3912f7321eb58ee9aa8f21778ad6221f87c
/library/init/native/ir.lean
269d8ac40888df0eeb88129abb868407d09e354a
[ "Apache-2.0" ]
permissive
bre7k30/lean
de893411bcfa7b3c5572e61b9e1c52951b310aa4
5a924699d076dab1bd5af23a8f910b433e598d7a
refs/heads/master
1,610,900,145,817
1,488,006,845,000
1,488,006,845,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
2,710
lean
/- Copyright (c) 2016 Jared Roesch. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jared Roesch -/ prelude import init.meta.name namespace ir inductive tag_ty | mk inductive ty | object : ty | ref : ty → ty | mut_ref : ty → ty | tag : tag_ty → ty → ty -- these are temporary | int : ty | object_buffer : ty | name : name → ty inductive literal | nat : nat → literal -- inductive value : Type -- | name : name → value -- | lit : literal → value -- TODO: eventually model ty.object, mk_object, project, etc in the IR itself mutual inductive expr, stmt with expr : Type | call : name → list name → expr | global : name → expr | lit : literal → expr | mk_object : nat → list name → expr | locl : name → expr | block : stmt → expr | project : name → nat → expr | panic : string → expr | mk_native_closure : name → list name → expr | invoke : name → list name → expr | assign : name → expr → expr | uninitialized : expr | constructor : name → list name → expr | address_of : name → expr -- hack for now, do in secon pass clean up | equals : expr → expr → expr | sub : expr → expr → expr | raw_int : nat → expr -- | value : value → expr with stmt : Type | ite : name → stmt → stmt → stmt | switch : name → list (nat × stmt) → stmt → stmt | letb : name → ty → expr → stmt → stmt | e : expr → stmt -- use a list here | seq : list stmt → stmt | return : expr → stmt | nop : stmt inductive defn | mk : name → list (name × ty) → ty → stmt → defn inductive decl | mk : name → list (name × ty) → ty → decl inductive item | defn : defn → item | decl : decl → item end ir -- def map (K V : Type) : Type := -- list (K × V) -- def lookup {K V} (key : K) (map : map K V) : option V := -- sorry -- def context := -- map name ir_decl -- inductive value -- | int : nat → value -- def local_context := -- map name ir_expr -- def call_fn (ctxt : context) (local_cx : local_context) (fn_name : name) (args : list name) : option ir_expr := -- sorry -- -- We fix the global context during evaluation. -- inductive step_expr (ctxt : context) : local_context → ir_expr → value → Prop -- | call : -- forall n args local_cx retval, -- call_fn ctxt local_cx n args = option.some retval → -- step_expr local_cx (ir_expr.call n args) retval -- | local_name : -- forall n e local_cx retval, -- lookup n local_cx = option.some e → -- step_expr local_cx n e -- inductive step_stmt : context → local_context → ir_stmt → ir_stmt → Prop -- | nop : forall ctxt local_ctxt, -- step_stmt ctxt local_ctxt nop nop -- |
4d8342360695d55d61de1547da56db8e49f6690b
d1a52c3f208fa42c41df8278c3d280f075eb020c
/tests/lean/run/struct1.lean
fecffe0ad84f59933202808a28fe511f1aeb4b88
[ "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
972
lean
structure A0.{u} (α : Type u) := (x : α) structure A.{u} (α : Type u) extends A0 α := (y : α) structure B.{u} (α : Type u) := (z : α) variable (β : Type _) variable (β' : Type _) universe u structure C.{v} (α : Type _) (δ : Type u) (η : Type v) extends A β, B α := mk2 :: (w : Nat := 10) #check C #check @C #check @C.mk2 #check { x := 10, y := 20, z := 30, w := 40 : C Nat Nat Nat Nat } #check C.recOn #check C.w #check fun (c : C Nat Nat Nat Nat) => c.x def f0 (c : C Nat Nat Nat Nat) : A Nat := c.toA def f1 (c : C Nat Nat Nat Nat) := c.x + c.w class Tst (α : Type u) extends Mul α := (comm : ∀ (a b : α), a * b = b * a) #check @Tst.comm #check @Tst.toMul def foo {α} [Tst α] (a b : α) := a * b #check { x := 10, y := 20, z := 30 : C Nat Nat Nat Nat } class Foo (α : Type u) extends Add α := (x : α) class Boo (α : Type u) extends Foo α := (y : α := x + x) #check @Boo.y._default #check { add := Nat.add, x := 10 : Boo Nat}
b1a278ac99c47cf77f588405f78901bbe62a5e2b
bbecf0f1968d1fba4124103e4f6b55251d08e9c4
/src/group_theory/submonoid/pointwise.lean
a43de2216ed5eac7d6d937f0ba16f9a41b28b238
[ "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,992
lean
/- Copyright (c) 2021 Eric Wieser. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Eric Wieser -/ import group_theory.submonoid.operations import algebra.pointwise /-! # Pointwise instances on `submonoid`s and `add_submonoid`s This file provides the actions * `submonoid.pointwise_mul_action` * `add_submonoid.pointwise_mul_action` which matches the action of `mul_action_set`. These actions are available in the `pointwise` locale. ## Implementation notes Most of the lemmas in this file are direct copies of lemmas from `algebra/pointwise.lean`. While the statements of these lemmas are defeq, we repeat them here due to them not being syntactically equal. Before adding new lemmas here, consider if they would also apply to the action on `set`s. -/ variables {α : Type*} {M : Type*} {A : Type*} [monoid M] [add_monoid A] namespace submonoid section monoid variables [monoid α] [mul_distrib_mul_action α M] /-- The action on a submonoid corresponding to applying the action to every element. This is available as an instance in the `pointwise` locale. -/ protected def pointwise_mul_action : mul_action α (submonoid M) := { smul := λ a S, S.map (mul_distrib_mul_action.to_monoid_End _ _ a), one_smul := λ S, (congr_arg (λ f, S.map f) (monoid_hom.map_one _)).trans S.map_id, mul_smul := λ a₁ a₂ S, (congr_arg (λ f, S.map f) (monoid_hom.map_mul _ _ _)).trans (S.map_map _ _).symm,} localized "attribute [instance] submonoid.pointwise_mul_action" in pointwise open_locale pointwise @[simp] lemma coe_pointwise_smul (a : α) (S : submonoid M) : ↑(a • S) = a • (S : set M) := rfl lemma smul_mem_pointwise_smul (m : M) (a : α) (S : submonoid M) : m ∈ S → a • m ∈ a • S := (set.smul_mem_smul_set : _ → _ ∈ a • (S : set M)) end monoid section group variables [group α] [mul_distrib_mul_action α M] open_locale pointwise @[simp] lemma smul_mem_pointwise_smul_iff {a : α} {S : submonoid M} {x : M} : a • x ∈ a • S ↔ x ∈ S := smul_mem_smul_set_iff lemma mem_pointwise_smul_iff_inv_smul_mem {a : α} {S : submonoid M} {x : M} : x ∈ a • S ↔ a⁻¹ • x ∈ S := mem_smul_set_iff_inv_smul_mem lemma mem_inv_pointwise_smul_iff {a : α} {S : submonoid M} {x : M} : x ∈ a⁻¹ • S ↔ a • x ∈ S := mem_inv_smul_set_iff @[simp] lemma pointwise_smul_le_pointwise_smul_iff {a : α} {S T : submonoid M} : a • S ≤ a • T ↔ S ≤ T := set_smul_subset_set_smul_iff lemma pointwise_smul_subset_iff {a : α} {S T : submonoid M} : a • S ≤ T ↔ S ≤ a⁻¹ • T := set_smul_subset_iff lemma subset_pointwise_smul_iff {a : α} {S T : submonoid M} : S ≤ a • T ↔ a⁻¹ • S ≤ T := subset_set_smul_iff end group section group_with_zero variables [group_with_zero α] [mul_distrib_mul_action α M] open_locale pointwise @[simp] lemma smul_mem_pointwise_smul_iff₀ {a : α} (ha : a ≠ 0) (S : submonoid M) (x : M) : a • x ∈ a • S ↔ x ∈ S := smul_mem_smul_set_iff₀ ha (S : set M) x lemma mem_pointwise_smul_iff_inv_smul_mem₀ {a : α} (ha : a ≠ 0) (S : submonoid M) (x : M) : x ∈ a • S ↔ a⁻¹ • x ∈ S := mem_smul_set_iff_inv_smul_mem₀ ha (S : set M) x lemma mem_inv_pointwise_smul_iff₀ {a : α} (ha : a ≠ 0) (S : submonoid M) (x : M) : x ∈ a⁻¹ • S ↔ a • x ∈ S := mem_inv_smul_set_iff₀ ha (S : set M) x @[simp] lemma pointwise_smul_le_pointwise_smul_iff₀ {a : α} (ha : a ≠ 0) {S T : submonoid M} : a • S ≤ a • T ↔ S ≤ T := set_smul_subset_set_smul_iff₀ ha lemma pointwise_smul_le_iff₀ {a : α} (ha : a ≠ 0) {S T : submonoid M} : a • S ≤ T ↔ S ≤ a⁻¹ • T := set_smul_subset_iff₀ ha lemma le_pointwise_smul_iff₀ {a : α} (ha : a ≠ 0) {S T : submonoid M} : S ≤ a • T ↔ a⁻¹ • S ≤ T := subset_set_smul_iff₀ ha end group_with_zero end submonoid namespace add_submonoid section monoid variables [monoid α] [distrib_mul_action α A] /-- The action on an additive submonoid corresponding to applying the action to every element. This is available as an instance in the `pointwise` locale. -/ protected def pointwise_mul_action : mul_action α (add_submonoid A) := { smul := λ a S, S.map (distrib_mul_action.to_add_monoid_End _ _ a), one_smul := λ S, (congr_arg (λ f, S.map f) (monoid_hom.map_one _)).trans S.map_id, mul_smul := λ a₁ a₂ S, (congr_arg (λ f, S.map f) (monoid_hom.map_mul _ _ _)).trans (S.map_map _ _).symm,} localized "attribute [instance] add_submonoid.pointwise_mul_action" in pointwise open_locale pointwise @[simp] lemma coe_pointwise_smul (a : α) (S : add_submonoid A) : ↑(a • S) = a • (S : set A) := rfl lemma smul_mem_pointwise_smul (m : A) (a : α) (S : add_submonoid A) : m ∈ S → a • m ∈ a • S := (set.smul_mem_smul_set : _ → _ ∈ a • (S : set A)) end monoid section group variables [group α] [distrib_mul_action α A] open_locale pointwise @[simp] lemma smul_mem_pointwise_smul_iff {a : α} {S : add_submonoid A} {x : A} : a • x ∈ a • S ↔ x ∈ S := smul_mem_smul_set_iff lemma mem_pointwise_smul_iff_inv_smul_mem {a : α} {S : add_submonoid A} {x : A} : x ∈ a • S ↔ a⁻¹ • x ∈ S := mem_smul_set_iff_inv_smul_mem lemma mem_inv_pointwise_smul_iff {a : α} {S : add_submonoid A} {x : A} : x ∈ a⁻¹ • S ↔ a • x ∈ S := mem_inv_smul_set_iff @[simp] lemma pointwise_smul_le_pointwise_smul_iff {a : α} {S T : add_submonoid A} : a • S ≤ a • T ↔ S ≤ T := set_smul_subset_set_smul_iff lemma pointwise_smul_le_iff {a : α} {S T : add_submonoid A} : a • S ≤ T ↔ S ≤ a⁻¹ • T := set_smul_subset_iff lemma le_pointwise_smul_iff {a : α} {S T : add_submonoid A} : S ≤ a • T ↔ a⁻¹ • S ≤ T := subset_set_smul_iff end group section group_with_zero variables [group_with_zero α] [distrib_mul_action α A] open_locale pointwise @[simp] lemma smul_mem_pointwise_smul_iff₀ {a : α} (ha : a ≠ 0) (S : add_submonoid A) (x : A) : a • x ∈ a • S ↔ x ∈ S := smul_mem_smul_set_iff₀ ha (S : set A) x lemma mem_pointwise_smul_iff_inv_smul_mem₀ {a : α} (ha : a ≠ 0) (S : add_submonoid A) (x : A) : x ∈ a • S ↔ a⁻¹ • x ∈ S := mem_smul_set_iff_inv_smul_mem₀ ha (S : set A) x lemma mem_inv_pointwise_smul_iff₀ {a : α} (ha : a ≠ 0) (S : add_submonoid A) (x : A) : x ∈ a⁻¹ • S ↔ a • x ∈ S := mem_inv_smul_set_iff₀ ha (S : set A) x @[simp] lemma pointwise_smul_le_pointwise_smul_iff₀ {a : α} (ha : a ≠ 0) {S T : add_submonoid A} : a • S ≤ a • T ↔ S ≤ T := set_smul_subset_set_smul_iff₀ ha lemma pointwise_smul_le_iff₀ {a : α} (ha : a ≠ 0) {S T : add_submonoid A} : a • S ≤ T ↔ S ≤ a⁻¹ • T := set_smul_subset_iff₀ ha lemma le_pointwise_smul_iff₀ {a : α} (ha : a ≠ 0) {S T : add_submonoid A} : S ≤ a • T ↔ a⁻¹ • S ≤ T := subset_set_smul_iff₀ ha end group_with_zero end add_submonoid
29538a4ee925a61c628b72f277068b2ef57710db
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/data/multiset/intervals.lean
12221adaf3eb7325aac1e0725caf3d507326891a
[]
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
4,174
lean
/- Copyright (c) 2019 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.data.multiset.nodup import Mathlib.data.list.intervals import Mathlib.PostPort namespace Mathlib /-! # Intervals in ℕ as multisets For now this only covers `Ico n m`, the "closed-open" interval containing `[n, ..., m-1]`. -/ namespace multiset /-! ### Ico -/ /-- `Ico n m` is the multiset lifted from the list `Ico n m`, e.g. the set `{n, n+1, ..., m-1}`. -/ def Ico (n : ℕ) (m : ℕ) : multiset ℕ := ↑(list.Ico n m) namespace Ico theorem map_add (n : ℕ) (m : ℕ) (k : ℕ) : map (Add.add k) (Ico n m) = Ico (n + k) (m + k) := congr_arg coe (list.Ico.map_add n m k) theorem map_sub (n : ℕ) (m : ℕ) (k : ℕ) (h : k ≤ n) : map (fun (x : ℕ) => x - k) (Ico n m) = Ico (n - k) (m - k) := congr_arg coe (list.Ico.map_sub n m k h) theorem zero_bot (n : ℕ) : Ico 0 n = range n := congr_arg coe (list.Ico.zero_bot n) @[simp] theorem card (n : ℕ) (m : ℕ) : coe_fn card (Ico n m) = m - n := list.Ico.length n m theorem nodup (n : ℕ) (m : ℕ) : nodup (Ico n m) := list.Ico.nodup n m @[simp] theorem mem {n : ℕ} {m : ℕ} {l : ℕ} : l ∈ Ico n m ↔ n ≤ l ∧ l < m := list.Ico.mem theorem eq_zero_of_le {n : ℕ} {m : ℕ} (h : m ≤ n) : Ico n m = 0 := congr_arg coe (list.Ico.eq_nil_of_le h) @[simp] theorem self_eq_zero {n : ℕ} : Ico n n = 0 := eq_zero_of_le (le_refl n) @[simp] theorem eq_zero_iff {n : ℕ} {m : ℕ} : Ico n m = 0 ↔ m ≤ n := iff.trans (coe_eq_zero (list.Ico n m)) list.Ico.eq_empty_iff theorem add_consecutive {n : ℕ} {m : ℕ} {l : ℕ} (hnm : n ≤ m) (hml : m ≤ l) : Ico n m + Ico m l = Ico n l := congr_arg coe (list.Ico.append_consecutive hnm hml) @[simp] theorem inter_consecutive (n : ℕ) (m : ℕ) (l : ℕ) : Ico n m ∩ Ico m l = 0 := congr_arg coe (list.Ico.bag_inter_consecutive n m l) @[simp] theorem succ_singleton {n : ℕ} : Ico n (n + 1) = singleton n := congr_arg coe list.Ico.succ_singleton theorem succ_top {n : ℕ} {m : ℕ} (h : n ≤ m) : Ico n (m + 1) = m ::ₘ Ico n m := sorry theorem eq_cons {n : ℕ} {m : ℕ} (h : n < m) : Ico n m = n ::ₘ Ico (n + 1) m := congr_arg coe (list.Ico.eq_cons h) @[simp] theorem pred_singleton {m : ℕ} (h : 0 < m) : Ico (m - 1) m = singleton (m - 1) := congr_arg coe (list.Ico.pred_singleton h) @[simp] theorem not_mem_top {n : ℕ} {m : ℕ} : ¬m ∈ Ico n m := list.Ico.not_mem_top theorem filter_lt_of_top_le {n : ℕ} {m : ℕ} {l : ℕ} (hml : m ≤ l) : filter (fun (x : ℕ) => x < l) (Ico n m) = Ico n m := congr_arg coe (list.Ico.filter_lt_of_top_le hml) theorem filter_lt_of_le_bot {n : ℕ} {m : ℕ} {l : ℕ} (hln : l ≤ n) : filter (fun (x : ℕ) => x < l) (Ico n m) = ∅ := congr_arg coe (list.Ico.filter_lt_of_le_bot hln) theorem filter_le_of_bot {n : ℕ} {m : ℕ} (hnm : n < m) : filter (fun (x : ℕ) => x ≤ n) (Ico n m) = singleton n := congr_arg coe (list.Ico.filter_le_of_bot hnm) theorem filter_lt_of_ge {n : ℕ} {m : ℕ} {l : ℕ} (hlm : l ≤ m) : filter (fun (x : ℕ) => x < l) (Ico n m) = Ico n l := congr_arg coe (list.Ico.filter_lt_of_ge hlm) @[simp] theorem filter_lt (n : ℕ) (m : ℕ) (l : ℕ) : filter (fun (x : ℕ) => x < l) (Ico n m) = Ico n (min m l) := congr_arg coe (list.Ico.filter_lt n m l) theorem filter_le_of_le_bot {n : ℕ} {m : ℕ} {l : ℕ} (hln : l ≤ n) : filter (fun (x : ℕ) => l ≤ x) (Ico n m) = Ico n m := congr_arg coe (list.Ico.filter_le_of_le_bot hln) theorem filter_le_of_top_le {n : ℕ} {m : ℕ} {l : ℕ} (hml : m ≤ l) : filter (fun (x : ℕ) => l ≤ x) (Ico n m) = ∅ := congr_arg coe (list.Ico.filter_le_of_top_le hml) theorem filter_le_of_le {n : ℕ} {m : ℕ} {l : ℕ} (hnl : n ≤ l) : filter (fun (x : ℕ) => l ≤ x) (Ico n m) = Ico l m := congr_arg coe (list.Ico.filter_le_of_le hnl) @[simp] theorem filter_le (n : ℕ) (m : ℕ) (l : ℕ) : filter (fun (x : ℕ) => l ≤ x) (Ico n m) = Ico (max n l) m := congr_arg coe (list.Ico.filter_le n m l)
9326330efef836ad36298ecc9450f480cf498dbb
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/field_theory/adjoin.lean
d6209b0b27df5303c54b8124075aec79c1b859ed
[]
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
28,859
lean
/- Copyright (c) 2020 Thomas Browning and Patrick Lutz. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Thomas Browning and Patrick Lutz -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.field_theory.intermediate_field import Mathlib.field_theory.splitting_field import Mathlib.field_theory.separable import Mathlib.PostPort universes u_1 u_2 u_3 l namespace Mathlib /-! # Adjoining Elements to Fields In this file we introduce the notion of adjoining elements to fields. This isn't quite the same as adjoining elements to rings. For example, `algebra.adjoin K {x}` might not include `x⁻¹`. ## Main results - `adjoin_adjoin_left`: adjoining S and then T is the same as adjoining `S ∪ T`. - `bot_eq_top_of_dim_adjoin_eq_one`: if `F⟮x⟯` has dimension `1` over `F` for every `x` in `E` then `F = E` ## Notation - `F⟮α⟯`: adjoin a single element `α` to `F`. -/ namespace intermediate_field /-- `adjoin F S` extends a field `F` by adjoining a set `S ⊆ E`. -/ def adjoin (F : Type u_1) [field F] {E : Type u_2} [field E] [algebra F E] (S : set E) : intermediate_field F E := mk (subfield.carrier (subfield.closure (set.range ⇑(algebra_map F E) ∪ S))) sorry sorry sorry sorry sorry sorry sorry @[simp] theorem adjoin_le_iff {F : Type u_1} [field F] {E : Type u_2} [field E] [algebra F E] {S : set E} {T : intermediate_field F E} : adjoin F S ≤ T ↔ S ≤ ↑T := sorry theorem gc {F : Type u_1} [field F] {E : Type u_2} [field E] [algebra F E] : galois_connection (adjoin F) coe := fun (_x : set E) (_x_1 : intermediate_field F E) => adjoin_le_iff /-- Galois insertion between `adjoin` and `coe`. -/ def gi {F : Type u_1} [field F] {E : Type u_2} [field E] [algebra F E] : galois_insertion (adjoin F) coe := galois_insertion.mk (fun (S : set E) (_x : ↑(adjoin F S) ≤ S) => adjoin F S) gc sorry sorry protected instance complete_lattice {F : Type u_1} [field F] {E : Type u_2} [field E] [algebra F E] : complete_lattice (intermediate_field F E) := galois_insertion.lift_complete_lattice gi protected instance inhabited {F : Type u_1} [field F] {E : Type u_2} [field E] [algebra F E] : Inhabited (intermediate_field F E) := { default := ⊤ } theorem mem_bot {F : Type u_1} [field F] {E : Type u_2} [field E] [algebra F E] {x : E} : x ∈ ⊥ ↔ x ∈ set.range ⇑(algebra_map F E) := sorry theorem mem_top {F : Type u_1} [field F] {E : Type u_2} [field E] [algebra F E] {x : E} : x ∈ ⊤ := subfield.subset_closure (Or.inr trivial) @[simp] theorem bot_to_subalgebra {F : Type u_1} [field F] {E : Type u_2} [field E] [algebra F E] : to_subalgebra ⊥ = ⊥ := sorry @[simp] theorem top_to_subalgebra {F : Type u_1} [field F] {E : Type u_2} [field E] [algebra F E] : to_subalgebra ⊤ = ⊤ := sorry /-- Construct an algebra isomorphism from an equality of subalgebras -/ def subalgebra.equiv_of_eq {F : Type u_1} [field F] {E : Type u_2} [field E] [algebra F E] {X : subalgebra F E} {Y : subalgebra F E} (h : X = Y) : alg_equiv F ↥X ↥Y := alg_equiv.mk (fun (x : ↥X) => { val := ↑x, property := sorry }) (fun (x : ↥Y) => { val := ↑x, property := sorry }) sorry sorry sorry sorry sorry /-- The bottom intermediate_field is isomorphic to the field. -/ def bot_equiv {F : Type u_1} [field F] {E : Type u_2} [field E] [algebra F E] : alg_equiv F (↥⊥) F := alg_equiv.trans (subalgebra.equiv_of_eq bot_to_subalgebra) (algebra.bot_equiv F E) @[simp] theorem bot_equiv_def {F : Type u_1} [field F] {E : Type u_2} [field E] [algebra F E] (x : F) : coe_fn bot_equiv (coe_fn (algebra_map F ↥⊥) x) = x := alg_equiv.commutes bot_equiv x protected instance algebra_over_bot {F : Type u_1} [field F] {E : Type u_2} [field E] [algebra F E] : algebra (↥⊥) F := ring_hom.to_algebra (alg_hom.to_ring_hom (alg_equiv.to_alg_hom bot_equiv)) protected instance is_scalar_tower_over_bot {F : Type u_1} [field F] {E : Type u_2} [field E] [algebra F E] : is_scalar_tower (↥⊥) F E := is_scalar_tower.of_algebra_map_eq fun (x : ↥⊥) => let ϕ : alg_hom F F ↥⊥ := algebra.of_id F ↥⊥; let ψ : alg_equiv F F ↥⊥ := alg_equiv.of_bijective ϕ (alg_equiv.bijective (alg_equiv.symm (algebra.bot_equiv F E))); id (eq.mpr (id (Eq._oldrec (Eq.refl (↑x = ↑(coe_fn ψ (coe_fn (alg_equiv.symm ψ) { val := ↑x, property := subalgebra.equiv_of_eq._proof_1 bot_to_subalgebra x })))) (alg_equiv.apply_symm_apply ψ { val := ↑x, property := subalgebra.equiv_of_eq._proof_1 bot_to_subalgebra x }))) (Eq.refl ↑x)) /-- The top intermediate_field is isomorphic to the field. -/ def top_equiv {F : Type u_1} [field F] {E : Type u_2} [field E] [algebra F E] : alg_equiv F (↥⊤) E := alg_equiv.trans (subalgebra.equiv_of_eq top_to_subalgebra) algebra.top_equiv @[simp] theorem top_equiv_def {F : Type u_1} [field F] {E : Type u_2} [field E] [algebra F E] (x : ↥⊤) : coe_fn top_equiv x = ↑x := sorry @[simp] theorem coe_bot_eq_self {F : Type u_1} [field F] {E : Type u_2} [field E] [algebra F E] (K : intermediate_field F E) : ↑⊥ = K := sorry @[simp] theorem coe_top_eq_top {F : Type u_1} [field F] {E : Type u_2} [field E] [algebra F E] (K : intermediate_field F E) : ↑⊤ = ⊤ := iff.mpr intermediate_field.ext'_iff (iff.mpr set.ext_iff fun (_x : E) => iff_of_true mem_top mem_top) theorem adjoin_eq_range_algebra_map_adjoin (F : Type u_1) [field F] {E : Type u_2} [field E] [algebra F E] (S : set E) : ↑(adjoin F S) = set.range ⇑(algebra_map (↥(adjoin F S)) E) := Eq.symm subtype.range_coe theorem adjoin.algebra_map_mem (F : Type u_1) [field F] {E : Type u_2} [field E] [algebra F E] (S : set E) (x : F) : coe_fn (algebra_map F E) x ∈ adjoin F S := algebra_map_mem (adjoin F S) x theorem adjoin.range_algebra_map_subset (F : Type u_1) [field F] {E : Type u_2} [field E] [algebra F E] (S : set E) : set.range ⇑(algebra_map F E) ⊆ ↑(adjoin F S) := sorry protected instance adjoin.field_coe (F : Type u_1) [field F] {E : Type u_2} [field E] [algebra F E] (S : set E) : has_coe_t F ↥(adjoin F S) := has_coe_t.mk fun (x : F) => { val := coe_fn (algebra_map F E) x, property := adjoin.algebra_map_mem F S x } theorem subset_adjoin (F : Type u_1) [field F] {E : Type u_2} [field E] [algebra F E] (S : set E) : S ⊆ ↑(adjoin F S) := fun (x : E) (hx : x ∈ S) => subfield.subset_closure (Or.inr hx) protected instance adjoin.set_coe (F : Type u_1) [field F] {E : Type u_2} [field E] [algebra F E] (S : set E) : has_coe_t ↥S ↥(adjoin F S) := has_coe_t.mk fun (x : ↥S) => { val := ↑x, property := sorry } theorem adjoin.mono (F : Type u_1) [field F] {E : Type u_2} [field E] [algebra F E] (S : set E) (T : set E) (h : S ⊆ T) : adjoin F S ≤ adjoin F T := galois_connection.monotone_l gc h theorem adjoin_contains_field_as_subfield {E : Type u_2} [field E] (S : set E) (F : subfield E) : ↑F ⊆ ↑(adjoin (↥F) S) := fun (x : E) (hx : x ∈ ↑F) => adjoin.algebra_map_mem (↥F) S { val := x, property := hx } theorem subset_adjoin_of_subset_left {E : Type u_2} [field E] (S : set E) {F : subfield E} {T : set E} (HT : T ⊆ ↑F) : T ⊆ ↑(adjoin (↥F) S) := fun (x : E) (hx : x ∈ T) => algebra_map_mem (adjoin (↥F) S) { val := x, property := HT hx } theorem subset_adjoin_of_subset_right (F : Type u_1) [field F] {E : Type u_2} [field E] [algebra F E] (S : set E) {T : set E} (H : T ⊆ S) : T ⊆ ↑(adjoin F S) := fun (x : E) (hx : x ∈ T) => subset_adjoin F S (H hx) @[simp] theorem adjoin_empty (F : Type u_1) (E : Type u_2) [field F] [field E] [algebra F E] : adjoin F ∅ = ⊥ := iff.mpr eq_bot_iff (iff.mpr adjoin_le_iff (set.empty_subset ↑⊥)) /-- If `K` is a field with `F ⊆ K` and `S ⊆ K` then `adjoin F S ≤ K`. -/ theorem adjoin_le_subfield (F : Type u_1) [field F] {E : Type u_2} [field E] [algebra F E] (S : set E) {K : subfield E} (HF : set.range ⇑(algebra_map F E) ⊆ ↑K) (HS : S ⊆ ↑K) : to_subfield (adjoin F S) ≤ K := iff.mpr subfield.closure_le (eq.mpr (id (Eq._oldrec (Eq.refl (set.range ⇑(algebra_map F E) ∪ S ⊆ ↑K)) (propext set.union_subset_iff))) { left := HF, right := HS }) theorem adjoin_subset_adjoin_iff (F : Type u_1) [field F] {E : Type u_2} [field E] [algebra F E] {F' : Type u_3} [field F'] [algebra F' E] {S : set E} {S' : set E} : ↑(adjoin F S) ⊆ ↑(adjoin F' S') ↔ set.range ⇑(algebra_map F E) ⊆ ↑(adjoin F' S') ∧ S ⊆ ↑(adjoin F' S') := sorry /-- `F[S][T] = F[S ∪ T]` -/ theorem adjoin_adjoin_left (F : Type u_1) [field F] {E : Type u_2} [field E] [algebra F E] (S : set E) (T : set E) : ↑(adjoin (↥(adjoin F S)) T) = adjoin F (S ∪ T) := sorry @[simp] theorem adjoin_insert_adjoin (F : Type u_1) [field F] {E : Type u_2} [field E] [algebra F E] (S : set E) (x : E) : adjoin F (insert x ↑(adjoin F S)) = adjoin F (insert x S) := sorry /-- `F[S][T] = F[T][S]` -/ theorem adjoin_adjoin_comm (F : Type u_1) [field F] {E : Type u_2} [field E] [algebra F E] (S : set E) (T : set E) : ↑(adjoin (↥(adjoin F S)) T) = ↑(adjoin (↥(adjoin F T)) S) := sorry theorem adjoin_map (F : Type u_1) [field F] {E : Type u_2} [field E] [algebra F E] (S : set E) {E' : Type u_3} [field E'] [algebra F E'] (f : alg_hom F E E') : map (adjoin F S) f = adjoin F (⇑f '' S) := sorry theorem algebra_adjoin_le_adjoin (F : Type u_1) [field F] {E : Type u_2} [field E] [algebra F E] (S : set E) : algebra.adjoin F S ≤ to_subalgebra (adjoin F S) := algebra.adjoin_le (subset_adjoin F S) theorem adjoin_eq_algebra_adjoin (F : Type u_1) [field F] {E : Type u_2} [field E] [algebra F E] (S : set E) (inv_mem : ∀ (x : E), x ∈ algebra.adjoin F S → x⁻¹ ∈ algebra.adjoin F S) : to_subalgebra (adjoin F S) = algebra.adjoin F S := sorry theorem eq_adjoin_of_eq_algebra_adjoin (F : Type u_1) [field F] {E : Type u_2} [field E] [algebra F E] (S : set E) (K : intermediate_field F E) (h : to_subalgebra K = algebra.adjoin F S) : K = adjoin F S := sorry theorem adjoin_induction (F : Type u_1) [field F] {E : Type u_2} [field E] [algebra F E] {s : set E} {p : E → Prop} {x : E} (h : x ∈ adjoin F s) (Hs : ∀ (x : E), x ∈ s → p x) (Hmap : ∀ (x : F), p (coe_fn (algebra_map F E) x)) (Hadd : ∀ (x y : E), p x → p y → p (x + y)) (Hneg : ∀ (x : E), p x → p (-x)) (Hinv : ∀ (x : E), p x → p (x⁻¹)) (Hmul : ∀ (x y : E), p x → p y → p (x * y)) : p x := sorry /-- Variation on `set.insert` to enable good notation for adjoining elements to fields. Used to preferentially use `singleton` rather than `insert` when adjoining one element. -/ --this definition of notation is courtesy of Kyle Miller on zulip class insert {α : Type u_3} (s : set α) where insert : α → set α protected instance insert_empty {α : Type u_1} : insert ∅ := insert.mk fun (x : α) => singleton x protected instance insert_nonempty {α : Type u_1} (s : set α) : insert s := insert.mk fun (x : α) => set.insert x s theorem mem_adjoin_simple_self (F : Type u_1) [field F] {E : Type u_2} [field E] [algebra F E] (α : E) : α ∈ adjoin F (insert.insert ∅ α) := subset_adjoin F (singleton α) (set.mem_singleton α) /-- generator of `F⟮α⟯` -/ def adjoin_simple.gen (F : Type u_1) [field F] {E : Type u_2} [field E] [algebra F E] (α : E) : ↥(adjoin F (insert.insert ∅ α)) := { val := α, property := mem_adjoin_simple_self F α } @[simp] theorem adjoin_simple.algebra_map_gen (F : Type u_1) [field F] {E : Type u_2} [field E] [algebra F E] (α : E) : coe_fn (algebra_map (↥(adjoin F (insert.insert ∅ α))) E) (adjoin_simple.gen F α) = α := rfl theorem adjoin_simple_adjoin_simple (F : Type u_1) [field F] {E : Type u_2} [field E] [algebra F E] (α : E) (β : E) : ↑(adjoin (↥(adjoin F (insert.insert ∅ α))) (insert.insert ∅ β)) = adjoin F (insert.insert (insert.insert ∅ β) α) := adjoin_adjoin_left F (insert.insert ∅ α) (insert.insert ∅ β) theorem adjoin_simple_comm (F : Type u_1) [field F] {E : Type u_2} [field E] [algebra F E] (α : E) (β : E) : ↑(adjoin (↥(adjoin F (insert.insert ∅ α))) (insert.insert ∅ β)) = ↑(adjoin (↥(adjoin F (insert.insert ∅ β))) (insert.insert ∅ α)) := adjoin_adjoin_comm F (insert.insert ∅ α) (insert.insert ∅ β) -- TODO: develop the API for `subalgebra.is_field_of_algebraic` so it can be used here theorem adjoin_simple_to_subalgebra_of_integral (F : Type u_1) [field F] {E : Type u_2} [field E] [algebra F E] (α : E) (hα : is_integral F α) : to_subalgebra (adjoin F (insert.insert ∅ α)) = algebra.adjoin F (singleton α) := sorry @[simp] theorem adjoin_eq_bot_iff {F : Type u_1} [field F] {E : Type u_2} [field E] [algebra F E] {S : set E} : adjoin F S = ⊥ ↔ S ⊆ ↑⊥ := eq.mpr (id (Eq._oldrec (Eq.refl (adjoin F S = ⊥ ↔ S ⊆ ↑⊥)) (propext eq_bot_iff))) (eq.mpr (id (Eq._oldrec (Eq.refl (adjoin F S ≤ ⊥ ↔ S ⊆ ↑⊥)) (propext adjoin_le_iff))) (iff.refl (S ≤ ↑⊥))) @[simp] theorem adjoin_simple_eq_bot_iff {F : Type u_1} [field F] {E : Type u_2} [field E] [algebra F E] {α : E} : adjoin F (insert.insert ∅ α) = ⊥ ↔ α ∈ ⊥ := eq.mpr (id (Eq._oldrec (Eq.refl (adjoin F (insert.insert ∅ α) = ⊥ ↔ α ∈ ⊥)) (propext adjoin_eq_bot_iff))) set.singleton_subset_iff @[simp] theorem adjoin_zero {F : Type u_1} [field F] {E : Type u_2} [field E] [algebra F E] : adjoin F (insert.insert ∅ 0) = ⊥ := iff.mpr adjoin_simple_eq_bot_iff (zero_mem ⊥) @[simp] theorem adjoin_one {F : Type u_1} [field F] {E : Type u_2} [field E] [algebra F E] : adjoin F (insert.insert ∅ 1) = ⊥ := iff.mpr adjoin_simple_eq_bot_iff (one_mem ⊥) @[simp] theorem adjoin_int {F : Type u_1} [field F] {E : Type u_2} [field E] [algebra F E] (n : ℤ) : adjoin F (insert.insert ∅ ↑n) = ⊥ := iff.mpr adjoin_simple_eq_bot_iff (coe_int_mem ⊥ n) @[simp] theorem adjoin_nat {F : Type u_1} [field F] {E : Type u_2} [field E] [algebra F E] (n : ℕ) : adjoin F (insert.insert ∅ ↑n) = ⊥ := iff.mpr adjoin_simple_eq_bot_iff (coe_int_mem ⊥ ↑n) @[simp] theorem dim_eq_one_iff {F : Type u_1} [field F] {E : Type u_2} [field E] [algebra F E] {K : intermediate_field F E} : vector_space.dim F ↥K = 1 ↔ K = ⊥ := sorry @[simp] theorem findim_eq_one_iff {F : Type u_1} [field F] {E : Type u_2} [field E] [algebra F E] {K : intermediate_field F E} : finite_dimensional.findim F ↥K = 1 ↔ K = ⊥ := sorry theorem dim_adjoin_eq_one_iff {F : Type u_1} [field F] {E : Type u_2} [field E] [algebra F E] {S : set E} : vector_space.dim F ↥(adjoin F S) = 1 ↔ S ⊆ ↑⊥ := iff.trans dim_eq_one_iff adjoin_eq_bot_iff theorem dim_adjoin_simple_eq_one_iff {F : Type u_1} [field F] {E : Type u_2} [field E] [algebra F E] {α : E} : vector_space.dim F ↥(adjoin F (insert.insert ∅ α)) = 1 ↔ α ∈ ⊥ := sorry theorem findim_adjoin_eq_one_iff {F : Type u_1} [field F] {E : Type u_2} [field E] [algebra F E] {S : set E} : finite_dimensional.findim F ↥(adjoin F S) = 1 ↔ S ⊆ ↑⊥ := iff.trans findim_eq_one_iff adjoin_eq_bot_iff theorem findim_adjoin_simple_eq_one_iff {F : Type u_1} [field F] {E : Type u_2} [field E] [algebra F E] {α : E} : finite_dimensional.findim F ↥(adjoin F (insert.insert ∅ α)) = 1 ↔ α ∈ ⊥ := sorry /-- If `F⟮x⟯` has dimension `1` over `F` for every `x ∈ E` then `F = E`. -/ theorem bot_eq_top_of_dim_adjoin_eq_one {F : Type u_1} [field F] {E : Type u_2} [field E] [algebra F E] (h : ∀ (x : E), vector_space.dim F ↥(adjoin F (insert.insert ∅ x)) = 1) : ⊥ = ⊤ := sorry theorem bot_eq_top_of_findim_adjoin_eq_one {F : Type u_1} [field F] {E : Type u_2} [field E] [algebra F E] (h : ∀ (x : E), finite_dimensional.findim F ↥(adjoin F (insert.insert ∅ x)) = 1) : ⊥ = ⊤ := sorry theorem subsingleton_of_dim_adjoin_eq_one {F : Type u_1} [field F] {E : Type u_2} [field E] [algebra F E] (h : ∀ (x : E), vector_space.dim F ↥(adjoin F (insert.insert ∅ x)) = 1) : subsingleton (intermediate_field F E) := subsingleton_of_bot_eq_top (bot_eq_top_of_dim_adjoin_eq_one h) theorem subsingleton_of_findim_adjoin_eq_one {F : Type u_1} [field F] {E : Type u_2} [field E] [algebra F E] (h : ∀ (x : E), finite_dimensional.findim F ↥(adjoin F (insert.insert ∅ x)) = 1) : subsingleton (intermediate_field F E) := subsingleton_of_bot_eq_top (bot_eq_top_of_findim_adjoin_eq_one h) /-- If `F⟮x⟯` has dimension `≤1` over `F` for every `x ∈ E` then `F = E`. -/ theorem bot_eq_top_of_findim_adjoin_le_one {F : Type u_1} [field F] {E : Type u_2} [field E] [algebra F E] [finite_dimensional F E] (h : ∀ (x : E), finite_dimensional.findim F ↥(adjoin F (insert.insert ∅ x)) ≤ 1) : ⊥ = ⊤ := sorry theorem subsingleton_of_findim_adjoin_le_one {F : Type u_1} [field F] {E : Type u_2} [field E] [algebra F E] [finite_dimensional F E] (h : ∀ (x : E), finite_dimensional.findim F ↥(adjoin F (insert.insert ∅ x)) ≤ 1) : subsingleton (intermediate_field F E) := subsingleton_of_bot_eq_top (bot_eq_top_of_findim_adjoin_le_one h) theorem aeval_gen_minpoly (F : Type u_1) [field F] {E : Type u_2} [field E] [algebra F E] (α : E) : coe_fn (polynomial.aeval (adjoin_simple.gen F α)) (minpoly F α) = 0 := sorry /-- algebra isomorphism between `adjoin_root` and `F⟮α⟯` -/ def adjoin_root_equiv_adjoin (F : Type u_1) [field F] {E : Type u_2} [field E] [algebra F E] {α : E} (h : is_integral F α) : alg_equiv F (adjoin_root (minpoly F α)) ↥(adjoin F (insert.insert ∅ α)) := alg_equiv.of_bijective (alg_hom.mk ⇑(adjoin_root.lift (algebra_map F ↥(adjoin F (insert.insert ∅ α))) (adjoin_simple.gen F α) (aeval_gen_minpoly F α)) sorry sorry sorry sorry sorry) sorry theorem adjoin_root_equiv_adjoin_apply_root (F : Type u_1) [field F] {E : Type u_2} [field E] [algebra F E] {α : E} (h : is_integral F α) : coe_fn (adjoin_root_equiv_adjoin F h) (adjoin_root.root (minpoly F α)) = adjoin_simple.gen F α := adjoin_root.lift_root /-- Algebra homomorphism `F⟮α⟯ →ₐ[F] K` are in bijection with the set of roots of `minpoly α` in `K`. -/ def alg_hom_adjoin_integral_equiv (F : Type u_1) [field F] {E : Type u_2} [field E] [algebra F E] {α : E} {K : Type u_3} [field K] [algebra F K] (h : is_integral F α) : alg_hom F (↥(adjoin F (insert.insert ∅ α))) K ≃ Subtype fun (x : K) => x ∈ polynomial.roots (polynomial.map (algebra_map F K) (minpoly F α)) := let ϕ : alg_equiv F (adjoin_root (minpoly F α)) ↥(adjoin F (insert.insert ∅ α)) := adjoin_root_equiv_adjoin F h; let swap1 : alg_hom F (↥(adjoin F (insert.insert ∅ α))) K ≃ alg_hom F (adjoin_root (minpoly F α)) K := equiv.mk (fun (f : alg_hom F (↥(adjoin F (insert.insert ∅ α))) K) => alg_hom.comp f (alg_equiv.to_alg_hom ϕ)) (fun (f : alg_hom F (adjoin_root (minpoly F α)) K) => alg_hom.comp f (alg_equiv.to_alg_hom (alg_equiv.symm ϕ))) sorry sorry; let swap2 : alg_hom F (adjoin_root (minpoly F α)) K ≃ Subtype fun (x : K) => x ∈ polynomial.roots (polynomial.map (algebra_map F K) (minpoly F α)) := adjoin_root.equiv F K (minpoly F α) sorry; equiv.trans swap1 swap2 /-- Fintype of algebra homomorphism `F⟮α⟯ →ₐ[F] K` -/ def fintype_of_alg_hom_adjoin_integral (F : Type u_1) [field F] {E : Type u_2} [field E] [algebra F E] {α : E} {K : Type u_3} [field K] [algebra F K] (h : is_integral F α) : fintype (alg_hom F (↥(adjoin F (insert.insert ∅ α))) K) := fintype.of_equiv (Subtype fun (x : K) => x ∈ polynomial.roots (polynomial.map (algebra_map F K) (minpoly F α))) (equiv.symm (alg_hom_adjoin_integral_equiv F h)) theorem card_alg_hom_adjoin_integral (F : Type u_1) [field F] {E : Type u_2} [field E] [algebra F E] {α : E} {K : Type u_3} [field K] [algebra F K] (h : is_integral F α) (h_sep : polynomial.separable (minpoly F α)) (h_splits : polynomial.splits (algebra_map F K) (minpoly F α)) : fintype.card (alg_hom F (↥(adjoin F (insert.insert ∅ α))) K) = polynomial.nat_degree (minpoly F α) := sorry /-- An intermediate field `S` is finitely generated if there exists `t : finset E` such that `intermediate_field.adjoin F t = S`. -/ def fg {F : Type u_1} [field F] {E : Type u_2} [field E] [algebra F E] (S : intermediate_field F E) := ∃ (t : finset E), adjoin F ↑t = S theorem fg_adjoin_finset {F : Type u_1} [field F] {E : Type u_2} [field E] [algebra F E] (t : finset E) : fg (adjoin F ↑t) := Exists.intro t rfl theorem fg_def {F : Type u_1} [field F] {E : Type u_2} [field E] [algebra F E] {S : intermediate_field F E} : fg S ↔ ∃ (t : set E), set.finite t ∧ adjoin F t = S := sorry theorem fg_bot {F : Type u_1} [field F] {E : Type u_2} [field E] [algebra F E] : fg ⊥ := Exists.intro ∅ (adjoin_empty F E) theorem fg_of_fg_to_subalgebra {F : Type u_1} [field F] {E : Type u_2} [field E] [algebra F E] (S : intermediate_field F E) (h : subalgebra.fg (to_subalgebra S)) : fg S := Exists.dcases_on h fun (t : finset E) (ht : algebra.adjoin F ↑t = to_subalgebra S) => Exists.intro t (Eq.symm (eq_adjoin_of_eq_algebra_adjoin F (↑t) S (Eq.symm ht))) theorem fg_of_noetherian {F : Type u_1} [field F] {E : Type u_2} [field E] [algebra F E] (S : intermediate_field F E) [is_noetherian F E] : fg S := fg_of_fg_to_subalgebra S (subalgebra.fg_of_noetherian (to_subalgebra S)) theorem induction_on_adjoin_finset {F : Type u_1} [field F] {E : Type u_2} [field E] [algebra F E] (S : finset E) (P : intermediate_field F E → Prop) (base : P ⊥) (ih : ∀ (K : intermediate_field F E) (x : E), x ∈ S → P K → P ↑(adjoin (↥K) (insert.insert ∅ x))) : P (adjoin F ↑S) := sorry theorem induction_on_adjoin_fg {F : Type u_1} [field F] {E : Type u_2} [field E] [algebra F E] (P : intermediate_field F E → Prop) (base : P ⊥) (ih : ∀ (K : intermediate_field F E) (x : E), P K → P ↑(adjoin (↥K) (insert.insert ∅ x))) (K : intermediate_field F E) (hK : fg K) : P K := sorry theorem induction_on_adjoin {F : Type u_1} [field F] {E : Type u_2} [field E] [algebra F E] [fd : finite_dimensional F E] (P : intermediate_field F E → Prop) (base : P ⊥) (ih : ∀ (K : intermediate_field F E) (x : E), P K → P ↑(adjoin (↥K) (insert.insert ∅ x))) (K : intermediate_field F E) : P K := induction_on_adjoin_fg P base ih K (fg_of_noetherian K) /-- Lifts `L → K` of `F → K` -/ def lifts (F : Type u_1) (E : Type u_2) (K : Type u_3) [field F] [field E] [field K] [algebra F E] [algebra F K] := sigma fun (L : intermediate_field F E) => alg_hom F (↥L) K protected instance lifts.order_bot {F : Type u_1} {E : Type u_2} {K : Type u_3} [field F] [field E] [field K] [algebra F E] [algebra F K] : order_bot (lifts F E K) := order_bot.mk (sigma.mk ⊥ (alg_hom.comp (algebra.of_id F K) (alg_equiv.to_alg_hom bot_equiv))) (fun (x y : lifts F E K) => sigma.fst x ≤ sigma.fst y ∧ ∀ (s : ↥(sigma.fst x)) (t : ↥(sigma.fst y)), ↑s = ↑t → coe_fn (sigma.snd x) s = coe_fn (sigma.snd y) t) (partial_order.lt._default fun (x y : lifts F E K) => sigma.fst x ≤ sigma.fst y ∧ ∀ (s : ↥(sigma.fst x)) (t : ↥(sigma.fst y)), ↑s = ↑t → coe_fn (sigma.snd x) s = coe_fn (sigma.snd y) t) sorry sorry sorry sorry protected instance lifts.inhabited {F : Type u_1} {E : Type u_2} {K : Type u_3} [field F] [field E] [field K] [algebra F E] [algebra F K] : Inhabited (lifts F E K) := { default := ⊥ } theorem lifts.eq_of_le {F : Type u_1} {E : Type u_2} {K : Type u_3} [field F] [field E] [field K] [algebra F E] [algebra F K] {x : lifts F E K} {y : lifts F E K} (hxy : x ≤ y) (s : ↥(sigma.fst x)) : coe_fn (sigma.snd x) s = coe_fn (sigma.snd y) { val := ↑s, property := and.left hxy (↑s) (subtype.mem s) } := and.right hxy s { val := ↑s, property := and.left hxy (↑s) (subtype.mem s) } rfl theorem lifts.exists_max_two {F : Type u_1} {E : Type u_2} {K : Type u_3} [field F] [field E] [field K] [algebra F E] [algebra F K] {c : set (lifts F E K)} {x : lifts F E K} {y : lifts F E K} (hc : zorn.chain LessEq c) (hx : x ∈ set.insert ⊥ c) (hy : y ∈ set.insert ⊥ c) : ∃ (z : lifts F E K), z ∈ set.insert ⊥ c ∧ x ≤ z ∧ y ≤ z := sorry theorem lifts.exists_max_three {F : Type u_1} {E : Type u_2} {K : Type u_3} [field F] [field E] [field K] [algebra F E] [algebra F K] {c : set (lifts F E K)} {x : lifts F E K} {y : lifts F E K} {z : lifts F E K} (hc : zorn.chain LessEq c) (hx : x ∈ set.insert ⊥ c) (hy : y ∈ set.insert ⊥ c) (hz : z ∈ set.insert ⊥ c) : ∃ (w : lifts F E K), w ∈ set.insert ⊥ c ∧ x ≤ w ∧ y ≤ w ∧ z ≤ w := sorry /-- An upper bound on a chain of lifts -/ def lifts.upper_bound_intermediate_field {F : Type u_1} {E : Type u_2} {K : Type u_3} [field F] [field E] [field K] [algebra F E] [algebra F K] {c : set (lifts F E K)} (hc : zorn.chain LessEq c) : intermediate_field F E := mk (fun (s : E) => ∃ (x : lifts F E K), x ∈ set.insert ⊥ c ∧ s ∈ sigma.fst x) sorry sorry sorry sorry sorry sorry sorry /-- The lift on the upper bound on a chain of lifts -/ def lifts.upper_bound_alg_hom {F : Type u_1} {E : Type u_2} {K : Type u_3} [field F] [field E] [field K] [algebra F E] [algebra F K] {c : set (lifts F E K)} (hc : zorn.chain LessEq c) : alg_hom F (↥(lifts.upper_bound_intermediate_field hc)) K := alg_hom.mk (fun (s : ↥(lifts.upper_bound_intermediate_field hc)) => coe_fn (sigma.snd (classical.some sorry)) { val := ↑s, property := sorry }) sorry sorry sorry sorry sorry /-- An upper bound on a chain of lifts -/ def lifts.upper_bound {F : Type u_1} {E : Type u_2} {K : Type u_3} [field F] [field E] [field K] [algebra F E] [algebra F K] {c : set (lifts F E K)} (hc : zorn.chain LessEq c) : lifts F E K := sigma.mk (lifts.upper_bound_intermediate_field hc) (lifts.upper_bound_alg_hom hc) theorem lifts.exists_upper_bound {F : Type u_1} {E : Type u_2} {K : Type u_3} [field F] [field E] [field K] [algebra F E] [algebra F K] (c : set (lifts F E K)) (hc : zorn.chain LessEq c) : ∃ (ub : lifts F E K), ∀ (a : lifts F E K), a ∈ c → a ≤ ub := sorry /-- Extend a lift `x : lifts F E K` to an element `s : E` whose conjugates are all in `K` -/ def lifts.lift_of_splits {F : Type u_1} {E : Type u_2} {K : Type u_3} [field F] [field E] [field K] [algebra F E] [algebra F K] (x : lifts F E K) {s : E} (h1 : is_integral F s) (h2 : polynomial.splits (algebra_map F K) (minpoly F s)) : lifts F E K := let h3 : is_integral (↥(sigma.fst x)) s := sorry; let key : polynomial.splits (alg_hom.to_ring_hom (sigma.snd x)) (minpoly (↥(sigma.fst x)) s) := sorry; sigma.mk (↑(adjoin (↥(sigma.fst x)) (insert.insert ∅ s))) (equiv.inv_fun alg_hom_equiv_sigma (sigma.mk (sigma.snd x) (equiv.inv_fun (alg_hom_adjoin_integral_equiv (↥(sigma.fst x)) h3) { val := polynomial.root_of_splits (alg_hom.to_ring_hom (sigma.snd x)) key sorry, property := sorry }))) theorem lifts.le_lifts_of_splits {F : Type u_1} {E : Type u_2} {K : Type u_3} [field F] [field E] [field K] [algebra F E] [algebra F K] (x : lifts F E K) {s : E} (h1 : is_integral F s) (h2 : polynomial.splits (algebra_map F K) (minpoly F s)) : x ≤ lifts.lift_of_splits x h1 h2 := sorry theorem lifts.mem_lifts_of_splits {F : Type u_1} {E : Type u_2} {K : Type u_3} [field F] [field E] [field K] [algebra F E] [algebra F K] (x : lifts F E K) {s : E} (h1 : is_integral F s) (h2 : polynomial.splits (algebra_map F K) (minpoly F s)) : s ∈ sigma.fst (lifts.lift_of_splits x h1 h2) := mem_adjoin_simple_self (↥(sigma.fst x)) s theorem lifts.exists_lift_of_splits {F : Type u_1} {E : Type u_2} {K : Type u_3} [field F] [field E] [field K] [algebra F E] [algebra F K] (x : lifts F E K) {s : E} (h1 : is_integral F s) (h2 : polynomial.splits (algebra_map F K) (minpoly F s)) : ∃ (y : lifts F E K), x ≤ y ∧ s ∈ sigma.fst y := Exists.intro (lifts.lift_of_splits x h1 h2) { left := lifts.le_lifts_of_splits x h1 h2, right := lifts.mem_lifts_of_splits x h1 h2 } theorem alg_hom_mk_adjoin_splits {F : Type u_1} {E : Type u_2} {K : Type u_3} [field F] [field E] [field K] [algebra F E] [algebra F K] {S : set E} (hK : ∀ (s : E), s ∈ S → is_integral F s ∧ polynomial.splits (algebra_map F K) (minpoly F s)) : Nonempty (alg_hom F (↥(adjoin F S)) K) := sorry theorem alg_hom_mk_adjoin_splits' {F : Type u_1} {E : Type u_2} {K : Type u_3} [field F] [field E] [field K] [algebra F E] [algebra F K] {S : set E} (hS : adjoin F S = ⊤) (hK : ∀ (x : E), x ∈ S → is_integral F x ∧ polynomial.splits (algebra_map F K) (minpoly F x)) : Nonempty (alg_hom F E K) := sorry
142942b8381549cc49a61bb19da4bdc6c0114841
d1bbf1801b3dcb214451d48214589f511061da63
/src/measure_theory/integration.lean
d1b04d10575bd2776f6419dec8e5571eeb1c3f41
[ "Apache-2.0" ]
permissive
cheraghchi/mathlib
5c366f8c4f8e66973b60c37881889da8390cab86
f29d1c3038422168fbbdb2526abf7c0ff13e86db
refs/heads/master
1,676,577,831,283
1,610,894,638,000
1,610,894,638,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
80,183
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Johannes Hölzl -/ import measure_theory.measure_space import measure_theory.borel_space import data.indicator_function import data.support /-! # Lebesgue integral for `ennreal`-valued functions We define simple functions and show that each Borel measurable function on `ennreal` can be approximated by a sequence of simple functions. To prove something for an arbitrary measurable function into `ennreal`, the theorem `measurable.ennreal_induction` shows that is it sufficient to show that the property holds for (multiples of) characteristic functions and is closed under addition and supremum of increasing sequences of functions. ## Notation We introduce the following notation for the lower Lebesgue integral of a function `f : α → ennreal`. * `∫⁻ x, f x ∂μ`: integral of a function `f : α → ennreal` with respect to a measure `μ`; * `∫⁻ x, f x`: integral of a function `f : α → ennreal` with respect to the canonical measure `volume` on `α`; * `∫⁻ x in s, f x ∂μ`: integral of a function `f : α → ennreal` over a set `s` with respect to a measure `μ`, defined as `∫⁻ x, f x ∂(μ.restrict s)`; * `∫⁻ x in s, f x`: integral of a function `f : α → ennreal` over a set `s` with respect to the canonical measure `volume`, defined as `∫⁻ x, f x ∂(volume.restrict s)`. -/ noncomputable theory open set (hiding restrict restrict_apply) filter ennreal open_locale classical topological_space big_operators nnreal namespace measure_theory variables {α β γ δ : Type*} /-- A function `f` from a measurable space to any type is called *simple*, if every preimage `f ⁻¹' {x}` is measurable, and the range is finite. This structure bundles a function with these properties. -/ structure {u v} simple_func (α : Type u) [measurable_space α] (β : Type v) := (to_fun : α → β) (is_measurable_fiber' : ∀ x, is_measurable (to_fun ⁻¹' {x})) (finite_range' : (set.range to_fun).finite) local infixr ` →ₛ `:25 := simple_func namespace simple_func section measurable variables [measurable_space α] instance has_coe_to_fun : has_coe_to_fun (α →ₛ β) := ⟨_, to_fun⟩ lemma coe_injective ⦃f g : α →ₛ β⦄ (H : ⇑f = g) : f = g := by cases f; cases g; congr; exact H @[ext] theorem ext {f g : α →ₛ β} (H : ∀ a, f a = g a) : f = g := coe_injective $ funext H lemma finite_range (f : α →ₛ β) : (set.range f).finite := f.finite_range' lemma is_measurable_fiber (f : α →ₛ β) (x : β) : is_measurable (f ⁻¹' {x}) := f.is_measurable_fiber' x /-- Range of a simple function `α →ₛ β` as a `finset β`. -/ protected def range (f : α →ₛ β) : finset β := f.finite_range.to_finset @[simp] theorem mem_range {f : α →ₛ β} {b} : b ∈ f.range ↔ b ∈ range f := finite.mem_to_finset theorem mem_range_self (f : α →ₛ β) (x : α) : f x ∈ f.range := mem_range.2 ⟨x, rfl⟩ @[simp] lemma coe_range (f : α →ₛ β) : (↑f.range : set β) = set.range f := f.finite_range.coe_to_finset theorem mem_range_of_measure_ne_zero {f : α →ₛ β} {x : β} {μ : measure α} (H : μ (f ⁻¹' {x}) ≠ 0) : x ∈ f.range := let ⟨a, ha⟩ := nonempty_of_measure_ne_zero H in mem_range.2 ⟨a, ha⟩ lemma forall_range_iff {f : α →ₛ β} {p : β → Prop} : (∀ y ∈ f.range, p y) ↔ ∀ x, p (f x) := by simp only [mem_range, set.forall_range_iff] lemma exists_range_iff {f : α →ₛ β} {p : β → Prop} : (∃ y ∈ f.range, p y) ↔ ∃ x, p (f x) := by simpa only [mem_range, exists_prop] using set.exists_range_iff lemma preimage_eq_empty_iff (f : α →ₛ β) (b : β) : f ⁻¹' {b} = ∅ ↔ b ∉ f.range := preimage_singleton_eq_empty.trans $ not_congr mem_range.symm lemma exists_forall_le [nonempty β] [directed_order β] (f : α →ₛ β) : ∃ C, ∀ x, f x ≤ C := f.range.exists_le.imp $ λ C, forall_range_iff.1 /-- Constant function as a `simple_func`. -/ def const (α) {β} [measurable_space α] (b : β) : α →ₛ β := ⟨λ a, b, λ x, is_measurable.const _, finite_range_const⟩ instance [inhabited β] : inhabited (α →ₛ β) := ⟨const _ (default _)⟩ theorem const_apply (a : α) (b : β) : (const α b) a = b := rfl @[simp] theorem coe_const (b : β) : ⇑(const α b) = function.const α b := rfl @[simp] lemma range_const (α) [measurable_space α] [nonempty α] (b : β) : (const α b).range = {b} := finset.coe_injective $ by simp lemma is_measurable_cut (r : α → β → Prop) (f : α →ₛ β) (h : ∀b, is_measurable {a | r a b}) : is_measurable {a | r a (f a)} := begin have : {a | r a (f a)} = ⋃ b ∈ range f, {a | r a b} ∩ f ⁻¹' {b}, { ext a, suffices : r a (f a) ↔ ∃ i, r a (f i) ∧ f a = f i, by simpa, exact ⟨λ h, ⟨a, ⟨h, rfl⟩⟩, λ ⟨a', ⟨h', e⟩⟩, e.symm ▸ h'⟩ }, rw this, exact is_measurable.bUnion f.finite_range.countable (λ b _, is_measurable.inter (h b) (f.is_measurable_fiber _)) end theorem is_measurable_preimage (f : α →ₛ β) (s) : is_measurable (f ⁻¹' s) := is_measurable_cut (λ _ b, b ∈ s) f (λ b, is_measurable.const (b ∈ s)) /-- A simple function is measurable -/ protected theorem measurable [measurable_space β] (f : α →ₛ β) : measurable f := λ s _, is_measurable_preimage f s protected theorem ae_measurable [measurable_space β] {μ : measure α} (f : α →ₛ β) : ae_measurable f μ := f.measurable.ae_measurable protected lemma sum_measure_preimage_singleton (f : α →ₛ β) {μ : measure α} (s : finset β) : ∑ y in s, μ (f ⁻¹' {y}) = μ (f ⁻¹' ↑s) := sum_measure_preimage_singleton _ (λ _ _, f.is_measurable_fiber _) lemma sum_range_measure_preimage_singleton (f : α →ₛ β) (μ : measure α) : ∑ y in f.range, μ (f ⁻¹' {y}) = μ univ := by rw [f.sum_measure_preimage_singleton, coe_range, preimage_range] /-- If-then-else as a `simple_func`. -/ def piecewise (s : set α) (hs : is_measurable s) (f g : α →ₛ β) : α →ₛ β := ⟨s.piecewise f g, λ x, by letI : measurable_space β := ⊤; exact f.measurable.piecewise hs g.measurable trivial, (f.finite_range.union g.finite_range).subset range_ite_subset⟩ @[simp] theorem coe_piecewise {s : set α} (hs : is_measurable s) (f g : α →ₛ β) : ⇑(piecewise s hs f g) = s.piecewise f g := rfl theorem piecewise_apply {s : set α} (hs : is_measurable s) (f g : α →ₛ β) (a) : piecewise s hs f g a = if a ∈ s then f a else g a := rfl @[simp] lemma piecewise_compl {s : set α} (hs : is_measurable sᶜ) (f g : α →ₛ β) : piecewise sᶜ hs f g = piecewise s hs.of_compl g f := coe_injective $ by simp [hs] @[simp] lemma piecewise_univ (f g : α →ₛ β) : piecewise univ is_measurable.univ f g = f := coe_injective $ by simp @[simp] lemma piecewise_empty (f g : α →ₛ β) : piecewise ∅ is_measurable.empty f g = g := coe_injective $ by simp lemma measurable_bind [measurable_space γ] (f : α →ₛ β) (g : β → α → γ) (hg : ∀ b, measurable (g b)) : measurable (λ a, g (f a) a) := λ s hs, f.is_measurable_cut (λ a b, g b a ∈ s) $ λ b, hg b hs /-- If `f : α →ₛ β` is a simple function and `g : β → α →ₛ γ` is a family of simple functions, then `f.bind g` binds the first argument of `g` to `f`. In other words, `f.bind g a = g (f a) a`. -/ def bind (f : α →ₛ β) (g : β → α →ₛ γ) : α →ₛ γ := ⟨λa, g (f a) a, λ c, f.is_measurable_cut (λ a b, g b a = c) $ λ b, (g b).is_measurable_preimage {c}, (f.finite_range.bUnion (λ b _, (g b).finite_range)).subset $ by rintro _ ⟨a, rfl⟩; simp; exact ⟨a, a, rfl⟩⟩ @[simp] theorem bind_apply (f : α →ₛ β) (g : β → α →ₛ γ) (a) : f.bind g a = g (f a) a := rfl /-- Given a function `g : β → γ` and a simple function `f : α →ₛ β`, `f.map g` return the simple function `g ∘ f : α →ₛ γ` -/ def map (g : β → γ) (f : α →ₛ β) : α →ₛ γ := bind f (const α ∘ g) theorem map_apply (g : β → γ) (f : α →ₛ β) (a) : f.map g a = g (f a) := rfl theorem map_map (g : β → γ) (h: γ → δ) (f : α →ₛ β) : (f.map g).map h = f.map (h ∘ g) := rfl @[simp] theorem coe_map (g : β → γ) (f : α →ₛ β) : (f.map g : α → γ) = g ∘ f := rfl @[simp] theorem range_map [decidable_eq γ] (g : β → γ) (f : α →ₛ β) : (f.map g).range = f.range.image g := finset.coe_injective $ by simp [range_comp] @[simp] theorem map_const (g : β → γ) (b : β) : (const α b).map g = const α (g b) := rfl lemma map_preimage (f : α →ₛ β) (g : β → γ) (s : set γ) : (f.map g) ⁻¹' s = f ⁻¹' ↑(f.range.filter (λb, g b ∈ s)) := by { simp only [coe_range, sep_mem_eq, set.mem_range, function.comp_app, coe_map, finset.coe_filter, ← mem_preimage, inter_comm, preimage_inter_range], apply preimage_comp } lemma map_preimage_singleton (f : α →ₛ β) (g : β → γ) (c : γ) : (f.map g) ⁻¹' {c} = f ⁻¹' ↑(f.range.filter (λ b, g b = c)) := map_preimage _ _ _ /-- Composition of a `simple_fun` and a measurable function is a `simple_func`. -/ def comp [measurable_space β] (f : β →ₛ γ) (g : α → β) (hgm : measurable g) : α →ₛ γ := { to_fun := f ∘ g, finite_range' := f.finite_range.subset $ set.range_comp_subset_range _ _, is_measurable_fiber' := λ z, hgm (f.is_measurable_fiber z) } @[simp] lemma coe_comp [measurable_space β] (f : β →ₛ γ) {g : α → β} (hgm : measurable g) : ⇑(f.comp g hgm) = f ∘ g := rfl lemma range_comp_subset_range [measurable_space β] (f : β →ₛ γ) {g : α → β} (hgm : measurable g) : (f.comp g hgm).range ⊆ f.range := finset.coe_subset.1 $ by simp only [coe_range, coe_comp, set.range_comp_subset_range] /-- If `f` is a simple function taking values in `β → γ` and `g` is another simple function with the same domain and codomain `β`, then `f.seq g = f a (g a)`. -/ def seq (f : α →ₛ (β → γ)) (g : α →ₛ β) : α →ₛ γ := f.bind (λf, g.map f) @[simp] lemma seq_apply (f : α →ₛ (β → γ)) (g : α →ₛ β) (a : α) : f.seq g a = f a (g a) := rfl /-- Combine two simple functions `f : α →ₛ β` and `g : α →ₛ β` into `λ a, (f a, g a)`. -/ def pair (f : α →ₛ β) (g : α →ₛ γ) : α →ₛ (β × γ) := (f.map prod.mk).seq g @[simp] lemma pair_apply (f : α →ₛ β) (g : α →ₛ γ) (a) : pair f g a = (f a, g a) := rfl lemma pair_preimage (f : α →ₛ β) (g : α →ₛ γ) (s : set β) (t : set γ) : (pair f g) ⁻¹' (set.prod s t) = (f ⁻¹' s) ∩ (g ⁻¹' t) := rfl /- A special form of `pair_preimage` -/ lemma pair_preimage_singleton (f : α →ₛ β) (g : α →ₛ γ) (b : β) (c : γ) : (pair f g) ⁻¹' {(b, c)} = (f ⁻¹' {b}) ∩ (g ⁻¹' {c}) := by { rw ← singleton_prod_singleton, exact pair_preimage _ _ _ _ } theorem bind_const (f : α →ₛ β) : f.bind (const α) = f := by ext; simp instance [has_zero β] : has_zero (α →ₛ β) := ⟨const α 0⟩ instance [has_add β] : has_add (α →ₛ β) := ⟨λf g, (f.map (+)).seq g⟩ instance [has_mul β] : has_mul (α →ₛ β) := ⟨λf g, (f.map (*)).seq g⟩ instance [has_sup β] : has_sup (α →ₛ β) := ⟨λf g, (f.map (⊔)).seq g⟩ instance [has_inf β] : has_inf (α →ₛ β) := ⟨λf g, (f.map (⊓)).seq g⟩ instance [has_le β] : has_le (α →ₛ β) := ⟨λf g, ∀a, f a ≤ g a⟩ @[simp, norm_cast] lemma coe_zero [has_zero β] : ⇑(0 : α →ₛ β) = 0 := rfl @[simp] lemma const_zero [has_zero β] : const α (0:β) = 0 := rfl @[simp, norm_cast] lemma coe_add [has_add β] (f g : α →ₛ β) : ⇑(f + g) = f + g := rfl @[simp, norm_cast] lemma coe_mul [has_mul β] (f g : α →ₛ β) : ⇑(f * g) = f * g := rfl @[simp, norm_cast] lemma coe_le [preorder β] {f g : α →ₛ β} : (f : α → β) ≤ g ↔ f ≤ g := iff.rfl @[simp] lemma range_zero [nonempty α] [has_zero β] : (0 : α →ₛ β).range = {0} := finset.ext $ λ x, by simp [eq_comm] lemma eq_zero_of_mem_range_zero [has_zero β] : ∀ {y : β}, y ∈ (0 : α →ₛ β).range → y = 0 := forall_range_iff.2 $ λ x, rfl lemma sup_apply [has_sup β] (f g : α →ₛ β) (a : α) : (f ⊔ g) a = f a ⊔ g a := rfl lemma mul_apply [has_mul β] (f g : α →ₛ β) (a : α) : (f * g) a = f a * g a := rfl lemma add_apply [has_add β] (f g : α →ₛ β) (a : α) : (f + g) a = f a + g a := rfl lemma add_eq_map₂ [has_add β] (f g : α →ₛ β) : f + g = (pair f g).map (λp:β×β, p.1 + p.2) := rfl lemma mul_eq_map₂ [has_mul β] (f g : α →ₛ β) : f * g = (pair f g).map (λp:β×β, p.1 * p.2) := rfl lemma sup_eq_map₂ [has_sup β] (f g : α →ₛ β) : f ⊔ g = (pair f g).map (λp:β×β, p.1 ⊔ p.2) := rfl lemma const_mul_eq_map [has_mul β] (f : α →ₛ β) (b : β) : const α b * f = f.map (λa, b * a) := rfl theorem map_add [has_add β] [has_add γ] {g : β → γ} (hg : ∀ x y, g (x + y) = g x + g y) (f₁ f₂ : α →ₛ β) : (f₁ + f₂).map g = f₁.map g + f₂.map g := ext $ λ x, hg _ _ instance [add_monoid β] : add_monoid (α →ₛ β) := function.injective.add_monoid (λ f, show α → β, from f) coe_injective coe_zero coe_add instance add_comm_monoid [add_comm_monoid β] : add_comm_monoid (α →ₛ β) := function.injective.add_comm_monoid (λ f, show α → β, from f) coe_injective coe_zero coe_add instance [has_neg β] : has_neg (α →ₛ β) := ⟨λf, f.map (has_neg.neg)⟩ @[simp, norm_cast] lemma coe_neg [has_neg β] (f : α →ₛ β) : ⇑(-f) = -f := rfl instance [has_sub β] : has_sub (α →ₛ β) := ⟨λf g, (f.map (has_sub.sub)).seq g⟩ @[simp, norm_cast] lemma coe_sub [has_sub β] (f g : α →ₛ β) : ⇑(f - g) = f - g := rfl lemma sub_apply [has_sub β] (f g : α →ₛ β) (x : α) : (f - g) x = f x - g x := rfl instance [add_group β] : add_group (α →ₛ β) := function.injective.add_group_sub (λ f, show α → β, from f) coe_injective coe_zero coe_add coe_neg coe_sub instance [add_comm_group β] : add_comm_group (α →ₛ β) := function.injective.add_comm_group_sub (λ f, show α → β, from f) coe_injective coe_zero coe_add coe_neg coe_sub variables {K : Type*} instance [has_scalar K β] : has_scalar K (α →ₛ β) := ⟨λk f, f.map ((•) k)⟩ @[simp] lemma coe_smul [has_scalar K β] (c : K) (f : α →ₛ β) : ⇑(c • f) = c • f := rfl lemma smul_apply [has_scalar K β] (k : K) (f : α →ₛ β) (a : α) : (k • f) a = k • f a := rfl instance [semiring K] [add_comm_monoid β] [semimodule K β] : semimodule K (α →ₛ β) := function.injective.semimodule K ⟨λ f, show α → β, from f, coe_zero, coe_add⟩ coe_injective coe_smul lemma smul_eq_map [has_scalar K β] (k : K) (f : α →ₛ β) : k • f = f.map ((•) k) := rfl instance [preorder β] : preorder (α →ₛ β) := { le_refl := λf a, le_refl _, le_trans := λf g h hfg hgh a, le_trans (hfg _) (hgh a), .. simple_func.has_le } instance [partial_order β] : partial_order (α →ₛ β) := { le_antisymm := assume f g hfg hgf, ext $ assume a, le_antisymm (hfg a) (hgf a), .. simple_func.preorder } instance [order_bot β] : order_bot (α →ₛ β) := { bot := const α ⊥, bot_le := λf a, bot_le, .. simple_func.partial_order } instance [order_top β] : order_top (α →ₛ β) := { top := const α ⊤, le_top := λf a, le_top, .. simple_func.partial_order } instance [semilattice_inf β] : semilattice_inf (α →ₛ β) := { inf := (⊓), inf_le_left := assume f g a, inf_le_left, inf_le_right := assume f g a, inf_le_right, le_inf := assume f g h hfh hgh a, le_inf (hfh a) (hgh a), .. simple_func.partial_order } instance [semilattice_sup β] : semilattice_sup (α →ₛ β) := { sup := (⊔), le_sup_left := assume f g a, le_sup_left, le_sup_right := assume f g a, le_sup_right, sup_le := assume f g h hfh hgh a, sup_le (hfh a) (hgh a), .. simple_func.partial_order } instance [semilattice_sup_bot β] : semilattice_sup_bot (α →ₛ β) := { .. simple_func.semilattice_sup,.. simple_func.order_bot } instance [lattice β] : lattice (α →ₛ β) := { .. simple_func.semilattice_sup,.. simple_func.semilattice_inf } instance [bounded_lattice β] : bounded_lattice (α →ₛ β) := { .. simple_func.lattice, .. simple_func.order_bot, .. simple_func.order_top } lemma finset_sup_apply [semilattice_sup_bot β] {f : γ → α →ₛ β} (s : finset γ) (a : α) : s.sup f a = s.sup (λc, f c a) := begin refine finset.induction_on s rfl _, assume a s hs ih, rw [finset.sup_insert, finset.sup_insert, sup_apply, ih] end section restrict variables [has_zero β] /-- Restrict a simple function `f : α →ₛ β` to a set `s`. If `s` is measurable, then `f.restrict s a = if a ∈ s then f a else 0`, otherwise `f.restrict s = const α 0`. -/ def restrict (f : α →ₛ β) (s : set α) : α →ₛ β := if hs : is_measurable s then piecewise s hs f 0 else 0 theorem restrict_of_not_measurable {f : α →ₛ β} {s : set α} (hs : ¬is_measurable s) : restrict f s = 0 := dif_neg hs @[simp] theorem coe_restrict (f : α →ₛ β) {s : set α} (hs : is_measurable s) : ⇑(restrict f s) = indicator s f := by { rw [restrict, dif_pos hs], refl } @[simp] theorem restrict_univ (f : α →ₛ β) : restrict f univ = f := by simp [restrict] @[simp] theorem restrict_empty (f : α →ₛ β) : restrict f ∅ = 0 := by simp [restrict] theorem map_restrict_of_zero [has_zero γ] {g : β → γ} (hg : g 0 = 0) (f : α →ₛ β) (s : set α) : (f.restrict s).map g = (f.map g).restrict s := ext $ λ x, if hs : is_measurable s then by simp [hs, set.indicator_comp_of_zero hg] else by simp [restrict_of_not_measurable hs, hg] theorem map_coe_ennreal_restrict (f : α →ₛ ℝ≥0) (s : set α) : (f.restrict s).map (coe : ℝ≥0 → ennreal) = (f.map coe).restrict s := map_restrict_of_zero ennreal.coe_zero _ _ theorem map_coe_nnreal_restrict (f : α →ₛ ℝ≥0) (s : set α) : (f.restrict s).map (coe : ℝ≥0 → ℝ) = (f.map coe).restrict s := map_restrict_of_zero nnreal.coe_zero _ _ theorem restrict_apply (f : α →ₛ β) {s : set α} (hs : is_measurable s) (a) : restrict f s a = if a ∈ s then f a else 0 := by simp only [hs, coe_restrict] theorem restrict_preimage (f : α →ₛ β) {s : set α} (hs : is_measurable s) {t : set β} (ht : (0:β) ∉ t) : restrict f s ⁻¹' t = s ∩ f ⁻¹' t := by simp [hs, indicator_preimage_of_not_mem _ _ ht] theorem restrict_preimage_singleton (f : α →ₛ β) {s : set α} (hs : is_measurable s) {r : β} (hr : r ≠ 0) : restrict f s ⁻¹' {r} = s ∩ f ⁻¹' {r} := f.restrict_preimage hs hr.symm lemma mem_restrict_range {r : β} {s : set α} {f : α →ₛ β} (hs : is_measurable s) : r ∈ (restrict f s).range ↔ (r = 0 ∧ s ≠ univ) ∨ (r ∈ f '' s) := by rw [← finset.mem_coe, coe_range, coe_restrict _ hs, mem_range_indicator] lemma mem_image_of_mem_range_restrict {r : β} {s : set α} {f : α →ₛ β} (hr : r ∈ (restrict f s).range) (h0 : r ≠ 0) : r ∈ f '' s := if hs : is_measurable s then by simpa [mem_restrict_range hs, h0] using hr else by { rw [restrict_of_not_measurable hs] at hr, exact (h0 $ eq_zero_of_mem_range_zero hr).elim } @[mono] lemma restrict_mono [preorder β] (s : set α) {f g : α →ₛ β} (H : f ≤ g) : f.restrict s ≤ g.restrict s := if hs : is_measurable s then λ x, by simp only [coe_restrict _ hs, indicator_le_indicator (H x)] else by simp only [restrict_of_not_measurable hs, le_refl] end restrict section approx section variables [semilattice_sup_bot β] [has_zero β] /-- Fix a sequence `i : ℕ → β`. Given a function `α → β`, its `n`-th approximation by simple functions is defined so that in case `β = ennreal` it sends each `a` to the supremum of the set `{i k | k ≤ n ∧ i k ≤ f a}`, see `approx_apply` and `supr_approx_apply` for details. -/ def approx (i : ℕ → β) (f : α → β) (n : ℕ) : α →ₛ β := (finset.range n).sup (λk, restrict (const α (i k)) {a:α | i k ≤ f a}) lemma approx_apply [topological_space β] [order_closed_topology β] [measurable_space β] [opens_measurable_space β] {i : ℕ → β} {f : α → β} {n : ℕ} (a : α) (hf : measurable f) : (approx i f n : α →ₛ β) a = (finset.range n).sup (λk, if i k ≤ f a then i k else 0) := begin dsimp only [approx], rw [finset_sup_apply], congr, funext k, rw [restrict_apply], refl, exact (hf is_measurable_Ici) end lemma monotone_approx (i : ℕ → β) (f : α → β) : monotone (approx i f) := assume n m h, finset.sup_mono $ finset.range_subset.2 h lemma approx_comp [topological_space β] [order_closed_topology β] [measurable_space β] [opens_measurable_space β] [measurable_space γ] {i : ℕ → β} {f : γ → β} {g : α → γ} {n : ℕ} (a : α) (hf : measurable f) (hg : measurable g) : (approx i (f ∘ g) n : α →ₛ β) a = (approx i f n : γ →ₛ β) (g a) := by rw [approx_apply _ hf, approx_apply _ (hf.comp hg)] end lemma supr_approx_apply [topological_space β] [complete_lattice β] [order_closed_topology β] [has_zero β] [measurable_space β] [opens_measurable_space β] (i : ℕ → β) (f : α → β) (a : α) (hf : measurable f) (h_zero : (0 : β) = ⊥) : (⨆n, (approx i f n : α →ₛ β) a) = (⨆k (h : i k ≤ f a), i k) := begin refine le_antisymm (supr_le $ assume n, _) (supr_le $ assume k, supr_le $ assume hk, _), { rw [approx_apply a hf, h_zero], refine finset.sup_le (assume k hk, _), split_ifs, exact le_supr_of_le k (le_supr _ h), exact bot_le }, { refine le_supr_of_le (k+1) _, rw [approx_apply a hf], have : k ∈ finset.range (k+1) := finset.mem_range.2 (nat.lt_succ_self _), refine le_trans (le_of_eq _) (finset.le_sup this), rw [if_pos hk] } end end approx section eapprox /-- A sequence of `ennreal`s such that its range is the set of non-negative rational numbers. -/ def ennreal_rat_embed (n : ℕ) : ennreal := ennreal.of_real ((encodable.decode ℚ n).get_or_else (0 : ℚ)) lemma ennreal_rat_embed_encode (q : ℚ) : ennreal_rat_embed (encodable.encode q) = nnreal.of_real q := by rw [ennreal_rat_embed, encodable.encodek]; refl /-- Approximate a function `α → ennreal` by a sequence of simple functions. -/ def eapprox : (α → ennreal) → ℕ → α →ₛ ennreal := approx ennreal_rat_embed @[mono] lemma monotone_eapprox (f : α → ennreal) : monotone (eapprox f) := monotone_approx _ f lemma supr_eapprox_apply (f : α → ennreal) (hf : measurable f) (a : α) : (⨆n, (eapprox f n : α →ₛ ennreal) a) = f a := begin rw [eapprox, supr_approx_apply ennreal_rat_embed f a hf rfl], refine le_antisymm (supr_le $ assume i, supr_le $ assume hi, hi) (le_of_not_gt _), assume h, rcases ennreal.lt_iff_exists_rat_btwn.1 h with ⟨q, hq, lt_q, q_lt⟩, have : (nnreal.of_real q : ennreal) ≤ (⨆ (k : ℕ) (h : ennreal_rat_embed k ≤ f a), ennreal_rat_embed k), { refine le_supr_of_le (encodable.encode q) _, rw [ennreal_rat_embed_encode q], refine le_supr_of_le (le_of_lt q_lt) _, exact le_refl _ }, exact lt_irrefl _ (lt_of_le_of_lt this lt_q) end lemma eapprox_comp [measurable_space γ] {f : γ → ennreal} {g : α → γ} {n : ℕ} (hf : measurable f) (hg : measurable g) : (eapprox (f ∘ g) n : α → ennreal) = (eapprox f n : γ →ₛ ennreal) ∘ g := funext $ assume a, approx_comp a hf hg end eapprox end measurable section measure variables [measurable_space α] {μ : measure α} /-- Integral of a simple function whose codomain is `ennreal`. -/ def lintegral (f : α →ₛ ennreal) (μ : measure α) : ennreal := ∑ x in f.range, x * μ (f ⁻¹' {x}) lemma lintegral_eq_of_subset (f : α →ₛ ennreal) {s : finset ennreal} (hs : ∀ x, f x ≠ 0 → μ (f ⁻¹' {f x}) ≠ 0 → f x ∈ s) : f.lintegral μ = ∑ x in s, x * μ (f ⁻¹' {x}) := begin refine finset.sum_bij_ne_zero (λr _ _, r) _ _ _ _, { simpa only [forall_range_iff, mul_ne_zero_iff, and_imp] }, { intros, assumption }, { intros b _ hb, refine ⟨b, _, hb, rfl⟩, rw [mem_range, ← preimage_singleton_nonempty], exact nonempty_of_measure_ne_zero (mul_ne_zero_iff.1 hb).2 }, { intros, refl } end /-- Calculate the integral of `(g ∘ f)`, where `g : β → ennreal` and `f : α →ₛ β`. -/ lemma map_lintegral (g : β → ennreal) (f : α →ₛ β) : (f.map g).lintegral μ = ∑ x in f.range, g x * μ (f ⁻¹' {x}) := begin simp only [lintegral, range_map], refine finset.sum_image' _ (assume b hb, _), rcases mem_range.1 hb with ⟨a, rfl⟩, rw [map_preimage_singleton, ← f.sum_measure_preimage_singleton, finset.mul_sum], refine finset.sum_congr _ _, { congr }, { assume x, simp only [finset.mem_filter], rintro ⟨_, h⟩, rw h }, end lemma add_lintegral (f g : α →ₛ ennreal) : (f + g).lintegral μ = f.lintegral μ + g.lintegral μ := calc (f + g).lintegral μ = ∑ x in (pair f g).range, (x.1 * μ (pair f g ⁻¹' {x}) + x.2 * μ (pair f g ⁻¹' {x})) : by rw [add_eq_map₂, map_lintegral]; exact finset.sum_congr rfl (assume a ha, add_mul _ _ _) ... = ∑ x in (pair f g).range, x.1 * μ (pair f g ⁻¹' {x}) + ∑ x in (pair f g).range, x.2 * μ (pair f g ⁻¹' {x}) : by rw [finset.sum_add_distrib] ... = ((pair f g).map prod.fst).lintegral μ + ((pair f g).map prod.snd).lintegral μ : by rw [map_lintegral, map_lintegral] ... = lintegral f μ + lintegral g μ : rfl lemma const_mul_lintegral (f : α →ₛ ennreal) (x : ennreal) : (const α x * f).lintegral μ = x * f.lintegral μ := calc (f.map (λa, x * a)).lintegral μ = ∑ r in f.range, x * r * μ (f ⁻¹' {r}) : map_lintegral _ _ ... = ∑ r in f.range, x * (r * μ (f ⁻¹' {r})) : finset.sum_congr rfl (assume a ha, mul_assoc _ _ _) ... = x * f.lintegral μ : finset.mul_sum.symm /-- Integral of a simple function `α →ₛ ennreal` as a bilinear map. -/ def lintegralₗ : (α →ₛ ennreal) →ₗ[ennreal] measure α →ₗ[ennreal] ennreal := { to_fun := λ f, { to_fun := lintegral f, map_add' := by simp [lintegral, mul_add, finset.sum_add_distrib], map_smul' := λ c μ, by simp [lintegral, mul_left_comm _ c, finset.mul_sum] }, map_add' := λ f g, linear_map.ext (λ μ, add_lintegral f g), map_smul' := λ c f, linear_map.ext (λ μ, const_mul_lintegral f c) } @[simp] lemma zero_lintegral : (0 : α →ₛ ennreal).lintegral μ = 0 := linear_map.ext_iff.1 lintegralₗ.map_zero μ lemma lintegral_add {ν} (f : α →ₛ ennreal) : f.lintegral (μ + ν) = f.lintegral μ + f.lintegral ν := (lintegralₗ f).map_add μ ν lemma lintegral_smul (f : α →ₛ ennreal) (c : ennreal) : f.lintegral (c • μ) = c • f.lintegral μ := (lintegralₗ f).map_smul c μ @[simp] lemma lintegral_zero (f : α →ₛ ennreal) : f.lintegral 0 = 0 := (lintegralₗ f).map_zero lemma lintegral_sum {ι} (f : α →ₛ ennreal) (μ : ι → measure α) : f.lintegral (measure.sum μ) = ∑' i, f.lintegral (μ i) := begin simp only [lintegral, measure.sum_apply, f.is_measurable_preimage, ← finset.tsum_subtype, ← ennreal.tsum_mul_left], apply ennreal.tsum_comm end lemma restrict_lintegral (f : α →ₛ ennreal) {s : set α} (hs : is_measurable s) : (restrict f s).lintegral μ = ∑ r in f.range, r * μ (f ⁻¹' {r} ∩ s) := calc (restrict f s).lintegral μ = ∑ r in f.range, r * μ (restrict f s ⁻¹' {r}) : lintegral_eq_of_subset _ $ λ x hx, if hxs : x ∈ s then by simp [f.restrict_apply hs, if_pos hxs, mem_range_self] else false.elim $ hx $ by simp [*] ... = ∑ r in f.range, r * μ (f ⁻¹' {r} ∩ s) : finset.sum_congr rfl $ forall_range_iff.2 $ λ b, if hb : f b = 0 then by simp only [hb, zero_mul] else by rw [restrict_preimage_singleton _ hs hb, inter_comm] lemma lintegral_restrict (f : α →ₛ ennreal) (s : set α) (μ : measure α) : f.lintegral (μ.restrict s) = ∑ y in f.range, y * μ (f ⁻¹' {y} ∩ s) := by simp only [lintegral, measure.restrict_apply, f.is_measurable_preimage] lemma restrict_lintegral_eq_lintegral_restrict (f : α →ₛ ennreal) {s : set α} (hs : is_measurable s) : (restrict f s).lintegral μ = f.lintegral (μ.restrict s) := by rw [f.restrict_lintegral hs, lintegral_restrict] lemma const_lintegral (c : ennreal) : (const α c).lintegral μ = c * μ univ := begin rw [lintegral], by_cases ha : nonempty α, { resetI, simp [preimage_const_of_mem] }, { simp [μ.eq_zero_of_not_nonempty ha] } end lemma const_lintegral_restrict (c : ennreal) (s : set α) : (const α c).lintegral (μ.restrict s) = c * μ s := by rw [const_lintegral, measure.restrict_apply is_measurable.univ, univ_inter] lemma restrict_const_lintegral (c : ennreal) {s : set α} (hs : is_measurable s) : ((const α c).restrict s).lintegral μ = c * μ s := by rw [restrict_lintegral_eq_lintegral_restrict _ hs, const_lintegral_restrict] lemma le_sup_lintegral (f g : α →ₛ ennreal) : f.lintegral μ ⊔ g.lintegral μ ≤ (f ⊔ g).lintegral μ := calc f.lintegral μ ⊔ g.lintegral μ = ((pair f g).map prod.fst).lintegral μ ⊔ ((pair f g).map prod.snd).lintegral μ : rfl ... ≤ ∑ x in (pair f g).range, (x.1 ⊔ x.2) * μ (pair f g ⁻¹' {x}) : begin rw [map_lintegral, map_lintegral], refine sup_le _ _; refine finset.sum_le_sum (λ a _, canonically_ordered_semiring.mul_le_mul _ (le_refl _)), exact le_sup_left, exact le_sup_right end ... = (f ⊔ g).lintegral μ : by rw [sup_eq_map₂, map_lintegral] /-- `simple_func.lintegral` is monotone both in function and in measure. -/ @[mono] lemma lintegral_mono {f g : α →ₛ ennreal} (hfg : f ≤ g) {μ ν : measure α} (hμν : μ ≤ ν) : f.lintegral μ ≤ g.lintegral ν := calc f.lintegral μ ≤ f.lintegral μ ⊔ g.lintegral μ : le_sup_left ... ≤ (f ⊔ g).lintegral μ : le_sup_lintegral _ _ ... = g.lintegral μ : by rw [sup_of_le_right hfg] ... ≤ g.lintegral ν : finset.sum_le_sum $ λ y hy, ennreal.mul_left_mono $ hμν _ (g.is_measurable_preimage _) /-- `simple_func.lintegral` depends only on the measures of `f ⁻¹' {y}`. -/ lemma lintegral_eq_of_measure_preimage [measurable_space β] {f : α →ₛ ennreal} {g : β →ₛ ennreal} {ν : measure β} (H : ∀ y, μ (f ⁻¹' {y}) = ν (g ⁻¹' {y})) : f.lintegral μ = g.lintegral ν := begin simp only [lintegral, ← H], apply lintegral_eq_of_subset, simp only [H], intros, exact mem_range_of_measure_ne_zero ‹_› end /-- If two simple functions are equal a.e., then their `lintegral`s are equal. -/ lemma lintegral_congr {f g : α →ₛ ennreal} (h : f =ᵐ[μ] g) : f.lintegral μ = g.lintegral μ := lintegral_eq_of_measure_preimage $ λ y, measure_congr $ eventually.set_eq $ h.mono $ λ x hx, by simp [hx] lemma lintegral_map {β} [measurable_space β] {μ' : measure β} (f : α →ₛ ennreal) (g : β →ₛ ennreal) (m : α → β) (eq : ∀a:α, f a = g (m a)) (h : ∀s:set β, is_measurable s → μ' s = μ (m ⁻¹' s)) : f.lintegral μ = g.lintegral μ' := lintegral_eq_of_measure_preimage $ λ y, by { simp only [preimage, eq], exact (h (g ⁻¹' {y}) (g.is_measurable_preimage _)).symm } end measure section fin_meas_supp variables [measurable_space α] [has_zero β] [has_zero γ] {μ : measure α} open finset ennreal function lemma support_eq (f : α →ₛ β) : support f = ⋃ y ∈ f.range.filter (λ y, y ≠ 0), f ⁻¹' {y} := set.ext $ λ x, by simp only [finset.bUnion_preimage_singleton, mem_support, set.mem_preimage, finset.mem_coe, mem_filter, mem_range_self, true_and] /-- A `simple_func` has finite measure support if it is equal to `0` outside of a set of finite measure. -/ protected def fin_meas_supp (f : α →ₛ β) (μ : measure α) : Prop := f =ᶠ[μ.cofinite] 0 lemma fin_meas_supp_iff_support {f : α →ₛ β} {μ : measure α} : f.fin_meas_supp μ ↔ μ (support f) < ⊤ := iff.rfl lemma fin_meas_supp_iff {f : α →ₛ β} {μ : measure α} : f.fin_meas_supp μ ↔ ∀ y ≠ 0, μ (f ⁻¹' {y}) < ⊤ := begin split, { refine λ h y hy, lt_of_le_of_lt (measure_mono _) h, exact λ x hx (H : f x = 0), hy $ H ▸ eq.symm hx }, { intro H, rw [fin_meas_supp_iff_support, support_eq], refine lt_of_le_of_lt (measure_bUnion_finset_le _ _) (sum_lt_top _), exact λ y hy, H y (finset.mem_filter.1 hy).2 } end namespace fin_meas_supp lemma meas_preimage_singleton_ne_zero {f : α →ₛ β} (h : f.fin_meas_supp μ) {y : β} (hy : y ≠ 0) : μ (f ⁻¹' {y}) < ⊤ := fin_meas_supp_iff.1 h y hy protected lemma map {f : α →ₛ β} {g : β → γ} (hf : f.fin_meas_supp μ) (hg : g 0 = 0) : (f.map g).fin_meas_supp μ := flip lt_of_le_of_lt hf (measure_mono $ support_comp_subset hg f) lemma of_map {f : α →ₛ β} {g : β → γ} (h : (f.map g).fin_meas_supp μ) (hg : ∀b, g b = 0 → b = 0) : f.fin_meas_supp μ := flip lt_of_le_of_lt h $ measure_mono $ support_subset_comp hg _ lemma map_iff {f : α →ₛ β} {g : β → γ} (hg : ∀ {b}, g b = 0 ↔ b = 0) : (f.map g).fin_meas_supp μ ↔ f.fin_meas_supp μ := ⟨λ h, h.of_map $ λ b, hg.1, λ h, h.map $ hg.2 rfl⟩ protected lemma pair {f : α →ₛ β} {g : α →ₛ γ} (hf : f.fin_meas_supp μ) (hg : g.fin_meas_supp μ) : (pair f g).fin_meas_supp μ := calc μ (support $ pair f g) = μ (support f ∪ support g) : congr_arg μ $ support_prod_mk f g ... ≤ μ (support f) + μ (support g) : measure_union_le _ _ ... < _ : add_lt_top.2 ⟨hf, hg⟩ protected lemma map₂ [has_zero δ] {μ : measure α} {f : α →ₛ β} (hf : f.fin_meas_supp μ) {g : α →ₛ γ} (hg : g.fin_meas_supp μ) {op : β → γ → δ} (H : op 0 0 = 0) : ((pair f g).map (function.uncurry op)).fin_meas_supp μ := (hf.pair hg).map H protected lemma add {β} [add_monoid β] {f g : α →ₛ β} (hf : f.fin_meas_supp μ) (hg : g.fin_meas_supp μ) : (f + g).fin_meas_supp μ := by { rw [add_eq_map₂], exact hf.map₂ hg (zero_add 0) } protected lemma mul {β} [monoid_with_zero β] {f g : α →ₛ β} (hf : f.fin_meas_supp μ) (hg : g.fin_meas_supp μ) : (f * g).fin_meas_supp μ := by { rw [mul_eq_map₂], exact hf.map₂ hg (zero_mul 0) } lemma lintegral_lt_top {f : α →ₛ ennreal} (hm : f.fin_meas_supp μ) (hf : ∀ᵐ a ∂μ, f a < ⊤) : f.lintegral μ < ⊤ := begin refine sum_lt_top (λ a ha, _), rcases eq_or_lt_of_le (le_top : a ≤ ⊤) with rfl|ha, { simp only [ae_iff, lt_top_iff_ne_top, ne.def, not_not] at hf, simp [set.preimage, hf] }, { by_cases ha0 : a = 0, { subst a, rwa [zero_mul] }, { exact mul_lt_top ha (fin_meas_supp_iff.1 hm _ ha0) } } end lemma of_lintegral_lt_top {f : α →ₛ ennreal} (h : f.lintegral μ < ⊤) : f.fin_meas_supp μ := begin refine fin_meas_supp_iff.2 (λ b hb, _), rw [lintegral, sum_lt_top_iff] at h, by_cases b_mem : b ∈ f.range, { rw ennreal.lt_top_iff_ne_top, have h : ¬ _ = ⊤ := ennreal.lt_top_iff_ne_top.1 (h b b_mem), simp only [mul_eq_top, not_or_distrib, not_and_distrib] at h, rcases h with ⟨h, h'⟩, refine or.elim h (λh, by contradiction) (λh, h) }, { rw ← preimage_eq_empty_iff at b_mem, rw [b_mem, measure_empty], exact with_top.zero_lt_top } end lemma iff_lintegral_lt_top {f : α →ₛ ennreal} (hf : ∀ᵐ a ∂μ, f a < ⊤) : f.fin_meas_supp μ ↔ f.lintegral μ < ⊤ := ⟨λ h, h.lintegral_lt_top hf, λ h, of_lintegral_lt_top h⟩ end fin_meas_supp end fin_meas_supp /-- To prove something for an arbitrary simple function, it suffices to show that the property holds for (multiples of) characteristic functions and is closed under addition (of functions with disjoint support). It is possible to make the hypotheses in `h_sum` a bit stronger, and such conditions can be added once we need them (for example it is only necessary to consider the case where `g` is a multiple of a characteristic function, and that this multiple doesn't appear in the image of `f`) -/ @[elab_as_eliminator] protected lemma induction {α γ} [measurable_space α] [add_monoid γ] {P : simple_func α γ → Prop} (h_ind : ∀ c {s} (hs : is_measurable s), P (simple_func.piecewise s hs (simple_func.const _ c) (simple_func.const _ 0))) (h_sum : ∀ ⦃f g : simple_func α γ⦄, set.univ ⊆ f ⁻¹' {0} ∪ g ⁻¹' {0} → P f → P g → P (f + g)) (f : simple_func α γ) : P f := begin generalize' h : f.range \ {0} = s, rw [← finset.coe_inj, finset.coe_sdiff, finset.coe_singleton, simple_func.coe_range] at h, revert s f h, refine finset.induction _ _, { intros f hf, rw [finset.coe_empty, diff_eq_empty, range_subset_singleton] at hf, convert h_ind 0 is_measurable.univ, ext x, simp [hf] }, { intros x s hxs ih f hf, have mx := f.is_measurable_preimage {x}, let g := simple_func.piecewise (f ⁻¹' {x}) mx 0 f, have Pg : P g, { apply ih, simp only [g, simple_func.coe_piecewise, range_piecewise], rw [image_compl_preimage, union_diff_distrib, diff_diff_comm, hf, finset.coe_insert, insert_diff_self_of_not_mem, diff_eq_empty.mpr, set.empty_union], { rw [set.image_subset_iff], convert set.subset_univ _, exact preimage_const_of_mem (mem_singleton _) }, { rwa [finset.mem_coe] }}, convert h_sum _ Pg (h_ind x mx), { ext1 y, by_cases hy : y ∈ f ⁻¹' {x}; [simpa [hy], simp [hy]] }, { rintro y -, by_cases hy : y ∈ f ⁻¹' {x}; simp [hy] } } end end simple_func section lintegral open simple_func variables [measurable_space α] {μ : measure α} /-- The lower Lebesgue integral of a function `f` with respect to a measure `μ`. -/ def lintegral (μ : measure α) (f : α → ennreal) : ennreal := ⨆ (g : α →ₛ ennreal) (hf : ⇑g ≤ f), g.lintegral μ /-! In the notation for integrals, an expression like `∫⁻ x, g ∥x∥ ∂μ` will not be parsed correctly, and needs parentheses. We do not set the binding power of `r` to `0`, because then `∫⁻ x, f x = 0` will be parsed incorrectly. -/ notation `∫⁻` binders `, ` r:(scoped:60 f, f) ` ∂` μ:70 := lintegral μ r notation `∫⁻` binders `, ` r:(scoped:60 f, lintegral volume f) := r notation `∫⁻` binders ` in ` s `, ` r:(scoped:60 f, f) ` ∂` μ:70 := lintegral (measure.restrict μ s) r notation `∫⁻` binders ` in ` s `, ` r:(scoped:60 f, lintegral (measure.restrict volume s) f) := r theorem simple_func.lintegral_eq_lintegral (f : α →ₛ ennreal) (μ : measure α) : ∫⁻ a, f a ∂ μ = f.lintegral μ := le_antisymm (bsupr_le $ λ g hg, lintegral_mono hg $ le_refl _) (le_supr_of_le f $ le_supr_of_le (le_refl _) (le_refl _)) @[mono] lemma lintegral_mono' ⦃μ ν : measure α⦄ (hμν : μ ≤ ν) ⦃f g : α → ennreal⦄ (hfg : f ≤ g) : ∫⁻ a, f a ∂μ ≤ ∫⁻ a, g a ∂ν := supr_le_supr $ λ φ, supr_le_supr2 $ λ hφ, ⟨le_trans hφ hfg, lintegral_mono (le_refl φ) hμν⟩ lemma lintegral_mono ⦃f g : α → ennreal⦄ (hfg : f ≤ g) : ∫⁻ a, f a ∂μ ≤ ∫⁻ a, g a ∂μ := lintegral_mono' (le_refl μ) hfg lemma lintegral_mono_nnreal {f g : α → ℝ≥0} (h : f ≤ g) : ∫⁻ a, f a ∂μ ≤ ∫⁻ a, g a ∂μ := begin refine lintegral_mono _, intro a, rw ennreal.coe_le_coe, exact h a, end lemma monotone_lintegral (μ : measure α) : monotone (lintegral μ) := lintegral_mono @[simp] lemma lintegral_const (c : ennreal) : ∫⁻ a, c ∂μ = c * μ univ := by rw [← simple_func.const_lintegral, ← simple_func.lintegral_eq_lintegral, simple_func.coe_const] @[simp] lemma lintegral_one : ∫⁻ a, (1 : ennreal) ∂μ = μ univ := by rw [lintegral_const, one_mul] lemma set_lintegral_const (s : set α) (c : ennreal) : ∫⁻ a in s, c ∂μ = c * μ s := by rw [lintegral_const, measure.restrict_apply_univ] lemma set_lintegral_one (s) : ∫⁻ a in s, 1 ∂μ = μ s := by rw [set_lintegral_const, one_mul] /-- `∫⁻ a in s, f a ∂μ` is defined as the supremum of integrals of simple functions `φ : α →ₛ ennreal` such that `φ ≤ f`. This lemma says that it suffices to take functions `φ : α →ₛ ℝ≥0`. -/ lemma lintegral_eq_nnreal (f : α → ennreal) (μ : measure α) : (∫⁻ a, f a ∂μ) = (⨆ (φ : α →ₛ ℝ≥0) (hf : ∀ x, ↑(φ x) ≤ f x), (φ.map (coe : ℝ≥0 → ennreal)).lintegral μ) := begin refine le_antisymm (bsupr_le $ assume φ hφ, _) (supr_le_supr2 $ λ φ, ⟨φ.map (coe : ℝ≥0 → ennreal), le_refl _⟩), by_cases h : ∀ᵐ a ∂μ, φ a ≠ ⊤, { let ψ := φ.map ennreal.to_nnreal, replace h : ψ.map (coe : ℝ≥0 → ennreal) =ᵐ[μ] φ := h.mono (λ a, ennreal.coe_to_nnreal), have : ∀ x, ↑(ψ x) ≤ f x := λ x, le_trans ennreal.coe_to_nnreal_le_self (hφ x), exact le_supr_of_le (φ.map ennreal.to_nnreal) (le_supr_of_le this (ge_of_eq $ lintegral_congr h)) }, { have h_meas : μ (φ ⁻¹' {⊤}) ≠ 0, from mt measure_zero_iff_ae_nmem.1 h, refine le_trans le_top (ge_of_eq $ (supr_eq_top _).2 $ λ b hb, _), obtain ⟨n, hn⟩ : ∃ n : ℕ, b < n * μ (φ ⁻¹' {⊤}), from exists_nat_mul_gt h_meas (ne_of_lt hb), use (const α (n : ℝ≥0)).restrict (φ ⁻¹' {⊤}), simp only [lt_supr_iff, exists_prop, coe_restrict, φ.is_measurable_preimage, coe_const, ennreal.coe_indicator, map_coe_ennreal_restrict, map_const, ennreal.coe_nat, restrict_const_lintegral], refine ⟨indicator_le (λ x hx, le_trans _ (hφ _)), hn⟩, simp only [mem_preimage, mem_singleton_iff] at hx, simp only [hx, le_top] } end lemma exists_simple_func_forall_lintegral_sub_lt_of_pos {f : α → ennreal} (h : ∫⁻ x, f x ∂μ < ⊤) {ε : ennreal} (hε : 0 < ε) : ∃ φ : α →ₛ ℝ≥0, (∀ x, ↑(φ x) ≤ f x) ∧ ∀ ψ : α →ₛ ℝ≥0, (∀ x, ↑(ψ x) ≤ f x) → (map coe (ψ - φ)).lintegral μ < ε := begin rw lintegral_eq_nnreal at h, have := ennreal.lt_add_right h hε, erw ennreal.bsupr_add at this; [skip, exact ⟨0, λ x, by simp⟩], simp_rw [lt_supr_iff, supr_lt_iff, supr_le_iff] at this, rcases this with ⟨φ, hle : ∀ x, ↑(φ x) ≤ f x, b, hbφ, hb⟩, refine ⟨φ, hle, λ ψ hψ, _⟩, have : (map coe φ).lintegral μ < ⊤, from (le_bsupr φ hle).trans_lt h, rw [← add_lt_add_iff_left this, ← add_lintegral, ← map_add @ennreal.coe_add], refine (hb _ (λ x, le_trans _ (max_le (hle x) (hψ x)))).trans_lt hbφ, norm_cast, simp only [add_apply, sub_apply, nnreal.add_sub_eq_max] end theorem supr_lintegral_le {ι : Sort*} (f : ι → α → ennreal) : (⨆i, ∫⁻ a, f i a ∂μ) ≤ (∫⁻ a, ⨆i, f i a ∂μ) := begin simp only [← supr_apply], exact (monotone_lintegral μ).le_map_supr end theorem supr2_lintegral_le {ι : Sort*} {ι' : ι → Sort*} (f : Π i, ι' i → α → ennreal) : (⨆i (h : ι' i), ∫⁻ a, f i h a ∂μ) ≤ (∫⁻ a, ⨆i (h : ι' i), f i h a ∂μ) := by { convert (monotone_lintegral μ).le_map_supr2 f, ext1 a, simp only [supr_apply] } theorem le_infi_lintegral {ι : Sort*} (f : ι → α → ennreal) : (∫⁻ a, ⨅i, f i a ∂μ) ≤ (⨅i, ∫⁻ a, f i a ∂μ) := by { simp only [← infi_apply], exact (monotone_lintegral μ).map_infi_le } theorem le_infi2_lintegral {ι : Sort*} {ι' : ι → Sort*} (f : Π i, ι' i → α → ennreal) : (∫⁻ a, ⨅ i (h : ι' i), f i h a ∂μ) ≤ (⨅ i (h : ι' i), ∫⁻ a, f i h a ∂μ) := by { convert (monotone_lintegral μ).map_infi2_le f, ext1 a, simp only [infi_apply] } /-- Monotone convergence theorem -- sometimes called Beppo-Levi convergence. See `lintegral_supr_directed` for a more general form. -/ theorem lintegral_supr {f : ℕ → α → ennreal} (hf : ∀n, measurable (f n)) (h_mono : monotone f) : (∫⁻ a, ⨆n, f n a ∂μ) = (⨆n, ∫⁻ a, f n a ∂μ) := begin set c : ℝ≥0 → ennreal := coe, set F := λ a:α, ⨆n, f n a, have hF : measurable F := measurable_supr hf, refine le_antisymm _ (supr_lintegral_le _), rw [lintegral_eq_nnreal], refine supr_le (assume s, supr_le (assume hsf, _)), refine ennreal.le_of_forall_lt_one_mul_le (assume a ha, _), rcases ennreal.lt_iff_exists_coe.1 ha with ⟨r, rfl, ha⟩, have ha : r < 1 := ennreal.coe_lt_coe.1 ha, let rs := s.map (λa, r * a), have eq_rs : (const α r : α →ₛ ennreal) * map c s = rs.map c, { ext1 a, exact ennreal.coe_mul.symm }, have eq : ∀p, (rs.map c) ⁻¹' {p} = (⋃n, (rs.map c) ⁻¹' {p} ∩ {a | p ≤ f n a}), { assume p, rw [← inter_Union, ← inter_univ ((map c rs) ⁻¹' {p})] {occs := occurrences.pos [1]}, refine set.ext (assume x, and_congr_right $ assume hx, (true_iff _).2 _), by_cases p_eq : p = 0, { simp [p_eq] }, simp at hx, subst hx, have : r * s x ≠ 0, { rwa [(≠), ← ennreal.coe_eq_zero] }, have : s x ≠ 0, { refine mt _ this, assume h, rw [h, mul_zero] }, have : (rs.map c) x < ⨆ (n : ℕ), f n x, { refine lt_of_lt_of_le (ennreal.coe_lt_coe.2 (_)) (hsf x), suffices : r * s x < 1 * s x, simpa [rs], exact mul_lt_mul_of_pos_right ha (pos_iff_ne_zero.2 this) }, rcases lt_supr_iff.1 this with ⟨i, hi⟩, exact mem_Union.2 ⟨i, le_of_lt hi⟩ }, have mono : ∀r:ennreal, monotone (λn, (rs.map c) ⁻¹' {r} ∩ {a | r ≤ f n a}), { assume r i j h, refine inter_subset_inter (subset.refl _) _, assume x hx, exact le_trans hx (h_mono h x) }, have h_meas : ∀n, is_measurable {a : α | ⇑(map c rs) a ≤ f n a} := assume n, is_measurable_le (simple_func.measurable _) (hf n), calc (r:ennreal) * (s.map c).lintegral μ = ∑ r in (rs.map c).range, r * μ ((rs.map c) ⁻¹' {r}) : by rw [← const_mul_lintegral, eq_rs, simple_func.lintegral] ... ≤ ∑ r in (rs.map c).range, r * μ (⋃n, (rs.map c) ⁻¹' {r} ∩ {a | r ≤ f n a}) : le_of_eq (finset.sum_congr rfl $ assume x hx, by rw ← eq) ... ≤ ∑ r in (rs.map c).range, (⨆n, r * μ ((rs.map c) ⁻¹' {r} ∩ {a | r ≤ f n a})) : le_of_eq (finset.sum_congr rfl $ assume x hx, begin rw [measure_Union_eq_supr _ (directed_of_sup $ mono x), ennreal.mul_supr], { assume i, refine ((rs.map c).is_measurable_preimage _).inter _, exact hf i is_measurable_Ici } end) ... ≤ ⨆n, ∑ r in (rs.map c).range, r * μ ((rs.map c) ⁻¹' {r} ∩ {a | r ≤ f n a}) : begin refine le_of_eq _, rw [ennreal.finset_sum_supr_nat], assume p i j h, exact canonically_ordered_semiring.mul_le_mul (le_refl _) (measure_mono $ mono p h) end ... ≤ (⨆n:ℕ, ((rs.map c).restrict {a | (rs.map c) a ≤ f n a}).lintegral μ) : begin refine supr_le_supr (assume n, _), rw [restrict_lintegral _ (h_meas n)], { refine le_of_eq (finset.sum_congr rfl $ assume r hr, _), congr' 2 with a, refine and_congr_right _, simp {contextual := tt} } end ... ≤ (⨆n, ∫⁻ a, f n a ∂μ) : begin refine supr_le_supr (assume n, _), rw [← simple_func.lintegral_eq_lintegral], refine lintegral_mono (assume a, _), dsimp, rw [restrict_apply], split_ifs; simp, simpa using h, exact h_meas n end end lemma lintegral_eq_supr_eapprox_lintegral {f : α → ennreal} (hf : measurable f) : (∫⁻ a, f a ∂μ) = (⨆n, (eapprox f n).lintegral μ) := calc (∫⁻ a, f a ∂μ) = (∫⁻ a, ⨆n, (eapprox f n : α → ennreal) a ∂μ) : by congr; ext a; rw [supr_eapprox_apply f hf] ... = (⨆n, ∫⁻ a, (eapprox f n : α → ennreal) a ∂μ) : begin rw [lintegral_supr], { assume n, exact (eapprox f n).measurable }, { assume i j h, exact (monotone_eapprox f h) } end ... = (⨆n, (eapprox f n).lintegral μ) : by congr; ext n; rw [(eapprox f n).lintegral_eq_lintegral] lemma lintegral_mono_ae {f g : α → ennreal} (h : ∀ᵐ a ∂μ, f a ≤ g a) : (∫⁻ a, f a ∂μ) ≤ (∫⁻ a, g a ∂μ) := begin rcases exists_is_measurable_superset_of_null h with ⟨t, hts, ht, ht0⟩, have : ∀ᵐ x ∂μ, x ∉ t := measure_zero_iff_ae_nmem.1 ht0, refine (supr_le $ assume s, supr_le $ assume hfs, le_supr_of_le (s.restrict tᶜ) $ le_supr_of_le _ _), { assume a, by_cases a ∈ t; simp [h, restrict_apply, ht.compl], exact le_trans (hfs a) (by_contradiction $ assume hnfg, h (hts hnfg)) }, { refine le_of_eq (simple_func.lintegral_congr $ this.mono $ λ a hnt, _), by_cases hat : a ∈ t; simp [hat, ht.compl], exact (hnt hat).elim } end lemma lintegral_congr_ae {f g : α → ennreal} (h : f =ᵐ[μ] g) : (∫⁻ a, f a ∂μ) = (∫⁻ a, g a ∂μ) := le_antisymm (lintegral_mono_ae $ h.le) (lintegral_mono_ae $ h.symm.le) lemma lintegral_congr {f g : α → ennreal} (h : ∀ a, f a = g a) : (∫⁻ a, f a ∂μ) = (∫⁻ a, g a ∂μ) := by simp only [h] lemma set_lintegral_congr {f : α → ennreal} {s t : set α} (h : s =ᵐ[μ] t) : ∫⁻ x in s, f x ∂μ = ∫⁻ x in t, f x ∂μ := by rw [restrict_congr_set h] /-- If `f` has finite integral, then `∫⁻ x in s, f x ∂μ` is absolutely continuous in `s`: it tends to zero as `μ s` tends to zero. This lemma states states this fact in terms of `ε` and `δ`. -/ lemma exists_pos_set_lintegral_lt_of_measure_lt {f : α → ennreal} (h : ∫⁻ x, f x ∂μ < ⊤) {ε : ennreal} (hε : 0 < ε) : ∃ δ > 0, ∀ s, μ s < δ → ∫⁻ x in s, f x ∂μ < ε := begin rcases exists_between hε with ⟨ε₂, hε₂0, hε₂ε⟩, rcases exists_between hε₂0 with ⟨ε₁, hε₁0, hε₁₂⟩, rcases exists_simple_func_forall_lintegral_sub_lt_of_pos h hε₁0 with ⟨φ, hle, hφ⟩, rcases φ.exists_forall_le with ⟨C, hC⟩, use [(ε₂ - ε₁) / C, ennreal.div_pos_iff.2 ⟨(zero_lt_sub_iff_lt.2 hε₁₂).ne', ennreal.coe_ne_top⟩], intros s hs, simp only [lintegral_eq_nnreal, supr_lt_iff, supr_le_iff], refine ⟨ε₂, hε₂ε, λ ψ hψ, _⟩, calc (map coe ψ).lintegral (μ.restrict s) ≤ (map coe φ).lintegral (μ.restrict s) + (map coe (ψ - φ)).lintegral (μ.restrict s) : begin rw [← simple_func.add_lintegral, ← simple_func.map_add @ennreal.coe_add], refine simple_func.lintegral_mono (λ x, _) le_rfl, simp [-ennreal.coe_add, nnreal.add_sub_eq_max, le_max_right] end ... ≤ (map coe φ).lintegral (μ.restrict s) + ε₁ : begin refine add_le_add le_rfl (le_trans _ (hφ _ hψ).le), exact simple_func.lintegral_mono le_rfl measure.restrict_le_self end ... ≤ (simple_func.const α (C : ennreal)).lintegral (μ.restrict s) + ε₁ : by { mono*, exacts [λ x, coe_le_coe.2 (hC x), le_rfl, le_rfl] } ... = C * μ s + ε₁ : by simp [← simple_func.lintegral_eq_lintegral] ... ≤ C * ((ε₂ - ε₁) / C) + ε₁ : by { mono*, exacts [le_rfl, hs.le, le_rfl] } ... ≤ (ε₂ - ε₁) + ε₁ : add_le_add mul_div_le le_rfl ... = ε₂ : sub_add_cancel_of_le hε₁₂.le, end /-- If `f` has finite integral, then `∫⁻ x in s, f x ∂μ` is absolutely continuous in `s`: it tends to zero as `μ s` tends to zero. -/ lemma tendsto_set_lintegral_zero {ι} {f : α → ennreal} (h : ∫⁻ x, f x ∂μ < ⊤) {l : filter ι} {s : ι → set α} (hl : tendsto (μ ∘ s) l (𝓝 0)) : tendsto (λ i, ∫⁻ x in s i, f x ∂μ) l (𝓝 0) := begin simp only [ennreal.nhds_zero, tendsto_infi, tendsto_principal, mem_Iio, ← pos_iff_ne_zero] at hl ⊢, intros ε ε0, rcases exists_pos_set_lintegral_lt_of_measure_lt h ε0 with ⟨δ, δ0, hδ⟩, exact (hl δ δ0).mono (λ i, hδ _) end @[simp] lemma lintegral_add {f g : α → ennreal} (hf : measurable f) (hg : measurable g) : (∫⁻ a, f a + g a ∂μ) = (∫⁻ a, f a ∂μ) + (∫⁻ a, g a ∂μ) := calc (∫⁻ a, f a + g a ∂μ) = (∫⁻ a, (⨆n, (eapprox f n : α → ennreal) a) + (⨆n, (eapprox g n : α → ennreal) a) ∂μ) : by simp only [supr_eapprox_apply, hf, hg] ... = (∫⁻ a, (⨆n, (eapprox f n + eapprox g n : α → ennreal) a) ∂μ) : begin congr, funext a, rw [ennreal.supr_add_supr_of_monotone], { refl }, { assume i j h, exact monotone_eapprox _ h a }, { assume i j h, exact monotone_eapprox _ h a }, end ... = (⨆n, (eapprox f n).lintegral μ + (eapprox g n).lintegral μ) : begin rw [lintegral_supr], { congr, funext n, rw [← simple_func.add_lintegral, ← simple_func.lintegral_eq_lintegral], refl }, { assume n, exact measurable.add (eapprox f n).measurable (eapprox g n).measurable }, { assume i j h a, exact add_le_add (monotone_eapprox _ h _) (monotone_eapprox _ h _) } end ... = (⨆n, (eapprox f n).lintegral μ) + (⨆n, (eapprox g n).lintegral μ) : by refine (ennreal.supr_add_supr_of_monotone _ _).symm; { assume i j h, exact simple_func.lintegral_mono (monotone_eapprox _ h) (le_refl μ) } ... = (∫⁻ a, f a ∂μ) + (∫⁻ a, g a ∂μ) : by rw [lintegral_eq_supr_eapprox_lintegral hf, lintegral_eq_supr_eapprox_lintegral hg] lemma lintegral_add' {f g : α → ennreal} (hf : ae_measurable f μ) (hg : ae_measurable g μ) : (∫⁻ a, f a + g a ∂μ) = (∫⁻ a, f a ∂μ) + (∫⁻ a, g a ∂μ) := calc (∫⁻ a, f a + g a ∂μ) = (∫⁻ a, hf.mk f a + hg.mk g a ∂μ) : lintegral_congr_ae (eventually_eq.add hf.ae_eq_mk hg.ae_eq_mk) ... = (∫⁻ a, hf.mk f a ∂μ) + (∫⁻ a, hg.mk g a ∂μ) : lintegral_add hf.measurable_mk hg.measurable_mk ... = (∫⁻ a, f a ∂μ) + (∫⁻ a, g a ∂μ) : begin congr' 1, { exact lintegral_congr_ae hf.ae_eq_mk.symm }, { exact lintegral_congr_ae hg.ae_eq_mk.symm }, end lemma lintegral_zero : (∫⁻ a:α, 0 ∂μ) = 0 := by simp lemma lintegral_zero_fun : (∫⁻ a:α, (0 : α → ennreal) a ∂μ) = 0 := by simp @[simp] lemma lintegral_smul_measure (c : ennreal) (f : α → ennreal) : ∫⁻ a, f a ∂ (c • μ) = c * ∫⁻ a, f a ∂μ := by simp only [lintegral, supr_subtype', simple_func.lintegral_smul, ennreal.mul_supr, smul_eq_mul] @[simp] lemma lintegral_sum_measure {ι} (f : α → ennreal) (μ : ι → measure α) : ∫⁻ a, f a ∂(measure.sum μ) = ∑' i, ∫⁻ a, f a ∂(μ i) := begin simp only [lintegral, supr_subtype', simple_func.lintegral_sum, ennreal.tsum_eq_supr_sum], rw [supr_comm], congr, funext s, induction s using finset.induction_on with i s hi hs, { apply bot_unique, simp }, simp only [finset.sum_insert hi, ← hs], refine (ennreal.supr_add_supr _).symm, intros φ ψ, exact ⟨⟨φ ⊔ ψ, λ x, sup_le (φ.2 x) (ψ.2 x)⟩, add_le_add (simple_func.lintegral_mono le_sup_left (le_refl _)) (finset.sum_le_sum $ λ j hj, simple_func.lintegral_mono le_sup_right (le_refl _))⟩ end @[simp] lemma lintegral_add_measure (f : α → ennreal) (μ ν : measure α) : ∫⁻ a, f a ∂ (μ + ν) = ∫⁻ a, f a ∂μ + ∫⁻ a, f a ∂ν := by simpa [tsum_fintype] using lintegral_sum_measure f (λ b, cond b μ ν) @[simp] lemma lintegral_zero_measure (f : α → ennreal) : ∫⁻ a, f a ∂0 = 0 := bot_unique $ by simp [lintegral] lemma lintegral_finset_sum (s : finset β) {f : β → α → ennreal} (hf : ∀b, measurable (f b)) : (∫⁻ a, ∑ b in s, f b a ∂μ) = ∑ b in s, ∫⁻ a, f b a ∂μ := begin refine finset.induction_on s _ _, { simp }, { assume a s has ih, simp only [finset.sum_insert has], rw [lintegral_add (hf _) (s.measurable_sum hf), ih] } end @[simp] lemma lintegral_const_mul (r : ennreal) {f : α → ennreal} (hf : measurable f) : (∫⁻ a, r * f a ∂μ) = r * (∫⁻ a, f a ∂μ) := calc (∫⁻ a, r * f a ∂μ) = (∫⁻ a, (⨆n, (const α r * eapprox f n) a) ∂μ) : by { congr, funext a, rw [← supr_eapprox_apply f hf, ennreal.mul_supr], refl } ... = (⨆n, r * (eapprox f n).lintegral μ) : begin rw [lintegral_supr], { congr, funext n, rw [← simple_func.const_mul_lintegral, ← simple_func.lintegral_eq_lintegral] }, { assume n, exact simple_func.measurable _ }, { assume i j h a, exact canonically_ordered_semiring.mul_le_mul (le_refl _) (monotone_eapprox _ h _) } end ... = r * (∫⁻ a, f a ∂μ) : by rw [← ennreal.mul_supr, lintegral_eq_supr_eapprox_lintegral hf] lemma lintegral_const_mul'' (r : ennreal) {f : α → ennreal} (hf : ae_measurable f μ) : (∫⁻ a, r * f a ∂μ) = r * (∫⁻ a, f a ∂μ) := begin have A : ∫⁻ a, f a ∂μ = ∫⁻ a, hf.mk f a ∂μ := lintegral_congr_ae hf.ae_eq_mk, have B : ∫⁻ a, r * f a ∂μ = ∫⁻ a, r * hf.mk f a ∂μ := lintegral_congr_ae (eventually_eq.fun_comp hf.ae_eq_mk _), rw [A, B, lintegral_const_mul _ hf.measurable_mk], end lemma lintegral_const_mul_le (r : ennreal) (f : α → ennreal) : r * (∫⁻ a, f a ∂μ) ≤ (∫⁻ a, r * f a ∂μ) := begin rw [lintegral, ennreal.mul_supr], refine supr_le (λs, _), rw [ennreal.mul_supr], simp only [supr_le_iff, ge_iff_le], assume hs, rw ← simple_func.const_mul_lintegral, refine le_supr_of_le (const α r * s) (le_supr_of_le (λx, _) (le_refl _)), exact canonically_ordered_semiring.mul_le_mul (le_refl _) (hs x) end lemma lintegral_const_mul' (r : ennreal) (f : α → ennreal) (hr : r ≠ ⊤) : (∫⁻ a, r * f a ∂μ) = r * (∫⁻ a, f a ∂μ) := begin by_cases h : r = 0, { simp [h] }, apply le_antisymm _ (lintegral_const_mul_le r f), have rinv : r * r⁻¹ = 1 := ennreal.mul_inv_cancel h hr, have rinv' : r ⁻¹ * r = 1, by { rw mul_comm, exact rinv }, have := lintegral_const_mul_le (r⁻¹) (λx, r * f x), simp [(mul_assoc _ _ _).symm, rinv'] at this, simpa [(mul_assoc _ _ _).symm, rinv] using canonically_ordered_semiring.mul_le_mul (le_refl r) this end lemma lintegral_mul_const (r : ennreal) {f : α → ennreal} (hf : measurable f) : ∫⁻ a, f a * r ∂μ = ∫⁻ a, f a ∂μ * r := by simp_rw [mul_comm, lintegral_const_mul r hf] lemma lintegral_mul_const'' (r : ennreal) {f : α → ennreal} (hf : ae_measurable f μ) : ∫⁻ a, f a * r ∂μ = ∫⁻ a, f a ∂μ * r := by simp_rw [mul_comm, lintegral_const_mul'' r hf] lemma lintegral_mul_const_le (r : ennreal) (f : α → ennreal) : ∫⁻ a, f a ∂μ * r ≤ ∫⁻ a, f a * r ∂μ := by simp_rw [mul_comm, lintegral_const_mul_le r f] lemma lintegral_mul_const' (r : ennreal) (f : α → ennreal) (hr : r ≠ ⊤): ∫⁻ a, f a * r ∂μ = ∫⁻ a, f a ∂μ * r := by simp_rw [mul_comm, lintegral_const_mul' r f hr] /- A double integral of a product where each factor contains only one variable is a product of integrals -/ lemma lintegral_lintegral_mul {β} [measurable_space β] {ν : measure β} {f : α → ennreal} {g : β → ennreal} (hf : measurable f) (hg : measurable g) : ∫⁻ x, ∫⁻ y, f x * g y ∂ν ∂μ = ∫⁻ x, f x ∂μ * ∫⁻ y, g y ∂ν := by simp [lintegral_const_mul _ hg, lintegral_mul_const _ hf] -- TODO: Need a better way of rewriting inside of a integral lemma lintegral_rw₁ {f f' : α → β} (h : f =ᵐ[μ] f') (g : β → ennreal) : (∫⁻ a, g (f a) ∂μ) = (∫⁻ a, g (f' a) ∂μ) := lintegral_congr_ae $ h.mono $ λ a h, by rw h -- TODO: Need a better way of rewriting inside of a integral lemma lintegral_rw₂ {f₁ f₁' : α → β} {f₂ f₂' : α → γ} (h₁ : f₁ =ᵐ[μ] f₁') (h₂ : f₂ =ᵐ[μ] f₂') (g : β → γ → ennreal) : (∫⁻ a, g (f₁ a) (f₂ a) ∂μ) = (∫⁻ a, g (f₁' a) (f₂' a) ∂μ) := lintegral_congr_ae $ h₁.mp $ h₂.mono $ λ _ h₂ h₁, by rw [h₁, h₂] @[simp] lemma lintegral_indicator (f : α → ennreal) {s : set α} (hs : is_measurable s) : ∫⁻ a, s.indicator f a ∂μ = ∫⁻ a in s, f a ∂μ := begin simp only [lintegral, ← restrict_lintegral_eq_lintegral_restrict _ hs, supr_subtype'], apply le_antisymm; refine supr_le_supr2 (subtype.forall.2 $ λ φ hφ, _), { refine ⟨⟨φ, le_trans hφ (indicator_le_self _ _)⟩, _⟩, refine simple_func.lintegral_mono (λ x, _) (le_refl _), by_cases hx : x ∈ s, { simp [hx, hs, le_refl] }, { apply le_trans (hφ x), simp [hx, hs, le_refl] } }, { refine ⟨⟨φ.restrict s, λ x, _⟩, le_refl _⟩, simp [hφ x, hs, indicator_le_indicator] } end /-- Chebyshev's inequality -/ lemma mul_meas_ge_le_lintegral {f : α → ennreal} (hf : measurable f) (ε : ennreal) : ε * μ {x | ε ≤ f x} ≤ ∫⁻ a, f a ∂μ := begin have : is_measurable {a : α | ε ≤ f a }, from hf is_measurable_Ici, rw [← simple_func.restrict_const_lintegral _ this, ← simple_func.lintegral_eq_lintegral], refine lintegral_mono (λ a, _), simp only [restrict_apply _ this], split_ifs; [assumption, exact zero_le _] end lemma meas_ge_le_lintegral_div {f : α → ennreal} (hf : measurable f) {ε : ennreal} (hε : ε ≠ 0) (hε' : ε ≠ ⊤) : μ {x | ε ≤ f x} ≤ (∫⁻ a, f a ∂μ) / ε := (ennreal.le_div_iff_mul_le (or.inl hε) (or.inl hε')).2 $ by { rw [mul_comm], exact mul_meas_ge_le_lintegral hf ε } @[simp] lemma lintegral_eq_zero_iff {f : α → ennreal} (hf : measurable f) : ∫⁻ a, f a ∂μ = 0 ↔ (f =ᵐ[μ] 0) := begin refine iff.intro (assume h, _) (assume h, _), { have : ∀n:ℕ, ∀ᵐ a ∂μ, f a < n⁻¹, { assume n, rw [ae_iff, ← nonpos_iff_eq_zero, ← @ennreal.zero_div n⁻¹, ennreal.le_div_iff_mul_le, mul_comm], simp only [not_lt], -- TODO: why `rw ← h` fails with "not an equality or an iff"? exacts [h ▸ mul_meas_ge_le_lintegral hf n⁻¹, or.inl (ennreal.inv_ne_zero.2 ennreal.coe_nat_ne_top), or.inr ennreal.zero_ne_top] }, refine (ae_all_iff.2 this).mono (λ a ha, _), by_contradiction h, rcases ennreal.exists_inv_nat_lt h with ⟨n, hn⟩, exact (lt_irrefl _ $ lt_trans hn $ ha n).elim }, { calc ∫⁻ a, f a ∂μ = ∫⁻ a, 0 ∂μ : lintegral_congr_ae h ... = 0 : lintegral_zero } end @[simp] lemma lintegral_eq_zero_iff' {f : α → ennreal} (hf : ae_measurable f μ) : ∫⁻ a, f a ∂μ = 0 ↔ (f =ᵐ[μ] 0) := begin have : ∫⁻ a, f a ∂μ = ∫⁻ a, hf.mk f a ∂μ := lintegral_congr_ae hf.ae_eq_mk, rw [this, lintegral_eq_zero_iff hf.measurable_mk], exact ⟨λ H, hf.ae_eq_mk.trans H, λ H, hf.ae_eq_mk.symm.trans H⟩ end lemma lintegral_pos_iff_support {f : α → ennreal} (hf : measurable f) : 0 < ∫⁻ a, f a ∂μ ↔ 0 < μ (function.support f) := by simp [pos_iff_ne_zero, hf, filter.eventually_eq, ae_iff, function.support] /-- Weaker version of the monotone convergence theorem-/ lemma lintegral_supr_ae {f : ℕ → α → ennreal} (hf : ∀n, measurable (f n)) (h_mono : ∀n, ∀ᵐ a ∂μ, f n a ≤ f n.succ a) : (∫⁻ a, ⨆n, f n a ∂μ) = (⨆n, ∫⁻ a, f n a ∂μ) := let ⟨s, hs⟩ := exists_is_measurable_superset_of_null (ae_iff.1 (ae_all_iff.2 h_mono)) in let g := λ n a, if a ∈ s then 0 else f n a in have g_eq_f : ∀ᵐ a ∂μ, ∀n, g n a = f n a, from (measure_zero_iff_ae_nmem.1 hs.2.2).mono (assume a ha n, if_neg ha), calc ∫⁻ a, ⨆n, f n a ∂μ = ∫⁻ a, ⨆n, g n a ∂μ : lintegral_congr_ae $ g_eq_f.mono $ λ a ha, by simp only [ha] ... = ⨆n, (∫⁻ a, g n a ∂μ) : lintegral_supr (assume n, measurable_const.piecewise hs.2.1 (hf n)) (monotone_of_monotone_nat $ assume n a, classical.by_cases (assume h : a ∈ s, by simp [g, if_pos h]) (assume h : a ∉ s, begin simp only [g, if_neg h], have := hs.1, rw subset_def at this, have := mt (this a) h, simp only [not_not, mem_set_of_eq] at this, exact this n end)) ... = ⨆n, (∫⁻ a, f n a ∂μ) : by simp only [lintegral_congr_ae (g_eq_f.mono $ λ a ha, ha _)] lemma lintegral_sub {f g : α → ennreal} (hf : measurable f) (hg : measurable g) (hg_fin : ∫⁻ a, g a ∂μ < ⊤) (h_le : g ≤ᵐ[μ] f) : ∫⁻ a, f a - g a ∂μ = ∫⁻ a, f a ∂μ - ∫⁻ a, g a ∂μ := begin rw [← ennreal.add_left_inj hg_fin, ennreal.sub_add_cancel_of_le (lintegral_mono_ae h_le), ← lintegral_add (hf.ennreal_sub hg) hg], refine lintegral_congr_ae (h_le.mono $ λ x hx, _), exact ennreal.sub_add_cancel_of_le hx end /-- Monotone convergence theorem for nonincreasing sequences of functions -/ lemma lintegral_infi_ae {f : ℕ → α → ennreal} (h_meas : ∀n, measurable (f n)) (h_mono : ∀n:ℕ, f n.succ ≤ᵐ[μ] f n) (h_fin : ∫⁻ a, f 0 a ∂μ < ⊤) : ∫⁻ a, ⨅n, f n a ∂μ = ⨅n, ∫⁻ a, f n a ∂μ := have fn_le_f0 : ∫⁻ a, ⨅n, f n a ∂μ ≤ ∫⁻ a, f 0 a ∂μ, from lintegral_mono (assume a, infi_le_of_le 0 (le_refl _)), have fn_le_f0' : (⨅n, ∫⁻ a, f n a ∂μ) ≤ ∫⁻ a, f 0 a ∂μ, from infi_le_of_le 0 (le_refl _), (ennreal.sub_right_inj h_fin fn_le_f0 fn_le_f0').1 $ show ∫⁻ a, f 0 a ∂μ - ∫⁻ a, ⨅n, f n a ∂μ = ∫⁻ a, f 0 a ∂μ - (⨅n, ∫⁻ a, f n a ∂μ), from calc ∫⁻ a, f 0 a ∂μ - (∫⁻ a, ⨅n, f n a ∂μ) = ∫⁻ a, f 0 a - ⨅n, f n a ∂μ: (lintegral_sub (h_meas 0) (measurable_infi h_meas) (calc (∫⁻ a, ⨅n, f n a ∂μ) ≤ ∫⁻ a, f 0 a ∂μ : lintegral_mono (assume a, infi_le _ _) ... < ⊤ : h_fin ) (ae_of_all _ $ assume a, infi_le _ _)).symm ... = ∫⁻ a, ⨆n, f 0 a - f n a ∂μ : congr rfl (funext (assume a, ennreal.sub_infi)) ... = ⨆n, ∫⁻ a, f 0 a - f n a ∂μ : lintegral_supr_ae (assume n, (h_meas 0).ennreal_sub (h_meas n)) (assume n, (h_mono n).mono $ assume a ha, ennreal.sub_le_sub (le_refl _) ha) ... = ⨆n, ∫⁻ a, f 0 a ∂μ - ∫⁻ a, f n a ∂μ : have h_mono : ∀ᵐ a ∂μ, ∀n:ℕ, f n.succ a ≤ f n a := ae_all_iff.2 h_mono, have h_mono : ∀n, ∀ᵐ a ∂μ, f n a ≤ f 0 a := assume n, h_mono.mono $ assume a h, begin induction n with n ih, {exact le_refl _}, {exact le_trans (h n) ih} end, congr rfl (funext $ assume n, lintegral_sub (h_meas _) (h_meas _) (calc ∫⁻ a, f n a ∂μ ≤ ∫⁻ a, f 0 a ∂μ : lintegral_mono_ae $ h_mono n ... < ⊤ : h_fin) (h_mono n)) ... = ∫⁻ a, f 0 a ∂μ - ⨅n, ∫⁻ a, f n a ∂μ : ennreal.sub_infi.symm /-- Monotone convergence theorem for nonincreasing sequences of functions -/ lemma lintegral_infi {f : ℕ → α → ennreal} (h_meas : ∀n, measurable (f n)) (h_mono : ∀ ⦃m n⦄, m ≤ n → f n ≤ f m) (h_fin : ∫⁻ a, f 0 a ∂μ < ⊤) : ∫⁻ a, ⨅n, f n a ∂μ = ⨅n, ∫⁻ a, f n a ∂μ := lintegral_infi_ae h_meas (λ n, ae_of_all _ $ h_mono $ le_of_lt n.lt_succ_self) h_fin /-- Known as Fatou's lemma -/ lemma lintegral_liminf_le {f : ℕ → α → ennreal} (h_meas : ∀n, measurable (f n)) : ∫⁻ a, liminf at_top (λ n, f n a) ∂μ ≤ liminf at_top (λ n, ∫⁻ a, f n a ∂μ) := calc ∫⁻ a, liminf at_top (λ n, f n a) ∂μ = ∫⁻ a, ⨆n:ℕ, ⨅i≥n, f i a ∂μ : by simp only [liminf_eq_supr_infi_of_nat] ... = ⨆n:ℕ, ∫⁻ a, ⨅i≥n, f i a ∂μ : lintegral_supr (assume n, measurable_binfi _ (countable_encodable _) h_meas) (assume n m hnm a, infi_le_infi_of_subset $ λ i hi, le_trans hnm hi) ... ≤ ⨆n:ℕ, ⨅i≥n, ∫⁻ a, f i a ∂μ : supr_le_supr $ λ n, le_infi2_lintegral _ ... = liminf at_top (λ n, ∫⁻ a, f n a ∂μ) : liminf_eq_supr_infi_of_nat.symm lemma limsup_lintegral_le {f : ℕ → α → ennreal} {g : α → ennreal} (hf_meas : ∀ n, measurable (f n)) (h_bound : ∀n, f n ≤ᵐ[μ] g) (h_fin : ∫⁻ a, g a ∂μ < ⊤) : limsup at_top (λn, ∫⁻ a, f n a ∂μ) ≤ ∫⁻ a, limsup at_top (λn, f n a) ∂μ := calc limsup at_top (λn, ∫⁻ a, f n a ∂μ) = ⨅n:ℕ, ⨆i≥n, ∫⁻ a, f i a ∂μ : limsup_eq_infi_supr_of_nat ... ≤ ⨅n:ℕ, ∫⁻ a, ⨆i≥n, f i a ∂μ : infi_le_infi $ assume n, supr2_lintegral_le _ ... = ∫⁻ a, ⨅n:ℕ, ⨆i≥n, f i a ∂μ : begin refine (lintegral_infi _ _ _).symm, { assume n, exact measurable_bsupr _ (countable_encodable _) hf_meas }, { assume n m hnm a, exact (supr_le_supr_of_subset $ λ i hi, le_trans hnm hi) }, { refine lt_of_le_of_lt (lintegral_mono_ae _) h_fin, refine (ae_all_iff.2 h_bound).mono (λ n hn, _), exact supr_le (λ i, supr_le $ λ hi, hn i) } end ... = ∫⁻ a, limsup at_top (λn, f n a) ∂μ : by simp only [limsup_eq_infi_supr_of_nat] /-- Dominated convergence theorem for nonnegative functions -/ lemma tendsto_lintegral_of_dominated_convergence {F : ℕ → α → ennreal} {f : α → ennreal} (bound : α → ennreal) (hF_meas : ∀n, measurable (F n)) (h_bound : ∀n, F n ≤ᵐ[μ] bound) (h_fin : ∫⁻ a, bound a ∂μ < ⊤) (h_lim : ∀ᵐ a ∂μ, tendsto (λ n, F n a) at_top (𝓝 (f a))) : tendsto (λn, ∫⁻ a, F n a ∂μ) at_top (𝓝 (∫⁻ a, f a ∂μ)) := tendsto_of_le_liminf_of_limsup_le (calc ∫⁻ a, f a ∂μ = ∫⁻ a, liminf at_top (λ (n : ℕ), F n a) ∂μ : lintegral_congr_ae $ h_lim.mono $ assume a h, h.liminf_eq.symm ... ≤ liminf at_top (λ n, ∫⁻ a, F n a ∂μ) : lintegral_liminf_le hF_meas) (calc limsup at_top (λ (n : ℕ), ∫⁻ a, F n a ∂μ) ≤ ∫⁻ a, limsup at_top (λn, F n a) ∂μ : limsup_lintegral_le hF_meas h_bound h_fin ... = ∫⁻ a, f a ∂μ : lintegral_congr_ae $ h_lim.mono $ λ a h, h.limsup_eq) /-- Dominated convergence theorem for nonnegative functions which are just almost everywhere measurable. -/ lemma tendsto_lintegral_of_dominated_convergence' {F : ℕ → α → ennreal} {f : α → ennreal} (bound : α → ennreal) (hF_meas : ∀n, ae_measurable (F n) μ) (h_bound : ∀n, F n ≤ᵐ[μ] bound) (h_fin : ∫⁻ a, bound a ∂μ < ⊤) (h_lim : ∀ᵐ a ∂μ, tendsto (λ n, F n a) at_top (𝓝 (f a))) : tendsto (λn, ∫⁻ a, F n a ∂μ) at_top (𝓝 (∫⁻ a, f a ∂μ)) := begin have : ∀ n, ∫⁻ a, F n a ∂μ = ∫⁻ a, (hF_meas n).mk (F n) a ∂μ := λ n, lintegral_congr_ae (hF_meas n).ae_eq_mk, simp_rw this, apply tendsto_lintegral_of_dominated_convergence bound (λ n, (hF_meas n).measurable_mk) _ h_fin, { have : ∀ n, ∀ᵐ a ∂μ, (hF_meas n).mk (F n) a = F n a := λ n, (hF_meas n).ae_eq_mk.symm, have : ∀ᵐ a ∂μ, ∀ n, (hF_meas n).mk (F n) a = F n a := ae_all_iff.mpr this, filter_upwards [this, h_lim], assume a H H', simp_rw H, exact H' }, { assume n, filter_upwards [h_bound n, (hF_meas n).ae_eq_mk], assume a H H', rwa H' at H } end /-- Dominated convergence theorem for filters with a countable basis -/ lemma tendsto_lintegral_filter_of_dominated_convergence {ι} {l : filter ι} {F : ι → α → ennreal} {f : α → ennreal} (bound : α → ennreal) (hl_cb : l.is_countably_generated) (hF_meas : ∀ᶠ n in l, measurable (F n)) (h_bound : ∀ᶠ n in l, ∀ᵐ a ∂μ, F n a ≤ bound a) (h_fin : ∫⁻ a, bound a ∂μ < ⊤) (h_lim : ∀ᵐ a ∂μ, tendsto (λ n, F n a) l (𝓝 (f a))) : tendsto (λn, ∫⁻ a, F n a ∂μ) l (𝓝 $ ∫⁻ a, f a ∂μ) := begin rw hl_cb.tendsto_iff_seq_tendsto, { intros x xl, have hxl, { rw tendsto_at_top' at xl, exact xl }, have h := inter_mem_sets hF_meas h_bound, replace h := hxl _ h, rcases h with ⟨k, h⟩, rw ← tendsto_add_at_top_iff_nat k, refine tendsto_lintegral_of_dominated_convergence _ _ _ _ _, { exact bound }, { intro, refine (h _ _).1, exact nat.le_add_left _ _ }, { intro, refine (h _ _).2, exact nat.le_add_left _ _ }, { assumption }, { refine h_lim.mono (λ a h_lim, _), apply @tendsto.comp _ _ _ (λn, x (n + k)) (λn, F n a), { assumption }, rw tendsto_add_at_top_iff_nat, assumption } }, end section open encodable /-- Monotone convergence for a suprema over a directed family and indexed by an encodable type -/ theorem lintegral_supr_directed [encodable β] {f : β → α → ennreal} (hf : ∀b, measurable (f b)) (h_directed : directed (≤) f) : ∫⁻ a, ⨆b, f b a ∂μ = ⨆b, ∫⁻ a, f b a ∂μ := begin by_cases hβ : nonempty β, swap, { simp [supr_of_empty hβ] }, resetI, inhabit β, have : ∀a, (⨆ b, f b a) = (⨆ n, f (h_directed.sequence f n) a), { assume a, refine le_antisymm (supr_le $ assume b, _) (supr_le $ assume n, le_supr (λn, f n a) _), exact le_supr_of_le (encode b + 1) (h_directed.le_sequence b a) }, calc ∫⁻ a, ⨆ b, f b a ∂μ = ∫⁻ a, ⨆ n, f (h_directed.sequence f n) a ∂μ : by simp only [this] ... = ⨆ n, ∫⁻ a, f (h_directed.sequence f n) a ∂μ : lintegral_supr (assume n, hf _) h_directed.sequence_mono ... = ⨆ b, ∫⁻ a, f b a ∂μ : begin refine le_antisymm (supr_le $ assume n, _) (supr_le $ assume b, _), { exact le_supr (λb, ∫⁻ a, f b a ∂μ) _ }, { exact le_supr_of_le (encode b + 1) (lintegral_mono $ h_directed.le_sequence b) } end end end lemma lintegral_tsum [encodable β] {f : β → α → ennreal} (hf : ∀i, measurable (f i)) : ∫⁻ a, ∑' i, f i a ∂μ = ∑' i, ∫⁻ a, f i a ∂μ := begin simp only [ennreal.tsum_eq_supr_sum], rw [lintegral_supr_directed], { simp [lintegral_finset_sum _ hf] }, { assume b, exact finset.measurable_sum _ hf }, { assume s t, use [s ∪ t], split, exact assume a, finset.sum_le_sum_of_subset (finset.subset_union_left _ _), exact assume a, finset.sum_le_sum_of_subset (finset.subset_union_right _ _) } end open measure lemma lintegral_Union [encodable β] {s : β → set α} (hm : ∀ i, is_measurable (s i)) (hd : pairwise (disjoint on s)) (f : α → ennreal) : ∫⁻ a in ⋃ i, s i, f a ∂μ = ∑' i, ∫⁻ a in s i, f a ∂μ := by simp only [measure.restrict_Union hd hm, lintegral_sum_measure] lemma lintegral_Union_le [encodable β] (s : β → set α) (f : α → ennreal) : ∫⁻ a in ⋃ i, s i, f a ∂μ ≤ ∑' i, ∫⁻ a in s i, f a ∂μ := begin rw [← lintegral_sum_measure], exact lintegral_mono' restrict_Union_le (le_refl _) end lemma lintegral_map [measurable_space β] {f : β → ennreal} {g : α → β} (hf : measurable f) (hg : measurable g) : ∫⁻ a, f a ∂(map g μ) = ∫⁻ a, f (g a) ∂μ := begin simp only [lintegral_eq_supr_eapprox_lintegral, hf, hf.comp hg], { congr, funext n, symmetry, apply simple_func.lintegral_map, { assume a, exact congr_fun (simple_func.eapprox_comp hf hg) a }, { assume s hs, exact map_apply hg hs } }, end lemma lintegral_map' [measurable_space β] {f : β → ennreal} {g : α → β} (hf : ae_measurable f (measure.map g μ)) (hg : measurable g) : ∫⁻ a, f a ∂(measure.map g μ) = ∫⁻ a, f (g a) ∂μ := calc ∫⁻ a, f a ∂(measure.map g μ) = ∫⁻ a, hf.mk f a ∂(measure.map g μ) : lintegral_congr_ae hf.ae_eq_mk ... = ∫⁻ a, hf.mk f (g a) ∂μ : lintegral_map hf.measurable_mk hg ... = ∫⁻ a, f (g a) ∂μ : lintegral_congr_ae (ae_eq_comp hg hf.ae_eq_mk.symm) lemma lintegral_comp [measurable_space β] {f : β → ennreal} {g : α → β} (hf : measurable f) (hg : measurable g) : lintegral μ (f ∘ g) = ∫⁻ a, f a ∂(map g μ) := (lintegral_map hf hg).symm lemma set_lintegral_map [measurable_space β] {f : β → ennreal} {g : α → β} {s : set β} (hs : is_measurable s) (hf : measurable f) (hg : measurable g) : ∫⁻ y in s, f y ∂(map g μ) = ∫⁻ x in g ⁻¹' s, f (g x) ∂μ := by rw [restrict_map hg hs, lintegral_map hf hg] lemma lintegral_dirac' (a : α) {f : α → ennreal} (hf : measurable f) : ∫⁻ a, f a ∂(dirac a) = f a := by simp [lintegral_congr_ae (ae_eq_dirac' hf)] lemma lintegral_dirac [measurable_singleton_class α] (a : α) (f : α → ennreal) : ∫⁻ a, f a ∂(dirac a) = f a := by simp [lintegral_congr_ae (ae_eq_dirac f)] lemma ae_lt_top {f : α → ennreal} (hf : measurable f) (h2f : ∫⁻ x, f x ∂μ < ⊤) : ∀ᵐ x ∂μ, f x < ⊤ := begin simp_rw [ae_iff, ennreal.not_lt_top], by_contra h, rw [← not_le] at h2f, apply h2f, have : (f ⁻¹' {⊤}).indicator ⊤ ≤ f, { intro x, by_cases hx : x ∈ f ⁻¹' {⊤}; [simpa [hx], simp [hx]] }, convert lintegral_mono this, rw [lintegral_indicator _ (hf (is_measurable_singleton ⊤))], simp [ennreal.top_mul, preimage, h] end /-- Given a measure `μ : measure α` and a function `f : α → ennreal`, `μ.with_density f` is the measure such that for a measurable set `s` we have `μ.with_density f s = ∫⁻ a in s, f a ∂μ`. -/ def measure.with_density (μ : measure α) (f : α → ennreal) : measure α := measure.of_measurable (λs hs, ∫⁻ a in s, f a ∂μ) (by simp) (λ s hs hd, lintegral_Union hs hd _) @[simp] lemma with_density_apply (f : α → ennreal) {s : set α} (hs : is_measurable s) : μ.with_density f s = ∫⁻ a in s, f a ∂μ := measure.of_measurable_apply s hs end lintegral end measure_theory open measure_theory measure_theory.simple_func /-- To prove something for an arbitrary measurable function into `ennreal`, it suffices to show that the property holds for (multiples of) characteristic functions and is closed under addition and supremum of increasing sequences of functions. It is possible to make the hypotheses in the induction steps a bit stronger, and such conditions can be added once we need them (for example in `h_sum` it is only necessary to consider the sum of a simple function with a multiple of a characteristic function and that the intersection of their images is a subset of `{0}`. -/ @[elab_as_eliminator] theorem measurable.ennreal_induction {α} [measurable_space α] {P : (α → ennreal) → Prop} (h_ind : ∀ (c : ennreal) ⦃s⦄, is_measurable s → P (indicator s (λ _, c))) (h_sum : ∀ ⦃f g : α → ennreal⦄, set.univ ⊆ f ⁻¹' {0} ∪ g ⁻¹' {0} → measurable f → measurable g → P f → P g → P (f + g)) (h_supr : ∀ ⦃f : ℕ → α → ennreal⦄ (hf : ∀n, measurable (f n)) (h_mono : monotone f) (hP : ∀ n, P (f n)), P (λ x, ⨆ n, f n x)) ⦃f : α → ennreal⦄ (hf : measurable f) : P f := begin convert h_supr (λ n, (eapprox f n).measurable) (monotone_eapprox f) _, { ext1 x, rw [supr_eapprox_apply f hf] }, { exact λ n, simple_func.induction (λ c s hs, h_ind c hs) (λ f g hfg hf hg, h_sum hfg f.measurable g.measurable hf hg) (eapprox f n) } end namespace measure_theory /-- This is Exercise 1.2.1 from [tao2010]. It allows you to express integration of a measurable function with respect to `(μ.with_density f)` as an integral with respect to `μ`, called the base measure. `μ` is often the Lebesgue measure, and in this circumstance `f` is the probability density function, and `(μ.with_density f)` represents any continuous random variable as a probability measure, such as the uniform distribution between 0 and 1, the Gaussian distribution, the exponential distribution, the Beta distribution, or the Cauchy distribution (see Section 2.4 of [wasserman2004]). Thus, this method shows how to one can calculate expectations, variances, and other moments as a function of the probability density function. -/ lemma lintegral_with_density_eq_lintegral_mul {α} [measurable_space α] (μ : measure α) {f : α → ennreal} (h_mf : measurable f) : ∀ {g : α → ennreal}, measurable g → ∫⁻ a, g a ∂(μ.with_density f) = ∫⁻ a, (f * g) a ∂μ := begin apply measurable.ennreal_induction, { intros c s h_ms, simp [*, mul_comm _ c] }, { intros g h h_univ h_mea_g h_mea_h h_ind_g h_ind_h, simp [mul_add, *, measurable.ennreal_mul] }, { intros g h_mea_g h_mono_g h_ind, have : monotone (λ n a, f a * g n a) := λ m n hmn x, ennreal.mul_le_mul le_rfl (h_mono_g hmn x), simp [lintegral_supr, ennreal.mul_supr, h_mf.ennreal_mul (h_mea_g _), *] } end end measure_theory
551fd97c6f0f7d3cdaf058c8659e6f00aad5b2e2
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/analysis/mean_inequalities.lean
163220f000d2cdbfd88cbb3982d33e64b8e44a73
[ "Apache-2.0" ]
permissive
AntoineChambert-Loir/mathlib
64aabb896129885f12296a799818061bc90da1ff
07be904260ab6e36a5769680b6012f03a4727134
refs/heads/master
1,693,187,631,771
1,636,719,886,000
1,636,719,886,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
33,001
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 data.real.conjugate_exponents /-! # 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 (`zpow_arith_mean_le_arith_mean_zpow`), 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 := strict_convex_on_exp.convex_on.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) := hn.convex_on_pow.map_sum_le hw hw' (λ _ _, trivial) theorem zpow_arith_mean_le_arith_mean_zpow (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_zpow 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 ≠ ⊤, { intro h, rw [h, top_rpow_of_pos hp_pos] at h_top_rpow_sum, exact h_top_rpow_sum rfl, }, exact λ a ha, (lt_top_of_sum_ne_top h_top_sum ha).ne }, have h_top_rpow : ∀ (a : ι), a ∈ s → w a * z a ^ p ≠ ⊤, { intros i hi, specialize h_top i hi, 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), { rw coe_finset_sum, refine sum_congr rfl (λ i hi, (coe_to_nnreal _).symm), refine (lt_top_of_sum_ne_top _ hi).ne, exact hw'.symm ▸ ennreal.one_ne_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 ≤ |a|^p / p + |b|^q / q := calc a * b ≤ |a * b| : le_abs_self (a * b) ... = |a| * |b| : abs_mul a b ... ≤ |a|^p / p + |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 mul_le_mul_left' (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 mul_le_mul_left' (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
d85d01aeece4e662c072979b487dbb58696cae0a
735bb6d9c54e20a6bdc031c27bff1717e68886b9
/pending/default.lean
727c3b3b969f05cfc891f94846994d2044ed903b
[]
no_license
digama0/library_dev
3ea441564c4d7eca54a562b701febaa4db6a1061
56520d5d1dda46d87c98bf3acdf850672fdab00f
refs/heads/master
1,611,047,574,219
1,500,469,648,000
1,500,469,648,000
87,738,883
0
0
null
1,491,771,880,000
1,491,771,879,000
null
UTF-8
Lean
false
false
111
lean
/- Temporary space for definitions pending merges to the lean repository -/ import data.stream data.lazy_list
eddd73c60fe11c836d1c96b5bf7ee0169c2feeb7
f618aea02cb4104ad34ecf3b9713065cc0d06103
/src/topology/metric_space/basic.lean
822ee5f382b28ad310cf22a6e0b9e581a357d72b
[ "Apache-2.0" ]
permissive
joehendrix/mathlib
84b6603f6be88a7e4d62f5b1b0cbb523bb82b9a5
c15eab34ad754f9ecd738525cb8b5a870e834ddc
refs/heads/master
1,589,606,591,630
1,555,946,393,000
1,555,946,393,000
182,813,854
0
0
null
1,555,946,309,000
1,555,946,308,000
null
UTF-8
Lean
false
false
56,281
lean
/- Copyright (c) 2015, 2017 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Metric spaces. Authors: Jeremy Avigad, Robert Y. Lewis, Johannes Hölzl, Mario Carneiro, Sébastien Gouëzel Many definitions and theorems expected on metric spaces are already introduced on uniform spaces and topological spaces. For example: open and closed sets, compactness, completeness, continuity and uniform continuity -/ import data.real.nnreal topology.metric_space.emetric_space topology.algebra.ordered open lattice set filter classical topological_space noncomputable theory local attribute [instance, priority 0] nat.cast_coe local notation `𝓤` := uniformity universes u v w variables {α : Type u} {β : Type v} {γ : Type w} /-- Construct a uniform structure from a distance function and metric space axioms -/ def uniform_space_of_dist (dist : α → α → ℝ) (dist_self : ∀ x : α, dist x x = 0) (dist_comm : ∀ x y : α, dist x y = dist y x) (dist_triangle : ∀ x y z : α, dist x z ≤ dist x y + dist y z) : uniform_space α := uniform_space.of_core { uniformity := (⨅ ε>0, principal {p:α×α | dist p.1 p.2 < ε}), refl := le_infi $ assume ε, le_infi $ by simp [set.subset_def, id_rel, dist_self, (>)] {contextual := tt}, comp := le_infi $ assume ε, le_infi $ assume h, lift'_le (mem_infi_sets (ε / 2) $ mem_infi_sets (div_pos_of_pos_of_pos h two_pos) (subset.refl _)) $ have ∀ (a b c : α), dist a c < ε / 2 → dist c b < ε / 2 → dist a b < ε, from assume a b c hac hcb, calc dist a b ≤ dist a c + dist c b : dist_triangle _ _ _ ... < ε / 2 + ε / 2 : add_lt_add hac hcb ... = ε : by rw [div_add_div_same, add_self_div_two], by simpa [comp_rel], symm := tendsto_infi.2 $ assume ε, tendsto_infi.2 $ assume h, tendsto_infi' ε $ tendsto_infi' h $ tendsto_principal_principal.2 $ by simp [dist_comm] } /-- The distance function (given an ambient metric space on `α`), which returns a nonnegative real number `dist x y` given `x y : α`. -/ class has_dist (α : Type*) := (dist : α → α → ℝ) export has_dist (dist) /-- Metric space Each metric space induces a canonical `uniform_space` and hence a canonical `topological_space`. This is enforced in the type class definition, by extending the `uniform_space` structure. When instantiating a `metric_space` structure, the uniformity fields are not necessary, they will be filled in by default. In the same way, each metric space induces an emetric space structure. It is included in the structure, but filled in by default. When one instantiates a metric space structure, for instance a product structure, this makes it possible to use a uniform structure and an edistance that are exactly the ones for the uniform spaces product and the emetric spaces products, thereby ensuring that everything in defeq in diamonds.-/ class metric_space (α : Type u) extends has_dist α : Type u := (dist_self : ∀ x : α, dist x x = 0) (eq_of_dist_eq_zero : ∀ {x y : α}, dist x y = 0 → x = y) (dist_comm : ∀ x y : α, dist x y = dist y x) (dist_triangle : ∀ x y z : α, dist x z ≤ dist x y + dist y z) (edist : α → α → ennreal := λx y, ennreal.of_real (dist x y)) (edist_dist : ∀ x y : α, edist x y = ennreal.of_real (dist x y) . control_laws_tac) (to_uniform_space : uniform_space α := uniform_space_of_dist dist dist_self dist_comm dist_triangle) (uniformity_dist : 𝓤 α = ⨅ ε>0, principal {p:α×α | dist p.1 p.2 < ε} . control_laws_tac) variables [metric_space α] instance metric_space.to_uniform_space' : uniform_space α := metric_space.to_uniform_space α instance metric_space.to_has_edist : has_edist α := ⟨metric_space.edist⟩ @[simp] theorem dist_self (x : α) : dist x x = 0 := metric_space.dist_self x theorem eq_of_dist_eq_zero {x y : α} : dist x y = 0 → x = y := metric_space.eq_of_dist_eq_zero theorem dist_comm (x y : α) : dist x y = dist y x := metric_space.dist_comm x y theorem edist_dist (x y : α) : edist x y = ennreal.of_real (dist x y) := metric_space.edist_dist _ x y @[simp] theorem dist_eq_zero {x y : α} : dist x y = 0 ↔ x = y := iff.intro eq_of_dist_eq_zero (assume : x = y, this ▸ dist_self _) @[simp] theorem zero_eq_dist {x y : α} : 0 = dist x y ↔ x = y := by rw [eq_comm, dist_eq_zero] theorem dist_triangle (x y z : α) : dist x z ≤ dist x y + dist y z := metric_space.dist_triangle x y z theorem dist_triangle_left (x y z : α) : dist x y ≤ dist z x + dist z y := by rw dist_comm z; apply dist_triangle theorem dist_triangle_right (x y z : α) : dist x y ≤ dist x z + dist y z := by rw dist_comm y; apply dist_triangle lemma dist_triangle4 (x y z w : α) : dist x w ≤ dist x y + dist y z + dist z w := calc dist x w ≤ dist x z + dist z w : dist_triangle x z w ... ≤ (dist x y + dist y z) + dist z w : add_le_add_right (metric_space.dist_triangle x y z) _ lemma dist_triangle4_left (x₁ y₁ x₂ y₂ : α) : dist x₂ y₂ ≤ dist x₁ y₁ + (dist x₁ x₂ + dist y₁ y₂) := by rw [add_left_comm, dist_comm x₁, ← add_assoc]; apply dist_triangle4 lemma dist_triangle4_right (x₁ y₁ x₂ y₂ : α) : dist x₁ y₁ ≤ dist x₁ x₂ + dist y₁ y₂ + dist x₂ y₂ := by rw [add_right_comm, dist_comm y₁]; apply dist_triangle4 theorem swap_dist : function.swap (@dist α _) = dist := by funext x y; exact dist_comm _ _ theorem abs_dist_sub_le (x y z : α) : abs (dist x z - dist y z) ≤ dist x y := abs_sub_le_iff.2 ⟨sub_le_iff_le_add.2 (dist_triangle _ _ _), sub_le_iff_le_add.2 (dist_triangle_left _ _ _)⟩ theorem dist_nonneg {x y : α} : 0 ≤ dist x y := have 2 * dist x y ≥ 0, from calc 2 * dist x y = dist x y + dist y x : by rw [dist_comm x y, two_mul] ... ≥ 0 : by rw ← dist_self x; apply dist_triangle, nonneg_of_mul_nonneg_left this two_pos @[simp] theorem dist_le_zero {x y : α} : dist x y ≤ 0 ↔ x = y := by simpa [le_antisymm_iff, dist_nonneg] using @dist_eq_zero _ _ x y @[simp] theorem dist_pos {x y : α} : 0 < dist x y ↔ x ≠ y := by simpa [-dist_le_zero] using not_congr (@dist_le_zero _ _ x y) @[simp] theorem abs_dist {a b : α} : abs (dist a b) = dist a b := abs_of_nonneg dist_nonneg theorem eq_of_forall_dist_le {x y : α} (h : ∀ε, ε > 0 → dist x y ≤ ε) : x = y := eq_of_dist_eq_zero (eq_of_le_of_forall_le_of_dense dist_nonneg h) def nndist (a b : α) : nnreal := ⟨dist a b, dist_nonneg⟩ /--Express `nndist` in terms of `edist`-/ lemma nndist_edist (x y : α) : nndist x y = (edist x y).to_nnreal := by simp [nndist, edist_dist, nnreal.of_real, max_eq_left dist_nonneg, ennreal.of_real] /--Express `edist` in terms of `nndist`-/ lemma edist_nndist (x y : α) : edist x y = ↑(nndist x y) := by simp [nndist, edist_dist, nnreal.of_real, max_eq_left dist_nonneg, ennreal.of_real] /--In a metric space, the extended distance is always finite-/ lemma edist_ne_top (x y : α) : edist x y ≠ ⊤ := by rw [edist_dist x y]; apply ennreal.coe_ne_top /--`nndist x x` vanishes-/ @[simp] lemma nndist_self (a : α) : nndist a a = 0 := (nnreal.coe_eq_zero _).1 (dist_self a) /--Express `dist` in terms of `nndist`-/ lemma dist_nndist (x y : α) : dist x y = ↑(nndist x y) := rfl /--Express `nndist` in terms of `dist`-/ lemma nndist_dist (x y : α) : nndist x y = nnreal.of_real (dist x y) := by rw [dist_nndist, nnreal.of_real_coe] /--Deduce the equality of points with the vanishing of the nonnegative distance-/ theorem eq_of_nndist_eq_zero {x y : α} : nndist x y = 0 → x = y := by simp only [nnreal.eq_iff.symm, (dist_nndist _ _).symm, imp_self, nnreal.coe_zero, dist_eq_zero] theorem nndist_comm (x y : α) : nndist x y = nndist y x := by simpa [nnreal.eq_iff.symm] using dist_comm x y /--Characterize the equality of points with the vanishing of the nonnegative distance-/ @[simp] theorem nndist_eq_zero {x y : α} : nndist x y = 0 ↔ x = y := by simp only [nnreal.eq_iff.symm, (dist_nndist _ _).symm, imp_self, nnreal.coe_zero, dist_eq_zero] @[simp] theorem zero_eq_nndist {x y : α} : 0 = nndist x y ↔ x = y := by simp only [nnreal.eq_iff.symm, (dist_nndist _ _).symm, imp_self, nnreal.coe_zero, zero_eq_dist] /--Triangle inequality for the nonnegative distance-/ theorem nndist_triangle (x y z : α) : nndist x z ≤ nndist x y + nndist y z := by simpa [nnreal.coe_le] using dist_triangle x y z theorem nndist_triangle_left (x y z : α) : nndist x y ≤ nndist z x + nndist z y := by simpa [nnreal.coe_le] using dist_triangle_left x y z theorem nndist_triangle_right (x y z : α) : nndist x y ≤ nndist x z + nndist y z := by simpa [nnreal.coe_le] using dist_triangle_right x y z /--Express `dist` in terms of `edist`-/ lemma dist_edist (x y : α) : dist x y = (edist x y).to_real := by rw [edist_dist, ennreal.to_real_of_real (dist_nonneg)] namespace metric /- instantiate metric space as a topology -/ variables {x y z : α} {ε ε₁ ε₂ : ℝ} {s : set α} /-- `ball x ε` is the set of all points `y` with `dist y x < ε` -/ def ball (x : α) (ε : ℝ) : set α := {y | dist y x < ε} @[simp] theorem mem_ball : y ∈ ball x ε ↔ dist y x < ε := iff.rfl theorem mem_ball' : y ∈ ball x ε ↔ dist x y < ε := by rw dist_comm; refl /-- `closed_ball x ε` is the set of all points `y` with `dist y x ≤ ε` -/ def closed_ball (x : α) (ε : ℝ) := {y | dist y x ≤ ε} @[simp] theorem mem_closed_ball : y ∈ closed_ball x ε ↔ dist y x ≤ ε := iff.rfl theorem ball_subset_closed_ball : ball x ε ⊆ closed_ball x ε := assume y, by simp; intros h; apply le_of_lt h theorem pos_of_mem_ball (hy : y ∈ ball x ε) : ε > 0 := lt_of_le_of_lt dist_nonneg hy theorem mem_ball_self (h : ε > 0) : x ∈ ball x ε := show dist x x < ε, by rw dist_self; assumption theorem mem_closed_ball_self (h : ε ≥ 0) : x ∈ closed_ball x ε := show dist x x ≤ ε, by rw dist_self; assumption theorem mem_ball_comm : x ∈ ball y ε ↔ y ∈ ball x ε := by simp [dist_comm] theorem ball_subset_ball (h : ε₁ ≤ ε₂) : ball x ε₁ ⊆ ball x ε₂ := λ y (yx : _ < ε₁), lt_of_lt_of_le yx h theorem closed_ball_subset_closed_ball {α : Type u} [metric_space α] {ε₁ ε₂ : ℝ} {x : α} (h : ε₁ ≤ ε₂) : closed_ball x ε₁ ⊆ closed_ball x ε₂ := λ y (yx : _ ≤ ε₁), le_trans yx h theorem ball_disjoint (h : ε₁ + ε₂ ≤ dist x y) : ball x ε₁ ∩ ball y ε₂ = ∅ := eq_empty_iff_forall_not_mem.2 $ λ z ⟨h₁, h₂⟩, not_lt_of_le (dist_triangle_left x y z) (lt_of_lt_of_le (add_lt_add h₁ h₂) h) theorem ball_disjoint_same (h : ε ≤ dist x y / 2) : ball x ε ∩ ball y ε = ∅ := ball_disjoint $ by rwa [← two_mul, ← le_div_iff' two_pos] theorem ball_subset (h : dist x y ≤ ε₂ - ε₁) : ball x ε₁ ⊆ ball y ε₂ := λ z zx, by rw ← add_sub_cancel'_right ε₁ ε₂; exact lt_of_le_of_lt (dist_triangle z x y) (add_lt_add_of_lt_of_le zx h) theorem ball_half_subset (y) (h : y ∈ ball x (ε / 2)) : ball y (ε / 2) ⊆ ball x ε := ball_subset $ by rw sub_self_div_two; exact le_of_lt h theorem exists_ball_subset_ball (h : y ∈ ball x ε) : ∃ ε' > 0, ball y ε' ⊆ ball x ε := ⟨_, sub_pos.2 h, ball_subset $ by rw sub_sub_self⟩ theorem ball_eq_empty_iff_nonpos : ε ≤ 0 ↔ ball x ε = ∅ := (eq_empty_iff_forall_not_mem.trans ⟨λ h, le_of_not_gt $ λ ε0, h _ $ mem_ball_self ε0, λ ε0 y h, not_lt_of_le ε0 $ pos_of_mem_ball h⟩).symm theorem uniformity_dist : 𝓤 α = (⨅ ε>0, principal {p:α×α | dist p.1 p.2 < ε}) := metric_space.uniformity_dist _ theorem uniformity_dist' : 𝓤 α = (⨅ε:{ε:ℝ // ε>0}, principal {p:α×α | dist p.1 p.2 < ε.val}) := by simp [infi_subtype]; exact uniformity_dist theorem mem_uniformity_dist {s : set (α×α)} : s ∈ 𝓤 α ↔ (∃ε>0, ∀{a b:α}, dist a b < ε → (a, b) ∈ s) := begin rw [uniformity_dist', mem_infi], simp [subset_def], exact assume ⟨r, hr⟩ ⟨p, hp⟩, ⟨⟨min r p, lt_min hr hp⟩, by simp [lt_min_iff, (≥)] {contextual := tt}⟩, exact ⟨⟨1, zero_lt_one⟩⟩ end theorem dist_mem_uniformity {ε:ℝ} (ε0 : 0 < ε) : {p:α×α | dist p.1 p.2 < ε} ∈ 𝓤 α := mem_uniformity_dist.2 ⟨ε, ε0, λ a b, id⟩ theorem uniform_continuous_iff [metric_space β] {f : α → β} : uniform_continuous f ↔ ∀ ε > 0, ∃ δ > 0, ∀{a b:α}, dist a b < δ → dist (f a) (f b) < ε := uniform_continuous_def.trans ⟨λ H ε ε0, mem_uniformity_dist.1 $ H _ $ dist_mem_uniformity ε0, λ H r ru, let ⟨ε, ε0, hε⟩ := mem_uniformity_dist.1 ru, ⟨δ, δ0, hδ⟩ := H _ ε0 in mem_uniformity_dist.2 ⟨δ, δ0, λ a b h, hε (hδ h)⟩⟩ theorem uniform_embedding_iff [metric_space β] {f : α → β} : uniform_embedding f ↔ function.injective f ∧ uniform_continuous f ∧ ∀ δ > 0, ∃ ε > 0, ∀ {a b : α}, dist (f a) (f b) < ε → dist a b < δ := uniform_embedding_def'.trans $ and_congr iff.rfl $ and_congr iff.rfl ⟨λ H δ δ0, let ⟨t, tu, ht⟩ := H _ (dist_mem_uniformity δ0), ⟨ε, ε0, hε⟩ := mem_uniformity_dist.1 tu in ⟨ε, ε0, λ a b h, ht _ _ (hε h)⟩, λ H s su, let ⟨δ, δ0, hδ⟩ := mem_uniformity_dist.1 su, ⟨ε, ε0, hε⟩ := H _ δ0 in ⟨_, dist_mem_uniformity ε0, λ a b h, hδ (hε h)⟩⟩ theorem totally_bounded_iff {s : set α} : totally_bounded s ↔ ∀ ε > 0, ∃t : set α, finite t ∧ s ⊆ ⋃y∈t, ball y ε := ⟨λ H ε ε0, H _ (dist_mem_uniformity ε0), λ H r ru, let ⟨ε, ε0, hε⟩ := mem_uniformity_dist.1 ru, ⟨t, ft, h⟩ := H ε ε0 in ⟨t, ft, subset.trans h $ Union_subset_Union $ λ y, Union_subset_Union $ λ yt z, hε⟩⟩ /-- A metric space space is totally bounded if one can reconstruct up to any ε>0 any element of the space from finitely many data. -/ lemma totally_bounded_of_finite_discretization {α : Type u} [metric_space α] {s : set α} (H : ∀ε > (0 : ℝ), ∃ (β : Type u) [fintype β] (F : s → β), ∀x y, F x = F y → dist (x:α) y < ε) : totally_bounded s := begin classical, by_cases hs : s = ∅, { rw hs, exact totally_bounded_empty }, rcases exists_mem_of_ne_empty hs with ⟨x0, hx0⟩, haveI : inhabited s := ⟨⟨x0, hx0⟩⟩, refine totally_bounded_iff.2 (λ ε ε0, _), rcases H ε ε0 with ⟨β, fβ, F, hF⟩, let Finv := function.inv_fun F, refine ⟨range (subtype.val ∘ Finv), finite_range _, λ x xs, _⟩, let x' := Finv (F ⟨x, xs⟩), have : F x' = F ⟨x, xs⟩ := function.inv_fun_eq ⟨⟨x, xs⟩, rfl⟩, simp only [set.mem_Union, set.mem_range], exact ⟨_, ⟨F ⟨x, xs⟩, rfl⟩, hF _ _ this.symm⟩ end protected lemma cauchy_iff {f : filter α} : cauchy f ↔ f ≠ ⊥ ∧ ∀ ε > 0, ∃ t ∈ f, ∀ x y ∈ t, dist x y < ε := cauchy_iff.trans $ and_congr iff.rfl ⟨λ H ε ε0, let ⟨t, tf, ts⟩ := H _ (dist_mem_uniformity ε0) in ⟨t, tf, λ x y xt yt, @ts (x, y) ⟨xt, yt⟩⟩, λ H r ru, let ⟨ε, ε0, hε⟩ := mem_uniformity_dist.1 ru, ⟨t, tf, h⟩ := H ε ε0 in ⟨t, tf, λ ⟨x, y⟩ ⟨hx, hy⟩, hε (h x y hx hy)⟩⟩ theorem nhds_eq : nhds x = (⨅ε:{ε:ℝ // ε>0}, principal (ball x ε.val)) := begin rw [nhds_eq_uniformity, uniformity_dist', lift'_infi], { apply congr_arg, funext ε, rw [lift'_principal], { simp [ball, dist_comm] }, { exact monotone_preimage } }, { exact ⟨⟨1, zero_lt_one⟩⟩ }, { intros, refl } end theorem mem_nhds_iff : s ∈ nhds x ↔ ∃ε>0, ball x ε ⊆ s := begin rw [nhds_eq, mem_infi], { simp }, { intros y z, cases y with y hy, cases z with z hz, refine ⟨⟨min y z, lt_min hy hz⟩, _⟩, simp [ball_subset_ball, min_le_left, min_le_right, (≥)] }, { exact ⟨⟨1, zero_lt_one⟩⟩ } end theorem is_open_iff : is_open s ↔ ∀x∈s, ∃ε>0, ball x ε ⊆ s := by simp [is_open_iff_nhds, mem_nhds_iff] theorem is_open_ball : is_open (ball x ε) := is_open_iff.2 $ λ y, exists_ball_subset_ball theorem ball_mem_nhds (x : α) {ε : ℝ} (ε0 : 0 < ε) : ball x ε ∈ nhds x := mem_nhds_sets is_open_ball (mem_ball_self ε0) theorem tendsto_nhds_nhds [metric_space β] {f : α → β} {a b} : tendsto f (nhds a) (nhds b) ↔ ∀ ε > 0, ∃ δ > 0, ∀{x:α}, dist x a < δ → dist (f x) b < ε := ⟨λ H ε ε0, mem_nhds_iff.1 (H (ball_mem_nhds _ ε0)), λ H s hs, let ⟨ε, ε0, hε⟩ := mem_nhds_iff.1 hs, ⟨δ, δ0, hδ⟩ := H _ ε0 in mem_nhds_iff.2 ⟨δ, δ0, λ x h, hε (hδ h)⟩⟩ theorem continuous_iff [metric_space β] {f : α → β} : continuous f ↔ ∀b (ε > 0), ∃ δ > 0, ∀a, dist a b < δ → dist (f a) (f b) < ε := continuous_iff_continuous_at.trans $ forall_congr $ λ b, tendsto_nhds_nhds theorem exists_delta_of_continuous [metric_space β] {f : α → β} {ε : ℝ} (hf : continuous f) (hε : ε > 0) (b : α) : ∃ δ > 0, ∀a, dist a b ≤ δ → dist (f a) (f b) < ε := let ⟨δ, δ_pos, hδ⟩ := continuous_iff.1 hf b ε hε in ⟨δ / 2, half_pos δ_pos, assume a ha, hδ a $ lt_of_le_of_lt ha $ div_two_lt_of_pos δ_pos⟩ theorem tendsto_nhds {f : filter β} {u : β → α} {a : α} : tendsto u f (nhds a) ↔ ∀ ε > 0, ∃ n ∈ f, ∀x ∈ n, dist (u x) a < ε := by simp only [metric.nhds_eq, tendsto_infi, subtype.forall, tendsto_principal, mem_ball]; exact forall_congr (assume ε, forall_congr (assume hε, exists_sets_subset_iff.symm)) theorem continuous_iff' [topological_space β] {f : β → α} : continuous f ↔ ∀a (ε > 0), ∃ n ∈ nhds a, ∀b ∈ n, dist (f b) (f a) < ε := continuous_iff_continuous_at.trans $ forall_congr $ λ b, tendsto_nhds theorem tendsto_at_top [nonempty β] [semilattice_sup β] {u : β → α} {a : α} : tendsto u at_top (nhds a) ↔ ∀ε>0, ∃N, ∀n≥N, dist (u n) a < ε := by simp only [metric.nhds_eq, tendsto_infi, subtype.forall, tendsto_at_top_principal]; refl end metric open metric instance metric_space.to_separated : separated α := separated_def.2 $ λ x y h, eq_of_forall_dist_le $ λ ε ε0, le_of_lt (h _ (dist_mem_uniformity ε0)) /-Instantiate a metric space as an emetric space. Before we can state the instance, we need to show that the uniform structure coming from the edistance and the distance coincide. -/ /-- Expressing the uniformity in terms of `edist` -/ protected lemma metric.mem_uniformity_edist {s : set (α×α)} : s ∈ 𝓤 α ↔ (∃ε>0, ∀{a b:α}, edist a b < ε → (a, b) ∈ s) := begin refine mem_uniformity_dist.trans ⟨_, _⟩; rintro ⟨ε, ε0, Hε⟩, { refine ⟨ennreal.of_real ε, _, λ a b, _⟩, { rwa [gt, ennreal.of_real_pos] }, { rw [edist_dist, ennreal.of_real_lt_of_real_iff ε0], exact Hε } }, { rcases ennreal.lt_iff_exists_real_btwn.1 ε0 with ⟨ε', _, ε0', hε⟩, rw [ennreal.of_real_pos] at ε0', refine ⟨ε', ε0', λ a b h, Hε (lt_trans _ hε)⟩, rwa [edist_dist, ennreal.of_real_lt_of_real_iff ε0'] } end protected theorem metric.uniformity_edist' : 𝓤 α = (⨅ε:{ε:ennreal // ε>0}, principal {p:α×α | edist p.1 p.2 < ε.val}) := begin ext s, rw mem_infi, { simp [metric.mem_uniformity_edist, subset_def] }, { rintro ⟨r, hr⟩ ⟨p, hp⟩, use ⟨min r p, lt_min hr hp⟩, simp [lt_min_iff, (≥)] {contextual := tt} }, { exact ⟨⟨1, ennreal.zero_lt_one⟩⟩ } end theorem uniformity_edist : 𝓤 α = (⨅ ε>0, principal {p:α×α | edist p.1 p.2 < ε}) := by simpa [infi_subtype] using @metric.uniformity_edist' α _ /-- A metric space induces an emetric space -/ instance metric_space.to_emetric_space : emetric_space α := { edist := edist, edist_self := by simp [edist_dist], eq_of_edist_eq_zero := assume x y h, by simpa [edist_dist] using h, edist_comm := by simp only [edist_dist, dist_comm]; simp, edist_triangle := assume x y z, begin simp only [edist_dist, (ennreal.of_real_add _ _).symm, dist_nonneg], rw ennreal.of_real_le_of_real_iff _, { exact dist_triangle _ _ _ }, { simpa using add_le_add (dist_nonneg : 0 ≤ dist x y) dist_nonneg } end, uniformity_edist := uniformity_edist, ..‹metric_space α› } /-- Balls defined using the distance or the edistance coincide -/ lemma metric.emetric_ball {x : α} {ε : ℝ} : emetric.ball x (ennreal.of_real ε) = ball x ε := begin classical, by_cases h : 0 < ε, { ext y, by simp [edist_dist, ennreal.of_real_lt_of_real_iff h] }, { have h' : ε ≤ 0, by simpa using h, have A : ball x ε = ∅, by simpa [ball_eq_empty_iff_nonpos.symm], have B : emetric.ball x (ennreal.of_real ε) = ∅, by simp [ennreal.of_real_eq_zero.2 h', emetric.ball_eq_empty_iff], rwa [A, B] } end /-- Closed balls defined using the distance or the edistance coincide -/ lemma metric.emetric_closed_ball {x : α} {ε : ℝ} (h : 0 ≤ ε) : emetric.closed_ball x (ennreal.of_real ε) = closed_ball x ε := by ext y; simp [edist_dist]; rw ennreal.of_real_le_of_real_iff h def metric_space.replace_uniformity {α} [U : uniform_space α] (m : metric_space α) (H : @uniformity _ U = @uniformity _ (metric_space.to_uniform_space α)) : metric_space α := { dist := @dist _ m.to_has_dist, dist_self := dist_self, eq_of_dist_eq_zero := @eq_of_dist_eq_zero _ _, dist_comm := dist_comm, dist_triangle := dist_triangle, edist := edist, edist_dist := edist_dist, to_uniform_space := U, uniformity_dist := H.trans (metric_space.uniformity_dist α) } /-- One gets a metric space from an emetric space if the edistance is everywhere finite. We set it up so that the edist and the uniformity are defeq in the metric space and the emetric space -/ def emetric_space.to_metric_space {α : Type u} [e : emetric_space α] (h : ∀x y: α, edist x y ≠ ⊤) : metric_space α := let m : metric_space α := { dist := λx y, ennreal.to_real (edist x y), eq_of_dist_eq_zero := λx y hxy, by simpa [dist, ennreal.to_real_eq_zero_iff, h x y] using hxy, dist_self := λx, by simp, dist_comm := λx y, by simp [emetric_space.edist_comm], dist_triangle := λx y z, begin rw [← ennreal.to_real_add (h _ _) (h _ _), ennreal.to_real_le_to_real (h _ _)], { exact edist_triangle _ _ _ }, { simp [ennreal.add_eq_top, h] } end, edist := λx y, edist x y, edist_dist := λx y, by simp [ennreal.of_real_to_real, h] } in metric_space.replace_uniformity m (by rw [uniformity_edist, uniformity_edist']; refl) section real /-- Instantiate the reals as a metric space. -/ instance real.metric_space : metric_space ℝ := { dist := λx y, abs (x - y), dist_self := by simp [abs_zero], eq_of_dist_eq_zero := by simp [add_neg_eq_zero], dist_comm := assume x y, abs_sub _ _, dist_triangle := assume x y z, abs_sub_le _ _ _ } theorem real.dist_eq (x y : ℝ) : dist x y = abs (x - y) := rfl theorem real.dist_0_eq_abs (x : ℝ) : dist x 0 = abs x := by simp [real.dist_eq] instance : orderable_topology ℝ := orderable_topology_of_nhds_abs $ λ x, begin simp only [show ∀ r, {b : ℝ | abs (x - b) < r} = ball x r, by simp [-sub_eq_add_neg, abs_sub, ball, real.dist_eq]], apply le_antisymm, { simp [le_infi_iff], exact λ ε ε0, mem_nhds_sets (is_open_ball) (mem_ball_self ε0) }, { intros s h, rcases mem_nhds_iff.1 h with ⟨ε, ε0, ss⟩, exact mem_infi_sets _ (mem_infi_sets ε0 (mem_principal_sets.2 ss)) }, end lemma closed_ball_Icc {x r : ℝ} : closed_ball x r = Icc (x-r) (x+r) := by ext y; rw [mem_closed_ball, dist_comm, real.dist_eq, abs_sub_le_iff, mem_Icc, ← sub_le_iff_le_add', sub_le] lemma squeeze_zero {α} {f g : α → ℝ} {t₀ : filter α} (hf : ∀t, 0 ≤ f t) (hft : ∀t, f t ≤ g t) (g0 : tendsto g t₀ (nhds 0)) : tendsto f t₀ (nhds 0) := begin apply tendsto_of_tendsto_of_tendsto_of_le_of_le (tendsto_const_nhds) g0; simp [*]; exact filter.univ_mem_sets end theorem metric.uniformity_eq_comap_nhds_zero : 𝓤 α = comap (λp:α×α, dist p.1 p.2) (nhds (0 : ℝ)) := begin simp only [uniformity_dist', nhds_eq, comap_infi, comap_principal], congr, funext ε, rw [principal_eq_iff_eq], ext ⟨a, b⟩, simp [real.dist_0_eq_abs] end lemma cauchy_seq_iff_tendsto_dist_at_top_0 [inhabited β] [semilattice_sup β] {u : β → α} : cauchy_seq u ↔ tendsto (λ (n : β × β), dist (u n.1) (u n.2)) at_top (nhds 0) := by rw [cauchy_seq_iff_prod_map, metric.uniformity_eq_comap_nhds_zero, ← map_le_iff_le_comap, filter.map_map, tendsto, prod.map_def] end real section cauchy_seq variables [inhabited β] [semilattice_sup β] /-- In a metric space, Cauchy sequences are characterized by the fact that, eventually, the distance between its elements is arbitrarily small -/ theorem metric.cauchy_seq_iff {u : β → α} : cauchy_seq u ↔ ∀ε>0, ∃N, ∀m n≥N, dist (u m) (u n) < ε := begin unfold cauchy_seq, rw metric.cauchy_iff, simp only [true_and, exists_prop, filter.mem_at_top_sets, filter.at_top_ne_bot, filter.mem_map, ne.def, filter.map_eq_bot_iff, not_false_iff, set.mem_set_of_eq], split, { intros H ε εpos, rcases H ε εpos with ⟨t, ⟨N, hN⟩, ht⟩, exact ⟨N, λm n hm hn, ht _ _ (hN _ hm) (hN _ hn)⟩ }, { intros H ε εpos, rcases H (ε/2) (half_pos εpos) with ⟨N, hN⟩, existsi ball (u N) (ε/2), split, { exact ⟨N, λx hx, hN _ _ hx (le_refl N)⟩ }, { exact λx y hx hy, calc dist x y ≤ dist x (u N) + dist y (u N) : dist_triangle_right _ _ _ ... < ε/2 + ε/2 : add_lt_add hx hy ... = ε : add_halves _ } } end /-- A variation around the metric characterization of Cauchy sequences -/ theorem metric.cauchy_seq_iff' {u : β → α} : cauchy_seq u ↔ ∀ε>0, ∃N, ∀n≥N, dist (u n) (u N) < ε := begin rw metric.cauchy_seq_iff, split, { intros H ε εpos, rcases H ε εpos with ⟨N, hN⟩, exact ⟨N, λn hn, hN _ _ hn (le_refl N)⟩ }, { intros H ε εpos, rcases H (ε/2) (half_pos εpos) with ⟨N, hN⟩, exact ⟨N, λ m n hm hn, calc dist (u m) (u n) ≤ dist (u m) (u N) + dist (u n) (u N) : dist_triangle_right _ _ _ ... < ε/2 + ε/2 : add_lt_add (hN _ hm) (hN _ hn) ... = ε : add_halves _⟩ } end /-- A Cauchy sequence on the natural numbers is bounded. -/ theorem cauchy_seq_bdd {u : ℕ → α} (hu : cauchy_seq u) : ∃ R > 0, ∀ m n, dist (u m) (u n) < R := begin rcases metric.cauchy_seq_iff'.1 hu 1 zero_lt_one with ⟨N, hN⟩, suffices : ∃ R > 0, ∀ n, dist (u n) (u N) < R, { rcases this with ⟨R, R0, H⟩, exact ⟨_, add_pos R0 R0, λ m n, lt_of_le_of_lt (dist_triangle_right _ _ _) (add_lt_add (H m) (H n))⟩ }, let R := finset.sup (finset.range N) (λ n, nndist (u n) (u N)), refine ⟨↑R + 1, add_pos_of_nonneg_of_pos R.2 zero_lt_one, λ n, _⟩, cases le_or_lt N n, { exact lt_of_lt_of_le (hN _ h) (le_add_of_nonneg_left R.2) }, { have : _ ≤ R := finset.le_sup (finset.mem_range.2 h), exact lt_of_le_of_lt this (lt_add_of_pos_right _ zero_lt_one) } end /-- Yet another metric characterization of Cauchy sequences on integers. This one is often the most efficient. -/ lemma cauchy_seq_iff_le_tendsto_0 {s : ℕ → α} : cauchy_seq s ↔ ∃ b : ℕ → ℝ, (∀ n, 0 ≤ b n) ∧ (∀ n m N : ℕ, N ≤ n → N ≤ m → dist (s n) (s m) ≤ b N) ∧ tendsto b at_top (nhds 0) := ⟨λ hs, begin /- `s` is a Cauchy sequence. The sequence `b` will be constructed by taking the supremum of the distances between `s n` and `s m` for `n m ≥ N`. First, we prove that all these distances are bounded, as otherwise the Sup would not make sense. -/ let S := λ N, (λ(p : ℕ × ℕ), dist (s p.1) (s p.2)) '' {p | p.1 ≥ N ∧ p.2 ≥ N}, have hS : ∀ N, ∃ x, ∀ y ∈ S N, y ≤ x, { rcases cauchy_seq_bdd hs with ⟨R, R0, hR⟩, refine λ N, ⟨R, _⟩, rintro _ ⟨⟨m, n⟩, _, rfl⟩, exact le_of_lt (hR m n) }, have bdd : bdd_above (range (λ(p : ℕ × ℕ), dist (s p.1) (s p.2))), { rcases cauchy_seq_bdd hs with ⟨R, R0, hR⟩, use R, rintro _ ⟨⟨m, n⟩, rfl⟩, exact le_of_lt (hR m n) }, -- Prove that it bounds the distances of points in the Cauchy sequence have ub : ∀ m n N, N ≤ m → N ≤ n → dist (s m) (s n) ≤ real.Sup (S N) := λ m n N hm hn, real.le_Sup _ (hS N) ⟨⟨_, _⟩, ⟨hm, hn⟩, rfl⟩, have S0m : ∀ n, (0:ℝ) ∈ S n := λ n, ⟨⟨n, n⟩, ⟨le_refl _, le_refl _⟩, dist_self _⟩, have S0 := λ n, real.le_Sup _ (hS n) (S0m n), -- Prove that it tends to `0`, by using the Cauchy property of `s` refine ⟨λ N, real.Sup (S N), S0, ub, metric.tendsto_at_top.2 (λ ε ε0, _)⟩, refine (metric.cauchy_seq_iff.1 hs (ε/2) (half_pos ε0)).imp (λ N hN n hn, _), rw [real.dist_0_eq_abs, abs_of_nonneg (S0 n)], refine lt_of_le_of_lt (real.Sup_le_ub _ ⟨_, S0m _⟩ _) (half_lt_self ε0), rintro _ ⟨⟨m', n'⟩, ⟨hm', hn'⟩, rfl⟩, exact le_of_lt (hN _ _ (le_trans hn hm') (le_trans hn hn')) end, λ ⟨b, _, b_bound, b_lim⟩, metric.cauchy_seq_iff.2 $ λ ε ε0, (metric.tendsto_at_top.1 b_lim ε ε0).imp $ λ N hN m n hm hn, calc dist (s m) (s n) ≤ b N : b_bound m n N hm hn ... ≤ abs (b N) : le_abs_self _ ... = dist (b N) 0 : by rw real.dist_0_eq_abs; refl ... < ε : (hN _ (le_refl N)) ⟩ end cauchy_seq def metric_space.induced {α β} (f : α → β) (hf : function.injective f) (m : metric_space β) : metric_space α := { dist := λ x y, dist (f x) (f y), dist_self := λ x, dist_self _, eq_of_dist_eq_zero := λ x y h, hf (dist_eq_zero.1 h), dist_comm := λ x y, dist_comm _ _, dist_triangle := λ x y z, dist_triangle _ _ _, edist := λ x y, edist (f x) (f y), edist_dist := λ x y, edist_dist _ _, to_uniform_space := uniform_space.comap f m.to_uniform_space, uniformity_dist := begin apply @uniformity_dist_of_mem_uniformity _ _ _ _ _ (λ x y, dist (f x) (f y)), refine λ s, mem_comap_sets.trans _, split; intro H, { rcases H with ⟨r, ru, rs⟩, rcases mem_uniformity_dist.1 ru with ⟨ε, ε0, hε⟩, refine ⟨ε, ε0, λ a b h, rs (hε _)⟩, exact h }, { rcases H with ⟨ε, ε0, hε⟩, exact ⟨_, dist_mem_uniformity ε0, λ ⟨a, b⟩, hε⟩ } end } instance subtype.metric_space {p : α → Prop} [t : metric_space α] : metric_space (subtype p) := metric_space.induced subtype.val (λ x y, subtype.eq) t theorem subtype.dist_eq {p : α → Prop} [t : metric_space α] (x y : subtype p) : dist x y = dist x.1 y.1 := rfl section nnreal instance : metric_space nnreal := by unfold nnreal; apply_instance end nnreal section prod instance prod.metric_space_max [metric_space β] : metric_space (α × β) := { dist := λ x y, max (dist x.1 y.1) (dist x.2 y.2), dist_self := λ x, by simp, eq_of_dist_eq_zero := λ x y h, begin cases max_le_iff.1 (le_of_eq h) with h₁ h₂, exact prod.ext_iff.2 ⟨dist_le_zero.1 h₁, dist_le_zero.1 h₂⟩ end, dist_comm := λ x y, by simp [dist_comm], dist_triangle := λ x y z, max_le (le_trans (dist_triangle _ _ _) (add_le_add (le_max_left _ _) (le_max_left _ _))) (le_trans (dist_triangle _ _ _) (add_le_add (le_max_right _ _) (le_max_right _ _))), edist := λ x y, max (edist x.1 y.1) (edist x.2 y.2), edist_dist := assume x y, begin have : monotone ennreal.of_real := assume x y h, ennreal.of_real_le_of_real h, rw [edist_dist, edist_dist, (max_distrib_of_monotone this).symm] end, uniformity_dist := begin refine uniformity_prod.trans _, simp [uniformity_dist, comap_infi], rw ← infi_inf_eq, congr, funext, rw ← infi_inf_eq, congr, funext, simp [inf_principal, ext_iff, max_lt_iff] end, to_uniform_space := prod.uniform_space } lemma prod.dist_eq [metric_space β] {x y : α × β} : dist x y = max (dist x.1 y.1) (dist x.2 y.2) := rfl end prod theorem uniform_continuous_dist' : uniform_continuous (λp:α×α, dist p.1 p.2) := metric.uniform_continuous_iff.2 (λ ε ε0, ⟨ε/2, half_pos ε0, begin suffices, { intros p q h, cases p with p₁ p₂, cases q with q₁ q₂, cases max_lt_iff.1 h with h₁ h₂, clear h, dsimp at h₁ h₂ ⊢, rw real.dist_eq, refine abs_sub_lt_iff.2 ⟨_, _⟩, { revert p₁ p₂ q₁ q₂ h₁ h₂, exact this }, { apply this; rwa dist_comm } }, intros p₁ p₂ q₁ q₂ h₁ h₂, have := add_lt_add (abs_sub_lt_iff.1 (lt_of_le_of_lt (abs_dist_sub_le p₁ q₁ p₂) h₁)).1 (abs_sub_lt_iff.1 (lt_of_le_of_lt (abs_dist_sub_le p₂ q₂ q₁) h₂)).1, rwa [add_halves, dist_comm p₂, sub_add_sub_cancel, dist_comm q₂] at this end⟩) theorem uniform_continuous_dist [uniform_space β] {f g : β → α} (hf : uniform_continuous f) (hg : uniform_continuous g) : uniform_continuous (λb, dist (f b) (g b)) := (hf.prod_mk hg).comp uniform_continuous_dist' theorem continuous_dist' : continuous (λp:α×α, dist p.1 p.2) := uniform_continuous_dist'.continuous theorem continuous_dist [topological_space β] {f g : β → α} (hf : continuous f) (hg : continuous g) : continuous (λb, dist (f b) (g b)) := (hf.prod_mk hg).comp continuous_dist' theorem tendsto_dist {f g : β → α} {x : filter β} {a b : α} (hf : tendsto f x (nhds a)) (hg : tendsto g x (nhds b)) : tendsto (λx, dist (f x) (g x)) x (nhds (dist a b)) := have tendsto (λp:α×α, dist p.1 p.2) (nhds (a, b)) (nhds (dist a b)), from continuous_iff_continuous_at.mp continuous_dist' (a, b), (hf.prod_mk hg).comp (by rw [nhds_prod_eq] at this; exact this) lemma nhds_comap_dist (a : α) : (nhds (0 : ℝ)).comap (λa', dist a' a) = nhds a := have h₁ : ∀ε, (λa', dist a' a) ⁻¹' ball 0 ε ⊆ ball a ε, by simp [subset_def, real.dist_0_eq_abs], have h₂ : tendsto (λa', dist a' a) (nhds a) (nhds (dist a a)), from tendsto_dist tendsto_id tendsto_const_nhds, le_antisymm (by simp [h₁, nhds_eq, infi_le_infi, principal_mono, -le_principal_iff, -le_infi_iff]) (by simpa [map_le_iff_le_comap.symm, tendsto] using h₂) lemma tendsto_iff_dist_tendsto_zero {f : β → α} {x : filter β} {a : α} : (tendsto f x (nhds a)) ↔ (tendsto (λb, dist (f b) a) x (nhds 0)) := by rw [← nhds_comap_dist a, tendsto_comap_iff] lemma uniform_continuous_nndist' : uniform_continuous (λp:α×α, nndist p.1 p.2) := uniform_continuous_subtype_mk uniform_continuous_dist' _ lemma continuous_nndist' : continuous (λp:α×α, nndist p.1 p.2) := uniform_continuous_nndist'.continuous lemma tendsto_nndist' (a b :α) : tendsto (λp:α×α, nndist p.1 p.2) (filter.prod (nhds a) (nhds b)) (nhds (nndist a b)) := by rw [← nhds_prod_eq]; exact continuous_iff_continuous_at.1 continuous_nndist' _ namespace metric variables {x y z : α} {ε ε₁ ε₂ : ℝ} {s : set α} theorem is_closed_ball : is_closed (closed_ball x ε) := is_closed_le (continuous_dist continuous_id continuous_const) continuous_const /-- ε-characterization of the closure in metric spaces-/ theorem mem_closure_iff' {α : Type u} [metric_space α] {s : set α} {a : α} : a ∈ closure s ↔ ∀ε>0, ∃b ∈ s, dist a b < ε := ⟨begin intros ha ε hε, have A : ball a ε ∩ s ≠ ∅ := mem_closure_iff.1 ha _ is_open_ball (mem_ball_self hε), cases ne_empty_iff_exists_mem.1 A with b hb, simp, exact ⟨b, ⟨hb.2, by have B := hb.1; simpa [mem_ball'] using B⟩⟩ end, begin intros H, apply mem_closure_iff.2, intros o ho ao, rcases is_open_iff.1 ho a ao with ⟨ε, ⟨εpos, hε⟩⟩, rcases H ε εpos with ⟨b, ⟨bs, bdist⟩⟩, have B : b ∈ o ∩ s := ⟨hε (by simpa [dist_comm]), bs⟩, apply ne_empty_of_mem B end⟩ theorem mem_of_closed' {α : Type u} [metric_space α] {s : set α} (hs : is_closed s) {a : α} : a ∈ s ↔ ∀ε>0, ∃b ∈ s, dist a b < ε := by simpa only [closure_eq_of_is_closed hs] using @mem_closure_iff' _ _ s a end metric section pi open finset lattice variables {π : β → Type*} [fintype β] [∀b, metric_space (π b)] instance has_dist_pi : has_dist (Πb, π b) := ⟨λf g, ((finset.sup univ (λb, nndist (f b) (g b)) : nnreal) : ℝ)⟩ lemma dist_pi_def (f g : Πb, π b) : dist f g = (finset.sup univ (λb, nndist (f b) (g b)) : nnreal) := rfl instance metric_space_pi : metric_space (Πb, π b) := { dist := dist, dist_self := assume f, (nnreal.coe_eq_zero _).2 $ bot_unique $ finset.sup_le $ by simp, dist_comm := assume f g, nnreal.eq_iff.2 $ by congr; ext a; exact nndist_comm _ _, dist_triangle := assume f g h, show dist f h ≤ (dist f g) + (dist g h), from begin simp only [dist_pi_def, (nnreal.coe_add _ _).symm, nnreal.coe_le.symm, finset.sup_le_iff], assume b hb, exact le_trans (nndist_triangle _ (g b) _) (add_le_add (le_sup hb) (le_sup hb)) end, eq_of_dist_eq_zero := assume f g eq0, begin simp only [dist_pi_def, nnreal.coe_eq_zero, nnreal.bot_eq_zero.symm, eq_bot_iff, finset.sup_le_iff] at eq0, exact (funext $ assume b, eq_of_nndist_eq_zero $ bot_unique $ eq0 b $ mem_univ b), end, edist := λ f g, finset.sup univ (λb, edist (f b) (g b)), edist_dist := assume x y, begin have A : sup univ (λ (b : β), ((nndist (x b) (y b)) : ennreal)) = ↑(sup univ (λ (b : β), nndist (x b) (y b))), { refine eq.symm (comp_sup_eq_sup_comp _ _ _), exact (assume x y h, ennreal.coe_le_coe.2 h), refl }, simp [dist, edist_nndist, ennreal.of_real, A] end } end pi section compact /-- Any compact set in a metric space can be covered by finitely many balls of a given positive radius -/ lemma finite_cover_balls_of_compact {α : Type u} [metric_space α] {s : set α} (hs : compact s) {e : ℝ} (he : e > 0) : ∃t ⊆ s, finite t ∧ s ⊆ ⋃x∈t, ball x e := begin apply compact_elim_finite_subcover_image hs, { simp [is_open_ball] }, { intros x xs, simp, exact ⟨x, ⟨xs, by simpa⟩⟩ } end end compact section proper_space open metric /-- A metric space is proper if all closed balls are compact. -/ class proper_space (α : Type u) [metric_space α] : Prop := (compact_ball : ∀x:α, ∀r, compact (closed_ball x r)) /- A compact metric space is proper -/ instance proper_of_compact [metric_space α] [compact_space α] : proper_space α := ⟨assume x r, compact_of_is_closed_subset compact_univ is_closed_ball (subset_univ _)⟩ /-- A proper space is locally compact -/ instance locally_compact_of_proper [metric_space α] [proper_space α] : locally_compact_space α := begin apply locally_compact_of_compact_nhds, intros x, existsi closed_ball x 1, split, { apply mem_nhds_iff.2, existsi (1 : ℝ), simp, exact ⟨zero_lt_one, ball_subset_closed_ball⟩ }, { apply proper_space.compact_ball } end /-- A proper space is complete -/ instance complete_of_proper {α : Type u} [metric_space α] [proper_space α] : complete_space α := ⟨begin intros f hf, /- We want to show that the Cauchy filter `f` is converging. It suffices to find a closed ball (therefore compact by properness) where it is nontrivial. -/ have A : ∃ t ∈ f, ∀ x y ∈ t, dist x y < 1 := (metric.cauchy_iff.1 hf).2 1 zero_lt_one, rcases A with ⟨t, ⟨t_fset, ht⟩⟩, rcases inhabited_of_mem_sets hf.1 t_fset with ⟨x, xt⟩, have : t ⊆ closed_ball x 1 := by intros y yt; simp [dist_comm]; apply le_of_lt (ht x y xt yt), have : closed_ball x 1 ∈ f := f.sets_of_superset t_fset this, rcases (compact_iff_totally_bounded_complete.1 (proper_space.compact_ball x 1)).2 f hf (le_principal_iff.2 this) with ⟨y, _, hy⟩, exact ⟨y, hy⟩ end⟩ /-- A proper metric space is separable, and therefore second countable. Indeed, any ball is compact, and therefore admits a countable dense subset. Taking a countable union over the balls centered at a fixed point and with integer radius, one obtains a countable set which is dense in the whole space. -/ instance second_countable_of_proper [metric_space α] [proper_space α] : second_countable_topology α := begin /- We show that the space admits a countable dense subset. The case where the space is empty is special, and trivial. -/ have A : (univ : set α) = ∅ → ∃(s : set α), countable s ∧ closure s = (univ : set α) := assume H, ⟨∅, ⟨by simp, by simp; exact H.symm⟩⟩, have B : (univ : set α) ≠ ∅ → ∃(s : set α), countable s ∧ closure s = (univ : set α) := begin /- When the space is not empty, we take a point `x` in the space, and then a countable set `T r` which is dense in the closed ball `closed_ball x r` for each `r`. Then the set `t = ⋃ T n` (where the union is over all integers `n`) is countable, as a countable union of countable sets, and dense in the space by construction. -/ assume non_empty, rcases ne_empty_iff_exists_mem.1 non_empty with ⟨x, x_univ⟩, choose T a using show ∀ (r:ℝ), ∃ t ⊆ closed_ball x r, (countable (t : set α) ∧ closed_ball x r = closure t), from assume r, emetric.countable_closure_of_compact (proper_space.compact_ball _ _), let t := (⋃n:ℕ, T (n : ℝ)), have T₁ : countable t := by finish [countable_Union], have T₂ : closure t ⊆ univ := by simp, have T₃ : univ ⊆ closure t := begin intros y y_univ, rcases exists_nat_gt (dist y x) with ⟨n, n_large⟩, have h : y ∈ closed_ball x (n : ℝ) := by simp; apply le_of_lt n_large, have h' : closed_ball x (n : ℝ) = closure (T (n : ℝ)) := by finish, have : y ∈ closure (T (n : ℝ)) := by rwa h' at h, show y ∈ closure t, from mem_of_mem_of_subset this (by apply closure_mono; apply subset_Union (λ(n:ℕ), T (n:ℝ))), end, exact ⟨t, ⟨T₁, subset.antisymm T₂ T₃⟩⟩ end, haveI : separable_space α := ⟨by_cases A B⟩, apply emetric.second_countable_of_separable, end end proper_space namespace metric section second_countable open topological_space /-- A metric space is second countable if, for every ε > 0, there is a countable set which is ε-dense. -/ lemma second_countable_of_almost_dense_set (H : ∀ε > (0 : ℝ), ∃ s : set α, countable s ∧ (∀x, ∃y ∈ s, dist x y ≤ ε)) : second_countable_topology α := begin choose T T_dense using H, have I1 : ∀n:ℕ, (n:ℝ) + 1 > 0 := λn, lt_of_lt_of_le zero_lt_one (le_add_of_nonneg_left (nat.cast_nonneg _)), have I : ∀n:ℕ, (n+1 : ℝ)⁻¹ > 0 := λn, inv_pos'.2 (I1 n), let t := ⋃n:ℕ, T (n+1)⁻¹ (I n), have count_t : countable t := by finish [countable_Union], have clos_t : closure t = univ, { refine subset.antisymm (subset_univ _) (λx xuniv, mem_closure_iff'.2 (λε εpos, _)), rcases exists_nat_gt ε⁻¹ with ⟨n, hn⟩, have : ε⁻¹ < n + 1 := lt_of_lt_of_le hn (le_add_of_nonneg_right zero_le_one), have nε : ((n:ℝ)+1)⁻¹ < ε := (inv_lt (I1 n) εpos).2 this, rcases (T_dense (n+1)⁻¹ (I n)).2 x with ⟨y, yT, Dxy⟩, have : y ∈ t := mem_of_mem_of_subset yT (by apply subset_Union (λ (n:ℕ), T (n+1)⁻¹ (I n))), exact ⟨y, this, lt_of_le_of_lt Dxy nε⟩ }, haveI : separable_space α := ⟨⟨t, ⟨count_t, clos_t⟩⟩⟩, exact emetric.second_countable_of_separable α end /-- A metric space space is second countable if one can reconstruct up to any ε>0 any element of the space from countably many data. -/ lemma second_countable_of_countable_discretization {α : Type u} [metric_space α] (H : ∀ε > (0 : ℝ), ∃ (β : Type u) [encodable β] (F : α → β), ∀x y, F x = F y → dist x y ≤ ε) : second_countable_topology α := begin classical, by_cases hs : (univ : set α) = ∅, { haveI : compact_space α := ⟨by rw hs; exact compact_of_finite (set.finite_empty)⟩, by apply_instance }, rcases exists_mem_of_ne_empty hs with ⟨x0, hx0⟩, letI : inhabited α := ⟨x0⟩, refine second_countable_of_almost_dense_set (λε ε0, _), rcases H ε ε0 with ⟨β, fβ, F, hF⟩, let Finv := function.inv_fun F, refine ⟨range Finv, ⟨countable_range _, λx, _⟩⟩, let x' := Finv (F x), have : F x' = F x := function.inv_fun_eq ⟨x, rfl⟩, exact ⟨x', mem_range_self _, hF _ _ this.symm⟩ end end second_countable end metric lemma lebesgue_number_lemma_of_metric {s : set α} {ι} {c : ι → set α} (hs : compact s) (hc₁ : ∀ i, is_open (c i)) (hc₂ : s ⊆ ⋃ i, c i) : ∃ δ > 0, ∀ x ∈ s, ∃ i, ball x δ ⊆ c i := let ⟨n, en, hn⟩ := lebesgue_number_lemma hs hc₁ hc₂, ⟨δ, δ0, hδ⟩ := mem_uniformity_dist.1 en in ⟨δ, δ0, assume x hx, let ⟨i, hi⟩ := hn x hx in ⟨i, assume y hy, hi (hδ (mem_ball'.mp hy))⟩⟩ lemma lebesgue_number_lemma_of_metric_sUnion {s : set α} {c : set (set α)} (hs : compact s) (hc₁ : ∀ t ∈ c, is_open t) (hc₂ : s ⊆ ⋃₀ c) : ∃ δ > 0, ∀ x ∈ s, ∃ t ∈ c, ball x δ ⊆ t := by rw sUnion_eq_Union at hc₂; simpa using lebesgue_number_lemma_of_metric hs (by simpa) hc₂ namespace metric /-- Boundedness of a subset of a metric space. We formulate the definition to work even in the empty space. -/ def bounded (s : set α) : Prop := ∃C, ∀x y ∈ s, dist x y ≤ C section bounded variables {x : α} {s t : set α} {r : ℝ} @[simp] lemma bounded_empty : bounded (∅ : set α) := ⟨0, by simp⟩ lemma bounded_iff_mem_bounded : bounded s ↔ ∀ x ∈ s, bounded s := ⟨λ h _ _, h, λ H, begin classical, by_cases s = ∅, { subst s, exact ⟨0, by simp⟩ }, { rcases exists_mem_of_ne_empty h with ⟨x, hx⟩, exact H x hx } end⟩ /-- Subsets of a bounded set are also bounded -/ lemma bounded.subset (incl : s ⊆ t) : bounded t → bounded s := Exists.imp $ λ C hC x y hx hy, hC x y (incl hx) (incl hy) /-- Closed balls are bounded -/ lemma bounded_closed_ball : bounded (closed_ball x r) := ⟨r + r, λ y z hy hz, begin simp only [mem_closed_ball] at *, calc dist y z ≤ dist y x + dist z x : dist_triangle_right _ _ _ ... ≤ r + r : add_le_add hy hz end⟩ /-- Open balls are bounded -/ lemma bounded_ball : bounded (ball x r) := bounded_closed_ball.subset ball_subset_closed_ball /-- Given a point, a bounded subset is included in some ball around this point -/ lemma bounded_iff_subset_ball (c : α) : bounded s ↔ ∃r, s ⊆ closed_ball c r := begin split; rintro ⟨C, hC⟩, { classical, by_cases s = ∅, { subst s, exact ⟨0, by simp⟩ }, { rcases exists_mem_of_ne_empty h with ⟨x, hx⟩, exact ⟨C + dist x c, λ y hy, calc dist y c ≤ dist y x + dist x c : dist_triangle _ _ _ ... ≤ C + dist x c : add_le_add_right (hC y x hy hx) _⟩ } }, { exact bounded_closed_ball.subset hC } end /-- The union of two bounded sets is bounded iff each of the sets is bounded -/ @[simp] lemma bounded_union : bounded (s ∪ t) ↔ bounded s ∧ bounded t := ⟨λh, ⟨h.subset (by simp), h.subset (by simp)⟩, begin rintro ⟨hs, ht⟩, refine bounded_iff_mem_bounded.2 (λ x _, _), rw bounded_iff_subset_ball x at hs ht ⊢, rcases hs with ⟨Cs, hCs⟩, rcases ht with ⟨Ct, hCt⟩, exact ⟨max Cs Ct, union_subset (subset.trans hCs $ closed_ball_subset_closed_ball $ le_max_left _ _) (subset.trans hCt $ closed_ball_subset_closed_ball $ le_max_right _ _)⟩, end⟩ /-- A finite union of bounded sets is bounded -/ lemma bounded_bUnion {I : set β} {s : β → set α} (H : finite I) : bounded (⋃i∈I, s i) ↔ ∀i ∈ I, bounded (s i) := finite.induction_on H (by simp) $ λ x I _ _ IH, by simp [or_imp_distrib, forall_and_distrib, IH] /-- A compact set is bounded -/ lemma bounded_of_compact {s : set α} (h : compact s) : bounded s := -- We cover the compact set by finitely many balls of radius 1, -- and then argue that a finite union of bounded sets is bounded let ⟨t, ht, fint, subs⟩ := finite_cover_balls_of_compact h zero_lt_one in bounded.subset subs $ (bounded_bUnion fint).2 $ λ i hi, bounded_ball /-- A finite set is bounded -/ lemma bounded_of_finite {s : set α} (h : finite s) : bounded s := bounded_of_compact $ compact_of_finite h /-- A singleton is bounded -/ lemma bounded_singleton {x : α} : bounded ({x} : set α) := bounded_of_finite $ finite_singleton _ /-- Characterization of the boundedness of the range of a function -/ lemma bounded_range_iff {f : β → α} : bounded (range f) ↔ ∃C, ∀x y, dist (f x) (f y) ≤ C := exists_congr $ λ C, ⟨ λ H x y, H _ _ ⟨x, rfl⟩ ⟨y, rfl⟩, by rintro H _ _ ⟨x, rfl⟩ ⟨y, rfl⟩; exact H x y⟩ /-- In a compact space, all sets are bounded -/ lemma bounded_of_compact_space [compact_space α] : bounded s := (bounded_of_compact compact_univ).subset (subset_univ _) /-- In a proper space, a set is compact if and only if it is closed and bounded -/ lemma compact_iff_closed_bounded [proper_space α] : compact s ↔ is_closed s ∧ bounded s := ⟨λ h, ⟨closed_of_compact _ h, bounded_of_compact h⟩, begin rintro ⟨hc, hb⟩, classical, by_cases s = ∅, {simp [h, compact_empty]}, rcases exists_mem_of_ne_empty h with ⟨x, hx⟩, rcases (bounded_iff_subset_ball x).1 hb with ⟨r, hr⟩, exact compact_of_is_closed_subset (proper_space.compact_ball x r) hc hr end⟩ end bounded section diam variables {s : set α} {x y : α} /-- The diameter of a set in a metric space. To get controllable behavior even when the diameter should be infinite, we express it in terms of the emetric.diameter -/ def diam (s : set α) : ℝ := ennreal.to_real (emetric.diam s) /-- The diameter of a set is always nonnegative -/ lemma diam_nonneg : 0 ≤ diam s := by simp [diam] /-- The empty set has zero diameter -/ @[simp] lemma diam_empty : diam (∅ : set α) = 0 := by simp [diam] /-- A singleton has zero diameter -/ @[simp] lemma diam_singleton : diam ({x} : set α) = 0 := by simp [diam] /-- Characterize the boundedness of a set in terms of the finiteness of its emetric.diameter. -/ lemma bounded_iff_diam_ne_top : bounded s ↔ emetric.diam s ≠ ⊤ := begin classical, by_cases hs : s = ∅, { simp [hs] }, { rcases ne_empty_iff_exists_mem.1 hs with ⟨x, hx⟩, split, { assume bs, rcases (bounded_iff_subset_ball x).1 bs with ⟨r, hr⟩, have r0 : 0 ≤ r := by simpa [closed_ball] using hr hx, have : emetric.diam s < ⊤ := calc emetric.diam s ≤ emetric.diam (emetric.closed_ball x (ennreal.of_real r)) : by rw emetric_closed_ball r0; exact emetric.diam_mono hr ... ≤ 2 * (ennreal.of_real r) : emetric.diam_closed_ball ... < ⊤ : begin apply ennreal.lt_top_iff_ne_top.2, simp [ennreal.mul_eq_top], end, exact ennreal.lt_top_iff_ne_top.1 this }, { assume ds, have : s ⊆ closed_ball x (ennreal.to_real (emetric.diam s)), { rw [← emetric_closed_ball ennreal.to_real_nonneg, ennreal.of_real_to_real ds], exact λy hy, emetric.edist_le_diam_of_mem hy hx }, exact bounded.subset this (bounded_closed_ball) }} end /-- An unbounded set has zero diameter. If you would prefer to get the value ∞, use `emetric.diam`. This lemma makes it possible to avoid side conditions in some situations -/ lemma diam_eq_zero_of_unbounded (h : ¬(bounded s)) : diam s = 0 := begin simp only [bounded_iff_diam_ne_top, not_not, ne.def] at h, simp [diam, h] end /-- If `s ⊆ t`, then the diameter of `s` is bounded by that of `t`, provided `t` is bounded. -/ lemma diam_mono {s t : set α} (h : s ⊆ t) (ht : bounded t) : diam s ≤ diam t := begin unfold diam, rw ennreal.to_real_le_to_real (bounded_iff_diam_ne_top.1 (bounded.subset h ht)) (bounded_iff_diam_ne_top.1 ht), exact emetric.diam_mono h end /-- The distance between two points in a set is controlled by the diameter of the set. -/ lemma dist_le_diam_of_mem (h : bounded s) (hx : x ∈ s) (hy : y ∈ s) : dist x y ≤ diam s := begin rw [diam, dist_edist], rw ennreal.to_real_le_to_real (edist_ne_top _ _) (bounded_iff_diam_ne_top.1 h), exact emetric.edist_le_diam_of_mem hx hy end /-- If the distance between any two points in a set is bounded by some constant, this constant bounds the diameter. -/ lemma diam_le_of_forall_dist_le {d : real} (hd : d ≥ 0) (h : ∀x y ∈ s, dist x y ≤ d) : diam s ≤ d := begin have I : emetric.diam s ≤ ennreal.of_real d, { refine emetric.diam_le_of_forall_edist_le (λx y hx hy, _), rw [edist_dist], exact ennreal.of_real_le_of_real (h x y hx hy) }, have A : emetric.diam s ≠ ⊤ := ennreal.lt_top_iff_ne_top.1 (lt_of_le_of_lt I (ennreal.lt_top_iff_ne_top.2 (by simp))), rw [← ennreal.to_real_of_real hd, diam, ennreal.to_real_le_to_real A], { exact I }, { simp } end /-- The diameter of a union is controlled by the sum of the diameters, and the distance between any two points in each of the sets. This lemma is true without any side condition, since it is obviously true if `s ∪ t` is unbounded. -/ lemma diam_union {t : set α} (xs : x ∈ s) (yt : y ∈ t) : diam (s ∪ t) ≤ diam s + dist x y + diam t := have I1 : ¬(bounded (s ∪ t)) → diam (s ∪ t) ≤ diam s + dist x y + diam t := λh, calc diam (s ∪ t) = 0 + 0 + 0 : by simp [diam_eq_zero_of_unbounded h] ... ≤ diam s + dist x y + diam t : add_le_add (add_le_add diam_nonneg dist_nonneg) diam_nonneg, have I2 : (bounded (s ∪ t)) → diam (s ∪ t) ≤ diam s + dist x y + diam t := λh, begin have : bounded s := bounded.subset (subset_union_left _ _) h, have : bounded t := bounded.subset (subset_union_right _ _) h, have A : ∀a ∈ s, ∀b ∈ t, dist a b ≤ diam s + dist x y + diam t := λa ha b hb, calc dist a b ≤ dist a x + dist x y + dist y b : dist_triangle4 _ _ _ _ ... ≤ diam s + dist x y + diam t : add_le_add (add_le_add (dist_le_diam_of_mem ‹bounded s› ha xs) (le_refl _)) (dist_le_diam_of_mem ‹bounded t› yt hb), have B : ∀a b ∈ s ∪ t, dist a b ≤ diam s + dist x y + diam t := λa b ha hb, begin cases (mem_union _ _ _).1 ha with h'a h'a; cases (mem_union _ _ _).1 hb with h'b h'b, { calc dist a b ≤ diam s : dist_le_diam_of_mem ‹bounded s› h'a h'b ... = diam s + (0 + 0) : by simp ... ≤ diam s + (dist x y + diam t) : add_le_add (le_refl _) (add_le_add dist_nonneg diam_nonneg) ... = diam s + dist x y + diam t : by simp only [add_comm, eq_self_iff_true, add_left_comm] }, { exact A a h'a b h'b }, { have Z := A b h'b a h'a, rwa [dist_comm] at Z }, { calc dist a b ≤ diam t : dist_le_diam_of_mem ‹bounded t› h'a h'b ... = (0 + 0) + diam t : by simp ... ≤ (diam s + dist x y) + diam t : add_le_add (add_le_add diam_nonneg dist_nonneg) (le_refl _) } end, have C : 0 ≤ diam s + dist x y + diam t := calc 0 = 0 + 0 + 0 : by simp ... ≤ diam s + dist x y + diam t : add_le_add (add_le_add diam_nonneg dist_nonneg) diam_nonneg, exact diam_le_of_forall_dist_le C B end, classical.by_cases I2 I1 /-- If two sets intersect, the diameter of the union is bounded by the sum of the diameters. -/ lemma diam_union' {t : set α} (h : s ∩ t ≠ ∅) : diam (s ∪ t) ≤ diam s + diam t := begin rcases ne_empty_iff_exists_mem.1 h with ⟨x, ⟨xs, xt⟩⟩, simpa using diam_union xs xt end /-- The diameter of a closed ball of radius `r` is at most `2 r`. -/ lemma diam_closed_ball {r : ℝ} (h : r ≥ 0) : diam (closed_ball x r) ≤ 2 * r := diam_le_of_forall_dist_le (mul_nonneg (by norm_num) h) $ λa b ha hb, calc dist a b ≤ dist a x + dist b x : dist_triangle_right _ _ _ ... ≤ r + r : add_le_add ha hb ... = 2 * r : by simp [mul_two, mul_comm] /-- The diameter of a ball of radius `r` is at most `2 r`. -/ lemma diam_ball {r : ℝ} (h : r ≥ 0) : diam (ball x r) ≤ 2 * r := le_trans (diam_mono ball_subset_closed_ball bounded_closed_ball) (diam_closed_ball h) end diam end metric
2e5152d3ff97e9f1ea4dfa1579055f6b4cc0b3d3
8d65764a9e5f0923a67fc435eb1a5a1d02fd80e3
/src/logic/relation.lean
33066a24f9ce114d1abcc94a2cb160e2573ca5ca
[ "Apache-2.0" ]
permissive
troyjlee/mathlib
e18d4b8026e32062ab9e89bc3b003a5d1cfec3f5
45e7eb8447555247246e3fe91c87066506c14875
refs/heads/master
1,689,248,035,046
1,629,470,528,000
1,629,470,528,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
16,555
lean
/- Copyright (c) 2018 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl Transitive reflexive as well as reflexive closure of relations. -/ import tactic.basic variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} section ne_imp variable {r : α → α → Prop} lemma is_refl.reflexive [is_refl α r] : reflexive r := λ x, is_refl.refl x /-- To show a reflexive relation `r : α → α → Prop` holds over `x y : α`, it suffices to show it holds when `x ≠ y`. -/ lemma reflexive.rel_of_ne_imp (h : reflexive r) {x y : α} (hr : x ≠ y → r x y) : r x y := begin by_cases hxy : x = y, { exact hxy ▸ h x }, { exact hr hxy } end /-- If a reflexive relation `r : α → α → Prop` holds over `x y : α`, then it holds whether or not `x ≠ y`. -/ lemma reflexive.ne_imp_iff (h : reflexive r) {x y : α} : (x ≠ y → r x y) ↔ r x y := ⟨h.rel_of_ne_imp, λ hr _, hr⟩ /-- If a reflexive relation `r : α → α → Prop` holds over `x y : α`, then it holds whether or not `x ≠ y`. Unlike `reflexive.ne_imp_iff`, this uses `[is_refl α r]`. -/ lemma reflexive_ne_imp_iff [is_refl α r] {x y : α} : (x ≠ y → r x y) ↔ r x y := is_refl.reflexive.ne_imp_iff protected lemma symmetric.iff (H : symmetric r) (x y : α) : r x y ↔ r y x := ⟨λ h, H h, λ h, H h⟩ end ne_imp section comap variables {r : β → β → Prop} lemma reflexive.comap (h : reflexive r) (f : α → β) : reflexive (r on f) := λ a, h (f a) lemma symmetric.comap (h : symmetric r) (f : α → β) : symmetric (r on f) := λ a b hab, h hab lemma transitive.comap (h : transitive r) (f : α → β) : transitive (r on f) := λ a b c hab hbc, h hab hbc end comap namespace relation section comp variables {r : α → β → Prop} {p : β → γ → Prop} {q : γ → δ → Prop} /-- The composition of two relations, yielding a new relation. The result relates a term of `α` and a term of `γ` if there is an intermediate term of `β` related to both. -/ def comp (r : α → β → Prop) (p : β → γ → Prop) (a : α) (c : γ) : Prop := ∃b, r a b ∧ p b c local infixr ` ∘r ` : 80 := relation.comp lemma comp_eq : r ∘r (=) = r := funext $ assume a, funext $ assume b, propext $ iff.intro (assume ⟨c, h, eq⟩, eq ▸ h) (assume h, ⟨b, h, rfl⟩) lemma eq_comp : (=) ∘r r = r := funext $ assume a, funext $ assume b, propext $ iff.intro (assume ⟨c, eq, h⟩, eq.symm ▸ h) (assume h, ⟨a, rfl, h⟩) lemma iff_comp {r : Prop → α → Prop} : (↔) ∘r r = r := have (↔) = (=), by funext a b; exact iff_eq_eq, by rw [this, eq_comp] lemma comp_iff {r : α → Prop → Prop} : r ∘r (↔) = r := have (↔) = (=), by funext a b; exact iff_eq_eq, by rw [this, comp_eq] lemma comp_assoc : (r ∘r p) ∘r q = r ∘r p ∘r q := begin funext a d, apply propext, split, exact assume ⟨c, ⟨b, hab, hbc⟩, hcd⟩, ⟨b, hab, c, hbc, hcd⟩, exact assume ⟨b, hab, c, hbc, hcd⟩, ⟨c, ⟨b, hab, hbc⟩, hcd⟩ end lemma flip_comp : flip (r ∘r p) = (flip p) ∘r (flip r) := begin funext c a, apply propext, split, exact assume ⟨b, hab, hbc⟩, ⟨b, hbc, hab⟩, exact assume ⟨b, hbc, hab⟩, ⟨b, hab, hbc⟩ end end comp /-- The map of a relation `r` through a pair of functions pushes the relation to the codomains of the functions. The resulting relation is defined by having pairs of terms related if they have preimages related by `r`. -/ protected def map (r : α → β → Prop) (f : α → γ) (g : β → δ) : γ → δ → Prop := λc d, ∃a b, r a b ∧ f a = c ∧ g b = d variables {r : α → α → Prop} {a b c d : α} /-- `refl_trans_gen r`: reflexive transitive closure of `r` -/ @[mk_iff relation.refl_trans_gen.cases_tail_iff] inductive refl_trans_gen (r : α → α → Prop) (a : α) : α → Prop | refl : refl_trans_gen a | tail {b c} : refl_trans_gen b → r b c → refl_trans_gen c attribute [refl] refl_trans_gen.refl /-- `refl_gen r`: reflexive closure of `r` -/ @[mk_iff] inductive refl_gen (r : α → α → Prop) (a : α) : α → Prop | refl : refl_gen a | single {b} : r a b → refl_gen b /-- `trans_gen r`: transitive closure of `r` -/ @[mk_iff] inductive trans_gen (r : α → α → Prop) (a : α) : α → Prop | single {b} : r a b → trans_gen b | tail {b c} : trans_gen b → r b c → trans_gen c attribute [refl] refl_gen.refl lemma refl_gen.to_refl_trans_gen : ∀{a b}, refl_gen r a b → refl_trans_gen r a b | a _ refl_gen.refl := by refl | a b (refl_gen.single h) := refl_trans_gen.tail refl_trans_gen.refl h namespace refl_trans_gen @[trans] lemma trans (hab : refl_trans_gen r a b) (hbc : refl_trans_gen r b c) : refl_trans_gen r a c := begin induction hbc, case refl_trans_gen.refl { assumption }, case refl_trans_gen.tail : c d hbc hcd hac { exact hac.tail hcd } end lemma single (hab : r a b) : refl_trans_gen r a b := refl.tail hab lemma head (hab : r a b) (hbc : refl_trans_gen r b c) : refl_trans_gen r a c := begin induction hbc, case refl_trans_gen.refl { exact refl.tail hab }, case refl_trans_gen.tail : c d hbc hcd hac { exact hac.tail hcd } end lemma symmetric (h : symmetric r) : symmetric (refl_trans_gen r) := begin intros x y h, induction h with z w a b c, { refl }, { apply relation.refl_trans_gen.head (h b) c } end lemma cases_tail : refl_trans_gen r a b → b = a ∨ (∃c, refl_trans_gen r a c ∧ r c b) := (cases_tail_iff r a b).1 @[elab_as_eliminator] lemma head_induction_on {P : ∀(a:α), refl_trans_gen r a b → Prop} {a : α} (h : refl_trans_gen r a b) (refl : P b refl) (head : ∀{a c} (h' : r a c) (h : refl_trans_gen r c b), P c h → P a (h.head h')) : P a h := begin induction h generalizing P, case refl_trans_gen.refl { exact refl }, case refl_trans_gen.tail : b c hab hbc ih { apply ih, show P b _, from head hbc _ refl, show ∀a a', r a a' → refl_trans_gen r a' b → P a' _ → P a _, from assume a a' hab hbc, head hab _ } end @[elab_as_eliminator] lemma trans_induction_on {P : ∀{a b : α}, refl_trans_gen r a b → Prop} {a b : α} (h : refl_trans_gen r a b) (ih₁ : ∀a, @P a a refl) (ih₂ : ∀{a b} (h : r a b), P (single h)) (ih₃ : ∀{a b c} (h₁ : refl_trans_gen r a b) (h₂ : refl_trans_gen r b c), P h₁ → P h₂ → P (h₁.trans h₂)) : P h := begin induction h, case refl_trans_gen.refl { exact ih₁ a }, case refl_trans_gen.tail : b c hab hbc ih { exact ih₃ hab (single hbc) ih (ih₂ hbc) } end lemma cases_head (h : refl_trans_gen r a b) : a = b ∨ (∃c, r a c ∧ refl_trans_gen r c b) := begin induction h using relation.refl_trans_gen.head_induction_on, { left, refl }, { right, existsi _, split; assumption } end lemma cases_head_iff : refl_trans_gen r a b ↔ a = b ∨ (∃c, r a c ∧ refl_trans_gen r c b) := begin split, { exact cases_head }, { assume h, rcases h with rfl | ⟨c, hac, hcb⟩, { refl }, { exact head hac hcb } } end lemma total_of_right_unique (U : relator.right_unique r) (ab : refl_trans_gen r a b) (ac : refl_trans_gen r a c) : refl_trans_gen r b c ∨ refl_trans_gen r c b := begin induction ab with b d ab bd IH, { exact or.inl ac }, { rcases IH with IH | IH, { rcases cases_head IH with rfl | ⟨e, be, ec⟩, { exact or.inr (single bd) }, { cases U.unique bd be, exact or.inl ec } }, { exact or.inr (IH.tail bd) } } end end refl_trans_gen namespace trans_gen lemma to_refl {a b} (h : trans_gen r a b) : refl_trans_gen r a b := begin induction h with b h b c _ bc ab, exact refl_trans_gen.single h, exact refl_trans_gen.tail ab bc end @[trans] lemma trans_left (hab : trans_gen r a b) (hbc : refl_trans_gen r b c) : trans_gen r a c := begin induction hbc, case refl_trans_gen.refl : { assumption }, case refl_trans_gen.tail : c d hbc hcd hac { exact hac.tail hcd } end @[trans] lemma trans (hab : trans_gen r a b) (hbc : trans_gen r b c) : trans_gen r a c := trans_left hab hbc.to_refl lemma head' (hab : r a b) (hbc : refl_trans_gen r b c) : trans_gen r a c := trans_left (single hab) hbc lemma tail' (hab : refl_trans_gen r a b) (hbc : r b c) : trans_gen r a c := begin induction hab generalizing c, case refl_trans_gen.refl : c hac { exact single hac }, case refl_trans_gen.tail : d b hab hdb IH { exact tail (IH hdb) hbc } end @[trans] lemma trans_right (hab : refl_trans_gen r a b) (hbc : trans_gen r b c) : trans_gen r a c := begin induction hbc, case trans_gen.single : c hbc { exact tail' hab hbc }, case trans_gen.tail : c d hbc hcd hac { exact hac.tail hcd } end lemma head (hab : r a b) (hbc : trans_gen r b c) : trans_gen r a c := head' hab hbc.to_refl lemma tail'_iff : trans_gen r a c ↔ ∃ b, refl_trans_gen r a b ∧ r b c := begin refine ⟨λ h, _, λ ⟨b, hab, hbc⟩, tail' hab hbc⟩, cases h with _ hac b _ hab hbc, { exact ⟨_, by refl, hac⟩ }, { exact ⟨_, hab.to_refl, hbc⟩ } end lemma head'_iff : trans_gen r a c ↔ ∃ b, r a b ∧ refl_trans_gen r b c := begin refine ⟨λ h, _, λ ⟨b, hab, hbc⟩, head' hab hbc⟩, induction h, case trans_gen.single : c hac { exact ⟨_, hac, by refl⟩ }, case trans_gen.tail : b c hab hbc IH { rcases IH with ⟨d, had, hdb⟩, exact ⟨_, had, hdb.tail hbc⟩ } end lemma trans_gen_eq_self (trans : transitive r) : trans_gen r = r := funext $ λ a, funext $ λ b, propext $ ⟨λ h, begin induction h, case trans_gen.single : c hc { exact hc }, case trans_gen.tail : c d hac hcd hac { exact trans hac hcd } end, trans_gen.single⟩ lemma transitive_trans_gen : transitive (trans_gen r) := assume a b c, trans lemma trans_gen_idem : trans_gen (trans_gen r) = trans_gen r := trans_gen_eq_self transitive_trans_gen lemma trans_gen_lift {p : β → β → Prop} {a b : α} (f : α → β) (h : ∀a b, r a b → p (f a) (f b)) (hab : trans_gen r a b) : trans_gen p (f a) (f b) := begin induction hab, case trans_gen.single : c hac { exact trans_gen.single (h a c hac) }, case trans_gen.tail : c d hac hcd hac { exact trans_gen.tail hac (h c d hcd) } end lemma trans_gen_lift' {p : β → β → Prop} {a b : α} (f : α → β) (h : ∀ a b, r a b → trans_gen p (f a) (f b)) (hab : trans_gen r a b) : trans_gen p (f a) (f b) := by simpa [trans_gen_idem] using trans_gen_lift f h hab lemma trans_gen_closed {p : α → α → Prop} : (∀ a b, r a b → trans_gen p a b) → trans_gen r a b → trans_gen p a b := trans_gen_lift' id end trans_gen section refl_trans_gen open refl_trans_gen lemma refl_trans_gen_iff_eq (h : ∀b, ¬ r a b) : refl_trans_gen r a b ↔ b = a := by rw [cases_head_iff]; simp [h, eq_comm] lemma refl_trans_gen_iff_eq_or_trans_gen : refl_trans_gen r a b ↔ b = a ∨ trans_gen r a b := begin refine ⟨λ h, _, λ h, _⟩, { cases h with c _ hac hcb, { exact or.inl rfl }, { exact or.inr (trans_gen.tail' hac hcb) } }, { rcases h with rfl | h, {refl}, {exact h.to_refl} } end lemma refl_trans_gen_lift {p : β → β → Prop} {a b : α} (f : α → β) (h : ∀a b, r a b → p (f a) (f b)) (hab : refl_trans_gen r a b) : refl_trans_gen p (f a) (f b) := refl_trans_gen.trans_induction_on hab (assume a, refl) (assume a b, refl_trans_gen.single ∘ h _ _) (assume a b c _ _, trans) lemma refl_trans_gen_mono {p : α → α → Prop} : (∀a b, r a b → p a b) → refl_trans_gen r a b → refl_trans_gen p a b := refl_trans_gen_lift id lemma refl_trans_gen_eq_self (refl : reflexive r) (trans : transitive r) : refl_trans_gen r = r := funext $ λ a, funext $ λ b, propext $ ⟨λ h, begin induction h with b c h₁ h₂ IH, {apply refl}, exact trans IH h₂, end, single⟩ lemma reflexive_refl_trans_gen : reflexive (refl_trans_gen r) := assume a, refl lemma transitive_refl_trans_gen : transitive (refl_trans_gen r) := assume a b c, trans lemma refl_trans_gen_idem : refl_trans_gen (refl_trans_gen r) = refl_trans_gen r := refl_trans_gen_eq_self reflexive_refl_trans_gen transitive_refl_trans_gen lemma refl_trans_gen_lift' {p : β → β → Prop} {a b : α} (f : α → β) (h : ∀a b, r a b → refl_trans_gen p (f a) (f b)) (hab : refl_trans_gen r a b) : refl_trans_gen p (f a) (f b) := by simpa [refl_trans_gen_idem] using refl_trans_gen_lift f h hab lemma refl_trans_gen_closed {p : α → α → Prop} : (∀ a b, r a b → refl_trans_gen p a b) → refl_trans_gen r a b → refl_trans_gen p a b := refl_trans_gen_lift' id end refl_trans_gen /-- The join of a relation on a single type is a new relation for which pairs of terms are related if there is a third term they are both related to. For example, if `r` is a relation representing rewrites in a term rewriting system, then *confluence* is the property that if `a` rewrites to both `b` and `c`, then `join r` relates `b` and `c` (see `relation.church_rosser`). -/ def join (r : α → α → Prop) : α → α → Prop := λa b, ∃c, r a c ∧ r b c section join open refl_trans_gen refl_gen lemma church_rosser (h : ∀a b c, r a b → r a c → ∃d, refl_gen r b d ∧ refl_trans_gen r c d) (hab : refl_trans_gen r a b) (hac : refl_trans_gen r a c) : join (refl_trans_gen r) b c := begin induction hab, case refl_trans_gen.refl { exact ⟨c, hac, refl⟩ }, case refl_trans_gen.tail : d e had hde ih { clear hac had a, rcases ih with ⟨b, hdb, hcb⟩, have : ∃a, refl_trans_gen r e a ∧ refl_gen r b a, { clear hcb, induction hdb, case refl_trans_gen.refl { exact ⟨e, refl, refl_gen.single hde⟩ }, case refl_trans_gen.tail : f b hdf hfb ih { rcases ih with ⟨a, hea, hfa⟩, cases hfa with _ hfa, { exact ⟨b, hea.tail hfb, refl_gen.refl⟩ }, { rcases h _ _ _ hfb hfa with ⟨c, hbc, hac⟩, exact ⟨c, hea.trans hac, hbc⟩ } } }, rcases this with ⟨a, hea, hba⟩, cases hba with _ hba, { exact ⟨b, hea, hcb⟩ }, { exact ⟨a, hea, hcb.tail hba⟩ } } end lemma join_of_single (h : reflexive r) (hab : r a b) : join r a b := ⟨b, hab, h b⟩ lemma symmetric_join : symmetric (join r) := assume a b ⟨c, hac, hcb⟩, ⟨c, hcb, hac⟩ lemma reflexive_join (h : reflexive r) : reflexive (join r) := assume a, ⟨a, h a, h a⟩ lemma transitive_join (ht : transitive r) (h : ∀a b c, r a b → r a c → join r b c) : transitive (join r) := assume a b c ⟨x, hax, hbx⟩ ⟨y, hby, hcy⟩, let ⟨z, hxz, hyz⟩ := h b x y hbx hby in ⟨z, ht hax hxz, ht hcy hyz⟩ lemma equivalence_join (hr : reflexive r) (ht : transitive r) (h : ∀a b c, r a b → r a c → join r b c) : equivalence (join r) := ⟨reflexive_join hr, symmetric_join, transitive_join ht h⟩ lemma equivalence_join_refl_trans_gen (h : ∀a b c, r a b → r a c → ∃d, refl_gen r b d ∧ refl_trans_gen r c d) : equivalence (join (refl_trans_gen r)) := equivalence_join reflexive_refl_trans_gen transitive_refl_trans_gen (assume a b c, church_rosser h) lemma join_of_equivalence {r' : α → α → Prop} (hr : equivalence r) (h : ∀a b, r' a b → r a b) : join r' a b → r a b | ⟨c, hac, hbc⟩ := hr.2.2 (h _ _ hac) (hr.2.1 $ h _ _ hbc) lemma refl_trans_gen_of_transitive_reflexive {r' : α → α → Prop} (hr : reflexive r) (ht : transitive r) (h : ∀a b, r' a b → r a b) (h' : refl_trans_gen r' a b) : r a b := begin induction h' with b c hab hbc ih, { exact hr _ }, { exact ht ih (h _ _ hbc) } end lemma refl_trans_gen_of_equivalence {r' : α → α → Prop} (hr : equivalence r) : (∀a b, r' a b → r a b) → refl_trans_gen r' a b → r a b := refl_trans_gen_of_transitive_reflexive hr.1 hr.2.2 end join section eqv_gen lemma eqv_gen_iff_of_equivalence (h : equivalence r) : eqv_gen r a b ↔ r a b := iff.intro begin assume h, induction h, case eqv_gen.rel { assumption }, case eqv_gen.refl { exact h.1 _ }, case eqv_gen.symm { apply h.2.1, assumption }, case eqv_gen.trans : a b c _ _ hab hbc { exact h.2.2 hab hbc } end (eqv_gen.rel a b) lemma eqv_gen_mono {r p : α → α → Prop} (hrp : ∀a b, r a b → p a b) (h : eqv_gen r a b) : eqv_gen p a b := begin induction h, case eqv_gen.rel : a b h { exact eqv_gen.rel _ _ (hrp _ _ h) }, case eqv_gen.refl : { exact eqv_gen.refl _ }, case eqv_gen.symm : a b h ih { exact eqv_gen.symm _ _ ih }, case eqv_gen.trans : a b c ih1 ih2 hab hbc { exact eqv_gen.trans _ _ _ hab hbc } end end eqv_gen end relation
3ee15b309ee232fe05fc7f4e58f1c49951e30b10
2de8c1580f92bb6c28b60135f589fe9d0513faba
/src/buchberger.lean
a21c1fd7daa698020c3ca15f0b38924ea97f5913
[]
no_license
FCL-lean/verification
44a52e40ab78b18654b8d61bb55c2c912a40d2f4
be02c698c0ca78b18762e3fe7749cdc72a55d197
refs/heads/master
1,585,960,207,309
1,560,259,990,000
1,560,259,990,000
155,650,137
0
0
null
1,541,039,704,000
1,541,038,972,000
Lean
UTF-8
Lean
false
false
11,013
lean
import order_mv_polynomial noetherian ideal open mv_polynomial open finsupp namespace buch variables {σ : Type*} {α : Type*} [decidable_eq σ] [decidable_eq α] [discrete_field α] [fintype σ] variables [decidable_linear_order (σ →₀ ℕ)] [is_well_founded (σ →₀ ℕ) (<)] [is_monomial_order (σ →₀ ℕ) (≤)] section reduction def reduction (a b : mv_polynomial σ α) := a - b * (monomial (a.LM - b.LM) (a.LC / b.LC)) def red_list_aux : mv_polynomial σ α → list (mv_polynomial σ α) → mv_polynomial σ α | a [] := a | a (hd :: tl) := if h : hd.LM ∣ a.LM then red_list_aux (reduction a hd) tl else red_list_aux a tl lemma reduction_of_LM_eqz {p q : mv_polynomial σ α} (hp : p.LM = 0) (hq : q.LM = 0) (hq' : q ≠ 0) : reduction p q = 0 := begin rw [reduction, eqC_of_LM_eqz.1 hp, eqC_of_LM_eqz.1 hq], simp [C, monomial_mul_monomial, mul_div_cancel' _ (LC_nez_iff.1 hq')], end lemma zero_red_list_aux : ∀ (l : list (mv_polynomial σ α)), red_list_aux 0 l = 0 | [] := by simp [red_list_aux] | (q :: l') := begin by_cases q.LM ∣ (0 : mv_polynomial (σ) α).LM; simp [red_list_aux, h, reduction]; exact zero_red_list_aux l', end theorem reduction_LM_lt {a b : mv_polynomial σ α} (hba : b.LM ∣ a.LM) (ha : a.LM ≠ 0) (hb : b ≠ 0) : (reduction a b).LM < a.LM := begin simp [reduction], apply sub_LM_lt _ ha, rw [LT_of_mul_m, LT_mul_monomial, add_sub_cancel' hba, mul_div_cancel' _ (LC_nez_iff.1 hb), LT], end lemma red_list_aux_red_LM_lt : ∀ (l : list (mv_polynomial σ α)) {p q : mv_polynomial σ α} (hqp : q.LM ∣ p.LM) (hp : p.LM ≠ 0) (hq : q ≠ 0), (red_list_aux (reduction p q) l).LM < p.LM | [] := by simp [red_list_aux]; apply reduction_LM_lt | (r :: l') := λ p q hqp hp hq, begin by_cases h_dvd : r.LM ∣ (reduction p q).LM; simp [red_list_aux, h_dvd], { by_cases hr : r = 0, {simp [reduction, hr], apply red_list_aux_red_LM_lt, assumption'}, by_cases h_r : (reduction p q).LM = 0, simp [h_r] at h_dvd, { rw [reduction_of_LM_eqz h_r h_dvd hr, zero_red_list_aux], simpa [finsupp.zero_lt_iff_ne_zero] using hp, }, {apply lt_trans (red_list_aux_red_LM_lt l' h_dvd h_r hr) (reduction_LM_lt hqp hp hq)}, }, {apply red_list_aux_red_LM_lt; assumption}, end theorem red_list_aux_LM_lt : ∀ (l : list (mv_polynomial σ α)) (p : mv_polynomial σ α) (hp : p.LM ≠ 0) (h_red : red_list_aux p l ≠ p), (red_list_aux p l).LM < p.LM | [] := by simp [red_list_aux] | (r :: l') := λ p hp h_red, begin by_cases hr : r = 0, {simp [red_list_aux, reduction, hr] at h_red ⊢, apply red_list_aux_LM_lt, assumption'}, by_cases hrp : r.LM ∣ p.LM; simp [red_list_aux, hrp] at h_red ⊢, apply red_list_aux_red_LM_lt l' hrp hp hr, apply red_list_aux_LM_lt, assumption', end def red_list : mv_polynomial σ α → list (mv_polynomial σ α) → mv_polynomial σ α | a l := let r := red_list_aux a l in if h₁ : r = a then r else if h₂ : a.LM = 0 then 0 else have r.LM < a.LM := red_list_aux_LM_lt _ _ h₂ h₁, red_list r l using_well_founded { rel_tac := λ _ _, `[exact ⟨_, inv_image.wf (λ a, a.1.LM) _inst_6.wf⟩] , dec_tac := tactic.assumption } lemma zero_red_list : ∀ (l : list (mv_polynomial σ α)), red_list 0 l = 0 | [] := by unfold red_list; simp [red_list_aux] | (hd :: tl) := begin unfold red_list, simp [zero_red_list_aux], end lemma eqz_of_red_list_aux_eq : ∀ (l : list (mv_polynomial σ α)) (p : mv_polynomial σ α), (red_list_aux p l = p) → (∃ (q : mv_polynomial σ α) (hq₁ : q ∈ l) (hq₂ : q ≠ 0), q.LM = 0) → p = 0 | [] := by simp | (r :: l') := λ p, begin simp_intros hp₁ hl [red_list_aux, -finset.insert_empty_eq_singleton], rcases hl with ⟨q, ⟨hq | hq, hq'₁, hq'₂⟩⟩, { rw hq at hq'₁ hq'₂, simp [hq'₂] at hp₁, by_cases hp₂ : p.LM = 0, {rwa [reduction_of_LM_eqz hp₂ hq'₂ hq'₁, zero_red_list_aux, eq_comm] at hp₁}, { have h := red_list_aux_red_LM_lt l' (by simp [hq'₂]) hp₂ hq'₁, rw hp₁ at h, apply absurd h (lt_irrefl _), }, }, by_cases hrp : r.LM ∣ p.LM; simp [hrp] at hp₁, { by_cases hr : r = 0, {exact eqz_of_red_list_aux_eq l' _ (by simpa [hr, reduction] using hp₁) ⟨q, hq, hq'₁, hq'₂⟩}, { by_cases hp₂ : p.LM = 0, { simp [hp₂] at hrp, rwa [reduction_of_LM_eqz hp₂ hrp hr, zero_red_list_aux, eq_comm] at hp₁, }, { have h := red_list_aux_red_LM_lt l' hrp hp₂ hr, rw hp₁ at h, apply absurd h (lt_irrefl _), }, }, }, {apply eqz_of_red_list_aux_eq l' _ hp₁, refine ⟨q, hq, hq'₁, hq'₂⟩}, end lemma red_list_eqz_of_const : ∀ (p : mv_polynomial σ α) (l : list (mv_polynomial σ α)), (∃ (q : mv_polynomial σ α) (hq₁ : q ∈ l) (hq₂ : q ≠ 0), q.LM = 0) → red_list p l = 0 | p l := λ h, begin unfold red_list, by_cases hp₁ : red_list_aux p l = p; by_cases hp₂ : p.LM = 0; simp [hp₁, hp₂], repeat {apply eqz_of_red_list_aux_eq l _ hp₁ h}, { let : (red_list_aux p l).LM < p.LM, from red_list_aux_LM_lt l p hp₂ hp₁, apply red_list_eqz_of_const, assumption, } end using_well_founded { rel_tac := λ _ _, `[exact ⟨_, inv_image.wf (λ a, a.1.LM) _inst_6.wf⟩] , dec_tac := tactic.assumption } lemma red_list_nez_no_const : ∀ (l : list (mv_polynomial σ α)) (p : mv_polynomial σ α) (h : red_list p l ≠ 0) (q : mv_polynomial σ α) (hq₁ : q ∈ l) (hq₂ : q ≠ 0), q.LM ≠ 0 := λ l p h q hq₁ hq₂ hq₃, h (red_list_eqz_of_const _ _ ⟨q, hq₁, hq₂, hq₃⟩) lemma red_list_aux_not_div : ∀ (l : list (mv_polynomial σ α)) (p : mv_polynomial σ α) (h : red_list_aux p l = p) (q : mv_polynomial σ α) (hq₁ : q ∈ l) (hq₂ : q.LM ≠ 0), q.LM ∤ p.LM | [] := by simp | (r :: l') := begin simp_intros p hp₁ q hq₁ hq₂ [red_list_aux, -finset.insert_empty_eq_singleton], cases hq₁; by_cases hrp : r.LM ∣ p.LM; simp [hrp] at hp₁, { by_cases hp : p.LM = 0, { rw hq₁ at hq₂, simp [hp] at hrp, apply absurd hrp hq₂, }, { rw hq₁ at hq₂, have h_r := red_list_aux_red_LM_lt l' hrp hp (nez_of_LM_nez hq₂), rw [hp₁] at h_r, apply absurd h_r (lt_irrefl _), }, }, {rwa hq₁,}, { by_cases hr : r = 0, {simp [reduction, hr] at hp₁, apply red_list_aux_not_div l', assumption',}, { by_cases hp : p.LM = 0, { simp [hp]at hrp, simp [reduction_of_LM_eqz hp hrp hr, zero_red_list_aux] at hp₁, simpa [hp₁.symm] using hq₂, }, { have h_r := red_list_aux_red_LM_lt l' hrp hp hr, rw [hp₁] at h_r, apply absurd h_r (lt_irrefl _), }, }, }, {apply red_list_aux_not_div l', assumption'}, end theorem red_list_not_div : ∀ (p : mv_polynomial σ α) (l : list (mv_polynomial σ α)) (h : red_list p l ≠ 0) (q : mv_polynomial σ α) (hq₁ : q ∈ l) (hq₂ : q ≠ 0), q.LM ∤ (red_list p l).LM | p l := λ h q hq₁ hq₂, begin have hq₃ := red_list_nez_no_const l p h _ hq₁ hq₂, unfold red_list at ⊢ h, by_cases hp₁ : red_list_aux p l = p; by_cases hp₂ : p.LM = 0; simp [hp₁, hp₂], assumption', {apply red_list_aux_not_div _ _ hp₁ _ hq₁ hq₃}, { let : (red_list_aux p l).LM < p.LM, from red_list_aux_LM_lt l p hp₂ hp₁, apply red_list_not_div, simp [hp₁, hp₂] at h, assumption', } end using_well_founded { rel_tac := λ _ _, `[exact ⟨_, inv_image.wf (λ a, a.1.LM) _inst_6.wf⟩] , dec_tac := tactic.assumption } end reduction def s_poly (p q : mv_polynomial σ α) : mv_polynomial σ α := let X := m_lcm (LM p) (LM q) in --let Xc := lcm (LC p) (LC q) in monomial (X - p.LM) (1 / (LC p)) * p - monomial (X - q.LM) (1 / (LC q)) * q def s_polyL : mv_polynomial σ α → list (mv_polynomial σ α) → list (mv_polynomial σ α) | p [] := [] | p (q :: l₁) := s_poly p q :: s_polyL p l₁ def s_polys : list (mv_polynomial σ α) → list (mv_polynomial σ α) | [] := [] | (a :: l) := s_polyL a l ++ (s_polys l) lemma mem_s_polyL {p q : mv_polynomial σ α} : ∀ {l : list (mv_polynomial σ α)}, q ∈ l → s_poly p q ∈ s_polyL p l | [] := by simp | (hd :: tl) := begin simp_intros hq [s_polyL], cases hq, {simp [hq]}, {simp [mem_s_polyL hq]} end lemma s_poly_comm {p q : mv_polynomial σ α} : s_poly p q = -(s_poly q p) := by simp [s_poly, m_lcm_comm] set_option class.instance_max_depth 50 theorem ideal_increase (l : list (mv_polynomial σ α)) (p : mv_polynomial σ α) (h : red_list p l ≠ 0) : monomial_ideal l < monomial_ideal (list.cons (red_list p l) l) := begin simp [lt_iff_le_and_ne], refine ⟨by apply ideal.span_mono; simp, _⟩, apply ideal.ne_of_not_mem_mem (red_list p l).LT, { intro h_mem, rcases monomial_mem_ideal (by rwa ←LC_nez_iff) l h_mem with ⟨q, ⟨hq₁, hq₂⟩, hq₃⟩, apply red_list_not_div p l h, assumption', }, { simp [monomial_ideal, ideal.mem_span_insert], refine ⟨1, 0, by simp, by simp⟩, } end def buchberger : (list (mv_polynomial σ α) × list (mv_polynomial σ α)) → list (mv_polynomial σ α) | ⟨l₁, []⟩ := l₁ | ⟨l₁, (p :: l₂)⟩ := let lex := prod.lex ((>) : ideal (mv_polynomial σ α) → ideal (mv_polynomial σ α) → Prop) nat.lt in let a := red_list p l₁ in if h : a = 0 then have lex ⟨monomial_ideal l₁, l₂.length⟩ ⟨monomial_ideal l₁, (list.cons p l₂).length⟩ := by right; rw [list.length_cons]; apply nat.lt_succ_self, buchberger ⟨l₁, l₂⟩ else have lex ⟨monomial_ideal (list.cons a l₁), (s_polyL a l₁ ++ l₂).length⟩ ⟨monomial_ideal l₁, (list.cons p l₂).length⟩ := by left; exact ideal_increase l₁ p h, buchberger ⟨a :: l₁, s_polyL a l₁ ++ l₂⟩ using_well_founded { rel_tac := λ _ _, `[exact ⟨_, inv_image.wf (λ ⟨l₁, l₂⟩, prod.mk (monomial_ideal l₁) l₂.length) (prod.lex_wf ideal_wf nat.lt_wf)⟩ ] , dec_tac := tactic.assumption } end buch
6a197edd7640fc927eeddd2bc29a56b43305cae3
a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91
/tests/lean/run/simp_ext_refl.lean
00cb4f9ee3dafac4c9f36b4f9d8b6e80a6cb1dcd
[ "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
896
lean
open tactic constants (A : Type.{1}) (x y z : A) (g : A → A) (Hg : g y = z) attribute Hg [simp] noncomputable definition f (a : A) := y lemma f.def : ∀ (a), f a = y := λ a, rfl meta_definition simp_f_to_y : tactic unit := mk_eq_simp_ext $ λ e, if expr.get_app_num_args e = 1 then do res ← mk_const `y, pf ← mk_app `rfl [e], return (res, pf) else fail "expected f applied to one arg" meta_definition simp_f_to_y₂ : tactic unit := mk_eq_simp_ext $ λ e, if expr.get_app_num_args e = 1 then do res ← mk_const `y, pf ← mk_app `f.def [expr.app_arg e], return (res, pf) else fail "expected f applied to one arg" register_simp_ext f simp_f_to_y definition foo : g (f x) = z := by simp register_simp_ext f simp_f_to_y₂ definition foo₂ : g (f x) = z := by simp print foo print foo₂
868f55e16b3ff6f9dd69f123bc919ff1a286c046
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/analysis/hofer.lean
9185c967361882bbae1274cc7cecdbc3cea58ab5
[]
no_license
AurelienSaue/Mathlib4_auto
f538cfd0980f65a6361eadea39e6fc639e9dae14
590df64109b08190abe22358fabc3eae000943f2
refs/heads/master
1,683,906,849,776
1,622,564,669,000
1,622,564,669,000
371,723,747
0
0
null
null
null
null
UTF-8
Lean
false
false
1,172
lean
/- Copyright (c) 2020 Patrick Massot. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Patrick Massot -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.analysis.specific_limits import Mathlib.PostPort universes u_1 namespace Mathlib /-! # Hofer's lemma This is an elementary lemma about complete metric spaces. It is motivated by an application to the bubbling-off analysis for holomorphic curves in symplectic topology. We are *very* far away from having these applications, but the proof here is a nice example of a proof needing to construct a sequence by induction in the middle of the proof. ## References: * H. Hofer and C. Viterbo, *The Weinstein conjecture in the presence of holomorphic spheres* -/ theorem hofer {X : Type u_1} [metric_space X] [complete_space X] (x : X) (ε : ℝ) (ε_pos : 0 < ε) {ϕ : X → ℝ} (cont : continuous ϕ) (nonneg : ∀ (y : X), 0 ≤ ϕ y) : ∃ (ε' : ℝ), ∃ (H : ε' > 0), ∃ (x' : X), ε' ≤ ε ∧ dist x' x ≤ bit0 1 * ε ∧ ε * ϕ x ≤ ε' * ϕ x' ∧ ∀ (y : X), dist x' y ≤ ε' → ϕ y ≤ bit0 1 * ϕ x' := sorry
ce09bf389f9c512a66ee7312aafa7a5051784a79
8e2026ac8a0660b5a490dfb895599fb445bb77a0
/library/init/meta/transfer.lean
cefd6af9800a3f153315ccfd94f82dfede6f39c6
[ "Apache-2.0" ]
permissive
pcmoritz/lean
6a8575115a724af933678d829b4f791a0cb55beb
35eba0107e4cc8a52778259bb5392300267bfc29
refs/heads/master
1,607,896,326,092
1,490,752,175,000
1,490,752,175,000
86,612,290
0
0
null
1,490,809,641,000
1,490,809,641,000
null
UTF-8
Lean
false
false
7,484
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), ty ← instantiate_mvars ty, e ← mk_instance ty, 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, (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
5ebb71fe1ee1539ded585a65ce9d5a24eb3f641f
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/run/begin_end_do.lean
89c371b3761521a43ee7f88102da546c59efbefc
[ "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
267
lean
open tactic example (a b c : nat) (p : nat → Prop) (f : nat → nat → nat) : p (f (f a a) (f b c)) := begin do { [x, y, z] ← match_target_subexpr ```(λ x y z, f x (f y z)) | failed, trace x, trace y, trace z, trace "------------"}, exact sorry end
611643ecbc8f5c54355240e27db663924cbd39c2
a0e23cfdd129a671bf3154ee1a8a3a72bf4c7940
/stage0/src/Lean/Server/InfoUtils.lean
26d9770a60594e348a1df2842c94e2ede1c0cc4d
[ "Apache-2.0" ]
permissive
WojciechKarpiel/lean4
7f89706b8e3c1f942b83a2c91a3a00b05da0e65b
f6e1314fa08293dea66a329e05b6c196a0189163
refs/heads/master
1,686,633,402,214
1,625,821,189,000
1,625,821,258,000
384,640,886
0
0
Apache-2.0
1,625,903,617,000
1,625,903,026,000
null
UTF-8
Lean
false
false
8,982
lean
/- Copyright (c) 2021 Wojciech Nawrocki. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Wojciech Nawrocki -/ import Lean.DocString import Lean.Elab.InfoTree import Lean.Util.Sorry protected structure String.Range where start : String.Pos stop : String.Pos deriving Inhabited, Repr def String.Range.contains (r : String.Range) (pos : String.Pos) : Bool := r.start <= pos && pos < r.stop def Lean.Syntax.getRange? (stx : Syntax) (originalOnly := false) : Option String.Range := match stx.getPos? originalOnly, stx.getTailPos? originalOnly with | some start, some stop => some { start, stop } | _, _ => none namespace Lean.Elab /-- For every branch, find the deepest node in that branch matching `p` with a surrounding context (the innermost one) and return all of them. -/ partial def InfoTree.deepestNodes (p : ContextInfo → Info → Std.PersistentArray InfoTree → Option α) : InfoTree → List α := go none where go ctx? | context ctx t => go ctx t | n@(node i cs) => let ccs := cs.toList.map (go <| i.updateContext? ctx?) let cs' := ccs.join if !cs'.isEmpty then cs' else match ctx? with | some ctx => match p ctx i cs with | some a => [a] | _ => [] | _ => [] | _ => [] partial def InfoTree.foldInfo (f : ContextInfo → Info → α → α) (init : α) : InfoTree → α := go none init where go ctx? a | context ctx t => go ctx a t | node i ts => let a := match ctx? with | none => a | some ctx => f ctx i a ts.foldl (init := a) (go <| i.updateContext? ctx?) | _ => a def Info.isTerm : Info → Bool | ofTermInfo _ => true | _ => false def Info.isCompletion : Info → Bool | ofCompletionInfo .. => true | _ => false def InfoTree.getCompletionInfos (infoTree : InfoTree) : Array (ContextInfo × CompletionInfo) := infoTree.foldInfo (init := #[]) fun ctx info result => match info with | Info.ofCompletionInfo info => result.push (ctx, info) | _ => result def Info.stx : Info → Syntax | ofTacticInfo i => i.stx | ofTermInfo i => i.stx | ofCommandInfo i => i.stx | ofMacroExpansionInfo i => i.stx | ofFieldInfo i => i.stx | ofCompletionInfo i => i.stx def Info.lctx : Info → LocalContext | Info.ofTermInfo i => i.lctx | Info.ofFieldInfo i => i.lctx | _ => LocalContext.empty def Info.pos? (i : Info) : Option String.Pos := i.stx.getPos? (originalOnly := true) def Info.tailPos? (i : Info) : Option String.Pos := i.stx.getTailPos? (originalOnly := true) def Info.range? (i : Info) : Option String.Range := i.stx.getRange? (originalOnly := true) def Info.contains (i : Info) (pos : String.Pos) : Bool := i.range?.any (·.contains pos) def Info.size? (i : Info) : Option Nat := OptionM.run do let pos ← i.pos? let tailPos ← i.tailPos? return tailPos - pos -- `Info` without position information are considered to have "infinite" size def Info.isSmaller (i₁ i₂ : Info) : Bool := match i₁.size?, i₂.pos? with | some sz₁, some sz₂ => sz₁ < sz₂ | some _, none => true | _, _ => false def Info.occursBefore? (i : Info) (hoverPos : String.Pos) : Option Nat := OptionM.run do let tailPos ← i.tailPos? guard (tailPos ≤ hoverPos) return hoverPos - tailPos def InfoTree.smallestInfo? (p : Info → Bool) (t : InfoTree) : Option (ContextInfo × Info) := let ts := t.deepestNodes fun ctx i _ => if p i then some (ctx, i) else none let infos := ts.map fun (ci, i) => let diff := i.tailPos?.get! - i.pos?.get! (diff, ci, i) infos.toArray.getMax? (fun a b => a.1 > b.1) |>.map fun (_, ci, i) => (ci, i) /-- Find an info node, if any, which should be shown on hover/cursor at position `hoverPos`. -/ partial def InfoTree.hoverableInfoAt? (t : InfoTree) (hoverPos : String.Pos) : Option (ContextInfo × Info) := t.smallestInfo? fun i => do if let Info.ofTermInfo ti := i then if ti.expr.isSyntheticSorry then return false if i matches Info.ofFieldInfo _ || i.toElabInfo?.isSome then return i.contains hoverPos return false /-- Construct a hover popup, if any, from an info node in a context.-/ def Info.fmtHover? (ci : ContextInfo) (i : Info) : IO (Option Format) := do ci.runMetaM i.lctx do let mut fmts := #[] try if let some f ← fmtTerm? then fmts := fmts.push f catch _ => pure () if let some f ← fmtDoc? then fmts := fmts.push f if fmts.isEmpty then none else f!"\n***\n".joinSep fmts.toList where fmtTerm? := do match i with | Info.ofTermInfo ti => let tp ← Meta.inferType ti.expr let eFmt ← Meta.ppExpr ti.expr let tpFmt ← Meta.ppExpr tp -- try not to show too scary internals let fmt := if isAtomicFormat eFmt then f!"{eFmt} : {tpFmt}" else tpFmt return some f!"```lean {fmt} ```" | Info.ofFieldInfo fi => let tp ← Meta.inferType fi.val let tpFmt ← Meta.ppExpr tp return some f!"```lean {fi.name} : {tpFmt} ```" | _ => return none fmtDoc? := do if let Info.ofTermInfo ti := i then if let some n := ti.expr.constName? then return ← findDocString? n if let some ei := i.toElabInfo? then return ← findDocString? ei.elaborator <||> findDocString? ei.stx.getKind return none isAtomicFormat : Format → Bool | Std.Format.text _ => true | Std.Format.group f _ => isAtomicFormat f | Std.Format.nest _ f => isAtomicFormat f | _ => false structure GoalsAtResult where ctxInfo : ContextInfo tacticInfo : TacticInfo useAfter : Bool /- Try to retrieve `TacticInfo` for `hoverPos`. We retrieve the `TacticInfo` `info`, if there is a node of the form `node (ofTacticInfo info) children` s.t. - `hoverPos` is sufficiently inside `info`'s range (see code), and - None of the `children` satisfy the condition above. That is, for composite tactics such as `induction`, we always give preference for information stored in nested (children) tactics. Moreover, we instruct the LSP server to use the state after the tactic execution if the hover is inside the info *and* there is no nested tactic info (i.e. it is a leaf tactic; tactic combinators should decide for themselves where to show intermediate/final states) -/ partial def InfoTree.goalsAt? (text : FileMap) (t : InfoTree) (hoverPos : String.Pos) : List GoalsAtResult := do t.deepestNodes fun | ctx, i@(Info.ofTacticInfo ti), cs => OptionM.run do let (some pos, some tailPos) ← pure (i.pos?, i.tailPos?) | failure let trailSize := i.stx.getTrailingSize -- show info at EOF even if strictly outside token + trail let atEOF := tailPos == text.source.bsize guard <| pos ≤ hoverPos ∧ (hoverPos < tailPos + trailSize || atEOF) return { ctxInfo := ctx, tacticInfo := ti, useAfter := hoverPos > pos && (hoverPos >= tailPos || !cs.any (hasNestedTactic pos tailPos)) } | _, _, _ => none where hasNestedTactic (pos tailPos) : InfoTree → Bool | InfoTree.node i@(Info.ofTacticInfo _) cs => do if let `(by $t) := i.stx then return false -- ignore term-nested proofs such as in `simp [show p by ...]` if let (some pos', some tailPos') := (i.pos?, i.tailPos?) then -- ignore nested infos of the same tactic, e.g. from expansion if (pos', tailPos') != (pos, tailPos) then return true cs.any (hasNestedTactic pos tailPos) | InfoTree.node (Info.ofMacroExpansionInfo _) cs => cs.any (hasNestedTactic pos tailPos) | _ => false /-- Find info nodes that should be used for the term goal feature. The main complication concerns applications like `f a b` where `f` is an identifier. In this case, the term goal at `f` should be the goal for the full application `f a b`. Therefore we first gather the position of these head function symbols such as `f`, and later ignore identifiers at these positions. -/ partial def InfoTree.termGoalAt? (t : InfoTree) (hoverPos : String.Pos) : Option (ContextInfo × Info) := let headFns : Std.HashSet String.Pos := t.foldInfo (init := {}) fun ctx i headFns => do if let some pos := getHeadFnPos? i.stx then headFns.insert pos else headFns t.smallestInfo? fun i => do if i.contains hoverPos then if let Info.ofTermInfo ti := i then return !ti.stx.isIdent || !headFns.contains i.pos?.get! false where /- Returns the position of the head function symbol, if it is an identifier. -/ getHeadFnPos? (s : Syntax) (foundArgs := false) : Option String.Pos := match s with | `(($s)) => getHeadFnPos? s foundArgs | `($f $as*) => getHeadFnPos? f (foundArgs := foundArgs || !as.isEmpty) | stx => if foundArgs && stx.isIdent then stx.getPos? else none end Lean.Elab
9ceede8df7c24ee67bce85ade8b0f915a0fcc570
94e33a31faa76775069b071adea97e86e218a8ee
/src/combinatorics/configuration.lean
778bb949eb37ba8d7b064c26e7d3352b36d74e8a
[ "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
23,382
lean
/- Copyright (c) 2021 Thomas Browning. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Thomas Browning -/ import algebra.big_operators.order import combinatorics.hall.basic import data.fintype.card import set_theory.cardinal.finite /-! # Configurations of Points and lines This file introduces abstract configurations of points and lines, and proves some basic properties. ## Main definitions * `configuration.nondegenerate`: Excludes certain degenerate configurations, and imposes uniqueness of intersection points. * `configuration.has_points`: A nondegenerate configuration in which every pair of lines has an intersection point. * `configuration.has_lines`: A nondegenerate configuration in which every pair of points has a line through them. * `configuration.line_count`: The number of lines through a given point. * `configuration.point_count`: The number of lines through a given line. ## Main statements * `configuration.has_lines.card_le`: `has_lines` implies `|P| ≤ |L|`. * `configuration.has_points.card_le`: `has_points` implies `|L| ≤ |P|`. * `configuration.has_lines.has_points`: `has_lines` and `|P| = |L|` implies `has_points`. * `configuration.has_points.has_lines`: `has_points` and `|P| = |L|` implies `has_lines`. Together, these four statements say that any two of the following properties imply the third: (a) `has_lines`, (b) `has_points`, (c) `|P| = |L|`. -/ open_locale big_operators namespace configuration universe u variables (P L : Type u) [has_mem P L] /-- A type synonym. -/ def dual := P instance [this : inhabited P] : inhabited (dual P) := this instance [this : fintype P] : fintype (dual P) := this instance : has_mem (dual L) (dual P) := ⟨function.swap (has_mem.mem : P → L → Prop)⟩ /-- A configuration is nondegenerate if: 1) there does not exist a line that passes through all of the points, 2) there does not exist a point that is on all of the lines, 3) there is at most one line through any two points, 4) any two lines have at most one intersection point. Conditions 3 and 4 are equivalent. -/ class nondegenerate : Prop := (exists_point : ∀ l : L, ∃ p, p ∉ l) (exists_line : ∀ p, ∃ l : L, p ∉ l) (eq_or_eq : ∀ {p₁ p₂ : P} {l₁ l₂ : L}, p₁ ∈ l₁ → p₂ ∈ l₁ → p₁ ∈ l₂ → p₂ ∈ l₂ → p₁ = p₂ ∨ l₁ = l₂) /-- A nondegenerate configuration in which every pair of lines has an intersection point. -/ class has_points extends nondegenerate P L : Type u := (mk_point : ∀ {l₁ l₂ : L} (h : l₁ ≠ l₂), P) (mk_point_ax : ∀ {l₁ l₂ : L} (h : l₁ ≠ l₂), mk_point h ∈ l₁ ∧ mk_point h ∈ l₂) /-- A nondegenerate configuration in which every pair of points has a line through them. -/ class has_lines extends nondegenerate P L : Type u := (mk_line : ∀ {p₁ p₂ : P} (h : p₁ ≠ p₂), L) (mk_line_ax : ∀ {p₁ p₂ : P} (h : p₁ ≠ p₂), p₁ ∈ mk_line h ∧ p₂ ∈ mk_line h) open nondegenerate has_points has_lines instance [nondegenerate P L] : nondegenerate (dual L) (dual P) := { exists_point := @exists_line P L _ _, exists_line := @exists_point P L _ _, eq_or_eq := λ l₁ l₂ p₁ p₂ h₁ h₂ h₃ h₄, (@eq_or_eq P L _ _ p₁ p₂ l₁ l₂ h₁ h₃ h₂ h₄).symm } instance [has_points P L] : has_lines (dual L) (dual P) := { mk_line := @mk_point P L _ _, mk_line_ax := λ _ _, mk_point_ax } instance [has_lines P L] : has_points (dual L) (dual P) := { mk_point := @mk_line P L _ _, mk_point_ax := λ _ _, mk_line_ax } lemma has_points.exists_unique_point [has_points P L] (l₁ l₂ : L) (hl : l₁ ≠ l₂) : ∃! p, p ∈ l₁ ∧ p ∈ l₂ := ⟨mk_point hl, mk_point_ax hl, λ p hp, (eq_or_eq hp.1 (mk_point_ax hl).1 hp.2 (mk_point_ax hl).2).resolve_right hl⟩ lemma has_lines.exists_unique_line [has_lines P L] (p₁ p₂ : P) (hp : p₁ ≠ p₂) : ∃! l : L, p₁ ∈ l ∧ p₂ ∈ l := has_points.exists_unique_point (dual L) (dual P) p₁ p₂ hp variables {P L} /-- If a nondegenerate configuration has at least as many points as lines, then there exists an injective function `f` from lines to points, such that `f l` does not lie on `l`. -/ lemma nondegenerate.exists_injective_of_card_le [nondegenerate P L] [fintype P] [fintype L] (h : fintype.card L ≤ fintype.card P) : ∃ f : L → P, function.injective f ∧ ∀ l, (f l) ∉ l := begin classical, let t : L → finset P := λ l, (set.to_finset {p | p ∉ l}), suffices : ∀ s : finset L, s.card ≤ (s.bUnion t).card, -- Hall's marriage theorem { obtain ⟨f, hf1, hf2⟩ := (finset.all_card_le_bUnion_card_iff_exists_injective t).mp this, exact ⟨f, hf1, λ l, set.mem_to_finset.mp (hf2 l)⟩ }, intro s, by_cases hs₀ : s.card = 0, -- If `s = ∅`, then `s.card = 0 ≤ (s.bUnion t).card` { simp_rw [hs₀, zero_le] }, by_cases hs₁ : s.card = 1, -- If `s = {l}`, then pick a point `p ∉ l` { obtain ⟨l, rfl⟩ := finset.card_eq_one.mp hs₁, obtain ⟨p, hl⟩ := exists_point l, rw [finset.card_singleton, finset.singleton_bUnion, nat.one_le_iff_ne_zero], exact finset.card_ne_zero_of_mem (set.mem_to_finset.mpr hl) }, suffices : (s.bUnion t)ᶜ.card ≤ sᶜ.card, -- Rephrase in terms of complements (uses `h`) { rw [finset.card_compl, finset.card_compl, tsub_le_iff_left] at this, replace := h.trans this, rwa [←add_tsub_assoc_of_le s.card_le_univ, le_tsub_iff_left (le_add_left s.card_le_univ), add_le_add_iff_right] at this }, have hs₂ : (s.bUnion t)ᶜ.card ≤ 1, -- At most one line through two points of `s` { refine finset.card_le_one_iff.mpr (λ p₁ p₂ hp₁ hp₂, _), simp_rw [finset.mem_compl, finset.mem_bUnion, exists_prop, not_exists, not_and, set.mem_to_finset, set.mem_set_of_eq, not_not] at hp₁ hp₂, obtain ⟨l₁, l₂, hl₁, hl₂, hl₃⟩ := finset.one_lt_card_iff.mp (nat.one_lt_iff_ne_zero_and_ne_one.mpr ⟨hs₀, hs₁⟩), exact (eq_or_eq (hp₁ l₁ hl₁) (hp₂ l₁ hl₁) (hp₁ l₂ hl₂) (hp₂ l₂ hl₂)).resolve_right hl₃ }, by_cases hs₃ : sᶜ.card = 0, { rw [hs₃, nat.le_zero_iff], rw [finset.card_compl, tsub_eq_zero_iff_le, has_le.le.le_iff_eq (finset.card_le_univ _), eq_comm, finset.card_eq_iff_eq_univ] at hs₃ ⊢, rw hs₃, rw finset.eq_univ_iff_forall at hs₃ ⊢, exact λ p, exists.elim (exists_line p) -- If `s = univ`, then show `s.bUnion t = univ` (λ l hl, finset.mem_bUnion.mpr ⟨l, finset.mem_univ l, set.mem_to_finset.mpr hl⟩) }, { exact hs₂.trans (nat.one_le_iff_ne_zero.mpr hs₃) }, -- If `s < univ`, then consequence of `hs₂` end variables {P} (L) /-- Number of points on a given line. -/ noncomputable def line_count (p : P) : ℕ := nat.card {l : L // p ∈ l} variables (P) {L} /-- Number of lines through a given point. -/ noncomputable def point_count (l : L) : ℕ := nat.card {p : P // p ∈ l} variables (P L) lemma sum_line_count_eq_sum_point_count [fintype P] [fintype L] : ∑ p : P, line_count L p = ∑ l : L, point_count P l := begin classical, simp only [line_count, point_count, nat.card_eq_fintype_card, ←fintype.card_sigma], apply fintype.card_congr, calc (Σ p, {l : L // p ∈ l}) ≃ {x : P × L // x.1 ∈ x.2} : (equiv.subtype_prod_equiv_sigma_subtype (∈)).symm ... ≃ {x : L × P // x.2 ∈ x.1} : (equiv.prod_comm P L).subtype_equiv (λ x, iff.rfl) ... ≃ (Σ l, {p // p ∈ l}) : equiv.subtype_prod_equiv_sigma_subtype (λ (l : L) (p : P), p ∈ l), end variables {P L} lemma has_lines.point_count_le_line_count [has_lines P L] {p : P} {l : L} (h : p ∉ l) [fintype {l : L // p ∈ l}] : point_count P l ≤ line_count L p := begin by_cases hf : infinite {p : P // p ∈ l}, { exactI (le_of_eq nat.card_eq_zero_of_infinite).trans (zero_le (line_count L p)) }, haveI := fintype_of_not_infinite hf, rw [line_count, point_count, nat.card_eq_fintype_card, nat.card_eq_fintype_card], have : ∀ p' : {p // p ∈ l}, p ≠ p' := λ p' hp', h ((congr_arg (∈ l) hp').mpr p'.2), exact fintype.card_le_of_injective (λ p', ⟨mk_line (this p'), (mk_line_ax (this p')).1⟩) (λ p₁ p₂ hp, subtype.ext ((eq_or_eq p₁.2 p₂.2 (mk_line_ax (this p₁)).2 ((congr_arg _ (subtype.ext_iff.mp hp)).mpr (mk_line_ax (this p₂)).2)).resolve_right (λ h', (congr_arg _ h').mp h (mk_line_ax (this p₁)).1))), end lemma has_points.line_count_le_point_count [has_points P L] {p : P} {l : L} (h : p ∉ l) [hf : fintype {p : P // p ∈ l}] : line_count L p ≤ point_count P l := @has_lines.point_count_le_line_count (dual L) (dual P) _ _ l p h hf variables (P L) /-- If a nondegenerate configuration has a unique line through any two points, then `|P| ≤ |L|`. -/ lemma has_lines.card_le [has_lines P L] [fintype P] [fintype L] : fintype.card P ≤ fintype.card L := begin classical, by_contradiction hc₂, obtain ⟨f, hf₁, hf₂⟩ := nondegenerate.exists_injective_of_card_le (le_of_not_le hc₂), have := calc ∑ p, line_count L p = ∑ l, point_count P l : sum_line_count_eq_sum_point_count P L ... ≤ ∑ l, line_count L (f l) : finset.sum_le_sum (λ l hl, has_lines.point_count_le_line_count (hf₂ l)) ... = ∑ p in finset.univ.image f, line_count L p : finset.sum_bij (λ l hl, f l) (λ l hl, finset.mem_image_of_mem f hl) (λ l hl, rfl) (λ l₁ l₂ hl₁ hl₂ hl₃, hf₁ hl₃) (λ p, by simp_rw [finset.mem_image, eq_comm, imp_self]) ... < ∑ p, line_count L p : _, { exact lt_irrefl _ this }, { obtain ⟨p, hp⟩ := not_forall.mp (mt (fintype.card_le_of_surjective f) hc₂), refine finset.sum_lt_sum_of_subset ((finset.univ.image f).subset_univ) (finset.mem_univ p) _ _ (λ p hp₁ hp₂, zero_le (line_count L p)), { simpa only [finset.mem_image, exists_prop, finset.mem_univ, true_and] }, { rw [line_count, nat.card_eq_fintype_card, fintype.card_pos_iff], obtain ⟨l, hl⟩ := @exists_line P L _ _ p, exact let this := not_exists.mp hp l in ⟨⟨mk_line this, (mk_line_ax this).2⟩⟩ } }, end /-- If a nondegenerate configuration has a unique point on any two lines, then `|L| ≤ |P|`. -/ lemma has_points.card_le [has_points P L] [fintype P] [fintype L] : fintype.card L ≤ fintype.card P := @has_lines.card_le (dual L) (dual P) _ _ _ _ variables {P L} lemma has_lines.exists_bijective_of_card_eq [has_lines P L] [fintype P] [fintype L] (h : fintype.card P = fintype.card L) : ∃ f : L → P, function.bijective f ∧ ∀ l, point_count P l = line_count L (f l) := begin classical, obtain ⟨f, hf1, hf2⟩ := nondegenerate.exists_injective_of_card_le (ge_of_eq h), have hf3 := (fintype.bijective_iff_injective_and_card f).mpr ⟨hf1, h.symm⟩, refine ⟨f, hf3, λ l, (finset.sum_eq_sum_iff_of_le (by exact λ l hl, has_lines.point_count_le_line_count (hf2 l))).mp ((sum_line_count_eq_sum_point_count P L).symm.trans ((finset.sum_bij (λ l hl, f l) (λ l hl, finset.mem_univ (f l)) (λ l hl, refl (line_count L (f l))) (λ l₁ l₂ hl₁ hl₂ hl, hf1 hl) (λ p hp, _)).symm)) l (finset.mem_univ l)⟩, obtain ⟨l, rfl⟩ := hf3.2 p, exact ⟨l, finset.mem_univ l, rfl⟩, end lemma has_lines.line_count_eq_point_count [has_lines P L] [fintype P] [fintype L] (hPL : fintype.card P = fintype.card L) {p : P} {l : L} (hpl : p ∉ l) : line_count L p = point_count P l := begin classical, obtain ⟨f, hf1, hf2⟩ := has_lines.exists_bijective_of_card_eq hPL, let s : finset (P × L) := set.to_finset {i | i.1 ∈ i.2}, have step1 : ∑ i : P × L, line_count L i.1 = ∑ i : P × L, point_count P i.2, { rw [←finset.univ_product_univ, finset.sum_product_right, finset.sum_product], simp_rw [finset.sum_const, finset.card_univ, hPL, sum_line_count_eq_sum_point_count] }, have step2 : ∑ i in s, line_count L i.1 = ∑ i in s, point_count P i.2, { rw [s.sum_finset_product finset.univ (λ p, set.to_finset {l | p ∈ l})], rw [s.sum_finset_product_right finset.univ (λ l, set.to_finset {p | p ∈ l})], refine (finset.sum_bij (λ l hl, f l) (λ l hl, finset.mem_univ (f l)) (λ l hl, _) (λ _ _ _ _ h, hf1.1 h) (λ p hp, _)).symm, { simp_rw [finset.sum_const, set.to_finset_card, ←nat.card_eq_fintype_card], change (point_count P l) • (point_count P l) = (line_count L (f l)) • (line_count L (f l)), rw hf2 }, { obtain ⟨l, hl⟩ := hf1.2 p, exact ⟨l, finset.mem_univ l, hl.symm⟩ }, all_goals { simp_rw [finset.mem_univ, true_and, set.mem_to_finset], exact λ p, iff.rfl } }, have step3 : ∑ i in sᶜ, line_count L i.1 = ∑ i in sᶜ, point_count P i.2, { rwa [←s.sum_add_sum_compl, ←s.sum_add_sum_compl, step2, add_left_cancel_iff] at step1 }, rw ← set.to_finset_compl at step3, exact ((finset.sum_eq_sum_iff_of_le (by exact λ i hi, has_lines.point_count_le_line_count (set.mem_to_finset.mp hi))).mp step3.symm (p, l) (set.mem_to_finset.mpr hpl)).symm, end lemma has_points.line_count_eq_point_count [has_points P L] [fintype P] [fintype L] (hPL : fintype.card P = fintype.card L) {p : P} {l : L} (hpl : p ∉ l) : line_count L p = point_count P l := (@has_lines.line_count_eq_point_count (dual L) (dual P) _ _ _ _ hPL.symm l p hpl).symm /-- If a nondegenerate configuration has a unique line through any two points, and if `|P| = |L|`, then there is a unique point on any two lines. -/ noncomputable def has_lines.has_points [has_lines P L] [fintype P] [fintype L] (h : fintype.card P = fintype.card L) : has_points P L := let this : ∀ l₁ l₂ : L, l₁ ≠ l₂ → ∃ p : P, p ∈ l₁ ∧ p ∈ l₂ := λ l₁ l₂ hl, begin classical, obtain ⟨f, hf1, hf2⟩ := has_lines.exists_bijective_of_card_eq h, haveI : nontrivial L := ⟨⟨l₁, l₂, hl⟩⟩, haveI := fintype.one_lt_card_iff_nontrivial.mp ((congr_arg _ h).mpr fintype.one_lt_card), have h₁ : ∀ p : P, 0 < line_count L p := λ p, exists.elim (exists_ne p) (λ q hq, (congr_arg _ nat.card_eq_fintype_card).mpr (fintype.card_pos_iff.mpr ⟨⟨mk_line hq, (mk_line_ax hq).2⟩⟩)), have h₂ : ∀ l : L, 0 < point_count P l := λ l, (congr_arg _ (hf2 l)).mpr (h₁ (f l)), obtain ⟨p, hl₁⟩ := fintype.card_pos_iff.mp ((congr_arg _ nat.card_eq_fintype_card).mp (h₂ l₁)), by_cases hl₂ : p ∈ l₂, exact ⟨p, hl₁, hl₂⟩, have key' : fintype.card {q : P // q ∈ l₂} = fintype.card {l : L // p ∈ l}, { exact ((has_lines.line_count_eq_point_count h hl₂).trans nat.card_eq_fintype_card).symm.trans nat.card_eq_fintype_card, }, have : ∀ q : {q // q ∈ l₂}, p ≠ q := λ q hq, hl₂ ((congr_arg (∈ l₂) hq).mpr q.2), let f : {q : P // q ∈ l₂} → {l : L // p ∈ l} := λ q, ⟨mk_line (this q), (mk_line_ax (this q)).1⟩, have hf : function.injective f := λ q₁ q₂ hq, subtype.ext ((eq_or_eq q₁.2 q₂.2 (mk_line_ax (this q₁)).2 ((congr_arg _ (subtype.ext_iff.mp hq)).mpr (mk_line_ax (this q₂)).2)).resolve_right (λ h, (congr_arg _ h).mp hl₂ (mk_line_ax (this q₁)).1)), have key' := ((fintype.bijective_iff_injective_and_card f).mpr ⟨hf, key'⟩).2, obtain ⟨q, hq⟩ := key' ⟨l₁, hl₁⟩, exact ⟨q, (congr_arg _ (subtype.ext_iff.mp hq)).mp (mk_line_ax (this q)).2, q.2⟩, end in { mk_point := λ l₁ l₂ hl, classical.some (this l₁ l₂ hl), mk_point_ax := λ l₁ l₂ hl, classical.some_spec (this l₁ l₂ hl) } /-- If a nondegenerate configuration has a unique point on any two lines, and if `|P| = |L|`, then there is a unique line through any two points. -/ noncomputable def has_points.has_lines [has_points P L] [fintype P] [fintype L] (h : fintype.card P = fintype.card L) : has_lines P L := let this := @has_lines.has_points (dual L) (dual P) _ _ _ _ h.symm in { mk_line := this.mk_point, mk_line_ax := this.mk_point_ax } variables (P L) /-- A projective plane is a nondegenerate configuration in which every pair of lines has an intersection point, every pair of points has a line through them, and which has three points in general position. -/ class projective_plane extends nondegenerate P L : Type u := (mk_point : ∀ {l₁ l₂ : L} (h : l₁ ≠ l₂), P) (mk_point_ax : ∀ {l₁ l₂ : L} (h : l₁ ≠ l₂), mk_point h ∈ l₁ ∧ mk_point h ∈ l₂) (mk_line : ∀ {p₁ p₂ : P} (h : p₁ ≠ p₂), L) (mk_line_ax : ∀ {p₁ p₂ : P} (h : p₁ ≠ p₂), p₁ ∈ mk_line h ∧ p₂ ∈ mk_line h) (exists_config : ∃ (p₁ p₂ p₃ : P) (l₁ l₂ l₃ : L), p₁ ∉ l₂ ∧ p₁ ∉ l₃ ∧ p₂ ∉ l₁ ∧ p₂ ∈ l₂ ∧ p₂ ∈ l₃ ∧ p₃ ∉ l₁ ∧ p₃ ∈ l₂ ∧ p₃ ∉ l₃) namespace projective_plane @[priority 100] -- see Note [lower instance priority] instance has_points [h : projective_plane P L] : has_points P L := { .. h } @[priority 100] -- see Note [lower instance priority] instance has_lines [h : projective_plane P L] : has_lines P L := { .. h } instance [projective_plane P L] : projective_plane (dual L) (dual P) := { mk_line := @mk_point P L _ _, mk_line_ax := λ _ _, mk_point_ax, mk_point := @mk_line P L _ _, mk_point_ax := λ _ _, mk_line_ax, exists_config := by { obtain ⟨p₁, p₂, p₃, l₁, l₂, l₃, h₁₂, h₁₃, h₂₁, h₂₂, h₂₃, h₃₁, h₃₂, h₃₃⟩ := @exists_config P L _ _, exact ⟨l₁, l₂, l₃, p₁, p₂, p₃, h₂₁, h₃₁, h₁₂, h₂₂, h₃₂, h₁₃, h₂₃, h₃₃⟩ }, .. dual.nondegenerate P L } /-- The order of a projective plane is one less than the number of lines through an arbitrary point. Equivalently, it is one less than the number of points on an arbitrary line. -/ noncomputable def order [projective_plane P L] : ℕ := line_count L (classical.some (@exists_config P L _ _)) - 1 variables [fintype P] [fintype L] lemma card_points_eq_card_lines [projective_plane P L] : fintype.card P = fintype.card L := le_antisymm (has_lines.card_le P L) (has_points.card_le P L) variables {P} (L) lemma line_count_eq_line_count [projective_plane P L] (p q : P) : line_count L p = line_count L q := begin obtain ⟨p₁, p₂, p₃, l₁, l₂, l₃, h₁₂, h₁₃, h₂₁, h₂₂, h₂₃, h₃₁, h₃₂, h₃₃⟩ := exists_config, have h := card_points_eq_card_lines P L, let n := line_count L p₂, have hp₂ : line_count L p₂ = n := rfl, have hl₁ : point_count P l₁ = n := (has_lines.line_count_eq_point_count h h₂₁).symm.trans hp₂, have hp₃ : line_count L p₃ = n := (has_lines.line_count_eq_point_count h h₃₁).trans hl₁, have hl₃ : point_count P l₃ = n := (has_lines.line_count_eq_point_count h h₃₃).symm.trans hp₃, have hp₁ : line_count L p₁ = n := (has_lines.line_count_eq_point_count h h₁₃).trans hl₃, have hl₂ : point_count P l₂ = n := (has_lines.line_count_eq_point_count h h₁₂).symm.trans hp₁, suffices : ∀ p : P, line_count L p = n, { exact (this p).trans (this q).symm }, refine λ p, or_not.elim (λ h₂, _) (λ h₂, (has_lines.line_count_eq_point_count h h₂).trans hl₂), refine or_not.elim (λ h₃, _) (λ h₃, (has_lines.line_count_eq_point_count h h₃).trans hl₃), rwa (eq_or_eq h₂ h₂₂ h₃ h₂₃).resolve_right (λ h, h₃₃ ((congr_arg (has_mem.mem p₃) h).mp h₃₂)), end variables (P) {L} lemma point_count_eq_point_count [projective_plane P L] (l m : L) : point_count P l = point_count P m := line_count_eq_line_count (dual P) l m variables {P L} lemma line_count_eq_point_count [projective_plane P L] (p : P) (l : L) : line_count L p = point_count P l := exists.elim (exists_point l) (λ q hq, (line_count_eq_line_count L p q).trans (has_lines.line_count_eq_point_count (card_points_eq_card_lines P L) hq)) variables (P L) lemma dual.order [projective_plane P L] : order (dual L) (dual P) = order P L := congr_arg (λ n, n - 1) (line_count_eq_point_count _ _) variables {P} (L) lemma line_count_eq [projective_plane P L] (p : P) : line_count L p = order P L + 1 := begin classical, obtain ⟨q, -, -, l, -, -, -, -, h, -⟩ := classical.some_spec (@exists_config P L _ _), rw [order, line_count_eq_line_count L p q, line_count_eq_line_count L (classical.some _) q, line_count, nat.card_eq_fintype_card, nat.sub_add_cancel], exact fintype.card_pos_iff.mpr ⟨⟨l, h⟩⟩, end variables (P) {L} lemma point_count_eq [projective_plane P L] (l : L) : point_count P l = order P L + 1 := (line_count_eq (dual P) l).trans (congr_arg (λ n, n + 1) (dual.order P L)) variables (P L) lemma one_lt_order [projective_plane P L] : 1 < order P L := begin obtain ⟨p₁, p₂, p₃, l₁, l₂, l₃, -, -, h₂₁, h₂₂, h₂₃, h₃₁, h₃₂, h₃₃⟩ := @exists_config P L _ _, classical, rw [←add_lt_add_iff_right, ←point_count_eq, point_count, nat.card_eq_fintype_card], simp_rw [fintype.two_lt_card_iff, ne, subtype.ext_iff], have h := mk_point_ax (λ h, h₂₁ ((congr_arg _ h).mpr h₂₂)), exact ⟨⟨mk_point _, h.2⟩, ⟨p₂, h₂₂⟩, ⟨p₃, h₃₂⟩, ne_of_mem_of_not_mem h.1 h₂₁, ne_of_mem_of_not_mem h.1 h₃₁, ne_of_mem_of_not_mem h₂₃ h₃₃⟩, end variables {P} (L) lemma two_lt_line_count [projective_plane P L] (p : P) : 2 < line_count L p := by simpa only [line_count_eq L p, nat.succ_lt_succ_iff] using one_lt_order P L variables (P) {L} lemma two_lt_point_count [projective_plane P L] (l : L) : 2 < point_count P l := by simpa only [point_count_eq P l, nat.succ_lt_succ_iff] using one_lt_order P L variables (P) (L) lemma card_points [projective_plane P L] : fintype.card P = order P L ^ 2 + order P L + 1 := begin obtain ⟨p, -⟩ := @exists_config P L _ _, let ϕ : {q // q ≠ p} ≃ Σ (l : {l : L // p ∈ l}), {q // q ∈ l.1 ∧ q ≠ p} := { to_fun := λ q, ⟨⟨mk_line q.2, (mk_line_ax q.2).2⟩, q, (mk_line_ax q.2).1, q.2⟩, inv_fun := λ lq, ⟨lq.2, lq.2.2.2⟩, left_inv := λ q, subtype.ext rfl, right_inv := λ lq, sigma.subtype_ext (subtype.ext ((eq_or_eq (mk_line_ax lq.2.2.2).1 (mk_line_ax lq.2.2.2).2 lq.2.2.1 lq.1.2).resolve_left lq.2.2.2)) rfl }, classical, have h1 : fintype.card {q // q ≠ p} + 1 = fintype.card P, { apply (eq_tsub_iff_add_eq_of_le (nat.succ_le_of_lt (fintype.card_pos_iff.mpr ⟨p⟩))).mp, convert (fintype.card_subtype_compl _).trans (congr_arg _ (fintype.card_subtype_eq p)) }, have h2 : ∀ l : {l : L // p ∈ l}, fintype.card {q // q ∈ l.1 ∧ q ≠ p} = order P L, { intro l, rw [←fintype.card_congr (equiv.subtype_subtype_equiv_subtype_inter _ _), fintype.card_subtype_compl (λ (x : subtype (∈ l.val)), x.val = p), ←nat.card_eq_fintype_card], refine tsub_eq_of_eq_add ((point_count_eq P l.1).trans _), rw ← fintype.card_subtype_eq (⟨p, l.2⟩ : {q : P // q ∈ l.1}), simp_rw subtype.ext_iff_val }, simp_rw [←h1, fintype.card_congr ϕ, fintype.card_sigma, h2, finset.sum_const, finset.card_univ], rw [←nat.card_eq_fintype_card, ←line_count, line_count_eq, smul_eq_mul, nat.succ_mul, sq], end lemma card_lines [projective_plane P L] : fintype.card L = order P L ^ 2 + order P L + 1 := (card_points (dual L) (dual P)).trans (congr_arg (λ n, n ^ 2 + n + 1) (dual.order P L)) end projective_plane end configuration
0114792f0f67958434fbaceea22c25c5417225b6
8e31b9e0d8cec76b5aa1e60a240bbd557d01047c
/scratch/misc.lean
b64f4c4e60b85c4ca72340c51ca824f5f536d39d
[]
no_license
ChrisHughes24/LP
7bdd62cb648461c67246457f3ddcb9518226dd49
e3ed64c2d1f642696104584e74ae7226d8e916de
refs/heads/master
1,685,642,642,858
1,578,070,602,000
1,578,070,602,000
195,268,102
4
3
null
1,569,229,518,000
1,562,255,287,000
Lean
UTF-8
Lean
false
false
23,573
lean
import data.matrix.pequiv tactic.fin_cases import linear_algebra.finite_dimensional local infix ` ⬝ `:70 := matrix.mul local postfix `ᵀ` : 1500 := matrix.transpose universes u v w namespace matrix section variables {l m n o : Type u} [fintype l] [fintype m] [fintype n] [fintype o] variables {one : Type u} [unique one] [fintype one] [decidable_eq one] {R : Type*} --[comm_ring R] open function pequiv local notation `£` := default _ instance matrix.vector_space [discrete_field R] : vector_space R (matrix m n R) := { ..matrix.module } instance [discrete_field R] : finite_dimensional R (matrix m n R) := @is_noetherian_pi R m _ _ _ _ _ (λ _, is_noetherian_pi) @[simp] lemma symm_single_apply {α β : Type*} [decidable_eq α] [decidable_eq β] (a : α) (b : β) : (single a b).symm b = some a := by dsimp; simp lemma mul_single_ext' [semiring R] (one : Type u) [unique one] [fintype one] [decidable_eq one] [decidable_eq m] [decidable_eq n] {A B : matrix m n R} (h : ∀ j, A ⬝ (single j (default one)).to_matrix = B ⬝ (single j (default one)).to_matrix) : A = B := begin ext i j, have := congr_fun (congr_fun (h j) i) (default one), rwa [matrix_mul_apply, matrix_mul_apply, symm_single_apply] at this end lemma single_mul_ext' [semiring R] (one : Type u) [unique one] [fintype one] [decidable_eq one] [decidable_eq m] [decidable_eq n] {A B : matrix m n R} (h : ∀ i, (single (default one) i).to_matrix ⬝ A = (single (default one) i).to_matrix ⬝ B) : A = B := begin ext i j, have := congr_fun (congr_fun (h i) (default one)) j, rwa [mul_matrix_apply, mul_matrix_apply, single_apply] at this end lemma matrix_eq_sum_single_mul [semiring R] [decidable_eq m] (M : matrix m n R) : M = finset.univ.sum (λ i : m, (single i i).to_matrix ⬝ M) := by letI := classical.dec_eq n; exact single_mul_ext' punit (begin assume i, simp only [matrix.mul_sum, single_mul_single], rw [finset.sum_eq_single i], { simp }, { assume _ _ hbi, rw [← matrix.mul_assoc, single_mul_single_of_ne hbi.symm, matrix.zero_mul] }, { simp } end) lemma matrix_eq_sum_mul_single [semiring R] [decidable_eq n] (M : matrix m n R) : M = finset.univ.sum (λ j : n, M ⬝ (single j j).to_matrix) := by letI := classical.dec_eq m; exact mul_single_ext' punit (begin assume j, simp only [matrix.sum_mul, single_mul_single], rw [finset.sum_eq_single j], { simp [matrix.mul_assoc] }, { assume _ _ hbj, rw [matrix.mul_assoc, single_mul_single_of_ne hbj, matrix.mul_zero] }, { simp } end) @[simp] lemma univ_unique {α : Type*} [unique α] [f : fintype α] : @finset.univ α _ = {default α} := by rw [subsingleton.elim f (@unique.fintype α _)]; refl lemma mul_eq_smul [comm_semiring R] {M : matrix n one R} (a : matrix one one R) : M ⬝ a = a (default one) (default one) • M := begin ext i j, rw unique.eq_default j, simp [matrix.mul, mul_comm] end set_option class.instance_max_depth 100 def linear_equiv_linear_map (m n one : Type u) (R : Type v) [fintype m] [fintype n] [unique one] [fintype one] [decidable_eq one] [comm_ring R] [decidable_eq m] [decidable_eq n] : matrix m n R ≃ₗ[R] ((matrix n one R) →ₗ[R] (matrix m one R)) := { to_fun := λ A, { to_fun := λ x, A ⬝ x, add := matrix.mul_add A, smul := matrix.mul_smul A }, inv_fun := λ f, finset.univ.sum (λ j : n, f (single j (default one)).to_matrix ⬝ (single (default one) j).to_matrix), left_inv := λ A, begin conv_rhs {rw [matrix_eq_sum_mul_single A]}, dsimp, simp [matrix.mul_assoc], end, right_inv := λ f, linear_map.ext $ λ v, begin dsimp, rw [matrix.sum_mul], simp only [matrix.mul_assoc, mul_eq_smul, (f.map_smul _ _).symm, finset.sum_hom f], simp only [(mul_eq_smul _).symm], conv_rhs { rw [matrix_eq_sum_single_mul v] }, simp, end, add := by simp only [matrix.add_mul]; intros; refl, smul := λ f g, linear_map.ext $ λ x, by dsimp; simp only [matrix.smul_mul]; refl } lemma linear_equiv_linear_map_comp [comm_ring R] [decidable_eq m] [decidable_eq n] [decidable_eq o] {M : matrix m n R} {N : matrix n o R} : (linear_equiv_linear_map m o one R).to_equiv (M ⬝ N) = ((linear_equiv_linear_map m n one R).to_equiv M).comp ((linear_equiv_linear_map n o one R).to_equiv N) := linear_map.ext $ matrix.mul_assoc M N lemma linear_equiv_linear_map_one [comm_ring R] [decidable_eq n] : (linear_equiv_linear_map n n one R).to_equiv (1 : matrix n n R) = linear_map.id := linear_map.ext matrix.one_mul def ring_equiv_linear_map (n one : Type u) (R : Type v) [fintype n] [unique one] [fintype one] [decidable_eq one] [comm_ring R] [decidable_eq n] : matrix n n R ≃r ((matrix n one R) →ₗ[R] (matrix n one R)) := { hom := { map_add := (linear_equiv_linear_map n n one R).add, map_mul := @linear_equiv_linear_map_comp _ _ _ _ _ _ _ _ _ _ _ _ _ _ _, map_one := @linear_equiv_linear_map_one _ _ _ _ _ _ _ _ _ }, ..linear_equiv_linear_map n n one R } /-- the same as row free if `R` is a field -/ def has_right_inverse [semiring R] [decidable_eq m] (M : matrix m n R) : Prop := ∃ N : matrix n m R, M ⬝ N = 1 /-- the same as column free if `R` is a field -/ def has_left_inverse [semiring R] [decidable_eq n] (M : matrix m n R) : Prop := ∃ N : matrix n m R, N ⬝ M = 1 lemma has_left_inverse_one [semiring R] [decidable_eq n] : (1 : matrix n n R).has_left_inverse := ⟨1, matrix.one_mul 1⟩ lemma has_right_inverse_one [semiring R] [decidable_eq n] : (1 : matrix n n R).has_right_inverse := ⟨1, matrix.one_mul 1⟩ lemma has_left_inverse_mul [semiring R] [decidable_eq m] [decidable_eq n] {M : matrix l m R} {N : matrix m n R} (hM : M.has_left_inverse) : N.has_left_inverse ↔ (M ⬝ N).has_left_inverse := let ⟨Mi, hMi⟩ := hM in ⟨λ ⟨Ni, hNi⟩, ⟨Ni ⬝ Mi, by rw [matrix.mul_assoc, ← Mi.mul_assoc, hMi, matrix.one_mul, hNi]⟩, λ ⟨MNi, hMNi⟩, ⟨MNi ⬝ M, by rw [matrix.mul_assoc, hMNi]⟩⟩ lemma has_right_inverse_mul [semiring R] [decidable_eq l] [decidable_eq m] {M : matrix l m R} {N : matrix m n R} (hN : N.has_right_inverse) : M.has_right_inverse ↔ (M ⬝ N).has_right_inverse := let ⟨Ni, hNi⟩ := hN in ⟨λ ⟨Mi, hMi⟩, ⟨Ni ⬝ Mi, by rw [M.mul_assoc, ← N.mul_assoc, hNi, matrix.one_mul, hMi]⟩, λ ⟨MNi, hMNi⟩, ⟨N ⬝ MNi, by rw [← matrix.mul_assoc, hMNi]⟩⟩ lemma mul_eq_one_comm [discrete_field R] [decidable_eq n] {M N : matrix n n R} : M ⬝ N = 1 ↔ N ⬝ M = 1 := by rw [← matrix.mul_eq_mul, ← matrix.mul_eq_mul, ← (ring_equiv_linear_map n punit R).to_equiv.injective.eq_iff, ← (ring_equiv_linear_map n punit R).to_equiv.injective.eq_iff, is_ring_hom.map_mul (ring_equiv_linear_map n punit R).to_equiv, is_ring_hom.map_one (ring_equiv_linear_map n punit R).to_equiv, linear_map.mul_eq_one_comm, ← is_ring_hom.map_mul (ring_equiv_linear_map n punit R).to_equiv, ← is_ring_hom.map_one (ring_equiv_linear_map n punit R).to_equiv] lemma has_right_inverse_iff_has_left_inverse [discrete_field R] [decidable_eq n] {M : matrix n n R} : has_right_inverse M ↔ has_left_inverse M := by simp [has_left_inverse, has_right_inverse, mul_eq_one_comm] lemma mul_right_inj [semiring R] [decidable_eq m] {L M : matrix l m R} {N : matrix m n R} (hN : N.has_right_inverse) : L ⬝ N = M ⬝ N ↔ L = M := let ⟨I, hI⟩ := hN in ⟨λ h, by rw [← L.mul_one, ← hI, ← matrix.mul_assoc, h, matrix.mul_assoc, hI, matrix.mul_one], λ h, by rw h⟩ lemma mul_left_inj [semiring R] [decidable_eq m] {L : matrix l m R} {M N : matrix m n R} (hL : L.has_left_inverse) : L ⬝ M = L ⬝ N ↔ M = N := let ⟨I, hI⟩ := hL in ⟨λ h, by rw [← M.one_mul, ← hI, matrix.mul_assoc, h, ← matrix.mul_assoc, hI, matrix.one_mul], λ h, by rw h⟩ def write [decidable_eq m] [decidable_eq n] (A : matrix m n R) (i : m) (j : n) (x : R) : matrix m n R | i' j' := if i' = i ∧ j' = j then x else A i' j' @[simp] lemma write_apply [decidable_eq m] [decidable_eq n] (A : matrix m n R) (i : m) (j : n) (x : R) : (A.write i j x) i j = x := if_pos ⟨rfl, rfl⟩ lemma write_apply_of_ne [decidable_eq m] [decidable_eq n] (A : matrix m n R) {i i' : m} {j j' : n} (h : i' ≠ i ∨ j' ≠ j) (x : R) : (A.write i j x) i' j' = A i' j' := if_neg (not_and_distrib.2 h) def write_row [decidable_eq m] (A : matrix m n R) (i : m) (x : n → R) : matrix m n R | i' j := if i = i' then x j else A i' j def write_column [decidable_eq n] (A : matrix m n R) (j : n) (x : m → R) : matrix m n R | i j' := if j = j' then x i else A i j' @[simp] lemma write_row_apply_of_eq [decidable_eq m] (A : matrix m n R) (i : m) (j : n) (x : n → R) : (A.write_row i x) i j = x j := if_pos rfl @[simp] lemma write_column_apply_of_eq [decidable_eq n] (A : matrix m n R) (i : m) (j : n) (x : m → R) : (A.write_column j x) i j = x i := if_pos rfl lemma write_row_apply [decidable_eq m] (A : matrix m n R) {i i' : m} (j : n) (x : n → R) : (A.write_row i x) i' j = ite (i = i') (x j) (A i' j) := rfl lemma write_column_apply [decidable_eq n] (A : matrix m n R) (i : m) (j j' : n) (x : m → R) : (A.write_column j x) i j' = ite (j = j') (x i) (A i j') := rfl lemma write_row_apply_of_ne [decidable_eq m] (A : matrix m n R) {i i' : m} (h : i ≠ i') (j : n) (x : n → R) : (A.write_row i x) i' j = A i' j := dif_neg h lemma write_column_apply_of_ne [decidable_eq n] (A : matrix m n R) {j j' : n} (h : j ≠ j') (i : m) (x : m → R) : (A.write_column j x) i j' = A i j' := dif_neg h section inverse variables [discrete_field R] /-- noncomputable inverse function for square matrices, returns `0` for noninvertible matrices -/ noncomputable def inverse (M : matrix n n R) : matrix n n R := by classical; exact if h : has_left_inverse M then classical.some h else 0 lemma inverse_mul [decidable_eq n] {M : matrix n n R} (h : M.has_left_inverse) : inverse M ⬝ M = 1 := begin rw [inverse, dif_pos], swap, convert h, convert classical.some_spec h, funext, congr end /-- false with current inverse definition. True when `M` is square -/ lemma mul_inverse [decidable_eq n] {M : matrix n n R} (h : M.has_right_inverse) : M ⬝ inverse M = 1 := by rw [mul_eq_one_comm, inverse_mul (has_right_inverse_iff_has_left_inverse.1 h)] lemma mul_inverse_rev [decidable_eq n] {M : matrix n n R} {N : matrix n n R} (hM : M.has_left_inverse) (hN : N.has_left_inverse) : inverse (M ⬝ N) = inverse N ⬝ inverse M := by rw [← mul_left_inj hN, ← matrix.mul_assoc, mul_inverse (has_right_inverse_iff_has_left_inverse.2 hN), matrix.one_mul, ← mul_left_inj hM, mul_inverse (has_right_inverse_iff_has_left_inverse.2 hM), ← matrix.mul_assoc, mul_inverse (has_right_inverse_iff_has_left_inverse.2 ((has_left_inverse_mul hM).1 hN))] lemma inverse_has_right_inverse [decidable_eq n] {M : matrix n n R} (h : M.has_left_inverse) : M.inverse.has_right_inverse := ⟨_, inverse_mul h⟩ lemma inverse_has_left_inverse [decidable_eq n] {M : matrix n n R} (h : M.has_right_inverse) : M.inverse.has_left_inverse := ⟨_, mul_inverse h⟩ lemma eq_inverse_of_mul_eq_one [decidable_eq n] {M N : matrix n n R} (h : M ⬝ N = 1) : M = inverse N := by rw [← matrix.one_mul (inverse N), ← h, matrix.mul_assoc, mul_inverse (has_right_inverse_iff_has_left_inverse.2 ⟨_, h⟩), matrix.mul_one] @[simp] lemma inverse_one [decidable_eq n] : inverse (1 : matrix n n R) = 1 := (eq_inverse_of_mul_eq_one (matrix.one_mul 1)).symm @[simp] lemma inverse_zero : inverse (0 : matrix n n R) = 0 := by letI := classical.dec_eq n; exact if h01 : (0 : matrix n n R) = 1 then (eq_inverse_of_mul_eq_one $ by rw [h01, matrix.one_mul]).symm else begin rw [inverse, dif_neg], rintros ⟨M, h⟩, rw [matrix.mul_zero] at h, apply h01, convert h end end inverse -- lemma minor_mul [ring R] (M : matrix m n R) (N : matrix n o R) (row : l → m) : -- minor M row id ⬝ N = minor (M ⬝ N) row id := rfl -- lemma mul_minor [ring R] {M : matrix m n R} {N : matrix n l R} (col : o → l) : -- M ⬝ minor N id col = minor (M ⬝ N) id col := rfl -- lemma minor_eq_mul_minor_one [ring R] [decidable_eq m] [decidable_eq n] (M : matrix m n R) -- (row : l → m) : minor M row id = minor 1 row id ⬝ M := -- by rw [minor_mul, M.one_mul] -- lemma minor_eq_minor_one_mul [ring R] [decidable_eq m] [decidable_eq n] (M : matrix m n R) -- (col : o → n) : minor M id col = M ⬝ minor 1 id col := -- by rw [mul_minor, M.mul_one] -- lemma transpose_diagonal [has_zero R] [decidable_eq n] (d : n → R) : -- (diagonal d)ᵀ = diagonal d := -- by ext; dsimp [diagonal, transpose]; split_ifs; cc -- @[simp] lemma transpose_one [has_zero R] [has_one R] [decidable_eq n] : -- (1 : matrix n n R)ᵀ = 1 := transpose_diagonal _ -- lemma transpose_minor [ring R] [decidable_eq m] [decidable_eq n] (M : matrix m n R) -- (row : l → m) (col : o → n) : (minor M row col)ᵀ = minor Mᵀ col row := rfl -- lemma minor_minor {k l m n o p : Type u} [fintype k] [fintype l] [fintype m] [fintype n] -- [fintype o] [fintype p] (M : matrix m n R) -- (row₁ : l → m) (row₂ : k → l) (col₁ : o → n) (col₂ : p → o) : -- minor (minor M row₁ col₁) row₂ col₂ = minor M (row₁ ∘ row₂) (col₁ ∘ col₂) := rfl -- lemma minor_diagonal_eq_diagonal [has_zero R] [decidable_eq m] [decidable_eq n] -- {f : m → n} (hf : injective f) (d : n → R) : minor (diagonal d) f f = diagonal (d ∘ f) := -- by ext; simp [diagonal, minor, hf.eq_iff]; congr -- lemma minor_one_eq_one [has_zero R] [has_one R] [decidable_eq m] [decidable_eq n] -- {f : m → n} (hf : injective f) : minor (1 : matrix n n R) f f = 1 := -- minor_diagonal_eq_diagonal hf _ -- open finset -- lemma minor_one_mul_transpose_eq_one [ring R] [decidable_eq n] [decidable_eq m] {f : m → n} -- (hf : injective f) : minor (1 : matrix n n R) f id ⬝ (minor 1 f id)ᵀ = 1 := -- by rw [minor_mul, transpose_minor, mul_minor, transpose_one, matrix.one_mul, minor_minor]; -- exact minor_one_eq_one hf -- lemma transpose_mul_minor_one_eq_diagonal [ring R] [decidable_eq n] [decidable_eq m] {f : m → n} -- (hf : injective f) : (minor (1 : matrix n n R) f id)ᵀ ⬝ (minor (1 : matrix n n R) f id) = -- diagonal (λ i, if i ∈ set.range f then 1 else 0) := -- begin -- ext i j, -- dsimp [transpose_minor, transpose_one, minor, minor, matrix.mul, diagonal, transpose, one_val], -- by_cases hi : i ∈ set.range f, -- { cases id hi with k hk, -- rw [sum_eq_single k]; -- simp [hk.symm, hi, -set.mem_range, hf.eq_iff] {contextual := tt}; try {congr} }, -- { rw [sum_eq_zero, if_neg hi]; simp * at * } -- end -- lemma transpose_mul_minor_one_eq_diagonal [ring R] [decidable_eq n] [decidable_eq m] -- {f : m → n} {g : l → n} (hf : injective f) (hg : injective g) : -- (minor (1 : matrix n n R) f id) ⬝ (minor (1 : matrix n n R) g id)ᵀ = -- diagonal (λ i, if i ∈ set.range f then 1 else 0) := -- lemma tranpose_mul_minor_one_add_transpose_mul_minor_one -- [ring R] [decidable_eq l] [decidable_eq m] [decidable_eq n] {f : m → n} {g : l → n} -- (hf : injective f) (hg : injective g) (hfg : ∀ i, i ∈ set.range f ∪ set.range g) -- (hd : disjoint (set.range f) (set.range g)): -- (minor (1 : matrix n n R) f id)ᵀ ⬝ (minor (1 : matrix n n R) f id) + -- (minor (1 : matrix n n R) g id)ᵀ ⬝ (minor (1 : matrix n n R) g id) = 1 := -- matrix.ext $ λ i j, begin -- have : i ∈ set.range f → i ∈ set.range g → false, -- from λ hf hg, set.disjoint_iff.1 hd ⟨hf, hg⟩, -- have := hfg i, -- rw [transpose_mul_minor_one_eq_diagonal hf, transpose_mul_minor_one_eq_diagonal hg, -- diagonal_add, diagonal], -- dsimp only, -- split_ifs; -- simp * at * -- end -- local attribute [instance] finsupp.add_comm_group finsupp.module -- def finsupp_equiv_cvec [ring R] [decidable_eq R] [decidable_eq m] : -- (m →₀ R) ≃ₗ[R] matrix m one R := -- { to_fun := λ x i _, x i, -- inv_fun := λ v, finsupp.equiv_fun_on_fintype.2 (λ i, v i £), -- left_inv := λ _, finsupp.ext (λ _, rfl), -- right_inv := λ _, cvec.ext (λ _, rfl), -- add := λ x y, rfl, -- smul := λ c x, rfl } -- def to_lin' (one : Type u) [unique one] [comm_ring R] (A : matrix m n R) : -- matrix n one R →ₗ[R] matrix m one R := -- { to_fun := (⬝) A, -- add := matrix.mul_add _, -- smul := matrix.mul_smul _, } -- def is_invertible [comm_ring R] : Prop := -- bijective (A.to_lin' punit : matrix n punit R → matrix m punit R) def one_by_one_equiv (one R : Type*) [unique one] [ring R] [decidable_eq one] : matrix one one R ≃ R := { to_fun := λ M, M (default _) (default _), inv_fun := λ x _ _, x, left_inv := λ _, matrix.ext (λ i j, by rw [unique.eq_default i, unique.eq_default j]), right_inv := λ _, rfl } lemma one_by_one_equiv.is_ring_hom (one R : Type*) [unique one] [decidable_eq one] [ring R] : is_ring_hom (one_by_one_equiv one R) := { map_one := if_pos rfl, map_add := λ _ _, rfl, map_mul := λ _ _, by dsimp [one_by_one_equiv, matrix.mul]; simp } instance [comm_ring R] : comm_ring (matrix one one R) := { mul_comm := λ a b, show a ⬝ b = b ⬝ a, from matrix.ext $ λ i j, by rw [unique.eq_default i, unique.eq_default j]; simp [matrix.mul]; exact mul_comm _ _, ..matrix.ring } /- should be changed once there is a computable matrix inverse -/ instance [discrete_field R] : discrete_field (matrix one one R) := have mul_inv : ∀ (M : matrix one one R), M ≠ 0 → (λ i j, M i j) ⬝ (λ i j, (M i j)⁻¹) = 1, begin assume M h, ext i j, have h : M (default one) (default one) ≠ 0, from λ hM, h (matrix.ext $ λ i j, by convert hM), rw [unique.eq_default i, unique.eq_default j], simp [matrix.mul, mul_inv_cancel h], end, { mul := (*), inv := λ M i j, (M i j)⁻¹, zero_ne_one := mt (matrix.ext_iff).2 (λ h, absurd (h (default one) (default one)) $ by rw [matrix.one_val, if_pos rfl]; exact zero_ne_one), mul_inv_cancel := mul_inv, inv_mul_cancel := λ M h, eq.trans (mul_comm _ _) (mul_inv M h), has_decidable_eq := by apply_instance, inv_zero := matrix.ext $ λ _ _, inv_zero, ..matrix.comm_ring } section matrix_order variables {α : Type*} def matrix.partial_order [partial_order α] : partial_order (matrix m n α) := pi.partial_order def matrix.ordered_comm_group [ordered_comm_group α] : ordered_comm_group (matrix m n α) := pi.ordered_comm_group local attribute [instance] matrix.partial_order matrix.ordered_comm_group lemma matrix.mul_nonneg [ordered_semiring α] {M : matrix m n α} {N : matrix n o α} (hM : 0 ≤ M) (hN : 0 ≤ N) : 0 ≤ M ⬝ N := λ i j, by classical; exact finset.sum_nonneg (λ _ _, mul_nonneg (hM _ _) (hN _ _)) lemma matrix.mul_nonpos_of_nonpos_of_nonneg [ordered_semiring α] {M : matrix m n α} {N : matrix n o α} (hM : M ≤ 0) (hN : 0 ≤ N) : M ⬝ N ≤ 0 := λ i j, by classical; exact finset.sum_nonpos (λ _ _, mul_nonpos_of_nonpos_of_nonneg (hM _ _) (hN _ _)) lemma pequiv_nonneg [decidable_eq m] [decidable_eq n] [linear_ordered_semiring α] (f : pequiv m n) : (0 : matrix _ _ α) ≤ f.to_matrix := λ i j, by rw [pequiv.to_matrix]; split_ifs; [exact zero_le_one, exact le_refl _] def matrix.decidable_le [partial_order α] [decidable_rel ((≤) : α → α → Prop)] : decidable_rel ((≤) : Π a b : matrix m n α, Prop) := λ M N, show decidable (∀ i j, M i j ≤ N i j), by apply_instance lemma le_iff_single_mul_le [decidable_eq l] [decidable_eq m] [decidable_eq n] [linear_ordered_semiring R] (x : l) (a b : matrix m n R) : a ≤ b ↔ (∀ i : m, (single x i).to_matrix ⬝ a ≤ (single x i).to_matrix ⬝ b) := show (∀ i j, a i j ≤ b i j) ↔ (∀ i j k, ((single x i).to_matrix ⬝ a) j k ≤ ((single x i).to_matrix ⬝ b) j k), begin simp only [mul_matrix_apply], split, { intros h i j k, dsimp [single], split_ifs, { rw if_pos h_1, exact h _ _ }, { rw if_neg h_1 } }, { intros h i j, convert h i x j; dsimp [single]; rw [if_pos rfl] } end lemma le_iff_mul_single_le [decidable_eq l] [decidable_eq m] [decidable_eq n] [linear_ordered_semiring R] (x : l) (a b : matrix m n R) : a ≤ b ↔ (∀ j : n, a ⬝ (single j x).to_matrix ≤ b ⬝ (single j x).to_matrix) := show (∀ i j, a i j ≤ b i j) ↔ (∀ (j : n) (i k), (a ⬝ (single j x).to_matrix) i k ≤ (b ⬝ (single j x).to_matrix) i k), begin simp only [matrix_mul_apply], split, { intros h i j k, dsimp [single, pequiv.symm], split_ifs, { rw if_pos h_1, exact h _ _ }, { rw if_neg h_1 } }, { intros h i j, convert h j i x; dsimp [single, pequiv.symm]; rw [if_pos rfl] } end lemma one_by_one_lt_iff [partial_order α] {a b : matrix one one α} : a < b ↔ a (default one) (default one) < b (default one) (default one) := begin simp only [lt_iff_le_not_le], show (∀ i j, a i j ≤ b i j) ∧ (¬ ∀ i j, b i j ≤ a i j) ↔ _, simp [unique.forall_iff], end instance [decidable_linear_order α] : decidable_linear_order (matrix one one α) := { le_total := λ a b, (le_total (a (default one) (default one)) (b (default one) (default one))).elim (λ hab, or.inl $ λ i j, by rw [unique.eq_default i, unique.eq_default j]; exact hab) (λ hba, or.inr $ λ i j, by rw [unique.eq_default i, unique.eq_default j]; exact hba), decidable_le := matrix.decidable_le, ..matrix.partial_order } instance [discrete_linear_ordered_field R] : discrete_linear_ordered_field (matrix one one R) := { mul_nonneg := λ a b ha0 hb0 i j, by simp [matrix.mul]; exact mul_nonneg (ha0 _ _) (hb0 _ _), mul_pos := λ a b ha0 hb0, begin rw [one_by_one_lt_iff] at *, simp [matrix.mul], exact mul_pos ha0 hb0 end, one := 1, zero_lt_one := one_by_one_lt_iff.2 $ by rw [one_val, if_pos rfl]; exact zero_lt_one, ..matrix.discrete_field, ..matrix.ordered_comm_group, ..matrix.decidable_linear_order } lemma inv_def [discrete_field R] (a : matrix one one R) : a⁻¹ = (λ _ _, (a (default one) (default one))⁻¹) := by ext i j; rw [unique.eq_default i, unique.eq_default j]; refl end matrix_order lemma mul_right_eq_of_mul_eq [semiring R] {M : matrix l m R} {N : matrix m n R} {O : matrix l n R} {P : matrix n o R} (h : M ⬝ N = O) : M ⬝ (N ⬝ P) = O ⬝ P := by classical; rw [← matrix.mul_assoc, h] lemma inv_eq_inverse [discrete_field R] (a : matrix one one R) : a⁻¹ = inverse a := if ha : a = 0 then by simp [ha] else eq_inverse_of_mul_eq_one (by rw [← matrix.mul_eq_mul, inv_mul_cancel ha]; congr) lemma one_by_one_mul_inv_cancel {M : matrix one one ℚ} (hM : M ≠ 0) : M ⬝ inverse M = 1 := by rw [← matrix.mul_eq_mul, ← inv_eq_inverse, mul_inv_cancel hM] lemma one_by_one_inv_mul_cancel {M : matrix (fin 1) (fin 1) ℚ} (hM : M ≠ 0) : inverse M ⬝ M = 1 := by rw [← matrix.mul_eq_mul, ← inv_eq_inverse, inv_mul_cancel hM] end end matrix open pequiv lemma mul_single_ext {R : Type*} {m n : ℕ} [semiring R] {A B : matrix (fin m) (fin n) R} (h : ∀ j : fin n, A ⬝ (single j (0 : fin 1)).to_matrix = B ⬝ (single j (0 : fin 1)).to_matrix) : A = B := by ext i j; simpa [matrix_mul_apply] using congr_fun (congr_fun (h j) i) 0 lemma single_mul_ext {R : Type*} {m n : ℕ} [semiring R] {A B : matrix (fin m) (fin n) R} (h : ∀ i, (single (0 : fin 1) i).to_matrix ⬝ A = (single (0 : fin 1) i).to_matrix ⬝ B) : A = B := by ext i j; simpa [mul_matrix_apply] using congr_fun (congr_fun (h i) 0) j
4e8a546c6e7810b302c5246f852c40bcf860fdd5
26ac254ecb57ffcb886ff709cf018390161a9225
/src/order/basic.lean
115b4ffb4f0c36244d4e7bee23a47b841ce297f8
[ "Apache-2.0" ]
permissive
eric-wieser/mathlib
42842584f584359bbe1fc8b88b3ff937c8acd72d
d0df6b81cd0920ad569158c06a3fd5abb9e63301
refs/heads/master
1,669,546,404,255
1,595,254,668,000
1,595,254,668,000
281,173,504
0
0
Apache-2.0
1,595,263,582,000
1,595,263,581,000
null
UTF-8
Lean
false
false
16,691
lean
/- Copyright (c) 2014 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Mario Carneiro -/ import data.subtype import data.prod open function /-! # Basic definitions about `≤` and `<` ## Definitions ### Predicates on functions - `monotone f`: a function between two types equipped with `≤` is monotone if `a ≤ b` implies `f a ≤ f b`. - `strict_mono f` : a function between two types equipped with `<` is strictly monotone if `a < b` implies `f a < f b`. - `order_dual α` : a type tag reversing the meaning of all inequalities. ### Transfering orders - `order.preimage`, `preorder.lift`: transfer a (pre)order on `β` to an order on `α` using a function `f : α → β`. - `partial_order.lift`, `linear_order.lift`, `decidable_linear_order.lift`: transfer a partial (resp., linear, decidable linear) order on `β` to a partial (resp., linear, decidable linear) order on `α` using an injective function `f`. ### Extra classes - `no_top_order`, `no_bot_order`: an order without a maximal/minimal element. - `densely_ordered`: an order with no gaps, i.e. for any two elements `a<b` there exists `c`, `a<c<b`. ## Main theorems - `monotone_of_monotone_nat`: if `f : ℕ → α` and `f n ≤ f (n + 1)` for all `n`, then `f` is monotone; - `strict_mono.nat`: if `f : ℕ → α` and `f n < f (n + 1)` for all `n`, then f is strictly monotone. ## TODO - expand module docs - automatic construction of dual definitions / theorems ## Tags preorder, order, partial order, linear order, monotone, strictly monotone -/ universes u v w variables {α : Type u} {β : Type v} {γ : Type w} {r : α → α → Prop} @[nolint ge_or_gt] -- see Note [nolint_ge] theorem ge_of_eq [preorder α] {a b : α} : a = b → a ≥ b := λ h, h ▸ le_refl a theorem preorder.ext {α} {A B : preorder α} (H : ∀ x y : α, (by haveI := A; exact x ≤ y) ↔ x ≤ y) : A = B := begin casesI A, casesI B, congr, { funext x y, exact propext (H x y) }, { funext x y, dsimp [(≤)] at A_lt_iff_le_not_le B_lt_iff_le_not_le H, simp [A_lt_iff_le_not_le, B_lt_iff_le_not_le, H] }, end theorem partial_order.ext {α} {A B : partial_order α} (H : ∀ x y : α, (by haveI := A; exact x ≤ y) ↔ x ≤ y) : A = B := by { haveI this := preorder.ext H, casesI A, casesI B, injection this, congr' } theorem linear_order.ext {α} {A B : linear_order α} (H : ∀ x y : α, (by haveI := A; exact x ≤ y) ↔ x ≤ y) : A = B := by { haveI this := partial_order.ext H, casesI A, casesI B, injection this, congr' } /-- Given an order `R` on `β` and a function `f : α → β`, the preimage order on `α` is defined by `x ≤ y ↔ f x ≤ f y`. It is the unique order on `α` making `f` an order embedding (assuming `f` is injective). -/ @[simp] def order.preimage {α β} (f : α → β) (s : β → β → Prop) (x y : α) := s (f x) (f y) infix ` ⁻¹'o `:80 := order.preimage /-- The preimage of a decidable order is decidable. -/ instance order.preimage.decidable {α β} (f : α → β) (s : β → β → Prop) [H : decidable_rel s] : decidable_rel (f ⁻¹'o s) := λ x y, H _ _ section monotone variables [preorder α] [preorder β] [preorder γ] /-- A function between preorders is monotone if `a ≤ b` implies `f a ≤ f b`. -/ def monotone (f : α → β) := ∀⦃a b⦄, a ≤ b → f a ≤ f b theorem monotone_id : @monotone α α _ _ id := assume x y h, h theorem monotone_const {b : β} : monotone (λ(a:α), b) := assume x y h, le_refl b protected theorem monotone.comp {g : β → γ} {f : α → β} (m_g : monotone g) (m_f : monotone f) : monotone (g ∘ f) := assume a b h, m_g (m_f h) protected theorem monotone.iterate {f : α → α} (hf : monotone f) (n : ℕ) : monotone (f^[n]) := nat.rec_on n monotone_id (λ n ihn, ihn.comp hf) lemma monotone_of_monotone_nat {f : ℕ → α} (hf : ∀n, f n ≤ f (n + 1)) : monotone f | n m h := begin induction h, { refl }, { transitivity, assumption, exact hf _ } end lemma reflect_lt {α β} [linear_order α] [preorder β] {f : α → β} (hf : monotone f) {x x' : α} (h : f x < f x') : x < x' := by { rw [← not_le], intro h', apply not_le_of_lt h, exact hf h' } end monotone /-- A function `f` is strictly monotone if `a < b` implies `f a < f b`. -/ def strict_mono [has_lt α] [has_lt β] (f : α → β) : Prop := ∀ ⦃a b⦄, a < b → f a < f b lemma strict_mono_id [has_lt α] : strict_mono (id : α → α) := λ a b, id /-- A function `f` is strictly monotone increasing on `t` if `x < y` for `x,y ∈ t` implies `f x < f y`. -/ def strict_mono_incr_on [has_lt α] [has_lt β] (f : α → β) (t : set α) : Prop := ∀ (x ∈ t) (y ∈ t), x < y → f x < f y /-- A function `f` is strictly monotone decreasing on `t` if `x < y` for `x,y ∈ t` implies `f y < f x`. -/ def strict_mono_decr_on [has_lt α] [has_lt β] (f : α → β) (t : set α) : Prop := ∀ (x ∈ t) (y ∈ t), x < y → f y < f x namespace strict_mono open ordering function lemma comp [has_lt α] [has_lt β] [has_lt γ] {g : β → γ} {f : α → β} (hg : strict_mono g) (hf : strict_mono f) : strict_mono (g ∘ f) := λ a b h, hg (hf h) protected theorem iterate [has_lt α] {f : α → α} (hf : strict_mono f) (n : ℕ) : strict_mono (f^[n]) := nat.rec_on n strict_mono_id (λ n ihn, ihn.comp hf) lemma id_le {φ : ℕ → ℕ} (h : strict_mono φ) : ∀ n, n ≤ φ n := λ n, nat.rec_on n (nat.zero_le _) (λ n hn, nat.succ_le_of_lt (lt_of_le_of_lt hn $ h $ nat.lt_succ_self n)) section variables [linear_order α] [preorder β] {f : α → β} lemma lt_iff_lt (H : strict_mono f) {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 injective (H : strict_mono f) : 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 theorem compares (H : strict_mono f) {a b} : ∀ {o}, compares o (f a) (f b) ↔ compares o a b | lt := H.lt_iff_lt | eq := ⟨λ h, H.injective h, congr_arg _⟩ | gt := H.lt_iff_lt lemma le_iff_le (H : strict_mono f) {a b} : f a ≤ f b ↔ a ≤ b := ⟨λ h, le_of_not_gt $ λ h', not_le_of_lt (H h') h, λ h, (lt_or_eq_of_le h).elim (λ h', le_of_lt (H h')) (λ h', h' ▸ le_refl _)⟩ end protected lemma nat {β} [preorder β] {f : ℕ → β} (h : ∀n, f n < f (n+1)) : strict_mono f := by { intros n m hnm, induction hnm with m' hnm' ih, apply h, exact lt.trans ih (h _) } -- `preorder α` isn't strong enough: if the preorder on α is an equivalence relation, -- then `strict_mono f` is vacuously true. lemma monotone [partial_order α] [preorder β] {f : α → β} (H : strict_mono f) : monotone f := λ a b h, (lt_or_eq_of_le h).rec (le_of_lt ∘ (@H _ _)) (by rintro rfl; refl) end strict_mono section open function lemma injective_of_lt_imp_ne [linear_order α] {f : α → β} (h : ∀ x y, x < y → f x ≠ f y) : injective f := begin intros x y k, contrapose k, rw [←ne.def, ne_iff_lt_or_gt] at k, cases k, { apply h _ _ k }, { rw eq_comm, apply h _ _ k } end variables [partial_order α] [partial_order β] {f : α → β} lemma strict_mono_of_monotone_of_injective (h₁ : monotone f) (h₂ : injective f) : strict_mono f := λ a b h, begin rw lt_iff_le_and_ne at ⊢ h, exact ⟨h₁ h.1, λ e, h.2 (h₂ e)⟩ end end /-- Type tag for a set with dual order: `≤` means `≥` and `<` means `>`. -/ def order_dual (α : Type*) := α namespace order_dual instance (α : Type*) [h : nonempty α] : nonempty (order_dual α) := h instance (α : Type*) [has_le α] : has_le (order_dual α) := ⟨λx y:α, y ≤ x⟩ instance (α : Type*) [has_lt α] : has_lt (order_dual α) := ⟨λx y:α, y < x⟩ -- `dual_le` and `dual_lt` should not be simp lemmas: -- they cause a loop since `α` and `order_dual α` are definitionally equal lemma dual_le [has_le α] {a b : α} : @has_le.le (order_dual α) _ a b ↔ @has_le.le α _ b a := iff.rfl lemma dual_lt [has_lt α] {a b : α} : @has_lt.lt (order_dual α) _ a b ↔ @has_lt.lt α _ b a := iff.rfl instance (α : Type*) [preorder α] : preorder (order_dual α) := { le_refl := le_refl, le_trans := assume a b c hab hbc, le_trans hbc hab, lt_iff_le_not_le := λ _ _, lt_iff_le_not_le, .. order_dual.has_le α, .. order_dual.has_lt α } instance (α : Type*) [partial_order α] : partial_order (order_dual α) := { le_antisymm := assume a b hab hba, @le_antisymm α _ a b hba hab, .. order_dual.preorder α } instance (α : Type*) [linear_order α] : linear_order (order_dual α) := { le_total := assume a b:α, le_total b a, .. order_dual.partial_order α } instance (α : Type*) [decidable_linear_order α] : decidable_linear_order (order_dual α) := { decidable_le := show decidable_rel (λa b:α, b ≤ a), by apply_instance, decidable_lt := show decidable_rel (λa b:α, b < a), by apply_instance, .. order_dual.linear_order α } instance : Π [inhabited α], inhabited (order_dual α) := id end order_dual /- order instances on the function space -/ instance pi.preorder {ι : Type u} {α : ι → Type v} [∀i, preorder (α i)] : preorder (Πi, α i) := { le := λx y, ∀i, x i ≤ y i, le_refl := assume a i, le_refl (a i), le_trans := assume a b c h₁ h₂ i, le_trans (h₁ i) (h₂ i) } instance pi.partial_order {ι : Type u} {α : ι → Type v} [∀i, partial_order (α i)] : partial_order (Πi, α i) := { le_antisymm := λf g h1 h2, funext (λb, le_antisymm (h1 b) (h2 b)), ..pi.preorder } theorem comp_le_comp_left_of_monotone [preorder α] [preorder β] {f : β → α} {g h : γ → β} (m_f : monotone f) (le_gh : g ≤ h) : has_le.le.{max w u} (f ∘ g) (f ∘ h) := assume x, m_f (le_gh x) section monotone variables [preorder α] [preorder γ] protected theorem monotone.order_dual {f : α → γ} (hf : monotone f) : @monotone (order_dual α) (order_dual γ) _ _ f := λ x y hxy, hf hxy theorem monotone_lam {f : α → β → γ} (m : ∀b, monotone (λa, f a b)) : monotone f := assume a a' h b, m b h theorem monotone_app (f : β → α → γ) (b : β) (m : monotone (λa b, f b a)) : monotone (f b) := assume a a' h, m h b end monotone theorem strict_mono.order_dual [has_lt α] [has_lt β] {f : α → β} (hf : strict_mono f) : @strict_mono (order_dual α) (order_dual β) _ _ f := λ x y hxy, hf hxy /-- Transfer a `preorder` on `β` to a `preorder` on `α` using a function `f : α → β`. -/ def preorder.lift {α β} [preorder β] (f : α → β) : preorder α := { le := λx y, f x ≤ f y, le_refl := λ a, le_refl _, le_trans := λ a b c, le_trans, lt := λx y, f x < f y, lt_iff_le_not_le := λ a b, lt_iff_le_not_le } /-- Transfer a `partial_order` on `β` to a `partial_order` on `α` using an injective function `f : α → β`. -/ def partial_order.lift {α β} [partial_order β] (f : α → β) (inj : injective f) : partial_order α := { le_antisymm := λ a b h₁ h₂, inj (le_antisymm h₁ h₂), .. preorder.lift f } /-- Transfer a `linear_order` on `β` to a `linear_order` on `α` using an injective function `f : α → β`. -/ def linear_order.lift {α β} [linear_order β] (f : α → β) (inj : injective f) : linear_order α := { le_total := λx y, le_total (f x) (f y), .. partial_order.lift f inj } /-- Transfer a `decidable_linear_order` on `β` to a `decidable_linear_order` on `α` using an injective function `f : α → β`. -/ def decidable_linear_order.lift {α β} [decidable_linear_order β] (f : α → β) (inj : injective f) : decidable_linear_order α := { decidable_le := λ x y, show decidable (f x ≤ f y), by apply_instance, decidable_lt := λ x y, show decidable (f x < f y), by apply_instance, decidable_eq := λ x y, decidable_of_iff _ ⟨@inj x y, congr_arg f⟩, .. linear_order.lift f inj } instance subtype.preorder {α} [preorder α] (p : α → Prop) : preorder (subtype p) := preorder.lift subtype.val instance subtype.partial_order {α} [partial_order α] (p : α → Prop) : partial_order (subtype p) := partial_order.lift subtype.val subtype.val_injective instance subtype.linear_order {α} [linear_order α] (p : α → Prop) : linear_order (subtype p) := linear_order.lift subtype.val subtype.val_injective instance subtype.decidable_linear_order {α} [decidable_linear_order α] (p : α → Prop) : decidable_linear_order (subtype p) := decidable_linear_order.lift subtype.val subtype.val_injective instance prod.has_le (α : Type u) (β : Type v) [has_le α] [has_le β] : has_le (α × β) := ⟨λp q, p.1 ≤ q.1 ∧ p.2 ≤ q.2⟩ instance prod.preorder (α : Type u) (β : Type v) [preorder α] [preorder β] : preorder (α × β) := { le_refl := assume ⟨a, b⟩, ⟨le_refl a, le_refl b⟩, le_trans := assume ⟨a, b⟩ ⟨c, d⟩ ⟨e, f⟩ ⟨hac, hbd⟩ ⟨hce, hdf⟩, ⟨le_trans hac hce, le_trans hbd hdf⟩, .. prod.has_le α β } /-- The pointwise partial order on a product. (The lexicographic ordering is defined in order/lexicographic.lean, and the instances are available via the type synonym `lex α β = α × β`.) -/ instance prod.partial_order (α : Type u) (β : Type v) [partial_order α] [partial_order β] : partial_order (α × β) := { le_antisymm := assume ⟨a, b⟩ ⟨c, d⟩ ⟨hac, hbd⟩ ⟨hca, hdb⟩, prod.ext (le_antisymm hac hca) (le_antisymm hbd hdb), .. prod.preorder α β } /-! ### Additional order classes -/ /-- order without a top element; somtimes called cofinal -/ class no_top_order (α : Type u) [preorder α] : Prop := (no_top : ∀a:α, ∃a', a < a') lemma no_top [preorder α] [no_top_order α] : ∀a:α, ∃a', a < a' := no_top_order.no_top /-- order without a bottom element; somtimes called coinitial or dense -/ class no_bot_order (α : Type u) [preorder α] : Prop := (no_bot : ∀a:α, ∃a', a' < a) lemma no_bot [preorder α] [no_bot_order α] : ∀a:α, ∃a', a' < a := no_bot_order.no_bot instance order_dual.no_top_order (α : Type u) [preorder α] [no_bot_order α] : no_top_order (order_dual α) := ⟨λ a, @no_bot α _ _ a⟩ instance order_dual.no_bot_order (α : Type u) [preorder α] [no_top_order α] : no_bot_order (order_dual α) := ⟨λ a, @no_top α _ _ a⟩ /-- An order is dense if there is an element between any pair of distinct elements. -/ class densely_ordered (α : Type u) [preorder α] : Prop := (dense : ∀a₁ a₂:α, a₁ < a₂ → ∃a, a₁ < a ∧ a < a₂) lemma dense [preorder α] [densely_ordered α] : ∀{a₁ a₂:α}, a₁ < a₂ → ∃a, a₁ < a ∧ a < a₂ := densely_ordered.dense instance order_dual.densely_ordered (α : Type u) [preorder α] [densely_ordered α] : densely_ordered (order_dual α) := ⟨λ a₁ a₂ ha, (@dense α _ _ _ _ ha).imp $ λ a, and.symm⟩ lemma le_of_forall_le_of_dense [linear_order α] [densely_ordered α] {a₁ a₂ : α} (h : ∀a₃>a₂, a₁ ≤ a₃) : a₁ ≤ a₂ := le_of_not_gt $ assume ha, let ⟨a, ha₁, ha₂⟩ := dense ha in lt_irrefl a $ lt_of_lt_of_le ‹a < a₁› (h _ ‹a₂ < a›) lemma eq_of_le_of_forall_le_of_dense [linear_order α] [densely_ordered α] {a₁ a₂ : α} (h₁ : a₂ ≤ a₁) (h₂ : ∀a₃>a₂, a₁ ≤ a₃) : a₁ = a₂ := le_antisymm (le_of_forall_le_of_dense h₂) h₁ lemma le_of_forall_ge_of_dense [linear_order α] [densely_ordered α] {a₁ a₂ : α} (h : ∀a₃<a₁, a₂ ≥ a₃) : a₁ ≤ a₂ := le_of_not_gt $ assume ha, let ⟨a, ha₁, ha₂⟩ := dense ha in lt_irrefl a $ lt_of_le_of_lt (h _ ‹a < a₁›) ‹a₂ < a› lemma eq_of_le_of_forall_ge_of_dense [linear_order α] [densely_ordered α] {a₁ a₂ : α} (h₁ : a₂ ≤ a₁) (h₂ : ∀a₃<a₁, a₂ ≥ a₃) : a₁ = a₂ := le_antisymm (le_of_forall_ge_of_dense h₂) h₁ @[nolint ge_or_gt] -- see Note [nolint_ge] lemma dense_or_discrete [linear_order α] (a₁ a₂ : α) : (∃a, a₁ < a ∧ a < a₂) ∨ ((∀a>a₁, a ≥ a₂) ∧ (∀a<a₂, a ≤ a₁)) := classical.or_iff_not_imp_left.2 $ assume h, ⟨assume a ha₁, le_of_not_gt $ assume ha₂, h ⟨a, ha₁, ha₂⟩, assume a ha₂, le_of_not_gt $ assume ha₁, h ⟨a, ha₁, ha₂⟩⟩ variables {s : β → β → Prop} {t : γ → γ → Prop} /-- Any `linear_order` is a noncomputable `decidable_linear_order`. This is not marked as an instance to avoid a loop. -/ noncomputable def classical.DLO (α) [LO : linear_order α] : decidable_linear_order α := { decidable_le := classical.dec_rel _, ..LO }
d38e15dc3532d15767a56527923da7585c6fad72
4efff1f47634ff19e2f786deadd394270a59ecd2
/src/group_theory/sylow.lean
7449e651cab24d03fead2dbaa99a85471746fe33
[ "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
12,429
lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes -/ import group_theory.group_action import group_theory.quotient_group import group_theory.order_of_element import data.zmod.basic import data.fintype.card import data.list.rotate open equiv fintype finset mul_action function open equiv.perm subgroup list quotient_group open_locale big_operators universes u v w variables {G : Type u} {α : Type v} {β : Type w} [group G] local attribute [instance, priority 10] subtype.fintype set_fintype classical.prop_decidable namespace mul_action variables [mul_action G α] lemma mem_fixed_points_iff_card_orbit_eq_one {a : α} [fintype (orbit G a)] : a ∈ fixed_points G α ↔ card (orbit G a) = 1 := begin rw [fintype.card_eq_one_iff, mem_fixed_points], split, { exact λ h, ⟨⟨a, mem_orbit_self _⟩, λ ⟨b, ⟨x, hx⟩⟩, subtype.eq $ by simp [h x, hx.symm]⟩ }, { assume h x, rcases h with ⟨⟨z, hz⟩, hz₁⟩, exact calc x • a = z : subtype.mk.inj (hz₁ ⟨x • a, mem_orbit _ _⟩) ... = a : (subtype.mk.inj (hz₁ ⟨a, mem_orbit_self _⟩)).symm } end lemma card_modeq_card_fixed_points [fintype α] [fintype G] [fintype (fixed_points G α)] (p : ℕ) {n : ℕ} [hp : fact p.prime] (h : card G = p ^ n) : card α ≡ card (fixed_points G α) [MOD p] := calc card α = card (Σ y : quotient (orbit_rel G α), {x // quotient.mk' x = y}) : card_congr (sigma_preimage_equiv (@quotient.mk' _ (orbit_rel G α))).symm ... = ∑ a : quotient (orbit_rel G α), card {x // quotient.mk' x = a} : card_sigma _ ... ≡ ∑ a : fixed_points G α, 1 [MOD p] : begin rw [← zmod.eq_iff_modeq_nat p, sum_nat_cast, sum_nat_cast], refine eq.symm (sum_bij_ne_zero (λ a _ _, quotient.mk' a.1) (λ _ _ _, mem_univ _) (λ a₁ a₂ _ _ _ _ h, subtype.eq ((mem_fixed_points' α).1 a₂.2 a₁.1 (quotient.exact' h))) (λ b, _) (λ a ha _, by rw [← mem_fixed_points_iff_card_orbit_eq_one.1 a.2]; simp only [quotient.eq']; congr)), { refine quotient.induction_on' b (λ b _ hb, _), have : card (orbit G b) ∣ p ^ n, { rw [← h, fintype.card_congr (orbit_equiv_quotient_stabilizer G b)]; exact card_quotient_dvd_card _ }, rcases (nat.dvd_prime_pow hp).1 this with ⟨k, _, hk⟩, have hb' :¬ p ^ 1 ∣ p ^ k, { rw [nat.pow_one, ← hk, ← nat.modeq.modeq_zero_iff, ← zmod.eq_iff_modeq_nat, nat.cast_zero, ← ne.def], exact eq.mpr (by simp only [quotient.eq']; congr) hb }, have : k = 0 := nat.le_zero_iff.1 (nat.le_of_lt_succ (lt_of_not_ge (mt (nat.pow_dvd_pow p) hb'))), refine ⟨⟨b, mem_fixed_points_iff_card_orbit_eq_one.2 $ by rw [hk, this, nat.pow_zero]⟩, mem_univ _, _, rfl⟩, rw [nat.cast_one], exact one_ne_zero } end ... = _ : by simp; refl end mul_action lemma quotient_group.card_preimage_mk [fintype G] (s : subgroup G) (t : set (quotient s)) : fintype.card (quotient_group.mk ⁻¹' t) = fintype.card s * fintype.card t := by rw [← fintype.card_prod, fintype.card_congr (preimage_mk_equiv_subgroup_times_set _ _)] namespace sylow /-- Given a vector `v` of length `n`, make a vector of length `n+1` whose product is `1`, by consing the the inverse of the product of `v`. -/ def mk_vector_prod_eq_one (n : ℕ) (v : vector G n) : vector G (n+1) := v.to_list.prod⁻¹ :: v lemma mk_vector_prod_eq_one_injective (n : ℕ) : injective (@mk_vector_prod_eq_one G _ n) := λ ⟨v, _⟩ ⟨w, _⟩ h, subtype.eq (show v = w, by injection h with h; injection h) /-- The type of vectors with terms from `G`, length `n`, and product equal to `1:G`. -/ def vectors_prod_eq_one (G : Type*) [group G] (n : ℕ) : set (vector G n) := {v | v.to_list.prod = 1} lemma mem_vectors_prod_eq_one {n : ℕ} (v : vector G n) : v ∈ vectors_prod_eq_one G n ↔ v.to_list.prod = 1 := iff.rfl lemma mem_vectors_prod_eq_one_iff {n : ℕ} (v : vector G (n + 1)) : v ∈ vectors_prod_eq_one G (n + 1) ↔ v ∈ set.range (@mk_vector_prod_eq_one G _ n) := ⟨λ (h : v.to_list.prod = 1), ⟨v.tail, begin unfold mk_vector_prod_eq_one, conv {to_rhs, rw ← vector.cons_head_tail v}, suffices : (v.tail.to_list.prod)⁻¹ = v.head, { rw this }, rw [← mul_left_inj v.tail.to_list.prod, inv_mul_self, ← list.prod_cons, ← vector.to_list_cons, vector.cons_head_tail, h] end⟩, λ ⟨w, hw⟩, by rw [mem_vectors_prod_eq_one, ← hw, mk_vector_prod_eq_one, vector.to_list_cons, list.prod_cons, inv_mul_self]⟩ /-- The rotation action of `zmod n` (viewed as multiplicative group) on `vectors_prod_eq_one G n`, where `G` is a multiplicative group. -/ def rotate_vectors_prod_eq_one (G : Type*) [group G] (n : ℕ) (m : multiplicative (zmod n)) (v : vectors_prod_eq_one G n) : vectors_prod_eq_one G n := ⟨⟨v.1.to_list.rotate m.val, by simp⟩, prod_rotate_eq_one_of_prod_eq_one v.2 _⟩ instance rotate_vectors_prod_eq_one.mul_action (n : ℕ) [fact (0 < n)] : mul_action (multiplicative (zmod n)) (vectors_prod_eq_one G n) := { smul := (rotate_vectors_prod_eq_one G n), one_smul := begin intro v, apply subtype.eq, apply vector.eq _ _, show rotate _ (0 : zmod n).val = _, rw zmod.val_zero, exact rotate_zero v.1.to_list end, mul_smul := λ a b ⟨⟨v, hv₁⟩, hv₂⟩, subtype.eq $ vector.eq _ _ $ show v.rotate ((a + b : zmod n).val) = list.rotate (list.rotate v (b.val)) (a.val), by rw [zmod.val_add, rotate_rotate, ← rotate_mod _ (b.val + a.val), add_comm, hv₁] } lemma one_mem_vectors_prod_eq_one (n : ℕ) : vector.repeat (1 : G) n ∈ vectors_prod_eq_one G n := by simp [vector.repeat, vectors_prod_eq_one] lemma one_mem_fixed_points_rotate (n : ℕ) [fact (0 < n)] : (⟨vector.repeat (1 : G) n, one_mem_vectors_prod_eq_one n⟩ : vectors_prod_eq_one G n) ∈ fixed_points (multiplicative (zmod n)) (vectors_prod_eq_one G n) := λ m, subtype.eq $ vector.eq _ _ $ rotate_eq_self_iff_eq_repeat.2 ⟨(1 : G), show list.repeat (1 : G) n = list.repeat 1 (list.repeat (1 : G) n).length, by simp⟩ _ /-- Cauchy's theorem -/ lemma exists_prime_order_of_dvd_card [fintype G] (p : ℕ) [hp : fact p.prime] (hdvd : p ∣ card G) : ∃ x : G, order_of x = p := let n : ℕ+ := ⟨p - 1, nat.sub_pos_of_lt hp.one_lt⟩ in have hn : p = n + 1 := nat.succ_sub hp.pos, have hcard : card (vectors_prod_eq_one G (n + 1)) = card G ^ (n : ℕ), by rw [set.ext mem_vectors_prod_eq_one_iff, set.card_range_of_injective (mk_vector_prod_eq_one_injective _), card_vector], have hzmod : fintype.card (multiplicative (zmod p)) = p ^ 1, by { rw nat.pow_one p, exact zmod.card p }, have hmodeq : _ = _ := @mul_action.card_modeq_card_fixed_points (multiplicative (zmod p)) (vectors_prod_eq_one G p) _ _ _ _ _ _ 1 hp hzmod, have hdvdcard : p ∣ fintype.card (vectors_prod_eq_one G (n + 1)) := calc p ∣ card G ^ 1 : by rwa nat.pow_one ... ∣ card G ^ (n : ℕ) : nat.pow_dvd_pow _ n.2 ... = card (vectors_prod_eq_one G (n + 1)) : hcard.symm, have hdvdcard₂ : p ∣ card (fixed_points (multiplicative (zmod p)) (vectors_prod_eq_one G p)), by { rw nat.dvd_iff_mod_eq_zero at hdvdcard ⊢, rwa [← hn, hmodeq] at hdvdcard }, have hcard_pos : 0 < card (fixed_points (multiplicative (zmod p)) (vectors_prod_eq_one G p)) := fintype.card_pos_iff.2 ⟨⟨⟨vector.repeat 1 p, one_mem_vectors_prod_eq_one _⟩, one_mem_fixed_points_rotate _⟩⟩, have hlt : 1 < card (fixed_points (multiplicative (zmod p)) (vectors_prod_eq_one G p)) := calc (1 : ℕ) < p : hp.one_lt ... ≤ _ : nat.le_of_dvd hcard_pos hdvdcard₂, let ⟨⟨⟨⟨x, hx₁⟩, hx₂⟩, hx₃⟩, hx₄⟩ := fintype.exists_ne_of_one_lt_card hlt ⟨_, one_mem_fixed_points_rotate p⟩ in have hx : x ≠ list.repeat (1 : G) p, from λ h, by simpa [h, vector.repeat] using hx₄, have ∃ a, x = list.repeat a x.length := by exactI rotate_eq_self_iff_eq_repeat.1 (λ n, have list.rotate x (n : zmod p).val = x := subtype.mk.inj (subtype.mk.inj (hx₃ (n : zmod p))), by rwa [zmod.val_cast_nat, ← hx₁, rotate_mod] at this), let ⟨a, ha⟩ := this in ⟨a, have hx1 : x.prod = 1 := hx₂, have ha1: a ≠ 1, from λ h, hx (ha.symm ▸ h ▸ hx₁ ▸ rfl), have a ^ p = 1, by rwa [ha, list.prod_repeat, hx₁] at hx1, (hp.2 _ (order_of_dvd_of_pow_eq_one this)).resolve_left (λ h, ha1 (order_of_eq_one_iff.1 h))⟩ open subgroup submonoid is_group_hom mul_action lemma mem_fixed_points_mul_left_cosets_iff_mem_normalizer {H : subgroup G} [fintype ((H : set G) : Type u)] {x : G} : (x : quotient H) ∈ fixed_points H (quotient H) ↔ x ∈ normalizer H := ⟨λ hx, have ha : ∀ {y : quotient H}, y ∈ orbit H (x : quotient H) → y = x, from λ _, ((mem_fixed_points' _).1 hx _), (inv_mem_iff _).1 (@mem_normalizer_fintype _ _ _ _inst_2 _ (λ n (hn : n ∈ H), have (n⁻¹ * x)⁻¹ * x ∈ H := quotient_group.eq.1 (ha (mem_orbit _ ⟨n⁻¹, H.inv_mem hn⟩)), show _ ∈ H, by {rw [mul_inv_rev, inv_inv] at this, convert this, rw inv_inv} )), λ (hx : ∀ (n : G), n ∈ H ↔ x * n * x⁻¹ ∈ H), (mem_fixed_points' _).2 $ λ y, quotient.induction_on' y $ λ y hy, quotient_group.eq.2 (let ⟨⟨b, hb₁⟩, hb₂⟩ := hy in have hb₂ : (b * x)⁻¹ * y ∈ H := quotient_group.eq.1 hb₂, (inv_mem_iff H).1 $ (hx _).2 $ (mul_mem_cancel_left H (H.inv_mem hb₁)).1 $ by rw hx at hb₂; simpa [mul_inv_rev, mul_assoc] using hb₂)⟩ def fixed_points_mul_left_cosets_equiv_quotient (H : subgroup G) [fintype (H : set G)] : fixed_points H (quotient H) ≃ quotient (subgroup.comap ((normalizer H).subtype : normalizer H →* G) H) := @subtype_quotient_equiv_quotient_subtype G (normalizer H : set G) (id _) (id _) (fixed_points _ _) (λ a, (@mem_fixed_points_mul_left_cosets_iff_mem_normalizer _ _ _ _inst_2 _).symm) (by intros; refl) lemma exists_subgroup_card_pow_prime [fintype G] (p : ℕ) : ∀ {n : ℕ} [hp : fact p.prime] (hdvd : p ^ n ∣ card G), ∃ H : subgroup G, fintype.card H = p ^ n | 0 := λ _ _, ⟨(⊥ : subgroup G), by convert card_trivial⟩ | (n+1) := λ hp hdvd, let ⟨H, hH2⟩ := @exists_subgroup_card_pow_prime _ hp (dvd.trans (nat.pow_dvd_pow _ (nat.le_succ _)) hdvd) in let ⟨s, hs⟩ := exists_eq_mul_left_of_dvd hdvd in have hcard : card (quotient H) = s * p := (nat.mul_left_inj (show card H > 0, from fintype.card_pos_iff.2 ⟨⟨1, H.one_mem⟩⟩)).1 (by rwa [← card_eq_card_quotient_mul_card_subgroup, hH2, hs, nat.pow_succ, mul_assoc, mul_comm p]), have hm : s * p % p = card (quotient (subgroup.comap ((normalizer H).subtype : normalizer H →* G) H)) % p := card_congr (fixed_points_mul_left_cosets_equiv_quotient H) ▸ hcard ▸ @card_modeq_card_fixed_points _ _ _ _ _ _ _ p _ hp hH2, have hm' : p ∣ card (quotient (subgroup.comap ((normalizer H).subtype : normalizer H →* G) H)) := nat.dvd_of_mod_eq_zero (by rwa [nat.mod_eq_zero_of_dvd (dvd_mul_left _ _), eq_comm] at hm), let ⟨x, hx⟩ := @exists_prime_order_of_dvd_card _ (quotient_group.group _) _ _ hp hm' in have hxcard : ∀ {f : fintype (subgroup.gpowers x)}, card (subgroup.gpowers x) = p, from λ f, by rw [← hx, order_eq_card_gpowers]; congr, have fintype (subgroup.comap (quotient_group.mk' (comap H.normalizer.subtype H)) (gpowers x)), by apply_instance, have hequiv : H ≃ (subgroup.comap ((normalizer H).subtype : normalizer H →* G) H) := ⟨λ a, ⟨⟨a.1, le_normalizer a.2⟩, a.2⟩, λ a, ⟨a.1.1, a.2⟩, λ ⟨_, _⟩, rfl, λ ⟨⟨_, _⟩, _⟩, rfl⟩, -- begin proof of ∃ H : subgroup G, fintype.card H = p ^ n ⟨subgroup.map ((normalizer H).subtype) (subgroup.comap (quotient_group.mk' _) (gpowers x)), begin show card ↥(map H.normalizer.subtype (comap (mk' (comap H.normalizer.subtype H)) (subgroup.gpowers x))) = p ^ (n + 1), suffices : card ↥(subtype.val '' ((subgroup.comap (mk' (comap H.normalizer.subtype H)) (gpowers x)) : set (↥(H.normalizer)))) = p^(n+1), { convert this }, rw [set.card_image_of_injective (subgroup.comap (quotient_group.mk' _) (gpowers x) : set (H.normalizer)) subtype.val_injective, nat.pow_succ, ← hH2, fintype.card_congr hequiv, ← hx, order_eq_card_gpowers, ← fintype.card_prod], exact @fintype.card_congr _ _ (id _) (id _) (preimage_mk_equiv_subgroup_times_set _ _) end ⟩ end sylow
bcd2d9ff48c20b1b2fe5143822bddbdd83ccd616
969dbdfed67fda40a6f5a2b4f8c4a3c7dc01e0fb
/src/category_theory/groupoid.lean
421b61ce6c6a8ccacd359b7859135f292fbf4472
[ "Apache-2.0" ]
permissive
SAAluthwela/mathlib
62044349d72dd63983a8500214736aa7779634d3
83a4b8b990907291421de54a78988c024dc8a552
refs/heads/master
1,679,433,873,417
1,615,998,031,000
1,615,998,031,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
2,697
lean
/- Copyright (c) 2018 Reid Barton All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Reid Barton, Scott Morrison, David Wärn -/ import category_theory.epi_mono namespace category_theory universes v v₂ u u₂ -- declare the `v`'s first; see `category_theory.category` for an explanation /-- A `groupoid` is a category such that all morphisms are isomorphisms. -/ class groupoid (obj : Type u) extends category.{v} obj : Type (max u (v+1)) := (inv : Π {X Y : obj}, (X ⟶ Y) → (Y ⟶ X)) (inv_comp' : ∀ {X Y : obj} (f : X ⟶ Y), comp (inv f) f = id Y . obviously) (comp_inv' : ∀ {X Y : obj} (f : X ⟶ Y), comp f (inv f) = id X . obviously) restate_axiom groupoid.inv_comp' restate_axiom groupoid.comp_inv' attribute [simp] groupoid.inv_comp groupoid.comp_inv /-- A `large_groupoid` is a groupoid where the objects live in `Type (u+1)` while the morphisms live in `Type u`. -/ abbreviation large_groupoid (C : Type (u+1)) : Type (u+1) := groupoid.{u} C /-- A `small_groupoid` is a groupoid where the objects and morphisms live in the same universe. -/ abbreviation small_groupoid (C : Type u) : Type (u+1) := groupoid.{u} C section variables {C : Type u} [groupoid.{v} C] {X Y : C} @[priority 100] -- see Note [lower instance priority] instance is_iso.of_groupoid (f : X ⟶ Y) : is_iso f := ⟨groupoid.inv f, by simp⟩ variables (X Y) /-- In a groupoid, isomorphisms are equivalent to morphisms. -/ def groupoid.iso_equiv_hom : (X ≅ Y) ≃ (X ⟶ Y) := { to_fun := iso.hom, inv_fun := λ f, ⟨f, groupoid.inv f⟩, left_inv := λ i, iso.ext rfl, right_inv := λ f, rfl } end section variables {C : Type u} [category.{v} C] /-- A category where every morphism `is_iso` is a groupoid. -/ noncomputable def groupoid.of_is_iso (all_is_iso : ∀ {X Y : C} (f : X ⟶ Y), is_iso f) : groupoid.{v} C := { inv := λ X Y f, inv f } /-- A category where every morphism has a `trunc` retraction is computably a groupoid. -/ -- FIXME this has unnecessarily become noncomputable! noncomputable def groupoid.of_trunc_split_mono (all_split_mono : ∀ {X Y : C} (f : X ⟶ Y), trunc (split_mono f)) : groupoid.{v} C := begin apply groupoid.of_is_iso, intros X Y f, trunc_cases all_split_mono f, trunc_cases all_split_mono (retraction f), apply is_iso.of_mono_retraction, end end instance induced_category.groupoid {C : Type u} (D : Type u₂) [groupoid.{v} D] (F : C → D) : groupoid.{v} (induced_category D F) := { inv := λ X Y f, groupoid.inv f, inv_comp' := λ X Y f, groupoid.inv_comp f, comp_inv' := λ X Y f, groupoid.comp_inv f, .. induced_category.category F } end category_theory
825b90990b7ac456ab987f5425f056b162ddcf33
d1a52c3f208fa42c41df8278c3d280f075eb020c
/src/Init/Notation.lean
81329a1584af6f1ad4bbf2650f7ade22cc8a4ae8
[ "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
20,711
lean
/- Copyright (c) 2020 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura 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 -- NOTE: precedence must be at least `arg` to be used in `macro` without parentheses syntax:arg stx:max "+" : stx syntax:arg stx:max "*" : stx syntax:arg stx:max "?" : stx syntax:2 stx:2 " <|> " 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:arg x:stx:max ",*" : stx => `(stx| sepBy($x, ",", ", ")) macro:arg x:stx:max ",+" : stx => `(stx| sepBy1($x, ",", ", ")) /- Comma-separated sequence with optional trailing comma. -/ macro:arg x:stx:max ",*,?" : stx => `(stx| sepBy($x, ",", ", ", allowTrailingSep)) macro:arg x:stx:max ",+,?" : stx => `(stx| sepBy1($x, ",", ", ", allowTrailingSep)) macro:arg "!" x:stx:max : 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 infixl:65 " ++ " => HAppend.hAppend 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% HAppend.hAppend $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 /- 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_no_prop% 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 infixr:67 " :: " => List.cons syntax:20 term:21 " <|> " term:20 : term syntax:60 term:61 " >> " term:60 : term infixl:55 " >>= " => Bind.bind notation:60 a:60 " <*> " b:61 => Seq.seq a fun _ : Unit => b notation:60 a:60 " <* " b:61 => SeqLeft.seqLeft a fun _ : Unit => b notation:60 a:60 " *> " b:61 => SeqRight.seqRight a fun _ : Unit => b infixr:100 " <$> " => Functor.map macro_rules | `($x <|> $y) => `(binop_lazy% HOrElse.hOrElse $x $y) macro_rules | `($x >> $y) => `(binop_lazy% HAndThen.hAndThen $x $y) syntax (name := termDepIfThenElse) ppRealGroup(ppRealFill(ppIndent("if " ident " : " term " then") ppSpace term) ppDedent(ppSpace) ppRealFill("else " term)) : term macro_rules | `(if $h:ident : $c then $t:term else $e:term) => `(let_mvar% ?m := $c; wait_if_type_mvar% ?m; dite ?m (fun $h:ident => $t) (fun $h:ident => $e)) syntax (name := termIfThenElse) ppRealGroup(ppRealFill(ppIndent("if " term " then") ppSpace term) ppDedent(ppSpace) ppRealFill("else " term)) : term macro_rules | `(if $c then $t:term else $e:term) => `(let_mvar% ?m := $c; wait_if_type_mvar% ?m; ite ?m $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 -- Declare `this` as a keyword that unhygienically binds to a scope-less `this` assumption (or other binding). -- The keyword prevents declaring a `this` binding except through metapgrogramming, as is done by `have`/`show`. /-- Special identifier introduced by "anonymous" `have : ...`, `suffices p ...` etc. -/ macro tk:"this" : term => Syntax.ident tk.getHeadInfo "this".toSubstring `this [] namespace Parser.Tactic /-- Introduce one or more hypotheses, optionally naming and/or pattern-matching them. For each hypothesis to be introduced, the remaining main goal's target type must be a `let` or function type. * `intro` by itself introduces one anonymous hypothesis, which can be accessed by e.g. `assumption`. * `intro x y` introduces two hypotheses and names them. Individual hypotheses can be anonymized via `_`, or matched against a pattern: ```lean -- ... ⊢ α × β → ... intro (a, b) -- ..., a : α, b : β ⊢ ... ``` * Alternatively, `intro` can be combined with pattern matching much like `fun`: ```lean intro | n + 1, 0 => tac | ... ``` -/ syntax (name := intro) "intro " notFollowedBy("|") (colGt term:max)* : tactic /-- `intros x...` behaves like `intro x...`, but then keeps introducing (anonymous) hypotheses until goal is not of a function type. -/ syntax (name := intros) "intros " (colGt (ident <|> "_"))* : tactic /-- `rename t => x` renames the most recent hypothesis whose type matches `t` (which may contain placeholders) to `x`, or fails if no such hypothesis could be found. -/ syntax (name := rename) "rename " term " => " ident : tactic /-- `revert x...` is the inverse of `intro x...`: it moves the given hypotheses into the main goal's target type. -/ syntax (name := revert) "revert " (colGt term:max)+ : tactic /-- `clear x...` removes the given hypotheses, or fails if there are remaining references to a hypothesis. -/ syntax (name := clear) "clear " (colGt term:max)+ : tactic /-- `subst x...` substitutes each `x` with `e` in the goal if there is a hypothesis of type `x = e` or `e = x`. If `x` is itself a hypothesis of type `y = e` or `e = y`, `y` is substituted instead. -/ syntax (name := subst) "subst " (colGt term:max)+ : tactic /-- `assumption` tries to solve the main goal using a hypothesis of compatible type, or else fails. Note also the `‹t›` term notation, which is a shorthand for `show t by assumption`. -/ syntax (name := assumption) "assumption" : tactic /-- `contradiction` closes the main goal if its hypotheses are "trivially contradictory". ```lean example (h : False) : p := by contradiction -- inductive type/family with no applicable constructors example (h : none = some true) : p := by contradiction -- injectivity of constructors example (h : 2 + 2 = 3) : p := by contradiction -- decidable false proposition example (h : p) (h' : ¬ p) : q := by contradiction example (x : Nat) (h : x ≠ x) : p := by contradiction ``` -/ syntax (name := contradiction) "contradiction" : tactic /-- `apply e` tries to match the current goal against the conclusion of `e`'s type. If it succeeds, then the tactic returns as many subgoals as the number of premises that have not been fixed by type inference or type class resolution. Non-dependent premises are added before dependent ones. The `apply` tactic uses higher-order pattern matching, type class resolution, and first-order unification with dependent types. -/ syntax (name := apply) "apply " term : tactic /-- `exact e` closes the main goal if its target type matches that of `e`. -/ syntax (name := exact) "exact " term : tactic /-- `refine e` behaves like `exact e`, except that named (`?x`) or unnamed (`?_`) holes in `e` that are not solved by unification with the main goal's target type are converted into new goals, using the hole's name, if any, as the goal case name. -/ syntax (name := refine) "refine " term : tactic /-- `refine' e` behaves like `refine e`, except that unsolved placeholders (`_`) and implicit parameters are also converted into new goals. -/ syntax (name := refine') "refine' " term : tactic /-- If the main goal's target type is an inductive type, `constructor` solves it with the first matching constructor, or else fails. -/ syntax (name := constructor) "constructor" : tactic /-- `case tag => tac` focuses on the goal with case name `tag` and solves it using `tac`, or else fails. `case tag x₁ ... xₙ => tac` additionally renames the `n` most recent hypotheses with inaccessible names to the given names. -/ syntax (name := case) "case " (ident <|> "_") (ident <|> "_")* " => " tacticSeq : tactic /-- `next => tac` focuses on the next goal solves it using `tac`, or else fails. `next x₁ ... xₙ => tac` additionally renames the `n` most recent hypotheses with inaccessible names to the given names. -/ macro "next " args:(ident <|> "_")* " => " tac:tacticSeq : tactic => `(tactic| case _ $(args.getArgs)* => $tac) /-- `allGoals tac` runs `tac` on each goal, concatenating the resulting goals, if any. -/ syntax (name := allGoals) "all_goals " tacticSeq : tactic /-- `anyGoals tac` applies the tactic `tac` to every goal, and succeeds if at least one application succeeds. -/ syntax (name := anyGoals) "any_goals " tacticSeq : tactic /-- `focus tac` focuses on the main goal, suppressing all other goals, and runs `tac` on it. Usually `· tac`, which enforces that the goal is closed by `tac`, should be preferred. -/ syntax (name := focus) "focus " tacticSeq : tactic /-- `skip` does nothing. -/ syntax (name := skip) "skip" : tactic /-- `done` succeeds iff there are no remaining goals. -/ syntax (name := done) "done" : tactic syntax (name := traceState) "trace_state" : tactic syntax (name := failIfSuccess) "fail_if_success " tacticSeq : tactic syntax (name := paren) "(" tacticSeq ")" : tactic syntax (name := withReducible) "with_reducible " tacticSeq : tactic syntax (name := withReducibleAndInstances) "with_reducible_and_instances " tacticSeq : tactic /-- `first | tac | ...` runs each `tac` until one succeeds, or else fails. -/ syntax (name := first) "first " withPosition((group(colGe "|" tacticSeq))+) : tactic syntax (name := rotateLeft) "rotate_left" (num)? : tactic syntax (name := rotateRight) "rotate_right" (num)? : tactic /-- `try tac` runs `tac` and succeeds even if `tac` failed. -/ macro "try " t:tacticSeq : tactic => `(first | $t | skip) /-- `tac <;> tac'` runs `tac` on the main goal and `tac'` on each produced goal, concatenating all goals produced by `tac'`. -/ macro:1 x:tactic " <;> " y:tactic:0 : tactic => `(tactic| focus ($x:tactic; all_goals $y:tactic)) /-- `rfl` is a shorthand for `exact rfl`. -/ macro "rfl" : tactic => `(exact rfl) /-- `admit` is a shorthand for `exact sorry`. -/ macro "admit" : tactic => `(exact sorry) /-- The `sorry` tactic is a shorthand for `exact sorry`. -/ macro "sorry" : tactic => `(exact sorry) macro "infer_instance" : tactic => `(exact inferInstance) /-- Optional configuration option for tactics -/ syntax config := atomic("(" &"config") " := " term ")" syntax locationWildcard := "*" syntax locationHyp := (colGt term:max)+ ("⊢" <|> "|-")? 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 " (config)? rwRuleSeq (location)? : tactic syntax (name := rwSeq) "rw " (config)? rwRuleSeq (location)? : tactic def rwWithRfl (kind : SyntaxNodeKind) (atom : String) (stx : Syntax) : MacroM Syntax := do -- We show the `rfl` state on `]` let seq := stx[2] 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 2 seq `(tactic| $tac; try (with_reducible rfl%$rbrak)) @[macro rwSeq] def expandRwSeq : Macro := rwWithRfl ``Lean.Parser.Tactic.rewriteSeq "rewrite" syntax (name := injection) "injection " term (" with " (colGt (ident <|> "_"))+)? : tactic syntax (name := injections) "injections" : tactic syntax discharger := atomic("(" (&"discharger" <|> &"disch")) " := " tacticSeq ")" syntax simpPre := "↓" syntax simpPost := "↑" syntax simpLemma := (simpPre <|> simpPost)? ("← " <|> "<- ")? term syntax simpErase := "-" term:max syntax simpStar := "*" syntax (name := simp) "simp " (config)? (discharger)? (&"only ")? ("[" (simpStar <|> simpErase <|> simpLemma),* "]")? (location)? : tactic syntax (name := simpAll) "simp_all " (config)? (discharger)? (&"only ")? ("[" (simpErase <|> simpLemma),* "]")? : tactic /-- Delta expand the given definition. This is a low-level tactic, it will expose how recursive definitions have been compiled by Lean. -/ syntax (name := delta) "delta " ident (location)? : tactic -- Auxiliary macro for lifting have/suffices/let/... -- It makes sure the "continuation" `?_` is the main goal after refining macro "refine_lift " e:term : tactic => `(focus (refine no_implicit_lambda% $e; rotate_right)) macro "have " d:haveDecl : tactic => `(refine_lift 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 => `(refine_lift suffices $d:sufficesDecl; ?_) macro "let " d:letDecl : tactic => `(refine_lift let $d:letDecl; ?_) macro "show " e:term : tactic => `(refine_lift show $e:term from ?_) syntax (name := letrec) withPosition(atomic(group("let " &"rec ")) letRecDecls) : tactic macro_rules | `(tactic| let rec $d:letRecDecls) => `(tactic| refine_lift let rec $d:letRecDecls; ?_) -- Similar to `refineLift`, but using `refine'` macro "refine_lift' " e:term : tactic => `(focus (refine' no_implicit_lambda% $e; rotate_right)) macro "have' " d:haveDecl : tactic => `(refine_lift' have $d:haveDecl; ?_) macro (priority := high) "have'" x:ident " := " p:term : tactic => `(have' $x:ident : _ := $p) macro "let' " d:letDecl : tactic => `(refine_lift' let $d:letDecl; ?_) syntax inductionAlt := ppDedent(ppLine) "| " (group("@"? ident) <|> "_") (ident <|> "_")* " => " (hole <|> syntheticHole <|> tacticSeq) syntax inductionAlts := "with " (tactic)? withPosition( (colGe inductionAlt)+) syntax (name := induction) "induction " term,+ (" using " ident)? ("generalizing " term:max+)? (inductionAlts)? : tactic syntax generalizeArg := atomic(ident " : ")? term:51 " = " ident /-- `generalize ([h :] e = x),+` replaces all occurrences `e`s in the main goal with a fresh hypothesis `x`s. If `h` is given, `h : e = x` is introduced as well. -/ syntax (name := generalize) "generalize " generalizeArg,+ : tactic syntax casesTarget := atomic(ident " : ")? term syntax (name := cases) "cases " casesTarget,+ (" using " ident)? (inductionAlts)? : tactic syntax (name := existsIntro) "exists " term : tactic /-- `rename_i x_1 ... x_n` renames the last `n` inaccessible names using the given names. -/ syntax (name := renameI) "rename_i " (colGt (ident <|> "_"))+ : tactic syntax "repeat " tacticSeq : tactic macro_rules | `(tactic| repeat $seq) => `(tactic| first | ($seq); repeat $seq | skip) syntax "trivial" : tactic syntax (name := split) "split " (colGt term)? (location)? : tactic /-- The tactic `specialize h a₁ ... aₙ` works on local hypothesis `h`. The premises of this hypothesis, either universal quantifications or non-dependent implications, are instantiated by concrete terms coming either from arguments `a₁` ... `aₙ`. The tactic adds a new hypothesis with the same name `h := h a₁ ... aₙ` and tries to clear the previous one. -/ syntax (name := specialize) "specialize " term : 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))
97c08a2dfd89128c9302d7d47ab58357c95dcd0b
d9d511f37a523cd7659d6f573f990e2a0af93c6f
/src/meta/expr.lean
cfad27888d488b4a67fef117d3d2f908ec8e5399
[ "Apache-2.0" ]
permissive
hikari0108/mathlib
b7ea2b7350497ab1a0b87a09d093ecc025a50dfa
a9e7d333b0cfd45f13a20f7b96b7d52e19fa2901
refs/heads/master
1,690,483,608,260
1,631,541,580,000
1,631,541,580,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
46,711
lean
/- Copyright (c) 2019 Robert Y. Lewis. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Simon Hudon, Scott Morrison, Keeley Hoek, Robert Y. Lewis, Floris van Doorn -/ import data.string.defs import meta.rb_map import tactic.derive_inhabited /-! # Additional operations on expr and related types This file defines basic operations on the types expr, name, declaration, level, environment. This file is mostly for non-tactics. Tactics should generally be placed in `tactic.core`. ## Tags expr, name, declaration, level, environment, meta, metaprogramming, tactic -/ attribute [derive has_reflect, derive decidable_eq] binder_info congr_arg_kind @[priority 100] meta instance has_reflect.has_to_pexpr {α} [has_reflect α] : has_to_pexpr α := ⟨λ b, pexpr.of_expr (reflect b)⟩ namespace binder_info /-! ### Declarations about `binder_info` -/ instance : inhabited binder_info := ⟨ binder_info.default ⟩ /-- The brackets corresponding to a given binder_info. -/ def brackets : binder_info → string × string | binder_info.implicit := ("{", "}") | binder_info.strict_implicit := ("{{", "}}") | binder_info.inst_implicit := ("[", "]") | _ := ("(", ")") end binder_info namespace name /-! ### Declarations about `name` -/ /-- Find the largest prefix `n` of a `name` such that `f n ≠ none`, then replace this prefix with the value of `f n`. -/ def map_prefix (f : name → option name) : name → name | anonymous := anonymous | (mk_string s n') := (f (mk_string s n')).get_or_else (mk_string s $ map_prefix n') | (mk_numeral d n') := (f (mk_numeral d n')).get_or_else (mk_numeral d $ map_prefix n') /-- If `nm` is a simple name (having only one string component) starting with `_`, then `deinternalize_field nm` removes the underscore. Otherwise, it does nothing. -/ meta def deinternalize_field : name → name | (mk_string s name.anonymous) := let i := s.mk_iterator in if i.curr = '_' then i.next.next_to_string else s | n := n /-- `get_nth_prefix nm n` removes the last `n` components from `nm` -/ meta def get_nth_prefix : name → ℕ → name | nm 0 := nm | nm (n + 1) := get_nth_prefix nm.get_prefix n /-- Auxiliary definition for `pop_nth_prefix` -/ private meta def pop_nth_prefix_aux : name → ℕ → name × ℕ | anonymous n := (anonymous, 1) | nm n := let (pfx, height) := pop_nth_prefix_aux nm.get_prefix n in if height ≤ n then (anonymous, height + 1) else (nm.update_prefix pfx, height + 1) /-- Pops the top `n` prefixes from the given name. -/ meta def pop_nth_prefix (nm : name) (n : ℕ) : name := prod.fst $ pop_nth_prefix_aux nm n /-- Pop the prefix of a name -/ meta def pop_prefix (n : name) : name := pop_nth_prefix n 1 /-- Auxiliary definition for `from_components` -/ private def from_components_aux : name → list string → name | n [] := n | n (s :: rest) := from_components_aux (name.mk_string s n) rest /-- Build a name from components. For example `from_components ["foo","bar"]` becomes ``` `foo.bar``` -/ def from_components : list string → name := from_components_aux name.anonymous /-- `name`s can contain numeral pieces, which are not legal names when typed/passed directly to the parser. We turn an arbitrary name into a legal identifier name by turning the numbers to strings. -/ meta def sanitize_name : name → name | name.anonymous := name.anonymous | (name.mk_string s p) := name.mk_string s $ sanitize_name p | (name.mk_numeral s p) := name.mk_string sformat!"n{s}" $ sanitize_name p /-- Append a string to the last component of a name. -/ def append_suffix : name → string → name | (mk_string s n) s' := mk_string (s ++ s') n | n _ := n /-- Update the last component of a name. -/ def update_last (f : string → string) : name → name | (mk_string s n) := mk_string (f s) n | n := n /-- `append_to_last nm s is_prefix` adds `s` to the last component of `nm`, either as prefix or as suffix (specified by `is_prefix`), separated by `_`. Used by `simps_add_projections`. -/ def append_to_last (nm : name) (s : string) (is_prefix : bool) : name := nm.update_last $ λ s', if is_prefix then s ++ "_" ++ s' else s' ++ "_" ++ s /-- The first component of a name, turning a number to a string -/ meta def head : name → string | (mk_string s anonymous) := s | (mk_string s p) := head p | (mk_numeral n p) := head p | anonymous := "[anonymous]" /-- Tests whether the first component of a name is `"_private"` -/ meta def is_private (n : name) : bool := n.head = "_private" /-- Get the last component of a name, and convert it to a string. -/ meta def last : name → string | (mk_string s _) := s | (mk_numeral n _) := repr n | anonymous := "[anonymous]" /-- Returns the number of characters used to print all the string components of a name, including periods between name segments. Ignores numerical parts of a name. -/ meta def length : name → ℕ | (mk_string s anonymous) := s.length | (mk_string s p) := s.length + 1 + p.length | (mk_numeral n p) := p.length | anonymous := "[anonymous]".length /-- Checks whether `nm` has a prefix (including itself) such that P is true -/ def has_prefix (P : name → bool) : name → bool | anonymous := ff | (mk_string s nm) := P (mk_string s nm) ∨ has_prefix nm | (mk_numeral s nm) := P (mk_numeral s nm) ∨ has_prefix nm /-- Appends `'` to the end of a name. -/ meta def add_prime : name → name | (name.mk_string s p) := name.mk_string (s ++ "'") p | n := (name.mk_string "x'" n) /-- `last_string n` returns the rightmost component of `n`, ignoring numeral components. For example, ``last_string `a.b.c.33`` will return `` `c ``. -/ def last_string : name → string | anonymous := "[anonymous]" | (mk_string s _) := s | (mk_numeral _ n) := last_string n /-- Constructs a (non-simple) name from a string. Example: ``name.from_string "foo.bar" = `foo.bar`` -/ meta def from_string (s : string) : name := from_components $ s.split (= '.') /-- In surface Lean, we can write anonymous Π binders (i.e. binders where the argument is not named) using the function arrow notation: ```lean inductive test : Type | intro : unit → test ``` After elaboration, however, every binder must have a name, so Lean generates one. In the example, the binder in the type of `intro` is anonymous, so Lean gives it the name `ᾰ`: ```lean test.intro : ∀ (ᾰ : unit), test ``` When there are multiple anonymous binders, they are named `ᾰ_1`, `ᾰ_2` etc. Thus, when we want to know whether the user named a binder, we can check whether the name follows this scheme. Note, however, that this is not reliable. When the user writes (for whatever reason) ```lean inductive test : Type | intro : ∀ (ᾰ : unit), test ``` we cannot tell that the binder was, in fact, named. The function `name.is_likely_generated_binder_name` checks if a name is of the form `ᾰ`, `ᾰ_1`, etc. -/ library_note "likely generated binder names" /-- Check whether a simple name was likely generated by Lean to name an anonymous binder. Such names are either `ᾰ` or `ᾰ_n` for some natural `n`. See note [likely generated binder names]. -/ meta def is_likely_generated_binder_simple_name : string → bool | "ᾰ" := tt | n := match n.get_rest "ᾰ_" with | none := ff | some suffix := suffix.is_nat end /-- Check whether a name was likely generated by Lean to name an anonymous binder. Such names are either `ᾰ` or `ᾰ_n` for some natural `n`. See note [likely generated binder names]. -/ meta def is_likely_generated_binder_name (n : name) : bool := match n with | mk_string s anonymous := is_likely_generated_binder_simple_name s | _ := ff end end name namespace level /-! ### Declarations about `level` -/ /-- Tests whether a universe level is non-zero for all assignments of its variables -/ meta def nonzero : level → bool | (succ _) := tt | (max l₁ l₂) := l₁.nonzero || l₂.nonzero | (imax _ l₂) := l₂.nonzero | _ := ff /-- `l.fold_mvar f` folds a function `f : name → α → α` over each `n : name` appearing in a `level.mvar n` in `l`. -/ meta def fold_mvar {α} : level → (name → α → α) → α → α | zero f := id | (succ a) f := fold_mvar a f | (param a) f := id | (mvar a) f := f a | (max a b) f := fold_mvar a f ∘ fold_mvar b f | (imax a b) f := fold_mvar a f ∘ fold_mvar b f /-- `l.params` is the set of parameters occuring in `l`. For example if `l = max 1 (max (u+1) (max v w))` then `l.params = {u, v, w}`. -/ protected meta def params (u : level) : name_set := u.fold mk_name_set $ λ v l, match v with | (param nm) := l.insert nm | _ := l end end level /-! ### Declarations about `binder` -/ /-- The type of binders containing a name, the binding info and the binding type -/ @[derive decidable_eq, derive inhabited] meta structure binder := (name : name) (info : binder_info) (type : expr) namespace binder /-- Turn a binder into a string. Uses expr.to_string for the type. -/ protected meta def to_string (b : binder) : string := let (l, r) := b.info.brackets in l ++ b.name.to_string ++ " : " ++ b.type.to_string ++ r open tactic meta instance : has_to_string binder := ⟨ binder.to_string ⟩ meta instance : has_to_format binder := ⟨ λ b, b.to_string ⟩ meta instance : has_to_tactic_format binder := ⟨ λ b, let (l, r) := b.info.brackets in (λ e, l ++ b.name.to_string ++ " : " ++ e ++ r) <$> pp b.type ⟩ end binder /-! ### Converting between expressions and numerals There are a number of ways to convert between expressions and numerals, depending on the input and output types and whether you want to infer the necessary type classes. See also the tactics `expr.of_nat`, `expr.of_int`, `expr.of_rat`. -/ /-- `nat.mk_numeral n` embeds `n` as a numeral expression inside a type with 0, 1, and +. `type`: an expression representing the target type. This must live in Type 0. `has_zero`, `has_one`, `has_add`: expressions of the type `has_zero %%type`, etc. -/ meta def nat.mk_numeral (type has_zero has_one has_add : expr) : ℕ → expr := let z : expr := `(@has_zero.zero.{0} %%type %%has_zero), o : expr := `(@has_one.one.{0} %%type %%has_one) in nat.binary_rec z (λ b n e, if n = 0 then o else if b then `(@bit1.{0} %%type %%has_one %%has_add %%e) else `(@bit0.{0} %%type %%has_add %%e)) /-- `int.mk_numeral z` embeds `z` as a numeral expression inside a type with 0, 1, +, and -. `type`: an expression representing the target type. This must live in Type 0. `has_zero`, `has_one`, `has_add`, `has_neg`: expressions of the type `has_zero %%type`, etc. -/ meta def int.mk_numeral (type has_zero has_one has_add has_neg : expr) : ℤ → expr | (int.of_nat n) := n.mk_numeral type has_zero has_one has_add | -[1+n] := let ne := (n+1).mk_numeral type has_zero has_one has_add in `(@has_neg.neg.{0} %%type %%has_neg %%ne) /-- `nat.to_pexpr n` creates a `pexpr` that will evaluate to `n`. The `pexpr` does not hold any typing information: `to_expr ``((%%(nat.to_pexpr 5) : ℤ))` will create a native integer numeral `(5 : ℤ)`. -/ meta def nat.to_pexpr : ℕ → pexpr | 0 := ``(0) | 1 := ``(1) | n := if n % 2 = 0 then ``(bit0 %%(nat.to_pexpr (n/2))) else ``(bit1 %%(nat.to_pexpr (n/2))) namespace expr /-- Turns an expression into a natural number, assuming it is only built up from `has_one.one`, `bit0`, `bit1`, `has_zero.zero`, `nat.zero`, and `nat.succ`. -/ protected meta def to_nat : expr → option ℕ | `(has_zero.zero) := some 0 | `(has_one.one) := some 1 | `(bit0 %%e) := bit0 <$> e.to_nat | `(bit1 %%e) := bit1 <$> e.to_nat | `(nat.succ %%e) := (+1) <$> e.to_nat | `(nat.zero) := some 0 | _ := none /-- Turns an expression into a integer, assuming it is only built up from `has_one.one`, `bit0`, `bit1`, `has_zero.zero` and a optionally a single `has_neg.neg` as head. -/ protected meta def to_int : expr → option ℤ | `(has_neg.neg %%e) := do n ← e.to_nat, some (-n) | e := coe <$> e.to_nat /-- Turns an expression into a list, assuming it is only built up from `list.nil` and `list.cons`. -/ protected meta def to_list {α} (f : expr → option α) : expr → option (list α) | `(list.nil) := some [] | `(list.cons %%x %%l) := list.cons <$> f x <*> l.to_list | _ := none /-- `is_num_eq n1 n2` returns true if `n1` and `n2` are both numerals with the same numeral structure, ignoring differences in type and type class arguments. -/ meta def is_num_eq : expr → expr → bool | `(@has_zero.zero _ _) `(@has_zero.zero _ _) := tt | `(@has_one.one _ _) `(@has_one.one _ _) := tt | `(bit0 %%a) `(bit0 %%b) := a.is_num_eq b | `(bit1 %%a) `(bit1 %%b) := a.is_num_eq b | `(-%%a) `(-%%b) := a.is_num_eq b | `(%%a/%%a') `(%%b/%%b') := a.is_num_eq b | _ _ := ff end expr /-! ### Declarations about `expr` -/ namespace expr open tactic /-- List of names removed by `clean`. All these names must resolve to functions defeq `id`. -/ meta def clean_ids : list name := [``id, ``id_rhs, ``id_delta, ``hidden] /-- Clean an expression by removing `id`s listed in `clean_ids`. -/ meta def clean (e : expr) : expr := e.replace (λ e n, match e with | (app (app (const n _) _) e') := if n ∈ clean_ids then some e' else none | (app (lam _ _ _ (var 0)) e') := some e' | _ := none end) /-- `replace_with e s s'` replaces ocurrences of `s` with `s'` in `e`. -/ meta def replace_with (e : expr) (s : expr) (s' : expr) : expr := e.replace $ λc d, if c = s then some (s'.lift_vars 0 d) else none /-- Implementation of `expr.mreplace`. -/ meta def mreplace_aux {m : Type* → Type*} [monad m] (R : expr → nat → m (option expr)) : expr → ℕ → m expr | (app f x) n := option.mget_or_else (R (app f x) n) (do Rf ← mreplace_aux f n, Rx ← mreplace_aux x n, return $ app Rf Rx) | (lam nm bi ty bd) n := option.mget_or_else (R (lam nm bi ty bd) n) (do Rty ← mreplace_aux ty n, Rbd ← mreplace_aux bd (n+1), return $ lam nm bi Rty Rbd) | (pi nm bi ty bd) n := option.mget_or_else (R (pi nm bi ty bd) n) (do Rty ← mreplace_aux ty n, Rbd ← mreplace_aux bd (n+1), return $ pi nm bi Rty Rbd) | (elet nm ty a b) n := option.mget_or_else (R (elet nm ty a b) n) (do Rty ← mreplace_aux ty n, Ra ← mreplace_aux a n, Rb ← mreplace_aux b n, return $ elet nm Rty Ra Rb) | (macro c es) n := option.mget_or_else (R (macro c es) n) $ macro c <$> es.mmap (λ e, mreplace_aux e n) | e n := option.mget_or_else (R e n) (return e) /-- Monadic analogue of `expr.replace`. The `mreplace R e` visits each subexpression `s` of `e`, and is called with `R s n`, where `n` is the number of binders above `e`. If `R s n` fails, the whole replacement fails. If `R s n` returns `some t`, `s` is replaced with `t` (and `mreplace` does not visit its subexpressions). If `R s n` return `none`, then `mreplace` continues visiting subexpressions of `s`. WARNING: This function performs exponentially worse on large terms than `expr.replace`, if a subexpression occurs more than once in an expression, `expr.replace` visits them only once, but this function will visit every occurence of it. Do not use this on large expressions. -/ meta def mreplace {m : Type* → Type*} [monad m] (R : expr → nat → m (option expr)) (e : expr) : m expr := mreplace_aux R e 0 /-- Match a variable. -/ meta def match_var {elab} : expr elab → option ℕ | (var n) := some n | _ := none /-- Match a sort. -/ meta def match_sort {elab} : expr elab → option level | (sort u) := some u | _ := none /-- Match a constant. -/ meta def match_const {elab} : expr elab → option (name × list level) | (const n lvls) := some (n, lvls) | _ := none /-- Match a metavariable. -/ meta def match_mvar {elab} : expr elab → option (name × name × expr elab) | (mvar unique pretty type) := some (unique, pretty, type) | _ := none /-- Match a local constant. -/ meta def match_local_const {elab} : expr elab → option (name × name × binder_info × expr elab) | (local_const unique pretty bi type) := some (unique, pretty, bi, type) | _ := none /-- Match an application. -/ meta def match_app {elab} : expr elab → option (expr elab × expr elab) | (app t u) := some (t, u) | _ := none /-- Match an application of `coe_fn`. -/ meta def match_app_coe_fn : expr → option (expr × expr × expr × expr) | (app `(@coe_fn %%α %%inst %%fexpr) x) := some (α, inst, fexpr, x) | _ := none /-- Match an abstraction. -/ meta def match_lam {elab} : expr elab → option (name × binder_info × expr elab × expr elab) | (lam var_name bi type body) := some (var_name, bi, type, body) | _ := none /-- Match a Π type. -/ meta def match_pi {elab} : expr elab → option (name × binder_info × expr elab × expr elab) | (pi var_name bi type body) := some (var_name, bi, type, body) | _ := none /-- Match a let. -/ meta def match_elet {elab} : expr elab → option (name × expr elab × expr elab × expr elab) | (elet var_name type assignment body) := some (var_name, type, assignment, body) | _ := none /-- Match a macro. -/ meta def match_macro {elab} : expr elab → option (macro_def × list (expr elab)) | (macro df args) := some (df, args) | _ := none /-- Tests whether an expression is a meta-variable. -/ meta def is_mvar : expr → bool | (mvar _ _ _) := tt | _ := ff /-- Tests whether an expression is a sort. -/ meta def is_sort : expr → bool | (sort _) := tt | e := ff /-- Get the universe levels of a `const` expression -/ meta def univ_levels : expr → list level | (const n ls) := ls | _ := [] /-- Replace any metavariables in the expression with underscores, in preparation for printing `refine ...` statements. -/ meta def replace_mvars (e : expr) : expr := e.replace (λ e' _, if e'.is_mvar then some (unchecked_cast pexpr.mk_placeholder) else none) /-- If `e` is a local constant, `to_implicit_local_const e` changes the binder info of `e` to `implicit`. See also `to_implicit_binder`, which also changes lambdas and pis. -/ meta def to_implicit_local_const : expr → expr | (expr.local_const uniq n bi t) := expr.local_const uniq n binder_info.implicit t | e := e /-- If `e` is a local constant, lamda, or pi expression, `to_implicit_binder e` changes the binder info of `e` to `implicit`. See also `to_implicit_local_const`, which only changes local constants. -/ meta def to_implicit_binder : expr → expr | (local_const n₁ n₂ _ d) := local_const n₁ n₂ binder_info.implicit d | (lam n _ d b) := lam n binder_info.implicit d b | (pi n _ d b) := pi n binder_info.implicit d b | e := e /-- Returns a list of all local constants in an expression (without duplicates). -/ meta def list_local_consts (e : expr) : list expr := e.fold [] (λ e' _ es, if e'.is_local_constant then insert e' es else es) /-- Returns the set of all local constants in an expression. -/ meta def list_local_consts' (e : expr) : expr_set := e.fold mk_expr_set (λ e' _ es, if e'.is_local_constant then es.insert e' else es) /-- Returns the unique names of all local constants in an expression. -/ meta def list_local_const_unique_names (e : expr) : name_set := e.fold mk_name_set (λ e' _ es, if e'.is_local_constant then es.insert e'.local_uniq_name else es) /-- Returns a name_set of all constants in an expression. -/ meta def list_constant (e : expr) : name_set := e.fold mk_name_set (λ e' _ es, if e'.is_constant then es.insert e'.const_name else es) /-- Returns a list of all meta-variables in an expression (without duplicates). -/ meta def list_meta_vars (e : expr) : list expr := e.fold [] (λ e' _ es, if e'.is_mvar then insert e' es else es) /-- Returns the set of all meta-variables in an expression. -/ meta def list_meta_vars' (e : expr) : expr_set := e.fold mk_expr_set (λ e' _ es, if e'.is_mvar then es.insert e' else es) /-- Returns a list of all universe meta-variables in an expression (without duplicates). -/ meta def list_univ_meta_vars (e : expr) : list name := native.rb_set.to_list $ e.fold native.mk_rb_set $ λ e' i s, match e' with | (sort u) := u.fold_mvar (flip native.rb_set.insert) s | (const _ ls) := ls.foldl (λ s' l, l.fold_mvar (flip native.rb_set.insert) s') s | _ := s end /-- Test `t` contains the specified subexpression `e`, or a metavariable. This represents the notion that `e` "may occur" in `t`, possibly after subsequent unification. -/ meta def contains_expr_or_mvar (t : expr) (e : expr) : bool := -- We can't use `t.has_meta_var` here, as that detects universe metavariables, too. ¬ t.list_meta_vars.empty ∨ e.occurs t /-- Returns a name_set of all constants in an expression starting with a certain prefix. -/ meta def list_names_with_prefix (pre : name) (e : expr) : name_set := e.fold mk_name_set $ λ e' _ l, match e' with | expr.const n _ := if n.get_prefix = pre then l.insert n else l | _ := l end /-- Returns true if `e` contains a name `n` where `p n` is true. Returns `true` if `p name.anonymous` is true. -/ meta def contains_constant (e : expr) (p : name → Prop) [decidable_pred p] : bool := e.fold ff (λ e' _ b, if p (e'.const_name) then tt else b) /-- Returns true if `e` contains a `sorry`. -/ meta def contains_sorry (e : expr) : bool := e.fold ff (λ e' _ b, if (is_sorry e').is_some then tt else b) /-- `app_symbol_in e l` returns true iff `e` is an application of a constant whose name is in `l`. -/ meta def app_symbol_in (e : expr) (l : list name) : bool := match e.get_app_fn with | (expr.const n _) := n ∈ l | _ := ff end /-- `get_simp_args e` returns the arguments of `e` that simp can reach via congruence lemmas. -/ meta def get_simp_args (e : expr) : tactic (list expr) := -- `mk_specialized_congr_lemma_simp` throws an assertion violation if its argument is not an app if ¬ e.is_app then pure [] else do cgr ← mk_specialized_congr_lemma_simp e, pure $ do (arg_kind, arg) ← cgr.arg_kinds.zip e.get_app_args, guard $ arg_kind = congr_arg_kind.eq, pure arg /-- Simplifies the expression `t` with the specified options. The result is `(new_e, pr)` with the new expression `new_e` and a proof `pr : e = new_e`. -/ meta def simp (t : expr) (cfg : simp_config := {}) (discharger : tactic unit := failed) (no_defaults := ff) (attr_names : list name := []) (hs : list simp_arg_type := []) : tactic (expr × expr × name_set) := do (s, to_unfold) ← mk_simp_set no_defaults attr_names hs, simplify s to_unfold t cfg `eq discharger /-- Definitionally simplifies the expression `t` with the specified options. The result is the simplified expression. -/ meta def dsimp (t : expr) (cfg : dsimp_config := {}) (no_defaults := ff) (attr_names : list name := []) (hs : list simp_arg_type := []) : tactic expr := do (s, to_unfold) ← mk_simp_set no_defaults attr_names hs, s.dsimplify to_unfold t cfg /-- Get the names of the bound variables by a sequence of pis or lambdas. -/ meta def binding_names : expr → list name | (pi n _ _ e) := n :: e.binding_names | (lam n _ _ e) := n :: e.binding_names | e := [] /-- head-reduce a single let expression -/ meta def reduce_let : expr → expr | (elet _ _ v b) := b.instantiate_var v | e := e /-- head-reduce all let expressions -/ meta def reduce_lets : expr → expr | (elet _ _ v b) := reduce_lets $ b.instantiate_var v | e := e /-- Instantiate lambdas in the second argument by expressions from the first. -/ meta def instantiate_lambdas : list expr → expr → expr | (e'::es) (lam n bi t e) := instantiate_lambdas es (e.instantiate_var e') | _ e := e /-- Repeatedly apply `expr.subst`. -/ meta def substs : expr → list expr → expr | e es := es.foldl expr.subst e /-- `instantiate_lambdas_or_apps es e` instantiates lambdas in `e` by expressions from `es`. If the length of `es` is larger than the number of lambdas in `e`, then the term is applied to the remaining terms. Also reduces head let-expressions in `e`, including those after instantiating all lambdas. This is very similar to `expr.substs`, but this also reduces head let-expressions. -/ meta def instantiate_lambdas_or_apps : list expr → expr → expr | (v::es) (lam n bi t b) := instantiate_lambdas_or_apps es $ b.instantiate_var v | es (elet _ _ v b) := instantiate_lambdas_or_apps es $ b.instantiate_var v | es e := mk_app e es /-- Some declarations work with open expressions, i.e. an expr that has free variables. Terms will free variables are not well-typed, and one should not use them in tactics like `infer_type` or `unify`. You can still do syntactic analysis/manipulation on them. The reason for working with open types is for performance: instantiating variables requires iterating through the expression. In one performance test `pi_binders` was more than 6x quicker than `mk_local_pis` (when applied to the type of all imported declarations 100x). -/ library_note "open expressions" /-- Get the codomain/target of a pi-type. This definition doesn't instantiate bound variables, and therefore produces a term that is open. See note [open expressions]. -/ meta def pi_codomain : expr → expr | (pi n bi d b) := pi_codomain b | e := e /-- Get the body/value of a lambda-expression. This definition doesn't instantiate bound variables, and therefore produces a term that is open. See note [open expressions]. -/ meta def lambda_body : expr → expr | (lam n bi d b) := lambda_body b | e := e /-- Auxiliary defintion for `pi_binders`. See note [open expressions]. -/ meta def pi_binders_aux : list binder → expr → list binder × expr | es (pi n bi d b) := pi_binders_aux (⟨n, bi, d⟩::es) b | es e := (es, e) /-- Get the binders and codomain of a pi-type. This definition doesn't instantiate bound variables, and therefore produces a term that is open. The.tactic `get_pi_binders` in `tactic.core` does the same, but also instantiates the free variables. See note [open expressions]. -/ meta def pi_binders (e : expr) : list binder × expr := let (es, e) := pi_binders_aux [] e in (es.reverse, e) /-- Auxiliary defintion for `get_app_fn_args`. -/ meta def get_app_fn_args_aux : list expr → expr → expr × list expr | r (app f a) := get_app_fn_args_aux (a::r) f | r e := (e, r) /-- A combination of `get_app_fn` and `get_app_args`: lists both the function and its arguments of an application -/ meta def get_app_fn_args : expr → expr × list expr := get_app_fn_args_aux [] /-- `drop_pis es e` instantiates the pis in `e` with the expressions from `es`. -/ meta def drop_pis : list expr → expr → tactic expr | (v :: vs) (pi n bi d b) := do t ← infer_type v, guard (t =ₐ d), drop_pis vs (b.instantiate_var v) | [] e := return e | _ _ := failed /-- `instantiate_pis es e` instantiates the pis in `e` with the expressions from `es`. Does not check whether the result remains type-correct. -/ meta def instantiate_pis : list expr → expr → expr | (v :: vs) (pi n bi d b) := instantiate_pis vs (b.instantiate_var v) | _ e := e /-- `mk_op_lst op empty [x1, x2, ...]` is defined as `op x1 (op x2 ...)`. Returns `empty` if the list is empty. -/ meta def mk_op_lst (op : expr) (empty : expr) : list expr → expr | [] := empty | [e] := e | (e :: es) := op e $ mk_op_lst es /-- `mk_and_lst [x1, x2, ...]` is defined as `x1 ∧ (x2 ∧ ...)`, or `true` if the list is empty. -/ meta def mk_and_lst : list expr → expr := mk_op_lst `(and) `(true) /-- `mk_or_lst [x1, x2, ...]` is defined as `x1 ∨ (x2 ∨ ...)`, or `false` if the list is empty. -/ meta def mk_or_lst : list expr → expr := mk_op_lst `(or) `(false) /-- `local_binding_info e` returns the binding info of `e` if `e` is a local constant. Otherwise returns `binder_info.default`. -/ meta def local_binding_info : expr → binder_info | (expr.local_const _ _ bi _) := bi | _ := binder_info.default /-- `is_default_local e` tests whether `e` is a local constant with binder info `binder_info.default` -/ meta def is_default_local : expr → bool | (expr.local_const _ _ binder_info.default _) := tt | _ := ff /-- `has_local_constant e l` checks whether local constant `l` occurs in expression `e` -/ meta def has_local_constant (e l : expr) : bool := e.has_local_in $ mk_name_set.insert l.local_uniq_name /-- Turns a local constant into a binder -/ meta def to_binder : expr → binder | (local_const _ nm bi t) := ⟨nm, bi, t⟩ | _ := default binder /-- Strip-away the context-dependent unique id for the given local const and return: its friendly `name`, its `binder_info`, and its `type : expr`. -/ meta def get_local_const_kind : expr → name × binder_info × expr | (expr.local_const _ n bi e) := (n, bi, e) | _ := (name.anonymous, binder_info.default, expr.const name.anonymous []) /-- `local_const_set_type e t` sets the type of `e` to `t`, if `e` is a `local_const`. -/ meta def local_const_set_type {elab : bool} : expr elab → expr elab → expr elab | (expr.local_const x n bi t) new_t := expr.local_const x n bi new_t | e new_t := e /-- `unsafe_cast e` freely changes the `elab : bool` parameter of the passed `expr`. Mainly used to access core `expr` manipulation functions for `pexpr`-based use, but which are restricted to `expr tt` at the site of definition unnecessarily. DANGER: Unless you know exactly what you are doing, this is probably not the function you are looking for. For `pexpr → expr` see `tactic.to_expr`. For `expr → pexpr` see `to_pexpr`. -/ meta def unsafe_cast {elab₁ elab₂ : bool} : expr elab₁ → expr elab₂ := unchecked_cast /-- `replace_subexprs e mappings` takes an `e : expr` and interprets a `list (expr × expr)` as a collection of rules for variable replacements. A pair `(f, t)` encodes a rule which says "whenever `f` is encountered in `e` verbatim, replace it with `t`". -/ meta def replace_subexprs {elab : bool} (e : expr elab) (mappings : list (expr × expr)) : expr elab := unsafe_cast $ e.unsafe_cast.replace $ λ e n, (mappings.filter $ λ ent : expr × expr, ent.1 = e).head'.map prod.snd /-- `is_implicitly_included_variable e vs` accepts `e`, an `expr.local_const`, and a list `vs` of other `expr.local_const`s. It determines whether `e` should be considered "available in context" as a variable by virtue of the fact that the variables `vs` have been deemed such. For example, given `variables (n : ℕ) [prime n] [ih : even n]`, a reference to `n` implies that the typeclass instance `prime n` should be included, but `ih : even n` should not. DANGER: It is possible that for `f : expr` another `expr.local_const`, we have `is_implicitly_included_variable f vs = ff` but `is_implicitly_included_variable f (e :: vs) = tt`. This means that one usually wants to iteratively add a list of local constants (usually, the `variables` declared in the local scope) which satisfy `is_implicitly_included_variable` to an initial `vs`, repeating if any variables were added in a particular iteration. The function `all_implicitly_included_variables` below implements this behaviour. Note that if `e ∈ vs` then `is_implicitly_included_variable e vs = tt`. -/ meta def is_implicitly_included_variable (e : expr) (vs : list expr) : bool := if ¬(e.local_pp_name.to_string.starts_with "_") then e ∈ vs else e.local_type.fold tt $ λ se _ b, if ¬b then ff else if ¬se.is_local_constant then tt else se ∈ vs /-- Private work function for `all_implicitly_included_variables`, performing the actual series of iterations, tracking with a boolean whether any updates occured this iteration. -/ private meta def all_implicitly_included_variables_aux : list expr → list expr → list expr → bool → list expr | [] vs rs tt := all_implicitly_included_variables_aux rs vs [] ff | [] vs rs ff := vs | (e :: rest) vs rs b := let (vs, rs, b) := if e.is_implicitly_included_variable vs then (e :: vs, rs, tt) else (vs, e :: rs, b) in all_implicitly_included_variables_aux rest vs rs b /-- `all_implicitly_included_variables es vs` accepts `es`, a list of `expr.local_const`, and `vs`, another such list. It returns a list of all variables `e` in `es` or `vs` for which an inclusion of the variables in `vs` into the local context implies that `e` should also be included. See `is_implicitly_included_variable e vs` for the details. In particular, those elements of `vs` are included automatically. -/ meta def all_implicitly_included_variables (es vs : list expr) : list expr := all_implicitly_included_variables_aux es vs [] ff /-- Infer the type of an application of the form `f x1 x2 ... xn`, where `f` is an identifier. This also works if `x1, ... xn` contain free variables. -/ protected meta def simple_infer_type (env : environment) (e : expr) : exceptional expr := do (@const tt n ls, es) ← return e.get_app_fn_args | exceptional.fail "expression is not a constant applied to arguments", d ← env.get n, return $ (d.type.instantiate_pis es).instantiate_univ_params $ d.univ_params.zip ls /-- Auxilliary function for `head_eta_expand`. -/ meta def head_eta_expand_aux : ℕ → expr → expr → expr | (n+1) e (pi x bi d b) := lam x bi d $ head_eta_expand_aux n e b | _ e _ := e /-- `head_eta_expand n e t` eta-expands `e` `n` times, with the binders info and domains obtained by its type `t`. -/ meta def head_eta_expand (n : ℕ) (e t : expr) : expr := ((e.lift_vars 0 n).mk_app $ (list.range n).reverse.map var).head_eta_expand_aux n t /-- `e.eta_expand env dict` eta-expands all expressions that have as head a constant `n` in `dict`. They are expanded until they are applied to one more argument than the maximum in `dict.find n`. -/ protected meta def eta_expand (env : environment) (dict : name_map $ list ℕ) : expr → expr | e := e.replace $ λ e _, do let (e0, es) := e.get_app_fn_args, let ns := (dict.find e0.const_name).iget, guard (bnot ns.empty), let e' := e0.mk_app $ es.map eta_expand, let needed_n := ns.foldr max 0 + 1, if needed_n ≤ es.length then some e' else do e'_type ← (e'.simple_infer_type env).to_option, some $ head_eta_expand (needed_n - es.length) e' e'_type /-- `e.apply_replacement_fun f test` applies `f` to each identifier (inductive type, defined function etc) in an expression, unless * The identifier occurs in an application with first argument `arg`; and * `test arg` is false. * Reorder contains the information about what arguments to reorder: e.g. `g x₁ x₂ x₃ ... xₙ` becomes `g x₂ x₁ x₃ ... xₙ` if `reorder.find g = some [1]`. We assume that all functions where we want to reorder arguments are fully applied. This can be done by applying `expr.eta_expand` first. -/ protected meta def apply_replacement_fun (f : name → name) (test : expr → bool) (reorder : name_map $ list ℕ) : expr → expr | e := e.replace $ λ e _, match e with | const n ls := some $ const (f n) $ -- if the first two arguments are reordered, we also reorder the first two universe parameters if 1 ∈ (reorder.find n).iget then ls.inth 1::ls.head::ls.drop 2 else ls | app g x := let l := (reorder.find g.get_app_fn.const_name).iget in -- this might be inefficient if g.get_app_num_args ∈ l ∧ test g.get_app_args.head then -- interchange `x` and the last argument of `g` some $ apply_replacement_fun g.app_fn (apply_replacement_fun x) $ apply_replacement_fun g.app_arg else if g.is_constant ∧ ¬ test x then some $ g (apply_replacement_fun x) else none | _ := none end open native /-- `univ_params_grouped e` computes for each `level` `u` of `e` the parameters that occur in `u`, and returns the corresponding set of lists of parameters. In pseudo-mathematical form, this returns `{ { p : parameter | p ∈ u } | (u : level) ∈ e }` We use `list name` instead of `name_set`, since `name_set` does not have an order. -/ meta def univ_params_grouped (e : expr) : rb_set (list name) := e.fold mk_rb_set $ λ e n l, match e with | e@(sort u) := l.insert u.params.to_list | e@(const nm us) := l.union $ rb_set.of_list $ us.map $ λ u : level, u.params.to_list | _ := l end end expr /-! ### Declarations about `environment` -/ namespace environment /-- Tests whether `n` is a structure. -/ meta def is_structure (env : environment) (n : name) : bool := (env.structure_fields n).is_some /-- Get the full names of all projections of the structure `n`. Returns `none` if `n` is not a structure. -/ meta def structure_fields_full (env : environment) (n : name) : option (list name) := (env.structure_fields n).map (list.map $ λ n', n ++ n') /-- Tests whether `nm` is a generalized inductive type that is not a normal inductive type. Note that `is_ginductive` returns `tt` even on regular inductive types. This returns `tt` if `nm` is (part of a) mutually defined inductive type or a nested inductive type. -/ meta def is_ginductive' (e : environment) (nm : name) : bool := e.is_ginductive nm ∧ ¬ e.is_inductive nm /-- For all declarations `d` where `f d = some x` this adds `x` to the returned list. -/ meta def decl_filter_map {α : Type} (e : environment) (f : declaration → option α) : list α := e.fold [] $ λ d l, match f d with | some r := r :: l | none := l end /-- Maps `f` to all declarations in the environment. -/ meta def decl_map {α : Type} (e : environment) (f : declaration → α) : list α := e.decl_filter_map $ λ d, some (f d) /-- Lists all declarations in the environment -/ meta def get_decls (e : environment) : list declaration := e.decl_map id /-- Lists all trusted (non-meta) declarations in the environment -/ meta def get_trusted_decls (e : environment) : list declaration := e.decl_filter_map (λ d, if d.is_trusted then some d else none) /-- Lists the name of all declarations in the environment -/ meta def get_decl_names (e : environment) : list name := e.decl_map declaration.to_name /-- Fold a monad over all declarations in the environment. -/ meta def mfold {α : Type} {m : Type → Type} [monad m] (e : environment) (x : α) (fn : declaration → α → m α) : m α := e.fold (return x) (λ d t, t >>= fn d) /-- Filters all declarations in the environment. -/ meta def filter (e : environment) (test : declaration → bool) : list declaration := e.fold [] $ λ d ds, if test d then d::ds else ds /-- Filters all declarations in the environment. -/ meta def mfilter (e : environment) (test : declaration → tactic bool) : tactic (list declaration) := e.mfold [] $ λ d ds, do b ← test d, return $ if b then d::ds else ds /-- Checks whether `s` is a prefix of the file where `n` is declared. This is used to check whether `n` is declared in mathlib, where `s` is the mathlib directory. -/ meta def is_prefix_of_file (e : environment) (s : string) (n : name) : bool := s.is_prefix_of $ (e.decl_olean n).get_or_else "" end environment /-! ### `is_eta_expansion` In this section we define the tactic `is_eta_expansion` which checks whether an expression is an eta-expansion of a structure. (not to be confused with eta-expanion for `λ`). -/ namespace expr open tactic /-- `is_eta_expansion_of args univs l` checks whether for all elements `(nm, pr)` in `l` we have `pr = nm.{univs} args`. Used in `is_eta_expansion`, where `l` consists of the projections and the fields of the value we want to eta-reduce. -/ meta def is_eta_expansion_of (args : list expr) (univs : list level) (l : list (name × expr)) : bool := l.all $ λ⟨proj, val⟩, val = (const proj univs).mk_app args /-- `is_eta_expansion_test l` checks whether there is a list of expresions `args` such that for all elements `(nm, pr)` in `l` we have `pr = nm args`. If so, returns the last element of `args`. Used in `is_eta_expansion`, where `l` consists of the projections and the fields of the value we want to eta-reduce. -/ meta def is_eta_expansion_test : list (name × expr) → option expr | [] := none | (⟨proj, val⟩::l) := match val.get_app_fn with | (const nm univs : expr) := if nm = proj then let args := val.get_app_args in let e := args.ilast in if is_eta_expansion_of args univs l then some e else none else none | _ := none end /-- `is_eta_expansion_aux val l` checks whether `val` can be eta-reduced to an expression `e`. Here `l` is intended to consists of the projections and the fields of `val`. This tactic calls `is_eta_expansion_test l`, but first removes all proofs from the list `l` and afterward checks whether the resulting expression `e` unifies with `val`. This last check is necessary, because `val` and `e` might have different types. -/ meta def is_eta_expansion_aux (val : expr) (l : list (name × expr)) : tactic (option expr) := do l' ← l.mfilter (λ⟨proj, val⟩, bnot <$> is_proof val), match is_eta_expansion_test l' with | some e := option.map (λ _, e) <$> try_core (unify e val) | none := return none end /-- `is_eta_expansion val` checks whether there is an expression `e` such that `val` is the eta-expansion of `e`. With eta-expansion we here mean the eta-expansion of a structure, not of a function. For example, the eta-expansion of `x : α × β` is `⟨x.1, x.2⟩`. This assumes that `val` is a fully-applied application of the constructor of a structure. This is useful to reduce expressions generated by the notation `{ field_1 := _, ..other_structure }` If `other_structure` is itself a field of the structure, then the elaborator will insert an eta-expanded version of `other_structure`. -/ meta def is_eta_expansion (val : expr) : tactic (option expr) := do e ← get_env, type ← infer_type val, projs ← e.structure_fields_full type.get_app_fn.const_name, let args := (val.get_app_args).drop type.get_app_args.length, is_eta_expansion_aux val (projs.zip args) end expr /-! ### Declarations about `declaration` -/ namespace declaration open tactic /-- `declaration.update_with_fun f test tgt decl` sets the name of the given `decl : declaration` to `tgt`, and applies both `expr.eta_expand` and `expr.apply_replacement_fun` to the value and type of `decl`. -/ protected meta def update_with_fun (env : environment) (f : name → name) (test : expr → bool) (reorder : name_map $ list ℕ) (tgt : name) (decl : declaration) : declaration := let decl := decl.update_name $ tgt in let decl := decl.update_type $ (decl.type.eta_expand env reorder).apply_replacement_fun f test reorder in decl.update_value $ (decl.value.eta_expand env reorder).apply_replacement_fun f test reorder /-- Checks whether the declaration is declared in the current file. This is a simple wrapper around `environment.in_current_file` Use `environment.in_current_file` instead if performance matters. -/ meta def in_current_file (d : declaration) : tactic bool := do e ← get_env, return $ e.in_current_file d.to_name /-- Checks whether a declaration is a theorem -/ meta def is_theorem : declaration → bool | (thm _ _ _ _) := tt | _ := ff /-- Checks whether a declaration is a constant -/ meta def is_constant : declaration → bool | (cnst _ _ _ _) := tt | _ := ff /-- Checks whether a declaration is a axiom -/ meta def is_axiom : declaration → bool | (ax _ _ _) := tt | _ := ff /-- Checks whether a declaration is automatically generated in the environment. There is no cheap way to check whether a declaration in the namespace of a generalized inductive type is automatically generated, so for now we say that all of them are automatically generated. -/ meta def is_auto_generated (e : environment) (d : declaration) : bool := e.is_constructor d.to_name ∨ (e.is_projection d.to_name).is_some ∨ (e.is_constructor d.to_name.get_prefix ∧ d.to_name.last ∈ ["inj", "inj_eq", "sizeof_spec", "inj_arrow"]) ∨ (e.is_inductive d.to_name.get_prefix ∧ d.to_name.last ∈ ["below", "binduction_on", "brec_on", "cases_on", "dcases_on", "drec_on", "drec", "rec", "rec_on", "no_confusion", "no_confusion_type", "sizeof", "ibelow", "has_sizeof_inst"]) ∨ d.to_name.has_prefix (λ nm, e.is_ginductive' nm) /-- Returns true iff `d` is an automatically-generated or internal declaration. -/ meta def is_auto_or_internal (env : environment) (d : declaration) : bool := d.to_name.is_internal || d.is_auto_generated env /-- Returns the list of universe levels of a declaration. -/ meta def univ_levels (d : declaration) : list level := d.univ_params.map level.param /-- Returns the `reducibility_hints` field of a `defn`, and `reducibility_hints.opaque` otherwise -/ protected meta def reducibility_hints : declaration → reducibility_hints | (declaration.defn _ _ _ _ red _) := red | _ := _root_.reducibility_hints.opaque /-- formats the arguments of a `declaration.thm` -/ private meta def print_thm (nm : name) (tp : expr) (body : task expr) : tactic format := do tp ← pp tp, body ← pp body.get, return $ "<theorem " ++ to_fmt nm ++ " : " ++ tp ++ " := " ++ body ++ ">" /-- formats the arguments of a `declaration.defn` -/ private meta def print_defn (nm : name) (tp : expr) (body : expr) (is_trusted : bool) : tactic format := do tp ← pp tp, body ← pp body, return $ "<" ++ (if is_trusted then "def " else "meta def ") ++ to_fmt nm ++ " : " ++ tp ++ " := " ++ body ++ ">" /-- formats the arguments of a `declaration.cnst` -/ private meta def print_cnst (nm : name) (tp : expr) (is_trusted : bool) : tactic format := do tp ← pp tp, return $ "<" ++ (if is_trusted then "constant " else "meta constant ") ++ to_fmt nm ++ " : " ++ tp ++ ">" /-- formats the arguments of a `declaration.ax` -/ private meta def print_ax (nm : name) (tp : expr) : tactic format := do tp ← pp tp, return $ "<axiom " ++ to_fmt nm ++ " : " ++ tp ++ ">" /-- pretty-prints a `declaration` object. -/ meta def to_tactic_format : declaration → tactic format | (declaration.thm nm _ tp bd) := print_thm nm tp bd | (declaration.defn nm _ tp bd _ is_trusted) := print_defn nm tp bd is_trusted | (declaration.cnst nm _ tp is_trusted) := print_cnst nm tp is_trusted | (declaration.ax nm _ tp) := print_ax nm tp meta instance : has_to_tactic_format declaration := ⟨to_tactic_format⟩ end declaration meta instance pexpr.decidable_eq {elab} : decidable_eq (expr elab) := unchecked_cast expr.has_decidable_eq
4ca31c14720a4a4bdc3e2aa3b2b5947bb6320254
130c49f47783503e462c16b2eff31933442be6ff
/stage0/src/Lean/PrettyPrinter/Parenthesizer.lean
77a234694592e03e83505e0a2c1368c009271231
[ "Apache-2.0" ]
permissive
Hazel-Brown/lean4
8aa5860e282435ffc30dcdfccd34006c59d1d39c
79e6732fc6bbf5af831b76f310f9c488d44e7a16
refs/heads/master
1,689,218,208,951
1,629,736,869,000
1,629,736,896,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
29,340
lean
/- Copyright (c) 2020 Sebastian Ullrich. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sebastian Ullrich -/ import Lean.CoreM import Lean.KeyedDeclsAttribute import Lean.Parser.Extension import Lean.ParserCompiler.Attribute import Lean.PrettyPrinter.Basic /-! The parenthesizer inserts parentheses into a `Syntax` object where syntactically necessary, usually as an intermediary step between the delaborator and the formatter. While the delaborator outputs structurally well-formed syntax trees that can be re-elaborated without post-processing, this tree structure is lost in the formatter and thus needs to be preserved by proper insertion of parentheses. # The abstract problem & solution The Lean 4 grammar is unstructured and extensible with arbitrary new parsers, so in general it is undecidable whether parentheses are necessary or even allowed at any point in the syntax tree. Parentheses for different categories, e.g. terms and levels, might not even have the same structure. In this module, we focus on the correct parenthesization of parsers defined via `Lean.Parser.prattParser`, which includes both aforementioned built-in categories. Custom parenthesizers can be added for new node kinds, but the data collected in the implementation below might not be appropriate for other parenthesization strategies. Usages of a parser defined via `prattParser` in general have the form `p prec`, where `prec` is the minimum precedence or binding power. Recall that a Pratt parser greedily runs a leading parser with precedence at least `prec` (otherwise it fails) followed by zero or more trailing parsers with precedence at least `prec`; the precedence of a parser is encoded in the call to `leadingNode/trailingNode`, respectively. Thus we should parenthesize a syntax node `stx` supposedly produced by `p prec` if 1. the leading/any trailing parser involved in `stx` has precedence < `prec` (because without parentheses, `p prec` would not produce all of `stx`), or 2. the trailing parser parsing the input to *the right of* `stx`, if any, has precedence >= `prec` (because without parentheses, `p prec` would have parsed it as well and made it a part of `stx`). We also check that the two parsers are from the same syntax category. Note that in case 2, it is also sufficient to parenthesize a *parent* node as long as the offending parser is still to the right of that node. For example, imagine the tree structure of `(f $ fun x => x) y` without parentheses. We need to insert *some* parentheses between `x` and `y` since the lambda body is parsed with precedence 0, while the identifier parser for `y` has precedence `maxPrec`. But we need to parenthesize the `$` node anyway since the precedence of its RHS (0) again is smaller than that of `y`. So it's better to only parenthesize the outer node than ending up with `(f $ (fun x => x)) y`. # Implementation We transform the syntax tree and collect the necessary precedence information for that in a single traversal. The traversal is right-to-left to cover case 2. More specifically, for every Pratt parser call, we store as monadic state the precedence of the left-most trailing parser and the minimum precedence of any parser (`contPrec`/`minPrec`) in this call, if any, and the precedence of the nested trailing Pratt parser call (`trailPrec`), if any. If `stP` is the state resulting from the traversal of a Pratt parser call `p prec`, and `st` is the state of the surrounding call, we parenthesize if `prec > stP.minPrec` (case 1) or if `stP.trailPrec <= st.contPrec` (case 2). The traversal can be customized for each `[*Parser]` parser declaration `c` (more specifically, each `SyntaxNodeKind` `c`) using the `[parenthesizer c]` attribute. Otherwise, a default parenthesizer will be synthesized from the used parser combinators by recursively replacing them with declarations tagged as `[combinatorParenthesizer]` for the respective combinator. If a called function does not have a registered combinator parenthesizer and is not reducible, the synthesizer fails. This happens mostly at the `Parser.mk` decl, which is irreducible, when some parser primitive has not been handled yet. The traversal over the `Syntax` object is complicated by the fact that a parser does not produce exactly one syntax node, but an arbitrary (but constant, for each parser) amount that it pushes on top of the parser stack. This amount can even be zero for parsers such as `checkWsBefore`. Thus we cannot simply pass and return a `Syntax` object to and from `visit`. Instead, we use a `Syntax.Traverser` that allows arbitrary movement and modification inside the syntax tree. Our traversal invariant is that a parser interpreter should stop at the syntax object to the *left* of all syntax objects its parser produced, except when it is already at the left-most child. This special case is not an issue in practice since if there is another parser to the left that produced zero nodes in this case, it should always do so, so there is no danger of the left-most child being processed multiple times. Ultimately, most parenthesizers are implemented via three primitives that do all the actual syntax traversal: `maybeParenthesize mkParen prec x` runs `x` and afterwards transforms it with `mkParen` if the above condition for `p prec` is fulfilled. `visitToken` advances to the preceding sibling and is used on atoms. `visitArgs x` executes `x` on the last child of the current node and then advances to the preceding sibling (of the original current node). -/ namespace Lean namespace PrettyPrinter namespace Parenthesizer structure Context where -- We need to store this `categoryParser` argument to deal with the implicit Pratt parser call in `trailingNode.parenthesizer`. cat : Name := Name.anonymous structure State where stxTrav : Syntax.Traverser --- precedence and category of the current left-most trailing parser, if any; see module doc for details contPrec : Option Nat := none contCat : Name := Name.anonymous -- current minimum precedence in this Pratt parser call, if any; see module doc for details minPrec : Option Nat := none -- precedence and category of the trailing Pratt parser call if any; see module doc for details trailPrec : Option Nat := none trailCat : Name := Name.anonymous -- true iff we have already visited a token on this parser level; used for detecting trailing parsers visitedToken : Bool := false end Parenthesizer abbrev ParenthesizerM := ReaderT Parenthesizer.Context $ StateRefT Parenthesizer.State CoreM abbrev Parenthesizer := ParenthesizerM Unit @[inline] def ParenthesizerM.orelse {α} (p₁ p₂ : ParenthesizerM α) : ParenthesizerM α := do let s ← get catchInternalId backtrackExceptionId p₁ (fun _ => do set s; p₂) instance {α} : OrElse (ParenthesizerM α) := ⟨ParenthesizerM.orelse⟩ unsafe def mkParenthesizerAttribute : IO (KeyedDeclsAttribute Parenthesizer) := KeyedDeclsAttribute.init { builtinName := `builtinParenthesizer, name := `parenthesizer, descr := "Register a parenthesizer for a parser. [parenthesizer k] registers a declaration of type `Lean.PrettyPrinter.Parenthesizer` for the `SyntaxNodeKind` `k`.", valueTypeName := `Lean.PrettyPrinter.Parenthesizer, evalKey := fun builtin stx => do let env ← getEnv let id ← Attribute.Builtin.getId stx -- `isValidSyntaxNodeKind` is updated only in the next stage for new `[builtin*Parser]`s, but we try to -- synthesize a parenthesizer for it immediately, so we just check for a declaration in this case if (builtin && (env.find? id).isSome) || Parser.isValidSyntaxNodeKind env id then pure id else throwError "invalid [parenthesizer] argument, unknown syntax kind '{id}'" } `Lean.PrettyPrinter.parenthesizerAttribute @[builtinInit mkParenthesizerAttribute] constant parenthesizerAttribute : KeyedDeclsAttribute Parenthesizer abbrev CategoryParenthesizer := forall (prec : Nat), Parenthesizer unsafe def mkCategoryParenthesizerAttribute : IO (KeyedDeclsAttribute CategoryParenthesizer) := KeyedDeclsAttribute.init { builtinName := `builtinCategoryParenthesizer, name := `categoryParenthesizer, descr := "Register a parenthesizer for a syntax category. [categoryParenthesizer cat] registers a declaration of type `Lean.PrettyPrinter.CategoryParenthesizer` for the category `cat`, which is used when parenthesizing calls of `categoryParser cat prec`. Implementations should call `maybeParenthesize` with the precedence and `cat`. If no category parenthesizer is registered, the category will never be parenthesized, but still be traversed for parenthesizing nested categories.", valueTypeName := `Lean.PrettyPrinter.CategoryParenthesizer, evalKey := fun _ stx => do let env ← getEnv let id ← Attribute.Builtin.getId stx if Parser.isParserCategory env id then pure id else throwError "invalid [categoryParenthesizer] argument, unknown parser category '{toString id}'" } `Lean.PrettyPrinter.categoryParenthesizerAttribute @[builtinInit mkCategoryParenthesizerAttribute] constant categoryParenthesizerAttribute : KeyedDeclsAttribute CategoryParenthesizer unsafe def mkCombinatorParenthesizerAttribute : IO ParserCompiler.CombinatorAttribute := ParserCompiler.registerCombinatorAttribute `combinatorParenthesizer "Register a parenthesizer for a parser combinator. [combinatorParenthesizer c] registers a declaration of type `Lean.PrettyPrinter.Parenthesizer` for the `Parser` declaration `c`. Note that, unlike with [parenthesizer], this is not a node kind since combinators usually do not introduce their own node kinds. The tagged declaration may optionally accept parameters corresponding to (a prefix of) those of `c`, where `Parser` is replaced with `Parenthesizer` in the parameter types." @[builtinInit mkCombinatorParenthesizerAttribute] constant combinatorParenthesizerAttribute : ParserCompiler.CombinatorAttribute namespace Parenthesizer open Lean.Core open Std.Format def throwBacktrack {α} : ParenthesizerM α := throw $ Exception.internal backtrackExceptionId instance : Syntax.MonadTraverser ParenthesizerM := ⟨{ get := State.stxTrav <$> get, set := fun t => modify (fun st => { st with stxTrav := t }), modifyGet := fun f => modifyGet (fun st => let (a, t) := f st.stxTrav; (a, { st with stxTrav := t })) }⟩ open Syntax.MonadTraverser def addPrecCheck (prec : Nat) : ParenthesizerM Unit := modify fun st => { st with contPrec := Nat.min (st.contPrec.getD prec) prec, minPrec := Nat.min (st.minPrec.getD prec) prec } /-- Execute `x` at the right-most child of the current node, if any, then advance to the left. -/ def visitArgs (x : ParenthesizerM Unit) : ParenthesizerM Unit := do let stx ← getCur if stx.getArgs.size > 0 then goDown (stx.getArgs.size - 1) *> x <* goUp goLeft -- Macro scopes in the parenthesizer output are ultimately ignored by the pretty printer, -- so give a trivial implementation. instance : MonadQuotation ParenthesizerM := { getCurrMacroScope := pure arbitrary, getMainModule := pure arbitrary, withFreshMacroScope := fun x => x, } /-- Run `x` and parenthesize the result using `mkParen` if necessary. If `canJuxtapose` is false, we assume the category does not have a token-less juxtaposition syntax a la function application and deactivate rule 2. -/ def maybeParenthesize (cat : Name) (canJuxtapose : Bool) (mkParen : Syntax → Syntax) (prec : Nat) (x : ParenthesizerM Unit) : ParenthesizerM Unit := do let stx ← getCur let idx ← getIdx let st ← get -- reset precs for the recursive call set { stxTrav := st.stxTrav : State } trace[PrettyPrinter.parenthesize] "parenthesizing (cont := {(st.contPrec, st.contCat)}){indentD (format stx)}" x let { minPrec := some minPrec, trailPrec := trailPrec, trailCat := trailCat, .. } ← get | trace[PrettyPrinter.parenthesize] "visited a syntax tree without precedences?!{line ++ format stx}" trace[PrettyPrinter.parenthesize] (m!"...precedences are {prec} >? {minPrec}" ++ if canJuxtapose then m!", {(trailPrec, trailCat)} <=? {(st.contPrec, st.contCat)}" else "") -- Should we parenthesize? if (prec > minPrec || canJuxtapose && match trailPrec, st.contPrec with | some trailPrec, some contPrec => trailCat == st.contCat && trailPrec <= contPrec | _, _ => false) then -- The recursive `visit` call, by the invariant, has moved to the preceding node. In order to parenthesize -- the original node, we must first move to the right, except if we already were at the left-most child in the first -- place. if idx > 0 then goRight let mut stx ← getCur -- Move leading/trailing whitespace of `stx` outside of parentheses if let SourceInfo.original _ pos trail endPos := stx.getHeadInfo then stx := stx.setHeadInfo (SourceInfo.original "".toSubstring pos trail endPos) if let SourceInfo.original lead pos _ endPos := stx.getTailInfo then stx := stx.setTailInfo (SourceInfo.original lead pos "".toSubstring endPos) let mut stx' := mkParen stx if let SourceInfo.original lead pos _ endPos := stx.getHeadInfo then stx' := stx'.setHeadInfo (SourceInfo.original lead pos "".toSubstring endPos) if let SourceInfo.original _ pos trail endPos := stx.getTailInfo then stx' := stx'.setTailInfo (SourceInfo.original "".toSubstring pos trail endPos) trace[PrettyPrinter.parenthesize] "parenthesized: {stx'.formatStx none}" setCur stx' goLeft -- after parenthesization, there is no more trailing parser modify (fun st => { st with contPrec := Parser.maxPrec, contCat := cat, trailPrec := none }) let { trailPrec := trailPrec, .. } ← get -- If we already had a token at this level, keep the trailing parser. Otherwise, use the minimum of -- `prec` and `trailPrec`. if st.visitedToken then modify fun stP => { stP with trailPrec := st.trailPrec, trailCat := st.trailCat } else let trailPrec := match trailPrec with | some trailPrec => Nat.min trailPrec prec | _ => prec modify fun stP => { stP with trailPrec := trailPrec, trailCat := cat } modify fun stP => { stP with minPrec := st.minPrec } /-- Adjust state and advance. -/ def visitToken : Parenthesizer := do modify fun st => { st with contPrec := none, contCat := Name.anonymous, visitedToken := true } goLeft @[combinatorParenthesizer Lean.Parser.orelse] def orelse.parenthesizer (p1 p2 : Parenthesizer) : Parenthesizer := do let st ← get -- HACK: We have no (immediate) information on which side of the orelse could have produced the current node, so try -- them in turn. Uses the syntax traverser non-linearly! p1 <|> p2 -- `mkAntiquot` is quite complex, so we'd rather have its parenthesizer synthesized below the actual parser definition. -- Note that there is a mutual recursion -- `categoryParser -> mkAntiquot -> termParser -> categoryParser`, so we need to introduce an indirection somewhere -- anyway. @[extern 8 "lean_mk_antiquot_parenthesizer"] constant mkAntiquot.parenthesizer' (name : String) (kind : Option SyntaxNodeKind) (anonymous := true) : Parenthesizer @[inline] def liftCoreM {α} (x : CoreM α) : ParenthesizerM α := liftM x -- break up big mutual recursion @[extern "lean_pretty_printer_parenthesizer_interpret_parser_descr"] constant interpretParserDescr' : ParserDescr → CoreM Parenthesizer unsafe def parenthesizerForKindUnsafe (k : SyntaxNodeKind) : Parenthesizer := do if k == `missing then pure () else let p ← runForNodeKind parenthesizerAttribute k interpretParserDescr' p @[implementedBy parenthesizerForKindUnsafe] constant parenthesizerForKind (k : SyntaxNodeKind) : Parenthesizer @[combinatorParenthesizer Lean.Parser.withAntiquot] def withAntiquot.parenthesizer (antiP p : Parenthesizer) : Parenthesizer := -- TODO: could be optimized using `isAntiquot` (which would have to be moved), but I'd rather -- fix the backtracking hack outright. orelse.parenthesizer antiP p @[combinatorParenthesizer Lean.Parser.withAntiquotSuffixSplice] def withAntiquotSuffixSplice.parenthesizer (k : SyntaxNodeKind) (p suffix : Parenthesizer) : Parenthesizer := do if (← getCur).isAntiquotSuffixSplice then visitArgs <| suffix *> p else p @[combinatorParenthesizer Lean.Parser.tokenWithAntiquot] def tokenWithAntiquot.parenthesizer (p : Parenthesizer) : Parenthesizer := do if (← getCur).isTokenAntiquot then visitArgs p else p def parenthesizeCategoryCore (cat : Name) (prec : Nat) : Parenthesizer := withReader (fun ctx => { ctx with cat := cat }) do let stx ← getCur if stx.getKind == `choice then visitArgs $ stx.getArgs.size.forM fun _ => do let stx ← getCur parenthesizerForKind stx.getKind else withAntiquot.parenthesizer (mkAntiquot.parenthesizer' cat.toString none) (parenthesizerForKind stx.getKind) modify fun st => { st with contCat := cat } @[combinatorParenthesizer Lean.Parser.categoryParser] def categoryParser.parenthesizer (cat : Name) (prec : Nat) : Parenthesizer := do let env ← getEnv match categoryParenthesizerAttribute.getValues env cat with | p::_ => p prec -- Fall back to the generic parenthesizer. -- In this case this node will never be parenthesized since we don't know which parentheses to use. | _ => parenthesizeCategoryCore cat prec @[combinatorParenthesizer Lean.Parser.categoryParserOfStack] def categoryParserOfStack.parenthesizer (offset : Nat) (prec : Nat) : Parenthesizer := do let st ← get let stx := st.stxTrav.parents.back.getArg (st.stxTrav.idxs.back - offset) categoryParser.parenthesizer stx.getId prec @[combinatorParenthesizer Lean.Parser.parserOfStack] def parserOfStack.parenthesizer (offset : Nat) (prec : Nat := 0) : Parenthesizer := do let st ← get let stx := st.stxTrav.parents.back.getArg (st.stxTrav.idxs.back - offset) parenthesizerForKind stx.getKind @[builtinCategoryParenthesizer term] def term.parenthesizer : CategoryParenthesizer | prec => do let stx ← getCur -- this can happen at `termParser <|> many1 commandParser` in `Term.stxQuot` if stx.getKind == nullKind then throwBacktrack else do maybeParenthesize `term true (fun stx => Unhygienic.run `(($stx))) prec $ parenthesizeCategoryCore `term prec @[builtinCategoryParenthesizer tactic] def tactic.parenthesizer : CategoryParenthesizer | prec => do maybeParenthesize `tactic false (fun stx => Unhygienic.run `(tactic|($stx))) prec $ parenthesizeCategoryCore `tactic prec @[builtinCategoryParenthesizer level] def level.parenthesizer : CategoryParenthesizer | prec => do maybeParenthesize `level false (fun stx => Unhygienic.run `(level|($stx))) prec $ parenthesizeCategoryCore `level prec @[combinatorParenthesizer Lean.Parser.error] def error.parenthesizer (msg : String) : Parenthesizer := pure () @[combinatorParenthesizer Lean.Parser.errorAtSavedPos] def errorAtSavedPos.parenthesizer (msg : String) (delta : Bool) : Parenthesizer := pure () @[combinatorParenthesizer Lean.Parser.atomic] def atomic.parenthesizer (p : Parenthesizer) : Parenthesizer := p @[combinatorParenthesizer Lean.Parser.lookahead] def lookahead.parenthesizer (p : Parenthesizer) : Parenthesizer := pure () @[combinatorParenthesizer Lean.Parser.notFollowedBy] def notFollowedBy.parenthesizer (p : Parenthesizer) : Parenthesizer := pure () @[combinatorParenthesizer Lean.Parser.andthen] def andthen.parenthesizer (p1 p2 : Parenthesizer) : Parenthesizer := p2 *> p1 @[combinatorParenthesizer Lean.Parser.node] def node.parenthesizer (k : SyntaxNodeKind) (p : Parenthesizer) : Parenthesizer := do let stx ← getCur if k != stx.getKind then trace[PrettyPrinter.parenthesize.backtrack] "unexpected node kind '{stx.getKind}', expected '{k}'" -- HACK; see `orelse.parenthesizer` throwBacktrack visitArgs p @[combinatorParenthesizer Lean.Parser.checkPrec] def checkPrec.parenthesizer (prec : Nat) : Parenthesizer := addPrecCheck prec @[combinatorParenthesizer Lean.Parser.leadingNode] def leadingNode.parenthesizer (k : SyntaxNodeKind) (prec : Nat) (p : Parenthesizer) : Parenthesizer := do node.parenthesizer k p addPrecCheck prec -- Limit `cont` precedence to `maxPrec-1`. -- This is because `maxPrec-1` is the precedence of function application, which is the only way to turn a leading parser -- into a trailing one. modify fun st => { st with contPrec := Nat.min (Parser.maxPrec-1) prec } @[combinatorParenthesizer Lean.Parser.trailingNode] def trailingNode.parenthesizer (k : SyntaxNodeKind) (prec lhsPrec : Nat) (p : Parenthesizer) : Parenthesizer := do let stx ← getCur if k != stx.getKind then trace[PrettyPrinter.parenthesize.backtrack] "unexpected node kind '{stx.getKind}', expected '{k}'" -- HACK; see `orelse.parenthesizer` throwBacktrack visitArgs do p addPrecCheck prec let ctx ← read modify fun st => { st with contCat := ctx.cat } -- After visiting the nodes actually produced by the parser passed to `trailingNode`, we are positioned on the -- left-most child, which is the term injected by `trailingNode` in place of the recursion. Left recursion is not an -- issue for the parenthesizer, so we can think of this child being produced by `termParser lhsPrec`, or whichever Pratt -- parser is calling us. categoryParser.parenthesizer ctx.cat lhsPrec @[combinatorParenthesizer Lean.Parser.rawCh] def rawCh.parenthesizer (ch : Char) := visitToken @[combinatorParenthesizer Lean.Parser.symbolNoAntiquot] def symbolNoAntiquot.parenthesizer (sym : String) := visitToken @[combinatorParenthesizer Lean.Parser.unicodeSymbolNoAntiquot] def unicodeSymbolNoAntiquot.parenthesizer (sym asciiSym : String) := visitToken @[combinatorParenthesizer Lean.Parser.identNoAntiquot] def identNoAntiquot.parenthesizer := visitToken @[combinatorParenthesizer Lean.Parser.rawIdentNoAntiquot] def rawIdentNoAntiquot.parenthesizer := visitToken @[combinatorParenthesizer Lean.Parser.identEq] def identEq.parenthesizer (id : Name) := visitToken @[combinatorParenthesizer Lean.Parser.nonReservedSymbolNoAntiquot] def nonReservedSymbolNoAntiquot.parenthesizer (sym : String) (includeIdent : Bool) := visitToken @[combinatorParenthesizer Lean.Parser.charLitNoAntiquot] def charLitNoAntiquot.parenthesizer := visitToken @[combinatorParenthesizer Lean.Parser.strLitNoAntiquot] def strLitNoAntiquot.parenthesizer := visitToken @[combinatorParenthesizer Lean.Parser.nameLitNoAntiquot] def nameLitNoAntiquot.parenthesizer := visitToken @[combinatorParenthesizer Lean.Parser.numLitNoAntiquot] def numLitNoAntiquot.parenthesizer := visitToken @[combinatorParenthesizer Lean.Parser.scientificLitNoAntiquot] def scientificLitNoAntiquot.parenthesizer := visitToken @[combinatorParenthesizer Lean.Parser.fieldIdx] def fieldIdx.parenthesizer := visitToken @[combinatorParenthesizer Lean.Parser.manyNoAntiquot] def manyNoAntiquot.parenthesizer (p : Parenthesizer) : Parenthesizer := do let stx ← getCur visitArgs $ stx.getArgs.size.forM fun _ => p @[combinatorParenthesizer Lean.Parser.many1NoAntiquot] def many1NoAntiquot.parenthesizer (p : Parenthesizer) : Parenthesizer := do manyNoAntiquot.parenthesizer p @[combinatorParenthesizer Lean.Parser.many1Unbox] def many1Unbox.parenthesizer (p : Parenthesizer) : Parenthesizer := do let stx ← getCur if stx.getKind == nullKind then manyNoAntiquot.parenthesizer p else p @[combinatorParenthesizer Lean.Parser.optionalNoAntiquot] def optionalNoAntiquot.parenthesizer (p : Parenthesizer) : Parenthesizer := do visitArgs p @[combinatorParenthesizer Lean.Parser.sepByNoAntiquot] def sepByNoAntiquot.parenthesizer (p pSep : Parenthesizer) : Parenthesizer := do let stx ← getCur visitArgs $ (List.range stx.getArgs.size).reverse.forM $ fun i => if i % 2 == 0 then p else pSep @[combinatorParenthesizer Lean.Parser.sepBy1NoAntiquot] def sepBy1NoAntiquot.parenthesizer := sepByNoAntiquot.parenthesizer @[combinatorParenthesizer Lean.Parser.withPosition] def withPosition.parenthesizer (p : Parenthesizer) : Parenthesizer := do -- We assume the formatter will indent syntax sufficiently such that parenthesizing a `withPosition` node is never necessary modify fun st => { st with contPrec := none } p @[combinatorParenthesizer Lean.Parser.withoutPosition] def withoutPosition.parenthesizer (p : Parenthesizer) : Parenthesizer := p @[combinatorParenthesizer Lean.Parser.withForbidden] def withForbidden.parenthesizer (tk : Parser.Token) (p : Parenthesizer) : Parenthesizer := p @[combinatorParenthesizer Lean.Parser.withoutForbidden] def withoutForbidden.parenthesizer (p : Parenthesizer) : Parenthesizer := p @[combinatorParenthesizer Lean.Parser.withoutInfo] def withoutInfo.parenthesizer (p : Parenthesizer) : Parenthesizer := p @[combinatorParenthesizer Lean.Parser.setExpected] def setExpected.parenthesizer (expected : List String) (p : Parenthesizer) : Parenthesizer := p @[combinatorParenthesizer Lean.Parser.incQuotDepth] def incQuotDepth.parenthesizer (p : Parenthesizer) : Parenthesizer := p @[combinatorParenthesizer Lean.Parser.decQuotDepth] def decQuotDepth.parenthesizer (p : Parenthesizer) : Parenthesizer := p @[combinatorParenthesizer Lean.Parser.suppressInsideQuot] def suppressInsideQuot.parenthesizer (p : Parenthesizer) : Parenthesizer := p @[combinatorParenthesizer Lean.Parser.evalInsideQuot] def evalInsideQuot.parenthesizer (declName : Name) (p : Parenthesizer) : Parenthesizer := p @[combinatorParenthesizer Lean.Parser.checkStackTop] def checkStackTop.parenthesizer : Parenthesizer := pure () @[combinatorParenthesizer Lean.Parser.checkWsBefore] def checkWsBefore.parenthesizer : Parenthesizer := pure () @[combinatorParenthesizer Lean.Parser.checkNoWsBefore] def checkNoWsBefore.parenthesizer : Parenthesizer := pure () @[combinatorParenthesizer Lean.Parser.checkLinebreakBefore] def checkLinebreakBefore.parenthesizer : Parenthesizer := pure () @[combinatorParenthesizer Lean.Parser.checkTailWs] def checkTailWs.parenthesizer : Parenthesizer := pure () @[combinatorParenthesizer Lean.Parser.checkColGe] def checkColGe.parenthesizer : Parenthesizer := pure () @[combinatorParenthesizer Lean.Parser.checkColGt] def checkColGt.parenthesizer : Parenthesizer := pure () @[combinatorParenthesizer Lean.Parser.checkLineEq] def checkLineEq.parenthesizer : Parenthesizer := pure () @[combinatorParenthesizer Lean.Parser.eoi] def eoi.parenthesizer : Parenthesizer := pure () @[combinatorParenthesizer Lean.Parser.notFollowedByCategoryToken] def notFollowedByCategoryToken.parenthesizer : Parenthesizer := pure () @[combinatorParenthesizer Lean.Parser.checkNoImmediateColon] def checkNoImmediateColon.parenthesizer : Parenthesizer := pure () @[combinatorParenthesizer Lean.Parser.checkInsideQuot] def checkInsideQuot.parenthesizer : Parenthesizer := pure () @[combinatorParenthesizer Lean.Parser.checkOutsideQuot] def checkOutsideQuot.parenthesizer : Parenthesizer := pure () @[combinatorParenthesizer Lean.Parser.skip] def skip.parenthesizer : Parenthesizer := pure () @[combinatorParenthesizer Lean.Parser.pushNone] def pushNone.parenthesizer : Parenthesizer := goLeft @[combinatorParenthesizer Lean.Parser.interpolatedStr] def interpolatedStr.parenthesizer (p : Parenthesizer) : Parenthesizer := do visitArgs $ (← getCur).getArgs.reverse.forM fun chunk => if chunk.isOfKind interpolatedStrLitKind then goLeft else p @[combinatorParenthesizer Lean.Parser.dbgTraceState] def dbgTraceState.parenthesizer (label : String) (p : Parenthesizer) : Parenthesizer := p @[combinatorParenthesizer ite, macroInline] def ite {α : Type} (c : Prop) [h : Decidable c] (t e : Parenthesizer) : Parenthesizer := if c then t else e open Parser abbrev ParenthesizerAliasValue := AliasValue Parenthesizer builtin_initialize parenthesizerAliasesRef : IO.Ref (NameMap ParenthesizerAliasValue) ← IO.mkRef {} def registerAlias (aliasName : Name) (v : ParenthesizerAliasValue) : IO Unit := do Parser.registerAliasCore parenthesizerAliasesRef aliasName v instance : Coe Parenthesizer ParenthesizerAliasValue := { coe := AliasValue.const } instance : Coe (Parenthesizer → Parenthesizer) ParenthesizerAliasValue := { coe := AliasValue.unary } instance : Coe (Parenthesizer → Parenthesizer → Parenthesizer) ParenthesizerAliasValue := { coe := AliasValue.binary } end Parenthesizer open Parenthesizer /-- Add necessary parentheses in `stx` parsed by `parser`. -/ def parenthesize (parenthesizer : Parenthesizer) (stx : Syntax) : CoreM Syntax := do trace[PrettyPrinter.parenthesize.input] "{format stx}" catchInternalId backtrackExceptionId (do let (_, st) ← (parenthesizer {}).run { stxTrav := Syntax.Traverser.fromSyntax stx } pure st.stxTrav.cur) (fun _ => throwError "parenthesize: uncaught backtrack exception") def parenthesizeTerm := parenthesize $ categoryParser.parenthesizer `term 0 def parenthesizeCommand := parenthesize $ categoryParser.parenthesizer `command 0 builtin_initialize registerTraceClass `PrettyPrinter.parenthesize end PrettyPrinter end Lean
b1a6bc4fab75f3181ab3654215814c1bfc899a83
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/run/1194.lean
849a53cecc57afa70105c0b01ceda577da735f4c
[ "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
251
lean
variable {f: Fin l} {f₀: Fin 0} (h: l = 0) (h': (h▸f) = f₀) example: l = 0 := by simp_all example (h'': l ≠ 0): False := by simp_all example: l = 0 := by simp[*] at * example (h'': l ≠ 0): False := by simp[*] at *
039a3306c750d9374763b04a56acced4473dd54e
b7f22e51856f4989b970961f794f1c435f9b8f78
/tests/lean/run/blast_cc3.lean
9294a4c4aa847d0fe0291fb6eed007d1b793af86
[ "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
373
lean
open nat set_option blast.strategy "cc" constant f (a b : nat) : a > b → nat constant g : nat → nat definition tst (a₁ a₂ b₁ b₂ c d : nat) (H₁ : a₁ > b₁) (H₂ : a₂ > b₂) : a₁ = c → a₂ = c → b₁ = d → d = b₂ → g (g (f a₁ b₁ H₁)) = g (g (f a₂ b₂ H₂)) := by blast print tst
4b7ed2062e21b351b224f4c12643ccff31e6d17b
d9d511f37a523cd7659d6f573f990e2a0af93c6f
/src/group_theory/quotient_group.lean
3a20060305030ede6d6b58b1a943a10b287420ec
[ "Apache-2.0" ]
permissive
hikari0108/mathlib
b7ea2b7350497ab1a0b87a09d093ecc025a50dfa
a9e7d333b0cfd45f13a20f7b96b7d52e19fa2901
refs/heads/master
1,690,483,608,260
1,631,541,580,000
1,631,541,580,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
17,700
lean
/- Copyright (c) 2018 Kevin Buzzard, Patrick Massot. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kevin Buzzard, Patrick Massot This file is to a certain extent based on `quotient_module.lean` by Johannes Hölzl. -/ import group_theory.coset /-! # Quotients of groups by normal subgroups This files develops the basic theory of quotients of groups by normal subgroups. In particular it proves Noether's first and second isomorphism theorems. ## Main definitions * `mk'`: the canonical group homomorphism `G →* G/N` given a normal subgroup `N` of `G`. * `lift φ`: the group homomorphism `G/N →* H` given a group homomorphism `φ : G →* H` such that `N ⊆ ker φ`. * `map f`: the group homomorphism `G/N →* H/M` given a group homomorphism `f : G →* H` such that `N ⊆ f⁻¹(M)`. ## Main statements * `quotient_ker_equiv_range`: Noether's first isomorphism theorem, an explicit isomorphism `G/ker φ → range φ` for every group homomorphism `φ : G →* H`. * `quotient_inf_equiv_prod_normal_quotient`: Noether's second isomorphism theorem, an explicit isomorphism between `H/(H ∩ N)` and `(HN)/N` given a subgroup `H` and a normal subgroup `N` of a group `G`. * `quotient_group.quotient_quotient_equiv_quotient`: Noether's third isomorphism theorem, the canonical isomorphism between `(G / M) / (M / N)` and `G / N`, where `N ≤ M`. ## Tags isomorphism theorems, quotient groups -/ universes u v namespace quotient_group variables {G : Type u} [group G] (N : subgroup G) [nN : N.normal] {H : Type v} [group H] include nN -- Define the `div_inv_monoid` before the `group` structure, -- to make sure we have `inv` fully defined before we show `mul_left_inv`. -- TODO: is there a non-invasive way of defining this in one declaration? @[to_additive quotient_add_group.div_inv_monoid] instance : div_inv_monoid (quotient N) := { one := (1 : G), mul := quotient.map₂' (*) (λ a₁ b₁ hab₁ a₂ b₂ hab₂, ((N.mul_mem_cancel_right (N.inv_mem hab₂)).1 (by rw [mul_inv_rev, mul_inv_rev, ← mul_assoc (a₂⁻¹ * a₁⁻¹), mul_assoc _ b₂, ← mul_assoc b₂, mul_inv_self, one_mul, mul_assoc (a₂⁻¹)]; exact nN.conj_mem _ hab₁ _))), mul_assoc := λ a b c, quotient.induction_on₃' a b c (λ a b c, congr_arg mk (mul_assoc a b c)), one_mul := λ a, quotient.induction_on' a (λ a, congr_arg mk (one_mul a)), mul_one := λ a, quotient.induction_on' a (λ a, congr_arg mk (mul_one a)), inv := λ a, quotient.lift_on' a (λ a, ((a⁻¹ : G) : quotient N)) (λ a b hab, quotient.sound' begin show a⁻¹⁻¹ * b⁻¹ ∈ N, rw ← mul_inv_rev, exact N.inv_mem (nN.mem_comm hab) end) } @[to_additive quotient_add_group.add_group] instance : group (quotient N) := { mul_left_inv := λ a, quotient.induction_on' a (λ a, congr_arg mk (mul_left_inv a)), .. quotient.div_inv_monoid _ } /-- The group homomorphism from `G` to `G/N`. -/ @[to_additive quotient_add_group.mk' "The additive group homomorphism from `G` to `G/N`."] def mk' : G →* quotient N := monoid_hom.mk' (quotient_group.mk) (λ _ _, rfl) @[to_additive, simp] lemma coe_mk' : (mk' N : G → quotient N) = coe := rfl @[to_additive, simp] lemma mk'_apply (x : G) : mk' N x = x := rfl /-- Two `monoid_hom`s from a quotient group are equal if their compositions with `quotient_group.mk'` are equal. See note [partially-applied ext lemmas]. -/ @[to_additive /-" Two `add_monoid_hom`s from an additive quotient group are equal if their compositions with `add_quotient_group.mk'` are equal. See note [partially-applied ext lemmas]. "-/, ext] lemma monoid_hom_ext ⦃f g : quotient N →* H⦄ (h : f.comp (mk' N) = g.comp (mk' N)) : f = g := monoid_hom.ext $ λ x, quotient_group.induction_on x $ (monoid_hom.congr_fun h : _) attribute [ext] quotient_add_group.add_monoid_hom_ext @[simp, to_additive quotient_add_group.eq_zero_iff] lemma eq_one_iff {N : subgroup G} [nN : N.normal] (x : G) : (x : quotient N) = 1 ↔ x ∈ N := begin refine quotient_group.eq.trans _, rw [mul_one, subgroup.inv_mem_iff], end @[simp, to_additive quotient_add_group.ker_mk] lemma ker_mk : monoid_hom.ker (quotient_group.mk' N : G →* quotient_group.quotient N) = N := subgroup.ext eq_one_iff @[to_additive quotient_add_group.eq_iff_sub_mem] lemma eq_iff_div_mem {N : subgroup G} [nN : N.normal] {x y : G} : (x : quotient N) = y ↔ x / y ∈ N := begin refine eq_comm.trans (quotient_group.eq.trans _), rw [nN.mem_comm_iff, div_eq_mul_inv] end -- for commutative groups we don't need normality assumption omit nN @[to_additive quotient_add_group.add_comm_group] instance {G : Type*} [comm_group G] (N : subgroup G) : comm_group (quotient N) := { mul_comm := λ a b, quotient.induction_on₂' a b (λ a b, congr_arg mk (mul_comm a b)), .. @quotient_group.quotient.group _ _ N N.normal_of_comm } include nN local notation ` Q ` := quotient N @[simp, to_additive quotient_add_group.coe_zero] lemma coe_one : ((1 : G) : Q) = 1 := rfl @[simp, to_additive quotient_add_group.coe_add] lemma coe_mul (a b : G) : ((a * b : G) : Q) = a * b := rfl @[simp, to_additive quotient_add_group.coe_neg] lemma coe_inv (a : G) : ((a⁻¹ : G) : Q) = a⁻¹ := rfl @[simp] lemma coe_pow (a : G) (n : ℕ) : ((a ^ n : G) : Q) = a ^ n := (mk' N).map_pow a n @[simp] lemma coe_gpow (a : G) (n : ℤ) : ((a ^ n : G) : Q) = a ^ n := (mk' N).map_gpow a n /-- A group homomorphism `φ : G →* H` with `N ⊆ ker(φ)` descends (i.e. `lift`s) to a group homomorphism `G/N →* H`. -/ @[to_additive quotient_add_group.lift "An `add_group` homomorphism `φ : G →+ H` with `N ⊆ ker(φ)` descends (i.e. `lift`s) to a group homomorphism `G/N →* H`."] def lift (φ : G →* H) (HN : ∀x∈N, φ x = 1) : Q →* H := monoid_hom.mk' (λ q : Q, q.lift_on' φ $ assume a b (hab : a⁻¹ * b ∈ N), (calc φ a = φ a * 1 : (mul_one _).symm ... = φ a * φ (a⁻¹ * b) : HN (a⁻¹ * b) hab ▸ rfl ... = φ (a * (a⁻¹ * b)) : (φ.map_mul a (a⁻¹ * b)).symm ... = φ b : by rw mul_inv_cancel_left)) (λ q r, quotient.induction_on₂' q r $ φ.map_mul) @[simp, to_additive quotient_add_group.lift_mk] lemma lift_mk {φ : G →* H} (HN : ∀x∈N, φ x = 1) (g : G) : lift N φ HN (g : Q) = φ g := rfl @[simp, to_additive quotient_add_group.lift_mk'] lemma lift_mk' {φ : G →* H} (HN : ∀x∈N, φ x = 1) (g : G) : lift N φ HN (mk g : Q) = φ g := rfl @[simp, to_additive quotient_add_group.lift_quot_mk] lemma lift_quot_mk {φ : G →* H} (HN : ∀x∈N, φ x = 1) (g : G) : lift N φ HN (quot.mk _ g : Q) = φ g := rfl /-- A group homomorphism `f : G →* H` induces a map `G/N →* H/M` if `N ⊆ f⁻¹(M)`. -/ @[to_additive quotient_add_group.map "An `add_group` homomorphism `f : G →+ H` induces a map `G/N →+ H/M` if `N ⊆ f⁻¹(M)`."] def map (M : subgroup H) [M.normal] (f : G →* H) (h : N ≤ M.comap f) : quotient N →* quotient M := begin refine quotient_group.lift N ((mk' M).comp f) _, assume x hx, refine quotient_group.eq.2 _, rw [mul_one, subgroup.inv_mem_iff], exact h hx, end @[simp, to_additive quotient_add_group.map_coe] lemma map_coe (M : subgroup H) [M.normal] (f : G →* H) (h : N ≤ M.comap f) (x : G) : map N M f h ↑x = ↑(f x) := lift_mk' _ _ x @[to_additive quotient_add_group.map_mk'] lemma map_mk' (M : subgroup H) [M.normal] (f : G →* H) (h : N ≤ M.comap f) (x : G) : map N M f h (mk' _ x) = ↑(f x) := quotient_group.lift_mk' _ _ x omit nN variables (φ : G →* H) open function monoid_hom /-- The induced map from the quotient by the kernel to the codomain. -/ @[to_additive quotient_add_group.ker_lift "The induced map from the quotient by the kernel to the codomain."] def ker_lift : quotient (ker φ) →* H := lift _ φ $ λ g, φ.mem_ker.mp @[simp, to_additive quotient_add_group.ker_lift_mk] lemma ker_lift_mk (g : G) : (ker_lift φ) g = φ g := lift_mk _ _ _ @[simp, to_additive quotient_add_group.ker_lift_mk'] lemma ker_lift_mk' (g : G) : (ker_lift φ) (mk g) = φ g := lift_mk' _ _ _ @[to_additive quotient_add_group.injective_ker_lift] lemma ker_lift_injective : injective (ker_lift φ) := assume a b, quotient.induction_on₂' a b $ assume a b (h : φ a = φ b), quotient.sound' $ show a⁻¹ * b ∈ ker φ, by rw [mem_ker, φ.map_mul, ← h, φ.map_inv, inv_mul_self] -- Note that `ker φ` isn't definitionally `ker (φ.range_restrict)` -- so there is a bit of annoying code duplication here /-- The induced map from the quotient by the kernel to the range. -/ @[to_additive quotient_add_group.range_ker_lift "The induced map from the quotient by the kernel to the range."] def range_ker_lift : quotient (ker φ) →* φ.range := lift _ φ.range_restrict $ λ g hg, (mem_ker _).mp $ by rwa range_restrict_ker @[to_additive quotient_add_group.range_ker_lift_injective] lemma range_ker_lift_injective : injective (range_ker_lift φ) := assume a b, quotient.induction_on₂' a b $ assume a b (h : φ.range_restrict a = φ.range_restrict b), quotient.sound' $ show a⁻¹ * b ∈ ker φ, by rw [←range_restrict_ker, mem_ker, φ.range_restrict.map_mul, ← h, φ.range_restrict.map_inv, inv_mul_self] @[to_additive quotient_add_group.range_ker_lift_surjective] lemma range_ker_lift_surjective : surjective (range_ker_lift φ) := begin rintro ⟨_, g, rfl⟩, use mk g, refl, end /-- **Noether's first isomorphism theorem** (a definition): the canonical isomorphism between `G/(ker φ)` to `range φ`. -/ @[to_additive quotient_add_group.quotient_ker_equiv_range "The first isomorphism theorem (a definition): the canonical isomorphism between `G/(ker φ)` to `range φ`."] noncomputable def quotient_ker_equiv_range : (quotient (ker φ)) ≃* range φ := mul_equiv.of_bijective (range_ker_lift φ) ⟨range_ker_lift_injective φ, range_ker_lift_surjective φ⟩ /-- The canonical isomorphism `G/(ker φ) ≃* H` induced by a homomorphism `φ : G →* H` with a right inverse `ψ : H → G`. -/ @[to_additive quotient_add_group.quotient_ker_equiv_of_right_inverse "The canonical isomorphism `G/(ker φ) ≃+ H` induced by a homomorphism `φ : G →+ H` with a right inverse `ψ : H → G`.", simps] def quotient_ker_equiv_of_right_inverse (ψ : H → G) (hφ : function.right_inverse ψ φ) : quotient (ker φ) ≃* H := { to_fun := ker_lift φ, inv_fun := mk ∘ ψ, left_inv := λ x, ker_lift_injective φ (by rw [function.comp_app, ker_lift_mk', hφ]), right_inv := hφ, .. ker_lift φ } /-- The canonical isomorphism `G/⊥ ≃* G`. -/ @[to_additive quotient_add_group.quotient_ker_equiv_of_right_inverse "The canonical isomorphism `G/⊥ ≃+ G`.", simps] def quotient_bot : quotient (⊥ : subgroup G) ≃* G := quotient_ker_equiv_of_right_inverse (monoid_hom.id G) id (λ x, rfl) /-- The canonical isomorphism `G/(ker φ) ≃* H` induced by a surjection `φ : G →* H`. For a `computable` version, see `quotient_group.quotient_ker_equiv_of_right_inverse`. -/ @[to_additive quotient_add_group.quotient_ker_equiv_of_surjective "The canonical isomorphism `G/(ker φ) ≃+ H` induced by a surjection `φ : G →+ H`. For a `computable` version, see `quotient_add_group.quotient_ker_equiv_of_right_inverse`."] noncomputable def quotient_ker_equiv_of_surjective (hφ : function.surjective φ) : quotient (ker φ) ≃* H := quotient_ker_equiv_of_right_inverse φ _ hφ.has_right_inverse.some_spec /-- If two normal subgroups `M` and `N` of `G` are the same, their quotient groups are isomorphic. -/ @[to_additive "If two normal subgroups `M` and `N` of `G` are the same, their quotient groups are isomorphic."] def equiv_quotient_of_eq {M N : subgroup G} [M.normal] [N.normal] (h : M = N) : quotient M ≃* quotient N := { to_fun := (lift M (mk' N) (λ m hm, quotient_group.eq.mpr (by simpa [← h] using M.inv_mem hm))), inv_fun := (lift N (mk' M) (λ n hn, quotient_group.eq.mpr (by simpa [← h] using N.inv_mem hn))), left_inv := λ x, x.induction_on' $ by { intro, refl }, right_inv := λ x, x.induction_on' $ by { intro, refl }, map_mul' := λ x y, by rw map_mul } @[simp, to_additive] lemma equiv_quotient_of_eq_mk {M N : subgroup G} [M.normal] [N.normal] (h : M = N) (x : G) : quotient_group.equiv_quotient_of_eq h (quotient_group.mk x) = (quotient_group.mk x) := rfl /-- Let `A', A, B', B` be subgroups of `G`. If `A' ≤ B'` and `A ≤ B`, then there is a map `A / (A' ⊓ A) →* B / (B' ⊓ B)` induced by the inclusions. -/ @[to_additive "Let `A', A, B', B` be subgroups of `G`. If `A' ≤ B'` and `A ≤ B`, then there is a map `A / (A' ⊓ A) →+ B / (B' ⊓ B)` induced by the inclusions."] def quotient_map_subgroup_of_of_le {A' A B' B : subgroup G} [hAN : (A'.subgroup_of A).normal] [hBN : (B'.subgroup_of B).normal] (h' : A' ≤ B') (h : A ≤ B) : quotient (A'.subgroup_of A) →* quotient (B'.subgroup_of B) := map _ _ (subgroup.inclusion h) $ by simp [subgroup.subgroup_of, subgroup.comap_comap]; exact subgroup.comap_mono h' @[simp, to_additive] lemma quotient_map_subgroup_of_of_le_coe {A' A B' B : subgroup G} [hAN : (A'.subgroup_of A).normal] [hBN : (B'.subgroup_of B).normal] (h' : A' ≤ B') (h : A ≤ B) (x : A) : quotient_map_subgroup_of_of_le h' h x = ↑(subgroup.inclusion h x : B) := rfl /-- Let `A', A, B', B` be subgroups of `G`. If `A' = B'` and `A = B`, then the quotients `A / (A' ⊓ A)` and `B / (B' ⊓ B)` are isomorphic. Applying this equiv is nicer than rewriting along the equalities, since the type of `(A'.subgroup_of A : subgroup A)` depends on on `A`. -/ @[to_additive "Let `A', A, B', B` be subgroups of `G`. If `A' = B'` and `A = B`, then the quotients `A / (A' ⊓ A)` and `B / (B' ⊓ B)` are isomorphic. Applying this equiv is nicer than rewriting along the equalities, since the type of `(A'.add_subgroup_of A : add_subgroup A)` depends on on `A`. "] def equiv_quotient_subgroup_of_of_eq {A' A B' B : subgroup G} [hAN : (A'.subgroup_of A).normal] [hBN : (B'.subgroup_of B).normal] (h' : A' = B') (h : A = B) : quotient (A'.subgroup_of A) ≃* quotient (B'.subgroup_of B) := monoid_hom.to_mul_equiv (quotient_map_subgroup_of_of_le h'.le h.le) (quotient_map_subgroup_of_of_le h'.ge h.ge) (by { ext ⟨x, hx⟩, refl }) (by { ext ⟨x, hx⟩, refl }) section snd_isomorphism_thm open subgroup /-- **Noether's second isomorphism theorem**: given two subgroups `H` and `N` of a group `G`, where `N` is normal, defines an isomorphism between `H/(H ∩ N)` and `(HN)/N`. -/ @[to_additive "The second isomorphism theorem: given two subgroups `H` and `N` of a group `G`, where `N` is normal, defines an isomorphism between `H/(H ∩ N)` and `(H + N)/N`"] noncomputable def quotient_inf_equiv_prod_normal_quotient (H N : subgroup G) [N.normal] : quotient ((H ⊓ N).comap H.subtype) ≃* quotient (N.comap (H ⊔ N).subtype) := /- φ is the natural homomorphism H →* (HN)/N. -/ let φ : H →* quotient (N.comap (H ⊔ N).subtype) := (mk' $ N.comap (H ⊔ N).subtype).comp (inclusion le_sup_left) in have φ_surjective : function.surjective φ := λ x, x.induction_on' $ begin rintro ⟨y, (hy : y ∈ ↑(H ⊔ N))⟩, rw mul_normal H N at hy, rcases hy with ⟨h, n, hh, hn, rfl⟩, use [h, hh], apply quotient.eq.mpr, change h⁻¹ * (h * n) ∈ N, rwa [←mul_assoc, inv_mul_self, one_mul], end, (equiv_quotient_of_eq (by simp [comap_comap, ←comap_ker])).trans (quotient_ker_equiv_of_surjective φ φ_surjective) end snd_isomorphism_thm section third_iso_thm variables (M : subgroup G) [nM : M.normal] include nM nN @[to_additive quotient_add_group.map_normal] instance map_normal : (M.map (quotient_group.mk' N)).normal := { conj_mem := begin rintro _ ⟨x, hx, rfl⟩ y, refine induction_on' y (λ y, ⟨y * x * y⁻¹, subgroup.normal.conj_mem nM x hx y, _⟩), simp only [mk'_apply, coe_mul, coe_inv] end } variables (h : N ≤ M) /-- The map from the third isomorphism theorem for groups: `(G / N) / (M / N) → G / M`. -/ @[to_additive quotient_add_group.quotient_quotient_equiv_quotient_aux "The map from the third isomorphism theorem for additive groups: `(A / N) / (M / N) → A / M`."] def quotient_quotient_equiv_quotient_aux : quotient (M.map (mk' N)) →* quotient M := lift (M.map (mk' N)) (map N M (monoid_hom.id G) h) (by { rintro _ ⟨x, hx, rfl⟩, rw map_mk' N M _ _ x, exact (quotient_group.eq_one_iff _).mpr hx }) @[simp, to_additive quotient_add_group.quotient_quotient_equiv_quotient_aux_coe] lemma quotient_quotient_equiv_quotient_aux_coe (x : quotient_group.quotient N) : quotient_quotient_equiv_quotient_aux N M h x = quotient_group.map N M (monoid_hom.id G) h x := quotient_group.lift_mk' _ _ x @[to_additive quotient_add_group.quotient_quotient_equiv_quotient_aux_coe_coe] lemma quotient_quotient_equiv_quotient_aux_coe_coe (x : G) : quotient_quotient_equiv_quotient_aux N M h (x : quotient_group.quotient N) = x := quotient_group.lift_mk' _ _ x /-- **Noether's third isomorphism theorem** for groups: `(G / N) / (M / N) ≃ G / M`. -/ @[to_additive quotient_add_group.quotient_quotient_equiv_quotient "**Noether's third isomorphism theorem** for additive groups: `(A / N) / (M / N) ≃ A / M`."] def quotient_quotient_equiv_quotient : quotient_group.quotient (M.map (quotient_group.mk' N)) ≃* quotient_group.quotient M := monoid_hom.to_mul_equiv (quotient_quotient_equiv_quotient_aux N M h) (quotient_group.map _ _ (quotient_group.mk' N) (subgroup.le_comap_map _ _)) (by { ext, simp }) (by { ext, simp }) end third_iso_thm end quotient_group
63fdf2e34e398a34698f273665336635f45f0b34
95dcf8dea2baf2b4b0a60d438f27c35ae3dd3990
/src/field_theory/splitting_field.lean
b713071f2fe28a2dfb61419593b822bf094fe760
[ "Apache-2.0" ]
permissive
uniformity1/mathlib
829341bad9dfa6d6be9adaacb8086a8a492e85a4
dd0e9bd8f2e5ec267f68e72336f6973311909105
refs/heads/master
1,588,592,015,670
1,554,219,842,000
1,554,219,842,000
179,110,702
0
0
Apache-2.0
1,554,220,076,000
1,554,220,076,000
null
UTF-8
Lean
false
false
7,730
lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes Definition of splitting fields, and definition of homomorphism into any field that splits -/ import ring_theory.adjoin_root ring_theory.unique_factorization_domain universes u v w variables {α : Type u} {β : Type v} {γ : Type w} namespace polynomial noncomputable theory local attribute [instance, priority 0] classical.prop_decidable variables [discrete_field α] [discrete_field β] [discrete_field γ] open polynomial adjoin_root section splits variables (i : α → β) [is_field_hom i] /-- a polynomial `splits` iff it is zero or all of its irreducible factors have `degree` 1 -/ def splits (f : polynomial α) : Prop := f = 0 ∨ ∀ {g : polynomial β}, irreducible g → g ∣ f.map i → degree g = 1 @[simp] lemma splits_zero : splits i (0 : polynomial α) := or.inl rfl @[simp] lemma splits_C (a : α) : splits i (C a) := if ha : a = 0 then ha.symm ▸ (@C_0 α _ _).symm ▸ splits_zero i else have hia : i a ≠ 0, from mt ((is_add_group_hom.injective_iff i).1 (is_field_hom.injective i) _) ha, or.inr $ λ g hg ⟨p, hp⟩, absurd hg.1 (classical.not_not.2 (is_unit_iff_degree_eq_zero.2 $ by have := congr_arg degree hp; simp [degree_C hia, @eq_comm (with_bot ℕ) 0, nat.with_bot.add_eq_zero_iff] at this; clear _fun_match; tautology)) lemma splits_of_degree_eq_one {f : polynomial α} (hf : degree f = 1) : splits i f := or.inr $ λ g hg ⟨p, hp⟩, by have := congr_arg degree hp; simp [nat.with_bot.add_eq_one_iff, hf, @eq_comm (with_bot ℕ) 1, mt is_unit_iff_degree_eq_zero.2 hg.1] at this; clear _fun_match; tauto lemma splits_of_degree_le_one {f : polynomial α} (hf : degree f ≤ 1) : splits i f := begin cases h : degree f with n, { rw [degree_eq_bot.1 h]; exact splits_zero i }, { cases n with n, { rw [eq_C_of_degree_le_zero (trans_rel_right (≤) h (le_refl _))]; exact splits_C _ _ }, { have hn : n = 0, { rw h at hf, cases n, { refl }, { exact absurd hf dec_trivial } }, exact splits_of_degree_eq_one _ (by rw [h, hn]; refl) } } end lemma splits_mul {f g : polynomial α} (hf : splits i f) (hg : splits i g) : splits i (f * g) := if h : f * g = 0 then by simp [h] else or.inr $ λ p hp hpf, ((principal_ideal_domain.irreducible_iff_prime.1 hp).2.2 _ _ (show p ∣ map i f * map i g, by convert hpf; rw map_mul)).elim (hf.resolve_left (λ hf, by simpa [hf] using h) hp) (hg.resolve_left (λ hg, by simpa [hg] using h) hp) lemma splits_of_splits_mul {f g : polynomial α} (hfg : f * g ≠ 0) (h : splits i (f * g)) : splits i f ∧ splits i g := ⟨or.inr $ λ g hgi hg, or.resolve_left h hfg hgi (by rw map_mul; exact dvd.trans hg (dvd_mul_right _ _)), or.inr $ λ g hgi hg, or.resolve_left h hfg hgi (by rw map_mul; exact dvd.trans hg (dvd_mul_left _ _))⟩ lemma splits_map_iff (j : β → γ) [is_field_hom j] {f : polynomial α} : splits j (f.map i) ↔ splits (λ x, j (i x)) f := by simp [splits, polynomial.map_map] lemma exists_root_of_splits {f : polynomial α} (hs : splits i f) (hf0 : degree f ≠ 0) : ∃ x, eval₂ i x f = 0 := if hf0 : f = 0 then ⟨37, by simp [hf0]⟩ else let ⟨g, hg⟩ := is_noetherian_ring.exists_irreducible_factor (show ¬ is_unit (f.map i), from mt is_unit_iff_degree_eq_zero.1 (by rwa degree_map)) (by rw [ne.def, map_eq_zero]; exact hf0) in let ⟨x, hx⟩ := exists_root_of_degree_eq_one (hs.resolve_left hf0 hg.1 hg.2) in let ⟨i, hi⟩ := hg.2 in ⟨x, by rw [← eval_map, hi, eval_mul, show _ = _, from hx, zero_mul]⟩ lemma exists_multiset_of_splits {f : polynomial α} : splits i f → ∃ (s : multiset β), f.map i = C (i f.leading_coeff) * (s.map (λ a : β, (X : polynomial β) - C a)).prod := suffices splits id (f.map i) → ∃ s : multiset β, f.map i = (C (f.map i).leading_coeff) * (s.map (λ a : β, (X : polynomial β) - C a)).prod, by rwa [splits_map_iff, leading_coeff_map i] at this, is_noetherian_ring.irreducible_induction_on (f.map i) (λ _, ⟨{37}, by simp [is_ring_hom.map_zero i]⟩) (λ u hu _, ⟨0, by conv_lhs { rw eq_C_of_degree_eq_zero (is_unit_iff_degree_eq_zero.1 hu) }; simp [leading_coeff, nat_degree_eq_of_degree_eq_some (is_unit_iff_degree_eq_zero.1 hu)]⟩) (λ f p hf0 hp ih hfs, have hpf0 : p * f ≠ 0, from mul_ne_zero (nonzero_of_irreducible hp) hf0, let ⟨s, hs⟩ := ih (splits_of_splits_mul _ hpf0 hfs).2 in ⟨-(p * norm_unit p).coeff 0 :: s, have hp1 : degree p = 1, from hfs.resolve_left hpf0 hp (by simp), begin rw [multiset.map_cons, multiset.prod_cons, leading_coeff_mul, C_mul, mul_assoc, mul_left_comm (C f.leading_coeff), ← hs, ← mul_assoc, domain.mul_right_inj hf0], conv_lhs {rw eq_X_add_C_of_degree_eq_one hp1}, simp only [mul_add, coe_norm_unit (nonzero_of_irreducible hp), mul_comm p, coeff_neg, C_neg, sub_eq_add_neg, neg_neg, coeff_C_mul, (mul_assoc _ _ _).symm, C_mul.symm, mul_inv_cancel (show p.leading_coeff ≠ 0, from mt leading_coeff_eq_zero.1 (nonzero_of_irreducible hp)), one_mul], end⟩) section UFD local attribute [instance, priority 0] principal_ideal_domain.to_unique_factorization_domain local infix ` ~ᵤ ` : 50 := associated open unique_factorization_domain associates lemma splits_of_exists_multiset {f : polynomial α} {s : multiset β} (hs : f.map i = C (i f.leading_coeff) * (s.map (λ a : β, (X : polynomial β) - C a)).prod) : splits i f := if hf0 : f = 0 then or.inl hf0 else or.inr $ λ p hp hdp, have ht : multiset.rel associated (factors (f.map i)) (s.map (λ a : β, (X : polynomial β) - C a)) := unique (λ p hp, irreducible_factors (mt (map_eq_zero i).1 hf0) _ hp) (λ p, by simp [@eq_comm _ _ p, -sub_eq_add_neg, irreducible_of_degree_eq_one (degree_X_sub_C _)] {contextual := tt}) (associated.symm $ calc _ ~ᵤ f.map i : ⟨units.map C (units.mk0 (f.map i).leading_coeff (mt leading_coeff_eq_zero.1 (mt (map_eq_zero i).1 hf0))), by conv_rhs {rw [hs, ← leading_coeff_map i, mul_comm]}; refl⟩ ... ~ᵤ _ : associated.symm (unique_factorization_domain.factors_prod (by simpa using hf0))), let ⟨q, hq, hpq⟩ := exists_mem_factors_of_dvd (by simpa) hp hdp in let ⟨q', hq', hqq'⟩ := multiset.exists_mem_of_rel_of_mem ht hq in let ⟨a, ha⟩ := multiset.mem_map.1 hq' in by rw [← degree_X_sub_C a, ha.2]; exact degree_eq_degree_of_associated (hpq.trans hqq') lemma splits_of_splits_id {f : polynomial α} : splits id f → splits i f := unique_factorization_domain.induction_on_prime f (λ _, splits_zero _) (λ _ hu _, splits_of_degree_le_one _ ((is_unit_iff_degree_eq_zero.1 hu).symm ▸ dec_trivial)) (λ a p ha0 hp ih hfi, splits_mul _ (splits_of_degree_eq_one _ ((splits_of_splits_mul _ (mul_ne_zero hp.1 ha0) hfi).1.resolve_left hp.1 (irreducible_of_prime hp) (by rw map_id))) (ih (splits_of_splits_mul _ (mul_ne_zero hp.1 ha0) hfi).2)) end UFD lemma splits_iff_exists_multiset {f : polynomial α} : splits i f ↔ ∃ (s : multiset β), f.map i = C (i f.leading_coeff) * (s.map (λ a : β, (X : polynomial β) - C a)).prod := ⟨exists_multiset_of_splits i, λ ⟨s, hs⟩, splits_of_exists_multiset i hs⟩ lemma splits_comp_of_splits (j : β → γ) [is_field_hom j] {f : polynomial α} (h : splits i f) : splits (λ x, j (i x)) f := begin change i with (λ x, id (i x)) at h, rw [← splits_map_iff], rw [← splits_map_iff i id] at h, exact splits_of_splits_id _ h end end splits end polynomial
11e65855f8a2413c6981c8eb4f534ee4cf650cab
94e33a31faa76775069b071adea97e86e218a8ee
/src/data/ordmap/ordset.lean
17375b3c9e6c247c0a3ca6e46fcef0d9d8eaf43a
[ "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
69,287
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.ordmap.ordnode import algebra.order.ring import data.nat.dist import tactic.linarith /-! # Verification of the `ordnode α` datatype This file proves the correctness of the operations in `data.ordmap.ordnode`. The public facing version is the type `ordset α`, which is a wrapper around `ordnode α` which includes the correctness invariant of the type, and it exposes parallel operations like `insert` as functions on `ordset` that do the same thing but bundle the correctness proofs. The advantage is that it is possible to, for example, prove that the result of `find` on `insert` will actually find the element, while `ordnode` cannot guarantee this if the input tree did not satisfy the type invariants. ## Main definitions * `ordset α`: A well formed set of values of type `α` ## Implementation notes The majority of this file is actually in the `ordnode` namespace, because we first have to prove the correctness of all the operations (and defining what correctness means here is actually somewhat subtle). So all the actual `ordset` operations are at the very end, once we have all the theorems. An `ordnode α` is an inductive type which describes a tree which stores the `size` at internal nodes. The correctness invariant of an `ordnode α` is: * `ordnode.sized t`: All internal `size` fields must match the actual measured size of the tree. (This is not hard to satisfy.) * `ordnode.balanced t`: Unless the tree has the form `()` or `((a) b)` or `(a (b))` (that is, nil or a single singleton subtree), the two subtrees must satisfy `size l ≤ δ * size r` and `size r ≤ δ * size l`, where `δ := 3` is a global parameter of the data structure (and this property must hold recursively at subtrees). This is why we say this is a "size balanced tree" data structure. * `ordnode.bounded lo hi t`: The members of the tree must be in strictly increasing order, meaning that if `a` is in the left subtree and `b` is the root, then `a ≤ b` and `¬ (b ≤ a)`. We enforce this using `ordnode.bounded` which includes also a global upper and lower bound. Because the `ordnode` file was ported from Haskell, the correctness invariants of some of the functions have not been spelled out, and some theorems like `ordnode.valid'.balance_l_aux` show very intricate assumptions on the sizes, which may need to be revised if it turns out some operations violate these assumptions, because there is a decent amount of slop in the actual data structure invariants, so the theorem will go through with multiple choices of assumption. **Note:** This file is incomplete, in the sense that the intent is to have verified versions and lemmas about all the definitions in `ordnode.lean`, but at the moment only a few operations are verified (the hard part should be out of the way, but still). Contributors are encouraged to pick this up and finish the job, if it appeals to you. ## Tags ordered map, ordered set, data structure, verified programming -/ variable {α : Type*} namespace ordnode /-! ### delta and ratio -/ theorem not_le_delta {s} (H : 1 ≤ s) : ¬ s ≤ delta * 0 := not_le_of_gt H theorem delta_lt_false {a b : ℕ} (h₁ : delta * a < b) (h₂ : delta * b < a) : false := not_le_of_lt (lt_trans ((mul_lt_mul_left dec_trivial).2 h₁) h₂) $ by simpa [mul_assoc] using nat.mul_le_mul_right a (dec_trivial : 1 ≤ delta * delta) /-! ### `singleton` -/ /-! ### `size` and `empty` -/ /-- O(n). Computes the actual number of elements in the set, ignoring the cached `size` field. -/ def real_size : ordnode α → ℕ | nil := 0 | (node _ l _ r) := real_size l + real_size r + 1 /-! ### `sized` -/ /-- The `sized` property asserts that all the `size` fields in nodes match the actual size of the respective subtrees. -/ def sized : ordnode α → Prop | nil := true | (node s l _ r) := s = size l + size r + 1 ∧ sized l ∧ sized r theorem sized.node' {l x r} (hl : @sized α l) (hr : sized r) : sized (node' l x r) := ⟨rfl, hl, hr⟩ theorem sized.eq_node' {s l x r} (h : @sized α (node s l x r)) : node s l x r = node' l x r := by rw h.1; refl theorem sized.size_eq {s l x r} (H : sized (@node α s l x r)) : size (@node α s l x r) = size l + size r + 1 := H.1 @[elab_as_eliminator] theorem sized.induction {t} (hl : @sized α t) {C : ordnode α → Prop} (H0 : C nil) (H1 : ∀ l x r, C l → C r → C (node' l x r)) : C t := begin induction t, {exact H0}, rw hl.eq_node', exact H1 _ _ _ (t_ih_l hl.2.1) (t_ih_r hl.2.2) end theorem size_eq_real_size : ∀ {t : ordnode α}, sized t → size t = real_size t | nil _ := rfl | (node s l x r) ⟨h₁, h₂, h₃⟩ := by rw [size, h₁, size_eq_real_size h₂, size_eq_real_size h₃]; refl @[simp] theorem sized.size_eq_zero {t : ordnode α} (ht : sized t) : size t = 0 ↔ t = nil := by cases t; [simp, simp [ht.1]] theorem sized.pos {s l x r} (h : sized (@node α s l x r)) : 0 < s := by rw h.1; apply nat.le_add_left /-! `dual` -/ theorem dual_dual : ∀ (t : ordnode α), dual (dual t) = t | nil := rfl | (node s l x r) := by rw [dual, dual, dual_dual, dual_dual] @[simp] theorem size_dual (t : ordnode α) : size (dual t) = size t := by cases t; refl /-! `balanced` -/ /-- The `balanced_sz l r` asserts that a hypothetical tree with children of sizes `l` and `r` is balanced: either `l ≤ δ * r` and `r ≤ δ * r`, or the tree is trivial with a singleton on one side and nothing on the other. -/ def balanced_sz (l r : ℕ) : Prop := l + r ≤ 1 ∨ (l ≤ delta * r ∧ r ≤ delta * l) instance balanced_sz.dec : decidable_rel balanced_sz := λ l r, or.decidable /-- The `balanced t` asserts that the tree `t` satisfies the balance invariants (at every level). -/ def balanced : ordnode α → Prop | nil := true | (node _ l _ r) := balanced_sz (size l) (size r) ∧ balanced l ∧ balanced r instance balanced.dec : decidable_pred (@balanced α) | t := by induction t; unfold balanced; resetI; apply_instance theorem balanced_sz.symm {l r : ℕ} : balanced_sz l r → balanced_sz r l := or.imp (by rw add_comm; exact id) and.symm theorem balanced_sz_zero {l : ℕ} : balanced_sz l 0 ↔ l ≤ 1 := by simp [balanced_sz] { contextual := tt } theorem balanced_sz_up {l r₁ r₂ : ℕ} (h₁ : r₁ ≤ r₂) (h₂ : l + r₂ ≤ 1 ∨ r₂ ≤ delta * l) (H : balanced_sz l r₁) : balanced_sz l r₂ := begin refine or_iff_not_imp_left.2 (λ h, _), refine ⟨_, h₂.resolve_left h⟩, cases H, { cases r₂, { cases h (le_trans (nat.add_le_add_left (nat.zero_le _) _) H) }, { exact le_trans (le_trans (nat.le_add_right _ _) H) (nat.le_add_left 1 _) } }, { exact le_trans H.1 (nat.mul_le_mul_left _ h₁) } end theorem balanced_sz_down {l r₁ r₂ : ℕ} (h₁ : r₁ ≤ r₂) (h₂ : l + r₂ ≤ 1 ∨ l ≤ delta * r₁) (H : balanced_sz l r₂) : balanced_sz l r₁ := have l + r₂ ≤ 1 → balanced_sz l r₁, from λ H, or.inl (le_trans (nat.add_le_add_left h₁ _) H), or.cases_on H this (λ H, or.cases_on h₂ this (λ h₂, or.inr ⟨h₂, le_trans h₁ H.2⟩)) theorem balanced.dual : ∀ {t : ordnode α}, balanced t → balanced (dual t) | nil h := ⟨⟩ | (node s l x r) ⟨b, bl, br⟩ := ⟨by rw [size_dual, size_dual]; exact b.symm, br.dual, bl.dual⟩ /-! ### `rotate` and `balance` -/ /-- Build a tree from three nodes, left associated (ignores the invariants). -/ def node3_l (l : ordnode α) (x : α) (m : ordnode α) (y : α) (r : ordnode α) : ordnode α := node' (node' l x m) y r /-- Build a tree from three nodes, right associated (ignores the invariants). -/ def node3_r (l : ordnode α) (x : α) (m : ordnode α) (y : α) (r : ordnode α) : ordnode α := node' l x (node' m y r) /-- Build a tree from three nodes, with `a () b -> (a ()) b` and `a (b c) d -> ((a b) (c d))`. -/ def node4_l : ordnode α → α → ordnode α → α → ordnode α → ordnode α | l x (node _ ml y mr) z r := node' (node' l x ml) y (node' mr z r) | l x nil z r := node3_l l x nil z r -- should not happen /-- Build a tree from three nodes, with `a () b -> a (() b)` and `a (b c) d -> ((a b) (c d))`. -/ def node4_r : ordnode α → α → ordnode α → α → ordnode α → ordnode α | l x (node _ ml y mr) z r := node' (node' l x ml) y (node' mr z r) | l x nil z r := node3_r l x nil z r -- should not happen /-- Concatenate two nodes, performing a left rotation `x (y z) -> ((x y) z)` if balance is upset. -/ def rotate_l : ordnode α → α → ordnode α → ordnode α | l x (node _ m y r) := if size m < ratio * size r then node3_l l x m y r else node4_l l x m y r | l x nil := node' l x nil -- should not happen /-- Concatenate two nodes, performing a right rotation `(x y) z -> (x (y z))` if balance is upset. -/ def rotate_r : ordnode α → α → ordnode α → ordnode α | (node _ l x m) y r := if size m < ratio * size l then node3_r l x m y r else node4_r l x m y r | nil y r := node' nil y r -- should not happen /-- A left balance operation. This will rebalance a concatenation, assuming the original nodes are not too far from balanced. -/ def balance_l' (l : ordnode α) (x : α) (r : ordnode α) : ordnode α := if size l + size r ≤ 1 then node' l x r else if size l > delta * size r then rotate_r l x r else node' l x r /-- A right balance operation. This will rebalance a concatenation, assuming the original nodes are not too far from balanced. -/ def balance_r' (l : ordnode α) (x : α) (r : ordnode α) : ordnode α := if size l + size r ≤ 1 then node' l x r else if size r > delta * size l then rotate_l l x r else node' l x r /-- The full balance operation. This is the same as `balance`, but with less manual inlining. It is somewhat easier to work with this version in proofs. -/ def balance' (l : ordnode α) (x : α) (r : ordnode α) : ordnode α := if size l + size r ≤ 1 then node' l x r else if size r > delta * size l then rotate_l l x r else if size l > delta * size r then rotate_r l x r else node' l x r theorem dual_node' (l : ordnode α) (x : α) (r : ordnode α) : dual (node' l x r) = node' (dual r) x (dual l) := by simp [node', add_comm] theorem dual_node3_l (l : ordnode α) (x : α) (m : ordnode α) (y : α) (r : ordnode α) : dual (node3_l l x m y r) = node3_r (dual r) y (dual m) x (dual l) := by simp [node3_l, node3_r, dual_node'] theorem dual_node3_r (l : ordnode α) (x : α) (m : ordnode α) (y : α) (r : ordnode α) : dual (node3_r l x m y r) = node3_l (dual r) y (dual m) x (dual l) := by simp [node3_l, node3_r, dual_node'] theorem dual_node4_l (l : ordnode α) (x : α) (m : ordnode α) (y : α) (r : ordnode α) : dual (node4_l l x m y r) = node4_r (dual r) y (dual m) x (dual l) := by cases m; simp [node4_l, node4_r, dual_node3_l, dual_node'] theorem dual_node4_r (l : ordnode α) (x : α) (m : ordnode α) (y : α) (r : ordnode α) : dual (node4_r l x m y r) = node4_l (dual r) y (dual m) x (dual l) := by cases m; simp [node4_l, node4_r, dual_node3_r, dual_node'] theorem dual_rotate_l (l : ordnode α) (x : α) (r : ordnode α) : dual (rotate_l l x r) = rotate_r (dual r) x (dual l) := by cases r; simp [rotate_l, rotate_r, dual_node']; split_ifs; simp [dual_node3_l, dual_node4_l] theorem dual_rotate_r (l : ordnode α) (x : α) (r : ordnode α) : dual (rotate_r l x r) = rotate_l (dual r) x (dual l) := by rw [← dual_dual (rotate_l _ _ _), dual_rotate_l, dual_dual, dual_dual] theorem dual_balance' (l : ordnode α) (x : α) (r : ordnode α) : dual (balance' l x r) = balance' (dual r) x (dual l) := begin simp [balance', add_comm], split_ifs; simp [dual_node', dual_rotate_l, dual_rotate_r], cases delta_lt_false h_1 h_2 end theorem dual_balance_l (l : ordnode α) (x : α) (r : ordnode α) : dual (balance_l l x r) = balance_r (dual r) x (dual l) := begin unfold balance_l balance_r, cases r with rs rl rx rr, { cases l with ls ll lx lr, {refl}, cases ll with lls lll llx llr; cases lr with lrs lrl lrx lrr; dsimp only [dual]; try {refl}, split_ifs; repeat {simp [h, add_comm]} }, { cases l with ls ll lx lr, {refl}, dsimp only [dual], split_ifs, swap, {simp [add_comm]}, cases ll with lls lll llx llr; cases lr with lrs lrl lrx lrr; try {refl}, dsimp only [dual], split_ifs; simp [h, add_comm] }, end theorem dual_balance_r (l : ordnode α) (x : α) (r : ordnode α) : dual (balance_r l x r) = balance_l (dual r) x (dual l) := by rw [← dual_dual (balance_l _ _ _), dual_balance_l, dual_dual, dual_dual] theorem sized.node3_l {l x m y r} (hl : @sized α l) (hm : sized m) (hr : sized r) : sized (node3_l l x m y r) := (hl.node' hm).node' hr theorem sized.node3_r {l x m y r} (hl : @sized α l) (hm : sized m) (hr : sized r) : sized (node3_r l x m y r) := hl.node' (hm.node' hr) theorem sized.node4_l {l x m y r} (hl : @sized α l) (hm : sized m) (hr : sized r) : sized (node4_l l x m y r) := by cases m; [exact (hl.node' hm).node' hr, exact (hl.node' hm.2.1).node' (hm.2.2.node' hr)] theorem node3_l_size {l x m y r} : size (@node3_l α l x m y r) = size l + size m + size r + 2 := by dsimp [node3_l, node', size]; rw add_right_comm _ 1 theorem node3_r_size {l x m y r} : size (@node3_r α l x m y r) = size l + size m + size r + 2 := by dsimp [node3_r, node', size]; rw [← add_assoc, ← add_assoc] theorem node4_l_size {l x m y r} (hm : sized m) : size (@node4_l α l x m y r) = size l + size m + size r + 2 := by cases m; simp [node4_l, node3_l, node', add_comm, add_left_comm]; [skip, simp [size, hm.1]]; rw [← add_assoc, ← bit0]; simp [add_comm, add_left_comm] theorem sized.dual : ∀ {t : ordnode α} (h : sized t), sized (dual t) | nil h := ⟨⟩ | (node s l x r) ⟨rfl, sl, sr⟩ := ⟨by simp [size_dual, add_comm], sized.dual sr, sized.dual sl⟩ theorem sized.dual_iff {t : ordnode α} : sized (dual t) ↔ sized t := ⟨λ h, by rw ← dual_dual t; exact h.dual, sized.dual⟩ theorem sized.rotate_l {l x r} (hl : @sized α l) (hr : sized r) : sized (rotate_l l x r) := begin cases r, {exact hl.node' hr}, rw rotate_l, split_ifs, { exact hl.node3_l hr.2.1 hr.2.2 }, { exact hl.node4_l hr.2.1 hr.2.2 } end theorem sized.rotate_r {l x r} (hl : @sized α l) (hr : sized r) : sized (rotate_r l x r) := sized.dual_iff.1 $ by rw dual_rotate_r; exact hr.dual.rotate_l hl.dual theorem sized.rotate_l_size {l x r} (hm : sized r) : size (@rotate_l α l x r) = size l + size r + 1 := begin cases r; simp [rotate_l], simp [size, hm.1, add_comm, add_left_comm], rw [← add_assoc, ← bit0], simp, split_ifs; simp [node3_l_size, node4_l_size hm.2.1, add_comm, add_left_comm] end theorem sized.rotate_r_size {l x r} (hl : sized l) : size (@rotate_r α l x r) = size l + size r + 1 := by rw [← size_dual, dual_rotate_r, hl.dual.rotate_l_size, size_dual, size_dual, add_comm (size l)] theorem sized.balance' {l x r} (hl : @sized α l) (hr : sized r) : sized (balance' l x r) := begin unfold balance', split_ifs, { exact hl.node' hr }, { exact hl.rotate_l hr }, { exact hl.rotate_r hr }, { exact hl.node' hr } end theorem size_balance' {l x r} (hl : @sized α l) (hr : sized r) : size (@balance' α l x r) = size l + size r + 1 := begin unfold balance', split_ifs, { refl }, { exact hr.rotate_l_size }, { exact hl.rotate_r_size }, { refl } end /-! ## `all`, `any`, `emem`, `amem` -/ theorem all.imp {P Q : α → Prop} (H : ∀ a, P a → Q a) : ∀ {t}, all P t → all Q t | nil h := ⟨⟩ | (node _ l x r) ⟨h₁, h₂, h₃⟩ := ⟨h₁.imp, H _ h₂, h₃.imp⟩ theorem any.imp {P Q : α → Prop} (H : ∀ a, P a → Q a) : ∀ {t}, any P t → any Q t | nil := id | (node _ l x r) := or.imp any.imp $ or.imp (H _) any.imp theorem all_singleton {P : α → Prop} {x : α} : all P (singleton x) ↔ P x := ⟨λ h, h.2.1, λ h, ⟨⟨⟩, h, ⟨⟩⟩⟩ theorem any_singleton {P : α → Prop} {x : α} : any P (singleton x) ↔ P x := ⟨by rintro (⟨⟨⟩⟩ | h | ⟨⟨⟩⟩); exact h, λ h, or.inr (or.inl h)⟩ theorem all_dual {P : α → Prop} : ∀ {t : ordnode α}, all P (dual t) ↔ all P t | nil := iff.rfl | (node s l x r) := ⟨λ ⟨hr, hx, hl⟩, ⟨all_dual.1 hl, hx, all_dual.1 hr⟩, λ ⟨hl, hx, hr⟩, ⟨all_dual.2 hr, hx, all_dual.2 hl⟩⟩ theorem all_iff_forall {P : α → Prop} : ∀ {t}, all P t ↔ ∀ x, emem x t → P x | nil := (iff_true_intro $ by rintro _ ⟨⟩).symm | (node _ l x r) := by simp [all, emem, all_iff_forall, any, or_imp_distrib, forall_and_distrib] theorem any_iff_exists {P : α → Prop} : ∀ {t}, any P t ↔ ∃ x, emem x t ∧ P x | nil := ⟨by rintro ⟨⟩, by rintro ⟨_, ⟨⟩, _⟩⟩ | (node _ l x r) := by simp [any, emem, any_iff_exists, or_and_distrib_right, exists_or_distrib] theorem emem_iff_all {x : α} {t} : emem x t ↔ ∀ P, all P t → P x := ⟨λ h P al, all_iff_forall.1 al _ h, λ H, H _ $ all_iff_forall.2 $ λ _, id⟩ theorem all_node' {P l x r} : @all α P (node' l x r) ↔ all P l ∧ P x ∧ all P r := iff.rfl theorem all_node3_l {P l x m y r} : @all α P (node3_l l x m y r) ↔ all P l ∧ P x ∧ all P m ∧ P y ∧ all P r := by simp [node3_l, all_node', and_assoc] theorem all_node3_r {P l x m y r} : @all α P (node3_r l x m y r) ↔ all P l ∧ P x ∧ all P m ∧ P y ∧ all P r := iff.rfl theorem all_node4_l {P l x m y r} : @all α P (node4_l l x m y r) ↔ all P l ∧ P x ∧ all P m ∧ P y ∧ all P r := by cases m; simp [node4_l, all_node', all, all_node3_l, and_assoc] theorem all_node4_r {P l x m y r} : @all α P (node4_r l x m y r) ↔ all P l ∧ P x ∧ all P m ∧ P y ∧ all P r := by cases m; simp [node4_r, all_node', all, all_node3_r, and_assoc] theorem all_rotate_l {P l x r} : @all α P (rotate_l l x r) ↔ all P l ∧ P x ∧ all P r := by cases r; simp [rotate_l, all_node']; split_ifs; simp [all_node3_l, all_node4_l, all] theorem all_rotate_r {P l x r} : @all α P (rotate_r l x r) ↔ all P l ∧ P x ∧ all P r := by rw [← all_dual, dual_rotate_r, all_rotate_l]; simp [all_dual, and_comm, and.left_comm] theorem all_balance' {P l x r} : @all α P (balance' l x r) ↔ all P l ∧ P x ∧ all P r := by rw balance'; split_ifs; simp [all_node', all_rotate_l, all_rotate_r] /-! ### `to_list` -/ theorem foldr_cons_eq_to_list : ∀ (t : ordnode α) (r : list α), t.foldr list.cons r = to_list t ++ r | nil r := rfl | (node _ l x r) r' := by rw [foldr, foldr_cons_eq_to_list, foldr_cons_eq_to_list, ← list.cons_append, ← list.append_assoc, ← foldr_cons_eq_to_list]; refl @[simp] theorem to_list_nil : to_list (@nil α) = [] := rfl @[simp] theorem to_list_node (s l x r) : to_list (@node α s l x r) = to_list l ++ x :: to_list r := by rw [to_list, foldr, foldr_cons_eq_to_list]; refl theorem emem_iff_mem_to_list {x : α} {t} : emem x t ↔ x ∈ to_list t := by unfold emem; induction t; simp [any, *, or_assoc] theorem length_to_list' : ∀ t : ordnode α, (to_list t).length = t.real_size | nil := rfl | (node _ l _ r) := by rw [to_list_node, list.length_append, list.length_cons, length_to_list', length_to_list']; refl theorem length_to_list {t : ordnode α} (h : sized t) : (to_list t).length = t.size := by rw [length_to_list', size_eq_real_size h] theorem equiv_iff {t₁ t₂ : ordnode α} (h₁ : sized t₁) (h₂ : sized t₂) : equiv t₁ t₂ ↔ to_list t₁ = to_list t₂ := and_iff_right_of_imp $ λ h, by rw [← length_to_list h₁, h, length_to_list h₂] /-! ### `mem` -/ theorem pos_size_of_mem [has_le α] [@decidable_rel α (≤)] {x : α} {t : ordnode α} (h : sized t) (h_mem : x ∈ t) : 0 < size t := by { cases t, { contradiction }, { simp [h.1] } } /-! ### `(find/erase/split)_(min/max)` -/ theorem find_min'_dual : ∀ t (x : α), find_min' (dual t) x = find_max' x t | nil x := rfl | (node _ l x r) _ := find_min'_dual r x theorem find_max'_dual (t) (x : α) : find_max' x (dual t) = find_min' t x := by rw [← find_min'_dual, dual_dual] theorem find_min_dual : ∀ t : ordnode α, find_min (dual t) = find_max t | nil := rfl | (node _ l x r) := congr_arg some $ find_min'_dual _ _ theorem find_max_dual (t : ordnode α) : find_max (dual t) = find_min t := by rw [← find_min_dual, dual_dual] theorem dual_erase_min : ∀ t : ordnode α, dual (erase_min t) = erase_max (dual t) | nil := rfl | (node _ nil x r) := rfl | (node _ l@(node _ _ _ _) x r) := by rw [erase_min, dual_balance_r, dual_erase_min, dual, dual, dual, erase_max] theorem dual_erase_max (t : ordnode α) : dual (erase_max t) = erase_min (dual t) := by rw [← dual_dual (erase_min _), dual_erase_min, dual_dual] theorem split_min_eq : ∀ s l (x : α) r, split_min' l x r = (find_min' l x, erase_min (node s l x r)) | _ nil x r := rfl | _ (node ls ll lx lr) x r := by rw [split_min', split_min_eq, split_min', find_min', erase_min] theorem split_max_eq : ∀ s l (x : α) r, split_max' l x r = (erase_max (node s l x r), find_max' x r) | _ l x nil := rfl | _ l x (node ls ll lx lr) := by rw [split_max', split_max_eq, split_max', find_max', erase_max] @[elab_as_eliminator] theorem find_min'_all {P : α → Prop} : ∀ t (x : α), all P t → P x → P (find_min' t x) | nil x h hx := hx | (node _ ll lx lr) x ⟨h₁, h₂, h₃⟩ hx := find_min'_all _ _ h₁ h₂ @[elab_as_eliminator] theorem find_max'_all {P : α → Prop} : ∀ (x : α) t, P x → all P t → P (find_max' x t) | x nil hx h := hx | x (node _ ll lx lr) hx ⟨h₁, h₂, h₃⟩ := find_max'_all _ _ h₂ h₃ /-! ### `glue` -/ /-! ### `merge` -/ @[simp] theorem merge_nil_left (t : ordnode α) : merge t nil = t := by cases t; refl @[simp] theorem merge_nil_right (t : ordnode α) : merge nil t = t := rfl @[simp] theorem merge_node {ls ll lx lr rs rl rx rr} : merge (@node α ls ll lx lr) (node rs rl rx rr) = if delta * ls < rs then balance_l (merge (node ls ll lx lr) rl) rx rr else if delta * rs < ls then balance_r ll lx (merge lr (node rs rl rx rr)) else glue (node ls ll lx lr) (node rs rl rx rr) := rfl /-! ### `insert` -/ theorem dual_insert [preorder α] [is_total α (≤)] [@decidable_rel α (≤)] (x : α) : ∀ t : ordnode α, dual (ordnode.insert x t) = @ordnode.insert αᵒᵈ _ _ x (dual t) | nil := rfl | (node _ l y r) := begin have : @cmp_le αᵒᵈ _ _ x y = cmp_le y x := rfl, rw [ordnode.insert, dual, ordnode.insert, this, ← cmp_le_swap x y], cases cmp_le x y; simp [ordering.swap, ordnode.insert, dual_balance_l, dual_balance_r, dual_insert] end /-! ### `balance` properties -/ theorem balance_eq_balance' {l x r} (hl : balanced l) (hr : balanced r) (sl : sized l) (sr : sized r) : @balance α l x r = balance' l x r := begin cases l with ls ll lx lr, { cases r with rs rl rx rr, { refl }, { rw sr.eq_node' at hr ⊢, cases rl with rls rll rlx rlr; cases rr with rrs rrl rrx rrr; dsimp [balance, balance'], { refl }, { have : size rrl = 0 ∧ size rrr = 0, { have := balanced_sz_zero.1 hr.1.symm, rwa [size, sr.2.2.1, nat.succ_le_succ_iff, nat.le_zero_iff, add_eq_zero_iff] at this }, cases sr.2.2.2.1.size_eq_zero.1 this.1, cases sr.2.2.2.2.size_eq_zero.1 this.2, obtain rfl : rrs = 1 := sr.2.2.1, rw [if_neg, if_pos, rotate_l, if_pos], {refl}, all_goals {exact dec_trivial} }, { have : size rll = 0 ∧ size rlr = 0, { have := balanced_sz_zero.1 hr.1, rwa [size, sr.2.1.1, nat.succ_le_succ_iff, nat.le_zero_iff, add_eq_zero_iff] at this }, cases sr.2.1.2.1.size_eq_zero.1 this.1, cases sr.2.1.2.2.size_eq_zero.1 this.2, obtain rfl : rls = 1 := sr.2.1.1, rw [if_neg, if_pos, rotate_l, if_neg], {refl}, all_goals {exact dec_trivial} }, { symmetry, rw [zero_add, if_neg, if_pos, rotate_l], { split_ifs, { simp [node3_l, node', add_comm, add_left_comm] }, { simp [node4_l, node', sr.2.1.1, add_comm, add_left_comm] } }, { exact dec_trivial }, { exact not_le_of_gt (nat.succ_lt_succ (add_pos sr.2.1.pos sr.2.2.pos)) } } } }, { cases r with rs rl rx rr, { rw sl.eq_node' at hl ⊢, cases ll with lls lll llx llr; cases lr with lrs lrl lrx lrr; dsimp [balance, balance'], { refl }, { have : size lrl = 0 ∧ size lrr = 0, { have := balanced_sz_zero.1 hl.1.symm, rwa [size, sl.2.2.1, nat.succ_le_succ_iff, nat.le_zero_iff, add_eq_zero_iff] at this }, cases sl.2.2.2.1.size_eq_zero.1 this.1, cases sl.2.2.2.2.size_eq_zero.1 this.2, obtain rfl : lrs = 1 := sl.2.2.1, rw [if_neg, if_neg, if_pos, rotate_r, if_neg], {refl}, all_goals {exact dec_trivial} }, { have : size lll = 0 ∧ size llr = 0, { have := balanced_sz_zero.1 hl.1, rwa [size, sl.2.1.1, nat.succ_le_succ_iff, nat.le_zero_iff, add_eq_zero_iff] at this }, cases sl.2.1.2.1.size_eq_zero.1 this.1, cases sl.2.1.2.2.size_eq_zero.1 this.2, obtain rfl : lls = 1 := sl.2.1.1, rw [if_neg, if_neg, if_pos, rotate_r, if_pos], {refl}, all_goals {exact dec_trivial} }, { symmetry, rw [if_neg, if_neg, if_pos, rotate_r], { split_ifs, { simp [node3_r, node', add_comm, add_left_comm] }, { simp [node4_r, node', sl.2.2.1, add_comm, add_left_comm] } }, { exact dec_trivial }, { exact dec_trivial }, { exact not_le_of_gt (nat.succ_lt_succ (add_pos sl.2.1.pos sl.2.2.pos)) } } }, { simp [balance, balance'], symmetry, rw [if_neg], { split_ifs, { have rd : delta ≤ size rl + size rr, { have := lt_of_le_of_lt (nat.mul_le_mul_left _ sl.pos) h, rwa [sr.1, nat.lt_succ_iff] at this }, cases rl with rls rll rlx rlr, { rw [size, zero_add] at rd, exact absurd (le_trans rd (balanced_sz_zero.1 hr.1.symm)) dec_trivial }, cases rr with rrs rrl rrx rrr, { exact absurd (le_trans rd (balanced_sz_zero.1 hr.1)) dec_trivial }, dsimp [rotate_l], split_ifs, { simp [node3_l, node', sr.1, add_comm, add_left_comm] }, { simp [node4_l, node', sr.1, sr.2.1.1, add_comm, add_left_comm] } }, { have ld : delta ≤ size ll + size lr, { have := lt_of_le_of_lt (nat.mul_le_mul_left _ sr.pos) h_1, rwa [sl.1, nat.lt_succ_iff] at this }, cases ll with lls lll llx llr, { rw [size, zero_add] at ld, exact absurd (le_trans ld (balanced_sz_zero.1 hl.1.symm)) dec_trivial }, cases lr with lrs lrl lrx lrr, { exact absurd (le_trans ld (balanced_sz_zero.1 hl.1)) dec_trivial }, dsimp [rotate_r], split_ifs, { simp [node3_r, node', sl.1, add_comm, add_left_comm] }, { simp [node4_r, node', sl.1, sl.2.2.1, add_comm, add_left_comm] } }, { simp [node'] } }, { exact not_le_of_gt (add_le_add sl.pos sr.pos : 2 ≤ ls + rs) } } } end theorem balance_l_eq_balance {l x r} (sl : sized l) (sr : sized r) (H1 : size l = 0 → size r ≤ 1) (H2 : 1 ≤ size l → 1 ≤ size r → size r ≤ delta * size l) : @balance_l α l x r = balance l x r := begin cases r with rs rl rx rr, { refl }, { cases l with ls ll lx lr, { have : size rl = 0 ∧ size rr = 0, { have := H1 rfl, rwa [size, sr.1, nat.succ_le_succ_iff, nat.le_zero_iff, add_eq_zero_iff] at this }, cases sr.2.1.size_eq_zero.1 this.1, cases sr.2.2.size_eq_zero.1 this.2, rw sr.eq_node', refl }, { replace H2 : ¬ rs > delta * ls := not_lt_of_le (H2 sl.pos sr.pos), simp [balance_l, balance, H2]; split_ifs; simp [add_comm] } } end /-- `raised n m` means `m` is either equal or one up from `n`. -/ def raised (n m : ℕ) : Prop := m = n ∨ m = n + 1 theorem raised_iff {n m} : raised n m ↔ n ≤ m ∧ m ≤ n + 1 := begin split, rintro (rfl | rfl), { exact ⟨le_rfl, nat.le_succ _⟩ }, { exact ⟨nat.le_succ _, le_rfl⟩ }, { rintro ⟨h₁, h₂⟩, rcases eq_or_lt_of_le h₁ with rfl | h₁, { exact or.inl rfl }, { exact or.inr (le_antisymm h₂ h₁) } } end theorem raised.dist_le {n m} (H : raised n m) : nat.dist n m ≤ 1 := by cases raised_iff.1 H with H1 H2; rwa [nat.dist_eq_sub_of_le H1, tsub_le_iff_left] theorem raised.dist_le' {n m} (H : raised n m) : nat.dist m n ≤ 1 := by rw nat.dist_comm; exact H.dist_le theorem raised.add_left (k) {n m} (H : raised n m) : raised (k + n) (k + m) := begin rcases H with rfl | rfl, { exact or.inl rfl }, { exact or.inr rfl } end theorem raised.add_right (k) {n m} (H : raised n m) : raised (n + k) (m + k) := by rw [add_comm, add_comm m]; exact H.add_left _ theorem raised.right {l x₁ x₂ r₁ r₂} (H : raised (size r₁) (size r₂)) : raised (size (@node' α l x₁ r₁)) (size (@node' α l x₂ r₂)) := begin dsimp [node', size], generalize_hyp : size r₂ = m at H ⊢, rcases H with rfl | rfl, { exact or.inl rfl }, { exact or.inr rfl } end theorem balance_l_eq_balance' {l x r} (hl : balanced l) (hr : balanced r) (sl : sized l) (sr : sized r) (H : (∃ l', raised l' (size l) ∧ balanced_sz l' (size r)) ∨ (∃ r', raised (size r) r' ∧ balanced_sz (size l) r')) : @balance_l α l x r = balance' l x r := begin rw [← balance_eq_balance' hl hr sl sr, balance_l_eq_balance sl sr], { intro l0, rw l0 at H, rcases H with ⟨_, ⟨⟨⟩⟩|⟨⟨⟩⟩, H⟩ | ⟨r', e, H⟩, { exact balanced_sz_zero.1 H.symm }, exact le_trans (raised_iff.1 e).1 (balanced_sz_zero.1 H.symm) }, { intros l1 r1, rcases H with ⟨l', e, H | ⟨H₁, H₂⟩⟩ | ⟨r', e, H | ⟨H₁, H₂⟩⟩, { exact le_trans (le_trans (nat.le_add_left _ _) H) (mul_pos dec_trivial l1 : (0:ℕ)<_) }, { exact le_trans H₂ (nat.mul_le_mul_left _ (raised_iff.1 e).1) }, { cases raised_iff.1 e, unfold delta, linarith }, { exact le_trans (raised_iff.1 e).1 H₂ } } end theorem balance_sz_dual {l r} (H : (∃ l', raised (@size α l) l' ∧ balanced_sz l' (@size α r)) ∨ ∃ r', raised r' (size r) ∧ balanced_sz (size l) r') : (∃ l', raised l' (size (dual r)) ∧ balanced_sz l' (size (dual l))) ∨ ∃ r', raised (size (dual l)) r' ∧ balanced_sz (size (dual r)) r' := begin rw [size_dual, size_dual], exact H.symm.imp (Exists.imp $ λ _, and.imp_right balanced_sz.symm) (Exists.imp $ λ _, and.imp_right balanced_sz.symm) end theorem size_balance_l {l x r} (hl : balanced l) (hr : balanced r) (sl : sized l) (sr : sized r) (H : (∃ l', raised l' (size l) ∧ balanced_sz l' (size r)) ∨ (∃ r', raised (size r) r' ∧ balanced_sz (size l) r')) : size (@balance_l α l x r) = size l + size r + 1 := by rw [balance_l_eq_balance' hl hr sl sr H, size_balance' sl sr] theorem all_balance_l {P l x r} (hl : balanced l) (hr : balanced r) (sl : sized l) (sr : sized r) (H : (∃ l', raised l' (size l) ∧ balanced_sz l' (size r)) ∨ (∃ r', raised (size r) r' ∧ balanced_sz (size l) r')) : all P (@balance_l α l x r) ↔ all P l ∧ P x ∧ all P r := by rw [balance_l_eq_balance' hl hr sl sr H, all_balance'] theorem balance_r_eq_balance' {l x r} (hl : balanced l) (hr : balanced r) (sl : sized l) (sr : sized r) (H : (∃ l', raised (size l) l' ∧ balanced_sz l' (size r)) ∨ (∃ r', raised r' (size r) ∧ balanced_sz (size l) r')) : @balance_r α l x r = balance' l x r := by rw [← dual_dual (balance_r l x r), dual_balance_r, balance_l_eq_balance' hr.dual hl.dual sr.dual sl.dual (balance_sz_dual H), ← dual_balance', dual_dual] theorem size_balance_r {l x r} (hl : balanced l) (hr : balanced r) (sl : sized l) (sr : sized r) (H : (∃ l', raised (size l) l' ∧ balanced_sz l' (size r)) ∨ (∃ r', raised r' (size r) ∧ balanced_sz (size l) r')) : size (@balance_r α l x r) = size l + size r + 1 := by rw [balance_r_eq_balance' hl hr sl sr H, size_balance' sl sr] theorem all_balance_r {P l x r} (hl : balanced l) (hr : balanced r) (sl : sized l) (sr : sized r) (H : (∃ l', raised (size l) l' ∧ balanced_sz l' (size r)) ∨ (∃ r', raised r' (size r) ∧ balanced_sz (size l) r')) : all P (@balance_r α l x r) ↔ all P l ∧ P x ∧ all P r := by rw [balance_r_eq_balance' hl hr sl sr H, all_balance'] /-! ### `bounded` -/ section variable [preorder α] /-- `bounded t lo hi` says that every element `x ∈ t` is in the range `lo < x < hi`, and also this property holds recursively in subtrees, making the full tree a BST. The bounds can be set to `lo = ⊥` and `hi = ⊤` if we care only about the internal ordering constraints. -/ def bounded : ordnode α → with_bot α → with_top α → Prop | nil (some a) (some b) := a < b | nil _ _ := true | (node _ l x r) o₁ o₂ := bounded l o₁ ↑x ∧ bounded r ↑x o₂ theorem bounded.dual : ∀ {t : ordnode α} {o₁ o₂} (h : bounded t o₁ o₂), @bounded αᵒᵈ _ (dual t) o₂ o₁ | nil o₁ o₂ h := by cases o₁; cases o₂; try {trivial}; exact h | (node s l x r) _ _ ⟨ol, or⟩ := ⟨or.dual, ol.dual⟩ theorem bounded.dual_iff {t : ordnode α} {o₁ o₂} : bounded t o₁ o₂ ↔ @bounded αᵒᵈ _ (dual t) o₂ o₁ := ⟨bounded.dual, λ h, by have := bounded.dual h; rwa [dual_dual, order_dual.preorder.dual_dual] at this⟩ theorem bounded.weak_left : ∀ {t : ordnode α} {o₁ o₂}, bounded t o₁ o₂ → bounded t ⊥ o₂ | nil o₁ o₂ h := by cases o₂; try {trivial}; exact h | (node s l x r) _ _ ⟨ol, or⟩ := ⟨ol.weak_left, or⟩ theorem bounded.weak_right : ∀ {t : ordnode α} {o₁ o₂}, bounded t o₁ o₂ → bounded t o₁ ⊤ | nil o₁ o₂ h := by cases o₁; try {trivial}; exact h | (node s l x r) _ _ ⟨ol, or⟩ := ⟨ol, or.weak_right⟩ theorem bounded.weak {t : ordnode α} {o₁ o₂} (h : bounded t o₁ o₂) : bounded t ⊥ ⊤ := h.weak_left.weak_right theorem bounded.mono_left {x y : α} (xy : x ≤ y) : ∀ {t : ordnode α} {o}, bounded t ↑y o → bounded t ↑x o | nil none h := ⟨⟩ | nil (some z) h := lt_of_le_of_lt xy h | (node s l z r) o ⟨ol, or⟩ := ⟨ol.mono_left, or⟩ theorem bounded.mono_right {x y : α} (xy : x ≤ y) : ∀ {t : ordnode α} {o}, bounded t o ↑x → bounded t o ↑y | nil none h := ⟨⟩ | nil (some z) h := lt_of_lt_of_le h xy | (node s l z r) o ⟨ol, or⟩ := ⟨ol, or.mono_right⟩ theorem bounded.to_lt : ∀ {t : ordnode α} {x y : α}, bounded t x y → x < y | nil x y h := h | (node _ l y r) x z ⟨h₁, h₂⟩ := lt_trans h₁.to_lt h₂.to_lt theorem bounded.to_nil {t : ordnode α} : ∀ {o₁ o₂}, bounded t o₁ o₂ → bounded nil o₁ o₂ | none _ h := ⟨⟩ | (some _) none h := ⟨⟩ | (some x) (some y) h := h.to_lt theorem bounded.trans_left {t₁ t₂ : ordnode α} {x : α} : ∀ {o₁ o₂}, bounded t₁ o₁ ↑x → bounded t₂ ↑x o₂ → bounded t₂ o₁ o₂ | none o₂ h₁ h₂ := h₂.weak_left | (some y) o₂ h₁ h₂ := h₂.mono_left (le_of_lt h₁.to_lt) theorem bounded.trans_right {t₁ t₂ : ordnode α} {x : α} : ∀ {o₁ o₂}, bounded t₁ o₁ ↑x → bounded t₂ ↑x o₂ → bounded t₁ o₁ o₂ | o₁ none h₁ h₂ := h₁.weak_right | o₁ (some y) h₁ h₂ := h₁.mono_right (le_of_lt h₂.to_lt) theorem bounded.mem_lt : ∀ {t o} {x : α}, bounded t o ↑x → all (< x) t | nil o x _ := ⟨⟩ | (node _ l y r) o x ⟨h₁, h₂⟩ := ⟨h₁.mem_lt.imp (λ z h, lt_trans h h₂.to_lt), h₂.to_lt, h₂.mem_lt⟩ theorem bounded.mem_gt : ∀ {t o} {x : α}, bounded t ↑x o → all (> x) t | nil o x _ := ⟨⟩ | (node _ l y r) o x ⟨h₁, h₂⟩ := ⟨h₁.mem_gt, h₁.to_lt, h₂.mem_gt.imp (λ z, lt_trans h₁.to_lt)⟩ theorem bounded.of_lt : ∀ {t o₁ o₂} {x : α}, bounded t o₁ o₂ → bounded nil o₁ ↑x → all (< x) t → bounded t o₁ ↑x | nil o₁ o₂ x _ hn _ := hn | (node _ l y r) o₁ o₂ x ⟨h₁, h₂⟩ hn ⟨al₁, al₂, al₃⟩ := ⟨h₁, h₂.of_lt al₂ al₃⟩ theorem bounded.of_gt : ∀ {t o₁ o₂} {x : α}, bounded t o₁ o₂ → bounded nil ↑x o₂ → all (> x) t → bounded t ↑x o₂ | nil o₁ o₂ x _ hn _ := hn | (node _ l y r) o₁ o₂ x ⟨h₁, h₂⟩ hn ⟨al₁, al₂, al₃⟩ := ⟨h₁.of_gt al₂ al₁, h₂⟩ theorem bounded.to_sep {t₁ t₂ o₁ o₂} {x : α} (h₁ : bounded t₁ o₁ ↑x) (h₂ : bounded t₂ ↑x o₂) : t₁.all (λ y, t₂.all (λ z : α, y < z)) := h₁.mem_lt.imp $ λ y yx, h₂.mem_gt.imp $ λ z xz, lt_trans yx xz end /-! ### `valid` -/ section variable [preorder α] /-- The validity predicate for an `ordnode` subtree. This asserts that the `size` fields are correct, the tree is balanced, and the elements of the tree are organized according to the ordering. This version of `valid` also puts all elements in the tree in the interval `(lo, hi)`. -/ structure valid' (lo : with_bot α) (t : ordnode α) (hi : with_top α) : Prop := (ord : t.bounded lo hi) (sz : t.sized) (bal : t.balanced) /-- The validity predicate for an `ordnode` subtree. This asserts that the `size` fields are correct, the tree is balanced, and the elements of the tree are organized according to the ordering. -/ def valid (t : ordnode α) : Prop := valid' ⊥ t ⊤ theorem valid'.mono_left {x y : α} (xy : x ≤ y) {t : ordnode α} {o} (h : valid' ↑y t o) : valid' ↑x t o := ⟨h.1.mono_left xy, h.2, h.3⟩ theorem valid'.mono_right {x y : α} (xy : x ≤ y) {t : ordnode α} {o} (h : valid' o t ↑x) : valid' o t ↑y := ⟨h.1.mono_right xy, h.2, h.3⟩ theorem valid'.trans_left {t₁ t₂ : ordnode α} {x : α} {o₁ o₂} (h : bounded t₁ o₁ ↑x) (H : valid' ↑x t₂ o₂) : valid' o₁ t₂ o₂ := ⟨h.trans_left H.1, H.2, H.3⟩ theorem valid'.trans_right {t₁ t₂ : ordnode α} {x : α} {o₁ o₂} (H : valid' o₁ t₁ ↑x) (h : bounded t₂ ↑x o₂) : valid' o₁ t₁ o₂ := ⟨H.1.trans_right h, H.2, H.3⟩ theorem valid'.of_lt {t : ordnode α} {x : α} {o₁ o₂} (H : valid' o₁ t o₂) (h₁ : bounded nil o₁ ↑x) (h₂ : all (< x) t) : valid' o₁ t ↑x := ⟨H.1.of_lt h₁ h₂, H.2, H.3⟩ theorem valid'.of_gt {t : ordnode α} {x : α} {o₁ o₂} (H : valid' o₁ t o₂) (h₁ : bounded nil ↑x o₂) (h₂ : all (> x) t) : valid' ↑x t o₂ := ⟨H.1.of_gt h₁ h₂, H.2, H.3⟩ theorem valid'.valid {t o₁ o₂} (h : @valid' α _ o₁ t o₂) : valid t := ⟨h.1.weak, h.2, h.3⟩ theorem valid'_nil {o₁ o₂} (h : bounded nil o₁ o₂) : valid' o₁ (@nil α) o₂ := ⟨h, ⟨⟩, ⟨⟩⟩ theorem valid_nil : valid (@nil α) := valid'_nil ⟨⟩ theorem valid'.node {s l x r o₁ o₂} (hl : valid' o₁ l ↑x) (hr : valid' ↑x r o₂) (H : balanced_sz (size l) (size r)) (hs : s = size l + size r + 1) : valid' o₁ (@node α s l x r) o₂ := ⟨⟨hl.1, hr.1⟩, ⟨hs, hl.2, hr.2⟩, ⟨H, hl.3, hr.3⟩⟩ theorem valid'.dual : ∀ {t : ordnode α} {o₁ o₂} (h : valid' o₁ t o₂), @valid' αᵒᵈ _ o₂ (dual t) o₁ | nil o₁ o₂ h := valid'_nil h.1.dual | (node s l x r) o₁ o₂ ⟨⟨ol, or⟩, ⟨rfl, sl, sr⟩, ⟨b, bl, br⟩⟩ := let ⟨ol', sl', bl'⟩ := valid'.dual ⟨ol, sl, bl⟩, ⟨or', sr', br'⟩ := valid'.dual ⟨or, sr, br⟩ in ⟨⟨or', ol'⟩, ⟨by simp [size_dual, add_comm], sr', sl'⟩, ⟨by rw [size_dual, size_dual]; exact b.symm, br', bl'⟩⟩ theorem valid'.dual_iff {t : ordnode α} {o₁ o₂} : valid' o₁ t o₂ ↔ @valid' αᵒᵈ _ o₂ (dual t) o₁ := ⟨valid'.dual, λ h, by have := valid'.dual h; rwa [dual_dual, order_dual.preorder.dual_dual] at this⟩ theorem valid.dual {t : ordnode α} : valid t → @valid αᵒᵈ _ (dual t) := valid'.dual theorem valid.dual_iff {t : ordnode α} : valid t ↔ @valid αᵒᵈ _ (dual t) := valid'.dual_iff theorem valid'.left {s l x r o₁ o₂} (H : valid' o₁ (@node α s l x r) o₂) : valid' o₁ l x := ⟨H.1.1, H.2.2.1, H.3.2.1⟩ theorem valid'.right {s l x r o₁ o₂} (H : valid' o₁ (@node α s l x r) o₂) : valid' ↑x r o₂ := ⟨H.1.2, H.2.2.2, H.3.2.2⟩ theorem valid.left {s l x r} (H : valid (@node α s l x r)) : valid l := H.left.valid theorem valid.right {s l x r} (H : valid (@node α s l x r)) : valid r := H.right.valid theorem valid.size_eq {s l x r} (H : valid (@node α s l x r)) : size (@node α s l x r) = size l + size r + 1 := H.2.1 theorem valid'.node' {l x r o₁ o₂} (hl : valid' o₁ l ↑x) (hr : valid' ↑x r o₂) (H : balanced_sz (size l) (size r)) : valid' o₁ (@node' α l x r) o₂ := hl.node hr H rfl theorem valid'_singleton {x : α} {o₁ o₂} (h₁ : bounded nil o₁ ↑x) (h₂ : bounded nil ↑x o₂) : valid' o₁ (singleton x : ordnode α) o₂ := (valid'_nil h₁).node (valid'_nil h₂) (or.inl zero_le_one) rfl theorem valid_singleton {x : α} : valid (singleton x : ordnode α) := valid'_singleton ⟨⟩ ⟨⟩ theorem valid'.node3_l {l x m y r o₁ o₂} (hl : valid' o₁ l ↑x) (hm : valid' ↑x m ↑y) (hr : valid' ↑y r o₂) (H1 : balanced_sz (size l) (size m)) (H2 : balanced_sz (size l + size m + 1) (size r)) : valid' o₁ (@node3_l α l x m y r) o₂ := (hl.node' hm H1).node' hr H2 theorem valid'.node3_r {l x m y r o₁ o₂} (hl : valid' o₁ l ↑x) (hm : valid' ↑x m ↑y) (hr : valid' ↑y r o₂) (H1 : balanced_sz (size l) (size m + size r + 1)) (H2 : balanced_sz (size m) (size r)) : valid' o₁ (@node3_r α l x m y r) o₂ := hl.node' (hm.node' hr H2) H1 theorem valid'.node4_l_lemma₁ {a b c d : ℕ} (lr₂ : 3 * (b + c + 1 + d) ≤ 16 * a + 9) (mr₂ : b + c + 1 ≤ 3 * d) (mm₁ : b ≤ 3 * c) : b < 3 * a + 1 := by linarith theorem valid'.node4_l_lemma₂ {b c d : ℕ} (mr₂ : b + c + 1 ≤ 3 * d) : c ≤ 3 * d := by linarith theorem valid'.node4_l_lemma₃ {b c d : ℕ} (mr₁ : 2 * d ≤ b + c + 1) (mm₁ : b ≤ 3 * c) : d ≤ 3 * c := by linarith theorem valid'.node4_l_lemma₄ {a b c d : ℕ} (lr₁ : 3 * a ≤ b + c + 1 + d) (mr₂ : b + c + 1 ≤ 3 * d) (mm₁ : b ≤ 3 * c) : a + b + 1 ≤ 3 * (c + d + 1) := by linarith theorem valid'.node4_l_lemma₅ {a b c d : ℕ} (lr₂ : 3 * (b + c + 1 + d) ≤ 16 * a + 9) (mr₁ : 2 * d ≤ b + c + 1) (mm₂ : c ≤ 3 * b) : c + d + 1 ≤ 3 * (a + b + 1) := by linarith theorem valid'.node4_l {l x m y r o₁ o₂} (hl : valid' o₁ l ↑x) (hm : valid' ↑x m ↑y) (hr : valid' ↑y r o₂) (Hm : 0 < size m) (H : (size l = 0 ∧ size m = 1 ∧ size r ≤ 1) ∨ (0 < size l ∧ ratio * size r ≤ size m ∧ delta * size l ≤ size m + size r ∧ 3 * (size m + size r) ≤ 16 * size l + 9 ∧ size m ≤ delta * size r)) : valid' o₁ (@node4_l α l x m y r) o₂ := begin cases m with s ml z mr, {cases Hm}, suffices : balanced_sz (size l) (size ml) ∧ balanced_sz (size mr) (size r) ∧ balanced_sz (size l + size ml + 1) (size mr + size r + 1), from (valid'.node' (hl.node' hm.left this.1) (hm.right.node' hr this.2.1) this.2.2), rcases H with ⟨l0, m1, r0⟩ | ⟨l0, mr₁, lr₁, lr₂, mr₂⟩, { rw [hm.2.size_eq, nat.succ_inj', add_eq_zero_iff] at m1, rw [l0, m1.1, m1.2], rcases size r with _|_|_; exact dec_trivial }, { cases nat.eq_zero_or_pos (size r) with r0 r0, { rw r0 at mr₂, cases not_le_of_lt Hm mr₂ }, rw [hm.2.size_eq] at lr₁ lr₂ mr₁ mr₂, by_cases mm : size ml + size mr ≤ 1, { have r1 := le_antisymm ((mul_le_mul_left dec_trivial).1 (le_trans mr₁ (nat.succ_le_succ mm) : _ ≤ ratio * 1)) r0, rw [r1, add_assoc] at lr₁, have l1 := le_antisymm ((mul_le_mul_left dec_trivial).1 (le_trans lr₁ (add_le_add_right mm 2) : _ ≤ delta * 1)) l0, rw [l1, r1], cases size ml; cases size mr, { exact dec_trivial }, { rw zero_add at mm, rcases mm with _|⟨_,⟨⟩⟩, exact dec_trivial }, { rcases mm with _|⟨_,⟨⟩⟩, exact dec_trivial }, { rw nat.succ_add at mm, rcases mm with _|⟨_,⟨⟩⟩ } }, rcases hm.3.1.resolve_left mm with ⟨mm₁, mm₂⟩, cases nat.eq_zero_or_pos (size ml) with ml0 ml0, { rw [ml0, mul_zero, nat.le_zero_iff] at mm₂, rw [ml0, mm₂] at mm, cases mm dec_trivial }, have : 2 * size l ≤ size ml + size mr + 1, { have := nat.mul_le_mul_left _ lr₁, rw [mul_left_comm, mul_add] at this, have := le_trans this (add_le_add_left mr₁ _), rw [← nat.succ_mul] at this, exact (mul_le_mul_left dec_trivial).1 this }, refine ⟨or.inr ⟨_, _⟩, or.inr ⟨_, _⟩, or.inr ⟨_, _⟩⟩, { refine (mul_le_mul_left dec_trivial).1 (le_trans this _), rw [two_mul, nat.succ_le_iff], refine add_lt_add_of_lt_of_le _ mm₂, simpa using (mul_lt_mul_right ml0).2 (dec_trivial:1<3) }, { exact nat.le_of_lt_succ (valid'.node4_l_lemma₁ lr₂ mr₂ mm₁) }, { exact valid'.node4_l_lemma₂ mr₂ }, { exact valid'.node4_l_lemma₃ mr₁ mm₁ }, { exact valid'.node4_l_lemma₄ lr₁ mr₂ mm₁ }, { exact valid'.node4_l_lemma₅ lr₂ mr₁ mm₂ } } end theorem valid'.rotate_l_lemma₁ {a b c : ℕ} (H2 : 3 * a ≤ b + c) (hb₂ : c ≤ 3 * b) : a ≤ 3 * b := by linarith theorem valid'.rotate_l_lemma₂ {a b c : ℕ} (H3 : 2 * (b + c) ≤ 9 * a + 3) (h : b < 2 * c) : b < 3 * a + 1 := by linarith theorem valid'.rotate_l_lemma₃ {a b c : ℕ} (H2 : 3 * a ≤ b + c) (h : b < 2 * c) : a + b < 3 * c := by linarith theorem valid'.rotate_l_lemma₄ {a b : ℕ} (H3 : 2 * b ≤ 9 * a + 3) : 3 * b ≤ 16 * a + 9 := by linarith theorem valid'.rotate_l {l x r o₁ o₂} (hl : valid' o₁ l ↑x) (hr : valid' ↑x r o₂) (H1 : ¬ size l + size r ≤ 1) (H2 : delta * size l < size r) (H3 : 2 * size r ≤ 9 * size l + 5 ∨ size r ≤ 3) : valid' o₁ (@rotate_l α l x r) o₂ := begin cases r with rs rl rx rr, {cases H2}, rw [hr.2.size_eq, nat.lt_succ_iff] at H2, rw [hr.2.size_eq] at H3, replace H3 : 2 * (size rl + size rr) ≤ 9 * size l + 3 ∨ size rl + size rr ≤ 2 := H3.imp (@nat.le_of_add_le_add_right 2 _ _) nat.le_of_succ_le_succ, have H3_0 : size l = 0 → size rl + size rr ≤ 2, { intro l0, rw l0 at H3, exact (or_iff_right_of_imp $ by exact λ h, (mul_le_mul_left dec_trivial).1 (le_trans h dec_trivial)).1 H3 }, have H3p : size l > 0 → 2 * (size rl + size rr) ≤ 9 * size l + 3 := λ l0 : 1 ≤ size l, (or_iff_left_of_imp $ by intro; linarith).1 H3, have ablem : ∀ {a b : ℕ}, 1 ≤ a → a + b ≤ 2 → b ≤ 1, {intros, linarith}, have hlp : size l > 0 → ¬ size rl + size rr ≤ 1 := λ l0 hb, absurd (le_trans (le_trans (nat.mul_le_mul_left _ l0) H2) hb) dec_trivial, rw rotate_l, split_ifs, { have rr0 : size rr > 0 := (mul_lt_mul_left dec_trivial).1 (lt_of_le_of_lt (nat.zero_le _) h : ratio * 0 < _), suffices : balanced_sz (size l) (size rl) ∧ balanced_sz (size l + size rl + 1) (size rr), { exact hl.node3_l hr.left hr.right this.1 this.2 }, cases nat.eq_zero_or_pos (size l) with l0 l0, { rw l0, replace H3 := H3_0 l0, have := hr.3.1, cases nat.eq_zero_or_pos (size rl) with rl0 rl0, { rw rl0 at this ⊢, rw le_antisymm (balanced_sz_zero.1 this.symm) rr0, exact dec_trivial }, have rr1 : size rr = 1 := le_antisymm (ablem rl0 H3) rr0, rw add_comm at H3, rw [rr1, show size rl = 1, from le_antisymm (ablem rr0 H3) rl0], exact dec_trivial }, replace H3 := H3p l0, rcases hr.3.1.resolve_left (hlp l0) with ⟨hb₁, hb₂⟩, refine ⟨or.inr ⟨_, _⟩, or.inr ⟨_, _⟩⟩, { exact valid'.rotate_l_lemma₁ H2 hb₂ }, { exact nat.le_of_lt_succ (valid'.rotate_l_lemma₂ H3 h) }, { exact valid'.rotate_l_lemma₃ H2 h }, { exact le_trans hb₂ (nat.mul_le_mul_left _ $ le_trans (nat.le_add_left _ _) (nat.le_add_right _ _)) } }, { cases nat.eq_zero_or_pos (size rl) with rl0 rl0, { rw [rl0, not_lt, nat.le_zero_iff, nat.mul_eq_zero] at h, replace h := h.resolve_left dec_trivial, rw [rl0, h, nat.le_zero_iff, nat.mul_eq_zero] at H2, rw [hr.2.size_eq, rl0, h, H2.resolve_left dec_trivial] at H1, cases H1 dec_trivial }, refine hl.node4_l hr.left hr.right rl0 _, cases nat.eq_zero_or_pos (size l) with l0 l0, { replace H3 := H3_0 l0, cases nat.eq_zero_or_pos (size rr) with rr0 rr0, { have := hr.3.1, rw rr0 at this, exact or.inl ⟨l0, le_antisymm (balanced_sz_zero.1 this) rl0, rr0.symm ▸ zero_le_one⟩ }, exact or.inl ⟨l0, le_antisymm (ablem rr0 $ by rwa add_comm) rl0, ablem rl0 H3⟩ }, exact or.inr ⟨l0, not_lt.1 h, H2, valid'.rotate_l_lemma₄ (H3p l0), (hr.3.1.resolve_left (hlp l0)).1⟩ } end theorem valid'.rotate_r {l x r o₁ o₂} (hl : valid' o₁ l ↑x) (hr : valid' ↑x r o₂) (H1 : ¬ size l + size r ≤ 1) (H2 : delta * size r < size l) (H3 : 2 * size l ≤ 9 * size r + 5 ∨ size l ≤ 3) : valid' o₁ (@rotate_r α l x r) o₂ := begin refine valid'.dual_iff.2 _, rw dual_rotate_r, refine hr.dual.rotate_l hl.dual _ _ _, { rwa [size_dual, size_dual, add_comm] }, { rwa [size_dual, size_dual] }, { rwa [size_dual, size_dual] } end theorem valid'.balance'_aux {l x r o₁ o₂} (hl : valid' o₁ l ↑x) (hr : valid' ↑x r o₂) (H₁ : 2 * @size α r ≤ 9 * size l + 5 ∨ size r ≤ 3) (H₂ : 2 * @size α l ≤ 9 * size r + 5 ∨ size l ≤ 3) : valid' o₁ (@balance' α l x r) o₂ := begin rw balance', split_ifs, { exact hl.node' hr (or.inl h) }, { exact hl.rotate_l hr h h_1 H₁ }, { exact hl.rotate_r hr h h_2 H₂ }, { exact hl.node' hr (or.inr ⟨not_lt.1 h_2, not_lt.1 h_1⟩) } end theorem valid'.balance'_lemma {α l l' r r'} (H1 : balanced_sz l' r') (H2 : nat.dist (@size α l) l' ≤ 1 ∧ size r = r' ∨ nat.dist (size r) r' ≤ 1 ∧ size l = l') : 2 * @size α r ≤ 9 * size l + 5 ∨ size r ≤ 3 := begin suffices : @size α r ≤ 3 * (size l + 1), { cases nat.eq_zero_or_pos (size l) with l0 l0, { apply or.inr, rwa l0 at this }, change 1 ≤ _ at l0, apply or.inl, linarith }, rcases H2 with ⟨hl, rfl⟩ | ⟨hr, rfl⟩; rcases H1 with h | ⟨h₁, h₂⟩, { exact le_trans (nat.le_add_left _ _) (le_trans h (nat.le_add_left _ _)) }, { exact le_trans h₂ (nat.mul_le_mul_left _ $ le_trans (nat.dist_tri_right _ _) (nat.add_le_add_left hl _)) }, { exact le_trans (nat.dist_tri_left' _ _) (le_trans (add_le_add hr (le_trans (nat.le_add_left _ _) h)) dec_trivial) }, { rw nat.mul_succ, exact le_trans (nat.dist_tri_right' _ _) (add_le_add h₂ (le_trans hr dec_trivial)) }, end theorem valid'.balance' {l x r o₁ o₂} (hl : valid' o₁ l ↑x) (hr : valid' ↑x r o₂) (H : ∃ l' r', balanced_sz l' r' ∧ (nat.dist (size l) l' ≤ 1 ∧ size r = r' ∨ nat.dist (size r) r' ≤ 1 ∧ size l = l')) : valid' o₁ (@balance' α l x r) o₂ := let ⟨l', r', H1, H2⟩ := H in valid'.balance'_aux hl hr (valid'.balance'_lemma H1 H2) (valid'.balance'_lemma H1.symm H2.symm) theorem valid'.balance {l x r o₁ o₂} (hl : valid' o₁ l ↑x) (hr : valid' ↑x r o₂) (H : ∃ l' r', balanced_sz l' r' ∧ (nat.dist (size l) l' ≤ 1 ∧ size r = r' ∨ nat.dist (size r) r' ≤ 1 ∧ size l = l')) : valid' o₁ (@balance α l x r) o₂ := by rw balance_eq_balance' hl.3 hr.3 hl.2 hr.2; exact hl.balance' hr H theorem valid'.balance_l_aux {l x r o₁ o₂} (hl : valid' o₁ l ↑x) (hr : valid' ↑x r o₂) (H₁ : size l = 0 → size r ≤ 1) (H₂ : 1 ≤ size l → 1 ≤ size r → size r ≤ delta * size l) (H₃ : 2 * @size α l ≤ 9 * size r + 5 ∨ size l ≤ 3) : valid' o₁ (@balance_l α l x r) o₂ := begin rw [balance_l_eq_balance hl.2 hr.2 H₁ H₂, balance_eq_balance' hl.3 hr.3 hl.2 hr.2], refine hl.balance'_aux hr (or.inl _) H₃, cases nat.eq_zero_or_pos (size r) with r0 r0, { rw r0, exact nat.zero_le _ }, cases nat.eq_zero_or_pos (size l) with l0 l0, { rw l0, exact le_trans (nat.mul_le_mul_left _ (H₁ l0)) dec_trivial }, replace H₂ : _ ≤ 3 * _ := H₂ l0 r0, linarith end theorem valid'.balance_l {l x r o₁ o₂} (hl : valid' o₁ l ↑x) (hr : valid' ↑x r o₂) (H : (∃ l', raised l' (size l) ∧ balanced_sz l' (size r)) ∨ (∃ r', raised (size r) r' ∧ balanced_sz (size l) r')) : valid' o₁ (@balance_l α l x r) o₂ := begin rw balance_l_eq_balance' hl.3 hr.3 hl.2 hr.2 H, refine hl.balance' hr _, rcases H with ⟨l', e, H⟩ | ⟨r', e, H⟩, { exact ⟨_, _, H, or.inl ⟨e.dist_le', rfl⟩⟩ }, { exact ⟨_, _, H, or.inr ⟨e.dist_le, rfl⟩⟩ }, end theorem valid'.balance_r_aux {l x r o₁ o₂} (hl : valid' o₁ l ↑x) (hr : valid' ↑x r o₂) (H₁ : size r = 0 → size l ≤ 1) (H₂ : 1 ≤ size r → 1 ≤ size l → size l ≤ delta * size r) (H₃ : 2 * @size α r ≤ 9 * size l + 5 ∨ size r ≤ 3) : valid' o₁ (@balance_r α l x r) o₂ := begin rw [valid'.dual_iff, dual_balance_r], have := hr.dual.balance_l_aux hl.dual, rw [size_dual, size_dual] at this, exact this H₁ H₂ H₃ end theorem valid'.balance_r {l x r o₁ o₂} (hl : valid' o₁ l ↑x) (hr : valid' ↑x r o₂) (H : (∃ l', raised (size l) l' ∧ balanced_sz l' (size r)) ∨ (∃ r', raised r' (size r) ∧ balanced_sz (size l) r')) : valid' o₁ (@balance_r α l x r) o₂ := by rw [valid'.dual_iff, dual_balance_r]; exact hr.dual.balance_l hl.dual (balance_sz_dual H) theorem valid'.erase_max_aux {s l x r o₁ o₂} (H : valid' o₁ (node s l x r) o₂) : valid' o₁ (@erase_max α (node' l x r)) ↑(find_max' x r) ∧ size (node' l x r) = size (erase_max (node' l x r)) + 1 := begin have := H.2.eq_node', rw this at H, clear this, induction r with rs rl rx rr IHrl IHrr generalizing l x o₁, { exact ⟨H.left, rfl⟩ }, have := H.2.2.2.eq_node', rw this at H ⊢, rcases IHrr H.right with ⟨h, e⟩, refine ⟨valid'.balance_l H.left h (or.inr ⟨_, or.inr e, H.3.1⟩), _⟩, rw [erase_max, size_balance_l H.3.2.1 h.3 H.2.2.1 h.2 (or.inr ⟨_, or.inr e, H.3.1⟩)], rw [size, e], refl end theorem valid'.erase_min_aux {s l x r o₁ o₂} (H : valid' o₁ (node s l x r) o₂) : valid' ↑(find_min' l x) (@erase_min α (node' l x r)) o₂ ∧ size (node' l x r) = size (erase_min (node' l x r)) + 1 := by have := H.dual.erase_max_aux; rwa [← dual_node', size_dual, ← dual_erase_min, size_dual, ← valid'.dual_iff, find_max'_dual] at this theorem erase_min.valid : ∀ {t} (h : @valid α _ t), valid (erase_min t) | nil _ := valid_nil | (node _ l x r) h := by rw h.2.eq_node'; exact h.erase_min_aux.1.valid theorem erase_max.valid {t} (h : @valid α _ t) : valid (erase_max t) := by rw [valid.dual_iff, dual_erase_max]; exact erase_min.valid h.dual theorem valid'.glue_aux {l r o₁ o₂} (hl : valid' o₁ l o₂) (hr : valid' o₁ r o₂) (sep : l.all (λ x, r.all (λ y, x < y))) (bal : balanced_sz (size l) (size r)) : valid' o₁ (@glue α l r) o₂ ∧ size (glue l r) = size l + size r := begin cases l with ls ll lx lr, {exact ⟨hr, (zero_add _).symm⟩ }, cases r with rs rl rx rr, {exact ⟨hl, rfl⟩ }, dsimp [glue], split_ifs, { rw [split_max_eq, glue], cases valid'.erase_max_aux hl with v e, suffices H, refine ⟨valid'.balance_r v (hr.of_gt _ _) H, _⟩, { refine find_max'_all lx lr hl.1.2.to_nil (sep.2.2.imp _), exact λ x h, hr.1.2.to_nil.mono_left (le_of_lt h.2.1) }, { exact @find_max'_all _ (λ a, all (> a) (node rs rl rx rr)) lx lr sep.2.1 sep.2.2 }, { rw [size_balance_r v.3 hr.3 v.2 hr.2 H, add_right_comm, ← e, hl.2.1], refl }, { refine or.inl ⟨_, or.inr e, _⟩, rwa hl.2.eq_node' at bal } }, { rw [split_min_eq, glue], cases valid'.erase_min_aux hr with v e, suffices H, refine ⟨valid'.balance_l (hl.of_lt _ _) v H, _⟩, { refine @find_min'_all _ (λ a, bounded nil o₁ ↑a) rl rx (sep.2.1.1.imp _) hr.1.1.to_nil, exact λ y h, hl.1.1.to_nil.mono_right (le_of_lt h) }, { exact @find_min'_all _ (λ a, all (< a) (node ls ll lx lr)) rl rx (all_iff_forall.2 $ λ x hx, sep.imp $ λ y hy, all_iff_forall.1 hy.1 _ hx) (sep.imp $ λ y hy, hy.2.1) }, { rw [size_balance_l hl.3 v.3 hl.2 v.2 H, add_assoc, ← e, hr.2.1], refl }, { refine or.inr ⟨_, or.inr e, _⟩, rwa hr.2.eq_node' at bal } }, end theorem valid'.glue {l x r o₁ o₂} (hl : valid' o₁ l ↑(x:α)) (hr : valid' ↑x r o₂) : balanced_sz (size l) (size r) → valid' o₁ (@glue α l r) o₂ ∧ size (@glue α l r) = size l + size r := valid'.glue_aux (hl.trans_right hr.1) (hr.trans_left hl.1) (hl.1.to_sep hr.1) theorem valid'.merge_lemma {a b c : ℕ} (h₁ : 3 * a < b + c + 1) (h₂ : b ≤ 3 * c) : 2 * (a + b) ≤ 9 * c + 5 := by linarith theorem valid'.merge_aux₁ {o₁ o₂ ls ll lx lr rs rl rx rr t} (hl : valid' o₁ (@node α ls ll lx lr) o₂) (hr : valid' o₁ (node rs rl rx rr) o₂) (h : delta * ls < rs) (v : valid' o₁ t ↑rx) (e : size t = ls + size rl) : valid' o₁ (balance_l t rx rr) o₂ ∧ size (balance_l t rx rr) = ls + rs := begin rw hl.2.1 at e, rw [hl.2.1, hr.2.1, delta] at h, rcases hr.3.1 with H|⟨hr₁, hr₂⟩, {linarith}, suffices H₂, suffices H₁, refine ⟨valid'.balance_l_aux v hr.right H₁ H₂ _, _⟩, { rw e, exact or.inl (valid'.merge_lemma h hr₁) }, { rw [balance_l_eq_balance v.2 hr.2.2.2 H₁ H₂, balance_eq_balance' v.3 hr.3.2.2 v.2 hr.2.2.2, size_balance' v.2 hr.2.2.2, e, hl.2.1, hr.2.1], simp [add_comm, add_left_comm] }, { rw [e, add_right_comm], rintro ⟨⟩ }, { intros _ h₁, rw e, unfold delta at hr₂ ⊢, linarith } end theorem valid'.merge_aux {l r o₁ o₂} (hl : valid' o₁ l o₂) (hr : valid' o₁ r o₂) (sep : l.all (λ x, r.all (λ y, x < y))) : valid' o₁ (@merge α l r) o₂ ∧ size (merge l r) = size l + size r := begin induction l with ls ll lx lr IHll IHlr generalizing o₁ o₂ r, { exact ⟨hr, (zero_add _).symm⟩ }, induction r with rs rl rx rr IHrl IHrr generalizing o₁ o₂, { exact ⟨hl, rfl⟩ }, rw [merge_node], split_ifs, { cases IHrl (sep.imp $ λ x h, h.1) (hl.of_lt hr.1.1.to_nil $ sep.imp $ λ x h, h.2.1) hr.left with v e, exact valid'.merge_aux₁ hl hr h v e }, { cases IHlr hl.right (hr.of_gt hl.1.2.to_nil sep.2.1) sep.2.2 with v e, have := valid'.merge_aux₁ hr.dual hl.dual h_1 v.dual, rw [size_dual, add_comm, size_dual, ← dual_balance_r, ← valid'.dual_iff, size_dual, add_comm rs] at this, exact this e }, { refine valid'.glue_aux hl hr sep (or.inr ⟨not_lt.1 h_1, not_lt.1 h⟩) } end theorem valid.merge {l r} (hl : valid l) (hr : valid r) (sep : l.all (λ x, r.all (λ y, x < y))) : valid (@merge α l r) := (valid'.merge_aux hl hr sep).1 theorem insert_with.valid_aux [is_total α (≤)] [@decidable_rel α (≤)] (f : α → α) (x : α) (hf : ∀ y, x ≤ y ∧ y ≤ x → x ≤ f y ∧ f y ≤ x) : ∀ {t o₁ o₂}, valid' o₁ t o₂ → bounded nil o₁ ↑x → bounded nil ↑x o₂ → valid' o₁ (insert_with f x t) o₂ ∧ raised (size t) (size (insert_with f x t)) | nil o₁ o₂ _ bl br := ⟨valid'_singleton bl br, or.inr rfl⟩ | (node sz l y r) o₁ o₂ h bl br := begin rw [insert_with, cmp_le], split_ifs; rw [insert_with], { rcases h with ⟨⟨lx, xr⟩, hs, hb⟩, rcases hf _ ⟨h_1, h_2⟩ with ⟨xf, fx⟩, refine ⟨⟨⟨lx.mono_right (le_trans h_2 xf), xr.mono_left (le_trans fx h_1)⟩, hs, hb⟩, or.inl rfl⟩ }, { rcases insert_with.valid_aux h.left bl (lt_of_le_not_le h_1 h_2) with ⟨vl, e⟩, suffices H, { refine ⟨vl.balance_l h.right H, _⟩, rw [size_balance_l vl.3 h.3.2.2 vl.2 h.2.2.2 H, h.2.size_eq], refine (e.add_right _).add_right _ }, { exact or.inl ⟨_, e, h.3.1⟩ } }, { have : y < x := lt_of_le_not_le ((total_of (≤) _ _).resolve_left h_1) h_1, rcases insert_with.valid_aux h.right this br with ⟨vr, e⟩, suffices H, { refine ⟨h.left.balance_r vr H, _⟩, rw [size_balance_r h.3.2.1 vr.3 h.2.2.1 vr.2 H, h.2.size_eq], refine (e.add_left _).add_right _ }, { exact or.inr ⟨_, e, h.3.1⟩ } }, end theorem insert_with.valid [is_total α (≤)] [@decidable_rel α (≤)] (f : α → α) (x : α) (hf : ∀ y, x ≤ y ∧ y ≤ x → x ≤ f y ∧ f y ≤ x) {t} (h : valid t) : valid (insert_with f x t) := (insert_with.valid_aux _ _ hf h ⟨⟩ ⟨⟩).1 theorem insert_eq_insert_with [@decidable_rel α (≤)] (x : α) : ∀ t, ordnode.insert x t = insert_with (λ _, x) x t | nil := rfl | (node _ l y r) := by unfold ordnode.insert insert_with; cases cmp_le x y; unfold ordnode.insert insert_with; simp [insert_eq_insert_with] theorem insert.valid [is_total α (≤)] [@decidable_rel α (≤)] (x : α) {t} (h : valid t) : valid (ordnode.insert x t) := by rw insert_eq_insert_with; exact insert_with.valid _ _ (λ _ _, ⟨le_rfl, le_rfl⟩) h theorem insert'_eq_insert_with [@decidable_rel α (≤)] (x : α) : ∀ t, insert' x t = insert_with id x t | nil := rfl | (node _ l y r) := by unfold insert' insert_with; cases cmp_le x y; unfold insert' insert_with; simp [insert'_eq_insert_with] theorem insert'.valid [is_total α (≤)] [@decidable_rel α (≤)] (x : α) {t} (h : valid t) : valid (insert' x t) := by rw insert'_eq_insert_with; exact insert_with.valid _ _ (λ _, id) h theorem valid'.map_aux {β} [preorder β] {f : α → β} (f_strict_mono : strict_mono f) {t a₁ a₂} (h : valid' a₁ t a₂) : valid' (option.map f a₁) (map f t) (option.map f a₂) ∧ (map f t).size = t.size := begin induction t generalizing a₁ a₂, { simp [map], apply valid'_nil, cases a₁, { trivial }, cases a₂, { trivial }, simp [bounded], exact f_strict_mono h.ord }, { have t_ih_l' := t_ih_l h.left, have t_ih_r' := t_ih_r h.right, clear t_ih_l t_ih_r, cases t_ih_l' with t_l_valid t_l_size, cases t_ih_r' with t_r_valid t_r_size, simp [map], split, { exact and.intro t_l_valid.ord t_r_valid.ord }, { repeat { split }, { rw [t_l_size, t_r_size], exact h.sz.1 }, { exact t_l_valid.sz }, { exact t_r_valid.sz } }, { repeat { split }, { rw [t_l_size, t_r_size], exact h.bal.1 }, { exact t_l_valid.bal }, { exact t_r_valid.bal } } }, end theorem map.valid {β} [preorder β] {f : α → β} (f_strict_mono : strict_mono f) {t} (h : valid t) : valid (map f t) := (valid'.map_aux f_strict_mono h).1 theorem valid'.erase_aux [@decidable_rel α (≤)] (x : α) {t a₁ a₂} (h : valid' a₁ t a₂) : valid' a₁ (erase x t) a₂ ∧ raised (erase x t).size t.size := begin induction t generalizing a₁ a₂, { simp [erase, raised], exact h }, { simp [erase], have t_ih_l' := t_ih_l h.left, have t_ih_r' := t_ih_r h.right, clear t_ih_l t_ih_r, cases t_ih_l' with t_l_valid t_l_size, cases t_ih_r' with t_r_valid t_r_size, cases (cmp_le x t_x); simp [erase._match_1]; rw h.sz.1, { suffices h_balanceable, split, { exact valid'.balance_r t_l_valid h.right h_balanceable }, { rw size_balance_r t_l_valid.bal h.right.bal t_l_valid.sz h.right.sz h_balanceable, repeat { apply raised.add_right }, exact t_l_size }, { left, existsi t_l.size, exact (and.intro t_l_size h.bal.1) } }, { have h_glue := valid'.glue h.left h.right h.bal.1, cases h_glue with h_glue_valid h_glue_sized, split, { exact h_glue_valid }, { right, rw h_glue_sized } }, { suffices h_balanceable, split, { exact valid'.balance_l h.left t_r_valid h_balanceable }, { rw size_balance_l h.left.bal t_r_valid.bal h.left.sz t_r_valid.sz h_balanceable, apply raised.add_right, apply raised.add_left, exact t_r_size }, { right, existsi t_r.size, exact (and.intro t_r_size h.bal.1) } } }, end theorem erase.valid [@decidable_rel α (≤)] (x : α) {t} (h : valid t) : valid (erase x t) := (valid'.erase_aux x h).1 theorem size_erase_of_mem [@decidable_rel α (≤)] {x : α} {t a₁ a₂} (h : valid' a₁ t a₂) (h_mem : x ∈ t) : size (erase x t) = size t - 1 := begin induction t generalizing a₁ a₂ h h_mem, { contradiction }, { have t_ih_l' := t_ih_l h.left, have t_ih_r' := t_ih_r h.right, clear t_ih_l t_ih_r, unfold has_mem.mem mem at h_mem, unfold erase, cases (cmp_le x t_x); simp [mem._match_1] at h_mem; simp [erase._match_1], { have t_ih_l := t_ih_l' h_mem, clear t_ih_l' t_ih_r', have t_l_h := valid'.erase_aux x h.left, cases t_l_h with t_l_valid t_l_size, rw size_balance_r t_l_valid.bal h.right.bal t_l_valid.sz h.right.sz (or.inl (exists.intro t_l.size (and.intro t_l_size h.bal.1))), rw [t_ih_l, h.sz.1], have h_pos_t_l_size := pos_size_of_mem h.left.sz h_mem, cases t_l.size with t_l_size, { cases h_pos_t_l_size }, simp [nat.succ_add] }, { rw [(valid'.glue h.left h.right h.bal.1).2, h.sz.1], refl }, { have t_ih_r := t_ih_r' h_mem, clear t_ih_l' t_ih_r', have t_r_h := valid'.erase_aux x h.right, cases t_r_h with t_r_valid t_r_size, rw size_balance_l h.left.bal t_r_valid.bal h.left.sz t_r_valid.sz (or.inr (exists.intro t_r.size (and.intro t_r_size h.bal.1))), rw [t_ih_r, h.sz.1], have h_pos_t_r_size := pos_size_of_mem h.right.sz h_mem, cases t_r.size with t_r_size, { cases h_pos_t_r_size }, simp [nat.succ_add, nat.add_succ] } }, end end end ordnode /-- An `ordset α` is a finite set of values, represented as a tree. The operations on this type maintain that the tree is balanced and correctly stores subtree sizes at each level. The correctness property of the tree is baked into the type, so all operations on this type are correct by construction. -/ def ordset (α : Type*) [preorder α] := {t : ordnode α // t.valid} namespace ordset open ordnode variable [preorder α] /-- O(1). The empty set. -/ def nil : ordset α := ⟨nil, ⟨⟩, ⟨⟩, ⟨⟩⟩ /-- O(1). Get the size of the set. -/ def size (s : ordset α) : ℕ := s.1.size /-- O(1). Construct a singleton set containing value `a`. -/ protected def singleton (a : α) : ordset α := ⟨singleton a, valid_singleton⟩ instance : has_emptyc (ordset α) := ⟨nil⟩ instance : inhabited (ordset α) := ⟨nil⟩ instance : has_singleton α (ordset α) := ⟨ordset.singleton⟩ /-- O(1). Is the set empty? -/ def empty (s : ordset α) : Prop := s = ∅ theorem empty_iff {s : ordset α} : s = ∅ ↔ s.1.empty := ⟨λ h, by cases h; exact rfl, λ h, by cases s; cases s_val; [exact rfl, cases h]⟩ instance : decidable_pred (@empty α _) := λ s, decidable_of_iff' _ empty_iff /-- O(log n). Insert an element into the set, preserving balance and the BST property. If an equivalent element is already in the set, this replaces it. -/ protected def insert [is_total α (≤)] [@decidable_rel α (≤)] (x : α) (s : ordset α) : ordset α := ⟨ordnode.insert x s.1, insert.valid _ s.2⟩ instance [is_total α (≤)] [@decidable_rel α (≤)] : has_insert α (ordset α) := ⟨ordset.insert⟩ /-- O(log n). Insert an element into the set, preserving balance and the BST property. If an equivalent element is already in the set, the set is returned as is. -/ def insert' [is_total α (≤)] [@decidable_rel α (≤)] (x : α) (s : ordset α) : ordset α := ⟨insert' x s.1, insert'.valid _ s.2⟩ section variables [@decidable_rel α (≤)] /-- O(log n). Does the set contain the element `x`? That is, is there an element that is equivalent to `x` in the order? -/ def mem (x : α) (s : ordset α) : bool := x ∈ s.val /-- O(log n). Retrieve an element in the set that is equivalent to `x` in the order, if it exists. -/ def find (x : α) (s : ordset α) : option α := ordnode.find x s.val instance : has_mem α (ordset α) := ⟨λ x s, mem x s⟩ instance mem.decidable (x : α) (s : ordset α) : decidable (x ∈ s) := bool.decidable_eq _ _ theorem pos_size_of_mem {x : α} {t : ordset α} (h_mem : x ∈ t) : 0 < size t := begin simp [has_mem.mem, mem] at h_mem, apply ordnode.pos_size_of_mem t.property.sz h_mem, end end /-- O(log n). Remove an element from the set equivalent to `x`. Does nothing if there is no such element. -/ def erase [@decidable_rel α (≤)] (x : α) (s : ordset α) : ordset α := ⟨ordnode.erase x s.val, ordnode.erase.valid x s.property⟩ /-- O(n). Map a function across a tree, without changing the structure. -/ def map {β} [preorder β] (f : α → β) (f_strict_mono : strict_mono f) (s : ordset α) : ordset β := ⟨ordnode.map f s.val, ordnode.map.valid f_strict_mono s.property⟩ end ordset
831291af0afac8a61cb4c0775e7b900a5e947bdb
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/docs/tutorial/category_theory/calculating_colimits_in_Top.lean
5892030933eb5b80d142e911918aa70e66e8e863
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
3,550
lean
import topology.category.Top.limits.basic import topology.instances.real import topology.tactic /-! 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 := { to_fun := λ _, unit.star, } -- We don't need to prove continuity: this is done automatically. def I₀ : pt ⟶ I := { to_fun := λ _, ⟨(0 : ℝ), by norm_num [set.left_mem_Icc]⟩, } def I₁ : pt ⟶ I := { to_fun := λ _, ⟨(1 : ℝ), by norm_num [set.right_mem_Icc]⟩, } def cylinder (X : Top) : Top := prod X I -- To define a map to the cylinder, we give a map to each factor. -- `prod.lift` is a helper method, providing a wrapper around `limit.lift` for binary products. def cylinder₀ (X : Top) : X ⟶ cylinder X := prod.lift (𝟙 X) (to_pt X ≫ I₀) def cylinder₁ (X : Top) : X ⟶ cylinder X := prod.lift (𝟙 X) (to_pt X ≫ I₁) -- The mapping cylinder is the pushout of the diagram -- X -- ↙ ↘ -- Y (X x I) -- (`pushout` is implemented just as a wrapper around `colimit`) is def mapping_cylinder {X Y : Top} (f : X ⟶ Y) : Top := pushout f (cylinder₁ X) /-- We construct the map from `X` into the "bottom" of the mapping cylinder for `f : X ⟶ Y`, as the composition of the inclusion of `X` into the bottom of the cylinder `prod X I`, followed by the map `pushout.inr` of `prod X I` into `mapping_cylinder f`. -/ def mapping_cylinder₀ {X Y : Top} (f : X ⟶ Y) : X ⟶ mapping_cylinder f := cylinder₀ X ≫ pushout.inr /-- The mapping cone is defined as the pushout of ``` X ↙ ↘ (Cyl f) pt ``` (where the left arrow is `mapping_cylinder₀`). This makes it an iterated colimit; one could also define it in one step as the colimit of ``` -- X X -- ↙ ↘ ↙ ↘ -- Y (X x I) pt ``` -/ def mapping_cone {X Y : Top} (f : X ⟶ Y) : Top := pushout (mapping_cylinder₀ 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 := { to_fun := λ _, (0 : ℝ), } /-- Two copies of the real line glued together at 0. -/ def X : Top := pushout 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. def g : X ⟶ R := pushout.desc (𝟙 _) (𝟙 _) rfl end Gluing section Products /-- The countably infinite product of copies of `ℝ`. -/ def Y : Top := ∏ (λ n : ℕ, R) /-- We can define a point in this infinite product by specifying its coordinates. Let's define the point whose `n`-th coordinate is `n + 1` (as a real number). -/ def q : pt ⟶ Y := pi.lift (λ (n : ℕ), ⟨λ (_ : pt), (n + 1 : ℝ), by continuity⟩) -- Note that writing `Y := ∏ (λ n : ℕ, R)` gives us *some* topological space which satisfies the -- universal property of the product, not some explicit construction of the product, so we cannot -- rely on any definitional properties of `Y` or `q`. -- If we really want to talk about a specific construction of the limit, we have to work directly -- with the corresponding limit cones. In this case, `Top.limit_cone`. end Products
cd82e997774cc53e9472ec85ec769670d8de6003
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/data/fintype/big_operators.lean
d2fd5fd1565325790eb07949c34d0356adfa7dcb
[ "Apache-2.0" ]
permissive
alreadydone/mathlib
dc0be621c6c8208c581f5170a8216c5ba6721927
c982179ec21091d3e102d8a5d9f5fe06c8fafb73
refs/heads/master
1,685,523,275,196
1,670,184,141,000
1,670,184,141,000
287,574,545
0
0
Apache-2.0
1,670,290,714,000
1,597,421,623,000
Lean
UTF-8
Lean
false
false
9,954
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.fintype.option import data.fintype.powerset import data.fintype.sigma import data.fintype.sum import data.fintype.vector import algebra.big_operators.ring import algebra.big_operators.option /-! Results about "big operations" over a `fintype`, and consequent results about cardinalities of certain types. ## Implementation note This content had previously been in `data.fintype.basic`, but was moved here to avoid requiring `algebra.big_operators` (and hence many other imports) as a dependency of `fintype`. However many of the results here really belong in `algebra.big_operators.basic` and should be moved at some point. -/ universes u v variables {α : Type*} {β : Type*} {γ : Type*} open_locale big_operators namespace fintype @[to_additive] lemma prod_bool [comm_monoid α] (f : bool → α) : ∏ b, f b = f tt * f ff := by simp lemma card_eq_sum_ones {α} [fintype α] : fintype.card α = ∑ a : α, 1 := finset.card_eq_sum_ones _ section open finset variables {ι : Type*} [decidable_eq ι] [fintype ι] @[to_additive] lemma prod_extend_by_one [comm_monoid α] (s : finset ι) (f : ι → α) : ∏ i, (if i ∈ s then f i else 1) = ∏ i in s, f i := by rw [← prod_filter, filter_mem_eq_inter, univ_inter] end section variables {M : Type*} [fintype α] [comm_monoid M] @[to_additive] lemma prod_eq_one (f : α → M) (h : ∀ a, f a = 1) : (∏ a, f a) = 1 := finset.prod_eq_one $ λ a ha, h a @[to_additive] lemma prod_congr (f g : α → M) (h : ∀ a, f a = g a) : (∏ a, f a) = ∏ a, g a := finset.prod_congr rfl $ λ a ha, h a @[to_additive] lemma prod_eq_single {f : α → M} (a : α) (h : ∀ x ≠ a, f x = 1) : (∏ x, f x) = f a := finset.prod_eq_single a (λ x _ hx, h x hx) $ λ ha, (ha (finset.mem_univ a)).elim @[to_additive] lemma prod_eq_mul {f : α → M} (a b : α) (h₁ : a ≠ b) (h₂ : ∀ x, x ≠ a ∧ x ≠ b → f x = 1) : (∏ x, f x) = (f a) * (f b) := begin apply finset.prod_eq_mul a b h₁ (λ x _ hx, h₂ x hx); exact λ hc, (hc (finset.mem_univ _)).elim end /-- If a product of a `finset` of a subsingleton type has a given value, so do the terms in that product. -/ @[to_additive "If a sum of a `finset` of a subsingleton type has a given value, so do the terms in that sum."] lemma eq_of_subsingleton_of_prod_eq {ι : Type*} [subsingleton ι] {s : finset ι} {f : ι → M} {b : M} (h : ∏ i in s, f i = b) : ∀ i ∈ s, f i = b := finset.eq_of_card_le_one_of_prod_eq (finset.card_le_one_of_subsingleton s) h end end fintype open finset section variables {M : Type*} [fintype α] [comm_monoid M] @[simp, to_additive] lemma fintype.prod_option (f : option α → M) : ∏ i, f i = f none * ∏ i, f (some i) := finset.prod_insert_none f univ end open finset @[simp] theorem fintype.card_sigma {α : Type*} (β : α → Type*) [fintype α] [∀ a, fintype (β a)] : fintype.card (sigma β) = ∑ a, fintype.card (β a) := card_sigma _ _ @[simp] lemma finset.card_pi [decidable_eq α] {δ : α → Type*} (s : finset α) (t : Π a, finset (δ a)) : (s.pi t).card = ∏ a in s, card (t a) := multiset.card_pi _ _ @[simp] lemma fintype.card_pi_finset [decidable_eq α] [fintype α] {δ : α → Type*} (t : Π a, finset (δ a)) : (fintype.pi_finset t).card = ∏ a, card (t a) := by simp [fintype.pi_finset, card_map] @[simp] lemma fintype.card_pi {β : α → Type*} [decidable_eq α] [fintype α] [f : Π a, fintype (β a)] : fintype.card (Π a, β a) = ∏ a, fintype.card (β a) := fintype.card_pi_finset _ -- FIXME ouch, this should be in the main file. @[simp] lemma fintype.card_fun [decidable_eq α] [fintype α] [fintype β] : fintype.card (α → β) = fintype.card β ^ fintype.card α := by rw [fintype.card_pi, finset.prod_const]; refl @[simp] lemma card_vector [fintype α] (n : ℕ) : fintype.card (vector α n) = fintype.card α ^ n := by rw fintype.of_equiv_card; simp @[simp, to_additive] lemma finset.prod_attach_univ [fintype α] [comm_monoid β] (f : {a : α // a ∈ @univ α _} → β) : ∏ x in univ.attach, f x = ∏ x, f ⟨x, (mem_univ _)⟩ := fintype.prod_equiv (equiv.subtype_univ_equiv (λ x, mem_univ _)) _ _ (λ x, by simp) /-- Taking a product over `univ.pi t` is the same as taking the product over `fintype.pi_finset t`. `univ.pi t` and `fintype.pi_finset t` are essentially the same `finset`, but differ in the type of their element, `univ.pi t` is a `finset (Π a ∈ univ, t a)` and `fintype.pi_finset t` is a `finset (Π a, t a)`. -/ @[to_additive "Taking a sum over `univ.pi t` is the same as taking the sum over `fintype.pi_finset t`. `univ.pi t` and `fintype.pi_finset t` are essentially the same `finset`, but differ in the type of their element, `univ.pi t` is a `finset (Π a ∈ univ, t a)` and `fintype.pi_finset t` is a `finset (Π a, t a)`."] lemma finset.prod_univ_pi [decidable_eq α] [fintype α] [comm_monoid β] {δ : α → Type*} {t : Π (a : α), finset (δ a)} (f : (Π (a : α), a ∈ (univ : finset α) → δ a) → β) : ∏ x in univ.pi t, f x = ∏ x in fintype.pi_finset t, f (λ a _, x a) := prod_bij (λ x _ a, x a (mem_univ _)) (by simp) (by simp) (by simp [function.funext_iff] {contextual := tt}) (λ x hx, ⟨λ a _, x a, by simp * at *⟩) /-- The product over `univ` of a sum can be written as a sum over the product of sets, `fintype.pi_finset`. `finset.prod_sum` is an alternative statement when the product is not over `univ` -/ lemma finset.prod_univ_sum [decidable_eq α] [fintype α] [comm_semiring β] {δ : α → Type u_1} [Π (a : α), decidable_eq (δ a)] {t : Π (a : α), finset (δ a)} {f : Π (a : α), δ a → β} : ∏ a, ∑ b in t a, f a b = ∑ p in fintype.pi_finset t, ∏ x, f x (p x) := by simp only [finset.prod_attach_univ, prod_sum, finset.sum_univ_pi] /-- Summing `a^s.card * b^(n-s.card)` over all finite subsets `s` of a fintype of cardinality `n` gives `(a + b)^n`. The "good" proof involves expanding along all coordinates using the fact that `x^n` is multilinear, but multilinear maps are only available now over rings, so we give instead a proof reducing to the usual binomial theorem to have a result over semirings. -/ lemma fintype.sum_pow_mul_eq_add_pow (α : Type*) [fintype α] {R : Type*} [comm_semiring R] (a b : R) : ∑ s : finset α, a ^ s.card * b ^ (fintype.card α - s.card) = (a + b) ^ (fintype.card α) := finset.sum_pow_mul_eq_add_pow _ _ _ @[to_additive] lemma function.bijective.prod_comp [fintype α] [fintype β] [comm_monoid γ] {f : α → β} (hf : function.bijective f) (g : β → γ) : ∏ i, g (f i) = ∏ i, g i := fintype.prod_bijective f hf _ _ (λ x, rfl) @[to_additive] lemma equiv.prod_comp [fintype α] [fintype β] [comm_monoid γ] (e : α ≃ β) (f : β → γ) : ∏ i, f (e i) = ∏ i, f i := e.bijective.prod_comp f @[to_additive] lemma equiv.prod_comp' [fintype α] [fintype β] [comm_monoid γ] (e : α ≃ β) (f : α → γ) (g : β → γ) (h : ∀ i, f i = g (e i)) : ∏ i, f i = ∏ i, g i := (show f = g ∘ e, from funext h).symm ▸ e.prod_comp _ /-- It is equivalent to compute the product of a function over `fin n` or `finset.range n`. -/ @[to_additive "It is equivalent to sum a function over `fin n` or `finset.range n`."] lemma fin.prod_univ_eq_prod_range [comm_monoid α] (f : ℕ → α) (n : ℕ) : ∏ i : fin n, f i = ∏ i in range n, f i := calc (∏ i : fin n, f i) = ∏ i : {x // x ∈ range n}, f i : (fin.equiv_subtype.trans (equiv.subtype_equiv_right (by simp))).prod_comp' _ _ (by simp) ... = ∏ i in range n, f i : by rw [← attach_eq_univ, prod_attach] @[to_additive] lemma finset.prod_fin_eq_prod_range [comm_monoid β] {n : ℕ} (c : fin n → β) : ∏ i, c i = ∏ i in finset.range n, if h : i < n then c ⟨i, h⟩ else 1 := begin rw [← fin.prod_univ_eq_prod_range, finset.prod_congr rfl], rintros ⟨i, hi⟩ _, simp only [fin.coe_eq_val, hi, dif_pos] end @[to_additive] lemma finset.prod_to_finset_eq_subtype {M : Type*} [comm_monoid M] [fintype α] (p : α → Prop) [decidable_pred p] (f : α → M) : ∏ a in {x | p x}.to_finset, f a = ∏ a : subtype p, f a := by { rw ← finset.prod_subtype, simp } @[to_additive] lemma finset.prod_fiberwise [decidable_eq β] [fintype β] [comm_monoid γ] (s : finset α) (f : α → β) (g : α → γ) : ∏ b : β, ∏ a in s.filter (λ a, f a = b), g a = ∏ a in s, g a := finset.prod_fiberwise_of_maps_to (λ x _, mem_univ _) _ @[to_additive] lemma fintype.prod_fiberwise [fintype α] [decidable_eq β] [fintype β] [comm_monoid γ] (f : α → β) (g : α → γ) : (∏ b : β, ∏ a : {a // f a = b}, g (a : α)) = ∏ a, g a := begin rw [← (equiv.sigma_fiber_equiv f).prod_comp, ← univ_sigma_univ, prod_sigma], refl end lemma fintype.prod_dite [fintype α] {p : α → Prop} [decidable_pred p] [comm_monoid β] (f : Π (a : α) (ha : p a), β) (g : Π (a : α) (ha : ¬p a), β) : (∏ a, dite (p a) (f a) (g a)) = (∏ a : {a // p a}, f a a.2) * (∏ a : {a // ¬p a}, g a a.2) := begin simp only [prod_dite, attach_eq_univ], congr' 1, { convert (equiv.subtype_equiv_right _).prod_comp (λ x : {x // p x}, f x x.2), simp }, { convert (equiv.subtype_equiv_right _).prod_comp (λ x : {x // ¬p x}, g x x.2), simp } end section open finset variables {α₁ : Type*} {α₂ : Type*} {M : Type*} [fintype α₁] [fintype α₂] [comm_monoid M] @[to_additive] lemma fintype.prod_sum_elim (f : α₁ → M) (g : α₂ → M) : (∏ x, sum.elim f g x) = (∏ a₁, f a₁) * (∏ a₂, g a₂) := prod_disj_sum _ _ _ @[simp, to_additive] lemma fintype.prod_sum_type (f : α₁ ⊕ α₂ → M) : (∏ x, f x) = (∏ a₁, f (sum.inl a₁)) * (∏ a₂, f (sum.inr a₂)) := prod_disj_sum _ _ _ end
c2c2e02504f7ec92189e9849ff7da51615f48b36
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/group_theory/specific_groups/dihedral.lean
7be44e835e22337085aff5eb1d9874bb304ec01f
[ "Apache-2.0" ]
permissive
alreadydone/mathlib
dc0be621c6c8208c581f5170a8216c5ba6721927
c982179ec21091d3e102d8a5d9f5fe06c8fafb73
refs/heads/master
1,685,523,275,196
1,670,184,141,000
1,670,184,141,000
287,574,545
0
0
Apache-2.0
1,670,290,714,000
1,597,421,623,000
Lean
UTF-8
Lean
false
false
5,804
lean
/- Copyright (c) 2020 Shing Tak Lam. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Shing Tak Lam -/ import data.zmod.basic import group_theory.exponent /-! # Dihedral Groups We define the dihedral groups `dihedral_group n`, with elements `r i` and `sr i` for `i : zmod n`. For `n ≠ 0`, `dihedral_group n` represents the symmetry group of the regular `n`-gon. `r i` represents the rotations of the `n`-gon by `2πi/n`, and `sr i` represents the reflections of the `n`-gon. `dihedral_group 0` corresponds to the infinite dihedral group. -/ /-- For `n ≠ 0`, `dihedral_group n` represents the symmetry group of the regular `n`-gon. `r i` represents the rotations of the `n`-gon by `2πi/n`, and `sr i` represents the reflections of the `n`-gon. `dihedral_group 0` corresponds to the infinite dihedral group. -/ @[derive decidable_eq] inductive dihedral_group (n : ℕ) : Type | r : zmod n → dihedral_group | sr : zmod n → dihedral_group namespace dihedral_group variables {n : ℕ} /-- Multiplication of the dihedral group. -/ private def mul : dihedral_group n → dihedral_group n → dihedral_group n | (r i) (r j) := r (i + j) | (r i) (sr j) := sr (j - i) | (sr i) (r j) := sr (i + j) | (sr i) (sr j) := r (j - i) /-- The identity `1` is the rotation by `0`. -/ private def one : dihedral_group n := r 0 instance : inhabited (dihedral_group n) := ⟨one⟩ /-- The inverse of a an element of the dihedral group. -/ private def inv : dihedral_group n → dihedral_group n | (r i) := r (-i) | (sr i) := sr i /-- The group structure on `dihedral_group n`. -/ instance : group (dihedral_group n) := { mul := mul, mul_assoc := begin rintros (a | a) (b | b) (c | c); simp only [mul]; ring, end, one := one, one_mul := begin rintros (a | a), exact congr_arg r (zero_add a), exact congr_arg sr (sub_zero a), end, mul_one := begin rintros (a | a), exact congr_arg r (add_zero a), exact congr_arg sr (add_zero a), end, inv := inv, mul_left_inv := begin rintros (a | a), exact congr_arg r (neg_add_self a), exact congr_arg r (sub_self a), end } @[simp] lemma r_mul_r (i j : zmod n) : r i * r j = r (i + j) := rfl @[simp] lemma r_mul_sr (i j : zmod n) : r i * sr j = sr (j - i) := rfl @[simp] lemma sr_mul_r (i j : zmod n) : sr i * r j = sr (i + j) := rfl @[simp] lemma sr_mul_sr (i j : zmod n) : sr i * sr j = r (j - i) := rfl lemma one_def : (1 : dihedral_group n) = r 0 := rfl private def fintype_helper : (zmod n ⊕ zmod n) ≃ dihedral_group n := { inv_fun := λ i, match i with | (r j) := sum.inl j | (sr j) := sum.inr j end, to_fun := λ i, match i with | (sum.inl j) := r j | (sum.inr j) := sr j end, left_inv := by rintro (x | x); refl, right_inv := by rintro (x | x); refl } /-- If `0 < n`, then `dihedral_group n` is a finite group. -/ instance [ne_zero n] : fintype (dihedral_group n) := fintype.of_equiv _ fintype_helper instance : nontrivial (dihedral_group n) := ⟨⟨r 0, sr 0, dec_trivial⟩⟩ /-- If `0 < n`, then `dihedral_group n` has `2n` elements. -/ lemma card [ne_zero n] : fintype.card (dihedral_group n) = 2 * n := by rw [← fintype.card_eq.mpr ⟨fintype_helper⟩, fintype.card_sum, zmod.card, two_mul] @[simp] lemma r_one_pow (k : ℕ) : (r 1 : dihedral_group n) ^ k = r k := begin induction k with k IH, { rw nat.cast_zero, refl }, { rw [pow_succ, IH, r_mul_r], congr' 1, norm_cast, rw nat.one_add } end @[simp] lemma r_one_pow_n : (r (1 : zmod n))^n = 1 := begin rw [r_one_pow, one_def], congr' 1, exact zmod.nat_cast_self _, end @[simp] lemma sr_mul_self (i : zmod n) : sr i * sr i = 1 := by rw [sr_mul_sr, sub_self, one_def] /-- If `0 < n`, then `sr i` has order 2. -/ @[simp] lemma order_of_sr (i : zmod n) : order_of (sr i) = 2 := begin rw order_of_eq_prime _ _, { exact ⟨nat.prime_two⟩ }, rw [sq, sr_mul_self], dec_trivial, end /-- If `0 < n`, then `r 1` has order `n`. -/ @[simp] lemma order_of_r_one : order_of (r 1 : dihedral_group n) = n := begin rcases eq_zero_or_ne_zero n with rfl | hn, { rw order_of_eq_zero_iff', intros n hn, rw [r_one_pow, one_def], apply mt r.inj, simpa using hn.ne' }, { resetI, apply (nat.le_of_dvd (ne_zero.pos n) $ order_of_dvd_of_pow_eq_one $ @r_one_pow_n n) .lt_or_eq.resolve_left, intro h, have h1 : (r 1 : dihedral_group n)^(order_of (r 1)) = 1, { exact pow_order_of_eq_one _ }, rw r_one_pow at h1, injection h1 with h2, rw [← zmod.val_eq_zero, zmod.val_nat_cast, nat.mod_eq_of_lt h] at h2, exact absurd h2.symm (order_of_pos _).ne }, end /-- If `0 < n`, then `i : zmod n` has order `n / gcd n i`. -/ lemma order_of_r [ne_zero n] (i : zmod n) : order_of (r i) = n / nat.gcd n i.val := begin conv_lhs { rw ←zmod.nat_cast_zmod_val i }, rw [←r_one_pow, order_of_pow, order_of_r_one] end lemma exponent : monoid.exponent (dihedral_group n) = lcm n 2 := begin rcases eq_zero_or_ne_zero n with rfl | hn, { exact monoid.exponent_eq_zero_of_order_zero order_of_r_one }, resetI, apply nat.dvd_antisymm, { apply monoid.exponent_dvd_of_forall_pow_eq_one, rintro (m | m), { rw [←order_of_dvd_iff_pow_eq_one, order_of_r], refine nat.dvd_trans ⟨gcd n m.val, _⟩ (dvd_lcm_left n 2), { exact (nat.div_mul_cancel (nat.gcd_dvd_left n m.val)).symm } }, { rw [←order_of_dvd_iff_pow_eq_one, order_of_sr], exact dvd_lcm_right n 2 } }, { apply lcm_dvd, { convert monoid.order_dvd_exponent (r 1), exact order_of_r_one.symm }, { convert monoid.order_dvd_exponent (sr 0), exact (order_of_sr 0).symm } } end end dihedral_group
b1d907a8b276e7b6f08335cc0d8e553093e343ef
624f6f2ae8b3b1adc5f8f67a365c51d5126be45a
/src/Init/Lean/Compiler/NameMangling.lean
7e373c3434565ab08240ee6da274ed81757c0fce
[ "Apache-2.0" ]
permissive
mhuisi/lean4
28d35a4febc2e251c7f05492e13f3b05d6f9b7af
dda44bc47f3e5d024508060dac2bcb59fd12e4c0
refs/heads/master
1,621,225,489,283
1,585,142,689,000
1,585,142,689,000
250,590,438
0
2
Apache-2.0
1,602,443,220,000
1,585,327,814,000
C
UTF-8
Lean
false
false
1,486
lean
/- Copyright (c) 2018 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura -/ prelude import Init.Lean.Data.Name namespace Lean private def String.mangleAux : Nat → String.Iterator → String → String | 0, it, r => r | i+1, it, r => let c := it.curr; if c.isAlpha || c.isDigit then String.mangleAux i it.next (r.push c) else if c = '_' then String.mangleAux i it.next (r ++ "__") else if c.toNat < 255 then let n := c.toNat; let r := r ++ "_x"; let r := r.push $ Nat.digitChar (n / 16); let r := r.push $ Nat.digitChar (n % 16); String.mangleAux i it.next r else let n := c.toNat; let r := r ++ "_u"; let r := r.push $ Nat.digitChar (n / 4096); let n := n % 4096; let r := r.push $ Nat.digitChar (n / 256); let n := n % 256; let r := r.push $ Nat.digitChar (n / 16); let r := r.push $ Nat.digitChar (n % 16); String.mangleAux i it.next r def String.mangle (s : String) : String := String.mangleAux s.length s.mkIterator "" private def Name.mangleAux : Name → String | Name.anonymous => "" | Name.str p s _ => let m := String.mangle s; match p with | Name.anonymous => m | _ => Name.mangleAux p ++ "_" ++ m | Name.num p n _ => Name.mangleAux p ++ "_" ++ toString n ++ "_" @[export lean_name_mangle] def Name.mangle (n : Name) (pre : String := "l_") : String := pre ++ Name.mangleAux n end Lean
faa09f7701ff706f3359be2ff11cce6b3046deb4
c777c32c8e484e195053731103c5e52af26a25d1
/src/ring_theory/witt_vector/discrete_valuation_ring.lean
abe97d3cecbc2fc6acdd62011522824d70e45819
[ "Apache-2.0" ]
permissive
kbuzzard/mathlib
2ff9e85dfe2a46f4b291927f983afec17e946eb8
58537299e922f9c77df76cb613910914a479c1f7
refs/heads/master
1,685,313,702,744
1,683,974,212,000
1,683,974,212,000
128,185,277
1
0
null
1,522,920,600,000
1,522,920,600,000
null
UTF-8
Lean
false
false
6,100
lean
/- Copyright (c) 2022 Robert Y. Lewis. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Robert Y. Lewis, Heather Macbeth, Johan Commelin -/ import ring_theory.witt_vector.domain import ring_theory.witt_vector.mul_coeff import ring_theory.discrete_valuation_ring.basic import tactic.linear_combination /-! # Witt vectors over a perfect ring This file establishes that Witt vectors over a perfect field are a discrete valuation ring. When `k` is a perfect ring, a nonzero `a : 𝕎 k` can be written as `p^m * b` for some `m : ℕ` and `b : 𝕎 k` with nonzero 0th coefficient. When `k` is also a field, this `b` can be chosen to be a unit of `𝕎 k`. ## Main declarations * `witt_vector.exists_eq_pow_p_mul`: the existence of this element `b` over a perfect ring * `witt_vector.exists_eq_pow_p_mul'`: the existence of this unit `b` over a perfect field * `witt_vector.discrete_valuation_ring`: `𝕎 k` is a discrete valuation ring if `k` is a perfect field -/ noncomputable theory namespace witt_vector variables {p : ℕ} [hp : fact p.prime] include hp local notation `𝕎` := witt_vector p section comm_ring variables {k : Type*} [comm_ring k] [char_p k p] /-- This is the `n+1`st coefficient of our inverse. -/ def succ_nth_val_units (n : ℕ) (a : units k) (A : 𝕎 k) (bs : fin (n+1) → k) : k := - ↑(a⁻¹ ^ (p^(n+1))) * (A.coeff (n + 1) * ↑(a⁻¹ ^ (p^(n+1))) + nth_remainder p n (truncate_fun (n+1) A) bs) /-- Recursively defines the sequence of coefficients for the inverse to a Witt vector whose first entry is a unit. -/ noncomputable def inverse_coeff (a : units k) (A : 𝕎 k) : ℕ → k | 0 := ↑a⁻¹ | (n + 1) := succ_nth_val_units n a A (λ i, inverse_coeff i.val) using_well_founded { dec_tac := `[apply fin.is_lt] } /-- Upgrade a Witt vector `A` whose first entry `A.coeff 0` is a unit to be, itself, a unit in `𝕎 k`. -/ def mk_unit {a : units k} {A : 𝕎 k} (hA : A.coeff 0 = a) : units (𝕎 k) := units.mk_of_mul_eq_one A (witt_vector.mk p (inverse_coeff a A)) begin ext n, induction n with n ih, { simp [witt_vector.mul_coeff_zero, inverse_coeff, hA] }, let H_coeff := A.coeff (n + 1) * ↑(a⁻¹ ^ p ^ (n + 1)) + nth_remainder p n (truncate_fun (n + 1) A) (λ (i : fin (n + 1)), inverse_coeff a A i), have H := units.mul_inv (a ^ p ^ (n + 1)), linear_combination -H_coeff*H with { normalize := ff }, have ha : (a:k) ^ (p ^ (n + 1)) = ↑(a ^ (p ^ (n + 1))) := by norm_cast, have ha_inv : (↑(a⁻¹):k) ^ (p ^ (n + 1)) = ↑(a ^ (p ^ (n + 1)))⁻¹ := by exact_mod_cast inv_pow _ _, simp only [nth_remainder_spec, inverse_coeff, succ_nth_val_units, hA, fin.val_eq_coe, one_coeff_eq_of_pos, nat.succ_pos', H_coeff, ha_inv, ha, inv_pow], ring!, end @[simp] lemma coe_mk_unit {a : units k} {A : 𝕎 k} (hA : A.coeff 0 = a) : (mk_unit hA : 𝕎 k) = A := rfl end comm_ring section field variables {k : Type*} [field k] [char_p k p] lemma is_unit_of_coeff_zero_ne_zero (x : 𝕎 k) (hx : x.coeff 0 ≠ 0) : is_unit x := begin let y : kˣ := units.mk0 (x.coeff 0) hx, have hy : x.coeff 0 = y := rfl, exact (mk_unit hy).is_unit end variables (p) lemma irreducible : irreducible (p : 𝕎 k) := begin have hp : ¬ is_unit (p : 𝕎 k), { intro hp, simpa only [constant_coeff_apply, coeff_p_zero, not_is_unit_zero] using (constant_coeff : witt_vector p k →+* _).is_unit_map hp, }, refine ⟨hp, λ a b hab, _⟩, obtain ⟨ha0, hb0⟩ : a ≠ 0 ∧ b ≠ 0, { rw ← mul_ne_zero_iff, intro h, rw h at hab, exact p_nonzero p k hab }, obtain ⟨m, a, ha, rfl⟩ := verschiebung_nonzero ha0, obtain ⟨n, b, hb, rfl⟩ := verschiebung_nonzero hb0, cases m, { exact or.inl (is_unit_of_coeff_zero_ne_zero a ha) }, cases n, { exact or.inr (is_unit_of_coeff_zero_ne_zero b hb) }, rw iterate_verschiebung_mul at hab, apply_fun (λ x, coeff x 1) at hab, simp only [coeff_p_one, nat.add_succ, add_comm _ n, function.iterate_succ', function.comp_app, verschiebung_coeff_add_one, verschiebung_coeff_zero] at hab, exact (one_ne_zero hab).elim end end field section perfect_ring variables {k : Type*} [comm_ring k] [char_p k p] [perfect_ring k p] lemma exists_eq_pow_p_mul (a : 𝕎 k) (ha : a ≠ 0) : ∃ (m : ℕ) (b : 𝕎 k), b.coeff 0 ≠ 0 ∧ a = p ^ m * b := begin obtain ⟨m, c, hc, hcm⟩ := witt_vector.verschiebung_nonzero ha, obtain ⟨b, rfl⟩ := (frobenius_bijective p k).surjective.iterate m c, rw witt_vector.iterate_frobenius_coeff at hc, have := congr_fun (witt_vector.verschiebung_frobenius_comm.comp_iterate m) b, simp only [function.comp_app] at this, rw ← this at hcm, refine ⟨m, b, _, _⟩, { contrapose! hc, have : 0 < p ^ m := pow_pos (nat.prime.pos (fact.out _)) _, simp [hc, zero_pow this] }, { rw ← mul_left_iterate (p : 𝕎 k) m, convert hcm, ext1 x, rw [mul_comm, ← witt_vector.verschiebung_frobenius x] }, end end perfect_ring section perfect_field variables {k : Type*} [field k] [char_p k p] [perfect_ring k p] lemma exists_eq_pow_p_mul' (a : 𝕎 k) (ha : a ≠ 0) : ∃ (m : ℕ) (b : units (𝕎 k)), a = p ^ m * b := begin obtain ⟨m, b, h₁, h₂⟩ := exists_eq_pow_p_mul a ha, let b₀ := units.mk0 (b.coeff 0) h₁, have hb₀ : b.coeff 0 = b₀ := rfl, exact ⟨m, mk_unit hb₀, h₂⟩, end /- Note: The following lemma should be an instance, but it seems to cause some exponential blowups in certain typeclass resolution problems. See the following Lean4 issue as well as the zulip discussion linked there: https://github.com/leanprover/lean4/issues/1102 -/ /-- The ring of Witt Vectors of a perfect field of positive characteristic is a DVR. -/ lemma discrete_valuation_ring : discrete_valuation_ring (𝕎 k) := discrete_valuation_ring.of_has_unit_mul_pow_irreducible_factorization begin refine ⟨p, irreducible p, λ x hx, _⟩, obtain ⟨n, b, hb⟩ := exists_eq_pow_p_mul' x hx, exact ⟨n, b, hb.symm⟩, end end perfect_field end witt_vector
58537eddcb89b0acabc925b5281b75c375dcc783
b7f22e51856f4989b970961f794f1c435f9b8f78
/hott/core.hlean
063223bf37635e7421bd1706f7442eab4dd0341a
[ "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
230
hlean
/- Copyright (c) 2015 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn The core of the HoTT library -/ import types cubical homotopy hit choice
07df0dd4867ade6f31c1384ca0581df2037fb064
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/analysis/normed/group/ball_sphere.lean
6d90e2110fa4b7b378fbe023119545f3804d70ea
[ "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
1,924
lean
/- Copyright (c) 2022 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudryashov, Heather Macbeth -/ import analysis.normed.group.basic /-! # Negation on spheres and balls > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. In this file we define `has_involutive_neg` instances for spheres, open balls, and closed balls in a semi normed group. -/ open metric set variables {E : Type*} [seminormed_add_comm_group E] {r : ℝ} /-- We equip the sphere, in a seminormed group, with a formal operation of negation, namely the antipodal map. -/ instance : has_involutive_neg (sphere (0 : E) r) := { neg := subtype.map has_neg.neg $ λ w, by simp, neg_neg := λ x, subtype.ext $ neg_neg x } @[simp] lemma coe_neg_sphere {r : ℝ} (v : sphere (0 : E) r) : ↑(-v) = (-v : E) := rfl instance : has_continuous_neg (sphere (0 : E) r) := ⟨continuous_neg.subtype_map _⟩ /-- We equip the ball, in a seminormed group, with a formal operation of negation, namely the antipodal map. -/ instance {r : ℝ} : has_involutive_neg (ball (0 : E) r) := { neg := subtype.map has_neg.neg $ λ w, by simp, neg_neg := λ x, subtype.ext $ neg_neg x } @[simp] lemma coe_neg_ball {r : ℝ} (v : ball (0 : E) r) : ↑(-v) = (-v : E) := rfl instance : has_continuous_neg (ball (0 : E) r) := ⟨continuous_neg.subtype_map _⟩ /-- We equip the closed ball, in a seminormed group, with a formal operation of negation, namely the antipodal map. -/ instance {r : ℝ} : has_involutive_neg (closed_ball (0 : E) r) := { neg := subtype.map has_neg.neg $ λ w, by simp, neg_neg := λ x, subtype.ext $ neg_neg x } @[simp] lemma coe_neg_closed_ball {r : ℝ} (v : closed_ball (0 : E) r) : ↑(-v) = (-v : E) := rfl instance : has_continuous_neg (closed_ball (0 : E) r) := ⟨continuous_neg.subtype_map _⟩
7a380c57746cff5df4880e7824760c67fc26168b
367134ba5a65885e863bdc4507601606690974c1
/src/computability/halting.lean
219c30c3a71ddb4b3a62c88fcca7589b139ab02d
[ "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
13,721
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Mario Carneiro -/ import computability.partrec_code /-! # Computability theory and the halting problem A universal partial recursive function, Rice's theorem, and the halting problem. ## References * [Mario Carneiro, *Formalizing computability theory via partial recursive functions*][carneiro2019] -/ open encodable denumerable namespace nat.partrec open computable roption theorem merge' {f g} (hf : nat.partrec f) (hg : nat.partrec g) : ∃ h, nat.partrec h ∧ ∀ a, (∀ x ∈ h a, x ∈ f a ∨ x ∈ g a) ∧ ((h a).dom ↔ (f a).dom ∨ (g a).dom) := begin rcases code.exists_code.1 hf with ⟨cf, rfl⟩, rcases code.exists_code.1 hg with ⟨cg, rfl⟩, have : nat.partrec (λ n, (nat.rfind_opt (λ k, cf.evaln k n <|> cg.evaln k n))) := partrec.nat_iff.1 (partrec.rfind_opt $ primrec.option_orelse.to_comp.comp (code.evaln_prim.to_comp.comp $ (snd.pair (const cf)).pair fst) (code.evaln_prim.to_comp.comp $ (snd.pair (const cg)).pair fst)), refine ⟨_, this, λ n, _⟩, suffices, refine ⟨this, ⟨λ h, (this _ ⟨h, rfl⟩).imp Exists.fst Exists.fst, _⟩⟩, { intro h, rw nat.rfind_opt_dom, simp [dom_iff_mem, code.evaln_complete] at h, rcases h with ⟨x, k, e⟩ | ⟨x, k, e⟩, { refine ⟨k, x, _⟩, simp [e] }, { refine ⟨k, _⟩, cases cf.evaln k n with y, { exact ⟨x, by simp [e]⟩ }, { exact ⟨y, by simp⟩ } } }, { intros x h, rcases nat.rfind_opt_spec h with ⟨k, e⟩, revert e, simp; cases e' : cf.evaln k n with y; simp; intro, { exact or.inr (code.evaln_sound e) }, { subst y, exact or.inl (code.evaln_sound e') } } end end nat.partrec namespace partrec variables {α : Type*} {β : Type*} {γ : Type*} {σ : Type*} variables [primcodable α] [primcodable β] [primcodable γ] [primcodable σ] open computable roption nat.partrec (code) nat.partrec.code theorem merge' {f g : α →. σ} (hf : partrec f) (hg : partrec g) : ∃ k : α →. σ, partrec k ∧ ∀ a, (∀ x ∈ k a, x ∈ f a ∨ x ∈ g a) ∧ ((k a).dom ↔ (f a).dom ∨ (g a).dom) := let ⟨k, hk, H⟩ := nat.partrec.merge' (bind_decode2_iff.1 hf) (bind_decode2_iff.1 hg) in begin let k' := λ a, (k (encode a)).bind (λ n, decode σ n), refine ⟨k', ((nat_iff.2 hk).comp computable.encode).bind (computable.decode.of_option.comp snd).to₂, λ a, _⟩, suffices, refine ⟨this, ⟨λ h, (this _ ⟨h, rfl⟩).imp Exists.fst Exists.fst, _⟩⟩, { intro h, simp [k'], have hk : (k (encode a)).dom := (H _).2.2 (by simpa [encodek2] using h), existsi hk, cases (H _).1 _ ⟨hk, rfl⟩ with h h; { simp at h, rcases h with ⟨a', ha', y, hy, e⟩, simp [e.symm, encodek] } }, { intros x h', simp [k'] at h', rcases h' with ⟨n, hn, hx⟩, have := (H _).1 _ hn, simp [mem_decode2, encode_injective.eq_iff] at this, cases this with h h; { rcases h with ⟨a', ha, rfl⟩, simp [encodek] at hx, subst a', simp [ha] } }, end theorem merge {f g : α →. σ} (hf : partrec f) (hg : partrec g) (H : ∀ a (x ∈ f a) (y ∈ g a), x = y) : ∃ k : α →. σ, partrec k ∧ ∀ a x, x ∈ k a ↔ x ∈ f a ∨ x ∈ g a := let ⟨k, hk, K⟩ := merge' hf hg in ⟨k, hk, λ a x, ⟨(K _).1 _, λ h, begin have : (k a).dom := (K _).2.2 (h.imp Exists.fst Exists.fst), refine ⟨this, _⟩, cases h with h h; cases (K _).1 _ ⟨this, rfl⟩ with h' h', { exact mem_unique h' h }, { exact (H _ _ h _ h').symm }, { exact H _ _ h' _ h }, { exact mem_unique h' h } end⟩⟩ theorem cond {c : α → bool} {f : α →. σ} {g : α →. σ} (hc : computable c) (hf : partrec f) (hg : partrec g) : partrec (λ a, cond (c a) (f a) (g a)) := let ⟨cf, ef⟩ := exists_code.1 hf, ⟨cg, eg⟩ := exists_code.1 hg in ((eval_part.comp (computable.cond hc (const cf) (const cg)) computable.id).bind ((@computable.decode σ _).comp snd).of_option.to₂).of_eq $ λ a, by cases c a; simp [ef, eg, encodek] theorem sum_cases {f : α → β ⊕ γ} {g : α → β →. σ} {h : α → γ →. σ} (hf : computable f) (hg : partrec₂ g) (hh : partrec₂ h) : @partrec _ σ _ _ (λ a, sum.cases_on (f a) (g a) (h a)) := option_some_iff.1 $ (cond (sum_cases hf (const tt).to₂ (const ff).to₂) (sum_cases_left hf (option_some_iff.2 hg).to₂ (const option.none).to₂) (sum_cases_right hf (const option.none).to₂ (option_some_iff.2 hh).to₂)) .of_eq $ λ a, by cases f a; simp end partrec /-- A computable predicate is one whose indicator function is computable. -/ def computable_pred {α} [primcodable α] (p : α → Prop) := ∃ [D : decidable_pred p], by exactI computable (λ a, to_bool (p a)) /-- A recursively enumerable predicate is one which is the domain of a computable partial function. -/ def re_pred {α} [primcodable α] (p : α → Prop) := partrec (λ a, roption.assert (p a) (λ _, roption.some ())) theorem computable_pred.of_eq {α} [primcodable α] {p q : α → Prop} (hp : computable_pred p) (H : ∀ a, p a ↔ q a) : computable_pred q := (funext (λ a, propext (H a)) : p = q) ▸ hp namespace computable_pred variables {α : Type*} {σ : Type*} variables [primcodable α] [primcodable σ] open nat.partrec (code) nat.partrec.code computable theorem computable_iff {p : α → Prop} : computable_pred p ↔ ∃ f : α → bool, computable f ∧ p = λ a, f a := ⟨λ ⟨D, h⟩, by exactI ⟨_, h, funext $ λ a, propext (to_bool_iff _).symm⟩, by rintro ⟨f, h, rfl⟩; exact ⟨by apply_instance, by simpa using h⟩⟩ protected theorem not {p : α → Prop} (hp : computable_pred p) : computable_pred (λ a, ¬ p a) := by rcases computable_iff.1 hp with ⟨f, hf, rfl⟩; exact ⟨by apply_instance, (cond hf (const ff) (const tt)).of_eq (λ n, by {dsimp, cases f n; refl})⟩ theorem to_re {p : α → Prop} (hp : computable_pred p) : re_pred p := begin rcases computable_iff.1 hp with ⟨f, hf, rfl⟩, unfold re_pred, refine (partrec.cond hf (partrec.const' (roption.some ())) partrec.none).of_eq (λ n, roption.ext $ λ a, _), cases a, cases f n; simp end theorem rice (C : set (ℕ →. ℕ)) (h : computable_pred (λ c, eval c ∈ C)) {f g} (hf : nat.partrec f) (hg : nat.partrec g) (fC : f ∈ C) : g ∈ C := begin cases h with _ h, resetI, rcases fixed_point₂ (partrec.cond (h.comp fst) ((partrec.nat_iff.2 hg).comp snd).to₂ ((partrec.nat_iff.2 hf).comp snd).to₂).to₂ with ⟨c, e⟩, simp at e, by_cases eval c ∈ C, { simp [h] at e, rwa ← e }, { simp [h] at e, rw e at h, contradiction } end theorem rice₂ (C : set code) (H : ∀ cf cg, eval cf = eval cg → (cf ∈ C ↔ cg ∈ C)) : computable_pred (λ c, c ∈ C) ↔ C = ∅ ∨ C = set.univ := by haveI := classical.dec; exact have hC : ∀ f, f ∈ C ↔ eval f ∈ eval '' C, from λ f, ⟨set.mem_image_of_mem _, λ ⟨g, hg, e⟩, (H _ _ e).1 hg⟩, ⟨λ h, or_iff_not_imp_left.2 $ λ C0, set.eq_univ_of_forall $ λ cg, let ⟨cf, fC⟩ := set.ne_empty_iff_nonempty.1 C0 in (hC _).2 $ rice (eval '' C) (h.of_eq hC) (partrec.nat_iff.1 $ eval_part.comp (const cf) computable.id) (partrec.nat_iff.1 $ eval_part.comp (const cg) computable.id) ((hC _).1 fC), λ h, by rcases h with rfl | rfl; simp [computable_pred]; exact ⟨by apply_instance, computable.const _⟩⟩ theorem halting_problem (n) : ¬ computable_pred (λ c, (eval c n).dom) | h := rice {f | (f n).dom} h nat.partrec.zero nat.partrec.none trivial -- Post's theorem on the equivalence of r.e., co-r.e. sets and -- computable sets. The assumption that p is decidable is required -- unless we assume Markov's principle or LEM. @[nolint decidable_classical] theorem computable_iff_re_compl_re {p : α → Prop} [decidable_pred p] : computable_pred p ↔ re_pred p ∧ re_pred (λ a, ¬ p a) := ⟨λ h, ⟨h.to_re, h.not.to_re⟩, λ ⟨h₁, h₂⟩, ⟨‹_›, begin rcases partrec.merge (h₁.map (computable.const tt).to₂) (h₂.map (computable.const ff).to₂) _ with ⟨k, pk, hk⟩, { refine partrec.of_eq pk (λ n, roption.eq_some_iff.2 _), rw hk, simp, apply decidable.em }, { intros a x hx y hy, simp at hx hy, cases hy.1 hx.1 } end⟩⟩ end computable_pred namespace nat open vector roption /-- A simplified basis for `partrec`. -/ inductive partrec' : ∀ {n}, (vector ℕ n →. ℕ) → Prop | prim {n f} : @primrec' n f → @partrec' n f | comp {m n f} (g : fin n → vector ℕ m →. ℕ) : partrec' f → (∀ i, partrec' (g i)) → partrec' (λ v, m_of_fn (λ i, g i v) >>= f) | rfind {n} {f : vector ℕ (n+1) → ℕ} : @partrec' (n+1) f → partrec' (λ v, rfind (λ n, some (f (n ::ᵥ v) = 0))) end nat namespace nat.partrec' open vector partrec computable nat (partrec') nat.partrec' theorem to_part {n f} (pf : @partrec' n f) : partrec f := begin induction pf, case nat.partrec'.prim : n f hf { exact hf.to_prim.to_comp }, case nat.partrec'.comp : m n f g _ _ hf hg { exact (vector_m_of_fn (λ i, hg i)).bind (hf.comp snd) }, case nat.partrec'.rfind : n f _ hf { have := ((primrec.eq.comp primrec.id (primrec.const 0)).to_comp.comp (hf.comp (vector_cons.comp snd fst))).to₂.part, exact this.rfind }, end theorem of_eq {n} {f g : vector ℕ n →. ℕ} (hf : partrec' f) (H : ∀ i, f i = g i) : partrec' g := (funext H : f = g) ▸ hf theorem of_prim {n} {f : vector ℕ n → ℕ} (hf : primrec f) : @partrec' n f := prim (nat.primrec'.of_prim hf) theorem head {n : ℕ} : @partrec' n.succ (@head ℕ n) := prim nat.primrec'.head theorem tail {n f} (hf : @partrec' n f) : @partrec' n.succ (λ v, f v.tail) := (hf.comp _ (λ i, @prim _ _ $ nat.primrec'.nth i.succ)).of_eq $ λ v, by simp; rw [← of_fn_nth v.tail]; congr; funext i; simp protected theorem bind {n f g} (hf : @partrec' n f) (hg : @partrec' (n+1) g) : @partrec' n (λ v, (f v).bind (λ a, g (a ::ᵥ v))) := (@comp n (n+1) g (λ i, fin.cases f (λ i v, some (v.nth i)) i) hg (λ i, begin refine fin.cases _ (λ i, _) i; simp *, exact prim (nat.primrec'.nth _) end)).of_eq $ λ v, by simp [m_of_fn, roption.bind_assoc, pure] protected theorem map {n f} {g : vector ℕ (n+1) → ℕ} (hf : @partrec' n f) (hg : @partrec' (n+1) g) : @partrec' n (λ v, (f v).map (λ a, g (a ::ᵥ v))) := by simp [(roption.bind_some_eq_map _ _).symm]; exact hf.bind hg /-- Analogous to `nat.partrec'` for `ℕ`-valued functions, a predicate for partial recursive vector-valued functions.-/ def vec {n m} (f : vector ℕ n → vector ℕ m) := ∀ i, partrec' (λ v, (f v).nth i) theorem vec.prim {n m f} (hf : @nat.primrec'.vec n m f) : vec f := λ i, prim $ hf i protected theorem nil {n} : @vec n 0 (λ _, nil) := λ i, i.elim0 protected theorem cons {n m} {f : vector ℕ n → ℕ} {g} (hf : @partrec' n f) (hg : @vec n m g) : vec (λ v, f v ::ᵥ g v) := λ i, fin.cases (by simp *) (λ i, by simp [hg i]) i theorem idv {n} : @vec n n id := vec.prim nat.primrec'.idv theorem comp' {n m f g} (hf : @partrec' m f) (hg : @vec n m g) : partrec' (λ v, f (g v)) := (hf.comp _ hg).of_eq $ λ v, by simp theorem comp₁ {n} (f : ℕ →. ℕ) {g : vector ℕ n → ℕ} (hf : @partrec' 1 (λ v, f v.head)) (hg : @partrec' n g) : @partrec' n (λ v, f (g v)) := by simpa using hf.comp' (partrec'.cons hg partrec'.nil) theorem rfind_opt {n} {f : vector ℕ (n+1) → ℕ} (hf : @partrec' (n+1) f) : @partrec' n (λ v, nat.rfind_opt (λ a, of_nat (option ℕ) (f (a ::ᵥ v)))) := ((rfind $ (of_prim (primrec.nat_sub.comp (primrec.const 1) primrec.vector_head)) .comp₁ (λ n, roption.some (1 - n)) hf) .bind ((prim nat.primrec'.pred).comp₁ nat.pred hf)).of_eq $ λ v, roption.ext $ λ b, begin simp [nat.rfind_opt, -nat.mem_rfind], refine exists_congr (λ a, (and_congr (iff_of_eq _) iff.rfl).trans (and_congr_right (λ h, _))), { congr; funext n, simp, cases f (n ::ᵥ v); simp [nat.succ_ne_zero]; refl }, { have := nat.rfind_spec h, simp at this, cases f (a ::ᵥ v) with c, {cases this}, rw [← option.some_inj, eq_comm], refl } end open nat.partrec.code theorem of_part : ∀ {n f}, partrec f → @partrec' n f := suffices ∀ f, nat.partrec f → @partrec' 1 (λ v, f v.head), from λ n f hf, begin let g, swap, exact (comp₁ g (this g hf) (prim nat.primrec'.encode)).of_eq (λ i, by dsimp [g]; simp [encodek, roption.map_id']), end, λ f hf, begin rcases exists_code.1 hf with ⟨c, rfl⟩, simpa [eval_eq_rfind_opt] using (rfind_opt $ of_prim $ primrec.encode_iff.2 $ evaln_prim.comp $ (primrec.vector_head.pair (primrec.const c)).pair $ primrec.vector_head.comp primrec.vector_tail) end theorem part_iff {n f} : @partrec' n f ↔ partrec f := ⟨to_part, of_part⟩ theorem part_iff₁ {f : ℕ →. ℕ} : @partrec' 1 (λ v, f v.head) ↔ partrec f := part_iff.trans ⟨ λ h, (h.comp $ (primrec.vector_of_fn $ λ i, primrec.id).to_comp).of_eq (λ v, by simp), λ h, h.comp vector_head⟩ theorem part_iff₂ {f : ℕ → ℕ →. ℕ} : @partrec' 2 (λ v, f v.head v.tail.head) ↔ partrec₂ f := part_iff.trans ⟨ λ h, (h.comp $ vector_cons.comp fst $ vector_cons.comp snd (const nil)).of_eq (λ v, by simp), λ h, h.comp vector_head (vector_head.comp vector_tail)⟩ theorem vec_iff {m n f} : @vec m n f ↔ computable f := ⟨λ h, by simpa using vector_of_fn (λ i, to_part (h i)), λ h i, of_part $ vector_nth.comp h (const i)⟩ end nat.partrec'
332cfdb9e5cc4d959c84ff6829b4f1b0a391172c
0c1546a496eccfb56620165cad015f88d56190c5
/library/init/meta/rec_util.lean
843ca848a939196036c2edcb5898ccf84232c96c
[ "Apache-2.0" ]
permissive
Solertis/lean
491e0939957486f664498fbfb02546e042699958
84188c5aa1673fdf37a082b2de8562dddf53df3f
refs/heads/master
1,610,174,257,606
1,486,263,620,000
1,486,263,620,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
2,878
lean
/- Copyright (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura Helper tactic for showing that a type has decidable equality. -/ prelude import init.meta.tactic namespace tactic open expr /- Return tt iff e's type is of the form `(I_name ...)` -/ meta def is_type_app_of (e : expr) (I_name : name) : tactic bool := do t ← infer_type e, return $ is_constant_of (get_app_fn t) I_name /- Auxiliary function for using brec_on "dictionary" -/ private meta def mk_rec_inst_aux : expr → nat → tactic expr | F 0 := do P ← mk_app `pprod.fst [F], mk_app `pprod.fst [P] | F (n+1) := do F' ← mk_app `pprod.snd [F], mk_rec_inst_aux F' n /- Construct brec_on "recursive value". F_name is the name of the brec_on "dictionary". Type of the F_name hypothesis should be of the form (below (C ...)) where C is a constructor. The result is the "recursive value" for the (i+1)-th recursive value of the constructor C. -/ meta def mk_brec_on_rec_value (F_name : name) (i : nat) : tactic expr := do F ← get_local F_name, mk_rec_inst_aux F i meta def constructor_num_fields (c : name) : tactic nat := do env ← get_env, decl ← returnex $ environment.get env c, ctype ← return $ declaration.type decl, arity ← get_pi_arity ctype, I ← returnopt $ environment.inductive_type_of env c, nparams ← return (environment.inductive_num_params env I), return $ arity - nparams private meta def mk_name_list_aux : name → nat → nat → list name → list name × nat | p i 0 l := (list.reverse l, i) | p i (j+1) l := mk_name_list_aux p (i+1) j (mk_num_name p i :: l) private meta def mk_name_list (p : name) (i : nat) (n : nat) : list name × nat := mk_name_list_aux p i n [] /- Return a list of names of the form [p.i, ..., p.{i+n}] where n is the number of fields of the constructor c -/ meta def mk_constructor_arg_names (c : name) (p : name) (i : nat) : tactic (list name × nat) := do nfields ← constructor_num_fields c, return $ mk_name_list p i nfields private meta def mk_constructors_arg_names_aux : list name → name → nat → list (list name) → tactic (list (list name)) | [] p i r := return (list.reverse r) | (c::cs) p i r := do v : list name × nat ← mk_constructor_arg_names c p i, match v with (l, i') := mk_constructors_arg_names_aux cs p i' (l :: r) end /- Given an inductive datatype I with k constructors and where constructor i has n_i fields, return the list [[p.1, ..., p.n_1], [p.{n_1 + 1}, ..., p.{n_1 + n_2}], ..., [..., p.{n_1 + ... + n_k}]] -/ meta def mk_constructors_arg_names (I : name) (p : name) : tactic (list (list name)) := do env ← get_env, cs ← return $ environment.constructors_of env I, mk_constructors_arg_names_aux cs p 1 [] end tactic
6a7e0bde11a77326984e65199790881ec6cedd57
d1a52c3f208fa42c41df8278c3d280f075eb020c
/stage0/src/Lean/Meta/DiscrTreeTypes.lean
07a6ceff7fd6bb6675723d05048b614a2c63f256
[ "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,188
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.Expr namespace Lean.Meta /- See file `DiscrTree.lean` for the actual implementation and documentation. -/ namespace DiscrTree inductive Key where | const : Name → Nat → Key | fvar : FVarId → Nat → Key | lit : Literal → Key | star : Key | other : Key | arrow : Key | proj : Name → Nat → Key deriving Inhabited, BEq, Repr protected def Key.hash : Key → UInt64 | Key.const n a => mixHash 5237 $ mixHash (hash n) (hash a) | Key.fvar n a => mixHash 3541 $ mixHash (hash n) (hash a) | Key.lit v => mixHash 1879 $ hash v | Key.star => 7883 | Key.other => 2411 | Key.arrow => 17 | Key.proj s i => mixHash 11 $ mixHash (hash s) (hash i) instance : Hashable Key := ⟨Key.hash⟩ inductive Trie (α : Type) where | node (vs : Array α) (children : Array (Key × Trie α)) : Trie α end DiscrTree open DiscrTree open Std (PersistentHashMap) structure DiscrTree (α : Type) where root : PersistentHashMap Key (Trie α) := {} end Lean.Meta
ab1ec1ccf2c00fc1c5a197afc32fb3c4302a8664
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/algebra/continued_fractions/computation/default_auto.lean
49a7563ebdb84019c9d90d9a9d8816abb9dafc9d
[]
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
402
lean
/- Copyright (c) 2020 Kevin Kappelmann. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kevin Kappelmann -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.algebra.continued_fractions.computation.basic import Mathlib.algebra.continued_fractions.computation.translations import Mathlib.PostPort namespace Mathlib end Mathlib
0312f0872bf5738506e951e96c71ab88bddaee56
64874bd1010548c7f5a6e3e8902efa63baaff785
/tests/lean/run/eq21.lean
d4618acf4d0af79551fc2687670c5c1b9d95a44b
[ "Apache-2.0" ]
permissive
tjiaqi/lean
4634d729795c164664d10d093f3545287c76628f
d0ce4cf62f4246b0600c07e074d86e51f2195e30
refs/heads/master
1,622,323,796,480
1,422,643,069,000
1,422,643,069,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
424
lean
inductive formula := eqf : nat → nat → formula, impf : formula → formula → formula namespace formula definition denote : formula → Prop, denote (eqf n1 n2) := n1 = n2, denote (impf f1 f2) := denote f1 → denote f2 theorem denote_eqf (n1 n2 : nat) : denote (eqf n1 n2) = (n1 = n2) := rfl theorem denote_impf (f1 f2 : formula) : denote (impf f1 f2) = (denote f1 → denote f2) := rfl end formula
39511b064862a350a0c61e65cc8b757af319c523
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/run/regset.lean
f8938aa8ece7cd26d81258f5d7bfc1c2bb45c484
[ "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
268
lean
namespace regset section parameter symbol : Type @[reducible] def lang : Type := set (list symbol) def concat : lang → lang → lang := λ a b : lang, { ll : list symbol | ∃xs ys : list symbol, ll = list.append xs ys ∧ xs ∈ a ∧ ys ∈ b } end end regset
14bf1916014389cc80e54780bab39519f4e8ea42
94e33a31faa76775069b071adea97e86e218a8ee
/src/measure_theory/function/strongly_measurable.lean
c5ef42c810a2e13fdc604bfbd43ac085015dcef1
[ "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
81,896
lean
/- Copyright (c) 2021 Rémy Degenne. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Rémy Degenne, Sébastien Gouëzel -/ import measure_theory.function.ess_sup import measure_theory.integral.mean_inequalities import topology.continuous_function.compact import topology.metric_space.metrizable import measure_theory.function.simple_func_dense /-! # Strongly measurable and finitely strongly measurable functions A function `f` is said to be strongly measurable if `f` is the sequential limit of simple functions. It is said to be finitely strongly measurable with respect to a measure `μ` if the supports of those simple functions have finite measure. We also provide almost everywhere versions of these notions. Almost everywhere strongly measurable functions form the largest class of functions that can be integrated using the Bochner integral. If the target space has a second countable topology, strongly measurable and measurable are equivalent. If the measure is sigma-finite, strongly measurable and finitely strongly measurable are equivalent. The main property of finitely strongly measurable functions is `fin_strongly_measurable.exists_set_sigma_finite`: there exists a measurable set `t` such that the function is supported on `t` and `μ.restrict t` is sigma-finite. As a consequence, we can prove some results for those functions as if the measure was sigma-finite. ## Main definitions * `strongly_measurable f`: `f : α → β` is the limit of a sequence `fs : ℕ → simple_func α β`. * `fin_strongly_measurable f μ`: `f : α → β` is the limit of a sequence `fs : ℕ → simple_func α β` such that for all `n ∈ ℕ`, the measure of the support of `fs n` is finite. * `ae_strongly_measurable f μ`: `f` is almost everywhere equal to a `strongly_measurable` function. * `ae_fin_strongly_measurable f μ`: `f` is almost everywhere equal to a `fin_strongly_measurable` function. * `ae_fin_strongly_measurable.sigma_finite_set`: a measurable set `t` such that `f =ᵐ[μ.restrict tᶜ] 0` and `μ.restrict t` is sigma-finite. ## Main statements * `ae_fin_strongly_measurable.exists_set_sigma_finite`: there exists a measurable set `t` such that `f =ᵐ[μ.restrict tᶜ] 0` and `μ.restrict t` is sigma-finite. We provide a solid API for strongly measurable functions, and for almost everywhere strongly measurable functions, as a basis for the Bochner integral. ## References * Hytönen, Tuomas, Jan Van Neerven, Mark Veraar, and Lutz Weis. Analysis in Banach spaces. Springer, 2016. -/ open measure_theory filter topological_space function set measure_theory.measure open_locale ennreal topological_space measure_theory nnreal big_operators /-- The typeclass `second_countable_topology_either α β` registers the fact that at least one of the two spaces has second countable topology. This is the right assumption to ensure that continuous maps from `α` to `β` are strongly measurable. -/ class second_countable_topology_either (α β : Type*) [topological_space α] [topological_space β] : Prop := (out : second_countable_topology α ∨ second_countable_topology β) @[priority 100] instance second_countable_topology_either_of_left (α β : Type*) [topological_space α] [topological_space β] [second_countable_topology α] : second_countable_topology_either α β := { out := or.inl (by apply_instance) } @[priority 100] instance second_countable_topology_either_of_right (α β : Type*) [topological_space α] [topological_space β] [second_countable_topology β] : second_countable_topology_either α β := { out := or.inr (by apply_instance) } variables {α β γ ι : Type*} [encodable ι] namespace measure_theory local infixr ` →ₛ `:25 := simple_func section definitions variable [topological_space β] /-- A function is `strongly_measurable` if it is the limit of simple functions. -/ def strongly_measurable [measurable_space α] (f : α → β) : Prop := ∃ fs : ℕ → α →ₛ β, ∀ x, tendsto (λ n, fs n x) at_top (𝓝 (f x)) localized "notation `strongly_measurable[` m `]` := @measure_theory.strongly_measurable _ _ _ m" in measure_theory /-- A function is `fin_strongly_measurable` with respect to a measure if it is the limit of simple functions with support with finite measure. -/ def fin_strongly_measurable [has_zero β] {m0 : measurable_space α} (f : α → β) (μ : measure α) : Prop := ∃ fs : ℕ → α →ₛ β, (∀ n, μ (support (fs n)) < ∞) ∧ (∀ x, tendsto (λ n, fs n x) at_top (𝓝 (f x))) /-- A function is `ae_strongly_measurable` with respect to a measure `μ` if it is almost everywhere equal to the limit of a sequence of simple functions. -/ def ae_strongly_measurable {m0 : measurable_space α} (f : α → β) (μ : measure α) : Prop := ∃ g, strongly_measurable g ∧ f =ᵐ[μ] g /-- A function is `ae_fin_strongly_measurable` with respect to a measure if it is almost everywhere equal to the limit of a sequence of simple functions with support with finite measure. -/ def ae_fin_strongly_measurable [has_zero β] {m0 : measurable_space α} (f : α → β) (μ : measure α) : Prop := ∃ g, fin_strongly_measurable g μ ∧ f =ᵐ[μ] g end definitions open_locale measure_theory /-! ## Strongly measurable functions -/ lemma strongly_measurable.ae_strongly_measurable {α β} {m0 : measurable_space α} [topological_space β] {f : α → β} {μ : measure α} (hf : strongly_measurable f) : ae_strongly_measurable f μ := ⟨f, hf, eventually_eq.refl _ _⟩ @[simp] lemma subsingleton.strongly_measurable {α β} [measurable_space α] [topological_space β] [subsingleton β] (f : α → β) : strongly_measurable f := begin let f_sf : α →ₛ β := ⟨f, λ x, _, set.subsingleton.finite set.subsingleton_of_subsingleton⟩, { exact ⟨λ n, f_sf, λ x, tendsto_const_nhds⟩, }, { have h_univ : f ⁻¹' {x} = set.univ, by { ext1 y, simp, }, rw h_univ, exact measurable_set.univ, }, end lemma simple_func.strongly_measurable {α β} {m : measurable_space α} [topological_space β] (f : α →ₛ β) : strongly_measurable f := ⟨λ _, f, λ x, tendsto_const_nhds⟩ lemma strongly_measurable_of_is_empty [is_empty α] {m : measurable_space α} [topological_space β] (f : α → β) : strongly_measurable f := ⟨λ n, simple_func.of_is_empty, is_empty_elim⟩ lemma strongly_measurable_const {α β} {m : measurable_space α} [topological_space β] {b : β} : strongly_measurable (λ a : α, b) := ⟨λ n, simple_func.const α b, λ a, tendsto_const_nhds⟩ @[to_additive] lemma strongly_measurable_one {α β} {m : measurable_space α} [topological_space β] [has_one β] : strongly_measurable (1 : α → β) := @strongly_measurable_const _ _ _ _ 1 /-- A version of `strongly_measurable_const` that assumes `f x = f y` for all `x, y`. This version works for functions between empty types. -/ lemma strongly_measurable_const' {α β} {m : measurable_space α} [topological_space β] {f : α → β} (hf : ∀ x y, f x = f y) : strongly_measurable f := begin casesI is_empty_or_nonempty α, { exact strongly_measurable_of_is_empty f }, { convert strongly_measurable_const, exact funext (λ x, hf x h.some) } end @[simp] lemma subsingleton.strongly_measurable' {α β} [measurable_space α] [topological_space β] [subsingleton α] (f : α → β) : strongly_measurable f := strongly_measurable_const' (λ x y, by rw subsingleton.elim x y) namespace strongly_measurable variables {f g : α → β} section basic_properties_in_any_topological_space variables [topological_space β] /-- A sequence of simple functions such that `∀ x, tendsto (λ n, hf.approx n x) at_top (𝓝 (f x))`. That property is given by `strongly_measurable.tendsto_approx`. -/ protected noncomputable def approx {m : measurable_space α} (hf : strongly_measurable f) : ℕ → α →ₛ β := hf.some protected lemma tendsto_approx {m : measurable_space α} (hf : strongly_measurable f) : ∀ x, tendsto (λ n, hf.approx n x) at_top (𝓝 (f x)) := hf.some_spec end basic_properties_in_any_topological_space lemma fin_strongly_measurable_of_set_sigma_finite [topological_space β] [has_zero β] {m : measurable_space α} {μ : measure α} (hf_meas : strongly_measurable f) {t : set α} (ht : measurable_set t) (hft_zero : ∀ x ∈ tᶜ, f x = 0) (htμ : sigma_finite (μ.restrict t)) : fin_strongly_measurable f μ := begin haveI : sigma_finite (μ.restrict t) := htμ, let S := spanning_sets (μ.restrict t), have hS_meas : ∀ n, measurable_set (S n), from measurable_spanning_sets (μ.restrict t), let f_approx := hf_meas.approx, let fs := λ n, simple_func.restrict (f_approx n) (S n ∩ t), have h_fs_t_compl : ∀ n, ∀ x ∉ t, fs n x = 0, { intros n x hxt, rw simple_func.restrict_apply _ ((hS_meas n).inter ht), refine set.indicator_of_not_mem _ _, simp [hxt], }, refine ⟨fs, _, λ x, _⟩, { simp_rw simple_func.support_eq, refine λ n, (measure_bUnion_finset_le _ _).trans_lt _, refine ennreal.sum_lt_top_iff.mpr (λ y hy, _), rw simple_func.restrict_preimage_singleton _ ((hS_meas n).inter ht), swap, { rw finset.mem_filter at hy, exact hy.2, }, refine (measure_mono (set.inter_subset_left _ _)).trans_lt _, have h_lt_top := measure_spanning_sets_lt_top (μ.restrict t) n, rwa measure.restrict_apply' ht at h_lt_top, }, { by_cases hxt : x ∈ t, swap, { rw [funext (λ n, h_fs_t_compl n x hxt), hft_zero x hxt], exact tendsto_const_nhds, }, have h : tendsto (λ n, (f_approx n) x) at_top (𝓝 (f x)), from hf_meas.tendsto_approx x, obtain ⟨n₁, hn₁⟩ : ∃ n, ∀ m, n ≤ m → fs m x = f_approx m x, { obtain ⟨n, hn⟩ : ∃ n, ∀ m, n ≤ m → x ∈ S m ∩ t, { suffices : ∃ n, ∀ m, n ≤ m → x ∈ S m, { obtain ⟨n, hn⟩ := this, exact ⟨n, λ m hnm, set.mem_inter (hn m hnm) hxt⟩, }, suffices : ∃ n, x ∈ S n, { rcases this with ⟨n, hn⟩, exact ⟨n, λ m hnm, monotone_spanning_sets (μ.restrict t) hnm hn⟩, }, rw [← set.mem_Union, Union_spanning_sets (μ.restrict t)], trivial, }, refine ⟨n, λ m hnm, _⟩, simp_rw [fs, simple_func.restrict_apply _ ((hS_meas m).inter ht), set.indicator_of_mem (hn m hnm)], }, rw tendsto_at_top' at h ⊢, intros s hs, obtain ⟨n₂, hn₂⟩ := h s hs, refine ⟨max n₁ n₂, λ m hm, _⟩, rw hn₁ m ((le_max_left _ _).trans hm.le), exact hn₂ m ((le_max_right _ _).trans hm.le), }, end /-- If the measure is sigma-finite, all strongly measurable functions are `fin_strongly_measurable`. -/ protected lemma fin_strongly_measurable [topological_space β] [has_zero β] {m0 : measurable_space α} (hf : strongly_measurable f) (μ : measure α) [sigma_finite μ] : fin_strongly_measurable f μ := hf.fin_strongly_measurable_of_set_sigma_finite measurable_set.univ (by simp) (by rwa measure.restrict_univ) /-- A strongly measurable function is measurable. -/ protected lemma measurable {m : measurable_space α} [topological_space β] [pseudo_metrizable_space β] [measurable_space β] [borel_space β] (hf : strongly_measurable f) : measurable f := measurable_of_tendsto_metrizable (λ n, (hf.approx n).measurable) (tendsto_pi_nhds.mpr hf.tendsto_approx) /-- A strongly measurable function is almost everywhere measurable. -/ protected lemma ae_measurable {m : measurable_space α} [topological_space β] [pseudo_metrizable_space β] [measurable_space β] [borel_space β] {μ : measure α} (hf : strongly_measurable f) : ae_measurable f μ := hf.measurable.ae_measurable lemma _root_.continuous.comp_strongly_measurable {m : measurable_space α} [topological_space β] [topological_space γ] {g : β → γ} {f : α → β} (hg : continuous g) (hf : strongly_measurable f) : strongly_measurable (λ x, g (f x)) := ⟨λ n, simple_func.map g (hf.approx n), λ x, (hg.tendsto _).comp (hf.tendsto_approx x)⟩ @[to_additive] lemma measurable_set_mul_support {m : measurable_space α} [has_one β] [topological_space β] [metrizable_space β] (hf : strongly_measurable f) : measurable_set (mul_support f) := by { borelize β, exact measurable_set_mul_support hf.measurable } protected lemma mono {m m' : measurable_space α} [topological_space β] (hf : strongly_measurable[m'] f) (h_mono : m' ≤ m) : strongly_measurable[m] f := begin let f_approx : ℕ → @simple_func α m β := λ n, { to_fun := hf.approx n, measurable_set_fiber' := λ x, h_mono _ (simple_func.measurable_set_fiber' _ x), finite_range' := simple_func.finite_range (hf.approx n) }, exact ⟨f_approx, hf.tendsto_approx⟩, end protected lemma prod_mk {m : measurable_space α} [topological_space β] [topological_space γ] {f : α → β} {g : α → γ} (hf : strongly_measurable f) (hg : strongly_measurable g) : strongly_measurable (λ x, (f x, g x)) := begin refine ⟨λ n, simple_func.pair (hf.approx n) (hg.approx n), λ x, _⟩, rw nhds_prod_eq, exact tendsto.prod_mk (hf.tendsto_approx x) (hg.tendsto_approx x), end lemma comp_measurable [topological_space β] {m : measurable_space α} {m' : measurable_space γ} {f : α → β} {g : γ → α} (hf : strongly_measurable f) (hg : measurable g) : strongly_measurable (f ∘ g) := ⟨λ n, simple_func.comp (hf.approx n) g hg, λ x, hf.tendsto_approx (g x)⟩ lemma of_uncurry_left [topological_space β] {mα : measurable_space α} {mγ : measurable_space γ} {f : α → γ → β} (hf : strongly_measurable (uncurry f)) {x : α} : strongly_measurable (f x) := hf.comp_measurable measurable_prod_mk_left lemma of_uncurry_right [topological_space β] {mα : measurable_space α} {mγ : measurable_space γ} {f : α → γ → β} (hf : strongly_measurable (uncurry f)) {y : γ} : strongly_measurable (λ x, f x y) := hf.comp_measurable measurable_prod_mk_right section arithmetic variables {mα : measurable_space α} [topological_space β] include mα @[to_additive] protected lemma mul [has_mul β] [has_continuous_mul β] (hf : strongly_measurable f) (hg : strongly_measurable g) : strongly_measurable (f * g) := ⟨λ n, hf.approx n * hg.approx n, λ x, (hf.tendsto_approx x).mul (hg.tendsto_approx x)⟩ @[to_additive] lemma mul_const [has_mul β] [has_continuous_mul β] (hf : strongly_measurable f) (c : β) : strongly_measurable (λ x, f x * c) := hf.mul strongly_measurable_const @[to_additive] lemma const_mul [has_mul β] [has_continuous_mul β] (hf : strongly_measurable f) (c : β) : strongly_measurable (λ x, c * f x) := strongly_measurable_const.mul hf @[to_additive] protected lemma inv [group β] [topological_group β] (hf : strongly_measurable f) : strongly_measurable f⁻¹ := ⟨λ n, (hf.approx n)⁻¹, λ x, (hf.tendsto_approx x).inv⟩ @[to_additive] protected lemma div [has_div β] [has_continuous_div β] (hf : strongly_measurable f) (hg : strongly_measurable g) : strongly_measurable (f / g) := ⟨λ n, hf.approx n / hg.approx n, λ x, (hf.tendsto_approx x).div' (hg.tendsto_approx x)⟩ @[to_additive] protected lemma smul {𝕜} [topological_space 𝕜] [has_smul 𝕜 β] [has_continuous_smul 𝕜 β] {f : α → 𝕜} {g : α → β} (hf : strongly_measurable f) (hg : strongly_measurable g) : strongly_measurable (λ x, f x • g x) := continuous_smul.comp_strongly_measurable (hf.prod_mk hg) protected lemma const_smul {𝕜} [has_smul 𝕜 β] [has_continuous_const_smul 𝕜 β] (hf : strongly_measurable f) (c : 𝕜) : strongly_measurable (c • f) := ⟨λ n, c • (hf.approx n), λ x, (hf.tendsto_approx x).const_smul c⟩ protected lemma const_smul' {𝕜} [has_smul 𝕜 β] [has_continuous_const_smul 𝕜 β] (hf : strongly_measurable f) (c : 𝕜) : strongly_measurable (λ x, c • (f x)) := hf.const_smul c @[to_additive] protected lemma smul_const {𝕜} [topological_space 𝕜] [has_smul 𝕜 β] [has_continuous_smul 𝕜 β] {f : α → 𝕜} (hf : strongly_measurable f) (c : β) : strongly_measurable (λ x, f x • c) := continuous_smul.comp_strongly_measurable (hf.prod_mk strongly_measurable_const) end arithmetic section mul_action variables [topological_space β] {G : Type*} [group G] [mul_action G β] [has_continuous_const_smul G β] lemma _root_.strongly_measurable_const_smul_iff {m : measurable_space α} (c : G) : strongly_measurable (λ x, c • f x) ↔ strongly_measurable f := ⟨λ h, by simpa only [inv_smul_smul] using h.const_smul' c⁻¹, λ h, h.const_smul c⟩ variables {G₀ : Type*} [group_with_zero G₀] [mul_action G₀ β] [has_continuous_const_smul G₀ β] lemma _root_.strongly_measurable_const_smul_iff₀ {m : measurable_space α} {c : G₀} (hc : c ≠ 0) : strongly_measurable (λ x, c • f x) ↔ strongly_measurable f := begin refine ⟨λ h, _, λ h, h.const_smul c⟩, convert h.const_smul' c⁻¹, simp [smul_smul, inv_mul_cancel hc] end end mul_action section order variables [measurable_space α] [topological_space β] open filter open_locale filter protected lemma sup [has_sup β] [has_continuous_sup β] (hf : strongly_measurable f) (hg : strongly_measurable g) : strongly_measurable (f ⊔ g) := ⟨λ n, hf.approx n ⊔ hg.approx n, λ x, (hf.tendsto_approx x).sup_right_nhds (hg.tendsto_approx x)⟩ protected lemma inf [has_inf β] [has_continuous_inf β] (hf : strongly_measurable f) (hg : strongly_measurable g) : strongly_measurable (f ⊓ g) := ⟨λ n, hf.approx n ⊓ hg.approx n, λ x, (hf.tendsto_approx x).inf_right_nhds (hg.tendsto_approx x)⟩ end order /-! ### Big operators: `∏` and `∑` -/ section monoid variables {M : Type*} [monoid M] [topological_space M] [has_continuous_mul M] {m : measurable_space α} include m @[to_additive] lemma _root_.list.strongly_measurable_prod' (l : list (α → M)) (hl : ∀ f ∈ l, strongly_measurable f) : strongly_measurable l.prod := begin induction l with f l ihl, { exact strongly_measurable_one }, rw [list.forall_mem_cons] at hl, rw [list.prod_cons], exact hl.1.mul (ihl hl.2) end @[to_additive] lemma _root_.list.strongly_measurable_prod (l : list (α → M)) (hl : ∀ f ∈ l, strongly_measurable f) : strongly_measurable (λ x, (l.map (λ f : α → M, f x)).prod) := by simpa only [← pi.list_prod_apply] using l.strongly_measurable_prod' hl end monoid section comm_monoid variables {M : Type*} [comm_monoid M] [topological_space M] [has_continuous_mul M] {m : measurable_space α} include m @[to_additive] lemma _root_.multiset.strongly_measurable_prod' (l : multiset (α → M)) (hl : ∀ f ∈ l, strongly_measurable f) : strongly_measurable l.prod := by { rcases l with ⟨l⟩, simpa using l.strongly_measurable_prod' (by simpa using hl) } @[to_additive] lemma _root_.multiset.strongly_measurable_prod (s : multiset (α → M)) (hs : ∀ f ∈ s, strongly_measurable f) : strongly_measurable (λ x, (s.map (λ f : α → M, f x)).prod) := by simpa only [← pi.multiset_prod_apply] using s.strongly_measurable_prod' hs @[to_additive] lemma _root_.finset.strongly_measurable_prod' {ι : Type*} {f : ι → α → M} (s : finset ι) (hf : ∀i ∈ s, strongly_measurable (f i)) : strongly_measurable (∏ i in s, f i) := finset.prod_induction _ _ (λ a b ha hb, ha.mul hb) (@strongly_measurable_one α M _ _ _) hf @[to_additive] lemma _root_.finset.strongly_measurable_prod {ι : Type*} {f : ι → α → M} (s : finset ι) (hf : ∀i ∈ s, strongly_measurable (f i)) : strongly_measurable (λ a, ∏ i in s, f i a) := by simpa only [← finset.prod_apply] using s.strongly_measurable_prod' hf end comm_monoid /-- The range of a strongly measurable function is separable. -/ lemma is_separable_range {m : measurable_space α} [topological_space β] (hf : strongly_measurable f) : topological_space.is_separable (range f) := begin have : is_separable (closure (⋃ n, range (hf.approx n))) := (is_separable_Union (λ n, (simple_func.finite_range (hf.approx n)).is_separable)).closure, apply this.mono, rintros _ ⟨x, rfl⟩, apply mem_closure_of_tendsto (hf.tendsto_approx x), apply eventually_of_forall (λ n, _), apply mem_Union_of_mem n, exact mem_range_self _ end lemma separable_space_range_union_singleton {m : measurable_space α} [topological_space β] [pseudo_metrizable_space β] (hf : strongly_measurable f) {b : β} : separable_space (range f ∪ {b} : set β) := begin letI := pseudo_metrizable_space_pseudo_metric β, exact (hf.is_separable_range.union (finite_singleton _).is_separable).separable_space end section second_countable_strongly_measurable variables {mα : measurable_space α} [measurable_space β] include mα /-- In a space with second countable topology, measurable implies strongly measurable. -/ lemma _root_.measurable.strongly_measurable [topological_space β] [pseudo_metrizable_space β] [second_countable_topology β] [opens_measurable_space β] (hf : measurable f) : strongly_measurable f := begin letI := pseudo_metrizable_space_pseudo_metric β, rcases is_empty_or_nonempty β; resetI, { exact subsingleton.strongly_measurable f, }, { inhabit β, exact ⟨simple_func.approx_on f hf set.univ default (set.mem_univ _), λ x, simple_func.tendsto_approx_on hf (set.mem_univ _) (by simp)⟩, }, end /-- In a space with second countable topology, strongly measurable and measurable are equivalent. -/ lemma _root_.strongly_measurable_iff_measurable [topological_space β] [metrizable_space β] [borel_space β] [second_countable_topology β] : strongly_measurable f ↔ measurable f := ⟨λ h, h.measurable, λ h, measurable.strongly_measurable h⟩ lemma _root_.strongly_measurable_id [topological_space α] [pseudo_metrizable_space α] [opens_measurable_space α] [second_countable_topology α] : strongly_measurable (id : α → α) := measurable_id.strongly_measurable end second_countable_strongly_measurable /-- A function is strongly measurable if and only if it is measurable and has separable range. -/ theorem _root_.strongly_measurable_iff_measurable_separable {m : measurable_space α} [topological_space β] [pseudo_metrizable_space β] [measurable_space β] [borel_space β] : strongly_measurable f ↔ (measurable f ∧ is_separable (range f)) := begin refine ⟨λ H, ⟨H.measurable, H.is_separable_range⟩, _⟩, rintros ⟨H, H'⟩, letI := pseudo_metrizable_space_pseudo_metric β, let g := cod_restrict f (closure (range f)) (λ x, subset_closure (mem_range_self x)), have fg : f = (coe : closure (range f) → β) ∘ g, by { ext x, refl }, have T : measurable_embedding (coe : closure (range f) → β), { apply closed_embedding.measurable_embedding, exact closed_embedding_subtype_coe is_closed_closure }, have g_meas : measurable g, { rw fg at H, exact T.measurable_comp_iff.1 H }, haveI : second_countable_topology (closure (range f)), { suffices : separable_space (closure (range f)), by exactI uniform_space.second_countable_of_separable _, exact (is_separable.closure H').separable_space }, have g_smeas : strongly_measurable g := measurable.strongly_measurable g_meas, rw fg, exact continuous_subtype_coe.comp_strongly_measurable g_smeas, end /-- A continuous function is strongly measurable when either the source space or the target space is second-countable. -/ lemma _root_.continuous.strongly_measurable [measurable_space α] [topological_space α] [opens_measurable_space α] {β : Type*} [topological_space β] [pseudo_metrizable_space β] [h : second_countable_topology_either α β] {f : α → β} (hf : continuous f) : strongly_measurable f := begin borelize β, casesI h.out, { rw strongly_measurable_iff_measurable_separable, refine ⟨hf.measurable, _⟩, rw ← image_univ, exact (is_separable_of_separable_space univ).image hf }, { exact hf.measurable.strongly_measurable } end /-- If `g` is a topological embedding, then `f` is strongly measurable iff `g ∘ f` is. -/ lemma _root_.embedding.comp_strongly_measurable_iff {m : measurable_space α} [topological_space β] [pseudo_metrizable_space β] [topological_space γ] [pseudo_metrizable_space γ] {g : β → γ} {f : α → β} (hg : embedding g) : strongly_measurable (λ x, g (f x)) ↔ strongly_measurable f := begin letI := pseudo_metrizable_space_pseudo_metric γ, borelize [β, γ], refine ⟨λ H, strongly_measurable_iff_measurable_separable.2 ⟨_, _⟩, λ H, hg.continuous.comp_strongly_measurable H⟩, { let G : β → range g := cod_restrict g (range g) mem_range_self, have hG : closed_embedding G := { closed_range := begin convert is_closed_univ, apply eq_univ_of_forall, rintros ⟨-, ⟨x, rfl⟩⟩, exact mem_range_self x end, .. hg.cod_restrict _ _ }, have : measurable (G ∘ f) := measurable.subtype_mk H.measurable, exact hG.measurable_embedding.measurable_comp_iff.1 this }, { have : is_separable (g ⁻¹' (range (g ∘ f))) := hg.is_separable_preimage H.is_separable_range, convert this, ext x, simp [hg.inj.eq_iff] } end /-- A sequential limit of strongly measurable functions is strongly measurable. -/ lemma _root_.strongly_measurable_of_tendsto {ι : Type*} {m : measurable_space α} [topological_space β] [pseudo_metrizable_space β] (u : filter ι) [ne_bot u] [is_countably_generated u] {f : ι → α → β} {g : α → β} (hf : ∀ i, strongly_measurable (f i)) (lim : tendsto f u (𝓝 g)) : strongly_measurable g := begin borelize β, refine strongly_measurable_iff_measurable_separable.2 ⟨_, _⟩, { exact measurable_of_tendsto_metrizable' u (λ i, (hf i).measurable) lim }, { rcases u.exists_seq_tendsto with ⟨v, hv⟩, have : is_separable (closure (⋃ i, range (f (v i)))) := (is_separable_Union (λ i, (hf (v i)).is_separable_range)).closure, apply this.mono, rintros _ ⟨x, rfl⟩, rw [tendsto_pi_nhds] at lim, apply mem_closure_of_tendsto ((lim x).comp hv), apply eventually_of_forall (λ n, _), apply mem_Union_of_mem n, exact mem_range_self _ } end protected lemma piecewise {m : measurable_space α} [topological_space β] {s : set α} {_ : decidable_pred (∈ s)} (hs : measurable_set s) (hf : strongly_measurable f) (hg : strongly_measurable g) : strongly_measurable (set.piecewise s f g) := begin refine ⟨λ n, simple_func.piecewise s hs (hf.approx n) (hg.approx n), λ x, _⟩, by_cases hx : x ∈ s, { simpa [hx] using hf.tendsto_approx x }, { simpa [hx] using hg.tendsto_approx x }, end /-- this is slightly different from `strongly_measurable.piecewise`. It can be used to show `strongly_measurable (ite (x=0) 0 1)` by `exact strongly_measurable.ite (measurable_set_singleton 0) strongly_measurable_const strongly_measurable_const`, but replacing `strongly_measurable.ite` by `strongly_measurable.piecewise` in that example proof does not work. -/ protected lemma ite {m : measurable_space α} [topological_space β] {p : α → Prop} {_ : decidable_pred p} (hp : measurable_set {a : α | p a}) (hf : strongly_measurable f) (hg : strongly_measurable g) : strongly_measurable (λ x, ite (p x) (f x) (g x)) := strongly_measurable.piecewise hp hf hg lemma _root_.strongly_measurable_of_strongly_measurable_union_cover {m : measurable_space α} [topological_space β] {f : α → β} (s t : set α) (hs : measurable_set s) (ht : measurable_set t) (h : univ ⊆ s ∪ t) (hc : strongly_measurable (λ a : s, f a)) (hd : strongly_measurable (λ a : t, f a)) : strongly_measurable f := begin classical, let f : ℕ → α →ₛ β := λ n, { to_fun := λ x, if hx : x ∈ s then hc.approx n ⟨x, hx⟩ else hd.approx n ⟨x, by simpa [hx] using h (mem_univ x)⟩, measurable_set_fiber' := begin assume x, convert (hs.subtype_image ((hc.approx n).measurable_set_fiber x)).union ((ht.subtype_image ((hd.approx n).measurable_set_fiber x)).diff hs), ext1 y, simp only [mem_union_eq, mem_preimage, mem_singleton_iff, mem_image, set_coe.exists, subtype.coe_mk, exists_and_distrib_right, exists_eq_right, mem_diff], by_cases hy : y ∈ s, { rw dif_pos hy, simp only [hy, exists_true_left, not_true, and_false, or_false]}, { rw dif_neg hy, have A : y ∈ t, by simpa [hy] using h (mem_univ y), simp only [A, hy, false_or, is_empty.exists_iff, not_false_iff, and_true, exists_true_left] } end, finite_range' := begin apply ((hc.approx n).finite_range.union (hd.approx n).finite_range).subset, rintros - ⟨y, rfl⟩, dsimp, by_cases hy : y ∈ s, { left, rw dif_pos hy, exact mem_range_self _ }, { right, rw dif_neg hy, exact mem_range_self _ } end }, refine ⟨f, λ y, _⟩, by_cases hy : y ∈ s, { convert hc.tendsto_approx ⟨y, hy⟩ using 1, ext1 n, simp only [dif_pos hy, simple_func.apply_mk] }, { have A : y ∈ t, by simpa [hy] using h (mem_univ y), convert hd.tendsto_approx ⟨y, A⟩ using 1, ext1 n, simp only [dif_neg hy, simple_func.apply_mk] } end lemma _root_.strongly_measurable_of_restrict_of_restrict_compl {m : measurable_space α} [topological_space β] {f : α → β} {s : set α} (hs : measurable_set s) (h₁ : strongly_measurable (s.restrict f)) (h₂ : strongly_measurable (sᶜ.restrict f)) : strongly_measurable f := strongly_measurable_of_strongly_measurable_union_cover s sᶜ hs hs.compl (union_compl_self s).ge h₁ h₂ protected lemma indicator {m : measurable_space α} [topological_space β] [has_zero β] (hf : strongly_measurable f) {s : set α} (hs : measurable_set s) : strongly_measurable (s.indicator f) := hf.piecewise hs strongly_measurable_const protected lemma dist {m : measurable_space α} {β : Type*} [pseudo_metric_space β] {f g : α → β} (hf : strongly_measurable f) (hg : strongly_measurable g) : strongly_measurable (λ x, dist (f x) (g x)) := continuous_dist.comp_strongly_measurable (hf.prod_mk hg) protected lemma norm {m : measurable_space α} {β : Type*} [normed_group β] {f : α → β} (hf : strongly_measurable f) : strongly_measurable (λ x, ∥f x∥) := continuous_norm.comp_strongly_measurable hf protected lemma nnnorm {m : measurable_space α} {β : Type*} [normed_group β] {f : α → β} (hf : strongly_measurable f) : strongly_measurable (λ x, ∥f x∥₊) := continuous_nnnorm.comp_strongly_measurable hf protected lemma ennnorm {m : measurable_space α} {β : Type*} [normed_group β] {f : α → β} (hf : strongly_measurable f) : measurable (λ a, (∥f a∥₊ : ℝ≥0∞)) := (ennreal.continuous_coe.comp_strongly_measurable hf.nnnorm).measurable protected lemma real_to_nnreal {m : measurable_space α} {f : α → ℝ} (hf : strongly_measurable f) : strongly_measurable (λ x, (f x).to_nnreal) := continuous_real_to_nnreal.comp_strongly_measurable hf lemma _root_.measurable_embedding.strongly_measurable_extend {f : α → β} {g : α → γ} {g' : γ → β} {mα : measurable_space α} {mγ : measurable_space γ} [topological_space β] (hg : measurable_embedding g) (hf : strongly_measurable f) (hg' : strongly_measurable g') : strongly_measurable (function.extend g f g') := begin refine ⟨λ n, simple_func.extend (hf.approx n) g hg (hg'.approx n), _⟩, assume x, by_cases hx : ∃ y, g y = x, { rcases hx with ⟨y, rfl⟩, simpa only [simple_func.extend_apply, hg.injective, extend_apply] using hf.tendsto_approx y }, { simpa only [hx, simple_func.extend_apply', not_false_iff, extend_apply'] using hg'.tendsto_approx x } end lemma _root_.measurable_embedding.exists_strongly_measurable_extend {f : α → β} {g : α → γ} {mα : measurable_space α} {mγ : measurable_space γ} [topological_space β] (hg : measurable_embedding g) (hf : strongly_measurable f) (hne : γ → nonempty β) : ∃ f' : γ → β, strongly_measurable f' ∧ f' ∘ g = f := ⟨function.extend g f (λ x, classical.choice (hne x)), hg.strongly_measurable_extend hf (strongly_measurable_const' $ λ _ _, rfl), funext $ λ x, extend_apply hg.injective _ _ _⟩ protected lemma inner {𝕜 : Type*} {E : Type*} [is_R_or_C 𝕜] [inner_product_space 𝕜 E] {m : measurable_space α} {f g : α → E} (hf : strongly_measurable f) (hg : strongly_measurable g) : strongly_measurable (λ t, @inner 𝕜 _ _(f t) (g t)) := continuous.comp_strongly_measurable continuous_inner (hf.prod_mk hg) lemma measurable_set_eq_fun {m : measurable_space α} {E} [topological_space E] [metrizable_space E] {f g : α → E} (hf : strongly_measurable f) (hg : strongly_measurable g) : measurable_set {x | f x = g x} := begin borelize E × E, exact (hf.prod_mk hg).measurable is_closed_diagonal.measurable_set end lemma measurable_set_lt {m : measurable_space α} [topological_space β] [linear_order β] [order_closed_topology β] [pseudo_metrizable_space β] {f g : α → β} (hf : strongly_measurable f) (hg : strongly_measurable g) : measurable_set {a | f a < g a} := begin borelize β × β, exact (hf.prod_mk hg).measurable is_open_lt_prod.measurable_set end lemma measurable_set_le {m : measurable_space α} [topological_space β] [preorder β] [order_closed_topology β] [pseudo_metrizable_space β] {f g : α → β} (hf : strongly_measurable f) (hg : strongly_measurable g) : measurable_set {a | f a ≤ g a} := begin borelize β × β, exact (hf.prod_mk hg).measurable is_closed_le_prod.measurable_set end lemma strongly_measurable_in_set {m : measurable_space α} [topological_space β] [has_zero β] {s : set α} {f : α → β} (hs : measurable_set s) (hf : strongly_measurable f) (hf_zero : ∀ x ∉ s, f x = 0) : ∃ fs : ℕ → α →ₛ β, (∀ x, tendsto (λ n, fs n x) at_top (𝓝 (f x))) ∧ (∀ (x ∉ s) n, fs n x = 0) := begin let g_seq_s : ℕ → @simple_func α m β := λ n, (hf.approx n).restrict s, have hg_eq : ∀ x ∈ s, ∀ n, g_seq_s n x = hf.approx n x, { intros x hx n, rw [simple_func.coe_restrict _ hs, set.indicator_of_mem hx], }, have hg_zero : ∀ x ∉ s, ∀ n, g_seq_s n x = 0, { intros x hx n, rw [simple_func.coe_restrict _ hs, set.indicator_of_not_mem hx], }, refine ⟨g_seq_s, λ x, _, hg_zero⟩, by_cases hx : x ∈ s, { simp_rw hg_eq x hx, exact hf.tendsto_approx x, }, { simp_rw [hg_zero x hx, hf_zero x hx], exact tendsto_const_nhds, }, end /-- If the restriction to a set `s` of a σ-algebra `m` is included in the restriction to `s` of another σ-algebra `m₂` (hypothesis `hs`), the set `s` is `m` measurable and a function `f` supported on `s` is `m`-strongly-measurable, then `f` is also `m₂`-strongly-measurable. -/ lemma strongly_measurable_of_measurable_space_le_on {α E} {m m₂ : measurable_space α} [topological_space E] [has_zero E] {s : set α} {f : α → E} (hs_m : measurable_set[m] s) (hs : ∀ t, measurable_set[m] (s ∩ t) → measurable_set[m₂] (s ∩ t)) (hf : strongly_measurable[m] f) (hf_zero : ∀ x ∉ s, f x = 0) : strongly_measurable[m₂] f := begin have hs_m₂ : measurable_set[m₂] s, { rw ← set.inter_univ s, refine hs set.univ _, rwa [set.inter_univ], }, obtain ⟨g_seq_s, hg_seq_tendsto, hg_seq_zero⟩ := strongly_measurable_in_set hs_m hf hf_zero, let g_seq_s₂ : ℕ → @simple_func α m₂ E := λ n, { to_fun := g_seq_s n, measurable_set_fiber' := λ x, begin rw [← set.inter_univ ((g_seq_s n) ⁻¹' {x}), ← set.union_compl_self s, set.inter_union_distrib_left, set.inter_comm ((g_seq_s n) ⁻¹' {x})], refine measurable_set.union (hs _ (hs_m.inter _)) _, { exact @simple_func.measurable_set_fiber _ _ m _ _, }, by_cases hx : x = 0, { suffices : (g_seq_s n) ⁻¹' {x} ∩ sᶜ = sᶜ, by { rw this, exact hs_m₂.compl, }, ext1 y, rw [hx, set.mem_inter_iff, set.mem_preimage, set.mem_singleton_iff], exact ⟨λ h, h.2, λ h, ⟨hg_seq_zero y h n, h⟩⟩, }, { suffices : (g_seq_s n) ⁻¹' {x} ∩ sᶜ = ∅, by { rw this, exact measurable_set.empty, }, ext1 y, simp only [mem_inter_eq, mem_preimage, mem_singleton_iff, mem_compl_eq, mem_empty_eq, iff_false, not_and, not_not_mem], refine imp_of_not_imp_not _ _ (λ hys, _), rw hg_seq_zero y hys n, exact ne.symm hx, }, end, finite_range' := @simple_func.finite_range _ _ m (g_seq_s n), }, have hg_eq : ∀ x n, g_seq_s₂ n x = g_seq_s n x := λ x n, rfl, refine ⟨g_seq_s₂, λ x, _⟩, simp_rw hg_eq, exact hg_seq_tendsto x, end end strongly_measurable /-! ## Finitely strongly measurable functions -/ lemma fin_strongly_measurable_zero {α β} {m : measurable_space α} {μ : measure α} [has_zero β] [topological_space β] : fin_strongly_measurable (0 : α → β) μ := ⟨0, by simp only [pi.zero_apply, simple_func.coe_zero, support_zero', measure_empty, with_top.zero_lt_top, forall_const], λ n, tendsto_const_nhds⟩ namespace fin_strongly_measurable variables {m0 : measurable_space α} {μ : measure α} {f g : α → β} lemma ae_fin_strongly_measurable [has_zero β] [topological_space β] (hf : fin_strongly_measurable f μ) : ae_fin_strongly_measurable f μ := ⟨f, hf, ae_eq_refl f⟩ section sequence variables [has_zero β] [topological_space β] (hf : fin_strongly_measurable f μ) /-- A sequence of simple functions such that `∀ x, tendsto (λ n, hf.approx n x) at_top (𝓝 (f x))` and `∀ n, μ (support (hf.approx n)) < ∞`. These properties are given by `fin_strongly_measurable.tendsto_approx` and `fin_strongly_measurable.fin_support_approx`. -/ protected noncomputable def approx : ℕ → α →ₛ β := hf.some protected lemma fin_support_approx : ∀ n, μ (support (hf.approx n)) < ∞ := hf.some_spec.1 protected lemma tendsto_approx : ∀ x, tendsto (λ n, hf.approx n x) at_top (𝓝 (f x)) := hf.some_spec.2 end sequence protected lemma strongly_measurable [has_zero β] [topological_space β] (hf : fin_strongly_measurable f μ) : strongly_measurable f := ⟨hf.approx, hf.tendsto_approx⟩ lemma exists_set_sigma_finite [has_zero β] [topological_space β] [t2_space β] (hf : fin_strongly_measurable f μ) : ∃ t, measurable_set t ∧ (∀ x ∈ tᶜ, f x = 0) ∧ sigma_finite (μ.restrict t) := begin rcases hf with ⟨fs, hT_lt_top, h_approx⟩, let T := λ n, support (fs n), have hT_meas : ∀ n, measurable_set (T n), from λ n, simple_func.measurable_set_support (fs n), let t := ⋃ n, T n, refine ⟨t, measurable_set.Union hT_meas, _, _⟩, { have h_fs_zero : ∀ n, ∀ x ∈ tᶜ, fs n x = 0, { intros n x hxt, rw [set.mem_compl_iff, set.mem_Union, not_exists] at hxt, simpa using (hxt n), }, refine λ x hxt, tendsto_nhds_unique (h_approx x) _, rw funext (λ n, h_fs_zero n x hxt), exact tendsto_const_nhds, }, { refine ⟨⟨⟨λ n, tᶜ ∪ T n, λ n, trivial, λ n, _, _⟩⟩⟩, { rw [measure.restrict_apply' (measurable_set.Union hT_meas), set.union_inter_distrib_right, set.compl_inter_self t, set.empty_union], exact (measure_mono (set.inter_subset_left _ _)).trans_lt (hT_lt_top n), }, { rw ← set.union_Union tᶜ T, exact set.compl_union_self _ } } end /-- A finitely strongly measurable function is measurable. -/ protected lemma measurable [has_zero β] [topological_space β] [pseudo_metrizable_space β] [measurable_space β] [borel_space β] (hf : fin_strongly_measurable f μ) : measurable f := hf.strongly_measurable.measurable section arithmetic variables [topological_space β] protected lemma mul [monoid_with_zero β] [has_continuous_mul β] (hf : fin_strongly_measurable f μ) (hg : fin_strongly_measurable g μ) : fin_strongly_measurable (f * g) μ := begin refine ⟨λ n, hf.approx n * hg.approx n, _, λ x, (hf.tendsto_approx x).mul (hg.tendsto_approx x)⟩, intro n, exact (measure_mono (support_mul_subset_left _ _)).trans_lt (hf.fin_support_approx n), end protected lemma add [add_monoid β] [has_continuous_add β] (hf : fin_strongly_measurable f μ) (hg : fin_strongly_measurable g μ) : fin_strongly_measurable (f + g) μ := ⟨λ n, hf.approx n + hg.approx n, λ n, (measure_mono (function.support_add _ _)).trans_lt ((measure_union_le _ _).trans_lt (ennreal.add_lt_top.mpr ⟨hf.fin_support_approx n, hg.fin_support_approx n⟩)), λ x, (hf.tendsto_approx x).add (hg.tendsto_approx x)⟩ protected lemma neg [add_group β] [topological_add_group β] (hf : fin_strongly_measurable f μ) : fin_strongly_measurable (-f) μ := begin refine ⟨λ n, -hf.approx n, λ n, _, λ x, (hf.tendsto_approx x).neg⟩, suffices : μ (function.support (λ x, - (hf.approx n) x)) < ∞, by convert this, rw function.support_neg (hf.approx n), exact hf.fin_support_approx n, end protected lemma sub [add_group β] [has_continuous_sub β] (hf : fin_strongly_measurable f μ) (hg : fin_strongly_measurable g μ) : fin_strongly_measurable (f - g) μ := ⟨λ n, hf.approx n - hg.approx n, λ n, (measure_mono (function.support_sub _ _)).trans_lt ((measure_union_le _ _).trans_lt (ennreal.add_lt_top.mpr ⟨hf.fin_support_approx n, hg.fin_support_approx n⟩)), λ x, (hf.tendsto_approx x).sub (hg.tendsto_approx x)⟩ protected lemma const_smul {𝕜} [topological_space 𝕜] [add_monoid β] [monoid 𝕜] [distrib_mul_action 𝕜 β] [has_continuous_smul 𝕜 β] (hf : fin_strongly_measurable f μ) (c : 𝕜) : fin_strongly_measurable (c • f) μ := begin refine ⟨λ n, c • (hf.approx n), λ n, _, λ x, (hf.tendsto_approx x).const_smul c⟩, rw simple_func.coe_smul, refine (measure_mono (support_smul_subset_right c _)).trans_lt (hf.fin_support_approx n), end end arithmetic section order variables [topological_space β] [has_zero β] protected lemma sup [semilattice_sup β] [has_continuous_sup β] (hf : fin_strongly_measurable f μ) (hg : fin_strongly_measurable g μ) : fin_strongly_measurable (f ⊔ g) μ := begin refine ⟨λ n, hf.approx n ⊔ hg.approx n, λ n, _, λ x, (hf.tendsto_approx x).sup_right_nhds (hg.tendsto_approx x)⟩, refine (measure_mono (support_sup _ _)).trans_lt _, exact measure_union_lt_top_iff.mpr ⟨hf.fin_support_approx n, hg.fin_support_approx n⟩, end protected lemma inf [semilattice_inf β] [has_continuous_inf β] (hf : fin_strongly_measurable f μ) (hg : fin_strongly_measurable g μ) : fin_strongly_measurable (f ⊓ g) μ := begin refine ⟨λ n, hf.approx n ⊓ hg.approx n, λ n, _, λ x, (hf.tendsto_approx x).inf_right_nhds (hg.tendsto_approx x)⟩, refine (measure_mono (support_inf _ _)).trans_lt _, exact measure_union_lt_top_iff.mpr ⟨hf.fin_support_approx n, hg.fin_support_approx n⟩, end end order end fin_strongly_measurable lemma fin_strongly_measurable_iff_strongly_measurable_and_exists_set_sigma_finite {α β} {f : α → β} [topological_space β] [t2_space β] [has_zero β] {m : measurable_space α} {μ : measure α} : fin_strongly_measurable f μ ↔ (strongly_measurable f ∧ (∃ t, measurable_set t ∧ (∀ x ∈ tᶜ, f x = 0) ∧ sigma_finite (μ.restrict t))) := ⟨λ hf, ⟨hf.strongly_measurable, hf.exists_set_sigma_finite⟩, λ hf, hf.1.fin_strongly_measurable_of_set_sigma_finite hf.2.some_spec.1 hf.2.some_spec.2.1 hf.2.some_spec.2.2⟩ lemma ae_fin_strongly_measurable_zero {α β} {m : measurable_space α} (μ : measure α) [has_zero β] [topological_space β] : ae_fin_strongly_measurable (0 : α → β) μ := ⟨0, fin_strongly_measurable_zero, eventually_eq.rfl⟩ /-! ## Almost everywhere strongly measurable functions -/ lemma ae_strongly_measurable_const {α β} {m : measurable_space α} {μ : measure α} [topological_space β] {b : β} : ae_strongly_measurable (λ a : α, b) μ := strongly_measurable_const.ae_strongly_measurable @[to_additive] lemma ae_strongly_measurable_one {α β} {m : measurable_space α} {μ : measure α} [topological_space β] [has_one β] : ae_strongly_measurable (1 : α → β) μ := strongly_measurable_one.ae_strongly_measurable @[simp] lemma subsingleton.ae_strongly_measurable {m : measurable_space α} [topological_space β] [subsingleton β] {μ : measure α} (f : α → β) : ae_strongly_measurable f μ := (subsingleton.strongly_measurable f).ae_strongly_measurable @[simp] lemma subsingleton.ae_strongly_measurable' {m : measurable_space α} [topological_space β] [subsingleton α] {μ : measure α} (f : α → β) : ae_strongly_measurable f μ := (subsingleton.strongly_measurable' f).ae_strongly_measurable @[simp] lemma ae_strongly_measurable_zero_measure [measurable_space α] [topological_space β] (f : α → β) : ae_strongly_measurable f (0 : measure α) := begin nontriviality α, inhabit α, exact ⟨λ x, f default, strongly_measurable_const, rfl⟩ end lemma simple_func.ae_strongly_measurable {m : measurable_space α} {μ : measure α} [topological_space β] (f : α →ₛ β) : ae_strongly_measurable f μ := f.strongly_measurable.ae_strongly_measurable namespace ae_strongly_measurable variables {m : measurable_space α} {μ : measure α} [topological_space β] [topological_space γ] {f g : α → β} section mk /-- A `strongly_measurable` function such that `f =ᵐ[μ] hf.mk f`. See lemmas `strongly_measurable_mk` and `ae_eq_mk`. -/ protected noncomputable def mk (f : α → β) (hf : ae_strongly_measurable f μ) : α → β := hf.some lemma strongly_measurable_mk (hf : ae_strongly_measurable f μ) : strongly_measurable (hf.mk f) := hf.some_spec.1 lemma measurable_mk [pseudo_metrizable_space β] [measurable_space β] [borel_space β] (hf : ae_strongly_measurable f μ) : measurable (hf.mk f) := hf.strongly_measurable_mk.measurable lemma ae_eq_mk (hf : ae_strongly_measurable f μ) : f =ᵐ[μ] hf.mk f := hf.some_spec.2 protected lemma ae_measurable {β} [measurable_space β] [topological_space β] [pseudo_metrizable_space β] [borel_space β] {f : α → β} (hf : ae_strongly_measurable f μ) : ae_measurable f μ := ⟨hf.mk f, hf.strongly_measurable_mk.measurable, hf.ae_eq_mk⟩ end mk lemma congr (hf : ae_strongly_measurable f μ) (h : f =ᵐ[μ] g) : ae_strongly_measurable g μ := ⟨hf.mk f, hf.strongly_measurable_mk, h.symm.trans hf.ae_eq_mk⟩ lemma _root_.ae_strongly_measurable_congr (h : f =ᵐ[μ] g) : ae_strongly_measurable f μ ↔ ae_strongly_measurable g μ := ⟨λ hf, hf.congr h, λ hg, hg.congr h.symm⟩ lemma mono_measure {ν : measure α} (hf : ae_strongly_measurable f μ) (h : ν ≤ μ) : ae_strongly_measurable f ν := ⟨hf.mk f, hf.strongly_measurable_mk, eventually.filter_mono (ae_mono h) hf.ae_eq_mk⟩ protected lemma mono' {ν : measure α} (h : ae_strongly_measurable f μ) (h' : ν ≪ μ) : ae_strongly_measurable f ν := ⟨h.mk f, h.strongly_measurable_mk, h' h.ae_eq_mk⟩ lemma mono_set {s t} (h : s ⊆ t) (ht : ae_strongly_measurable f (μ.restrict t)) : ae_strongly_measurable f (μ.restrict s) := ht.mono_measure (restrict_mono h le_rfl) protected lemma restrict (hfm : ae_strongly_measurable f μ) {s} : ae_strongly_measurable f (μ.restrict s) := hfm.mono_measure measure.restrict_le_self lemma ae_mem_imp_eq_mk {s} (h : ae_strongly_measurable f (μ.restrict s)) : ∀ᵐ x ∂μ, x ∈ s → f x = h.mk f x := ae_imp_of_ae_restrict h.ae_eq_mk /-- The composition of a continuous function and an ae strongly measurable function is ae strongly measurable. -/ lemma _root_.continuous.comp_ae_strongly_measurable {g : β → γ} {f : α → β} (hg : continuous g) (hf : ae_strongly_measurable f μ) : ae_strongly_measurable (λ x, g (f x)) μ := ⟨_, hg.comp_strongly_measurable hf.strongly_measurable_mk, eventually_eq.fun_comp hf.ae_eq_mk g⟩ /-- A continuous function from `α` to `β` is ae strongly measurable when one of the two spaces is second countable. -/ lemma _root_.continuous.ae_strongly_measurable [topological_space α] [opens_measurable_space α] [pseudo_metrizable_space β] [second_countable_topology_either α β] (hf : continuous f) : ae_strongly_measurable f μ := hf.strongly_measurable.ae_strongly_measurable protected lemma prod_mk {f : α → β} {g : α → γ} (hf : ae_strongly_measurable f μ) (hg : ae_strongly_measurable g μ) : ae_strongly_measurable (λ x, (f x, g x)) μ := ⟨λ x, (hf.mk f x, hg.mk g x), hf.strongly_measurable_mk.prod_mk hg.strongly_measurable_mk, hf.ae_eq_mk.prod_mk hg.ae_eq_mk⟩ /-- In a space with second countable topology, measurable implies ae strongly measurable. -/ lemma _root_.measurable.ae_strongly_measurable {m : measurable_space α} {μ : measure α} [measurable_space β] [pseudo_metrizable_space β] [second_countable_topology β] [opens_measurable_space β] (hf : measurable f) : ae_strongly_measurable f μ := hf.strongly_measurable.ae_strongly_measurable section arithmetic @[to_additive] protected lemma mul [has_mul β] [has_continuous_mul β] (hf : ae_strongly_measurable f μ) (hg : ae_strongly_measurable g μ) : ae_strongly_measurable (f * g) μ := ⟨hf.mk f * hg.mk g, hf.strongly_measurable_mk.mul hg.strongly_measurable_mk, hf.ae_eq_mk.mul hg.ae_eq_mk⟩ @[to_additive] protected lemma mul_const [has_mul β] [has_continuous_mul β] (hf : ae_strongly_measurable f μ) (c : β) : ae_strongly_measurable (λ x, f x * c) μ := hf.mul ae_strongly_measurable_const @[to_additive] protected lemma const_mul [has_mul β] [has_continuous_mul β] (hf : ae_strongly_measurable f μ) (c : β) : ae_strongly_measurable (λ x, c * f x) μ := ae_strongly_measurable_const.mul hf @[to_additive] protected lemma inv [group β] [topological_group β] (hf : ae_strongly_measurable f μ) : ae_strongly_measurable (f⁻¹) μ := ⟨(hf.mk f)⁻¹, hf.strongly_measurable_mk.inv, hf.ae_eq_mk.inv⟩ @[to_additive] protected lemma div [group β] [topological_group β] (hf : ae_strongly_measurable f μ) (hg : ae_strongly_measurable g μ) : ae_strongly_measurable (f / g) μ := ⟨hf.mk f / hg.mk g, hf.strongly_measurable_mk.div hg.strongly_measurable_mk, hf.ae_eq_mk.div hg.ae_eq_mk⟩ @[to_additive] protected lemma smul {𝕜} [topological_space 𝕜] [has_smul 𝕜 β] [has_continuous_smul 𝕜 β] {f : α → 𝕜} {g : α → β} (hf : ae_strongly_measurable f μ) (hg : ae_strongly_measurable g μ) : ae_strongly_measurable (λ x, f x • g x) μ := continuous_smul.comp_ae_strongly_measurable (hf.prod_mk hg) protected lemma const_smul {𝕜} [has_smul 𝕜 β] [has_continuous_const_smul 𝕜 β] (hf : ae_strongly_measurable f μ) (c : 𝕜) : ae_strongly_measurable (c • f) μ := ⟨c • hf.mk f, hf.strongly_measurable_mk.const_smul c, hf.ae_eq_mk.const_smul c⟩ protected lemma const_smul' {𝕜} [has_smul 𝕜 β] [has_continuous_const_smul 𝕜 β] (hf : ae_strongly_measurable f μ) (c : 𝕜) : ae_strongly_measurable (λ x, c • (f x)) μ := hf.const_smul c @[to_additive] protected lemma smul_const {𝕜} [topological_space 𝕜] [has_smul 𝕜 β] [has_continuous_smul 𝕜 β] {f : α → 𝕜} (hf : ae_strongly_measurable f μ) (c : β) : ae_strongly_measurable (λ x, f x • c) μ := continuous_smul.comp_ae_strongly_measurable (hf.prod_mk ae_strongly_measurable_const) end arithmetic section order protected lemma sup [semilattice_sup β] [has_continuous_sup β] (hf : ae_strongly_measurable f μ) (hg : ae_strongly_measurable g μ) : ae_strongly_measurable (f ⊔ g) μ := ⟨hf.mk f ⊔ hg.mk g, hf.strongly_measurable_mk.sup hg.strongly_measurable_mk, hf.ae_eq_mk.sup hg.ae_eq_mk⟩ protected lemma inf [semilattice_inf β] [has_continuous_inf β] (hf : ae_strongly_measurable f μ) (hg : ae_strongly_measurable g μ) : ae_strongly_measurable (f ⊓ g) μ := ⟨hf.mk f ⊓ hg.mk g, hf.strongly_measurable_mk.inf hg.strongly_measurable_mk, hf.ae_eq_mk.inf hg.ae_eq_mk⟩ end order /-! ### Big operators: `∏` and `∑` -/ section monoid variables {M : Type*} [monoid M] [topological_space M] [has_continuous_mul M] @[to_additive] lemma _root_.list.ae_strongly_measurable_prod' (l : list (α → M)) (hl : ∀ f ∈ l, ae_strongly_measurable f μ) : ae_strongly_measurable l.prod μ := begin induction l with f l ihl, { exact ae_strongly_measurable_one }, rw [list.forall_mem_cons] at hl, rw [list.prod_cons], exact hl.1.mul (ihl hl.2) end @[to_additive] lemma _root_.list.ae_strongly_measurable_prod (l : list (α → M)) (hl : ∀ f ∈ l, ae_strongly_measurable f μ) : ae_strongly_measurable (λ x, (l.map (λ f : α → M, f x)).prod) μ := by simpa only [← pi.list_prod_apply] using l.ae_strongly_measurable_prod' hl end monoid section comm_monoid variables {M : Type*} [comm_monoid M] [topological_space M] [has_continuous_mul M] @[to_additive] lemma _root_.multiset.ae_strongly_measurable_prod' (l : multiset (α → M)) (hl : ∀ f ∈ l, ae_strongly_measurable f μ) : ae_strongly_measurable l.prod μ := by { rcases l with ⟨l⟩, simpa using l.ae_strongly_measurable_prod' (by simpa using hl) } @[to_additive] lemma _root_.multiset.ae_strongly_measurable_prod (s : multiset (α → M)) (hs : ∀ f ∈ s, ae_strongly_measurable f μ) : ae_strongly_measurable (λ x, (s.map (λ f : α → M, f x)).prod) μ := by simpa only [← pi.multiset_prod_apply] using s.ae_strongly_measurable_prod' hs @[to_additive] lemma _root_.finset.ae_strongly_measurable_prod' {ι : Type*} {f : ι → α → M} (s : finset ι) (hf : ∀i ∈ s, ae_strongly_measurable (f i) μ) : ae_strongly_measurable (∏ i in s, f i) μ := multiset.ae_strongly_measurable_prod' _ $ λ g hg, let ⟨i, hi, hg⟩ := multiset.mem_map.1 hg in (hg ▸ hf _ hi) @[to_additive] lemma _root_.finset.ae_strongly_measurable_prod {ι : Type*} {f : ι → α → M} (s : finset ι) (hf : ∀i ∈ s, ae_strongly_measurable (f i) μ) : ae_strongly_measurable (λ a, ∏ i in s, f i a) μ := by simpa only [← finset.prod_apply] using s.ae_strongly_measurable_prod' hf end comm_monoid section second_countable_ae_strongly_measurable variables [measurable_space β] /-- In a space with second countable topology, measurable implies strongly measurable. -/ lemma _root_.ae_measurable.ae_strongly_measurable [pseudo_metrizable_space β] [opens_measurable_space β] [second_countable_topology β] (hf : ae_measurable f μ) : ae_strongly_measurable f μ := ⟨hf.mk f, hf.measurable_mk.strongly_measurable, hf.ae_eq_mk⟩ lemma _root_.ae_strongly_measurable_id {α : Type*} [topological_space α] [pseudo_metrizable_space α] {m : measurable_space α} [opens_measurable_space α] [second_countable_topology α] {μ : measure α} : ae_strongly_measurable (id : α → α) μ := ae_measurable_id.ae_strongly_measurable /-- In a space with second countable topology, strongly measurable and measurable are equivalent. -/ lemma _root_.ae_strongly_measurable_iff_ae_measurable [pseudo_metrizable_space β] [borel_space β] [second_countable_topology β] : ae_strongly_measurable f μ ↔ ae_measurable f μ := ⟨λ h, h.ae_measurable, λ h, h.ae_strongly_measurable⟩ end second_countable_ae_strongly_measurable protected lemma dist {β : Type*} [pseudo_metric_space β] {f g : α → β} (hf : ae_strongly_measurable f μ) (hg : ae_strongly_measurable g μ) : ae_strongly_measurable (λ x, dist (f x) (g x)) μ := continuous_dist.comp_ae_strongly_measurable (hf.prod_mk hg) protected lemma norm {β : Type*} [normed_group β] {f : α → β} (hf : ae_strongly_measurable f μ) : ae_strongly_measurable (λ x, ∥f x∥) μ := continuous_norm.comp_ae_strongly_measurable hf protected lemma nnnorm {β : Type*} [normed_group β] {f : α → β} (hf : ae_strongly_measurable f μ) : ae_strongly_measurable (λ x, ∥f x∥₊) μ := continuous_nnnorm.comp_ae_strongly_measurable hf protected lemma ennnorm {β : Type*} [normed_group β] {f : α → β} (hf : ae_strongly_measurable f μ) : ae_measurable (λ a, (∥f a∥₊ : ℝ≥0∞)) μ := (ennreal.continuous_coe.comp_ae_strongly_measurable hf.nnnorm).ae_measurable protected lemma edist {β : Type*} [normed_group β] {f g : α → β} (hf : ae_strongly_measurable f μ) (hg : ae_strongly_measurable g μ) : ae_measurable (λ a, edist (f a) (g a)) μ := (continuous_edist.comp_ae_strongly_measurable (hf.prod_mk hg)).ae_measurable protected lemma real_to_nnreal {f : α → ℝ} (hf : ae_strongly_measurable f μ) : ae_strongly_measurable (λ x, (f x).to_nnreal) μ := continuous_real_to_nnreal.comp_ae_strongly_measurable hf section variables {𝕜 : Type*} {E : Type*} [is_R_or_C 𝕜] [inner_product_space 𝕜 E] local notation `⟪`x`, `y`⟫` := @inner 𝕜 _ _ x y protected lemma re {f : α → 𝕜} (hf : ae_strongly_measurable f μ) : ae_strongly_measurable (λ x, is_R_or_C.re (f x)) μ := is_R_or_C.continuous_re.comp_ae_strongly_measurable hf protected lemma im {f : α → 𝕜} (hf : ae_strongly_measurable f μ) : ae_strongly_measurable (λ x, is_R_or_C.im (f x)) μ := is_R_or_C.continuous_im.comp_ae_strongly_measurable hf protected lemma inner {m : measurable_space α} {μ : measure α} {f g : α → E} (hf : ae_strongly_measurable f μ) (hg : ae_strongly_measurable g μ) : ae_strongly_measurable (λ x, ⟪f x, g x⟫) μ := continuous_inner.comp_ae_strongly_measurable (hf.prod_mk hg) end lemma _root_.ae_strongly_measurable_indicator_iff [has_zero β] {s : set α} (hs : measurable_set s) : ae_strongly_measurable (indicator s f) μ ↔ ae_strongly_measurable f (μ.restrict s) := begin split, { intro h, exact (h.mono_measure measure.restrict_le_self).congr (indicator_ae_eq_restrict hs) }, { intro h, refine ⟨indicator s (h.mk f), h.strongly_measurable_mk.indicator hs, _⟩, have A : s.indicator f =ᵐ[μ.restrict s] s.indicator (h.mk f) := (indicator_ae_eq_restrict hs).trans (h.ae_eq_mk.trans $ (indicator_ae_eq_restrict hs).symm), have B : s.indicator f =ᵐ[μ.restrict sᶜ] s.indicator (h.mk f) := (indicator_ae_eq_restrict_compl hs).trans (indicator_ae_eq_restrict_compl hs).symm, exact ae_of_ae_restrict_of_ae_restrict_compl _ A B }, end protected lemma indicator [has_zero β] (hfm : ae_strongly_measurable f μ) {s : set α} (hs : measurable_set s) : ae_strongly_measurable (s.indicator f) μ := (ae_strongly_measurable_indicator_iff hs).mpr hfm.restrict lemma _root_.ae_strongly_measurable_of_ae_strongly_measurable_trim {α} {m m0 : measurable_space α} {μ : measure α} (hm : m ≤ m0) {f : α → β} (hf : ae_strongly_measurable f (μ.trim hm)) : ae_strongly_measurable f μ := ⟨hf.mk f, strongly_measurable.mono hf.strongly_measurable_mk hm, ae_eq_of_ae_eq_trim hf.ae_eq_mk⟩ lemma comp_ae_measurable {γ : Type*} {mγ : measurable_space γ} {mα : measurable_space α} {f : γ → α} {μ : measure γ} (hg : ae_strongly_measurable g (measure.map f μ)) (hf : ae_measurable f μ) : ae_strongly_measurable (g ∘ f) μ := ⟨(hg.mk g) ∘ hf.mk f, hg.strongly_measurable_mk.comp_measurable hf.measurable_mk, (ae_eq_comp hf hg.ae_eq_mk).trans ((hf.ae_eq_mk).fun_comp (hg.mk g))⟩ lemma comp_measurable {γ : Type*} {mγ : measurable_space γ} {mα : measurable_space α} {f : γ → α} {μ : measure γ} (hg : ae_strongly_measurable g (measure.map f μ)) (hf : measurable f) : ae_strongly_measurable (g ∘ f) μ := hg.comp_ae_measurable hf.ae_measurable lemma comp_measurable' {γ : Type*} {mγ : measurable_space γ} {mα : measurable_space α} {f : γ → α} {μ : measure γ} {ν : measure α} (hg : ae_strongly_measurable g ν) (hf : measurable f) (h : μ.map f ≪ ν) : ae_strongly_measurable (g ∘ f) μ := (hg.mono' h).comp_measurable hf lemma is_separable_ae_range (hf : ae_strongly_measurable f μ) : ∃ (t : set β), is_separable t ∧ ∀ᵐ x ∂μ, f x ∈ t := begin refine ⟨range (hf.mk f), hf.strongly_measurable_mk.is_separable_range, _⟩, filter_upwards [hf.ae_eq_mk] with x hx, simp [hx] end /-- A function is almost everywhere strongly measurable if and only if it is almost everywhere measurable, and up to a zero measure set its range is contained in a separable set. -/ theorem _root_.ae_strongly_measurable_iff_ae_measurable_separable [pseudo_metrizable_space β] [measurable_space β] [borel_space β] : ae_strongly_measurable f μ ↔ (ae_measurable f μ ∧ ∃ (t : set β), is_separable t ∧ ∀ᵐ x ∂μ, f x ∈ t) := begin refine ⟨λ H, ⟨H.ae_measurable, H.is_separable_ae_range⟩, _⟩, rintros ⟨H, ⟨t, t_sep, ht⟩⟩, rcases eq_empty_or_nonempty t with rfl|h₀, { simp only [mem_empty_eq, eventually_false_iff_eq_bot, ae_eq_bot] at ht, rw ht, exact ae_strongly_measurable_zero_measure f }, { obtain ⟨g, g_meas, gt, fg⟩ : ∃ (g : α → β), measurable g ∧ range g ⊆ t ∧ f =ᵐ[μ] g := H.exists_ae_eq_range_subset ht h₀, refine ⟨g, _, fg⟩, exact strongly_measurable_iff_measurable_separable.2 ⟨g_meas, t_sep.mono gt⟩ } end lemma _root_.measurable_embedding.ae_strongly_measurable_map_iff {γ : Type*} {mγ : measurable_space γ} {mα : measurable_space α} {f : γ → α} {μ : measure γ} (hf : measurable_embedding f) {g : α → β} : ae_strongly_measurable g (measure.map f μ) ↔ ae_strongly_measurable (g ∘ f) μ := begin refine ⟨λ H, H.comp_measurable hf.measurable, _⟩, rintro ⟨g₁, hgm₁, heq⟩, rcases hf.exists_strongly_measurable_extend hgm₁ (λ x, ⟨g x⟩) with ⟨g₂, hgm₂, rfl⟩, exact ⟨g₂, hgm₂, hf.ae_map_iff.2 heq⟩ end lemma _root_.embedding.ae_strongly_measurable_comp_iff [pseudo_metrizable_space β] [pseudo_metrizable_space γ] {g : β → γ} {f : α → β} (hg : embedding g) : ae_strongly_measurable (λ x, g (f x)) μ ↔ ae_strongly_measurable f μ := begin letI := pseudo_metrizable_space_pseudo_metric γ, borelize [β, γ], refine ⟨λ H, ae_strongly_measurable_iff_ae_measurable_separable.2 ⟨_, _⟩, λ H, hg.continuous.comp_ae_strongly_measurable H⟩, { let G : β → range g := cod_restrict g (range g) mem_range_self, have hG : closed_embedding G := { closed_range := begin convert is_closed_univ, apply eq_univ_of_forall, rintros ⟨-, ⟨x, rfl⟩⟩, exact mem_range_self x end, .. hg.cod_restrict _ _ }, have : ae_measurable (G ∘ f) μ := ae_measurable.subtype_mk H.ae_measurable, exact hG.measurable_embedding.ae_measurable_comp_iff.1 this }, { rcases (ae_strongly_measurable_iff_ae_measurable_separable.1 H).2 with ⟨t, ht, h't⟩, exact ⟨g⁻¹' t, hg.is_separable_preimage ht, h't⟩ } end lemma _root_.measure_theory.measure_preserving.ae_strongly_measurable_comp_iff {β : Type*} {f : α → β} {mα : measurable_space α} {μa : measure α} {mβ : measurable_space β} {μb : measure β} (hf : measure_preserving f μa μb) (h₂ : measurable_embedding f) {g : β → γ} : ae_strongly_measurable (g ∘ f) μa ↔ ae_strongly_measurable g μb := by rw [← hf.map_eq, h₂.ae_strongly_measurable_map_iff] /-- An almost everywhere sequential limit of almost everywhere strongly measurable functions is almost everywhere strongly measurable. -/ lemma _root_.ae_strongly_measurable_of_tendsto_ae {ι : Type*} [pseudo_metrizable_space β] (u : filter ι) [ne_bot u] [is_countably_generated u] {f : ι → α → β} {g : α → β} (hf : ∀ i, ae_strongly_measurable (f i) μ) (lim : ∀ᵐ x ∂μ, tendsto (λ n, f n x) u (𝓝 (g x))) : ae_strongly_measurable g μ := begin borelize β, refine ae_strongly_measurable_iff_ae_measurable_separable.2 ⟨_, _⟩, { exact ae_measurable_of_tendsto_metrizable_ae _ (λ n, (hf n).ae_measurable) lim }, { rcases u.exists_seq_tendsto with ⟨v, hv⟩, have : ∀ (n : ℕ), ∃ (t : set β), is_separable t ∧ f (v n) ⁻¹' t ∈ μ.ae := λ n, (ae_strongly_measurable_iff_ae_measurable_separable.1 (hf (v n))).2, choose t t_sep ht using this, refine ⟨closure (⋃ i, (t i)), (is_separable_Union (λ i, (t_sep i))).closure, _⟩, filter_upwards [ae_all_iff.2 ht, lim] with x hx h'x, apply mem_closure_of_tendsto ((h'x).comp hv), apply eventually_of_forall (λ n, _), apply mem_Union_of_mem n, exact hx n } end /-- If a sequence of almost everywhere strongly measurable functions converges almost everywhere, one can select a strongly measurable function as the almost everywhere limit. -/ lemma _root_.exists_strongly_measurable_limit_of_tendsto_ae [pseudo_metrizable_space β] {f : ℕ → α → β} (hf : ∀ n, ae_strongly_measurable (f n) μ) (h_ae_tendsto : ∀ᵐ x ∂μ, ∃ l : β, tendsto (λ n, f n x) at_top (𝓝 l)) : ∃ (f_lim : α → β) (hf_lim_meas : strongly_measurable f_lim), ∀ᵐ x ∂μ, tendsto (λ n, f n x) at_top (𝓝 (f_lim x)) := begin borelize β, obtain ⟨g, g_meas, hg⟩ : ∃ (g : α → β) (g_meas : measurable g), ∀ᵐ x ∂μ, tendsto (λ n, f n x) at_top (𝓝 (g x)) := measurable_limit_of_tendsto_metrizable_ae (λ n, (hf n).ae_measurable) h_ae_tendsto, have Hg : ae_strongly_measurable g μ := ae_strongly_measurable_of_tendsto_ae _ hf hg, refine ⟨Hg.mk g, Hg.strongly_measurable_mk, _⟩, filter_upwards [hg, Hg.ae_eq_mk] with x hx h'x, rwa h'x at hx, end lemma sum_measure [pseudo_metrizable_space β] {m : measurable_space α} {μ : ι → measure α} (h : ∀ i, ae_strongly_measurable f (μ i)) : ae_strongly_measurable f (measure.sum μ) := begin borelize β, refine ae_strongly_measurable_iff_ae_measurable_separable.2 ⟨ae_measurable.sum_measure (λ i, (h i).ae_measurable), _⟩, have A : ∀ (i : ι), ∃ (t : set β), is_separable t ∧ f ⁻¹' t ∈ (μ i).ae := λ i, (ae_strongly_measurable_iff_ae_measurable_separable.1 (h i)).2, choose t t_sep ht using A, refine ⟨(⋃ i, t i), is_separable_Union t_sep, _⟩, simp only [measure.ae_sum_eq, mem_Union, eventually_supr], assume i, filter_upwards [ht i] with x hx, exact ⟨i, hx⟩ end @[simp] lemma _root_.ae_strongly_measurable_sum_measure_iff [pseudo_metrizable_space β] {m : measurable_space α} {μ : ι → measure α} : ae_strongly_measurable f (sum μ) ↔ ∀ i, ae_strongly_measurable f (μ i) := ⟨λ h i, h.mono_measure (measure.le_sum _ _), sum_measure⟩ @[simp] lemma _root_.ae_strongly_measurable_add_measure_iff [pseudo_metrizable_space β] {ν : measure α} : ae_strongly_measurable f (μ + ν) ↔ ae_strongly_measurable f μ ∧ ae_strongly_measurable f ν := by { rw [← sum_cond, ae_strongly_measurable_sum_measure_iff, bool.forall_bool, and.comm], refl } lemma add_measure [pseudo_metrizable_space β] {ν : measure α} {f : α → β} (hμ : ae_strongly_measurable f μ) (hν : ae_strongly_measurable f ν) : ae_strongly_measurable f (μ + ν) := ae_strongly_measurable_add_measure_iff.2 ⟨hμ, hν⟩ protected lemma Union [pseudo_metrizable_space β] {s : ι → set α} (h : ∀ i, ae_strongly_measurable f (μ.restrict (s i))) : ae_strongly_measurable f (μ.restrict (⋃ i, s i)) := (sum_measure h).mono_measure $ restrict_Union_le @[simp] lemma _root_.ae_strongly_measurable_Union_iff [pseudo_metrizable_space β] {s : ι → set α} : ae_strongly_measurable f (μ.restrict (⋃ i, s i)) ↔ ∀ i, ae_strongly_measurable f (μ.restrict (s i)) := ⟨λ h i, h.mono_measure $ restrict_mono (subset_Union _ _) le_rfl, ae_strongly_measurable.Union⟩ @[simp] lemma _root_.ae_strongly_measurable_union_iff [pseudo_metrizable_space β] {s t : set α} : ae_strongly_measurable f (μ.restrict (s ∪ t)) ↔ ae_strongly_measurable f (μ.restrict s) ∧ ae_strongly_measurable f (μ.restrict t) := by simp only [union_eq_Union, ae_strongly_measurable_Union_iff, bool.forall_bool, cond, and.comm] lemma smul_measure {R : Type*} [monoid R] [distrib_mul_action R ℝ≥0∞] [is_scalar_tower R ℝ≥0∞ ℝ≥0∞] (h : ae_strongly_measurable f μ) (c : R) : ae_strongly_measurable f (c • μ) := ⟨h.mk f, h.strongly_measurable_mk, ae_smul_measure h.ae_eq_mk c⟩ section normed_space variables {𝕜 : Type*} [nondiscrete_normed_field 𝕜] [complete_space 𝕜] variables {E : Type*} [normed_group E] [normed_space 𝕜 E] lemma _root_.ae_strongly_measurable_smul_const_iff {f : α → 𝕜} {c : E} (hc : c ≠ 0) : ae_strongly_measurable (λ x, f x • c) μ ↔ ae_strongly_measurable f μ := (closed_embedding_smul_left hc).to_embedding.ae_strongly_measurable_comp_iff end normed_space section mul_action variables {G : Type*} [group G] [mul_action G β] [has_continuous_const_smul G β] lemma _root_.ae_strongly_measurable_const_smul_iff (c : G) : ae_strongly_measurable (λ x, c • f x) μ ↔ ae_strongly_measurable f μ := ⟨λ h, by simpa only [inv_smul_smul] using h.const_smul' c⁻¹, λ h, h.const_smul c⟩ variables {G₀ : Type*} [group_with_zero G₀] [mul_action G₀ β] [has_continuous_const_smul G₀ β] lemma _root_.ae_strongly_measurable_const_smul_iff₀ {c : G₀} (hc : c ≠ 0) : ae_strongly_measurable (λ x, c • f x) μ ↔ ae_strongly_measurable f μ := begin refine ⟨λ h, _, λ h, h.const_smul c⟩, convert h.const_smul' c⁻¹, simp [smul_smul, inv_mul_cancel hc] end end mul_action section continuous_linear_map_nondiscrete_normed_field variables {𝕜 : Type*} [nondiscrete_normed_field 𝕜] variables {E : Type*} [normed_group E] [normed_space 𝕜 E] variables {F : Type*} [normed_group F] [normed_space 𝕜 F] variables {G : Type*} [normed_group G] [normed_space 𝕜 G] lemma _root_.strongly_measurable.apply_continuous_linear_map {m : measurable_space α} {φ : α → F →L[𝕜] E} (hφ : strongly_measurable φ) (v : F) : strongly_measurable (λ a, φ a v) := (continuous_linear_map.apply 𝕜 E v).continuous.comp_strongly_measurable hφ lemma apply_continuous_linear_map {φ : α → F →L[𝕜] E} (hφ : ae_strongly_measurable φ μ) (v : F) : ae_strongly_measurable (λ a, φ a v) μ := (continuous_linear_map.apply 𝕜 E v).continuous.comp_ae_strongly_measurable hφ lemma _root_.continuous_linear_map.ae_strongly_measurable_comp₂ (L : E →L[𝕜] F →L[𝕜] G) {f : α → E} {g : α → F} (hf : ae_strongly_measurable f μ) (hg : ae_strongly_measurable g μ) : ae_strongly_measurable (λ x, L (f x) (g x)) μ := L.continuous₂.comp_ae_strongly_measurable $ hf.prod_mk hg end continuous_linear_map_nondiscrete_normed_field lemma _root_.ae_strongly_measurable_with_density_iff {E : Type*} [normed_group E] [normed_space ℝ E] {f : α → ℝ≥0} (hf : measurable f) {g : α → E} : ae_strongly_measurable g (μ.with_density (λ x, (f x : ℝ≥0∞))) ↔ ae_strongly_measurable (λ x, (f x : ℝ) • g x) μ := begin split, { rintros ⟨g', g'meas, hg'⟩, have A : measurable_set {x : α | f x ≠ 0} := (hf (measurable_set_singleton 0)).compl, refine ⟨λ x, (f x : ℝ) • g' x, hf.coe_nnreal_real.strongly_measurable.smul g'meas, _⟩, apply @ae_of_ae_restrict_of_ae_restrict_compl _ _ _ {x | f x ≠ 0}, { rw [eventually_eq, ae_with_density_iff hf.coe_nnreal_ennreal] at hg', rw ae_restrict_iff' A, filter_upwards [hg'] with a ha h'a, have : (f a : ℝ≥0∞) ≠ 0, by simpa only [ne.def, ennreal.coe_eq_zero] using h'a, rw ha this }, { filter_upwards [ae_restrict_mem A.compl] with x hx, simp only [not_not, mem_set_of_eq, mem_compl_eq] at hx, simp [hx] } }, { rintros ⟨g', g'meas, hg'⟩, refine ⟨λ x, (f x : ℝ)⁻¹ • g' x, hf.coe_nnreal_real.inv.strongly_measurable.smul g'meas, _⟩, rw [eventually_eq, ae_with_density_iff hf.coe_nnreal_ennreal], filter_upwards [hg'] with x hx h'x, rw [← hx, smul_smul, _root_.inv_mul_cancel, one_smul], simp only [ne.def, ennreal.coe_eq_zero] at h'x, simpa only [nnreal.coe_eq_zero, ne.def] using h'x } end end ae_strongly_measurable /-! ## Almost everywhere finitely strongly measurable functions -/ namespace ae_fin_strongly_measurable variables {m : measurable_space α} {μ : measure α} [topological_space β] {f g : α → β} section mk variables [has_zero β] /-- A `fin_strongly_measurable` function such that `f =ᵐ[μ] hf.mk f`. See lemmas `fin_strongly_measurable_mk` and `ae_eq_mk`. -/ protected noncomputable def mk (f : α → β) (hf : ae_fin_strongly_measurable f μ) : α → β := hf.some lemma fin_strongly_measurable_mk (hf : ae_fin_strongly_measurable f μ) : fin_strongly_measurable (hf.mk f) μ := hf.some_spec.1 lemma ae_eq_mk (hf : ae_fin_strongly_measurable f μ) : f =ᵐ[μ] hf.mk f := hf.some_spec.2 protected lemma ae_measurable {β} [has_zero β] [measurable_space β] [topological_space β] [pseudo_metrizable_space β] [borel_space β] {f : α → β} (hf : ae_fin_strongly_measurable f μ) : ae_measurable f μ := ⟨hf.mk f, hf.fin_strongly_measurable_mk.measurable, hf.ae_eq_mk⟩ end mk section arithmetic protected lemma mul [monoid_with_zero β] [has_continuous_mul β] (hf : ae_fin_strongly_measurable f μ) (hg : ae_fin_strongly_measurable g μ) : ae_fin_strongly_measurable (f * g) μ := ⟨hf.mk f * hg.mk g, hf.fin_strongly_measurable_mk.mul hg.fin_strongly_measurable_mk, hf.ae_eq_mk.mul hg.ae_eq_mk⟩ protected lemma add [add_monoid β] [has_continuous_add β] (hf : ae_fin_strongly_measurable f μ) (hg : ae_fin_strongly_measurable g μ) : ae_fin_strongly_measurable (f + g) μ := ⟨hf.mk f + hg.mk g, hf.fin_strongly_measurable_mk.add hg.fin_strongly_measurable_mk, hf.ae_eq_mk.add hg.ae_eq_mk⟩ protected lemma neg [add_group β] [topological_add_group β] (hf : ae_fin_strongly_measurable f μ) : ae_fin_strongly_measurable (-f) μ := ⟨-hf.mk f, hf.fin_strongly_measurable_mk.neg, hf.ae_eq_mk.neg⟩ protected lemma sub [add_group β] [has_continuous_sub β] (hf : ae_fin_strongly_measurable f μ) (hg : ae_fin_strongly_measurable g μ) : ae_fin_strongly_measurable (f - g) μ := ⟨hf.mk f - hg.mk g, hf.fin_strongly_measurable_mk.sub hg.fin_strongly_measurable_mk, hf.ae_eq_mk.sub hg.ae_eq_mk⟩ protected lemma const_smul {𝕜} [topological_space 𝕜] [add_monoid β] [monoid 𝕜] [distrib_mul_action 𝕜 β] [has_continuous_smul 𝕜 β] (hf : ae_fin_strongly_measurable f μ) (c : 𝕜) : ae_fin_strongly_measurable (c • f) μ := ⟨c • hf.mk f, hf.fin_strongly_measurable_mk.const_smul c, hf.ae_eq_mk.const_smul c⟩ end arithmetic section order variables [has_zero β] protected lemma sup [semilattice_sup β] [has_continuous_sup β] (hf : ae_fin_strongly_measurable f μ) (hg : ae_fin_strongly_measurable g μ) : ae_fin_strongly_measurable (f ⊔ g) μ := ⟨hf.mk f ⊔ hg.mk g, hf.fin_strongly_measurable_mk.sup hg.fin_strongly_measurable_mk, hf.ae_eq_mk.sup hg.ae_eq_mk⟩ protected lemma inf [semilattice_inf β] [has_continuous_inf β] (hf : ae_fin_strongly_measurable f μ) (hg : ae_fin_strongly_measurable g μ) : ae_fin_strongly_measurable (f ⊓ g) μ := ⟨hf.mk f ⊓ hg.mk g, hf.fin_strongly_measurable_mk.inf hg.fin_strongly_measurable_mk, hf.ae_eq_mk.inf hg.ae_eq_mk⟩ end order variables [has_zero β] [t2_space β] lemma exists_set_sigma_finite (hf : ae_fin_strongly_measurable f μ) : ∃ t, measurable_set t ∧ f =ᵐ[μ.restrict tᶜ] 0 ∧ sigma_finite (μ.restrict t) := begin rcases hf with ⟨g, hg, hfg⟩, obtain ⟨t, ht, hgt_zero, htμ⟩ := hg.exists_set_sigma_finite, refine ⟨t, ht, _, htμ⟩, refine eventually_eq.trans (ae_restrict_of_ae hfg) _, rw [eventually_eq, ae_restrict_iff' ht.compl], exact eventually_of_forall hgt_zero, end /-- A measurable set `t` such that `f =ᵐ[μ.restrict tᶜ] 0` and `sigma_finite (μ.restrict t)`. -/ def sigma_finite_set (hf : ae_fin_strongly_measurable f μ) : set α := hf.exists_set_sigma_finite.some protected lemma measurable_set (hf : ae_fin_strongly_measurable f μ) : measurable_set hf.sigma_finite_set := hf.exists_set_sigma_finite.some_spec.1 lemma ae_eq_zero_compl (hf : ae_fin_strongly_measurable f μ) : f =ᵐ[μ.restrict hf.sigma_finite_setᶜ] 0 := hf.exists_set_sigma_finite.some_spec.2.1 instance sigma_finite_restrict (hf : ae_fin_strongly_measurable f μ) : sigma_finite (μ.restrict hf.sigma_finite_set) := hf.exists_set_sigma_finite.some_spec.2.2 end ae_fin_strongly_measurable section second_countable_topology variables {G : Type*} {p : ℝ≥0∞} {m m0 : measurable_space α} {μ : measure α} [normed_group G] [measurable_space G] [borel_space G] [second_countable_topology G] {f : α → G} /-- In a space with second countable topology and a sigma-finite measure, `fin_strongly_measurable` and `measurable` are equivalent. -/ lemma fin_strongly_measurable_iff_measurable {m0 : measurable_space α} (μ : measure α) [sigma_finite μ] : fin_strongly_measurable f μ ↔ measurable f := ⟨λ h, h.measurable, λ h, (measurable.strongly_measurable h).fin_strongly_measurable μ⟩ /-- In a space with second countable topology and a sigma-finite measure, `ae_fin_strongly_measurable` and `ae_measurable` are equivalent. -/ lemma ae_fin_strongly_measurable_iff_ae_measurable {m0 : measurable_space α} (μ : measure α) [sigma_finite μ] : ae_fin_strongly_measurable f μ ↔ ae_measurable f μ := by simp_rw [ae_fin_strongly_measurable, ae_measurable, fin_strongly_measurable_iff_measurable] end second_countable_topology lemma measurable_uncurry_of_continuous_of_measurable {α β ι : Type*} [topological_space ι] [metrizable_space ι] [measurable_space ι] [second_countable_topology ι] [opens_measurable_space ι] {mβ : measurable_space β} [topological_space β] [pseudo_metrizable_space β] [borel_space β] {m : measurable_space α} {u : ι → α → β} (hu_cont : ∀ x, continuous (λ i, u i x)) (h : ∀ i, measurable (u i)) : measurable (function.uncurry u) := begin obtain ⟨t_sf, ht_sf⟩ : ∃ t : ℕ → simple_func ι ι, ∀ j x, tendsto (λ n, u (t n j) x) at_top (𝓝 $ u j x), { have h_str_meas : strongly_measurable (id : ι → ι), from strongly_measurable_id, refine ⟨h_str_meas.approx, λ j x, _⟩, exact ((hu_cont x).tendsto j).comp (h_str_meas.tendsto_approx j), }, let U := λ (n : ℕ) (p : ι × α), u (t_sf n p.fst) p.snd, have h_tendsto : tendsto U at_top (𝓝 (λ p, u p.fst p.snd)), { rw tendsto_pi_nhds, exact λ p, ht_sf p.fst p.snd, }, refine measurable_of_tendsto_metrizable (λ n, _) h_tendsto, haveI : encodable (t_sf n).range, from fintype.to_encodable ↥(t_sf n).range, have h_meas : measurable (λ (p : (t_sf n).range × α), u ↑p.fst p.snd), { have : (λ (p : ↥((t_sf n).range) × α), u ↑(p.fst) p.snd) = (λ (p : α × ((t_sf n).range)), u ↑(p.snd) p.fst) ∘ prod.swap := rfl, rw [this, @measurable_swap_iff α ↥((t_sf n).range) β m], exact measurable_from_prod_encodable (λ j, h j), }, have : (λ p : ι × α, u (t_sf n p.fst) p.snd) = (λ p : ↥(t_sf n).range × α, u p.fst p.snd) ∘ (λ p : ι × α, (⟨t_sf n p.fst, simple_func.mem_range_self _ _⟩, p.snd)) := rfl, simp_rw [U, this], refine h_meas.comp (measurable.prod_mk _ measurable_snd), exact ((t_sf n).measurable.comp measurable_fst).subtype_mk, end lemma strongly_measurable_uncurry_of_continuous_of_strongly_measurable {α β ι : Type*} [topological_space ι] [metrizable_space ι] [measurable_space ι] [second_countable_topology ι] [opens_measurable_space ι] [topological_space β] [pseudo_metrizable_space β] [measurable_space α] {u : ι → α → β} (hu_cont : ∀ x, continuous (λ i, u i x)) (h : ∀ i, strongly_measurable (u i)) : strongly_measurable (function.uncurry u) := begin borelize β, obtain ⟨t_sf, ht_sf⟩ : ∃ t : ℕ → simple_func ι ι, ∀ j x, tendsto (λ n, u (t n j) x) at_top (𝓝 $ u j x), { have h_str_meas : strongly_measurable (id : ι → ι), from strongly_measurable_id, refine ⟨h_str_meas.approx, λ j x, _⟩, exact ((hu_cont x).tendsto j).comp (h_str_meas.tendsto_approx j), }, let U := λ (n : ℕ) (p : ι × α), u (t_sf n p.fst) p.snd, have h_tendsto : tendsto U at_top (𝓝 (λ p, u p.fst p.snd)), { rw tendsto_pi_nhds, exact λ p, ht_sf p.fst p.snd, }, refine strongly_measurable_of_tendsto _ (λ n, _) h_tendsto, haveI : encodable (t_sf n).range, from fintype.to_encodable ↥(t_sf n).range, have h_str_meas : strongly_measurable (λ (p : (t_sf n).range × α), u ↑p.fst p.snd), { refine strongly_measurable_iff_measurable_separable.2 ⟨_, _⟩, { have : (λ (p : ↥((t_sf n).range) × α), u ↑(p.fst) p.snd) = (λ (p : α × ((t_sf n).range)), u ↑(p.snd) p.fst) ∘ prod.swap := rfl, rw [this, measurable_swap_iff], exact measurable_from_prod_encodable (λ j, (h j).measurable), }, { have : is_separable (⋃ (i : (t_sf n).range), range (u i)) := is_separable_Union (λ i, (h i).is_separable_range), apply this.mono, rintros _ ⟨⟨i, x⟩, rfl⟩, simp only [mem_Union, mem_range], exact ⟨i, x, rfl⟩ } }, have : (λ p : ι × α, u (t_sf n p.fst) p.snd) = (λ p : ↥(t_sf n).range × α, u p.fst p.snd) ∘ (λ p : ι × α, (⟨t_sf n p.fst, simple_func.mem_range_self _ _⟩, p.snd)) := rfl, simp_rw [U, this], refine h_str_meas.comp_measurable (measurable.prod_mk _ measurable_snd), exact ((t_sf n).measurable.comp measurable_fst).subtype_mk, end end measure_theory
0f13496751cead787a2edfe8a49e0c3d752bad38
2eab05920d6eeb06665e1a6df77b3157354316ad
/src/algebra/periodic.lean
dc17d8fa17ae165b88c6ebc2de034dc7f67720ec
[ "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
14,798
lean
/- Copyright (c) 2021 Benjamin Davidson. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Benjamin Davidson -/ import algebra.module.opposites import algebra.order.archimedean import data.int.parity /-! # Periodicity In this file we define and then prove facts about periodic and antiperiodic functions. ## Main definitions * `function.periodic`: A function `f` is *periodic* if `∀ x, f (x + c) = f x`. `f` is referred to as periodic with period `c` or `c`-periodic. * `function.antiperiodic`: A function `f` is *antiperiodic* if `∀ x, f (x + c) = -f x`. `f` is referred to as antiperiodic with antiperiod `c` or `c`-antiperiodic. Note that any `c`-antiperiodic function will necessarily also be `2*c`-periodic. ## Tags period, periodic, periodicity, antiperiodic -/ variables {α β γ : Type*} {f g : α → β} {c c₁ c₂ x : α} namespace function /-! ### Periodicity -/ /-- A function `f` is said to be `periodic` with period `c` if for all `x`, `f (x + c) = f x`. -/ @[simp] def periodic [has_add α] (f : α → β) (c : α) : Prop := ∀ x : α, f (x + c) = f x lemma periodic.funext [has_add α] (h : periodic f c) : (λ x, f (x + c)) = f := funext h lemma periodic.comp [has_add α] (h : periodic f c) (g : β → γ) : periodic (g ∘ f) c := by simp * at * lemma periodic.comp_add_hom [has_add α] [has_add γ] (h : periodic f c) (g : add_hom γ α) (g_inv : α → γ) (hg : right_inverse g_inv g) : periodic (f ∘ g) (g_inv c) := λ x, by simp only [hg c, h (g x), add_hom.map_add, comp_app] @[to_additive] lemma periodic.mul [has_add α] [has_mul β] (hf : periodic f c) (hg : periodic g c) : periodic (f * g) c := by simp * at * @[to_additive] lemma periodic.div [has_add α] [has_div β] (hf : periodic f c) (hg : periodic g c) : periodic (f / g) c := by simp * at * lemma periodic.const_smul [add_monoid α] [group γ] [distrib_mul_action γ α] (h : periodic f c) (a : γ) : periodic (λ x, f (a • x)) (a⁻¹ • c) := λ x, by simpa only [smul_add, smul_inv_smul] using h (a • x) lemma periodic.const_smul₀ [add_comm_monoid α] [division_ring γ] [module γ α] (h : periodic f c) (a : γ) : periodic (λ x, f (a • x)) (a⁻¹ • c) := begin intro x, by_cases ha : a = 0, { simp only [ha, zero_smul] }, simpa only [smul_add, smul_inv_smul₀ ha] using h (a • x), end lemma periodic.const_mul [division_ring α] (h : periodic f c) (a : α) : periodic (λ x, f (a * x)) (a⁻¹ * c) := h.const_smul₀ a lemma periodic.const_inv_smul [add_monoid α] [group γ] [distrib_mul_action γ α] (h : periodic f c) (a : γ) : periodic (λ x, f (a⁻¹ • x)) (a • c) := by simpa only [inv_inv] using h.const_smul a⁻¹ lemma periodic.const_inv_smul₀ [add_comm_monoid α] [division_ring γ] [module γ α] (h : periodic f c) (a : γ) : periodic (λ x, f (a⁻¹ • x)) (a • c) := by simpa only [inv_inv₀] using h.const_smul₀ a⁻¹ lemma periodic.const_inv_mul [division_ring α] (h : periodic f c) (a : α) : periodic (λ x, f (a⁻¹ * x)) (a * c) := h.const_inv_smul₀ a lemma periodic.mul_const [division_ring α] (h : periodic f c) (a : α) : periodic (λ x, f (x * a)) (c * a⁻¹) := h.const_smul₀ $ opposite.op a lemma periodic.mul_const' [division_ring α] (h : periodic f c) (a : α) : periodic (λ x, f (x * a)) (c / a) := by simpa only [div_eq_mul_inv] using h.mul_const a lemma periodic.mul_const_inv [division_ring α] (h : periodic f c) (a : α) : periodic (λ x, f (x * a⁻¹)) (c * a) := h.const_inv_smul₀ $ opposite.op a lemma periodic.div_const [division_ring α] (h : periodic f c) (a : α) : periodic (λ x, f (x / a)) (c * a) := by simpa only [div_eq_mul_inv] using h.mul_const_inv a lemma periodic.add_period [add_semigroup α] (h1 : periodic f c₁) (h2 : periodic f c₂) : periodic f (c₁ + c₂) := by simp [*, ← add_assoc] at * lemma periodic.sub_eq [add_group α] (h : periodic f c) (x : α) : f (x - c) = f x := by simpa only [sub_add_cancel] using (h (x - c)).symm lemma periodic.sub_eq' [add_comm_group α] (h : periodic f c) : f (c - x) = f (-x) := by simpa only [sub_eq_neg_add] using h (-x) lemma periodic.neg [add_group α] (h : periodic f c) : periodic f (-c) := by simpa only [sub_eq_add_neg, periodic] using h.sub_eq lemma periodic.sub_period [add_comm_group α] (h1 : periodic f c₁) (h2 : periodic f c₂) : periodic f (c₁ - c₂) := let h := h2.neg in by simp [*, sub_eq_add_neg, add_comm c₁, ← add_assoc] at * lemma periodic.nsmul [add_monoid α] (h : periodic f c) (n : ℕ) : periodic f (n • c) := by induction n; simp [nat.succ_eq_add_one, add_nsmul, ← add_assoc, zero_nsmul, *] at * lemma periodic.nat_mul [semiring α] (h : periodic f c) (n : ℕ) : periodic f (n * c) := by simpa only [nsmul_eq_mul] using h.nsmul n lemma periodic.neg_nsmul [add_group α] (h : periodic f c) (n : ℕ) : periodic f (-(n • c)) := (h.nsmul n).neg lemma periodic.neg_nat_mul [ring α] (h : periodic f c) (n : ℕ) : periodic f (-(n * c)) := (h.nat_mul n).neg lemma periodic.sub_nsmul_eq [add_group α] (h : periodic f c) (n : ℕ) : f (x - n • c) = f x := by simpa only [sub_eq_add_neg] using h.neg_nsmul n x lemma periodic.sub_nat_mul_eq [ring α] (h : periodic f c) (n : ℕ) : f (x - n * c) = f x := by simpa only [nsmul_eq_mul] using h.sub_nsmul_eq n lemma periodic.nsmul_sub_eq [add_comm_group α] (h : periodic f c) (n : ℕ) : f (n • c - x) = f (-x) := by simpa only [sub_eq_neg_add] using h.nsmul n (-x) lemma periodic.nat_mul_sub_eq [ring α] (h : periodic f c) (n : ℕ) : f (n * c - x) = f (-x) := by simpa only [sub_eq_neg_add] using h.nat_mul n (-x) lemma periodic.gsmul [add_group α] (h : periodic f c) (n : ℤ) : periodic f (n • c) := begin cases n, { simpa only [int.of_nat_eq_coe, gsmul_coe_nat] using h.nsmul n }, { simpa only [gsmul_neg_succ_of_nat] using (h.nsmul n.succ).neg }, end lemma periodic.int_mul [ring α] (h : periodic f c) (n : ℤ) : periodic f (n * c) := by simpa only [gsmul_eq_mul] using h.gsmul n lemma periodic.sub_gsmul_eq [add_group α] (h : periodic f c) (n : ℤ) : f (x - n • c) = f x := (h.gsmul n).sub_eq x lemma periodic.sub_int_mul_eq [ring α] (h : periodic f c) (n : ℤ) : f (x - n * c) = f x := (h.int_mul n).sub_eq x lemma periodic.gsmul_sub_eq [add_comm_group α] (h : periodic f c) (n : ℤ) : f (n • c - x) = f (-x) := by simpa only [sub_eq_neg_add] using h.gsmul n (-x) lemma periodic.int_mul_sub_eq [ring α] (h : periodic f c) (n : ℤ) : f (n * c - x) = f (-x) := by simpa only [sub_eq_neg_add] using h.int_mul n (-x) lemma periodic.eq [add_zero_class α] (h : periodic f c) : f c = f 0 := by simpa only [zero_add] using h 0 lemma periodic.neg_eq [add_group α] (h : periodic f c) : f (-c) = f 0 := h.neg.eq lemma periodic.nsmul_eq [add_monoid α] (h : periodic f c) (n : ℕ) : f (n • c) = f 0 := (h.nsmul n).eq lemma periodic.nat_mul_eq [semiring α] (h : periodic f c) (n : ℕ) : f (n * c) = f 0 := (h.nat_mul n).eq lemma periodic.gsmul_eq [add_group α] (h : periodic f c) (n : ℤ) : f (n • c) = f 0 := (h.gsmul n).eq lemma periodic.int_mul_eq [ring α] (h : periodic f c) (n : ℤ) : f (n * c) = f 0 := (h.int_mul n).eq /-- If a function `f` is `periodic` with positive period `c`, then for all `x` there exists some `y ∈ Ico 0 c` such that `f x = f y`. -/ lemma periodic.exists_mem_Ico [linear_ordered_add_comm_group α] [archimedean α] (h : periodic f c) (hc : 0 < c) (x) : ∃ y ∈ set.Ico 0 c, f x = f y := let ⟨n, H⟩ := linear_ordered_add_comm_group.exists_int_smul_near_of_pos' hc x in ⟨x - n • c, H, (h.sub_gsmul_eq n).symm⟩ lemma periodic_with_period_zero [add_zero_class α] (f : α → β) : periodic f 0 := λ x, by rw add_zero /-! ### Antiperiodicity -/ /-- A function `f` is said to be `antiperiodic` with antiperiod `c` if for all `x`, `f (x + c) = -f x`. -/ @[simp] def antiperiodic [has_add α] [has_neg β] (f : α → β) (c : α) : Prop := ∀ x : α, f (x + c) = -f x lemma antiperiodic.funext [has_add α] [has_neg β] (h : antiperiodic f c) : (λ x, f (x + c)) = -f := funext h lemma antiperiodic.funext' [has_add α] [add_group β] (h : antiperiodic f c) : (λ x, -f (x + c)) = f := (eq_neg_iff_eq_neg.mp h.funext).symm /-- If a function is `antiperiodic` with antiperiod `c`, then it is also `periodic` with period `2 * c`. -/ lemma antiperiodic.periodic [semiring α] [add_group β] (h : antiperiodic f c) : periodic f (2 * c) := by simp [two_mul, ← add_assoc, h _] lemma antiperiodic.eq [add_zero_class α] [has_neg β] (h : antiperiodic f c) : f c = -f 0 := by simpa only [zero_add] using h 0 lemma antiperiodic.nat_even_mul_periodic [semiring α] [add_group β] (h : antiperiodic f c) (n : ℕ) : periodic f (n * (2 * c)) := h.periodic.nat_mul n lemma antiperiodic.nat_odd_mul_antiperiodic [semiring α] [add_group β] (h : antiperiodic f c) (n : ℕ) : antiperiodic f (n * (2 * c) + c) := λ x, by rw [← add_assoc, h, h.periodic.nat_mul] lemma antiperiodic.int_even_mul_periodic [ring α] [add_group β] (h : antiperiodic f c) (n : ℤ) : periodic f (n * (2 * c)) := h.periodic.int_mul n lemma antiperiodic.int_odd_mul_antiperiodic [ring α] [add_group β] (h : antiperiodic f c) (n : ℤ) : antiperiodic f (n * (2 * c) + c) := λ x, by rw [← add_assoc, h, h.periodic.int_mul] lemma antiperiodic.nat_mul_eq_of_eq_zero [comm_semiring α] [add_group β] (h : antiperiodic f c) (hi : f 0 = 0) (n : ℕ) : f (n * c) = 0 := begin rcases nat.even_or_odd n with ⟨k, rfl⟩ | ⟨k, rfl⟩; have hk : (k : α) * (2 * c) = 2 * k * c := by rw [mul_left_comm, ← mul_assoc], { simpa [hk, hi] using (h.nat_even_mul_periodic k).eq }, { simpa [add_mul, hk, hi] using (h.nat_odd_mul_antiperiodic k).eq }, end lemma antiperiodic.int_mul_eq_of_eq_zero [comm_ring α] [add_group β] (h : antiperiodic f c) (hi : f 0 = 0) (n : ℤ) : f (n * c) = 0 := begin rcases int.even_or_odd n with ⟨k, rfl⟩ | ⟨k, rfl⟩; have hk : (k : α) * (2 * c) = 2 * k * c := by rw [mul_left_comm, ← mul_assoc], { simpa [hk, hi] using (h.int_even_mul_periodic k).eq }, { simpa [add_mul, hk, hi] using (h.int_odd_mul_antiperiodic k).eq }, end lemma antiperiodic.sub_eq [add_group α] [add_group β] (h : antiperiodic f c) (x : α) : f (x - c) = -f x := by simp only [eq_neg_iff_eq_neg.mp (h (x - c)), sub_add_cancel] lemma antiperiodic.sub_eq' [add_comm_group α] [add_group β] (h : antiperiodic f c) : f (c - x) = -f (-x) := by simpa only [sub_eq_neg_add] using h (-x) lemma antiperiodic.neg [add_group α] [add_group β] (h : antiperiodic f c) : antiperiodic f (-c) := by simpa only [sub_eq_add_neg, antiperiodic] using h.sub_eq lemma antiperiodic.neg_eq [add_group α] [add_group β] (h : antiperiodic f c) : f (-c) = -f 0 := by simpa only [zero_add] using h.neg 0 lemma antiperiodic.const_smul [add_monoid α] [has_neg β] [group γ] [distrib_mul_action γ α] (h : antiperiodic f c) (a : γ) : antiperiodic (λ x, f (a • x)) (a⁻¹ • c) := λ x, by simpa only [smul_add, smul_inv_smul] using h (a • x) lemma antiperiodic.const_smul₀ [add_comm_monoid α] [has_neg β] [division_ring γ] [module γ α] (h : antiperiodic f c) {a : γ} (ha : a ≠ 0) : antiperiodic (λ x, f (a • x)) (a⁻¹ • c) := λ x, by simpa only [smul_add, smul_inv_smul₀ ha] using h (a • x) lemma antiperiodic.const_mul [division_ring α] [has_neg β] (h : antiperiodic f c) {a : α} (ha : a ≠ 0) : antiperiodic (λ x, f (a * x)) (a⁻¹ * c) := h.const_smul₀ ha lemma antiperiodic.const_inv_smul [add_monoid α] [has_neg β] [group γ] [distrib_mul_action γ α] (h : antiperiodic f c) (a : γ) : antiperiodic (λ x, f (a⁻¹ • x)) (a • c) := by simpa only [inv_inv] using h.const_smul a⁻¹ lemma antiperiodic.const_inv_smul₀ [add_comm_monoid α] [has_neg β] [division_ring γ] [module γ α] (h : antiperiodic f c) {a : γ} (ha : a ≠ 0) : antiperiodic (λ x, f (a⁻¹ • x)) (a • c) := by simpa only [inv_inv₀] using h.const_smul₀ (inv_ne_zero ha) lemma antiperiodic.const_inv_mul [division_ring α] [has_neg β] (h : antiperiodic f c) {a : α} (ha : a ≠ 0) : antiperiodic (λ x, f (a⁻¹ * x)) (a * c) := h.const_inv_smul₀ ha lemma antiperiodic.mul_const [division_ring α] [has_neg β] (h : antiperiodic f c) {a : α} (ha : a ≠ 0) : antiperiodic (λ x, f (x * a)) (c * a⁻¹) := h.const_smul₀ $ (opposite.op_ne_zero_iff a).mpr ha lemma antiperiodic.mul_const' [division_ring α] [has_neg β] (h : antiperiodic f c) {a : α} (ha : a ≠ 0) : antiperiodic (λ x, f (x * a)) (c / a) := by simpa only [div_eq_mul_inv] using h.mul_const ha lemma antiperiodic.mul_const_inv [division_ring α] [has_neg β] (h : antiperiodic f c) {a : α} (ha : a ≠ 0) : antiperiodic (λ x, f (x * a⁻¹)) (c * a) := h.const_inv_smul₀ $ (opposite.op_ne_zero_iff a).mpr ha lemma antiperiodic.div_inv [division_ring α] [has_neg β] (h : antiperiodic f c) {a : α} (ha : a ≠ 0) : antiperiodic (λ x, f (x / a)) (c * a) := by simpa only [div_eq_mul_inv] using h.mul_const_inv ha lemma antiperiodic.add [add_group α] [add_group β] (h1 : antiperiodic f c₁) (h2 : antiperiodic f c₂) : periodic f (c₁ + c₂) := by simp [*, ← add_assoc] at * lemma antiperiodic.sub [add_comm_group α] [add_group β] (h1 : antiperiodic f c₁) (h2 : antiperiodic f c₂) : periodic f (c₁ - c₂) := let h := h2.neg in by simp [*, sub_eq_add_neg, add_comm c₁, ← add_assoc] at * lemma periodic.add_antiperiod [add_group α] [add_group β] (h1 : periodic f c₁) (h2 : antiperiodic f c₂) : antiperiodic f (c₁ + c₂) := by simp [*, ← add_assoc] at * lemma periodic.sub_antiperiod [add_comm_group α] [add_group β] (h1 : periodic f c₁) (h2 : antiperiodic f c₂) : antiperiodic f (c₁ - c₂) := let h := h2.neg in by simp [*, sub_eq_add_neg, add_comm c₁, ← add_assoc] at * lemma periodic.add_antiperiod_eq [add_group α] [add_group β] (h1 : periodic f c₁) (h2 : antiperiodic f c₂) : f (c₁ + c₂) = -f 0 := (h1.add_antiperiod h2).eq lemma periodic.sub_antiperiod_eq [add_comm_group α] [add_group β] (h1 : periodic f c₁) (h2 : antiperiodic f c₂) : f (c₁ - c₂) = -f 0 := (h1.sub_antiperiod h2).eq lemma antiperiodic.mul [has_add α] [ring β] (hf : antiperiodic f c) (hg : antiperiodic g c) : periodic (f * g) c := by simp * at * lemma antiperiodic.div [has_add α] [division_ring β] (hf : antiperiodic f c) (hg : antiperiodic g c) : periodic (f / g) c := by simp [*, neg_div_neg_eq] at * end function
0a8519591f5b326be5d26ac954bfebc566472c0e
bf532e3e865883a676110e756f800e0ddeb465be
/data/nat/sqrt.lean
91eceffc5da37412784badb00167dca3cb324c8b
[ "Apache-2.0" ]
permissive
aqjune/mathlib
da42a97d9e6670d2efaa7d2aa53ed3585dafc289
f7977ff5a6bcf7e5c54eec908364ceb40dafc795
refs/heads/master
1,631,213,225,595
1,521,089,840,000
1,521,089,840,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
6,352
lean
/- Copyright (c) 2015 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura, Johannes Hölzl, Mario Carneiro An efficient binary implementation of a (sqrt n) function that returns s s.t. s*s ≤ n ≤ s*s + s + s -/ import data.nat.basic algebra.ordered_group algebra.ring tactic namespace nat theorem sqrt_aux_dec {b} (h : b ≠ 0) : shiftr b 2 < b := begin simp [shiftr_eq_div_pow], apply (nat.div_lt_iff_lt_mul _ _ (dec_trivial : 4 > 0)).2, have := nat.mul_lt_mul_of_pos_left (dec_trivial : 1 < 4) (nat.pos_of_ne_zero h), rwa mul_one at this end def sqrt_aux : ℕ → ℕ → ℕ → ℕ | b r n := if b0 : b = 0 then r else let b' := shiftr b 2 in have b' < b, from sqrt_aux_dec b0, match (n - (r + b : ℕ) : ℤ) with | (n' : ℕ) := sqrt_aux b' (div2 r + b) n' | _ := sqrt_aux b' (div2 r) n end /-- `sqrt n` is the square root of a natural number `n`. If `n` is not a perfect square, it returns the largest `k:ℕ` such that `k*k ≤ n`. -/ def sqrt (n : ℕ) : ℕ := match size n with | 0 := 0 | succ s := sqrt_aux (shiftl 1 (bit0 (div2 s))) 0 n end theorem sqrt_aux_0 (r n) : sqrt_aux 0 r n = r := by rw sqrt_aux; simp local attribute [simp] sqrt_aux_0 theorem sqrt_aux_1 {r n b} (h : b ≠ 0) {n'} (h₂ : r + b + n' = n) : sqrt_aux b r n = sqrt_aux (shiftr b 2) (div2 r + b) n' := by rw sqrt_aux; simp only [h, h₂.symm, int.coe_nat_add, if_false]; rw [add_comm _ (n':ℤ), add_sub_cancel, sqrt_aux._match_1] theorem sqrt_aux_2 {r n b} (h : b ≠ 0) (h₂ : n < r + b) : sqrt_aux b r n = sqrt_aux (shiftr b 2) (div2 r) n := begin rw sqrt_aux; simp only [h, h₂, if_false], cases int.eq_neg_succ_of_lt_zero (sub_lt_zero.2 (int.coe_nat_lt_coe_nat_of_lt h₂)) with k e, rw [e, sqrt_aux._match_1] end private def is_sqrt (n q : ℕ) : Prop := q*q ≤ n ∧ n < (q+1)*(q+1) private lemma sqrt_aux_is_sqrt_lemma (m r n) (h₁ : r*r ≤ n) (m') (hm : shiftr (2^m * 2^m) 2 = m') (H1 : n < (r + 2^m) * (r + 2^m) → is_sqrt n (sqrt_aux m' (r * 2^m) (n - r * r))) (H2 : (r + 2^m) * (r + 2^m) ≤ n → is_sqrt n (sqrt_aux m' ((r + 2^m) * 2^m) (n - (r + 2^m) * (r + 2^m)))) : is_sqrt n (sqrt_aux (2^m * 2^m) ((2*r)*2^m) (n - r*r)) := begin have b0 := have b0:_, from ne_of_gt (@pos_pow_of_pos 2 m dec_trivial), nat.mul_ne_zero b0 b0, have lb : n - r * r < 2 * r * 2^m + 2^m * 2^m ↔ n < (r+2^m)*(r+2^m), { rw [nat.sub_lt_right_iff_lt_add h₁], simp [left_distrib, right_distrib, two_mul, mul_comm, mul_assoc] }, have re : div2 (2 * r * 2^m) = r * 2^m, { rw [div2_val, mul_assoc, nat.mul_div_cancel_left _ (dec_trivial:2>0)] }, cases lt_or_ge n ((r+2^m)*(r+2^m)) with hl hl, { rw [sqrt_aux_2 b0 (lb.2 hl), hm, re], apply H1 hl }, { cases le.dest hl with n' e, rw [@sqrt_aux_1 (2 * r * 2^m) (n-r*r) (2^m * 2^m) b0 (n - (r + 2^m) * (r + 2^m)), hm, re, ← right_distrib], { apply H2 hl }, apply eq.symm, apply nat.sub_eq_of_eq_add, rw [← add_assoc, (_ : r*r + _ = _)], exact (nat.add_sub_cancel' hl).symm, simp [left_distrib, right_distrib, two_mul, mul_comm, mul_assoc] }, end private lemma sqrt_aux_is_sqrt (n) : ∀ m r, r*r ≤ n → n < (r + 2^(m+1)) * (r + 2^(m+1)) → is_sqrt n (sqrt_aux (2^m * 2^m) (2*r*2^m) (n - r*r)) | 0 r h₁ h₂ := by apply sqrt_aux_is_sqrt_lemma 0 r n h₁ 0 rfl; intros; simp; [exact ⟨h₁, a⟩, exact ⟨a, h₂⟩] | (m+1) r h₁ h₂ := begin apply sqrt_aux_is_sqrt_lemma (m+1) r n h₁ (2^m * 2^m) (by simp [shiftr, pow_succ, div2_val, mul_comm, mul_left_comm]; repeat {rw @nat.mul_div_cancel_left _ 2 dec_trivial}); intros, { have := sqrt_aux_is_sqrt m r h₁ a, simpa [pow_succ, mul_comm, mul_left_comm] }, { rw [pow_succ, mul_two, ← add_assoc] at h₂, have := sqrt_aux_is_sqrt m (r + 2^(m+1)) a h₂, rwa show (r + 2^(m + 1)) * 2^(m+1) = 2 * (r + 2^(m + 1)) * 2^m, by simp [pow_succ, mul_comm, mul_left_comm] } end private lemma sqrt_is_sqrt (n : ℕ) : is_sqrt n (sqrt n) := begin generalize e : size n = s, cases s with s; simp [e, sqrt], { rw [size_eq_zero.1 e, is_sqrt], exact dec_trivial }, { have := sqrt_aux_is_sqrt n (div2 s) 0 (zero_le _), simp [show 2^div2 s * 2^div2 s = shiftl 1 (bit0 (div2 s)), by { generalize: div2 s = x, change bit0 x with x+x, rw [one_shiftl, pow_add] }] at this, apply this, rw [← pow_add, ← mul_two], apply size_le.1, rw e, apply (@div_lt_iff_lt_mul _ _ 2 dec_trivial).1, rw [div2_val], apply lt_succ_self } end theorem sqrt_le (n : ℕ) : sqrt n * sqrt n ≤ n := (sqrt_is_sqrt n).left theorem lt_succ_sqrt (n : ℕ) : n < succ (sqrt n) * succ (sqrt n) := (sqrt_is_sqrt n).right theorem sqrt_le_add (n : ℕ) : n ≤ sqrt n * sqrt n + sqrt n + sqrt n := by rw ← succ_mul; exact le_of_lt_succ (lt_succ_sqrt n) theorem le_sqrt {m n : ℕ} : m ≤ sqrt n ↔ m*m ≤ n := ⟨λ h, le_trans (mul_self_le_mul_self h) (sqrt_le n), λ h, le_of_lt_succ $ mul_self_lt_mul_self_iff.2 $ lt_of_le_of_lt h (lt_succ_sqrt n)⟩ theorem sqrt_lt {m n : ℕ} : sqrt m < n ↔ m < n*n := le_iff_le_iff_lt_iff_lt.1 le_sqrt theorem sqrt_le_self (n : ℕ) : sqrt n ≤ n := le_trans (le_mul_self _) (sqrt_le n) theorem sqrt_le_sqrt {m n : ℕ} (h : m ≤ n) : sqrt m ≤ sqrt n := le_sqrt.2 (le_trans (sqrt_le _) h) theorem sqrt_eq_zero {n : ℕ} : sqrt n = 0 ↔ n = 0 := ⟨λ h, eq_zero_of_le_zero $ le_of_lt_succ $ (@sqrt_lt n 1).1 $ by rw [h]; exact dec_trivial, λ e, e.symm ▸ rfl⟩ theorem le_three_of_sqrt_eq_one {n : ℕ} (h : sqrt n = 1) : n ≤ 3 := le_of_lt_succ $ (@sqrt_lt n 2).1 $ by rw [h]; exact dec_trivial theorem sqrt_lt_self {n : ℕ} (h : n > 1) : sqrt n < n := sqrt_lt.2 $ by have := nat.mul_lt_mul_of_pos_left h (lt_of_succ_lt h); rwa [mul_one] at this theorem sqrt_pos {n : ℕ} : sqrt n > 0 ↔ n > 0 := le_sqrt theorem sqrt_add_eq (n : ℕ) {a : ℕ} (h : a ≤ n + n) : sqrt (n*n + a) = n := le_antisymm (le_of_lt_succ $ sqrt_lt.2 $ by rw [succ_mul, mul_succ, add_succ, add_assoc]; exact lt_succ_of_le (nat.add_le_add_left h _)) (le_sqrt.2 $ nat.le_add_right _ _) theorem sqrt_eq (n : ℕ) : sqrt (n*n) = n := sqrt_add_eq n (zero_le _) end nat
b8dba6121b074f4c9b4f61dbd6bd31d60b986f5e
abd85493667895c57a7507870867b28124b3998f
/src/ring_theory/multiplicity.lean
6027df32b36573db986216a0de2f502c1297b86c
[ "Apache-2.0" ]
permissive
pechersky/mathlib
d56eef16bddb0bfc8bc552b05b7270aff5944393
f1df14c2214ee114c9738e733efd5de174deb95d
refs/heads/master
1,666,714,392,571
1,591,747,567,000
1,591,747,567,000
270,557,274
0
0
Apache-2.0
1,591,597,975,000
1,591,597,974,000
null
UTF-8
Lean
false
false
17,352
lean
/- Copyright (c) 2018 Robert Y. Lewis. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Robert Y. Lewis, Chris Hughes -/ import algebra.associated import data.int.gcd import algebra.big_operators variables {α : Type*} open nat roption open_locale big_operators theorem nat.find_le {p q : ℕ → Prop} [decidable_pred p] [decidable_pred q] (h : ∀ n, q n → p n) (hp : ∃ n, p n) (hq : ∃ n, q n) : nat.find hp ≤ nat.find hq := nat.find_min' _ ((h _) (nat.find_spec hq)) /-- `multiplicity a b` returns the largest natural number `n` such that `a ^ n ∣ b`, as an `enat` or natural with infinity. If `∀ n, a ^ n ∣ b`, then it returns `⊤`-/ def multiplicity [comm_semiring α] [decidable_rel ((∣) : α → α → Prop)] (a b : α) : enat := ⟨∃ n : ℕ, ¬a ^ (n + 1) ∣ b, λ h, nat.find h⟩ namespace multiplicity section comm_semiring variables [comm_semiring α] @[reducible] def finite (a b : α) : Prop := ∃ n : ℕ, ¬a ^ (n + 1) ∣ b lemma finite_iff_dom [decidable_rel ((∣) : α → α → Prop)] {a b : α} : finite a b ↔ (multiplicity a b).dom := iff.rfl lemma finite_def {a b : α} : finite a b ↔ ∃ n : ℕ, ¬a ^ (n + 1) ∣ b := iff.rfl @[norm_cast] theorem int.coe_nat_multiplicity (a b : ℕ) : multiplicity (a : ℤ) (b : ℤ) = multiplicity a b := begin apply roption.ext', { repeat {rw [← finite_iff_dom, finite_def]}, norm_cast, simp }, { intros h1 h2, apply _root_.le_antisymm; { apply nat.find_le, norm_cast, simp }} end lemma not_finite_iff_forall {a b : α} : (¬ finite a b) ↔ ∀ n : ℕ, a ^ n ∣ b := ⟨λ h n, nat.cases_on n (one_dvd _) (by simpa [finite, classical.not_not] using h), by simp [finite, multiplicity, classical.not_not]; tauto⟩ lemma not_unit_of_finite {a b : α} (h : finite a b) : ¬is_unit a := let ⟨n, hn⟩ := h in mt (is_unit_iff_forall_dvd.1 ∘ is_unit_pow (n + 1)) $ λ h, hn (h b) lemma ne_zero_of_finite {a b : α} (h : finite a b) : b ≠ 0 := let ⟨n, hn⟩ := h in λ hb, by simpa [hb] using hn lemma finite_of_finite_mul_left {a b c : α} : finite a (b * c) → finite a c := λ ⟨n, hn⟩, ⟨n, λ h, hn (dvd.trans h (by simp [_root_.mul_pow]))⟩ lemma finite_of_finite_mul_right {a b c : α} : finite a (b * c) → finite a b := by rw mul_comm; exact finite_of_finite_mul_left variable [decidable_rel ((∣) : α → α → Prop)] lemma pow_dvd_of_le_multiplicity {a b : α} {k : ℕ} : (k : enat) ≤ multiplicity a b → a ^ k ∣ b := nat.cases_on k (λ _, one_dvd _) (λ k ⟨h₁, h₂⟩, by_contradiction (λ hk, (nat.find_min _ (lt_of_succ_le (h₂ ⟨k, hk⟩)) hk))) lemma pow_multiplicity_dvd {a b : α} (h : finite a b) : a ^ get (multiplicity a b) h ∣ b := pow_dvd_of_le_multiplicity (by rw enat.coe_get) lemma is_greatest {a b : α} {m : ℕ} (hm : multiplicity a b < m) : ¬a ^ m ∣ b := λ h, have finite a b, from enat.dom_of_le_some (le_of_lt hm), by rw [← enat.coe_get (finite_iff_dom.1 this), enat.coe_lt_coe] at hm; exact nat.find_spec this (dvd.trans (pow_dvd_pow _ hm) h) lemma is_greatest' {a b : α} {m : ℕ} (h : finite a b) (hm : get (multiplicity a b) h < m) : ¬a ^ m ∣ b := is_greatest (by rwa [← enat.coe_lt_coe, enat.coe_get] at hm) lemma unique {a b : α} {k : ℕ} (hk : a ^ k ∣ b) (hsucc : ¬a ^ (k + 1) ∣ b) : (k : enat) = multiplicity a b := le_antisymm (le_of_not_gt (λ hk', is_greatest hk' hk)) $ have finite a b, from ⟨k, hsucc⟩, by rw [← enat.coe_get (finite_iff_dom.1 this), enat.coe_le_coe]; exact nat.find_min' _ hsucc lemma unique' {a b : α} {k : ℕ} (hk : a ^ k ∣ b) (hsucc : ¬ a ^ (k + 1) ∣ b) : k = get (multiplicity a b) ⟨k, hsucc⟩ := by rw [← enat.coe_inj, enat.coe_get, unique hk hsucc] lemma le_multiplicity_of_pow_dvd {a b : α} {k : ℕ} (hk : a ^ k ∣ b) : (k : enat) ≤ multiplicity a b := le_of_not_gt $ λ hk', is_greatest hk' hk lemma pow_dvd_iff_le_multiplicity {a b : α} {k : ℕ} : a ^ k ∣ b ↔ (k : enat) ≤ multiplicity a b := ⟨le_multiplicity_of_pow_dvd, pow_dvd_of_le_multiplicity⟩ lemma multiplicity_lt_iff_neg_dvd {a b : α} {k : ℕ} : multiplicity a b < (k : enat) ↔ ¬ a ^ k ∣ b := by { rw [pow_dvd_iff_le_multiplicity, not_le] } lemma eq_some_iff {a b : α} {n : ℕ} : multiplicity a b = (n : enat) ↔ a ^ n ∣ b ∧ ¬a ^ (n + 1) ∣ b := ⟨λ h, let ⟨h₁, h₂⟩ := eq_some_iff.1 h in h₂ ▸ ⟨pow_multiplicity_dvd _, is_greatest (by conv_lhs {rw ← enat.coe_get h₁ }; rw [enat.coe_lt_coe]; exact lt_succ_self _)⟩, λ h, eq_some_iff.2 ⟨⟨n, h.2⟩, eq.symm $ unique' h.1 h.2⟩⟩ lemma eq_top_iff {a b : α} : multiplicity a b = ⊤ ↔ ∀ n : ℕ, a ^ n ∣ b := ⟨λ h n, nat.cases_on n (one_dvd _) (λ n, by_contradiction (not_exists.1 (eq_none_iff'.1 h) n : _)), λ h, eq_none_iff.2 (λ n ⟨⟨_, h₁⟩, _⟩, h₁ (h _))⟩ @[simp] protected lemma zero (a : α) : multiplicity a 0 = ⊤ := roption.eq_none_iff.2 (λ n ⟨⟨k, hk⟩, _⟩, hk (dvd_zero _)) lemma one_right {a : α} (ha : ¬is_unit a) : multiplicity a 1 = 0 := eq_some_iff.2 ⟨dvd_refl _, mt is_unit_iff_dvd_one.2 $ by simpa⟩ @[simp] lemma get_one_right {a : α} (ha : finite a 1) : get (multiplicity a 1) ha = 0 := get_eq_iff_eq_some.2 (eq_some_iff.2 ⟨dvd_refl _, by simpa [is_unit_iff_dvd_one.symm] using not_unit_of_finite ha⟩) @[simp] lemma multiplicity_unit {a : α} (b : α) (ha : is_unit a) : multiplicity a b = ⊤ := eq_top_iff.2 (λ _, is_unit_iff_forall_dvd.1 (is_unit_pow _ ha) _) @[simp] lemma one_left (b : α) : multiplicity 1 b = ⊤ := by simp [eq_top_iff] lemma multiplicity_eq_zero_of_not_dvd {a b : α} (ha : ¬a ∣ b) : multiplicity a b = 0 := eq_some_iff.2 (by simpa) lemma eq_top_iff_not_finite {a b : α} : multiplicity a b = ⊤ ↔ ¬ finite a b := roption.eq_none_iff' open_locale classical lemma multiplicity_le_multiplicity_iff {a b c d : α} : multiplicity a b ≤ multiplicity c d ↔ (∀ n : ℕ, a ^ n ∣ b → c ^ n ∣ d) := ⟨λ h n hab, (pow_dvd_of_le_multiplicity (le_trans (le_multiplicity_of_pow_dvd hab) h)), λ h, if hab : finite a b then by rw [← enat.coe_get (finite_iff_dom.1 hab)]; exact le_multiplicity_of_pow_dvd (h _ (pow_multiplicity_dvd _)) else have ∀ n : ℕ, c ^ n ∣ d, from λ n, h n (not_finite_iff_forall.1 hab _), by rw [eq_top_iff_not_finite.2 hab, eq_top_iff_not_finite.2 (not_finite_iff_forall.2 this)]⟩ lemma min_le_multiplicity_add {p a b : α} : min (multiplicity p a) (multiplicity p b) ≤ multiplicity p (a + b) := (le_total (multiplicity p a) (multiplicity p b)).elim (λ h, by rw [min_eq_left h, multiplicity_le_multiplicity_iff]; exact λ n hn, dvd_add hn (multiplicity_le_multiplicity_iff.1 h n hn)) (λ h, by rw [min_eq_right h, multiplicity_le_multiplicity_iff]; exact λ n hn, dvd_add (multiplicity_le_multiplicity_iff.1 h n hn) hn) lemma dvd_of_multiplicity_pos {a b : α} (h : (0 : enat) < multiplicity a b) : a ∣ b := by rw [← _root_.pow_one a]; exact pow_dvd_of_le_multiplicity (enat.pos_iff_one_le.1 h) lemma finite_nat_iff {a b : ℕ} : finite a b ↔ (a ≠ 1 ∧ 0 < b) := begin rw [← not_iff_not, not_finite_iff_forall, not_and_distrib, ne.def, not_not, not_lt, nat.le_zero_iff], exact ⟨λ h, or_iff_not_imp_right.2 (λ hb, have ha : a ≠ 0, from λ ha, by simpa [ha] using h 1, by_contradiction (λ ha1 : a ≠ 1, have ha_gt_one : 1 < a, from have ∀ a : ℕ, a ≤ 1 → a ≠ 0 → a ≠ 1 → false, from dec_trivial, lt_of_not_ge (λ ha', this a ha' ha ha1), not_lt_of_ge (le_of_dvd (nat.pos_of_ne_zero hb) (h b)) (by simp only [nat.pow_eq_pow]; exact lt_pow_self ha_gt_one b))), λ h, by cases h; simp *⟩ end lemma finite_int_iff_nat_abs_finite {a b : ℤ} : finite a b ↔ finite a.nat_abs b.nat_abs := begin rw [finite_def, finite_def], conv in (a ^ _ ∣ b) { rw [← int.nat_abs_dvd_abs_iff, int.nat_abs_pow, ← pow_eq_pow] } end lemma finite_int_iff {a b : ℤ} : finite a b ↔ (a.nat_abs ≠ 1 ∧ b ≠ 0) := begin have := int.nat_abs_eq a, have := @int.nat_abs_ne_zero_of_ne_zero b, rw [finite_int_iff_nat_abs_finite, finite_nat_iff, nat.pos_iff_ne_zero], split; finish end instance decidable_nat : decidable_rel (λ a b : ℕ, (multiplicity a b).dom) := λ a b, decidable_of_iff _ finite_nat_iff.symm instance decidable_int : decidable_rel (λ a b : ℤ, (multiplicity a b).dom) := λ a b, decidable_of_iff _ finite_int_iff.symm end comm_semiring section comm_ring variables [comm_ring α] [decidable_rel ((∣) : α → α → Prop)] open_locale classical @[simp] protected lemma neg (a b : α) : multiplicity a (-b) = multiplicity a b := roption.ext' (by simp only [multiplicity]; conv in (_ ∣ - _) {rw dvd_neg}) (λ h₁ h₂, enat.coe_inj.1 (by rw [enat.coe_get]; exact eq.symm (unique ((dvd_neg _ _).2 (pow_multiplicity_dvd _)) (mt (dvd_neg _ _).1 (is_greatest' _ (lt_succ_self _)))))) lemma multiplicity_add_of_gt {p a b : α} (h : multiplicity p b < multiplicity p a) : multiplicity p (a + b) = multiplicity p b := begin apply le_antisymm, { apply enat.le_of_lt_add_one, cases enat.ne_top_iff.mp (enat.ne_top_of_lt h) with k hk, rw [hk], rw_mod_cast [multiplicity_lt_iff_neg_dvd], intro h_dvd, rw [← dvd_add_iff_right] at h_dvd, apply multiplicity.is_greatest _ h_dvd, rw [hk], apply_mod_cast nat.lt_succ_self, rw [pow_dvd_iff_le_multiplicity, enat.coe_add, ← hk], exact enat.add_one_le_of_lt h }, { convert min_le_multiplicity_add, rw [min_eq_right (le_of_lt h)] } end lemma multiplicity_sub_of_gt {p a b : α} (h : multiplicity p b < multiplicity p a) : multiplicity p (a - b) = multiplicity p b := by { rw [sub_eq_add_neg, multiplicity_add_of_gt]; rwa [multiplicity.neg] } lemma multiplicity_add_eq_min {p a b : α} (h : multiplicity p a ≠ multiplicity p b) : multiplicity p (a + b) = min (multiplicity p a) (multiplicity p b) := begin rcases lt_trichotomy (multiplicity p a) (multiplicity p b) with hab|hab|hab, { rw [add_comm, multiplicity_add_of_gt hab, min_eq_left], exact le_of_lt hab }, { contradiction }, { rw [multiplicity_add_of_gt hab, min_eq_right], exact le_of_lt hab}, end end comm_ring section integral_domain variables [integral_domain α] lemma finite_mul_aux {p : α} (hp : prime p) : ∀ {n m : ℕ} {a b : α}, ¬p ^ (n + 1) ∣ a → ¬p ^ (m + 1) ∣ b → ¬p ^ (n + m + 1) ∣ a * b | n m := λ a b ha hb ⟨s, hs⟩, have p ∣ a * b, from ⟨p ^ (n + m) * s, by simp [hs, _root_.pow_add, mul_comm, mul_assoc, mul_left_comm]⟩, (hp.2.2 a b this).elim (λ ⟨x, hx⟩, have hn0 : 0 < n, from nat.pos_of_ne_zero (λ hn0, by clear _fun_match _fun_match; simpa [hx, hn0] using ha), have wf : (n - 1) < n, from nat.sub_lt_self hn0 dec_trivial, have hpx : ¬ p ^ (n - 1 + 1) ∣ x, from λ ⟨y, hy⟩, ha (hx.symm ▸ ⟨y, (domain.mul_left_inj hp.1).1 $ by rw [nat.sub_add_cancel hn0] at hy; simp [hy, _root_.pow_add, mul_comm, mul_assoc, mul_left_comm]⟩), have 1 ≤ n + m, from le_trans hn0 (le_add_right n m), finite_mul_aux hpx hb ⟨s, (domain.mul_left_inj hp.1).1 begin rw [← nat.sub_add_comm hn0, nat.sub_add_cancel this], clear _fun_match _fun_match finite_mul_aux, simp [*, mul_comm, mul_assoc, mul_left_comm, _root_.pow_add] at * end⟩) (λ ⟨x, hx⟩, have hm0 : 0 < m, from nat.pos_of_ne_zero (λ hm0, by clear _fun_match _fun_match; simpa [hx, hm0] using hb), have wf : (m - 1) < m, from nat.sub_lt_self hm0 dec_trivial, have hpx : ¬ p ^ (m - 1 + 1) ∣ x, from λ ⟨y, hy⟩, hb (hx.symm ▸ ⟨y, (domain.mul_left_inj hp.1).1 $ by rw [nat.sub_add_cancel hm0] at hy; simp [hy, _root_.pow_add, mul_comm, mul_assoc, mul_left_comm]⟩), finite_mul_aux ha hpx ⟨s, (domain.mul_left_inj hp.1).1 begin rw [add_assoc, nat.sub_add_cancel hm0], clear _fun_match _fun_match finite_mul_aux, simp [*, mul_comm, mul_assoc, mul_left_comm, _root_.pow_add] at * end⟩) lemma finite_mul {p a b : α} (hp : prime p) : finite p a → finite p b → finite p (a * b) := λ ⟨n, hn⟩ ⟨m, hm⟩, ⟨n + m, finite_mul_aux hp hn hm⟩ lemma finite_mul_iff {p a b : α} (hp : prime p) : finite p (a * b) ↔ finite p a ∧ finite p b := ⟨λ h, ⟨finite_of_finite_mul_right h, finite_of_finite_mul_left h⟩, λ h, finite_mul hp h.1 h.2⟩ lemma finite_pow {p a : α} (hp : prime p) : Π {k : ℕ} (ha : finite p a), finite p (a ^ k) | 0 ha := ⟨0, by simp [mt is_unit_iff_dvd_one.2 hp.2.1]⟩ | (k+1) ha := by rw [pow_succ]; exact finite_mul hp ha (finite_pow ha) variable [decidable_rel ((∣) : α → α → Prop)] @[simp] lemma multiplicity_self {a : α} (ha : ¬is_unit a) (ha0 : a ≠ 0) : multiplicity a a = 1 := eq_some_iff.2 ⟨by simp, λ ⟨b, hb⟩, ha (is_unit_iff_dvd_one.2 ⟨b, (domain.mul_right_inj ha0).1 $ by clear _fun_match; simpa [pow_succ, mul_assoc] using hb⟩)⟩ @[simp] lemma get_multiplicity_self {a : α} (ha : finite a a) : get (multiplicity a a) ha = 1 := roption.get_eq_iff_eq_some.2 (eq_some_iff.2 ⟨by simp, λ ⟨b, hb⟩, by rw [← mul_one a, _root_.pow_add, _root_.pow_one, mul_assoc, mul_assoc, domain.mul_right_inj (ne_zero_of_finite ha)] at hb; exact mt is_unit_iff_dvd_one.2 (not_unit_of_finite ha) ⟨b, by clear _fun_match; simp * at *⟩⟩) protected lemma mul' {p a b : α} (hp : prime p) (h : (multiplicity p (a * b)).dom) : get (multiplicity p (a * b)) h = get (multiplicity p a) ((finite_mul_iff hp).1 h).1 + get (multiplicity p b) ((finite_mul_iff hp).1 h).2 := have hdiva : p ^ get (multiplicity p a) ((finite_mul_iff hp).1 h).1 ∣ a, from pow_multiplicity_dvd _, have hdivb : p ^ get (multiplicity p b) ((finite_mul_iff hp).1 h).2 ∣ b, from pow_multiplicity_dvd _, have hpoweq : p ^ (get (multiplicity p a) ((finite_mul_iff hp).1 h).1 + get (multiplicity p b) ((finite_mul_iff hp).1 h).2) = p ^ get (multiplicity p a) ((finite_mul_iff hp).1 h).1 * p ^ get (multiplicity p b) ((finite_mul_iff hp).1 h).2, by simp [_root_.pow_add], have hdiv : p ^ (get (multiplicity p a) ((finite_mul_iff hp).1 h).1 + get (multiplicity p b) ((finite_mul_iff hp).1 h).2) ∣ a * b, by rw [hpoweq]; apply mul_dvd_mul; assumption, have hsucc : ¬p ^ ((get (multiplicity p a) ((finite_mul_iff hp).1 h).1 + get (multiplicity p b) ((finite_mul_iff hp).1 h).2) + 1) ∣ a * b, from λ h, not_or (is_greatest' _ (lt_succ_self _)) (is_greatest' _ (lt_succ_self _)) (succ_dvd_or_succ_dvd_of_succ_sum_dvd_mul hp (by convert hdiva) (by convert hdivb) h), by rw [← enat.coe_inj, enat.coe_get, eq_some_iff]; exact ⟨hdiv, hsucc⟩ open_locale classical protected lemma mul {p a b : α} (hp : prime p) : multiplicity p (a * b) = multiplicity p a + multiplicity p b := if h : finite p a ∧ finite p b then by rw [← enat.coe_get (finite_iff_dom.1 h.1), ← enat.coe_get (finite_iff_dom.1 h.2), ← enat.coe_get (finite_iff_dom.1 (finite_mul hp h.1 h.2)), ← enat.coe_add, enat.coe_inj, multiplicity.mul' hp]; refl else begin rw [eq_top_iff_not_finite.2 (mt (finite_mul_iff hp).1 h)], cases not_and_distrib.1 h with h h; simp [eq_top_iff_not_finite.2 h] end lemma finset.prod {β : Type*} {p : α} (hp : prime p) (s : finset β) (f : β → α) : multiplicity p (∏ x in s, f x) = s.sum (λ x, multiplicity p (f x)) := begin classical, induction s using finset.induction with a s has ih h, { simp only [finset.sum_empty, finset.prod_empty], convert one_right hp.not_unit }, { simp [has, ← ih], convert multiplicity.mul hp } end protected lemma pow' {p a : α} (hp : prime p) (ha : finite p a) : ∀ {k : ℕ}, get (multiplicity p (a ^ k)) (finite_pow hp ha) = k * get (multiplicity p a) ha | 0 := by dsimp [_root_.pow_zero]; simp [one_right hp.not_unit]; refl | (k+1) := by dsimp only [pow_succ]; erw [multiplicity.mul' hp, pow', add_mul, one_mul, add_comm] lemma pow {p a : α} (hp : prime p) : ∀ {k : ℕ}, multiplicity p (a ^ k) = k •ℕ (multiplicity p a) | 0 := by simp [one_right hp.not_unit] | (succ k) := by simp [pow_succ, succ_nsmul, pow, multiplicity.mul hp] lemma multiplicity_pow_self {p : α} (h0 : p ≠ 0) (hu : ¬ is_unit p) (n : ℕ) : multiplicity p (p ^ n) = n := by { rw [eq_some_iff], use dvd_refl _, rw [pow_dvd_pow_iff h0 hu], apply nat.not_succ_le_self } lemma multiplicity_pow_self_of_prime {p : α} (hp : prime p) (n : ℕ) : multiplicity p (p ^ n) = n := multiplicity_pow_self hp.ne_zero hp.not_unit n end integral_domain end multiplicity section nat open multiplicity lemma multiplicity_eq_zero_of_coprime {p a b : ℕ} (hp : p ≠ 1) (hle : multiplicity p a ≤ multiplicity p b) (hab : nat.coprime a b) : multiplicity p a = 0 := begin rw [multiplicity_le_multiplicity_iff] at hle, rw [← le_zero_iff_eq, ← not_lt, enat.pos_iff_one_le, ← enat.coe_one, ← pow_dvd_iff_le_multiplicity], assume h, have := nat.dvd_gcd h (hle _ h), rw [coprime.gcd_eq_one hab, nat.dvd_one, _root_.pow_one] at this, exact hp this end end nat
9aec577c3ce0a346976fccd28e2cb1525b9e0d9c
037dba89703a79cd4a4aec5e959818147f97635d
/src/2020/logic/SAT_example.lean
b7afc947f07b2d3b8886d95744e5ab17e3a92877
[]
no_license
ImperialCollegeLondon/M40001_lean
3a6a09298da395ab51bc220a535035d45bbe919b
62a76fa92654c855af2b2fc2bef8e60acd16ccec
refs/heads/master
1,666,750,403,259
1,665,771,117,000
1,665,771,117,000
209,141,835
115
12
null
1,640,270,596,000
1,568,749,174,000
Lean
UTF-8
Lean
false
false
4,746
lean
import tactic -- First we do the question using Prop (optimised for proving) variables (P Q R S U : Prop) example : ∃ P Q R S U : Prop, (Q ∨ P ∨ U) ∧ (U ∨ ¬Q ∨ S) ∧ (U ∨ Q ∨ ¬R) ∧ (P ∨ R ∨ ¬S) ∧ (P ∨ S ∨ R) ∧ (R ∨ ¬U ∨ Q) ∧ (R ∨ S ∨ ¬U) ∧ (¬S ∨ ¬R ∨ U) ∧ (U ∨ ¬Q ∨ ¬R) ∧ (¬Q ∨ U ∨ ¬S) ∧ (¬P ∨ ¬R ∨ Q) ∧ (S ∨ ¬U ∨ ¬P) ∧ (¬R ∨ ¬P ∨ U) ∧ (S ∨ ¬R ∨ ¬U) ∧ (¬R ∨ ¬Q ∨ ¬S) ∧ (Q ∨ R ∨ S) ∧ (¬U ∨ P ∨ ¬Q) ∧ (R ∨ ¬Q ∨ ¬P) ∧ (P ∨ R ∨ ¬Q) ∧ (S ∨ P ∨ Q) ∧ (R ∨ P ∨ U) ∧ (¬U ∨ Q ∨ R) ∧ (¬U ∨ R ∨ ¬Q) ∧ (¬S ∨ ¬U ∨ ¬Q) ∧ (¬U ∨ ¬S ∨ R) ∧ (¬S ∨ P ∨ U) ∧ (P ∨ Q ∨ ¬R) ∧ (¬S ∨ ¬R ∨ U) ∧ (¬Q ∨ ¬S ∨ U) ∧ (P ∨ R ∨ ¬Q) ∧ (P ∨ Q ∨ ¬S) ∧ (U ∨ ¬S ∨ ¬P) ∧ (¬U ∨ R ∨ ¬P) ∧ (¬U ∨ P ∨ ¬Q) ∧ (¬R ∨ ¬P ∨ S) ∧ (R ∨ S ∨ ¬U) ∧ (P ∨ ¬U ∨ Q) ∧ (¬S ∨ R ∨ P) ∧ (¬P ∨ ¬Q ∨ ¬R) ∧ (¬P ∨ R ∨ ¬S) := begin -- unprovable according to bool calc sorry end theorem trick {Q : Prop} (hQ : Q) : Q ↔ true := iff_of_true hQ trivial theorem trick2 {Q : Prop} (hQ : ¬ Q) : Q ↔ false := iff_false_intro hQ example : ∀ P Q R S U : Prop, ¬ ( (Q ∨ P ∨ U) ∧ (U ∨ ¬Q ∨ S) ∧ (U ∨ Q ∨ ¬R) ∧ (P ∨ R ∨ ¬S) ∧ (P ∨ S ∨ R) ∧ (R ∨ ¬U ∨ Q) ∧ (R ∨ S ∨ ¬U) ∧ (¬S ∨ ¬R ∨ U) ∧ (U ∨ ¬Q ∨ ¬R) ∧ (¬Q ∨ U ∨ ¬S) ∧ (¬P ∨ ¬R ∨ Q) ∧ (S ∨ ¬U ∨ ¬P) ∧ (¬R ∨ ¬P ∨ U) ∧ (S ∨ ¬R ∨ ¬U) ∧ (¬R ∨ ¬Q ∨ ¬S) ∧ (Q ∨ R ∨ S) ∧ (¬U ∨ P ∨ ¬Q) ∧ (R ∨ ¬Q ∨ ¬P) ∧ (P ∨ R ∨ ¬Q) ∧ (S ∨ P ∨ Q) ∧ (R ∨ P ∨ U) ∧ (¬U ∨ Q ∨ R) ∧ (¬U ∨ R ∨ ¬Q) ∧ (¬S ∨ ¬U ∨ ¬Q) ∧ (¬U ∨ ¬S ∨ R) ∧ (¬S ∨ P ∨ U) ∧ (P ∨ Q ∨ ¬R) ∧ (¬S ∨ ¬R ∨ U) ∧ (¬Q ∨ ¬S ∨ U) ∧ (P ∨ R ∨ ¬Q) ∧ (P ∨ Q ∨ ¬S) ∧ (U ∨ ¬S ∨ ¬P) ∧ (¬U ∨ R ∨ ¬P) ∧ (¬U ∨ P ∨ ¬Q) ∧ (¬R ∨ ¬P ∨ S) ∧ (R ∨ S ∨ ¬U) ∧ (P ∨ ¬U ∨ Q) ∧ (¬S ∨ R ∨ P) ∧ (¬P ∨ ¬Q ∨ ¬R) ∧ (¬P ∨ R ∨ ¬S)) := begin intros, by_cases hP : P;rw trick hP; try {rw iff_false_intro hP}; clear hP; simp; by_cases hP : Q;rw trick hP; try {rw iff_false_intro hP}; clear hP; simp; by_cases hP : R;rw trick hP; try {rw iff_false_intro hP}; clear hP; simp; by_cases hP : S;rw trick hP; try {rw iff_false_intro hP}; clear hP; simp; by_cases hP : U;rw trick hP; try {rw iff_false_intro hP}; clear hP; simp, end example : ∃ P Q R S U : bool, (Q || P || U) && (U || !Q || S) && (U || Q || !R) && (P || R || !S) && (P || S || R) && (R || !U || Q) && (R || S || !U) && (!S || !R || U) && (U || !Q || !R) && (!Q || U || !S) && (!P || !R || Q) && (S || !U || !P) && (!R || !P || U) && (S || !R || !U) && (!R || !Q || !S) && (Q || R || S) && (!U || P || !Q) && (R || !Q || !P) && (P || R || !Q) && (S || P || Q) && (R || P || U) && (!U || Q || R) && (!U || R || !Q) && (!S || !U || !Q) && (!U || !S || R) && (!S || P || U) && (P || Q || !R) && (!S || !R || U) && (!Q || !S || U) && (P || R || !Q) && (P || Q || !S) && (U || !S || !P) && (!U || R || !P) && (!U || P || !Q) && (!R || !P || S) && (R || S || !U) && (P || !U || Q) && (!S || R || P) && (!P || !Q || !R) && (!P || R || !S) = tt := begin simp, -- ⊢ false -- oops sorry end example : ∀ P Q R S U : bool, (Q || P || U) && (U || !Q || S) && (U || Q || !R) && (P || R || !S) && (P || S || R) && (R || !U || Q) && (R || S || !U) && (!S || !R || U) && (U || !Q || !R) && (!Q || U || !S) && (!P || !R || Q) && (S || !U || !P) && (!R || !P || U) && (S || !R || !U) && (!R || !Q || !S) && (Q || R || S) && (!U || P || !Q) && (R || !Q || !P) && (P || R || !Q) && (S || P || Q) && (R || P || U) && (!U || Q || R) && (!U || R || !Q) && (!S || !U || !Q) && (!U || !S || R) && (!S || P || U) && (P || Q || !R) && (!S || !R || U) && (!Q || !S || U) && (P || R || !Q) && (P || Q || !S) && (U || !S || !P) && (!U || R || !P) && (!U || P || !Q) && (!R || !P || S) && (R || S || !U) && (P || !U || Q) && (!S || R || P) && (!P || !Q || !R) && (!P || R || !S) = ff := begin --simp -- this works -- but `squeeze_simp` gives information about how `simp` did it -- and it tells us that this works too: --simp only [bnot_eq_ff_eq_eq_tt, bor_eq_false_eq_eq_ff_and_eq_ff, -- bool.forall_bool, eq_self_iff_true, or_false, or_true, and_self, -- and_false, false_and, band_eq_false_eq_eq_ff_or_eq_ff], -- Clearly it's using reasoning. Here's a real proof by cases: rintros (P|P) (Q|Q) (R|R) (S|S) (T|T); -- 32 goals at this point, change `;` to `,` to see them refl, end
61de3217de3a95a42d6fb789b757883f36b8becc
1abd1ed12aa68b375cdef28959f39531c6e95b84
/src/analysis/complex/circle.lean
239fc5a6675791f5d4efa9b9388886d07205a5ed
[ "Apache-2.0" ]
permissive
jumpy4/mathlib
d3829e75173012833e9f15ac16e481e17596de0f
af36f1a35f279f0e5b3c2a77647c6bf2cfd51a13
refs/heads/master
1,693,508,842,818
1,636,203,271,000
1,636,203,271,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
4,245
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.special_functions.exp import topology.continuous_function.basic /-! # The circle This file defines `circle` to be the metric sphere (`metric.sphere`) in `ℂ` centred at `0` of radius `1`. We equip it with the following structure: * a submonoid of `ℂ` * a group * a topological group We furthermore define `exp_map_circle` to be the natural map `λ t, exp (t * I)` from `ℝ` to `circle`, and show that this map is a group homomorphism. ## Implementation notes Because later (in `geometry.manifold.instances.sphere`) one wants to equip the circle with a smooth manifold structure borrowed from `metric.sphere`, the underlying set is `{z : ℂ | abs (z - 0) = 1}`. This prevents certain algebraic facts from working definitionally -- for example, the circle is not defeq to `{z : ℂ | abs z = 1}`, which is the kernel of `complex.abs` considered as a homomorphism from `ℂ` to `ℝ`, nor is it defeq to `{z : ℂ | norm_sq z = 1}`, which is the kernel of the homomorphism `complex.norm_sq` from `ℂ` to `ℝ`. -/ noncomputable theory open complex metric open_locale complex_conjugate /-- The unit circle in `ℂ`, here given the structure of a submonoid of `ℂ`. -/ def circle : submonoid ℂ := { carrier := sphere (0:ℂ) 1, one_mem' := by simp, mul_mem' := λ a b, begin simp only [norm_eq_abs, mem_sphere_zero_iff_norm], intros ha hb, simp [ha, hb], end } @[simp] lemma mem_circle_iff_abs (z : ℂ) : z ∈ circle ↔ abs z = 1 := mem_sphere_zero_iff_norm lemma circle_def : ↑circle = {z : ℂ | abs z = 1} := by { ext, simp } @[simp] lemma abs_eq_of_mem_circle (z : circle) : abs z = 1 := by { convert z.2, simp } @[simp] lemma norm_sq_eq_of_mem_circle (z : circle) : norm_sq z = 1 := by simp [norm_sq_eq_abs] lemma nonzero_of_mem_circle (z : circle) : (z:ℂ) ≠ 0 := nonzero_of_mem_unit_sphere z instance : group circle := { inv := λ z, ⟨conj (z : ℂ), by simp⟩, mul_left_inv := λ z, subtype.ext $ by { simp [has_inv.inv, ← norm_sq_eq_conj_mul_self, ← mul_self_abs] }, .. circle.to_monoid } lemma coe_inv_circle_eq_conj (z : circle) : ↑(z⁻¹) = (conj : ring_aut ℂ) z := rfl @[simp] lemma coe_inv_circle (z : circle) : ↑(z⁻¹) = (z : ℂ)⁻¹ := begin rw coe_inv_circle_eq_conj, apply eq_inv_of_mul_right_eq_one, rw [mul_comm, ← complex.norm_sq_eq_conj_mul_self], simp, end @[simp] lemma coe_div_circle (z w : circle) : ↑(z / w) = (z:ℂ) / w := show ↑(z * w⁻¹) = (z:ℂ) * w⁻¹, by simp instance : compact_space circle := metric.sphere.compact_space _ _ -- the following result could instead be deduced from the Lie group structure on the circle using -- `topological_group_of_lie_group`, but that seems a little awkward since one has to first provide -- and then forget the model space instance : topological_group circle := { continuous_mul := let h : continuous (λ x : circle, (x : ℂ)) := continuous_subtype_coe in continuous_induced_rng (continuous_mul.comp (h.prod_map h)), continuous_inv := continuous_induced_rng $ complex.conj_cle.continuous.comp continuous_subtype_coe } /-- The map `λ t, exp (t * I)` from `ℝ` to the unit circle in `ℂ`. -/ def exp_map_circle : C(ℝ, circle) := { to_fun := λ t, ⟨exp (t * I), by simp [exp_mul_I, abs_cos_add_sin_mul_I]⟩ } @[simp] lemma exp_map_circle_apply (t : ℝ) : ↑(exp_map_circle t) = complex.exp (t * complex.I) := rfl @[simp] lemma exp_map_circle_zero : exp_map_circle 0 = 1 := subtype.ext $ by rw [exp_map_circle_apply, of_real_zero, zero_mul, exp_zero, submonoid.coe_one] @[simp] lemma exp_map_circle_add (x y : ℝ) : exp_map_circle (x + y) = exp_map_circle x * exp_map_circle y := subtype.ext $ by simp only [exp_map_circle_apply, submonoid.coe_mul, of_real_add, add_mul, complex.exp_add] /-- The map `λ t, exp (t * I)` from `ℝ` to the unit circle in `ℂ`, considered as a homomorphism of groups. -/ def exp_map_circle_hom : ℝ →+ (additive circle) := { to_fun := additive.of_mul ∘ exp_map_circle, map_zero' := exp_map_circle_zero, map_add' := exp_map_circle_add }
da878cc41e0a05e2f96f4a5555ebfbda4d032bed
7cef822f3b952965621309e88eadf618da0c8ae9
/src/topology/metric_space/gromov_hausdorff_realized.lean
a7675133a9aea442d0a1b308575e38cd0c044ac4
[ "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
27,002
lean
/- Copyright (c) 2019 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Sébastien Gouëzel Construction of a good coupling between nonempty compact metric spaces, minimizing their Hausdorff distance. This construction is instrumental to study the Gromov-Hausdorff distance between nonempty compact metric spaces -/ import topology.bounded_continuous_function topology.metric_space.gluing topology.metric_space.hausdorff_distance noncomputable theory open_locale classical open_locale topological_space universes u v w open classical lattice set function topological_space filter metric quotient open bounded_continuous_function open sum (inl inr) set_option class.instance_max_depth 50 local attribute [instance] metric_space_sum namespace Gromov_Hausdorff section Gromov_Hausdorff_realized /- This section shows that the Gromov-Hausdorff distance is realized. For this, we consider candidate distances on the disjoint union α ⊕ β of two compact nonempty metric spaces, almost realizing the Gromov-Hausdorff distance, and show that they form a compact family by applying Arzela-Ascoli theorem. The existence of a minimizer follows. -/ section definitions variables (α : Type u) (β : Type v) [metric_space α] [compact_space α] [nonempty α] [metric_space β] [compact_space β] [nonempty β] @[reducible] private def prod_space_fun : Type* := ((α ⊕ β) × (α ⊕ β)) → ℝ @[reducible] private def Cb : Type* := bounded_continuous_function ((α ⊕ β) × (α ⊕ β)) ℝ private def max_var : nnreal := 2 * ⟨diam (univ : set α), diam_nonneg⟩ + 1 + 2 * ⟨diam (univ : set β), diam_nonneg⟩ private lemma one_le_max_var : 1 ≤ max_var α β := calc (1 : real) = 2 * 0 + 1 + 2 * 0 : by simp ... ≤ 2 * diam (univ : set α) + 1 + 2 * diam (univ : set β) : by apply_rules [add_le_add, mul_le_mul_of_nonneg_left, diam_nonneg, diam_nonneg]; norm_num /-- The set of functions on α ⊕ β that are candidates distances to realize the minimum of the Hausdorff distances between α and β in a coupling -/ def candidates : set (prod_space_fun α β) := {f | (((((∀x y : α, f (sum.inl x, sum.inl y) = dist x y) ∧ (∀x y : β, f (sum.inr x, sum.inr y) = dist x y)) ∧ (∀x y, f (x, y) = f (y, x))) ∧ (∀x y z, f (x, z) ≤ f (x, y) + f (y, z))) ∧ (∀x, f (x, x) = 0)) ∧ (∀x y, f (x, y) ≤ max_var α β) } /-- Version of the set of candidates in bounded_continuous_functions, to apply Arzela-Ascoli -/ private def candidates_b : set (Cb α β) := {f : Cb α β | f.val ∈ candidates α β} end definitions --section section constructions variables {α : Type u} {β : Type v} [metric_space α] [compact_space α] [nonempty α] [metric_space β] [compact_space β] [nonempty β] {f : prod_space_fun α β} {x y z t : α ⊕ β} local attribute [instance, priority 10] inhabited_of_nonempty' private lemma max_var_bound : dist x y ≤ max_var α β := calc dist x y ≤ diam (univ : set (α ⊕ β)) : dist_le_diam_of_mem (bounded_of_compact compact_univ) (mem_univ _) (mem_univ _) ... = diam (inl '' (univ : set α) ∪ inr '' (univ : set β)) : by apply congr_arg; ext x y z; cases x; simp [mem_univ, mem_range_self] ... ≤ diam (inl '' (univ : set α)) + dist (inl (default α)) (inr (default β)) + diam (inr '' (univ : set β)) : diam_union (mem_image_of_mem _ (mem_univ _)) (mem_image_of_mem _ (mem_univ _)) ... = diam (univ : set α) + (dist (default α) (default α) + 1 + dist (default β) (default β)) + diam (univ : set β) : by { rw [isometry.diam_image isometry_on_inl, isometry.diam_image isometry_on_inr], refl } ... = 1 * diam (univ : set α) + 1 + 1 * diam (univ : set β) : by simp ... ≤ 2 * diam (univ : set α) + 1 + 2 * diam (univ : set β) : begin apply_rules [add_le_add, mul_le_mul_of_nonneg_right, diam_nonneg, diam_nonneg, le_refl], norm_num, norm_num end private lemma candidates_symm (fA : f ∈ candidates α β) : f (x, y) = f (y ,x) := fA.1.1.1.2 x y private lemma candidates_triangle (fA : f ∈ candidates α β) : f (x, z) ≤ f (x, y) + f (y, z) := fA.1.1.2 x y z private lemma candidates_refl (fA : f ∈ candidates α β) : f (x, x) = 0 := fA.1.2 x private lemma candidates_nonneg (fA : f ∈ candidates α β) : 0 ≤ f (x, y) := begin have : 0 ≤ 2 * f (x, y) := calc 0 = f (x, x) : (candidates_refl fA).symm ... ≤ f (x, y) + f (y, x) : candidates_triangle fA ... = f (x, y) + f (x, y) : by rw [candidates_symm fA] ... = 2 * f (x, y) : by ring, by linarith end private lemma candidates_dist_inl (fA : f ∈ candidates α β) (x y: α) : f (inl x, inl y) = dist x y := fA.1.1.1.1.1 x y private lemma candidates_dist_inr (fA : f ∈ candidates α β) (x y : β) : f (inr x, inr y) = dist x y := fA.1.1.1.1.2 x y private lemma candidates_le_max_var (fA : f ∈ candidates α β) : f (x, y) ≤ max_var α β := fA.2 x y /-- candidates are bounded by max_var α β -/ private lemma candidates_dist_bound (fA : f ∈ candidates α β) : ∀ {x y : α ⊕ β}, f (x, y) ≤ max_var α β * dist x y | (inl x) (inl y) := calc f (inl x, inl y) = dist x y : candidates_dist_inl fA x y ... = dist (inl x) (inl y) : by { rw @sum.dist_eq α β, refl } ... = 1 * dist (inl x) (inl y) : by simp ... ≤ max_var α β * dist (inl x) (inl y) : mul_le_mul_of_nonneg_right (one_le_max_var α β) dist_nonneg | (inl x) (inr y) := calc f (inl x, inr y) ≤ max_var α β : candidates_le_max_var fA ... = max_var α β * 1 : by simp ... ≤ max_var α β * dist (inl x) (inr y) : mul_le_mul_of_nonneg_left sum.one_dist_le (le_trans (zero_le_one) (one_le_max_var α β)) | (inr x) (inl y) := calc f (inr x, inl y) ≤ max_var α β : candidates_le_max_var fA ... = max_var α β * 1 : by simp ... ≤ max_var α β * dist (inl x) (inr y) : mul_le_mul_of_nonneg_left sum.one_dist_le (le_trans (zero_le_one) (one_le_max_var α β)) | (inr x) (inr y) := calc f (inr x, inr y) = dist x y : candidates_dist_inr fA x y ... = dist (inr x) (inr y) : by { rw @sum.dist_eq α β, refl } ... = 1 * dist (inr x) (inr y) : by simp ... ≤ max_var α β * dist (inr x) (inr y) : mul_le_mul_of_nonneg_right (one_le_max_var α β) dist_nonneg /-- Technical lemma to prove that candidates are Lipschitz -/ private lemma candidates_lipschitz_aux (fA : f ∈ candidates α β) : f (x, y) - f (z, t) ≤ 2 * max_var α β * dist (x, y) (z, t) := calc f (x, y) - f(z, t) ≤ f (x, t) + f (t, y) - f (z, t) : add_le_add_right (candidates_triangle fA) _ ... ≤ (f (x, z) + f (z, t) + f(t, y)) - f (z, t) : add_le_add_right (add_le_add_right (candidates_triangle fA) _ ) _ ... = f (x, z) + f (t, y) : by simp ... ≤ max_var α β * dist x z + max_var α β * dist t y : add_le_add (candidates_dist_bound fA) (candidates_dist_bound fA) ... ≤ max_var α β * max (dist x z) (dist t y) + max_var α β * max (dist x z) (dist t y) : begin apply add_le_add, apply mul_le_mul_of_nonneg_left (le_max_left (dist x z) (dist t y)) (le_trans zero_le_one (one_le_max_var α β)), apply mul_le_mul_of_nonneg_left (le_max_right (dist x z) (dist t y)) (le_trans zero_le_one (one_le_max_var α β)), end ... = 2 * max_var α β * max (dist x z) (dist y t) : by { simp [dist_comm], ring } ... = 2 * max_var α β * dist (x, y) (z, t) : by refl /-- Candidates are Lipschitz -/ private lemma candidates_lipschitz (fA : f ∈ candidates α β) : lipschitz_with (2 * max_var α β) f := begin rintros ⟨x, y⟩ ⟨z, t⟩, rw real.dist_eq, apply abs_le_of_le_of_neg_le, { exact candidates_lipschitz_aux fA }, { have : -(f (x, y) - f (z, t)) = f (z, t) - f (x, y), by ring, rw [this, dist_comm], exact candidates_lipschitz_aux fA } end /-- candidates give rise to elements of bounded_continuous_functions -/ def candidates_b_of_candidates (f : prod_space_fun α β) (fA : f ∈ candidates α β) : Cb α β := bounded_continuous_function.mk_of_compact f (candidates_lipschitz fA).to_continuous lemma candidates_b_of_candidates_mem (f : prod_space_fun α β) (fA : f ∈ candidates α β) : candidates_b_of_candidates f fA ∈ candidates_b α β := fA /-- The distance on α ⊕ β is a candidate -/ private lemma dist_mem_candidates : (λp : (α ⊕ β) × (α ⊕ β), dist p.1 p.2) ∈ candidates α β := begin simp only [candidates, dist_comm, forall_const, and_true, add_comm, eq_self_iff_true, and_self, sum.forall, set.mem_set_of_eq, dist_self], repeat { split <|> exact (λa y z, dist_triangle_left _ _ _) <|> exact (λx y, by refl) <|> exact (λx y, max_var_bound) } end def candidates_b_dist (α : Type u) (β : Type v) [metric_space α] [compact_space α] [inhabited α] [metric_space β] [compact_space β] [inhabited β] : Cb α β := candidates_b_of_candidates _ dist_mem_candidates lemma candidates_b_dist_mem_candidates_b : candidates_b_dist α β ∈ candidates_b α β := candidates_b_of_candidates_mem _ _ private lemma candidates_b_ne_empty : candidates_b α β ≠ ∅ := ne_empty_of_mem candidates_b_dist_mem_candidates_b /-- To apply Arzela-Ascoli, we need to check that the set of candidates is closed and equicontinuous. Equicontinuity follows from the Lipschitz control, we check closedness -/ private lemma closed_candidates_b : is_closed (candidates_b α β) := begin have I1 : ∀x y, is_closed {f : Cb α β | f (inl x, inl y) = dist x y} := λx y, is_closed_eq continuous_evalx continuous_const, have I2 : ∀x y, is_closed {f : Cb α β | f (inr x, inr y) = dist x y } := λx y, is_closed_eq continuous_evalx continuous_const, have I3 : ∀x y, is_closed {f : Cb α β | f (x, y) = f (y, x)} := λx y, is_closed_eq continuous_evalx continuous_evalx, have I4 : ∀x y z, is_closed {f : Cb α β | f (x, z) ≤ f (x, y) + f (y, z)} := λx y z, is_closed_le continuous_evalx (continuous_evalx.add continuous_evalx), have I5 : ∀x, is_closed {f : Cb α β | f (x, x) = 0} := λx, is_closed_eq continuous_evalx continuous_const, have I6 : ∀x y, is_closed {f : Cb α β | f (x, y) ≤ max_var α β} := λx y, is_closed_le continuous_evalx continuous_const, have : candidates_b α β = (⋂x y, {f : Cb α β | f ((@inl α β x), (@inl α β y)) = dist x y}) ∩ (⋂x y, {f : Cb α β | f ((@inr α β x), (@inr α β y)) = dist x y}) ∩ (⋂x y, {f : Cb α β | f (x, y) = f (y, x)}) ∩ (⋂x y z, {f : Cb α β | f (x, z) ≤ f (x, y) + f (y, z)}) ∩ (⋂x, {f : Cb α β | f (x, x) = 0}) ∩ (⋂x y, {f : Cb α β | f (x, y) ≤ max_var α β}) := begin ext, unfold candidates_b, unfold candidates, simp [-sum.forall], refl end, rw this, repeat { apply is_closed_inter _ _ <|> apply is_closed_Inter _ <|> apply I1 _ _ <|> apply I2 _ _ <|> apply I3 _ _ <|> apply I4 _ _ _ <|> apply I5 _ <|> apply I6 _ _ <|> assume x }, end /-- Compactness of candidates (in bounded_continuous_functions) follows -/ private lemma compact_candidates_b : compact (candidates_b α β) := begin refine arzela_ascoli₂ (Icc 0 (max_var α β)) compact_Icc (candidates_b α β) closed_candidates_b _ _, { rintros f ⟨x1, x2⟩ hf, simp only [set.mem_Icc], exact ⟨candidates_nonneg hf, candidates_le_max_var hf⟩ }, { refine equicontinuous_of_continuity_modulus (λt, 2 * max_var α β * t) _ _ _, { have : tendsto (λ (t : ℝ), 2 * (max_var α β : ℝ) * t) (𝓝 0) (𝓝 (2 * max_var α β * 0)) := tendsto_const_nhds.mul tendsto_id, simpa using this }, { assume x y f hf, exact candidates_lipschitz hf _ _ } } end /-- We will then choose the candidate minimizing the Hausdorff distance. Except that we are not in a metric space setting, so we need to define our custom version of Hausdorff distance, called HD, and prove its basic properties. -/ def HD (f : Cb α β) := max (supr (λx:α, infi (λy:β, f (inl x, inr y)))) (supr (λy:β, infi (λx:α, f (inl x, inr y)))) /- We will show that HD is continuous on bounded_continuous_functions, to deduce that its minimum on the compact set candidates_b is attained. Since it is defined in terms of infimum and supremum on ℝ, which is only conditionnally complete, we will need all the time to check that the defining sets are bounded below or above. This is done in the next few technical lemmas -/ lemma HD_below_aux1 {f : Cb α β} (C : ℝ) {x : α} : bdd_below (range (λ (y : β), f (inl x, inr y) + C)) := let ⟨cf, hcf⟩ := (real.bounded_iff_bdd_below_bdd_above.1 bounded_range).1 in ⟨cf + C, forall_range_iff.2 (λi, add_le_add_right ((λx, hcf (mem_range_self x)) _) _)⟩ private lemma HD_bound_aux1 (f : Cb α β) (C : ℝ) : bdd_above (range (λ (x : α), infi (λy:β, f (inl x, inr y) + C))) := begin rcases (real.bounded_iff_bdd_below_bdd_above.1 bounded_range).2 with ⟨Cf, hCf⟩, refine ⟨Cf + C, forall_range_iff.2 (λx, _)⟩, calc infi (λy:β, f (inl x, inr y) + C) ≤ f (inl x, inr (default β)) + C : cinfi_le (HD_below_aux1 C) ... ≤ Cf + C : add_le_add ((λx, hCf (mem_range_self x)) _) (le_refl _) end lemma HD_below_aux2 {f : Cb α β} (C : ℝ) {y : β} : bdd_below (range (λ (x : α), f (inl x, inr y) + C)) := let ⟨cf, hcf⟩ := (real.bounded_iff_bdd_below_bdd_above.1 bounded_range).1 in ⟨cf + C, forall_range_iff.2 (λi, add_le_add_right ((λx, hcf (mem_range_self x)) _) _)⟩ private lemma HD_bound_aux2 (f : Cb α β) (C : ℝ) : bdd_above (range (λ (y : β), infi (λx:α, f (inl x, inr y) + C))) := begin rcases (real.bounded_iff_bdd_below_bdd_above.1 bounded_range).2 with ⟨Cf, hCf⟩, refine ⟨Cf + C, forall_range_iff.2 (λy, _)⟩, calc infi (λx:α, f (inl x, inr y) + C) ≤ f (inl (default α), inr y) + C : cinfi_le (HD_below_aux2 C) ... ≤ Cf + C : add_le_add ((λx, hCf (mem_range_self x)) _) (le_refl _) end /-- Explicit bound on HD (dist). This means that when looking for minimizers it will be sufficient to look for functions with HD(f) bounded by this bound. -/ lemma HD_candidates_b_dist_le : HD (candidates_b_dist α β) ≤ diam (univ : set α) + 1 + diam (univ : set β) := begin refine max_le (csupr_le (λx, _)) (csupr_le (λy, _)), { have A : infi (λy:β, candidates_b_dist α β (inl x, inr y)) ≤ candidates_b_dist α β (inl x, inr (default β)) := cinfi_le (by simpa using HD_below_aux1 0), have B : dist (inl x) (inr (default β)) ≤ diam (univ : set α) + 1 + diam (univ : set β) := calc dist (inl x) (inr (default β)) = dist x (default α) + 1 + dist (default β) (default β) : rfl ... ≤ diam (univ : set α) + 1 + diam (univ : set β) : begin apply add_le_add (add_le_add _ (le_refl _)), exact dist_le_diam_of_mem (bounded_of_compact (compact_univ)) (mem_univ _) (mem_univ _), exact dist_le_diam_of_mem (bounded_of_compact (compact_univ)) (mem_univ _) (mem_univ _) end, exact le_trans A B }, { have A : infi (λx:α, candidates_b_dist α β (inl x, inr y)) ≤ candidates_b_dist α β (inl (default α), inr y) := cinfi_le (by simpa using HD_below_aux2 0), have B : dist (inl (default α)) (inr y) ≤ diam (univ : set α) + 1 + diam (univ : set β) := calc dist (inl (default α)) (inr y) = dist (default α) (default α) + 1 + dist (default β) y : rfl ... ≤ diam (univ : set α) + 1 + diam (univ : set β) : begin apply add_le_add (add_le_add _ (le_refl _)), exact dist_le_diam_of_mem (bounded_of_compact (compact_univ)) (mem_univ _) (mem_univ _), exact dist_le_diam_of_mem (bounded_of_compact (compact_univ)) (mem_univ _) (mem_univ _) end, exact le_trans A B }, end /- To check that HD is continuous, we check that it is Lipschitz. As HD is a max, we prove separately inequalities controlling the two terms (relying too heavily on copy-paste...) -/ private lemma HD_lipschitz_aux1 (f g : Cb α β) : supr (λx:α, infi (λy:β, f (inl x, inr y))) ≤ supr (λx:α, infi (λy:β, g (inl x, inr y))) + dist f g := begin rcases (real.bounded_iff_bdd_below_bdd_above.1 bounded_range).1 with ⟨cg, hcg⟩, have Hcg : ∀x, cg ≤ g x := λx, hcg (mem_range_self x), rcases (real.bounded_iff_bdd_below_bdd_above.1 bounded_range).1 with ⟨cf, hcf⟩, have Hcf : ∀x, cf ≤ f x := λx, hcf (mem_range_self x), -- prove the inequality but with `dist f g` inside, by using inequalities comparing -- supr to supr and infi to infi have Z : supr (λx:α, infi (λy:β, f (inl x, inr y))) ≤ supr (λx:α, infi (λy:β, g (inl x, inr y) + dist f g)) := csupr_le_csupr (HD_bound_aux1 _ (dist f g)) (λx, cinfi_le_cinfi ⟨cf, forall_range_iff.2(λi, Hcf _)⟩ (λy, coe_le_coe_add_dist)), -- move the `dist f g` out of the infimum and the supremum, arguing that continuous monotone maps -- (here the addition of `dist f g`) preserve infimum and supremum have E1 : ∀x, infi (λy:β, g (inl x, inr y)) + dist f g = infi ((λz, z + dist f g) ∘ (λy:β, (g (inl x, inr y)))), { assume x, refine cinfi_of_cinfi_of_monotone_of_continuous (_ : continuous (λ (z : ℝ), z + dist f g)) _ _, { exact continuous_id.add continuous_const }, { assume x y hx, simpa }, { show bdd_below (range (λ (y : β), g (inl x, inr y))), from ⟨cg, forall_range_iff.2(λi, Hcg _)⟩ } }, have E2 : supr (λx:α, infi (λy:β, g (inl x, inr y))) + dist f g = supr ((λz, z + dist f g) ∘ (λx:α, infi (λy:β, g (inl x, inr y)))), { refine csupr_of_csupr_of_monotone_of_continuous (_ : continuous (λ (z : ℝ), z + dist f g)) _ _, { exact continuous_id.add continuous_const }, { assume x y hx, simpa }, { by simpa using HD_bound_aux1 _ 0 } }, -- deduce the result from the above two steps simp only [add_comm] at Z, simpa [E2, E1, function.comp] end private lemma HD_lipschitz_aux2 (f g : Cb α β) : supr (λy:β, infi (λx:α, f (inl x, inr y))) ≤ supr (λy:β, infi (λx:α, g (inl x, inr y))) + dist f g := begin rcases (real.bounded_iff_bdd_below_bdd_above.1 bounded_range).1 with ⟨cg, hcg⟩, have Hcg : ∀x, cg ≤ g x := λx, hcg (mem_range_self x), rcases (real.bounded_iff_bdd_below_bdd_above.1 bounded_range).1 with ⟨cf, hcf⟩, have Hcf : ∀x, cf ≤ f x := λx, hcf (mem_range_self x), -- prove the inequality but with `dist f g` inside, by using inequalities comparing -- supr to supr and infi to infi have Z : supr (λy:β, infi (λx:α, f (inl x, inr y))) ≤ supr (λy:β, infi (λx:α, g (inl x, inr y) + dist f g)) := csupr_le_csupr (HD_bound_aux2 _ (dist f g)) (λy, cinfi_le_cinfi ⟨cf, forall_range_iff.2(λi, Hcf _)⟩ (λy, coe_le_coe_add_dist)), -- move the `dist f g` out of the infimum and the supremum, arguing that continuous monotone maps -- (here the addition of `dist f g`) preserve infimum and supremum have E1 : ∀y, infi (λx:α, g (inl x, inr y)) + dist f g = infi ((λz, z + dist f g) ∘ (λx:α, (g (inl x, inr y)))), { assume y, refine cinfi_of_cinfi_of_monotone_of_continuous (_ : continuous (λ (z : ℝ), z + dist f g)) _ _, { exact continuous_id.add continuous_const }, { assume x y hx, simpa }, { show bdd_below (range (λx:α, g (inl x, inr y))), from ⟨cg, forall_range_iff.2(λi, Hcg _)⟩ } }, have E2 : supr (λy:β, infi (λx:α, g (inl x, inr y))) + dist f g = supr ((λz, z + dist f g) ∘ (λy:β, infi (λx:α, g (inl x, inr y)))), { refine csupr_of_csupr_of_monotone_of_continuous (_ : continuous (λ (z : ℝ), z + dist f g)) _ _, { exact continuous_id.add continuous_const }, { assume x y hx, simpa }, { by simpa using HD_bound_aux2 _ 0 } }, -- deduce the result from the above two steps simp only [add_comm] at Z, simpa [E2, E1, function.comp] end private lemma HD_lipschitz_aux3 (f g : Cb α β) : HD f ≤ HD g + dist f g := max_le (le_trans (HD_lipschitz_aux1 f g) (add_le_add_right (le_max_left _ _) _)) (le_trans (HD_lipschitz_aux2 f g) (add_le_add_right (le_max_right _ _) _)) /-- Conclude that HD, being Lipschitz, is continuous -/ private lemma HD_continuous : continuous (HD : Cb α β → ℝ) := lipschitz_with.to_continuous (lipschitz_with.one_of_le_add HD_lipschitz_aux3) end constructions --section section consequences variables (α : Type u) (β : Type v) [metric_space α] [compact_space α] [nonempty α] [metric_space β] [compact_space β] [nonempty β] /- Now that we have proved that the set of candidates is compact, and that HD is continuous, we can finally select a candidate minimizing HD. This will be the candidate realizing the optimal coupling. -/ private lemma exists_minimizer : ∃f ∈ candidates_b α β, ∀g ∈ candidates_b α β, HD f ≤ HD g := compact_candidates_b.exists_forall_le candidates_b_ne_empty _ HD_continuous.continuous_on private definition optimal_GH_dist : Cb α β := classical.some (exists_minimizer α β) private lemma optimal_GH_dist_mem_candidates_b : optimal_GH_dist α β ∈ candidates_b α β := by cases (classical.some_spec (exists_minimizer α β)); assumption private lemma HD_optimal_GH_dist_le (g : Cb α β) (hg : g ∈ candidates_b α β) : HD (optimal_GH_dist α β) ≤ HD g := let ⟨Z1, Z2⟩ := classical.some_spec (exists_minimizer α β) in Z2 g hg /-- With the optimal candidate, construct a premetric space structure on α ⊕ β, on which the predistance is given by the candidate. Then, we will identify points at 0 predistance to obtain a genuine metric space -/ def premetric_optimal_GH_dist : premetric_space (α ⊕ β) := { dist := λp q, optimal_GH_dist α β (p, q), dist_self := λx, candidates_refl (optimal_GH_dist_mem_candidates_b α β), dist_comm := λx y, candidates_symm (optimal_GH_dist_mem_candidates_b α β), dist_triangle := λx y z, candidates_triangle (optimal_GH_dist_mem_candidates_b α β) } local attribute [instance] premetric_optimal_GH_dist premetric.dist_setoid /-- A metric space which realizes the optimal coupling between α and β -/ @[derive [metric_space]] definition optimal_GH_coupling : Type* := premetric.metric_quot (α ⊕ β) /-- Injection of α in the optimal coupling between α and β -/ def optimal_GH_injl (x : α) : optimal_GH_coupling α β := ⟦inl x⟧ /-- The injection of α in the optimal coupling between α and β is an isometry. -/ lemma isometry_optimal_GH_injl : isometry (optimal_GH_injl α β) := begin refine isometry_emetric_iff_metric.2 (λx y, _), change dist ⟦inl x⟧ ⟦inl y⟧ = dist x y, exact candidates_dist_inl (optimal_GH_dist_mem_candidates_b α β) _ _, end /-- Injection of β in the optimal coupling between α and β -/ def optimal_GH_injr (y : β) : optimal_GH_coupling α β := ⟦inr y⟧ /-- The injection of β in the optimal coupling between α and β is an isometry. -/ lemma isometry_optimal_GH_injr : isometry (optimal_GH_injr α β) := begin refine isometry_emetric_iff_metric.2 (λx y, _), change dist ⟦inr x⟧ ⟦inr y⟧ = dist x y, exact candidates_dist_inr (optimal_GH_dist_mem_candidates_b α β) _ _, end /-- The optimal coupling between two compact spaces α and β is still a compact space -/ instance compact_space_optimal_GH_coupling : compact_space (optimal_GH_coupling α β) := ⟨begin have : (univ : set (optimal_GH_coupling α β)) = (optimal_GH_injl α β '' univ) ∪ (optimal_GH_injr α β '' univ), { refine subset.antisymm (λxc hxc, _) (subset_univ _), rcases quotient.exists_rep xc with ⟨x, hx⟩, cases x; rw ← hx, { have : ⟦inl x⟧ = optimal_GH_injl α β x := rfl, rw this, exact mem_union_left _ (mem_image_of_mem _ (mem_univ _)) }, { have : ⟦inr x⟧ = optimal_GH_injr α β x := rfl, rw this, exact mem_union_right _ (mem_image_of_mem _ (mem_univ _)) } }, rw this, exact (compact_univ.image (isometry_optimal_GH_injl α β).continuous).union (compact_univ.image (isometry_optimal_GH_injr α β).continuous) end⟩ /-- For any candidate f, HD(f) is larger than or equal to the Hausdorff distance in the optimal coupling. This follows from the fact that HD of the optimal candidate is exactly the Hausdorff distance in the optimal coupling, although we only prove here the inequality we need. -/ lemma Hausdorff_dist_optimal_le_HD {f} (h : f ∈ candidates_b α β) : Hausdorff_dist (range (optimal_GH_injl α β)) (range (optimal_GH_injr α β)) ≤ HD f := begin refine le_trans (le_of_forall_le_of_dense (λr hr, _)) (HD_optimal_GH_dist_le α β f h), have A : ∀ x ∈ range (optimal_GH_injl α β), ∃ y ∈ range (optimal_GH_injr α β), dist x y ≤ r, { assume x hx, rcases mem_range.1 hx with ⟨z, hz⟩, rw ← hz, have I1 : supr (λx:α, infi (λy:β, optimal_GH_dist α β (inl x, inr y))) < r := lt_of_le_of_lt (le_max_left _ _) hr, have I2 : infi (λy:β, optimal_GH_dist α β (inl z, inr y)) ≤ supr (λx:α, infi (λy:β, optimal_GH_dist α β (inl x, inr y))) := le_cSup (by simpa using HD_bound_aux1 _ 0) (mem_range_self _), have I : infi (λy:β, optimal_GH_dist α β (inl z, inr y)) < r := lt_of_le_of_lt I2 I1, rcases exists_lt_of_cInf_lt (by simpa) I with ⟨r', r'range, hr'⟩, rcases mem_range.1 r'range with ⟨z', hz'⟩, existsi [optimal_GH_injr α β z', mem_range_self _], have : (optimal_GH_dist α β) (inl z, inr z') ≤ r := begin rw hz', exact le_of_lt hr' end, exact this }, refine Hausdorff_dist_le_of_mem_dist _ A _, { rcases exists_mem_of_nonempty α with ⟨xα, _⟩, have : optimal_GH_injl α β xα ∈ range (optimal_GH_injl α β) := mem_range_self _, rcases A _ this with ⟨y, yrange, hy⟩, exact le_trans dist_nonneg hy }, { assume y hy, rcases mem_range.1 hy with ⟨z, hz⟩, rw ← hz, have I1 : supr (λy:β, infi (λx:α, optimal_GH_dist α β (inl x, inr y))) < r := lt_of_le_of_lt (le_max_right _ _) hr, have I2 : infi (λx:α, optimal_GH_dist α β (inl x, inr z)) ≤ supr (λy:β, infi (λx:α, optimal_GH_dist α β (inl x, inr y))) := le_cSup (by simpa using HD_bound_aux2 _ 0) (mem_range_self _), have I : infi (λx:α, optimal_GH_dist α β (inl x, inr z)) < r := lt_of_le_of_lt I2 I1, rcases exists_lt_of_cInf_lt (by simpa) I with ⟨r', r'range, hr'⟩, rcases mem_range.1 r'range with ⟨z', hz'⟩, existsi [optimal_GH_injl α β z', mem_range_self _], have : (optimal_GH_dist α β) (inl z', inr z) ≤ r := begin rw hz', exact le_of_lt hr' end, rw dist_comm, exact this } end end consequences /- We are done with the construction of the optimal coupling -/ end Gromov_Hausdorff_realized end Gromov_Hausdorff
e05a69b4660a21a9729d219f58c6f6cd0cf61c40
947b78d97130d56365ae2ec264df196ce769371a
/src/Std/Data/DList.lean
7b6b279e877996477856e30a2fbf670f9b82439f
[ "Apache-2.0" ]
permissive
shyamalschandra/lean4
27044812be8698f0c79147615b1d5090b9f4b037
6e7a883b21eaf62831e8111b251dc9b18f40e604
refs/heads/master
1,671,417,126,371
1,601,859,995,000
1,601,860,020,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,777
lean
/- Copyright (c) 2018 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura -/ namespace Std universes u /-- A difference List is a Function that, given a List, returns the original contents of the difference List prepended to the given List. This structure supports `O(1)` `append` and `concat` operations on lists, making it useful for append-heavy uses such as logging and pretty printing. -/ structure DList (α : Type u) := (apply : List α → List α) (invariant : ∀ l, apply l = apply [] ++ l) namespace DList variables {α : Type u} open List def ofList (l : List α) : DList α := ⟨HasAppend.append l, fun t => (appendNil l).symm ▸ rfl⟩ def empty : DList α := ⟨id, fun t => rfl⟩ instance : HasEmptyc (DList α) := ⟨DList.empty⟩ def toList : DList α → List α | ⟨f, h⟩ => f [] def singleton (a : α) : DList α := ⟨fun t => a :: t, fun t => rfl⟩ def cons : α → DList α → DList α | a, ⟨f, h⟩ => ⟨fun t => a :: f t, fun t => show a :: f t = a :: f [] ++ t from have h₁ : a :: f t = a :: (f nil ++ t) := h t ▸ rfl; have h₂ : a :: (f nil ++ t) = a :: f nil ++ t := (consAppend _ _ _).symm; Eq.trans h₁ h₂⟩ def append : DList α → DList α → DList α | ⟨f, h₁⟩, ⟨g, h₂⟩ => ⟨f ∘ g, fun t => show f (g t) = (f (g [])) ++ t from (h₁ (g [])).symm ▸ (appendAssoc (f []) (g []) t).symm ▸ h₂ t ▸ h₁ (g t) ▸ rfl⟩ def push : DList α → α → DList α | ⟨f, h⟩, a => ⟨fun t => f (a :: t), fun t => (h (a::t)).symm ▸ (h [a]).symm ▸ (appendAssoc (f []) [a] t).symm ▸ rfl⟩ instance : HasAppend (DList α) := ⟨DList.append⟩ end DList end Std
93d5b1f63185d53968167c678b4d02be3a45ad5b
2eab05920d6eeb06665e1a6df77b3157354316ad
/src/measure_theory/covering/besicovitch.lean
46860d0fb3a5af1b904d7f634be1468becf90731
[ "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
44,371
lean
/- Copyright (c) 2021 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sébastien Gouëzel -/ import topology.metric_space.basic import set_theory.cardinal_ordinal import measure_theory.integral.lebesgue /-! # Besicovitch covering theorems The topological Besicovitch covering theorem ensures that, in a nice metric space, there exists a number `N` such that, from any family of balls with bounded radii, one can extract `N` families, each made of disjoint balls, covering together all the centers of the initial family. By "nice metric space", we mean a technical property stated as follows: there exists no satellite configuration of `N+1` points (with a given parameter `τ > 1`). Such a configuration is a family of `N + 1` balls, where the first `N` balls all intersect the last one, but none of them contains the center of another one and their radii are controlled. This property is for instance satisfied by finite-dimensional real vector spaces. In this file, we prove the topological Besicovitch covering theorem, in `besicovitch.exist_disjoint_covering_families`. The measurable Besicovitch theorem ensures that, in the same class of metric spaces, if at every point one considers a class of balls of arbitrarily small radii, called admissible balls, then one can cover almost all the space by a family of disjoint admissible balls. It is deduced from the topological Besicovitch theorem, and proved in `besicovitch.exists_disjoint_closed_ball_covering_ae`. ## Main definitions and results * `satellite_config α N τ` is the type of all satellite configurations of `N+1` points in the metric space `α`, with parameter `τ`. * `has_besicovitch_covering` is a class recording that there exist `N` and `τ > 1` such that there is no satellite configuration of `N+1` points with parameter `τ`. * `exist_disjoint_covering_families` is the topological Besicovitch covering theorem: from any family of balls one can extract finitely many disjoint subfamilies covering the same set. * `exists_disjoint_closed_ball_covering` is the measurable Besicovitch covering theorem: from any family of balls with arbitrarily small radii at every point, one can extract countably many disjoint balls covering almost all the space. While the value of `N` is relevant for the precise statement of the topological Besicovitch theorem, it becomes irrelevant for the measurable one. Therefore, this statement is expressed using the `Prop`-valued typeclass `has_besicovitch_covering`. ## Implementation #### Sketch of proof of the topological Besicovitch theorem: We choose balls in a greedy way. First choose a ball with maximal radius (or rather, since there is no guarantee the maximal radius is realized, a ball with radius within a factor `τ` of the supremum). Then, remove all balls whose center is covered by the first ball, and choose among the remaining ones a ball with radius close to maximum. Go on forever until there is no available center (this is a transfinite induction in general). Then define inductively a coloring of the balls. A ball will be of color `i` if it intersects already chosen balls of color `0`, ..., `i - 1`, but none of color `i`. In this way, balls of the same color form a disjoint family, and the space is covered by the families of the different colors. The nontrivial part is to show that at most `N` colors are used. If one needs `N+1` colors, consider the first time this happens. Then the corresponding ball intersects `N` balls of the different colors. Moreover, the inductive construction ensures that the radii of all the balls are controlled: they form a satellite configuration with `N+1` balls (essentially by definition of satellite configurations). Since we assume that there are no such configurations, this is a contradiction. #### Sketch of proof of the measurable Besicovitch theorem: From the topological Besicovitch theorem, one can find a disjoint countable family of balls covering a proportion `> 1/(N+1)` of the space. Taking a large enough finite subset of these balls, one gets the same property for finitely many balls. Their union is closed. Therefore, any point in the complement has around it an admissible ball not intersecting these finitely many balls. Applying again the topological Besicovitch theorem, one extracts from these a disjoint countable subfamily covering a proportion `> 1/(N+1)` of the remaining points, and then even a disjoint finite subfamily. Then one goes on again and again, covering at each step a positive proportion of the remaining points, while remaining disjoint from the already chosen balls. The union of all these balls is the desired almost everywhere covering. -/ noncomputable theory universe u open metric set filter fin measure_theory topological_space open_locale topological_space classical big_operators ennreal measure_theory nnreal /-! ### Satellite configurations -/ /-- A satellite configuration is a configuration of `N+1` points that shows up in the inductive construction for the Besicovitch covering theorem. It depends on some parameter `τ ≥ 1`. This is a family of balls (indexed by `i : fin N.succ`, with center `c i` and radius `r i`) such that the last ball intersects all the other balls (condition `inter`), and given any two balls there is an order between them, ensuring that the first ball does not contain the center of the other one, and the radius of the second ball can not be larger than the radius of the first ball (up to a factor `τ`). This order corresponds to the order of choice in the inductive construction: otherwise, the second ball would have been chosen before. This is the condition `h`. Finally, the last ball is chosen after all the other ones, meaning that `h` can be strengthened by keeping only one side of the alternative in `hlast`. -/ structure besicovitch.satellite_config (α : Type*) [metric_space α] (N : ℕ) (τ : ℝ) := (c : fin N.succ → α) (r : fin N.succ → ℝ) (rpos : ∀ i, 0 < r i) (h : ∀ i j, i ≠ j → (r i ≤ dist (c i) (c j) ∧ r j ≤ τ * r i) ∨ (r j ≤ dist (c j) (c i) ∧ r i ≤ τ * r j)) (hlast : ∀ i < last N, r i ≤ dist (c i) (c (last N)) ∧ r (last N) ≤ τ * r i) (inter : ∀ i < last N, dist (c i) (c (last N)) ≤ r i + r (last N)) /-- A metric space has the Besicovitch covering property if there exist `N` and `τ > 1` such that there are no satellite configuration of parameter `τ` with `N+1` points. This is the condition that guarantees that the measurable Besicovitch covering theorem holds. It is satified by finite-dimensional real vector spaces. -/ class has_besicovitch_covering (α : Type*) [metric_space α] : Prop := (no_satellite_config : ∃ (N : ℕ) (τ : ℝ), 1 < τ ∧ is_empty (besicovitch.satellite_config α N τ)) /-- There is always a satellite configuration with a single point. -/ instance {α : Type*} {τ : ℝ} [inhabited α] [metric_space α] : inhabited (besicovitch.satellite_config α 0 τ) := ⟨{ c := λ i, default α, r := λ i, 1, rpos := λ i, zero_lt_one, h := λ i j hij, (hij (subsingleton.elim i j)).elim, hlast := λ i hi, by { rw subsingleton.elim i (last 0) at hi, exact (lt_irrefl _ hi).elim }, inter := λ i hi, by { rw subsingleton.elim i (last 0) at hi, exact (lt_irrefl _ hi).elim } }⟩ namespace besicovitch namespace satellite_config variables {α : Type*} [metric_space α] {N : ℕ} {τ : ℝ} (a : satellite_config α N τ) lemma inter' (i : fin N.succ) : dist (a.c i) (a.c (last N)) ≤ a.r i + a.r (last N) := begin rcases lt_or_le i (last N) with H|H, { exact a.inter i H }, { have I : i = last N := top_le_iff.1 H, have := (a.rpos (last N)).le, simp only [I, add_nonneg this this, dist_self] } end lemma hlast' (i : fin N.succ) (h : 1 ≤ τ) : a.r (last N) ≤ τ * a.r i := begin rcases lt_or_le i (last N) with H|H, { exact (a.hlast i H).2 }, { have : i = last N := top_le_iff.1 H, rw this, exact le_mul_of_one_le_left (a.rpos _).le h } end end satellite_config /-! ### Extracting disjoint subfamilies from a ball covering -/ /-- A ball package is a family of balls in a metric space with positive bounded radii. -/ structure ball_package (β : Type*) (α : Type*) := (c : β → α) (r : β → ℝ) (rpos : ∀ b, 0 < r b) (r_bound : ℝ) (r_le : ∀ b, r b ≤ r_bound) /-- The ball package made of unit balls. -/ def unit_ball_package (α : Type*) : ball_package α α := { c := id, r := λ _, 1, rpos := λ _, zero_lt_one, r_bound := 1, r_le := λ _, le_rfl } instance (α : Type*) : inhabited (ball_package α α) := ⟨unit_ball_package α⟩ /-- A Besicovitch tau-package is a family of balls in a metric space with positive bounded radii, together with enough data to proceed with the Besicovitch greedy algorithm. We register this in a single structure to make sure that all our constructions in this algorithm only depend on one variable. -/ structure tau_package (β : Type*) (α : Type*) extends ball_package β α := (τ : ℝ) (one_lt_tau : 1 < τ) instance (α : Type*) : inhabited (tau_package α α) := ⟨{ τ := 2, one_lt_tau := one_lt_two, .. unit_ball_package α }⟩ variables {α : Type*} [metric_space α] {β : Type u} namespace tau_package variables [nonempty β] (p : tau_package β α) include p /-- Choose inductively large balls with centers that are not contained in the union of already chosen balls. This is a transfinite induction. -/ noncomputable def index : ordinal.{u} → β | i := -- `Z` is the set of points that are covered by already constructed balls let Z := ⋃ (j : {j // j < i}), ball (p.c (index j)) (p.r (index j)), -- `R` is the supremum of the radii of balls with centers not in `Z` R := supr (λ b : {b : β // p.c b ∉ Z}, p.r b) in -- return an index `b` for which the center `c b` is not in `Z`, and the radius is at -- least `R / τ`, if such an index exists (and garbage otherwise). classical.epsilon (λ b : β, p.c b ∉ Z ∧ R ≤ p.τ * p.r b) using_well_founded {dec_tac := `[exact j.2]} /-- The set of points that are covered by the union of balls selected at steps `< i`. -/ def Union_up_to (i : ordinal.{u}) : set α := ⋃ (j : {j // j < i}), ball (p.c (p.index j)) (p.r (p.index j)) lemma monotone_Union_up_to : monotone p.Union_up_to := begin assume i j hij, simp only [Union_up_to], apply Union_subset_Union2, assume r, exact ⟨⟨r, r.2.trans_le hij⟩, subset.refl _⟩, end /-- Supremum of the radii of balls whose centers are not yet covered at step `i`. -/ def R (i : ordinal.{u}) : ℝ := supr (λ b : {b : β // p.c b ∉ p.Union_up_to i}, p.r b) /-- Group the balls into disjoint families, by assigning to a ball the smallest color for which it does not intersect any already chosen ball of this color. -/ noncomputable def color : ordinal.{u} → ℕ | i := let A : set ℕ := ⋃ (j : {j // j < i}) (hj : (closed_ball (p.c (p.index j)) (p.r (p.index j)) ∩ closed_ball (p.c (p.index i)) (p.r (p.index i))).nonempty), {color j} in Inf (univ \ A) using_well_founded {dec_tac := `[exact j.2]} /-- `p.last_step` is the first ordinal where the construction stops making sense, i.e., `f` returns garbage since there is no point left to be chosen. We will only use ordinals before this step. -/ def last_step : ordinal.{u} := Inf {i | ¬ ∃ (b : β), p.c b ∉ p.Union_up_to i ∧ p.R i ≤ p.τ * p.r b} lemma last_step_nonempty : {i | ¬ ∃ (b : β), p.c b ∉ p.Union_up_to i ∧ p.R i ≤ p.τ * p.r b}.nonempty := begin by_contra, suffices H : function.injective p.index, from not_injective_of_ordinal p.index H, assume x y hxy, wlog x_le_y : x ≤ y := le_total x y using [x y, y x], rcases eq_or_lt_of_le x_le_y with rfl|H, { refl }, simp only [nonempty_def, not_exists, exists_prop, not_and, not_lt, not_le, mem_set_of_eq, not_forall] at h, specialize h y, have A : p.c (p.index y) ∉ p.Union_up_to y, { have : p.index y = classical.epsilon (λ b : β, p.c b ∉ p.Union_up_to y ∧ p.R y ≤ p.τ * p.r b), by { rw [tau_package.index], refl }, rw this, exact (classical.epsilon_spec h).1 }, simp only [Union_up_to, not_exists, exists_prop, mem_Union, mem_closed_ball, not_and, not_le, subtype.exists, subtype.coe_mk] at A, specialize A x H, simp [hxy] at A, exact (lt_irrefl _ ((p.rpos (p.index y)).trans_le A)).elim end /-- Every point is covered by chosen balls, before `p.last_step`. -/ lemma mem_Union_up_to_last_step (x : β) : p.c x ∈ p.Union_up_to p.last_step := begin have A : ∀ (z : β), p.c z ∈ p.Union_up_to p.last_step ∨ p.τ * p.r z < p.R p.last_step, { have : p.last_step ∈ {i | ¬ ∃ (b : β), p.c b ∉ p.Union_up_to i ∧ p.R i ≤ p.τ * p.r b} := Inf_mem p.last_step_nonempty, simpa only [not_exists, mem_set_of_eq, not_and_distrib, not_le, not_not_mem] }, by_contra, rcases A x with H|H, { exact h H }, have Rpos : 0 < p.R p.last_step, { apply lt_trans (mul_pos (_root_.zero_lt_one.trans p.one_lt_tau) (p.rpos _)) H }, have B : p.τ⁻¹ * p.R p.last_step < p.R p.last_step, { conv_rhs { rw ← one_mul (p.R p.last_step) }, exact mul_lt_mul (inv_lt_one p.one_lt_tau) le_rfl Rpos zero_le_one }, obtain ⟨y, hy1, hy2⟩ : ∃ (y : β), p.c y ∉ p.Union_up_to p.last_step ∧ (p.τ)⁻¹ * p.R p.last_step < p.r y, { simpa only [exists_prop, mem_range, exists_exists_and_eq_and, subtype.exists, subtype.coe_mk] using exists_lt_of_lt_cSup _ B, rw [← image_univ, nonempty_image_iff], exact ⟨⟨_, h⟩, mem_univ _⟩ }, rcases A y with Hy|Hy, { exact hy1 Hy }, { rw ← div_eq_inv_mul at hy2, have := (div_le_iff' (_root_.zero_lt_one.trans p.one_lt_tau)).1 hy2.le, exact lt_irrefl _ (Hy.trans_le this) } end /-- If there are no configurations of satellites with `N+1` points, one never uses more than `N` distinct families in the Besicovitch inductive construction. -/ lemma color_lt {i : ordinal.{u}} (hi : i < p.last_step) {N : ℕ} (hN : is_empty (satellite_config α N p.τ)) : p.color i < N := begin /- By contradiction, consider the first ordinal `i` for which one would have `p.color i = N`. Choose for each `k < N` a ball with color `k` that intersects the ball at color `i` (there is such a ball, otherwise one would have used the color `k` and not `N`). Then this family of `N+1` balls forms a satellite configuration, which is forbidden by the assumption `hN`. -/ induction i using ordinal.induction with i IH, let A : set ℕ := ⋃ (j : {j // j < i}) (hj : (closed_ball (p.c (p.index j)) (p.r (p.index j)) ∩ closed_ball (p.c (p.index i)) (p.r (p.index i))).nonempty), {p.color j}, have color_i : p.color i = Inf (univ \ A), by rw [color], rw color_i, have N_mem : N ∈ univ \ A, { simp only [not_exists, true_and, exists_prop, mem_Union, mem_singleton_iff, mem_closed_ball, not_and, mem_univ, mem_diff, subtype.exists, subtype.coe_mk], assume j ji hj, exact (IH j ji (ji.trans hi)).ne' }, suffices : Inf (univ \ A) ≠ N, { rcases (cInf_le (order_bot.bdd_below (univ \ A)) N_mem).lt_or_eq with H|H, { exact H }, { exact (this H).elim } }, assume Inf_eq_N, have : ∀ k, k < N → ∃ j, j < i ∧ (closed_ball (p.c (p.index j)) (p.r (p.index j)) ∩ closed_ball (p.c (p.index i)) (p.r (p.index i))).nonempty ∧ k = p.color j, { assume k hk, rw ← Inf_eq_N at hk, have : k ∈ A, by simpa only [true_and, mem_univ, not_not, mem_diff] using nat.not_mem_of_lt_Inf hk, simp at this, simpa only [exists_prop, mem_Union, mem_singleton_iff, mem_closed_ball, subtype.exists, subtype.coe_mk] }, choose! g hg using this, -- Choose for each `k < N` an ordinal `G k < i` giving a ball of color `k` intersecting -- the last ball. let G : ℕ → ordinal := λ n, if n = N then i else g n, have color_G : ∀ n, n ≤ N → p.color (G n) = n, { assume n hn, unfreezingI { rcases hn.eq_or_lt with rfl|H }, { simp only [G], simp only [color_i, Inf_eq_N, if_true, eq_self_iff_true] }, { simp only [G], simp only [H.ne, (hg n H).right.right.symm, if_false] } }, have G_lt_last : ∀ n, n ≤ N → G n < p.last_step, { assume n hn, unfreezingI { rcases hn.eq_or_lt with rfl|H }, { simp only [G], simp only [hi, if_true, eq_self_iff_true], }, { simp only [G], simp only [H.ne, (hg n H).left.trans hi, if_false] } }, have fGn : ∀ n, n ≤ N → p.c (p.index (G n)) ∉ p.Union_up_to (G n) ∧ p.R (G n) ≤ p.τ * p.r (p.index (G n)), { assume n hn, have: p.index (G n) = classical.epsilon (λ t, p.c t ∉ p.Union_up_to (G n) ∧ p.R (G n) ≤ p.τ * p.r t), by { rw index, refl }, rw this, have : ∃ t, p.c t ∉ p.Union_up_to (G n) ∧ p.R (G n) ≤ p.τ * p.r t, by simpa only [not_exists, exists_prop, not_and, not_lt, not_le, mem_set_of_eq, not_forall] using not_mem_of_lt_cInf (G_lt_last n hn) (order_bot.bdd_below _), exact classical.epsilon_spec this }, -- the balls with indices `G k` satisfy the characteristic property of satellite configurations. have Gab : ∀ (a b : fin (nat.succ N)), G a < G b → p.r (p.index (G a)) ≤ dist (p.c (p.index (G a))) (p.c (p.index (G b))) ∧ p.r (p.index (G b)) ≤ p.τ * p.r (p.index (G a)), { assume a b G_lt, have ha : (a : ℕ) ≤ N := nat.lt_succ_iff.1 a.2, have hb : (b : ℕ) ≤ N := nat.lt_succ_iff.1 b.2, split, { have := (fGn b hb).1, simp only [Union_up_to, not_exists, exists_prop, mem_Union, mem_closed_ball, not_and, not_le, subtype.exists, subtype.coe_mk] at this, simpa only [dist_comm, mem_ball, not_lt] using this (G a) G_lt }, { apply le_trans _ (fGn a ha).2, have B : p.c (p.index (G b)) ∉ p.Union_up_to (G a), { assume H, exact (fGn b hb).1 (p.monotone_Union_up_to G_lt.le H) }, let b' : {t // p.c t ∉ p.Union_up_to (G a)} := ⟨p.index (G b), B⟩, apply @le_csupr _ _ _ (λ t : {t // p.c t ∉ p.Union_up_to (G a)}, p.r t) _ b', refine ⟨p.r_bound, λ t ht, _⟩, simp only [exists_prop, mem_range, subtype.exists, subtype.coe_mk] at ht, rcases ht with ⟨u, hu⟩, rw ← hu.2, exact p.r_le _ } }, -- therefore, one may use them to construct a satellite configuration with `N+1` points let sc : satellite_config α N p.τ := { c := λ k, p.c (p.index (G k)), r := λ k, p.r (p.index (G k)), rpos := λ k, p.rpos (p.index (G k)), h := begin assume a b a_ne_b, wlog G_le : G a ≤ G b := le_total (G a) (G b) using [a b, b a] tactic.skip, { have G_lt : G a < G b, { rcases G_le.lt_or_eq with H|H, { exact H }, have A : (a : ℕ) ≠ b := fin.coe_injective.ne a_ne_b, rw [← color_G a (nat.lt_succ_iff.1 a.2), ← color_G b (nat.lt_succ_iff.1 b.2), H] at A, exact (A rfl).elim }, exact or.inl (Gab a b G_lt) }, { assume a_ne_b, rw or_comm, exact this a_ne_b.symm } end, hlast := begin assume a ha, have I : (a : ℕ) < N := ha, have : G a < G (fin.last N), by { dsimp [G], simp [I.ne, (hg a I).1] }, exact Gab _ _ this, end, inter := begin assume a ha, have I : (a : ℕ) < N := ha, have J : G (fin.last N) = i, by { dsimp [G], simp only [if_true, eq_self_iff_true], }, have K : G a = g a, { dsimp [G], simp [I.ne, (hg a I).1] }, convert dist_le_add_of_nonempty_closed_ball_inter_closed_ball (hg _ I).2.1, end }, -- this is a contradiction exact (hN.false : _) sc end end tau_package open tau_package /-- The topological Besicovitch covering theorem: there exist finitely many families of disjoint balls covering all the centers in a package. More specifically, one can use `N` families if there are no satellite configurations with `N+1` points. -/ theorem exist_disjoint_covering_families {N : ℕ} {τ : ℝ} (hτ : 1 < τ) (hN : is_empty (satellite_config α N τ)) (q : ball_package β α) : ∃ s : fin N → set β, (∀ (i : fin N), (s i).pairwise_on (disjoint on (λ j, closed_ball (q.c j) (q.r j)))) ∧ (range q.c ⊆ ⋃ (i : fin N), ⋃ (j ∈ s i), ball (q.c j) (q.r j)) := begin -- first exclude the trivial case where `β` is empty (we need non-emptiness for the transfinite -- induction, to be able to choose garbage when there is no point left). casesI is_empty_or_nonempty β, { refine ⟨λ i, ∅, λ i, by simp, _⟩, rw [← image_univ, eq_empty_of_is_empty (univ : set β)], simp }, -- Now, assume `β` is nonempty. let p : tau_package β α := { τ := τ, one_lt_tau := hτ, .. q }, -- we use for `s i` the balls of color `i`. let s := λ (i : fin N), ⋃ (k : ordinal.{u}) (hk : k < p.last_step) (h'k : p.color k = i), ({p.index k} : set β), refine ⟨s, λ i, _, _⟩, { -- show that balls of the same color are disjoint simp only [function.on_fun], assume x hx y hy x_ne_y, obtain ⟨jx, jx_lt, jxi, rfl⟩ : ∃ (jx : ordinal), jx < p.last_step ∧ p.color jx = i ∧ x = p.index jx, by simpa only [exists_prop, mem_Union, mem_singleton_iff] using hx, obtain ⟨jy, jy_lt, jyi, rfl⟩ : ∃ (jy : ordinal), jy < p.last_step ∧ p.color jy = i ∧ y = p.index jy, by simpa only [exists_prop, mem_Union, mem_singleton_iff] using hy, wlog jxy : jx ≤ jy := le_total jx jy using [jx jy, jy jx] tactic.skip, swap, { assume h1 h2 h3 h4 h5 h6 h7, rw disjoint.comm, exact this h4 h5 h6 h1 h2 h3 h7.symm }, replace jxy : jx < jy, by { rcases lt_or_eq_of_le jxy with H|rfl, { exact H }, { exact (x_ne_y rfl).elim } }, let A : set ℕ := ⋃ (j : {j // j < jy}) (hj : (closed_ball (p.c (p.index j)) (p.r (p.index j)) ∩ closed_ball (p.c (p.index jy)) (p.r (p.index jy))).nonempty), {p.color j}, have color_j : p.color jy = Inf (univ \ A), by rw [tau_package.color], have : p.color jy ∈ univ \ A, { rw color_j, apply Inf_mem, refine ⟨N, _⟩, simp only [not_exists, true_and, exists_prop, mem_Union, mem_singleton_iff, not_and, mem_univ, mem_diff, subtype.exists, subtype.coe_mk], assume k hk H, exact (p.color_lt (hk.trans jy_lt) hN).ne' }, simp only [not_exists, true_and, exists_prop, mem_Union, mem_singleton_iff, not_and, mem_univ, mem_diff, subtype.exists, subtype.coe_mk] at this, specialize this jx jxy, contrapose! this, simpa only [jxi, jyi, and_true, eq_self_iff_true, ← not_disjoint_iff_nonempty_inter] }, { -- show that the balls of color at most `N` cover every center. refine range_subset_iff.2 (λ b, _), obtain ⟨a, ha⟩ : ∃ (a : ordinal), a < p.last_step ∧ dist (p.c b) (p.c (p.index a)) < p.r (p.index a), by simpa only [Union_up_to, exists_prop, mem_Union, mem_ball, subtype.exists, subtype.coe_mk] using p.mem_Union_up_to_last_step b, simp only [exists_prop, mem_Union, mem_ball, mem_singleton_iff, bUnion_and', exists_eq_left, Union_exists, exists_and_distrib_left], exact ⟨⟨p.color a, p.color_lt ha.1 hN⟩, p.index a, ⟨a, rfl, ha.1, rfl⟩, ha.2⟩ } end /-! ### The measurable Besicovitch covering theorem -/ open_locale nnreal /-- Consider, for each `x` in a set `s`, a radius `r x ∈ (0, 1]`. Then one can find finitely many disjoint balls of the form `closed_ball x (r x)` covering a proportion `1/(N+1)` of `s`, if there are no satellite configurations with `N+1` points. -/ lemma exist_finset_disjoint_balls_large_measure [second_countable_topology α] [measurable_space α] [opens_measurable_space α] (μ : measure α) [is_finite_measure μ] {N : ℕ} {τ : ℝ} (hτ : 1 < τ) (hN : is_empty (satellite_config α N τ)) (s : set α) (r : α → ℝ) (rpos : ∀ x ∈ s, 0 < r x) (rle : ∀ x ∈ s, r x ≤ 1) : ∃ (t : finset α), (↑t ⊆ s) ∧ μ (s \ (⋃ (x ∈ t), closed_ball x (r x))) ≤ N/(N+1) * μ s ∧ (t : set α).pairwise_on (disjoint on (λ x, closed_ball x (r x))) := begin -- exclude the trivial case where `μ s = 0`. rcases le_or_lt (μ s) 0 with hμs|hμs, { have : μ s = 0 := le_bot_iff.1 hμs, refine ⟨∅, by simp only [finset.coe_empty, empty_subset], _, _⟩, { simp only [this, diff_empty, Union_false, Union_empty, nonpos_iff_eq_zero, mul_zero] }, { simp only [finset.coe_empty, pairwise_on_empty], } }, casesI is_empty_or_nonempty α, { simp only [eq_empty_of_is_empty s, measure_empty] at hμs, exact (lt_irrefl _ hμs).elim }, have Npos : N ≠ 0, { unfreezingI { rintros rfl }, inhabit α, exact (not_is_empty_of_nonempty _) hN }, -- introduce a measurable superset `o` with the same measure, for measure computations obtain ⟨o, so, omeas, μo⟩ : ∃ (o : set α), s ⊆ o ∧ measurable_set o ∧ μ o = μ s := exists_measurable_superset μ s, /- We will apply the topological Besicovitch theorem, giving `N` disjoint subfamilies of balls covering `s`. Among these, one of them covers a proportion at least `1/N` of `s`. A large enough finite subfamily will then cover a proportion at least `1/(N+1)`. -/ let a : ball_package s α := { c := λ x, x, r := λ x, r x, rpos := λ x, rpos x x.2, r_bound := 1, r_le := λ x, rle x x.2 }, rcases exist_disjoint_covering_families hτ hN a with ⟨u, hu, hu'⟩, have u_count : ∀ i, countable (u i), { assume i, refine countable_of_nonempty_interior_of_disjoint _ (λ j hj, _) (hu i), have : (ball (j : α) (r j)).nonempty := nonempty_ball.2 (a.rpos _), exact this.mono ball_subset_interior_closed_ball }, let v : fin N → set α := λ i, ⋃ (x : s) (hx : x ∈ u i), closed_ball x (r x), have : ∀ i, measurable_set (v i) := λ i, measurable_set.bUnion (u_count i) (λ b hb, measurable_set_closed_ball), have A : s = ⋃ (i : fin N), s ∩ v i, { refine subset.antisymm _ (Union_subset (λ i, inter_subset_left _ _)), assume x hx, obtain ⟨i, y, hxy, h'⟩ : ∃ (i : fin N) (i_1 : ↥s) (i : i_1 ∈ u i), x ∈ ball ↑i_1 (r ↑i_1), { have : x ∈ range a.c, by simpa only [subtype.range_coe_subtype, set_of_mem_eq], simpa only [mem_Union] using hu' this }, refine mem_Union.2 ⟨i, ⟨hx, _⟩⟩, simp only [v, exists_prop, mem_Union, set_coe.exists, exists_and_distrib_right, subtype.coe_mk], exact ⟨y, ⟨y.2, by simpa only [subtype.coe_eta]⟩, ball_subset_closed_ball h'⟩ }, have S : ∑ (i : fin N), μ s / N ≤ ∑ i, μ (s ∩ v i) := calc ∑ (i : fin N), μ s / N = μ s : begin simp only [finset.card_fin, finset.sum_const, nsmul_eq_mul], rw ennreal.mul_div_cancel', { simp only [Npos, ne.def, nat.cast_eq_zero, not_false_iff] }, { exact ennreal.coe_nat_ne_top } end ... ≤ ∑ i, μ (s ∩ v i) : by { conv_lhs { rw A }, apply measure_Union_fintype_le }, -- choose an index `i` of a subfamily covering at least a proportion `1/N` of `s`. obtain ⟨i, -, hi⟩ : ∃ (i : fin N) (hi : i ∈ finset.univ), μ s / N ≤ μ (s ∩ v i), { apply ennreal.exists_le_of_sum_le _ S, exact ⟨⟨0, bot_lt_iff_ne_bot.2 Npos⟩, finset.mem_univ _⟩ }, replace hi : μ s / (N + 1) < μ (s ∩ v i), { apply lt_of_lt_of_le _ hi, apply (ennreal.mul_lt_mul_left hμs.ne' (measure_lt_top μ s).ne).2, rw ennreal.inv_lt_inv, conv_lhs {rw ← add_zero (N : ℝ≥0∞) }, exact ennreal.add_lt_add_left (ennreal.nat_ne_top N) ennreal.zero_lt_one }, have B : μ (o ∩ v i) = ∑' (x : u i), μ (o ∩ closed_ball x (r x)), { have : o ∩ v i = ⋃ (x : s) (hx : x ∈ u i), o ∩ closed_ball x (r x), by simp only [inter_Union], rw [this, measure_bUnion (u_count i)], { refl }, { exact pairwise_on_disjoint_on_mono (hu i) (λ k hk, inter_subset_right _ _) }, { exact λ b hb, omeas.inter measurable_set_closed_ball } }, -- A large enough finite subfamily of `u i` will also cover a proportion `> 1/(N+1)` of `s`. -- Since `s` might not be measurable, we express this in terms of the measurable superset `o`. obtain ⟨w, hw⟩ : ∃ (w : finset (u i)), μ s / (N + 1) < ∑ (x : u i) in w, μ (o ∩ closed_ball (x : α) (r (x : α))), { have C : has_sum (λ (x : u i), μ (o ∩ closed_ball x (r x))) (μ (o ∩ v i)), by { rw B, exact ennreal.summable.has_sum }, have : μ s / (N+1) < μ (o ∩ v i) := hi.trans_le (measure_mono (inter_subset_inter_left _ so)), exact ((tendsto_order.1 C).1 _ this).exists }, -- Bring back the finset `w i` of `↑(u i)` to a finset of `α`, and check that it works by design. refine ⟨finset.image (λ (x : u i), x) w, _, _, _⟩, -- show that the finset is included in `s`. { simp only [image_subset_iff, coe_coe, finset.coe_image], assume y hy, simp only [subtype.coe_prop, mem_preimage] }, -- show that it covers a large enough proportion of `s`. For measure computations, we do not -- use `s` (which might not be measurable), but its measurable superset `o`. Since their measures -- are the same, this does not spoil the estimates { suffices H : μ (o \ ⋃ x ∈ w, closed_ball ↑x (r ↑x)) ≤ N/(N+1) * μ s, { rw [finset.set_bUnion_finset_image], exact le_trans (measure_mono (diff_subset_diff so (subset.refl _))) H }, rw [← diff_inter_self_eq_diff, measure_diff_le_iff_le_add _ omeas (inter_subset_right _ _) ((measure_lt_top μ _).ne)], swap, { apply measurable_set.inter _ omeas, haveI : encodable (u i) := (u_count i).to_encodable, exact measurable_set.Union (λ b, measurable_set.Union_Prop (λ hb, measurable_set_closed_ball)) }, calc μ o = 1/(N+1) * μ s + N/(N+1) * μ s : by { rw [μo, ← add_mul, ennreal.div_add_div_same, add_comm, ennreal.div_self, one_mul]; simp } ... ≤ μ ((⋃ (x ∈ w), closed_ball ↑x (r ↑x)) ∩ o) + N/(N+1) * μ s : begin refine add_le_add _ le_rfl, rw [div_eq_mul_inv, one_mul, mul_comm, ← div_eq_mul_inv], apply hw.le.trans (le_of_eq _), rw [← finset.set_bUnion_coe, inter_comm _ o, inter_bUnion, finset.set_bUnion_coe, measure_bUnion_finset], { have : (w : set (u i)).pairwise_on (disjoint on (λ (b : u i), closed_ball (b : α) (r (b : α)))), by { assume k hk l hl hkl, exact hu i k k.2 l l.2 (subtype.coe_injective.ne hkl) }, exact pairwise_on_disjoint_on_mono this (λ k hk, inter_subset_right _ _) }, { assume b hb, apply omeas.inter measurable_set_closed_ball } end }, -- show that the balls are disjoint { assume k hk l hl hkl, obtain ⟨k', k'w, rfl⟩ : ∃ (k' : u i), k' ∈ w ∧ ↑↑k' = k, by simpa only [mem_image, finset.mem_coe, coe_coe, finset.coe_image] using hk, obtain ⟨l', l'w, rfl⟩ : ∃ (l' : u i), l' ∈ w ∧ ↑↑l' = l, by simpa only [mem_image, finset.mem_coe, coe_coe, finset.coe_image] using hl, have k'nel' : (k' : s) ≠ l', by { assume h, rw h at hkl, exact hkl rfl }, exact hu i k' k'.2 l' l'.2 k'nel' } end /-- The measurable Besicovitch covering theorem. Assume that, for any `x` in a set `s`, one is given a set of admissible closed balls centered at `x`, with arbitrarily small radii. Then there exists a disjoint covering of almost all `s` by admissible closed balls centered at some points of `s`. This version requires that the underlying measure is finite, and that the space has the Besicovitch covering property (which is satisfied for instance by normed real vector spaces). It expresses the conclusion in a slightly awkward form (with a subset of `α × ℝ`) coming from the proof technique. For a version assuming that the measure is sigma-finite, see `exists_disjoint_closed_ball_covering_ae_aux`. For a version giving the conclusion in a nicer form, see `exists_disjoint_closed_ball_covering_ae`. -/ theorem exists_disjoint_closed_ball_covering_ae_of_finite_measure_aux [second_countable_topology α] [hb : has_besicovitch_covering α] [measurable_space α] [opens_measurable_space α] (μ : measure α) [is_finite_measure μ] (f : α → set ℝ) (s : set α) (hf : ∀ x ∈ s, (f x).nonempty) (hf' : ∀ x ∈ s, f x ⊆ Ioi 0) (hf'' : ∀ x ∈ s, Inf (f x) ≤ 0) : ∃ (t : set (α × ℝ)), (countable t) ∧ (∀ (p : α × ℝ), p ∈ t → p.1 ∈ s) ∧ (∀ (p : α × ℝ), p ∈ t → p.2 ∈ f p.1) ∧ μ (s \ (⋃ (p : α × ℝ) (hp : p ∈ t), closed_ball p.1 p.2)) = 0 ∧ t.pairwise_on (disjoint on (λ p, closed_ball p.1 p.2)) := begin rcases hb.no_satellite_config with ⟨N, τ, hτ, hN⟩, /- Introduce a property `P` on finsets saying that we have a nice disjoint covering of a subset of `s` by admissible balls. -/ let P : finset (α × ℝ) → Prop := λ t, (t : set (α × ℝ)).pairwise_on (disjoint on (λ p, closed_ball p.1 p.2)) ∧ (∀ (p : α × ℝ), p ∈ t → p.1 ∈ s) ∧ (∀ (p : α × ℝ), p ∈ t → p.2 ∈ f p.1), /- Given a finite good covering of a subset `s`, one can find a larger finite good covering, covering additionally a proportion at least `1/(N+1)` of leftover points. This follows from `exist_finset_disjoint_balls_large_measure` applied to balls not intersecting the initial covering. -/ have : ∀ (t : finset (α × ℝ)), P t → ∃ (u : finset (α × ℝ)), t ⊆ u ∧ P u ∧ μ (s \ (⋃ (p : α × ℝ) (hp : p ∈ u), closed_ball p.1 p.2)) ≤ N/(N+1) * μ (s \ (⋃ (p : α × ℝ) (hp : p ∈ t), closed_ball p.1 p.2)), { assume t ht, set B := ⋃ (p : α × ℝ) (hp : p ∈ t), closed_ball p.1 p.2 with hB, have B_closed : is_closed B := is_closed_bUnion (finset.finite_to_set _) (λ i hi, is_closed_ball), set s' := s \ B with hs', have : ∀ x ∈ s', ∃ r ∈ f x, r ≤ 1 ∧ disjoint B (closed_ball x r), { assume x hx, have xs : x ∈ s := ((mem_diff x).1 hx).1, rcases eq_empty_or_nonempty B with hB|hB, { have : (0 : ℝ) < 1 := zero_lt_one, rcases exists_lt_of_cInf_lt (hf x xs) ((hf'' x xs).trans_lt zero_lt_one) with ⟨r, hr, h'r⟩, exact ⟨r, hr, h'r.le, by simp only [hB, empty_disjoint]⟩ }, { let R := inf_dist x B, have : 0 < min R 1 := lt_min ((B_closed.not_mem_iff_inf_dist_pos hB).1 ((mem_diff x).1 hx).2) zero_lt_one, rcases exists_lt_of_cInf_lt (hf x xs) ((hf'' x xs).trans_lt this) with ⟨r, hr, h'r⟩, refine ⟨r, hr, h'r.le.trans (min_le_right _ _), _⟩, rw disjoint.comm, exact disjoint_closed_ball_of_lt_inf_dist (h'r.trans_le (min_le_left _ _)) } }, choose! r hr using this, obtain ⟨v, vs', hμv, hv⟩ : ∃ (v : finset α), ↑v ⊆ s' ∧ μ (s' \ ⋃ (x ∈ v), closed_ball x (r x)) ≤ N/(N+1) * μ s' ∧ (v : set α).pairwise_on (disjoint on λ (x : α), closed_ball x (r x)), { have rpos : ∀ x ∈ s', 0 < r x := λ x hx, hf' x ((mem_diff x).1 hx).1 (hr x hx).1, have rle : ∀ x ∈ s', r x ≤ 1 := λ x hx, (hr x hx).2.1, exact exist_finset_disjoint_balls_large_measure μ hτ hN s' r rpos rle }, refine ⟨t ∪ (finset.image (λ x, (x, r x)) v), finset.subset_union_left _ _, ⟨_, _, _⟩, _⟩, { simp only [finset.coe_union, pairwise_on_union, ht.1, true_and, finset.coe_image], split, { assume p hp q hq hpq, rcases (mem_image _ _ _).1 hp with ⟨p', p'v, rfl⟩, rcases (mem_image _ _ _).1 hq with ⟨q', q'v, rfl⟩, refine hv p' p'v q' q'v (λ hp'q', _), rw [hp'q'] at hpq, exact hpq rfl }, { simp only [function.on_fun, disjoint.comm, and_self], assume p hp q hq hpq, rcases (mem_image _ _ _).1 hq with ⟨q', q'v, rfl⟩, apply disjoint_of_subset_left _ (hr q' (vs' q'v)).2.2, rw [hB, ← finset.set_bUnion_coe], exact subset_bUnion_of_mem hp } }, { assume p hp, rcases finset.mem_union.1 hp with h'p|h'p, { exact ht.2.1 p h'p }, { rcases finset.mem_image.1 h'p with ⟨p', p'v, rfl⟩, exact ((mem_diff _).1 (vs' (finset.mem_coe.2 p'v))).1 } }, { assume p hp, rcases finset.mem_union.1 hp with h'p|h'p, { exact ht.2.2 p h'p }, { rcases finset.mem_image.1 h'p with ⟨p', p'v, rfl⟩, dsimp, exact (hr p' (vs' p'v)).1 } }, { convert hμv using 2, rw [finset.set_bUnion_union, ← diff_diff, finset.set_bUnion_finset_image] } }, /- Define `F` associating to a finite good covering the above enlarged good covering, covering a proportion `1/(N+1)` of leftover points. Iterating `F`, one will get larger and larger good coverings, missing in the end only a measure-zero set. -/ choose! F hF using this, let u := λ n, F^[n] ∅, have u_succ : ∀ (n : ℕ), u n.succ = F (u n) := λ n, by simp only [u, function.comp_app, function.iterate_succ'], have Pu : ∀ n, P (u n), { assume n, induction n with n IH, { simp only [u, P, prod.forall, id.def, function.iterate_zero], simp only [finset.not_mem_empty, forall_false_left, finset.coe_empty, forall_2_true_iff, and_self, pairwise_on_empty] }, { rw u_succ, exact (hF (u n) IH).2.1 } }, refine ⟨⋃ n, u n, countable_Union (λ n, (u n).countable_to_set), _, _, _, _⟩, { assume p hp, rcases mem_Union.1 hp with ⟨n, hn⟩, exact (Pu n).2.1 p (finset.mem_coe.1 hn) }, { assume p hp, rcases mem_Union.1 hp with ⟨n, hn⟩, exact (Pu n).2.2 p (finset.mem_coe.1 hn) }, { have A : ∀ n, μ (s \ ⋃ (p : α × ℝ) (hp : p ∈ ⋃ (n : ℕ), (u n : set (α × ℝ))), closed_ball p.fst p.snd) ≤ μ (s \ ⋃ (p : α × ℝ) (hp : p ∈ u n), closed_ball p.fst p.snd), { assume n, apply measure_mono, apply diff_subset_diff (subset.refl _), exact bUnion_subset_bUnion_left (subset_Union (λ i, (u i : set (α × ℝ))) n) }, have B : ∀ n, μ (s \ ⋃ (p : α × ℝ) (hp : p ∈ u n), closed_ball p.fst p.snd) ≤ (N/(N+1))^n * μ s, { assume n, induction n with n IH, { simp only [le_refl, diff_empty, one_mul, Union_false, Union_empty, pow_zero] }, calc μ (s \ ⋃ (p : α × ℝ) (hp : p ∈ u n.succ), closed_ball p.fst p.snd) ≤ (N/(N+1)) * μ (s \ ⋃ (p : α × ℝ) (hp : p ∈ u n), closed_ball p.fst p.snd) : by { rw u_succ, exact (hF (u n) (Pu n)).2.2 } ... ≤ (N/(N+1))^n.succ * μ s : by { rw [pow_succ, mul_assoc], exact ennreal.mul_le_mul le_rfl IH } }, have C : tendsto (λ (n : ℕ), ((N : ℝ≥0∞)/(N+1))^n * μ s) at_top (𝓝 (0 * μ s)), { apply ennreal.tendsto.mul_const _ (or.inr (measure_lt_top μ s).ne), apply ennreal.tendsto_pow_at_top_nhds_0_of_lt_1, rw [ennreal.div_lt_iff, one_mul], { conv_lhs {rw ← add_zero (N : ℝ≥0∞) }, exact ennreal.add_lt_add_left (ennreal.nat_ne_top N) ennreal.zero_lt_one }, { simp only [true_or, add_eq_zero_iff, ne.def, not_false_iff, one_ne_zero, and_false] }, { simp only [ennreal.nat_ne_top, ne.def, not_false_iff, or_true] } }, rw zero_mul at C, apply le_bot_iff.1, exact le_of_tendsto_of_tendsto' tendsto_const_nhds C (λ n, (A n).trans (B n)) }, { refine (pairwise_on_Union _).2 (λ n, (Pu n).1), apply (monotone_nat_of_le_succ (λ n, _)).directed_le, rw u_succ, exact (hF (u n) (Pu n)).1 } end /-- The measurable Besicovitch covering theorem. Assume that, for any `x` in a set `s`, one is given a set of admissible closed balls centered at `x`, with arbitrarily small radii. Then there exists a disjoint covering of almost all `s` by admissible closed balls centered at some points of `s`. This version requires that the underlying measure is sigma-finite, and that the space has the Besicovitch covering property (which is satisfied for instance by normed real vector spaces). It expresses the conclusion in a slightly awkward form (with a subset of `α × ℝ`) coming from the proof technique. For a version giving the conclusion in a nicer form, see `exists_disjoint_closed_ball_covering_ae`. -/ theorem exists_disjoint_closed_ball_covering_ae_aux [second_countable_topology α] [has_besicovitch_covering α] [measurable_space α] [opens_measurable_space α] (μ : measure α) [sigma_finite μ] (f : α → set ℝ) (s : set α) (hf : ∀ x ∈ s, (f x).nonempty) (hf' : ∀ x ∈ s, f x ⊆ Ioi 0) (hf'' : ∀ x ∈ s, Inf (f x) ≤ 0) : ∃ (t : set (α × ℝ)), (countable t) ∧ (∀ (p : α × ℝ), p ∈ t → p.1 ∈ s) ∧ (∀ (p : α × ℝ), p ∈ t → p.2 ∈ f p.1) ∧ μ (s \ (⋃ (p : α × ℝ) (hp : p ∈ t), closed_ball p.1 p.2)) = 0 ∧ t.pairwise_on (disjoint on (λ p, closed_ball p.1 p.2)) := begin /- This is deduced from the finite measure case, by using a finite measure with respect to which the initial sigma-finite measure is absolutely continuous. -/ unfreezingI { rcases exists_absolutely_continuous_is_finite_measure μ with ⟨ν, hν, hμν⟩ }, rcases exists_disjoint_closed_ball_covering_ae_of_finite_measure_aux ν f s hf hf' hf'' with ⟨t, t_count, ts, tr, tν, tdisj⟩, exact ⟨t, t_count, ts, tr, hμν tν, tdisj⟩, end /-- The measurable Besicovitch covering theorem. Assume that, for any `x` in a set `s`, one is given a set of admissible closed balls centered at `x`, with arbitrarily small radii. Then there exists a disjoint covering of almost all `s` by admissible closed balls centered at some points of `s`. This version requires that the underlying measure is sigma-finite, and that the space has the Besicovitch covering property (which is satisfied for instance by normed real vector spaces). -/ theorem exists_disjoint_closed_ball_covering_ae [second_countable_topology α] [hb : has_besicovitch_covering α] [measurable_space α] [opens_measurable_space α] (μ : measure α) [sigma_finite μ] (f : α → set ℝ) (s : set α) (hf : ∀ x ∈ s, (f x).nonempty) (hf' : ∀ x ∈ s, f x ⊆ Ioi 0) (hf'' : ∀ x ∈ s, Inf (f x) ≤ 0) : ∃ (t : set α) (r : α → ℝ), countable t ∧ t ⊆ s ∧ (∀ x ∈ t, r x ∈ f x) ∧ μ (s \ (⋃ (x ∈ t), closed_ball x (r x))) = 0 ∧ t.pairwise_on (disjoint on (λ x, closed_ball x (r x))) := begin rcases exists_disjoint_closed_ball_covering_ae_aux μ f s hf hf' hf'' with ⟨v, v_count, vs, vf, μv, v_disj⟩, let t := prod.fst '' v, have : ∀ x ∈ t, ∃ (r : ℝ), (x, r) ∈ v, { assume x hx, rcases (mem_image _ _ _).1 hx with ⟨⟨p, q⟩, hp, rfl⟩, exact ⟨q, hp⟩ }, choose! r hr using this, have im_t : (λ x, (x, r x)) '' t = v, { have I : ∀ (p : α × ℝ), p ∈ v → 0 ≤ p.2 := λ p hp, le_of_lt (hf' _ (vs _ hp) (vf _ hp)), apply subset.antisymm, { simp only [image_subset_iff], rintros ⟨x, p⟩ hxp, simp only [mem_preimage], exact hr _ (mem_image_of_mem _ hxp) }, { rintros ⟨x, p⟩ hxp, have hxrx : (x, r x) ∈ v := hr _ (mem_image_of_mem _ hxp), have : p = r x, { by_contra, have A : (x, p) ≠ (x, r x), by simpa only [true_and, prod.mk.inj_iff, eq_self_iff_true, ne.def] using h, have H := v_disj (x, p) hxp (x, r x) hxrx A, contrapose H, rw not_disjoint_iff_nonempty_inter, refine ⟨x, by simp [I _ hxp, I _ hxrx]⟩ }, rw this, apply mem_image_of_mem, exact mem_image_of_mem _ hxp } }, refine ⟨t, r, v_count.image _, _, _, _, _⟩, { assume x hx, rcases (mem_image _ _ _).1 hx with ⟨⟨p, q⟩, hp, rfl⟩, exact vs _ hp }, { assume x hx, rcases (mem_image _ _ _).1 hx with ⟨⟨p, q⟩, hp, rfl⟩, exact vf _ (hr _ hx) }, { have : (⋃ (x : α) (H : x ∈ t), closed_ball x (r x)) = (⋃ (p : α × ℝ) (H : p ∈ (λ x, (x, r x)) '' t), closed_ball p.1 p.2), by conv_rhs { rw bUnion_image }, rw [this, im_t], exact μv }, { have A : inj_on (λ x : α, (x, r x)) t, by simp only [inj_on, prod.mk.inj_iff, implies_true_iff, eq_self_iff_true] {contextual := tt}, rwa [← im_t, A.pairwise_on_image] at v_disj } end end besicovitch
d2d05ee85707ea78e1717250b2223c3e882a4b7f
4efff1f47634ff19e2f786deadd394270a59ecd2
/src/category_theory/monoidal/braided.lean
9b9cff316df44d5552ef0ebd8c2ee9ed996dcc6a
[ "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
4,123
lean
/- Copyright (c) 2020 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import category_theory.monoidal.functor /-! # Braided and symmetric monoidal categories The basic definitions of braided monoidal categories, and symmetric monoidal categories, as well as braided functors. ## Implementation note We make `braided_monoidal_category` another typeclass, but then have `symmetric_monoidal_category` extend this. The rationale is that we are not carrying any additional data, just requiring a property. ## Future work * Construct the Drinfeld center of a monoidal category as a braided monoidal category. * Say something about pseudo-natural transformations. -/ open category_theory universes v v₁ v₂ v₃ u u₁ u₂ u₃ namespace category_theory /-- A braided monoidal category is a monoidal category equipped with a braiding isomorphism `β_ X Y : X ⊗ Y ≅ Y ⊗ X` which is natural in both arguments, and also satisfies the two hexagon identities. -/ class braided_category (C : Type u) [category.{v} C] [monoidal_category.{v} C] := -- braiding natural iso: (braiding : Π X Y : C, X ⊗ Y ≅ Y ⊗ X) (braiding_naturality' : ∀ {X X' Y Y' : C} (f : X ⟶ Y) (g : X' ⟶ Y'), (f ⊗ g) ≫ (braiding Y Y').hom = (braiding X X').hom ≫ (g ⊗ f) . obviously) -- hexagon identities: (hexagon_forward' : Π X Y Z : C, (α_ X Y Z).hom ≫ (braiding X (Y ⊗ Z)).hom ≫ (α_ Y Z X).hom = ((braiding X Y).hom ⊗ (𝟙 Z)) ≫ (α_ Y X Z).hom ≫ ((𝟙 Y) ⊗ (braiding X Z).hom) . obviously) (hexagon_reverse' : Π X Y Z : C, (α_ X Y Z).inv ≫ (braiding (X ⊗ Y) Z).hom ≫ (α_ Z X Y).inv = ((𝟙 X) ⊗ (braiding Y Z).hom) ≫ (α_ X Z Y).inv ≫ ((braiding X Z).hom ⊗ (𝟙 Y)) . obviously) restate_axiom braided_category.braiding_naturality' attribute [simp,reassoc] braided_category.braiding_naturality restate_axiom braided_category.hexagon_forward' restate_axiom braided_category.hexagon_reverse' open braided_category notation `β_` := braiding section prio set_option default_priority 100 -- see Note [default priority] /-- A symmetric monoidal category is a braided monoidal category for which the braiding is symmetric. -/ class symmetric_category (C : Type u) [category.{v} C] [monoidal_category.{v} C] extends braided_category.{v} C := -- braiding symmetric: (symmetry' : ∀ X Y : C, (β_ X Y).hom ≫ (β_ Y X).hom = 𝟙 (X ⊗ Y) . obviously) end prio restate_axiom symmetric_category.symmetry' attribute [simp,reassoc] symmetric_category.symmetry variables (C : Type u₁) [category.{v₁} C] [monoidal_category C] [braided_category C] variables (D : Type u₂) [category.{v₂} D] [monoidal_category D] [braided_category D] variables (E : Type u₃) [category.{v₃} E] [monoidal_category E] [braided_category E] /-- A braided functor between braided monoidal categories is a monoidal functor which preserves the braiding. -/ structure braided_functor extends monoidal_functor C D := (braided' : ∀ X Y : C, map (β_ X Y).hom = inv (μ X Y) ≫ (β_ (obj X) (obj Y)).hom ≫ μ Y X . obviously) restate_axiom braided_functor.braided' -- It's not totally clear that `braided` deserves to be a `simp` lemma. -- The principle being applying here is that `μ` "doesn't weigh much" -- (similar to all the structural morphisms, e.g. associators and unitors) -- and the `simp` normal form is determined by preferring `obj` over `map`. attribute [simp] braided_functor.braided namespace braided_functor /-- The identity braided monoidal functor. -/ @[simps] def id : braided_functor C C := { braided' := λ X Y, by { dsimp, simp, }, .. monoidal_functor.id C } instance : inhabited (braided_functor C C) := ⟨id C⟩ variables {C D E} /-- The composition of braided monoidal functors. -/ @[simps] def comp (F : braided_functor C D) (G : braided_functor D E) : braided_functor C E := { braided' := λ X Y, by { dsimp, simp, }, ..(monoidal_functor.comp F.to_monoidal_functor G.to_monoidal_functor) } end braided_functor end category_theory
9b286cf188fe427c1da9bd421b49bd9e10de2b52
cf39355caa609c0f33405126beee2739aa3cb77e
/library/init/data/fin/ops.lean
da75e685ecee3819720e2e7fab3d6335abe7608e
[ "Apache-2.0" ]
permissive
leanprover-community/lean
12b87f69d92e614daea8bcc9d4de9a9ace089d0e
cce7990ea86a78bdb383e38ed7f9b5ba93c60ce0
refs/heads/master
1,687,508,156,644
1,684,951,104,000
1,684,951,104,000
169,960,991
457
107
Apache-2.0
1,686,744,372,000
1,549,790,268,000
C++
UTF-8
Lean
false
false
3,308
lean
/- Copyright (c) 2017 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura -/ prelude import init.data.nat init.data.fin.basic namespace fin open nat variable {n : nat} protected def succ : fin n → fin (succ n) | ⟨a, h⟩ := ⟨nat.succ a, succ_lt_succ h⟩ def of_nat {n : nat} (a : nat) : fin (succ n) := ⟨a % succ n, nat.mod_lt _ (nat.zero_lt_succ _)⟩ private lemma mlt {n b : nat} : ∀ {a}, n > a → b % n < n | 0 h := nat.mod_lt _ h | (a+1) h := have n > 0, from lt_trans (nat.zero_lt_succ _) h, nat.mod_lt _ this protected def add : fin n → fin n → fin n | ⟨a, h⟩ ⟨b, _⟩ := ⟨(a + b) % n, mlt h⟩ protected def mul : fin n → fin n → fin n | ⟨a, h⟩ ⟨b, _⟩ := ⟨(a * b) % n, mlt h⟩ private lemma sublt {a b n : nat} (h : a < n) : a - b < n := lt_of_le_of_lt (nat.sub_le a b) h protected def sub : fin n → fin n → fin n | ⟨a, h⟩ ⟨b, _⟩ := ⟨(a + (n - b)) % n, mlt h⟩ private lemma modlt {a b n : nat} (h₁ : a < n) (h₂ : b < n) : a % b < n := begin cases b with b, {simp [mod_zero], assumption}, {have h : a % (succ b) < succ b, apply nat.mod_lt _ (nat.zero_lt_succ _), exact lt_trans h h₂} end protected def mod : fin n → fin n → fin n | ⟨a, h₁⟩ ⟨b, h₂⟩ := ⟨a % b, modlt h₁ h₂⟩ private lemma divlt {a b n : nat} (h : a < n) : a / b < n := lt_of_le_of_lt (nat.div_le_self a b) h protected def div : fin n → fin n → fin n | ⟨a, h⟩ ⟨b, _⟩ := ⟨a / b, divlt h⟩ instance : has_zero (fin (succ n)) := ⟨⟨0, succ_pos n⟩⟩ instance : has_one (fin (succ n)) := ⟨of_nat 1⟩ instance : has_add (fin n) := ⟨fin.add⟩ instance : has_sub (fin n) := ⟨fin.sub⟩ instance : has_mul (fin n) := ⟨fin.mul⟩ instance : has_mod (fin n) := ⟨fin.mod⟩ instance : has_div (fin n) := ⟨fin.div⟩ lemma of_nat_zero : @of_nat n 0 = 0 := rfl lemma add_def (a b : fin n) : (a + b).val = (a.val + b.val) % n := show (fin.add a b).val = (a.val + b.val) % n, from by cases a; cases b; simp [fin.add] lemma mul_def (a b : fin n) : (a * b).val = (a.val * b.val) % n := show (fin.mul a b).val = (a.val * b.val) % n, from by cases a; cases b; simp [fin.mul] lemma sub_def (a b : fin n) : (a - b).val = (a.val + (n - b.val)) % n := by cases a; cases b; refl lemma mod_def (a b : fin n) : (a % b).val = a.val % b.val := show (fin.mod a b).val = a.val % b.val, from by cases a; cases b; simp [fin.mod] lemma div_def (a b : fin n) : (a / b).val = a.val / b.val := show (fin.div a b).val = a.val / b.val, from by cases a; cases b; simp [fin.div] lemma lt_def (a b : fin n) : (a < b) = (a.val < b.val) := show (fin.lt a b) = (a.val < b.val), from by cases a; cases b; simp [fin.lt] lemma le_def (a b : fin n) : (a ≤ b) = (a.val ≤ b.val) := show (fin.le a b) = (a.val ≤ b.val), from by cases a; cases b; simp [fin.le] lemma val_zero : (0 : fin (succ n)).val = 0 := rfl def pred {n : nat} : ∀ i : fin (succ n), i ≠ 0 → fin n | ⟨a, h₁⟩ h₂ := ⟨a.pred, begin have this : a ≠ 0, { have aux₁ := vne_of_ne h₂, dsimp at aux₁, rw val_zero at aux₁, exact aux₁ }, exact nat.pred_lt_pred this h₁ end⟩ end fin
fab6903daa2bdf5422be4b0a3cd87d33e423c1fe
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/archive/imo/imo2013_q5.lean
16f7cdf6c6ab6e263a70a191614cd07f4eb4f6b7
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
13,143
lean
/- Copyright (c) 2021 David Renshaw. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: David Renshaw -/ import algebra.geom_sum import data.rat.defs import data.real.basic import tactic.positivity /-! # IMO 2013 Q5 > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. Let `ℚ>₀` be the positive rational numbers. Let `f : ℚ>₀ → ℝ` be a function satisfying the conditions 1. `f(x) * f(y) ≥ f(x * y)` 2. `f(x + y) ≥ f(x) + f(y)` for all `x, y ∈ ℚ>₀`. Given that `f(a) = a` for some rational `a > 1`, prove that `f(x) = x` for all `x ∈ ℚ>₀`. # Solution We provide a direct translation of the solution found in https://www.imo-official.org/problems/IMO2013SL.pdf -/ open_locale big_operators namespace imo2013_q5 lemma le_of_all_pow_lt_succ {x y : ℝ} (hx : 1 < x) (hy : 1 < y) (h : ∀ n : ℕ, 0 < n → x^n - 1 < y^n) : x ≤ y := begin by_contra' hxy, have hxmy : 0 < x - y := sub_pos.mpr hxy, have hn : ∀ n : ℕ, 0 < n → (x - y) * (n : ℝ) ≤ x^n - y^n, { intros n hn, have hterm : ∀ i : ℕ, i ∈ finset.range n → 1 ≤ x^i * y^(n - 1 - i), { intros i hi, have hx' : 1 ≤ x ^ i := one_le_pow_of_one_le hx.le i, have hy' : 1 ≤ y ^ (n - 1 - i) := one_le_pow_of_one_le hy.le (n - 1 - i), calc 1 ≤ x^i : hx' ... = x^i * 1 : (mul_one _).symm ... ≤ x^i * y^(n-1-i) : mul_le_mul_of_nonneg_left hy' (zero_le_one.trans hx') }, calc (x - y) * (n : ℝ) = (n : ℝ) * (x - y) : mul_comm _ _ ... = (∑ (i : ℕ) in finset.range n, (1 : ℝ)) * (x - y) : by simp only [mul_one, finset.sum_const, nsmul_eq_mul, finset.card_range] ... ≤ (∑ (i : ℕ) in finset.range n, x ^ i * y ^ (n - 1 - i)) * (x-y) : (mul_le_mul_right hxmy).mpr (finset.sum_le_sum hterm) ... = x^n - y^n : geom_sum₂_mul x y n, }, -- Choose n larger than 1 / (x - y). obtain ⟨N, hN⟩ := exists_nat_gt (1 / (x - y)), have hNp : 0 < N, { exact_mod_cast (one_div_pos.mpr hxmy).trans hN }, have := calc 1 = (x - y) * (1 / (x - y)) : by field_simp [ne_of_gt hxmy] ... < (x - y) * N : (mul_lt_mul_left hxmy).mpr hN ... ≤ x^N - y^N : hn N hNp, linarith [h N hNp] end /-- Like le_of_all_pow_lt_succ, but with a weaker assumption for y. -/ lemma le_of_all_pow_lt_succ' {x y : ℝ} (hx : 1 < x) (hy : 0 < y) (h : ∀ n : ℕ, 0 < n → x^n - 1 < y^n) : x ≤ y := begin refine le_of_all_pow_lt_succ hx _ h, by_contra' hy'' : y ≤ 1, -- Then there exists y' such that 0 < y ≤ 1 < y' < x. let y' := (x + 1) / 2, have h_y'_lt_x : y' < x, { have hh : (x + 1)/2 < (x * 2) / 2, { linarith }, calc y' < (x * 2) / 2 : hh ... = x : by field_simp }, have h1_lt_y' : 1 < y', { have hh' : 1 * 2 / 2 < (x + 1) / 2, { linarith }, calc 1 = 1 * 2 / 2 : by field_simp ... < y' : hh' }, have h_y_lt_y' : y < y' := hy''.trans_lt h1_lt_y', have hh : ∀ n, 0 < n → x^n - 1 < y'^n, { intros n hn, calc x^n - 1 < y^n : h n hn ... ≤ y'^n : pow_le_pow_of_le_left hy.le h_y_lt_y'.le n }, exact h_y'_lt_x.not_le (le_of_all_pow_lt_succ hx h1_lt_y' hh) end lemma f_pos_of_pos {f : ℚ → ℝ} {q : ℚ} (hq : 0 < q) (H1 : ∀ x y, 0 < x → 0 < y → f (x * y) ≤ f x * f y) (H4 : ∀ n : ℕ, 0 < n → (n : ℝ) ≤ f n) : 0 < f q := begin have num_pos : 0 < q.num := rat.num_pos_iff_pos.mpr hq, have hmul_pos := calc (0 : ℝ) < q.num : int.cast_pos.mpr num_pos ... = ((q.num.nat_abs : ℤ) : ℝ) : congr_arg coe (int.nat_abs_of_nonneg num_pos.le).symm ... ≤ f q.num.nat_abs : H4 q.num.nat_abs (int.nat_abs_pos_of_ne_zero num_pos.ne') ... = f q.num : by rw [nat.cast_nat_abs, abs_of_nonneg num_pos.le] ... = f (q * q.denom) : by rw ←rat.mul_denom_eq_num ... ≤ f q * f q.denom : H1 q q.denom hq (nat.cast_pos.mpr q.pos), have h_f_denom_pos := calc (0 : ℝ) < q.denom : nat.cast_pos.mpr q.pos ... ≤ f q.denom : H4 q.denom q.pos, exact pos_of_mul_pos_left hmul_pos h_f_denom_pos.le, end lemma fx_gt_xm1 {f : ℚ → ℝ} {x : ℚ} (hx : 1 ≤ x) (H1 : ∀ x y, 0 < x → 0 < y → f (x * y) ≤ f x * f y) (H2 : ∀ x y, 0 < x → 0 < y → f x + f y ≤ f (x + y)) (H4 : ∀ n : ℕ, 0 < n → (n : ℝ) ≤ f n) : (x - 1 : ℝ) < f x := begin have hx0 := calc (x - 1 : ℝ) < ⌊x⌋₊ : by exact_mod_cast nat.sub_one_lt_floor x ... ≤ f ⌊x⌋₊ : H4 _ (nat.floor_pos.2 hx), obtain h_eq | h_lt := (nat.floor_le $ zero_le_one.trans hx).eq_or_lt, { rwa h_eq at hx0 }, calc (x - 1 : ℝ) < f ⌊x⌋₊ : hx0 ... < f (x - ⌊x⌋₊) + f ⌊x⌋₊ : lt_add_of_pos_left _ (f_pos_of_pos (sub_pos.mpr h_lt) H1 H4) ... ≤ f (x - ⌊x⌋₊ + ⌊x⌋₊) : H2 _ _ (sub_pos.mpr h_lt) (nat.cast_pos.2 (nat.floor_pos.2 hx)) ... = f x : by rw sub_add_cancel end lemma pow_f_le_f_pow {f : ℚ → ℝ} {n : ℕ} (hn : 0 < n) {x : ℚ} (hx : 1 < x) (H1 : ∀ x y, 0 < x → 0 < y → f (x * y) ≤ f x * f y) (H4 : ∀ n : ℕ, 0 < n → (n : ℝ) ≤ f n) : f (x^n) ≤ (f x)^n := begin induction n with pn hpn, { exfalso, exact nat.lt_asymm hn hn }, cases pn, { simp only [pow_one] }, have hpn' := hpn pn.succ_pos, rw [pow_succ' x (pn + 1), pow_succ' (f x) (pn + 1)], have hxp : 0 < x := by positivity, calc f ((x ^ (pn+1)) * x) ≤ f (x ^ (pn+1)) * f x : H1 (x ^ (pn+1)) x (pow_pos hxp (pn+1)) hxp ... ≤ (f x) ^ (pn+1) * f x : (mul_le_mul_right (f_pos_of_pos hxp H1 H4)).mpr hpn' end lemma fixed_point_of_pos_nat_pow {f : ℚ → ℝ} {n : ℕ} (hn : 0 < n) (H1 : ∀ x y, 0 < x → 0 < y → f (x * y) ≤ f x * f y) (H4 : ∀ n : ℕ, 0 < n → (n : ℝ) ≤ f n) (H5 : ∀ x : ℚ, 1 < x → (x : ℝ) ≤ f x) {a : ℚ} (ha1 : 1 < a) (hae : f a = a) : f (a^n) = a^n := begin have hh0 : (a : ℝ) ^ n ≤ f (a ^ n), { exact_mod_cast H5 (a ^ n) (one_lt_pow ha1 hn.ne') }, have hh1 := calc f (a^n) ≤ (f a)^n : pow_f_le_f_pow hn ha1 H1 H4 ... = (a : ℝ)^n : by rw ← hae, exact hh1.antisymm hh0 end lemma fixed_point_of_gt_1 {f : ℚ → ℝ} {x : ℚ} (hx : 1 < x) (H1 : ∀ x y, 0 < x → 0 < y → f (x * y) ≤ f x * f y) (H2 : ∀ x y, 0 < x → 0 < y → f x + f y ≤ f (x + y)) (H4 : ∀ n : ℕ, 0 < n → (n : ℝ) ≤ f n) (H5 : ∀ x : ℚ, 1 < x → (x : ℝ) ≤ f x) {a : ℚ} (ha1 : 1 < a) (hae : f a = a) : f x = x := begin -- Choose n such that 1 + x < a^n. obtain ⟨N, hN⟩ := pow_unbounded_of_one_lt (1 + x) ha1, have h_big_enough : (1:ℚ) < a^N - x := lt_sub_iff_add_lt.mpr hN, have h1 := calc (x : ℝ) + ((a^N - x) : ℚ) ≤ f x + ((a^N - x) : ℚ) : add_le_add_right (H5 x hx) _ ... ≤ f x + f (a^N - x) : add_le_add_left (H5 _ h_big_enough) _, have hxp : 0 < x := by positivity, have hNp : 0 < N, { by_contra' H, rw [le_zero_iff.mp H] at hN, linarith }, have h2 := calc f x + f (a^N - x) ≤ f (x + (a^N - x)) : H2 x (a^N - x) hxp (zero_lt_one.trans h_big_enough) ... = f (a^N) : by ring_nf ... = a^N : fixed_point_of_pos_nat_pow hNp H1 H4 H5 ha1 hae ... = x + (a^N - x) : by ring, have heq := h1.antisymm (by exact_mod_cast h2), linarith [H5 x hx, H5 _ h_big_enough] end end imo2013_q5 open imo2013_q5 theorem imo2013_q5 (f : ℚ → ℝ) (H1 : ∀ x y, 0 < x → 0 < y → f (x * y) ≤ f x * f y) (H2 : ∀ x y, 0 < x → 0 < y → f x + f y ≤ f (x + y)) (H_fixed_point : ∃ a, 1 < a ∧ f a = a) : ∀ x, 0 < x → f x = x := begin obtain ⟨a, ha1, hae⟩ := H_fixed_point, have H3 : ∀ x : ℚ, 0 < x → ∀ n : ℕ, 0 < n → ↑n * f x ≤ f (n * x), { intros x hx n hn, cases n, { exact (lt_irrefl 0 hn).elim }, induction n with pn hpn, { simp only [one_mul, nat.cast_one] }, calc ↑(pn + 2) * f x = (↑pn + 1 + 1) * f x : by norm_cast ... = ((pn : ℝ) + 1) * f x + 1 * f x : add_mul (↑pn + 1) 1 (f x) ... = (↑pn + 1) * f x + f x : by rw one_mul ... ≤ f ((↑pn.succ) * x) + f x : by exact_mod_cast add_le_add_right (hpn pn.succ_pos) (f x) ... ≤ f ((↑pn + 1) * x + x) : by exact_mod_cast H2 _ _ (mul_pos pn.cast_add_one_pos hx) hx ... = f ((↑pn + 1) * x + 1 * x) : by rw one_mul ... = f ((↑pn + 1 + 1) * x) : congr_arg f (add_mul (↑pn + 1) 1 x).symm ... = f (↑(pn + 2) * x) : by norm_cast }, have H4 : ∀ n : ℕ, 0 < n → (n : ℝ) ≤ f n, { intros n hn, have hf1 : 1 ≤ f 1, { have a_pos : (0 : ℝ) < a := rat.cast_pos.mpr (zero_lt_one.trans ha1), suffices : ↑a * 1 ≤ ↑a * f 1, from (mul_le_mul_left a_pos).mp this, calc ↑a * 1 = ↑a : mul_one ↑a ... = f a : hae.symm ... = f (a * 1) : by rw mul_one ... ≤ f a * f 1 : (H1 a 1) (zero_lt_one.trans ha1) zero_lt_one ... = ↑a * f 1 : by rw hae }, calc (n : ℝ) = (n : ℝ) * 1 : (mul_one _).symm ... ≤ (n : ℝ) * f 1 : mul_le_mul_of_nonneg_left hf1 (nat.cast_nonneg _) ... ≤ f (n * 1) : H3 1 zero_lt_one n hn ... = f n : by rw mul_one }, have H5 : ∀ x : ℚ, 1 < x → (x : ℝ) ≤ f x, { intros x hx, have hxnm1 : ∀ n : ℕ, 0 < n → (x : ℝ)^n - 1 < (f x)^n, { intros n hn, calc (x : ℝ)^n - 1 < f (x^n) : by exact_mod_cast fx_gt_xm1 (one_le_pow_of_one_le hx.le n) H1 H2 H4 ... ≤ (f x)^n : pow_f_le_f_pow hn hx H1 H4 }, have hx' : 1 < (x : ℝ) := by exact_mod_cast hx, have hxp : 0 < x := by positivity, exact le_of_all_pow_lt_succ' hx' (f_pos_of_pos hxp H1 H4) hxnm1 }, have h_f_commutes_with_pos_nat_mul : ∀ n : ℕ, 0 < n → ∀ x : ℚ, 0 < x → f (n * x) = n * f x, { intros n hn x hx, have h2 : f (n * x) ≤ n * f x, { cases n, { exfalso, exact nat.lt_asymm hn hn }, cases n, { simp only [one_mul, nat.cast_one] }, have hfneq : f (n.succ.succ) = n.succ.succ, { have := fixed_point_of_gt_1 (nat.one_lt_cast.mpr (nat.succ_lt_succ n.succ_pos)) H1 H2 H4 H5 ha1 hae, rwa (rat.cast_coe_nat n.succ.succ) at this }, rw ← hfneq, exact H1 (n.succ.succ : ℚ) x (nat.cast_pos.mpr hn) hx }, exact h2.antisymm (H3 x hx n hn) }, -- For the final calculation, we expand x as (2*x.num) / (2*x.denom), because -- we need the top of the fraction to be strictly greater than 1 in order -- to apply fixed_point_of_gt_1. intros x hx, let x2denom := 2 * x.denom, let x2num := 2 * x.num, have hx2pos := calc 0 < x.denom : x.pos ... < x.denom + x.denom : lt_add_of_pos_left x.denom x.pos ... = 2 * x.denom : by ring, have hxcnez : (x.denom : ℚ) ≠ (0 : ℚ) := ne_of_gt (nat.cast_pos.mpr x.pos), have hx2cnezr : (x2denom : ℝ) ≠ (0 : ℝ) := nat.cast_ne_zero.mpr (ne_of_gt hx2pos), have hrat_expand2 := calc x = x.num / x.denom : by exact_mod_cast rat.num_denom.symm ... = x2num / x2denom : by { field_simp [-rat.num_div_denom], linarith }, have h_denom_times_fx := calc (x2denom : ℝ) * f x = f (x2denom * x) : (h_f_commutes_with_pos_nat_mul x2denom hx2pos x hx).symm ... = f (x2denom * (x2num / x2denom)) : by rw hrat_expand2 ... = f x2num : by { congr, field_simp, ring }, have h_fx2num_fixed : f x2num = x2num, { have hx2num_gt_one : (1 : ℚ) < (2 * x.num : ℤ), { norm_cast, linarith [rat.num_pos_iff_pos.mpr hx] }, have hh := fixed_point_of_gt_1 hx2num_gt_one H1 H2 H4 H5 ha1 hae, rwa (rat.cast_coe_int x2num) at hh }, calc f x = f x * 1 : (mul_one (f x)).symm ... = f x * (x2denom / x2denom) : by rw ←(div_self hx2cnezr) ... = (f x * x2denom) / x2denom : mul_div_assoc' (f x) _ _ ... = (x2denom * f x) / x2denom : by rw mul_comm ... = f x2num / x2denom : by rw h_denom_times_fx ... = x2num / x2denom : by rw h_fx2num_fixed ... = (((x2num : ℚ) / (x2denom : ℚ) : ℚ) : ℝ) : by norm_cast ... = x : by rw ←hrat_expand2 end
6c9642659bf97732a25cc59e16ea73661a3fd2cb
d31b9f832ff922a603f76cf32e0f3aa822640508
/src/hott/types/arrow.lean
2259d3122dc80f1de4a1c5b95a4992a6249a26ef
[ "Apache-2.0" ]
permissive
javra/hott3
6e7a9e72a991a2fae32e5764982e521dca617b16
cd51f2ab2aa48c1246a188f9b525b30f76c3d651
refs/heads/master
1,585,819,679,148
1,531,232,382,000
1,536,682,965,000
154,294,022
0
0
Apache-2.0
1,540,284,376,000
1,540,284,375,000
null
UTF-8
Lean
false
false
5,891
lean
/- Copyright (c) 2014 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Floris van Doorn Ported from Coq HoTT Theorems about arrow types (function spaces) -/ import hott.types.pi universe u hott_theory namespace hott open eq equiv is_equiv funext pi is_trunc unit namespace pi variables {A : Type _} {A' : Type _} {B : Type _} {B' : Type _} {C : A → B → Type _} {D : A → Type _} {a a' a'' : A} {b b' b'' : B} {f g : A → B} {d : D a} {d' : D a'} -- all lemmas here are special cases of the ones for pi-types /- Functorial action -/ variables (f0 : A' → A) (f1 : B → B') @[hott] def arrow_functor : (A → B) → (A' → B') := pi_functor f0 (λa, f1) /- Equivalences -/ @[hott] def is_equiv_arrow_functor [H0 : is_equiv f0] [H1 : is_equiv f1] : is_equiv (arrow_functor f0 f1) := is_equiv_pi_functor f0 (λa, f1) @[hott] def arrow_equiv_arrow_rev (f0 : A' ≃ A) (f1 : B ≃ B') : (A → B) ≃ (A' → B') := equiv.mk _ (is_equiv_arrow_functor f0 f1) @[hott] def arrow_equiv_arrow (f0 : A ≃ A') (f1 : B ≃ B') : (A → B) ≃ (A' → B') := arrow_equiv_arrow_rev (equiv.symm f0) f1 variable (A) @[hott] def arrow_equiv_arrow_right (f1 : B ≃ B') : (A → B) ≃ (A → B') := arrow_equiv_arrow_rev equiv.rfl f1 variables {A} (B) @[hott] def arrow_equiv_arrow_left_rev (f0 : A' ≃ A) : (A → B) ≃ (A' → B) := arrow_equiv_arrow_rev f0 equiv.rfl @[hott] def arrow_equiv_arrow_left (f0 : A ≃ A') : (A → B) ≃ (A' → B) := arrow_equiv_arrow f0 equiv.rfl variables {B} @[hott] def arrow_equiv_arrow_right' (f1 : A → (B ≃ B')) : (A → B) ≃ (A → B') := pi_equiv_pi_right f1 /- Equivalence if one of the types is contractible -/ variables (A B) -- we prove this separately from pi_equiv_of_is_contr_left, -- because the underlying inverse function is simpler here (no transport needed) @[hott] def arrow_equiv_of_is_contr_left [H : is_contr A] : (A → B) ≃ B := begin fapply equiv.MK, { intro f, exact f (center A)}, { intros b a, exact b}, { intro b, reflexivity}, { intro f, apply eq_of_homotopy, intro a, exact ap f (is_prop.elim _ _)} end @[hott] def arrow_equiv_of_is_contr_right [H : is_contr B] : (A → B) ≃ unit := pi_equiv_of_is_contr_right _ /- Interaction with other type constructors -/ -- most of these are in the file of the other type constructor @[hott] def arrow_empty_left : (empty → B) ≃ unit := pi_empty_left _ @[hott] def arrow_unit_left : (unit → B) ≃ B := arrow_equiv_of_is_contr_left _ _ @[hott] def arrow_unit_right : (A → unit) ≃ unit := arrow_equiv_of_is_contr_right _ _ variables {A B} /- Transport -/ @[hott] def arrow_transport {B C : A → Type _} (p : a = a') (f : B a → C a) : (transport (λa, B a → C a) p f) ~ (λb, p ▸ f (p⁻¹ ▸ b)) := eq.rec_on p (λx, idp) /- Pathovers -/ @[hott] def arrow_pathover {B C : A → Type _} {f : B a → C a} {g : B a' → C a'} {p : a = a'} (r : Π(b : B a) (b' : B a') (q : b =[p] b'), f b =[p] g b') : f =[p; λa, B a → C a] g := begin induction p, apply pathover_idp_of_eq, apply eq_of_homotopy, hintro b, exact eq_of_pathover_idp (r b b idpo), end @[hott] def arrow_pathover_left {B C : A → Type _} {f : B a → C a} {g : B a' → C a'} {p : a = a'} (r : Π(b : B a), f b =[p] g (p ▸ b)) : f =[p; λa, B a → C a] g := begin induction p, apply pathover_idp_of_eq, apply eq_of_homotopy, hintro b, exact eq_of_pathover_idp (r b), end @[hott] def arrow_pathover_right {B C : A → Type _} {f : B a → C a} {g : B a' → C a'} {p : a = a'} (r : Π(b' : B a'), f (p⁻¹ ▸ b') =[p] g b') : f =[p; λa, B a → C a] g := begin induction p, apply pathover_idp_of_eq, apply eq_of_homotopy, hintro b, exact eq_of_pathover_idp (r b), end @[hott] def arrow_pathover_constant_left {B : Type _} {C : A → Type _} {f : B → C a} {g : B → C a'} {p : a = a'} (r : Π(b : B), f b =[p] g b) : f =[p; λa, B → C a] g := pi_pathover_constant r @[hott] def arrow_pathover_constant_right' {B : A → Type _} {C : Type _} {f : B a → C} {g : B a' → C} {p : a = a'} (r : Π⦃b : B a⦄ ⦃b' : B a'⦄ (q : b =[p] b'), f b = g b') : f =[p; λa, B a → C] g := arrow_pathover (λb b' q, pathover_of_eq p (r q)) @[hott] def arrow_pathover_constant_right {B : A → Type _} {C : Type _} {f : B a → C} {g : B a' → C} {p : a = a'} (r : Π(b : B a), f b = g (p ▸ b)) : f =[p; λa, B a → C] g := arrow_pathover_left (λb, pathover_of_eq p (r b)) @[hott] def arrow_pathover_constant_right_rev {A : Type _} {B : A → Type _} {C : Type _} {a a' : A} {f : B a → C} {g : B a' → C} {p : a = a'} (r : Π(b : B a'), f (p⁻¹ ▸ b) = g b) : f =[p; λa, B a → C] g := arrow_pathover_right (λb, pathover_of_eq p (r b)) /- a @[hott] lemma used for the flattening lemma, and is also used in the colimits file -/ @[hott] def apo11_arrow_pathover_constant_right {f : D a → A'} {g : D a' → A'} {p : a = a'} {q : d =[p; D] d'} (r : Π(d : D a), f d = g (p ▸ d)) : apo11_constant_right (arrow_pathover_constant_right r) q = r d ⬝ ap g (tr_eq_of_pathover q) := begin induction q, eapply homotopy.rec_on r, clear r, intro r, dsimp at r, induction r, dsimp [apd10, arrow_pathover_constant_right, arrow_pathover_left, pathover_of_eq, eq_of_pathover_idp, tr_eq_of_pathover], rwr [eq_of_homotopy_idp] end /- The fact that the arrow type preserves truncation level is a direct consequence of the fact that pi's preserve truncation level -/ @[hott] def is_trunc_arrow (B : Type _) (n : ℕ₋₂) [H : is_trunc n B] : is_trunc n (A → B) := by apply_instance end pi end hott
d78bc8bb7775905a2b70926162c8faa532a74ed9
8e6cad62ec62c6c348e5faaa3c3f2079012bdd69
/src/topology/local_homeomorph.lean
8fa8c39c829baa3d3acaba5749c14905cf92c097
[ "Apache-2.0" ]
permissive
benjamindavidson/mathlib
8cc81c865aa8e7cf4462245f58d35ae9a56b150d
fad44b9f670670d87c8e25ff9cdf63af87ad731e
refs/heads/master
1,679,545,578,362
1,615,343,014,000
1,615,343,014,000
312,926,983
0
0
Apache-2.0
1,615,360,301,000
1,605,399,418,000
Lean
UTF-8
Lean
false
false
38,479
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 data.equiv.local_equiv import topology.opens /-! # Local homeomorphisms This file defines homeomorphisms between open subsets of topological spaces. An element `e` of `local_homeomorph α β` is an extension of `local_equiv α β`, i.e., it is a pair of functions `e.to_fun` and `e.inv_fun`, inverse of each other on the sets `e.source` and `e.target`. Additionally, we require that these sets are open, and that the functions are continuous on them. Equivalently, they are homeomorphisms there. As in equivs, we register a coercion to functions, and we use `e x` and `e.symm x` throughout instead of `e.to_fun x` and `e.inv_fun x`. ## Main definitions `homeomorph.to_local_homeomorph`: associating a local homeomorphism to a homeomorphism, with source = target = univ `local_homeomorph.symm` : the inverse of a local homeomorphism `local_homeomorph.trans` : the composition of two local homeomorphisms `local_homeomorph.refl` : the identity local homeomorphism `local_homeomorph.of_set`: the identity on a set `s` `eq_on_source` : equivalence relation describing the "right" notion of equality for local homeomorphisms ## Implementation notes Most statements are copied from their local_equiv versions, although some care is required especially when restricting to subsets, as these should be open subsets. For design notes, see `local_equiv.lean`. ### Local coding conventions If a lemma deals with the intersection of a set with either source or target of a `local_equiv`, then it should use `e.source ∩ s` or `e.target ∩ t`, not `s ∩ e.source` or `t ∩ e.target`. -/ open function set filter open_locale topological_space variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} [topological_space α] [topological_space β] [topological_space γ] [topological_space δ] /-- local homeomorphisms, defined on open subsets of the space -/ @[nolint has_inhabited_instance] structure local_homeomorph (α : Type*) (β : Type*) [topological_space α] [topological_space β] extends local_equiv α β := (open_source : is_open source) (open_target : is_open target) (continuous_to_fun : continuous_on to_fun source) (continuous_inv_fun : continuous_on inv_fun target) /-- A homeomorphism induces a local homeomorphism on the whole space -/ def homeomorph.to_local_homeomorph (e : α ≃ₜ β) : local_homeomorph α β := { open_source := is_open_univ, open_target := is_open_univ, continuous_to_fun := by { erw ← continuous_iff_continuous_on_univ, exact e.continuous_to_fun }, continuous_inv_fun := by { erw ← continuous_iff_continuous_on_univ, exact e.continuous_inv_fun }, ..e.to_equiv.to_local_equiv } namespace local_homeomorph variables (e : local_homeomorph α β) (e' : local_homeomorph β γ) instance : has_coe_to_fun (local_homeomorph α β) := ⟨_, λ e, e.to_local_equiv.to_fun⟩ /-- The inverse of a local homeomorphism -/ protected def symm : local_homeomorph β α := { open_source := e.open_target, open_target := e.open_source, continuous_to_fun := e.continuous_inv_fun, continuous_inv_fun := e.continuous_to_fun, ..e.to_local_equiv.symm } protected lemma continuous_on : continuous_on e e.source := e.continuous_to_fun lemma continuous_on_symm : continuous_on e.symm e.target := e.continuous_inv_fun @[simp, mfld_simps] lemma mk_coe (e : local_equiv α β) (a b c d) : (local_homeomorph.mk e a b c d : α → β) = e := rfl @[simp, mfld_simps] lemma mk_coe_symm (e : local_equiv α β) (a b c d) : ((local_homeomorph.mk e a b c d).symm : β → α) = e.symm := rfl /- Register a few simp lemmas to make sure that `simp` puts the application of a local homeomorphism in its normal form, i.e., in terms of its coercion to a function. -/ @[simp, mfld_simps] lemma to_fun_eq_coe (e : local_homeomorph α β) : e.to_fun = e := rfl @[simp, mfld_simps] lemma inv_fun_eq_coe (e : local_homeomorph α β) : e.inv_fun = e.symm := rfl @[simp, mfld_simps] lemma coe_coe : (e.to_local_equiv : α → β) = e := rfl @[simp, mfld_simps] lemma coe_coe_symm : (e.to_local_equiv.symm : β → α) = e.symm := rfl @[simp, mfld_simps] lemma map_source {x : α} (h : x ∈ e.source) : e x ∈ e.target := e.map_source' h @[simp, mfld_simps] lemma map_target {x : β} (h : x ∈ e.target) : e.symm x ∈ e.source := e.map_target' h @[simp, mfld_simps] lemma left_inv {x : α} (h : x ∈ e.source) : e.symm (e x) = x := e.left_inv' h @[simp, mfld_simps] lemma right_inv {x : β} (h : x ∈ e.target) : e (e.symm x) = x := e.right_inv' h protected lemma maps_to : maps_to e e.source e.target := λ x, e.map_source protected lemma symm_maps_to : maps_to e.symm e.target e.source := e.symm.maps_to protected lemma left_inv_on : left_inv_on e.symm e e.source := λ x, e.left_inv protected lemma right_inv_on : right_inv_on e.symm e e.target := λ x, e.right_inv protected lemma inv_on : inv_on e.symm e e.source e.target := ⟨e.left_inv_on, e.right_inv_on⟩ protected lemma inj_on : inj_on e e.source := e.left_inv_on.inj_on protected lemma bij_on : bij_on e e.source e.target := e.inv_on.bij_on e.maps_to e.symm_maps_to protected lemma surj_on : surj_on e e.source e.target := e.bij_on.surj_on lemma source_preimage_target : e.source ⊆ e ⁻¹' e.target := λ _ h, map_source e h lemma eq_of_local_equiv_eq {e e' : local_homeomorph α β} (h : e.to_local_equiv = e'.to_local_equiv) : e = e' := by { cases e, cases e', cases h, refl } lemma eventually_left_inverse (e : local_homeomorph α β) {x} (hx : x ∈ e.source) : ∀ᶠ y in 𝓝 x, e.symm (e y) = y := (e.open_source.eventually_mem hx).mono e.left_inv' lemma eventually_left_inverse' (e : local_homeomorph α β) {x} (hx : x ∈ e.target) : ∀ᶠ y in 𝓝 (e.symm x), e.symm (e y) = y := e.eventually_left_inverse (e.map_target hx) lemma eventually_right_inverse (e : local_homeomorph α β) {x} (hx : x ∈ e.target) : ∀ᶠ y in 𝓝 x, e (e.symm y) = y := (e.open_target.eventually_mem hx).mono e.right_inv' lemma eventually_right_inverse' (e : local_homeomorph α β) {x} (hx : x ∈ e.source) : ∀ᶠ y in 𝓝 (e x), e (e.symm y) = y := e.eventually_right_inverse (e.map_source hx) lemma eventually_ne_nhds_within (e : local_homeomorph α β) {x} (hx : x ∈ e.source) : ∀ᶠ x' in 𝓝[{x}ᶜ] x, e x' ≠ e x := eventually_nhds_within_iff.2 $ (e.eventually_left_inverse hx).mono $ λ x' hx', mt $ λ h, by rw [mem_singleton_iff, ← e.left_inv hx, ← h, hx'] lemma nhds_within_source_inter {x} (hx : x ∈ e.source) (s : set α) : 𝓝[e.source ∩ s] x = 𝓝[s] x := nhds_within_inter_of_mem (mem_nhds_within_of_mem_nhds $ mem_nhds_sets e.open_source hx) lemma nhds_within_target_inter {x} (hx : x ∈ e.target) (s : set β) : 𝓝[e.target ∩ s] x = 𝓝[s] x := e.symm.nhds_within_source_inter hx s lemma image_eq_target_inter_inv_preimage {s : set α} (h : s ⊆ e.source) : e '' s = e.target ∩ e.symm ⁻¹' s := e.to_local_equiv.image_eq_target_inter_inv_preimage h lemma image_source_inter_eq' (s : set α) : e '' (e.source ∩ s) = e.target ∩ e.symm ⁻¹' s := e.to_local_equiv.image_source_inter_eq' s lemma image_source_inter_eq (s : set α) : e '' (e.source ∩ s) = e.target ∩ e.symm ⁻¹' (e.source ∩ s) := e.to_local_equiv.image_source_inter_eq s lemma symm_image_eq_source_inter_preimage {s : set β} (h : s ⊆ e.target) : e.symm '' s = e.source ∩ e ⁻¹' s := e.symm.image_eq_target_inter_inv_preimage h lemma symm_image_target_inter_eq (s : set β) : e.symm '' (e.target ∩ s) = e.source ∩ e ⁻¹' (e.target ∩ s) := e.symm.image_source_inter_eq _ lemma source_inter_preimage_inv_preimage (s : set α) : e.source ∩ e ⁻¹' (e.symm ⁻¹' s) = e.source ∩ s := e.to_local_equiv.source_inter_preimage_inv_preimage s lemma target_inter_inv_preimage_preimage (s : set β) : e.target ∩ e.symm ⁻¹' (e ⁻¹' s) = e.target ∩ s := e.symm.source_inter_preimage_inv_preimage _ /-- Two local homeomorphisms are equal when they have equal `to_fun`, `inv_fun` and `source`. It is not sufficient to have equal `to_fun` and `source`, as this only determines `inv_fun` on the target. This would only be true for a weaker notion of equality, arguably the right one, called `eq_on_source`. -/ @[ext] protected lemma ext (e' : local_homeomorph α β) (h : ∀x, e x = e' x) (hinv : ∀x, e.symm x = e'.symm x) (hs : e.source = e'.source) : e = e' := eq_of_local_equiv_eq (local_equiv.ext h hinv hs) @[simp, mfld_simps] lemma symm_to_local_equiv : e.symm.to_local_equiv = e.to_local_equiv.symm := rfl -- The following lemmas are already simp via local_equiv lemma symm_source : e.symm.source = e.target := rfl lemma symm_target : e.symm.target = e.source := rfl @[simp, mfld_simps] lemma symm_symm : e.symm.symm = e := eq_of_local_equiv_eq $ by simp /-- A local homeomorphism is continuous at any point of its source -/ protected lemma continuous_at {x : α} (h : x ∈ e.source) : continuous_at e x := (e.continuous_on x h).continuous_at (mem_nhds_sets e.open_source h) /-- A local homeomorphism inverse is continuous at any point of its target -/ lemma continuous_at_symm {x : β} (h : x ∈ e.target) : continuous_at e.symm x := e.symm.continuous_at h lemma tendsto_symm (e : local_homeomorph α β) {x} (hx : x ∈ e.source) : tendsto e.symm (𝓝 (e x)) (𝓝 x) := by simpa only [continuous_at, e.left_inv hx] using e.continuous_at_symm (e.map_source hx) lemma map_nhds_eq (e : local_homeomorph α β) {x} (hx : x ∈ e.source) : map e (𝓝 x) = 𝓝 (e x) := le_antisymm (e.continuous_at hx) $ le_map_of_right_inverse (e.eventually_right_inverse' hx) (e.tendsto_symm hx) lemma symm_map_nhds_eq (e : local_homeomorph α β) {x} (hx : x ∈ e.source) : map e.symm (𝓝 (e x)) = 𝓝 x := (e.symm.map_nhds_eq $ e.map_source hx).trans $ by rw e.left_inv hx lemma image_mem_nhds (e : local_homeomorph α β) {x} (hx : x ∈ e.source) {s : set α} (hs : s ∈ 𝓝 x) : e '' s ∈ 𝓝 (e x) := e.map_nhds_eq hx ▸ filter.image_mem_map hs lemma map_nhds_within_eq (e : local_homeomorph α β) {x} (hx : x ∈ e.source) (s : set α) : map e (𝓝[s] x) = 𝓝[e '' (e.source ∩ s)] (e x) := calc map e (𝓝[s] x) = map e (𝓝[e.source ∩ s] x) : congr_arg (map e) (e.nhds_within_source_inter hx _).symm ... = 𝓝[e '' (e.source ∩ s)] (e x) : (e.left_inv_on.mono $ inter_subset_left _ _).map_nhds_within_eq (e.left_inv hx) (e.continuous_at_symm (e.map_source hx)).continuous_within_at (e.continuous_at hx).continuous_within_at lemma map_nhds_within_preimage_eq (e : local_homeomorph α β) {x} (hx : x ∈ e.source) (s : set β) : map e (𝓝[e ⁻¹' s] x) = 𝓝[s] (e x) := by rw [e.map_nhds_within_eq hx, e.image_source_inter_eq', e.target_inter_inv_preimage_preimage, e.nhds_within_target_inter (e.map_source hx)] /-- Preimage of interior or interior of preimage coincide for local homeomorphisms, when restricted to the source. -/ lemma preimage_interior (s : set β) : e.source ∩ e ⁻¹' (interior s) = e.source ∩ interior (e ⁻¹' s) := begin refine set.ext (λ x, and.congr_right_iff.2 $ λ hx, _), rw [mem_interior_iff_mem_nhds, mem_preimage, mem_interior_iff_mem_nhds, ← e.map_nhds_eq hx, mem_map, preimage] end lemma preimage_closure (s : set β) : e.source ∩ e ⁻¹' (closure s) = e.source ∩ closure (e ⁻¹' s) := begin refine set.ext (λ x, and.congr_right_iff.2 $ λ hx, _), rw [mem_closure_iff_nhds_within_ne_bot, mem_preimage, mem_closure_iff_nhds_within_ne_bot, ← map_ne_bot_iff e.symm, e.symm.map_nhds_within_eq (e.map_source hx), e.left_inv hx, e.symm.image_source_inter_eq', symm_symm, nhds_within_inter_of_mem], exact mem_nhds_within_of_mem_nhds (mem_nhds_sets e.open_source hx) end lemma preimage_frontier (s : set β) : e.source ∩ e ⁻¹' (frontier s) = e.source ∩ frontier (e ⁻¹' s) := begin rw [frontier_eq_closure_inter_closure, frontier_eq_closure_inter_closure], have := @preimage_compl _ _ e s, convert congr_arg2 (∩) (e.preimage_closure s) (e.preimage_closure sᶜ) using 1; mfld_set_tac end lemma preimage_open_of_open {s : set β} (hs : is_open s) : is_open (e.source ∩ e ⁻¹' s) := e.continuous_on.preimage_open_of_open e.open_source hs lemma preimage_open_of_open_symm {s : set α} (hs : is_open s) : is_open (e.target ∩ e.symm ⁻¹' s) := e.symm.continuous_on.preimage_open_of_open e.open_target hs /-- The image of an open set in the source is open. -/ lemma image_open_of_open {s : set α} (hs : is_open s) (h : s ⊆ e.source) : is_open (e '' s) := begin have : e '' s = e.target ∩ e.symm ⁻¹' s := e.to_local_equiv.image_eq_target_inter_inv_preimage h, rw this, exact e.continuous_on_symm.preimage_open_of_open e.open_target hs end /-- The image of the restriction of an open set to the source is open. -/ lemma image_open_of_open' {s : set α} (hs : is_open s) : is_open (e '' (e.source ∩ s)) := image_open_of_open _ (is_open_inter e.open_source hs) (inter_subset_left _ _) /-- A `local_equiv` with continuous open forward map and an open source is a `local_homeomorph`. -/ def of_continuous_open_restrict (e : local_equiv α β) (hc : continuous_on e e.source) (ho : is_open_map (e.source.restrict e)) (hs : is_open e.source) : local_homeomorph α β := { to_local_equiv := e, open_source := hs, open_target := by simpa only [range_restrict, e.image_source_eq_target] using ho.is_open_range, continuous_to_fun := hc, continuous_inv_fun := e.image_source_eq_target ▸ ho.continuous_on_image_of_left_inv_on e.left_inv_on } /-- A `local_equiv` with continuous open forward map and an open source is a `local_homeomorph`. -/ def of_continuous_open (e : local_equiv α β) (hc : continuous_on e e.source) (ho : is_open_map e) (hs : is_open e.source) : local_homeomorph α β := of_continuous_open_restrict e hc (ho.restrict hs) hs /-- Restricting a local homeomorphism `e` to `e.source ∩ s` when `s` is open. This is sometimes hard to use because of the openness assumption, but it has the advantage that when it can be used then its local_equiv is defeq to local_equiv.restr -/ protected def restr_open (s : set α) (hs : is_open s) : local_homeomorph α β := { open_source := is_open_inter e.open_source hs, open_target := (continuous_on_open_iff e.open_target).1 e.continuous_inv_fun s hs, continuous_to_fun := e.continuous_to_fun.mono (inter_subset_left _ _), continuous_inv_fun := e.continuous_inv_fun.mono (inter_subset_left _ _), ..e.to_local_equiv.restr s} @[simp, mfld_simps] lemma restr_open_to_local_equiv (s : set α) (hs : is_open s) : (e.restr_open s hs).to_local_equiv = e.to_local_equiv.restr s := rfl -- Already simp via local_equiv lemma restr_open_source (s : set α) (hs : is_open s) : (e.restr_open s hs).source = e.source ∩ s := rfl /-- Restricting a local homeomorphism `e` to `e.source ∩ interior s`. We use the interior to make sure that the restriction is well defined whatever the set s, since local homeomorphisms are by definition defined on open sets. In applications where `s` is open, this coincides with the restriction of local equivalences -/ protected def restr (s : set α) : local_homeomorph α β := e.restr_open (interior s) is_open_interior @[simp, mfld_simps] lemma restr_to_local_equiv (s : set α) : (e.restr s).to_local_equiv = (e.to_local_equiv).restr (interior s) := rfl @[simp, mfld_simps] lemma restr_coe (s : set α) : (e.restr s : α → β) = e := rfl @[simp, mfld_simps] lemma restr_coe_symm (s : set α) : ((e.restr s).symm : β → α) = e.symm := rfl lemma restr_source (s : set α) : (e.restr s).source = e.source ∩ interior s := rfl lemma restr_target (s : set α) : (e.restr s).target = e.target ∩ e.symm ⁻¹' (interior s) := rfl lemma restr_source' (s : set α) (hs : is_open s) : (e.restr s).source = e.source ∩ s := by rw [e.restr_source, hs.interior_eq] lemma restr_to_local_equiv' (s : set α) (hs : is_open s): (e.restr s).to_local_equiv = e.to_local_equiv.restr s := by rw [e.restr_to_local_equiv, hs.interior_eq] lemma restr_eq_of_source_subset {e : local_homeomorph α β} {s : set α} (h : e.source ⊆ s) : e.restr s = e := begin apply eq_of_local_equiv_eq, rw restr_to_local_equiv, apply local_equiv.restr_eq_of_source_subset, have := interior_mono h, rwa e.open_source.interior_eq at this end @[simp, mfld_simps] lemma restr_univ {e : local_homeomorph α β} : e.restr univ = e := restr_eq_of_source_subset (subset_univ _) lemma restr_source_inter (s : set α) : e.restr (e.source ∩ s) = e.restr s := begin refine local_homeomorph.ext _ _ (λx, rfl) (λx, rfl) _, simp [e.open_source.interior_eq], rw [← inter_assoc, inter_self] end /-- The identity on the whole space as a local homeomorphism. -/ protected def refl (α : Type*) [topological_space α] : local_homeomorph α α := (homeomorph.refl α).to_local_homeomorph @[simp, mfld_simps] lemma refl_local_equiv : (local_homeomorph.refl α).to_local_equiv = local_equiv.refl α := rfl lemma refl_source : (local_homeomorph.refl α).source = univ := rfl lemma refl_target : (local_homeomorph.refl α).target = univ := rfl @[simp, mfld_simps] lemma refl_symm : (local_homeomorph.refl α).symm = local_homeomorph.refl α := rfl @[simp, mfld_simps] lemma refl_coe : (local_homeomorph.refl α : α → α) = id := rfl section variables {s : set α} (hs : is_open s) /-- The identity local equiv on a set `s` -/ def of_set (s : set α) (hs : is_open s) : local_homeomorph α α := { open_source := hs, open_target := hs, continuous_to_fun := continuous_id.continuous_on, continuous_inv_fun := continuous_id.continuous_on, ..local_equiv.of_set s } @[simp, mfld_simps] lemma of_set_to_local_equiv : (of_set s hs).to_local_equiv = local_equiv.of_set s := rfl lemma of_set_source : (of_set s hs).source = s := rfl lemma of_set_target : (of_set s hs).target = s := rfl @[simp, mfld_simps] lemma of_set_coe : (of_set s hs : α → α) = id := rfl @[simp, mfld_simps] lemma of_set_symm : (of_set s hs).symm = of_set s hs := rfl @[simp, mfld_simps] lemma of_set_univ_eq_refl : of_set univ is_open_univ = local_homeomorph.refl α := by ext; simp end /-- Composition of two local homeomorphisms when the target of the first and the source of the second coincide. -/ protected def trans' (h : e.target = e'.source) : local_homeomorph α γ := { open_source := e.open_source, open_target := e'.open_target, continuous_to_fun := begin apply continuous_on.comp e'.continuous_to_fun e.continuous_to_fun, rw ← h, exact e.to_local_equiv.source_subset_preimage_target end, continuous_inv_fun := begin apply continuous_on.comp e.continuous_inv_fun e'.continuous_inv_fun, rw h, exact e'.to_local_equiv.target_subset_preimage_source end, ..local_equiv.trans' e.to_local_equiv e'.to_local_equiv h } /-- Composing two local homeomorphisms, by restricting to the maximal domain where their composition is well defined. -/ protected def trans : local_homeomorph α γ := local_homeomorph.trans' (e.symm.restr_open e'.source e'.open_source).symm (e'.restr_open e.target e.open_target) (by simp [inter_comm]) @[simp, mfld_simps] lemma trans_to_local_equiv : (e.trans e').to_local_equiv = e.to_local_equiv.trans e'.to_local_equiv := rfl @[simp, mfld_simps] lemma coe_trans : (e.trans e' : α → γ) = e' ∘ e := rfl @[simp, mfld_simps] lemma coe_trans_symm : ((e.trans e').symm : γ → α) = e.symm ∘ e'.symm := rfl lemma trans_symm_eq_symm_trans_symm : (e.trans e').symm = e'.symm.trans e.symm := by cases e; cases e'; refl /- This could be considered as a simp lemma, but there are many situations where it makes something simple into something more complicated. -/ lemma trans_source : (e.trans e').source = e.source ∩ e ⁻¹' e'.source := local_equiv.trans_source e.to_local_equiv e'.to_local_equiv lemma trans_source' : (e.trans e').source = e.source ∩ e ⁻¹' (e.target ∩ e'.source) := local_equiv.trans_source' e.to_local_equiv e'.to_local_equiv lemma trans_source'' : (e.trans e').source = e.symm '' (e.target ∩ e'.source) := local_equiv.trans_source'' e.to_local_equiv e'.to_local_equiv lemma image_trans_source : e '' (e.trans e').source = e.target ∩ e'.source := local_equiv.image_trans_source e.to_local_equiv e'.to_local_equiv lemma trans_target : (e.trans e').target = e'.target ∩ e'.symm ⁻¹' e.target := rfl lemma trans_target' : (e.trans e').target = e'.target ∩ e'.symm ⁻¹' (e'.source ∩ e.target) := trans_source' e'.symm e.symm lemma trans_target'' : (e.trans e').target = e' '' (e'.source ∩ e.target) := trans_source'' e'.symm e.symm lemma inv_image_trans_target : e'.symm '' (e.trans e').target = e'.source ∩ e.target := image_trans_source e'.symm e.symm lemma trans_assoc (e'' : local_homeomorph γ δ) : (e.trans e').trans e'' = e.trans (e'.trans e'') := eq_of_local_equiv_eq $ local_equiv.trans_assoc e.to_local_equiv e'.to_local_equiv e''.to_local_equiv @[simp, mfld_simps] lemma trans_refl : e.trans (local_homeomorph.refl β) = e := eq_of_local_equiv_eq $ local_equiv.trans_refl e.to_local_equiv @[simp, mfld_simps] lemma refl_trans : (local_homeomorph.refl α).trans e = e := eq_of_local_equiv_eq $ local_equiv.refl_trans e.to_local_equiv lemma trans_of_set {s : set β} (hs : is_open s) : e.trans (of_set s hs) = e.restr (e ⁻¹' s) := local_homeomorph.ext _ _ (λx, rfl) (λx, rfl) $ by simp [local_equiv.trans_source, (e.preimage_interior _).symm, hs.interior_eq] lemma trans_of_set' {s : set β} (hs : is_open s) : e.trans (of_set s hs) = e.restr (e.source ∩ e ⁻¹' s) := by rw [trans_of_set, restr_source_inter] lemma of_set_trans {s : set α} (hs : is_open s) : (of_set s hs).trans e = e.restr s := local_homeomorph.ext _ _ (λx, rfl) (λx, rfl) $ by simp [local_equiv.trans_source, hs.interior_eq, inter_comm] lemma of_set_trans' {s : set α} (hs : is_open s) : (of_set s hs).trans e = e.restr (e.source ∩ s) := by rw [of_set_trans, restr_source_inter] @[simp, mfld_simps] lemma of_set_trans_of_set {s : set α} (hs : is_open s) {s' : set α} (hs' : is_open s') : (of_set s hs).trans (of_set s' hs') = of_set (s ∩ s') (is_open_inter hs hs') := begin rw (of_set s hs).trans_of_set hs', ext; simp [hs'.interior_eq] end lemma restr_trans (s : set α) : (e.restr s).trans e' = (e.trans e').restr s := eq_of_local_equiv_eq $ local_equiv.restr_trans e.to_local_equiv e'.to_local_equiv (interior s) /-- `eq_on_source e e'` means that `e` and `e'` have the same source, and coincide there. They should really be considered the same local equiv. -/ def eq_on_source (e e' : local_homeomorph α β) : Prop := e.source = e'.source ∧ (eq_on e e' e.source) lemma eq_on_source_iff (e e' : local_homeomorph α β) : eq_on_source e e' ↔ local_equiv.eq_on_source e.to_local_equiv e'.to_local_equiv := iff.rfl /-- `eq_on_source` is an equivalence relation -/ instance : setoid (local_homeomorph α β) := { r := eq_on_source, iseqv := ⟨ λe, (@local_equiv.eq_on_source_setoid α β).iseqv.1 e.to_local_equiv, λe e' h, (@local_equiv.eq_on_source_setoid α β).iseqv.2.1 ((eq_on_source_iff e e').1 h), λe e' e'' h h', (@local_equiv.eq_on_source_setoid α β).iseqv.2.2 ((eq_on_source_iff e e').1 h) ((eq_on_source_iff e' e'').1 h')⟩ } lemma eq_on_source_refl : e ≈ e := setoid.refl _ /-- If two local homeomorphisms are equivalent, so are their inverses -/ lemma eq_on_source.symm' {e e' : local_homeomorph α β} (h : e ≈ e') : e.symm ≈ e'.symm := local_equiv.eq_on_source.symm' h /-- Two equivalent local homeomorphisms have the same source -/ lemma eq_on_source.source_eq {e e' : local_homeomorph α β} (h : e ≈ e') : e.source = e'.source := h.1 /-- Two equivalent local homeomorphisms have the same target -/ lemma eq_on_source.target_eq {e e' : local_homeomorph α β} (h : e ≈ e') : e.target = e'.target := h.symm'.1 /-- Two equivalent local homeomorphisms have coinciding `to_fun` on the source -/ lemma eq_on_source.eq_on {e e' : local_homeomorph α β} (h : e ≈ e') : eq_on e e' e.source := h.2 /-- Two equivalent local homeomorphisms have coinciding `inv_fun` on the target -/ lemma eq_on_source.symm_eq_on_target {e e' : local_homeomorph α β} (h : e ≈ e') : eq_on e.symm e'.symm e.target := h.symm'.2 /-- Composition of local homeomorphisms respects equivalence -/ lemma eq_on_source.trans' {e e' : local_homeomorph α β} {f f' : local_homeomorph β γ} (he : e ≈ e') (hf : f ≈ f') : e.trans f ≈ e'.trans f' := local_equiv.eq_on_source.trans' he hf /-- Restriction of local homeomorphisms respects equivalence -/ lemma eq_on_source.restr {e e' : local_homeomorph α β} (he : e ≈ e') (s : set α) : e.restr s ≈ e'.restr s := local_equiv.eq_on_source.restr he _ /-- Composition of a local homeomorphism and its inverse is equivalent to the restriction of the identity to the source -/ lemma trans_self_symm : e.trans e.symm ≈ local_homeomorph.of_set e.source e.open_source := local_equiv.trans_self_symm _ lemma trans_symm_self : e.symm.trans e ≈ local_homeomorph.of_set e.target e.open_target := e.symm.trans_self_symm lemma eq_of_eq_on_source_univ {e e' : local_homeomorph α β} (h : e ≈ e') (s : e.source = univ) (t : e.target = univ) : e = e' := eq_of_local_equiv_eq $ local_equiv.eq_of_eq_on_source_univ _ _ h s t section prod /-- The product of two local homeomorphisms, as a local homeomorphism on the product space. -/ def prod (e : local_homeomorph α β) (e' : local_homeomorph γ δ) : local_homeomorph (α × γ) (β × δ) := { open_source := e.open_source.prod e'.open_source, open_target := e.open_target.prod e'.open_target, continuous_to_fun := continuous_on.prod (e.continuous_to_fun.comp continuous_fst.continuous_on (prod_subset_preimage_fst _ _)) (e'.continuous_to_fun.comp continuous_snd.continuous_on (prod_subset_preimage_snd _ _)), continuous_inv_fun := continuous_on.prod (e.continuous_inv_fun.comp continuous_fst.continuous_on (prod_subset_preimage_fst _ _)) (e'.continuous_inv_fun.comp continuous_snd.continuous_on (prod_subset_preimage_snd _ _)), ..e.to_local_equiv.prod e'.to_local_equiv } @[simp, mfld_simps] lemma prod_to_local_equiv (e : local_homeomorph α β) (e' : local_homeomorph γ δ) : (e.prod e').to_local_equiv = e.to_local_equiv.prod e'.to_local_equiv := rfl lemma prod_source (e : local_homeomorph α β) (e' : local_homeomorph γ δ) : (e.prod e').source = set.prod e.source e'.source := rfl lemma prod_target (e : local_homeomorph α β) (e' : local_homeomorph γ δ) : (e.prod e').target = set.prod e.target e'.target := rfl @[simp, mfld_simps] lemma prod_coe (e : local_homeomorph α β) (e' : local_homeomorph γ δ) : (e.prod e' : α × γ → β × δ) = λp, (e p.1, e' p.2) := rfl lemma prod_coe_symm (e : local_homeomorph α β) (e' : local_homeomorph γ δ) : ((e.prod e').symm : β × δ → α × γ) = λp, (e.symm p.1, e'.symm p.2) := rfl @[simp, mfld_simps] lemma prod_symm (e : local_homeomorph α β) (e' : local_homeomorph γ δ) : (e.prod e').symm = (e.symm.prod e'.symm) := rfl @[simp, mfld_simps] lemma prod_trans {η : Type*} {ε : Type*} [topological_space η] [topological_space ε] (e : local_homeomorph α β) (f : local_homeomorph β γ) (e' : local_homeomorph δ η) (f' : local_homeomorph η ε) : (e.prod e').trans (f.prod f') = (e.trans f).prod (e'.trans f') := local_homeomorph.eq_of_local_equiv_eq $ by dsimp only [trans_to_local_equiv, prod_to_local_equiv]; apply local_equiv.prod_trans end prod section continuity /-- Continuity within a set at a point can be read under right composition with a local homeomorphism, if the point is in its target -/ lemma continuous_within_at_iff_continuous_within_at_comp_right {f : β → γ} {s : set β} {x : β} (h : x ∈ e.target) : continuous_within_at f s x ↔ continuous_within_at (f ∘ e) (e ⁻¹' s) (e.symm x) := by simp_rw [continuous_within_at, ← @tendsto_map'_iff _ _ _ _ e, e.map_nhds_within_preimage_eq (e.map_target h), (∘), e.right_inv h] /-- Continuity at a point can be read under right composition with a local homeomorphism, if the point is in its target -/ lemma continuous_at_iff_continuous_at_comp_right {f : β → γ} {x : β} (h : x ∈ e.target) : continuous_at f x ↔ continuous_at (f ∘ e) (e.symm x) := by rw [← continuous_within_at_univ, e.continuous_within_at_iff_continuous_within_at_comp_right h, preimage_univ, continuous_within_at_univ] /-- A function is continuous on a set if and only if its composition with a local homeomorphism on the right is continuous on the corresponding set. -/ lemma continuous_on_iff_continuous_on_comp_right {f : β → γ} {s : set β} (h : s ⊆ e.target) : continuous_on f s ↔ continuous_on (f ∘ e) (e.source ∩ e ⁻¹' s) := begin simp only [← e.symm_image_eq_source_inter_preimage h, continuous_on, ball_image_iff], refine forall_congr (λ x, forall_congr $ λ hx, _), rw [e.continuous_within_at_iff_continuous_within_at_comp_right (h hx), e.symm_image_eq_source_inter_preimage h, inter_comm, continuous_within_at_inter], exact mem_nhds_sets e.open_source (e.map_target (h hx)) end /-- Continuity within a set at a point can be read under left composition with a local homeomorphism if a neighborhood of the initial point is sent to the source of the local homeomorphism-/ lemma continuous_within_at_iff_continuous_within_at_comp_left {f : γ → α} {s : set γ} {x : γ} (hx : f x ∈ e.source) (h : f ⁻¹' e.source ∈ 𝓝[s] x) : continuous_within_at f s x ↔ continuous_within_at (e ∘ f) s x := begin refine ⟨(e.continuous_at hx).tendsto.comp, λ fe_cont, _⟩, rw [← continuous_within_at_inter' h] at fe_cont ⊢, have : continuous_within_at (e.symm ∘ (e ∘ f)) (s ∩ f ⁻¹' e.source) x, { have : continuous_within_at e.symm univ (e (f x)) := (e.continuous_at_symm (e.map_source hx)).continuous_within_at, exact continuous_within_at.comp this fe_cont (subset_univ _) }, exact this.congr (λy hy, by simp [e.left_inv hy.2]) (by simp [e.left_inv hx]) end /-- Continuity at a point can be read under left composition with a local homeomorphism if a neighborhood of the initial point is sent to the source of the local homeomorphism-/ lemma continuous_at_iff_continuous_at_comp_left {f : γ → α} {x : γ} (h : f ⁻¹' e.source ∈ 𝓝 x) : continuous_at f x ↔ continuous_at (e ∘ f) x := begin have hx : f x ∈ e.source := (mem_of_nhds h : _), have h' : f ⁻¹' e.source ∈ 𝓝[univ] x, by rwa nhds_within_univ, rw [← continuous_within_at_univ, ← continuous_within_at_univ, e.continuous_within_at_iff_continuous_within_at_comp_left hx h'] end /-- A function is continuous on a set if and only if its composition with a local homeomorphism on the left is continuous on the corresponding set. -/ lemma continuous_on_iff_continuous_on_comp_left {f : γ → α} {s : set γ} (h : s ⊆ f ⁻¹' e.source) : continuous_on f s ↔ continuous_on (e ∘ f) s := forall_congr $ λ x, forall_congr $ λ hx, e.continuous_within_at_iff_continuous_within_at_comp_left (h hx) (mem_sets_of_superset self_mem_nhds_within h) end continuity /-- If a local homeomorphism has source and target equal to univ, then it induces a homeomorphism between the whole spaces, expressed in this definition. -/ def to_homeomorph_of_source_eq_univ_target_eq_univ (h : e.source = (univ : set α)) (h' : e.target = univ) : homeomorph α β := { to_fun := e, inv_fun := e.symm, left_inv := λx, e.left_inv $ by { rw h, exact mem_univ _ }, right_inv := λx, e.right_inv $ by { rw h', exact mem_univ _ }, continuous_to_fun := begin rw [continuous_iff_continuous_on_univ], convert e.continuous_to_fun, rw h end, continuous_inv_fun := begin rw [continuous_iff_continuous_on_univ], convert e.continuous_inv_fun, rw h' end } @[simp, mfld_simps] lemma to_homeomorph_coe (h : e.source = (univ : set α)) (h' : e.target = univ) : (e.to_homeomorph_of_source_eq_univ_target_eq_univ h h' : α → β) = e := rfl @[simp, mfld_simps] lemma to_homeomorph_symm_coe (h : e.source = (univ : set α)) (h' : e.target = univ) : ((e.to_homeomorph_of_source_eq_univ_target_eq_univ h h').symm : β → α) = e.symm := rfl /-- A local homeomorphism whose source is all of `α` defines an open embedding of `α` into `β`. The converse is also true; see `open_embedding.to_local_homeomorph`. -/ lemma to_open_embedding (h : e.source = set.univ) : open_embedding e := begin apply open_embedding_of_continuous_injective_open, { apply continuous_iff_continuous_on_univ.mpr, rw ← h, exact e.continuous_to_fun }, { apply set.injective_iff_inj_on_univ.mpr, rw ← h, exact e.inj_on }, { intros U hU, simpa only [h, subset_univ] with mfld_simps using e.image_open_of_open hU} end end local_homeomorph namespace homeomorph variables (e : homeomorph α β) (e' : homeomorph β γ) /- Register as simp lemmas that the fields of a local homeomorphism built from a homeomorphism correspond to the fields of the original homeomorphism. -/ @[simp, mfld_simps] lemma to_local_homeomorph_source : e.to_local_homeomorph.source = univ := rfl @[simp, mfld_simps] lemma to_local_homeomorph_target : e.to_local_homeomorph.target = univ := rfl @[simp, mfld_simps] lemma to_local_homeomorph_coe : (e.to_local_homeomorph : α → β) = e := rfl @[simp, mfld_simps] lemma to_local_homeomorph_coe_symm : (e.to_local_homeomorph.symm : β → α) = e.symm := rfl @[simp, mfld_simps] lemma refl_to_local_homeomorph : (homeomorph.refl α).to_local_homeomorph = local_homeomorph.refl α := rfl @[simp, mfld_simps] lemma symm_to_local_homeomorph : e.symm.to_local_homeomorph = e.to_local_homeomorph.symm := rfl @[simp, mfld_simps] lemma trans_to_local_homeomorph : (e.trans e').to_local_homeomorph = e.to_local_homeomorph.trans e'.to_local_homeomorph := local_homeomorph.eq_of_local_equiv_eq $ equiv.trans_to_local_equiv _ _ end homeomorph namespace open_embedding variables [nonempty α] variables (f : α → β) (h : open_embedding f) /-- An open embedding of `α` into `β`, with `α` nonempty, defines a local homeomorphism whose source is all of `α`. The converse is also true; see `local_homeomorph.to_open_embedding`. -/ noncomputable def to_local_homeomorph : local_homeomorph α β := local_homeomorph.of_continuous_open ((h.to_embedding.inj.inj_on univ).to_local_equiv _ _) h.continuous.continuous_on h.is_open_map is_open_univ @[simp, mfld_simps] lemma to_local_homeomorph_coe : ⇑(h.to_local_homeomorph f) = f := rfl @[simp, mfld_simps] lemma source : (h.to_local_homeomorph f).source = set.univ := rfl @[simp, mfld_simps] lemma target : (h.to_local_homeomorph f).target = set.range f := image_univ end open_embedding -- We close and reopen the namespace to avoid -- picking up the unnecessary `[nonempty α]` typeclass argument namespace open_embedding lemma continuous_at_iff {f : α → β} {g : β → γ} (hf : open_embedding f) {x : α} : continuous_at (g ∘ f) x ↔ continuous_at g (f x) := begin haveI : nonempty α := ⟨x⟩, convert (((hf.to_local_homeomorph f).continuous_at_iff_continuous_at_comp_right) _).symm, { apply (local_homeomorph.left_inv _ _).symm, simp, }, { simp, }, end end open_embedding namespace topological_space.opens open topological_space variables (s : opens α) [nonempty s] /-- The inclusion of an open subset `s` of a space `α` into `α` is a local homeomorphism from the subtype `s` to `α`. -/ noncomputable def local_homeomorph_subtype_coe : local_homeomorph s α := open_embedding.to_local_homeomorph _ s.2.open_embedding_subtype_coe @[simp, mfld_simps] lemma local_homeomorph_subtype_coe_coe : (s.local_homeomorph_subtype_coe : s → α) = coe := rfl @[simp, mfld_simps] lemma local_homeomorph_subtype_coe_source : s.local_homeomorph_subtype_coe.source = set.univ := rfl @[simp, mfld_simps] lemma local_homeomorph_subtype_coe_target : s.local_homeomorph_subtype_coe.target = s := by { simp only [local_homeomorph_subtype_coe, subtype.range_coe_subtype] with mfld_simps, refl } end topological_space.opens namespace local_homeomorph open topological_space variables (e : local_homeomorph α β) variables (s : opens α) [nonempty s] /-- The restriction of a local homeomorphism `e` to an open subset `s` of the domain type produces a local homeomorphism whose domain is the subtype `s`.-/ noncomputable def subtype_restr : local_homeomorph s β := s.local_homeomorph_subtype_coe.trans e lemma subtype_restr_def : e.subtype_restr s = s.local_homeomorph_subtype_coe.trans e := rfl @[simp, mfld_simps] lemma subtype_restr_coe : ((e.subtype_restr s : local_homeomorph s β) : s → β) = set.restrict (e : α → β) s := rfl @[simp, mfld_simps] lemma subtype_restr_source : (e.subtype_restr s).source = coe ⁻¹' e.source := by simp only [subtype_restr_def] with mfld_simps /- This lemma characterizes the transition functions of an open subset in terms of the transition functions of the original space. -/ lemma subtype_restr_symm_trans_subtype_restr (f f' : local_homeomorph α β) : (f.subtype_restr s).symm.trans (f'.subtype_restr s) ≈ (f.symm.trans f').restr (f.target ∩ (f.symm) ⁻¹' s) := begin simp only [subtype_restr_def, trans_symm_eq_symm_trans_symm], have openness₁ : is_open (f.target ∩ f.symm ⁻¹' s) := f.preimage_open_of_open_symm s.2, rw [← of_set_trans _ openness₁, ← trans_assoc, ← trans_assoc], refine eq_on_source.trans' _ (eq_on_source_refl _), -- f' has been eliminated !!! have sets_identity : f.symm.source ∩ (f.target ∩ (f.symm) ⁻¹' s) = f.symm.source ∩ f.symm ⁻¹' s, { mfld_set_tac }, have openness₂ : is_open (s : set α) := s.2, rw [of_set_trans', sets_identity, ← trans_of_set' _ openness₂, trans_assoc], refine eq_on_source.trans' (eq_on_source_refl _) _, -- f has been eliminated !!! refine setoid.trans (trans_symm_self s.local_homeomorph_subtype_coe) _, simp only with mfld_simps, end end local_homeomorph
09275ef00ed595d9ef82722dc2e8fc0bb2e2e11d
d1a52c3f208fa42c41df8278c3d280f075eb020c
/stage0/src/Std/Data/RBTree.lean
3d5ff8ca81f0cb17fc4a7026d13a6a81fd960007
[ "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,453
lean
/- Copyright (c) 2017 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Std.Data.RBMap namespace Std universe u v w def RBTree (α : Type u) (cmp : α → α → Ordering) : Type u := RBMap α Unit cmp instance : Inhabited (RBTree α p) where default := RBMap.empty @[inline] def mkRBTree (α : Type u) (cmp : α → α → Ordering) : RBTree α cmp := mkRBMap α Unit cmp instance (α : Type u) (cmp : α → α → Ordering) : EmptyCollection (RBTree α cmp) := ⟨mkRBTree α cmp⟩ namespace RBTree variable {α : Type u} {β : Type v} {cmp : α → α → Ordering} @[inline] def empty : RBTree α cmp := RBMap.empty @[inline] def depth (f : Nat → Nat → Nat) (t : RBTree α cmp) : Nat := RBMap.depth f t @[inline] def fold (f : β → α → β) (init : β) (t : RBTree α cmp) : β := RBMap.fold (fun r a _ => f r a) init t @[inline] def revFold (f : β → α → β) (init : β) (t : RBTree α cmp) : β := RBMap.revFold (fun r a _ => f r a) init t @[inline] def foldM {m : Type v → Type w} [Monad m] (f : β → α → m β) (init : β) (t : RBTree α cmp) : m β := RBMap.foldM (fun r a _ => f r a) init t @[inline] def forM {m : Type v → Type w} [Monad m] (f : α → m PUnit) (t : RBTree α cmp) : m PUnit := t.foldM (fun _ a => f a) ⟨⟩ @[inline] protected def forIn [Monad m] (t : RBTree α cmp) (init : σ) (f : α → σ → m (ForInStep σ)) : m σ := t.val.forIn init (fun a _ acc => f a acc) instance : ForIn m (RBTree α cmp) α where forIn := RBTree.forIn @[inline] def isEmpty (t : RBTree α cmp) : Bool := RBMap.isEmpty t @[specialize] def toList (t : RBTree α cmp) : List α := t.revFold (fun as a => a::as) [] @[specialize] def toArray (t : RBTree α cmp) : Array α := t.fold (fun as a => as.push a) #[] @[inline] protected def min (t : RBTree α cmp) : Option α := match RBMap.min t with | some ⟨a, _⟩ => some a | none => none @[inline] protected def max (t : RBTree α cmp) : Option α := match RBMap.max t with | some ⟨a, _⟩ => some a | none => none instance [Repr α] : Repr (RBTree α cmp) where reprPrec t prec := Repr.addAppParen ("Std.rbtreeOf " ++ repr t.toList) prec @[inline] def insert (t : RBTree α cmp) (a : α) : RBTree α cmp := RBMap.insert t a () @[inline] def erase (t : RBTree α cmp) (a : α) : RBTree α cmp := RBMap.erase t a @[specialize] def ofList : List α → RBTree α cmp | [] => mkRBTree .. | x::xs => (ofList xs).insert x @[inline] def find? (t : RBTree α cmp) (a : α) : Option α := match RBMap.findCore? t a with | some ⟨a, _⟩ => some a | none => none @[inline] def contains (t : RBTree α cmp) (a : α) : Bool := (t.find? a).isSome def fromList (l : List α) (cmp : α → α → Ordering) : RBTree α cmp := l.foldl insert (mkRBTree α cmp) @[inline] def all (t : RBTree α cmp) (p : α → Bool) : Bool := RBMap.all t (fun a _ => p a) @[inline] def any (t : RBTree α cmp) (p : α → Bool) : Bool := RBMap.any t (fun a _ => p a) def subset (t₁ t₂ : RBTree α cmp) : Bool := t₁.all fun a => (t₂.find? a).toBool def seteq (t₁ t₂ : RBTree α cmp) : Bool := subset t₁ t₂ && subset t₂ t₁ end RBTree def rbtreeOf {α : Type u} (l : List α) (cmp : α → α → Ordering) : RBTree α cmp := RBTree.fromList l cmp end Std
408e900f0c9aee17090bec34097d7b100e4e654f
4727251e0cd73359b15b664c3170e5d754078599
/src/category_theory/preadditive/single_obj.lean
17cf6cf1c28970d63d2b86c45e4cd6af063f2bac
[ "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
610
lean
/- Copyright (c) 2021 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import category_theory.preadditive.default import category_theory.single_obj /-! # `single_obj α` is preadditive when `α` is a ring. -/ namespace category_theory variables {α : Type*} [ring α] instance : preadditive (single_obj α) := { add_comp' := λ _ _ _ f f' g, mul_add g f f', comp_add' := λ _ _ _ f g g', add_mul g g' f, } -- TODO define `PreAddCat` (with additive functors as morphisms), and `Ring ⥤ PreAddCat`. end category_theory
c60c122f0442fb35996e98996f29182e5aae6185
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/order/filter/interval.lean
fd29a67556f54768002159182738acb5bcda4acf
[ "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
11,612
lean
/- Copyright (c) 2020 Yury G. Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury G. Kudryashov -/ import data.set.intervals.ord_connected import order.filter.lift import order.filter.at_top_bot /-! # Convergence of intervals If both `a` and `b` tend to some filter `l₁`, sometimes this implies that `Ixx a b` tends to `l₂.lift' powerset`, i.e., for any `s ∈ l₂` eventually `Ixx a b` becomes a subset of `s`. Here and below `Ixx` is one of `Icc`, `Ico`, `Ioc`, and `Ioo`. We define `filter.tendsto_Ixx_class Ixx l₁ l₂` to be a typeclass representing this property. The instances provide the best `l₂` for a given `l₁`. In many cases `l₁ = l₂` but sometimes we can drop an endpoint from an interval: e.g., we prove `tendsto_Ixx_class Ico (𝓟 $ Iic a) (𝓟 $ Iio a)`, i.e., if `u₁ n` and `u₂ n` belong eventually to `Iic a`, then the interval `Ico (u₁ n) (u₂ n)` is eventually included in `Iio a`. The next table shows “output” filters `l₂` for different values of `Ixx` and `l₁`. The instances that need topology are defined in `topology/algebra/ordered`. | Input filter | `Ixx = Icc` | `Ixx = Ico` | `Ixx = Ioc` | `Ixx = Ioo` | | -----------: | :-----------: | :-----------: | :-----------: | :-----------: | | `at_top` | `at_top` | `at_top` | `at_top` | `at_top` | | `at_bot` | `at_bot` | `at_bot` | `at_bot` | `at_bot` | | `pure a` | `pure a` | `⊥` | `⊥` | `⊥` | | `𝓟 (Iic a)` | `𝓟 (Iic a)` | `𝓟 (Iio a)` | `𝓟 (Iic a)` | `𝓟 (Iio a)` | | `𝓟 (Ici a)` | `𝓟 (Ici a)` | `𝓟 (Ici a)` | `𝓟 (Ioi a)` | `𝓟 (Ioi a)` | | `𝓟 (Ioi a)` | `𝓟 (Ioi a)` | `𝓟 (Ioi a)` | `𝓟 (Ioi a)` | `𝓟 (Ioi a)` | | `𝓟 (Iio a)` | `𝓟 (Iio a)` | `𝓟 (Iio a)` | `𝓟 (Iio a)` | `𝓟 (Iio a)` | | `𝓝 a` | `𝓝 a` | `𝓝 a` | `𝓝 a` | `𝓝 a` | | `𝓝[Iic a] b` | `𝓝[Iic a] b` | `𝓝[Iio a] b` | `𝓝[Iic a] b` | `𝓝[Iio a] b` | | `𝓝[Ici a] b` | `𝓝[Ici a] b` | `𝓝[Ici a] b` | `𝓝[Ioi a] b` | `𝓝[Ioi a] b` | | `𝓝[Ioi a] b` | `𝓝[Ioi a] b` | `𝓝[Ioi a] b` | `𝓝[Ioi a] b` | `𝓝[Ioi a] b` | | `𝓝[Iio a] b` | `𝓝[Iio a] b` | `𝓝[Iio a] b` | `𝓝[Iio a] b` | `𝓝[Iio a] b` | -/ variables {α β : Type*} open_locale classical filter interval open set function namespace filter section preorder variables [preorder α] /-- A pair of filters `l₁`, `l₂` has `tendsto_Ixx_class Ixx` property if `Ixx a b` tends to `l₂.lift' powerset` as `a` and `b` tend to `l₁`. In all instances `Ixx` is one of `Icc`, `Ico`, `Ioc`, or `Ioo`. The instances provide the best `l₂` for a given `l₁`. In many cases `l₁ = l₂` but sometimes we can drop an endpoint from an interval: e.g., we prove `tendsto_Ixx_class Ico (𝓟 $ Iic a) (𝓟 $ Iio a)`, i.e., if `u₁ n` and `u₂ n` belong eventually to `Iic a`, then the interval `Ico (u₁ n) (u₂ n)` is eventually included in `Iio a`. We mark `l₂` as an `out_param` so that Lean can automatically find an appropriate `l₂` based on `Ixx` and `l₁`. This way, e.g., `tendsto.Ico h₁ h₂` works without specifying explicitly `l₂`. -/ class tendsto_Ixx_class (Ixx : α → α → set α) (l₁ : filter α) (l₂ : out_param $ filter α) : Prop := (tendsto_Ixx : tendsto (λ p : α × α, Ixx p.1 p.2) (l₁ ×ᶠ l₁) (l₂.lift' powerset)) lemma tendsto.Icc {l₁ l₂ : filter α} [tendsto_Ixx_class Icc l₁ l₂] {lb : filter β} {u₁ u₂ : β → α} (h₁ : tendsto u₁ lb l₁) (h₂ : tendsto u₂ lb l₁) : tendsto (λ x, Icc (u₁ x) (u₂ x)) lb (l₂.lift' powerset) := tendsto_Ixx_class.tendsto_Ixx.comp $ h₁.prod_mk h₂ lemma tendsto.Ioc {l₁ l₂ : filter α} [tendsto_Ixx_class Ioc l₁ l₂] {lb : filter β} {u₁ u₂ : β → α} (h₁ : tendsto u₁ lb l₁) (h₂ : tendsto u₂ lb l₁) : tendsto (λ x, Ioc (u₁ x) (u₂ x)) lb (l₂.lift' powerset) := tendsto_Ixx_class.tendsto_Ixx.comp $ h₁.prod_mk h₂ lemma tendsto.Ico {l₁ l₂ : filter α} [tendsto_Ixx_class Ico l₁ l₂] {lb : filter β} {u₁ u₂ : β → α} (h₁ : tendsto u₁ lb l₁) (h₂ : tendsto u₂ lb l₁) : tendsto (λ x, Ico (u₁ x) (u₂ x)) lb (l₂.lift' powerset) := tendsto_Ixx_class.tendsto_Ixx.comp $ h₁.prod_mk h₂ lemma tendsto.Ioo {l₁ l₂ : filter α} [tendsto_Ixx_class Ioo l₁ l₂] {lb : filter β} {u₁ u₂ : β → α} (h₁ : tendsto u₁ lb l₁) (h₂ : tendsto u₂ lb l₁) : tendsto (λ x, Ioo (u₁ x) (u₂ x)) lb (l₂.lift' powerset) := tendsto_Ixx_class.tendsto_Ixx.comp $ h₁.prod_mk h₂ lemma tendsto_Ixx_class_principal {s t : set α} {Ixx : α → α → set α} : tendsto_Ixx_class Ixx (𝓟 s) (𝓟 t) ↔ ∀ (x ∈ s) (y ∈ s), Ixx x y ⊆ t := begin refine iff.trans ⟨λ h, h.1, λ h, ⟨h⟩⟩ _, simp [lift'_principal monotone_powerset, -mem_prod, -prod.forall, forall_prod_set] end lemma tendsto_Ixx_class_inf {l₁ l₁' l₂ l₂' : filter α} {Ixx} [h : tendsto_Ixx_class Ixx l₁ l₂] [h' : tendsto_Ixx_class Ixx l₁' l₂'] : tendsto_Ixx_class Ixx (l₁ ⊓ l₁') (l₂ ⊓ l₂') := ⟨by simpa only [prod_inf_prod, lift'_inf_powerset] using h.1.inf h'.1⟩ lemma tendsto_Ixx_class_of_subset {l₁ l₂ : filter α} {Ixx Ixx' : α → α → set α} (h : ∀ a b, Ixx a b ⊆ Ixx' a b) [h' : tendsto_Ixx_class Ixx' l₁ l₂] : tendsto_Ixx_class Ixx l₁ l₂ := ⟨tendsto_lift'_powerset_mono h'.1 $ eventually_of_forall $ prod.forall.2 h⟩ lemma has_basis.tendsto_Ixx_class {ι : Type*} {p : ι → Prop} {s} {l : filter α} (hl : l.has_basis p s) {Ixx : α → α → set α} (H : ∀ i, p i → ∀ (x ∈ s i) (y ∈ s i), Ixx x y ⊆ s i) : tendsto_Ixx_class Ixx l l := ⟨(hl.prod_self.tendsto_iff (hl.lift' monotone_powerset)).2 $ λ i hi, ⟨i, hi, λ x hx, H i hi _ hx.1 _ hx.2⟩⟩ instance tendsto_Icc_at_top_at_top : tendsto_Ixx_class Icc (at_top : filter α) at_top := (has_basis_infi_principal_finite _).tendsto_Ixx_class $ λ s hs, set.ord_connected.out $ ord_connected_bInter $ λ i hi, ord_connected_Ici instance tendsto_Ico_at_top_at_top : tendsto_Ixx_class Ico (at_top : filter α) at_top := tendsto_Ixx_class_of_subset (λ _ _, Ico_subset_Icc_self) instance tendsto_Ioc_at_top_at_top : tendsto_Ixx_class Ioc (at_top : filter α) at_top := tendsto_Ixx_class_of_subset (λ _ _, Ioc_subset_Icc_self) instance tendsto_Ioo_at_top_at_top : tendsto_Ixx_class Ioo (at_top : filter α) at_top := tendsto_Ixx_class_of_subset (λ _ _, Ioo_subset_Icc_self) instance tendsto_Icc_at_bot_at_bot : tendsto_Ixx_class Icc (at_bot : filter α) at_bot := (has_basis_infi_principal_finite _).tendsto_Ixx_class $ λ s hs, set.ord_connected.out $ ord_connected_bInter $ λ i hi, ord_connected_Iic instance tendsto_Ico_at_bot_at_bot : tendsto_Ixx_class Ico (at_bot : filter α) at_bot := tendsto_Ixx_class_of_subset (λ _ _, Ico_subset_Icc_self) instance tendsto_Ioc_at_bot_at_bot : tendsto_Ixx_class Ioc (at_bot : filter α) at_bot := tendsto_Ixx_class_of_subset (λ _ _, Ioc_subset_Icc_self) instance tendsto_Ioo_at_bot_at_bot : tendsto_Ixx_class Ioo (at_bot : filter α) at_bot := tendsto_Ixx_class_of_subset (λ _ _, Ioo_subset_Icc_self) instance ord_connected.tendsto_Icc {s : set α} [hs : ord_connected s] : tendsto_Ixx_class Icc (𝓟 s) (𝓟 s) := tendsto_Ixx_class_principal.2 hs.out instance tendsto_Ico_Ici_Ici {a : α} : tendsto_Ixx_class Ico (𝓟 (Ici a)) (𝓟 (Ici a)) := tendsto_Ixx_class_of_subset (λ _ _, Ico_subset_Icc_self) instance tendsto_Ico_Ioi_Ioi {a : α} : tendsto_Ixx_class Ico (𝓟 (Ioi a)) (𝓟 (Ioi a)) := tendsto_Ixx_class_of_subset (λ _ _, Ico_subset_Icc_self) instance tendsto_Ico_Iic_Iio {a : α} : tendsto_Ixx_class Ico (𝓟 (Iic a)) (𝓟 (Iio a)) := tendsto_Ixx_class_principal.2 $ λ a ha b hb x hx, lt_of_lt_of_le hx.2 hb instance tendsto_Ico_Iio_Iio {a : α} : tendsto_Ixx_class Ico (𝓟 (Iio a)) (𝓟 (Iio a)) := tendsto_Ixx_class_of_subset (λ _ _, Ico_subset_Icc_self) instance tendsto_Ioc_Ici_Ioi {a : α} : tendsto_Ixx_class Ioc (𝓟 (Ici a)) (𝓟 (Ioi a)) := tendsto_Ixx_class_principal.2 $ λ x hx y hy t ht, lt_of_le_of_lt hx ht.1 instance tendsto_Ioc_Iic_Iic {a : α} : tendsto_Ixx_class Ioc (𝓟 (Iic a)) (𝓟 (Iic a)) := tendsto_Ixx_class_of_subset (λ _ _, Ioc_subset_Icc_self) instance tendsto_Ioc_Iio_Iio {a : α} : tendsto_Ixx_class Ioc (𝓟 (Iio a)) (𝓟 (Iio a)) := tendsto_Ixx_class_of_subset (λ _ _, Ioc_subset_Icc_self) instance tendsto_Ioc_Ioi_Ioi {a : α} : tendsto_Ixx_class Ioc (𝓟 (Ioi a)) (𝓟 (Ioi a)) := tendsto_Ixx_class_of_subset (λ _ _, Ioc_subset_Icc_self) instance tendsto_Ioo_Ici_Ioi {a : α} : tendsto_Ixx_class Ioo (𝓟 (Ici a)) (𝓟 (Ioi a)) := tendsto_Ixx_class_of_subset (λ _ _, Ioo_subset_Ioc_self) instance tendsto_Ioo_Iic_Iio {a : α} : tendsto_Ixx_class Ioo (𝓟 (Iic a)) (𝓟 (Iio a)) := tendsto_Ixx_class_of_subset (λ _ _, Ioo_subset_Ico_self) instance tendsto_Ioo_Ioi_Ioi {a : α} : tendsto_Ixx_class Ioo (𝓟 (Ioi a)) (𝓟 (Ioi a)) := tendsto_Ixx_class_of_subset (λ _ _, Ioo_subset_Ioc_self) instance tendsto_Ioo_Iio_Iio {a : α} : tendsto_Ixx_class Ioo (𝓟 (Iio a)) (𝓟 (Iio a)) := tendsto_Ixx_class_of_subset (λ _ _, Ioo_subset_Ioc_self) instance tendsto_Icc_Icc_Icc {a b : α} : tendsto_Ixx_class Icc (𝓟 (Icc a b)) (𝓟 (Icc a b)) := tendsto_Ixx_class_principal.mpr $ λ x hx y hy, Icc_subset_Icc hx.1 hy.2 instance tendsto_Ioc_Icc_Icc {a b : α} : tendsto_Ixx_class Ioc (𝓟 (Icc a b)) (𝓟 (Icc a b)) := tendsto_Ixx_class_of_subset $ λ _ _, Ioc_subset_Icc_self end preorder section partial_order variable [partial_order α] instance tendsto_Icc_pure_pure {a : α} : tendsto_Ixx_class Icc (pure a) (pure a : filter α) := by { rw ← principal_singleton, exact tendsto_Ixx_class_principal.2 ord_connected_singleton.out } instance tendsto_Ico_pure_bot {a : α} : tendsto_Ixx_class Ico (pure a) ⊥ := ⟨by simp [lift'_bot monotone_powerset]⟩ instance tendsto_Ioc_pure_bot {a : α} : tendsto_Ixx_class Ioc (pure a) ⊥ := ⟨by simp [lift'_bot monotone_powerset]⟩ instance tendsto_Ioo_pure_bot {a : α} : tendsto_Ixx_class Ioo (pure a) ⊥ := tendsto_Ixx_class_of_subset (λ _ _, Ioo_subset_Ioc_self) end partial_order section linear_order variables [linear_order α] instance tendsto_Icc_interval_interval {a b : α} : tendsto_Ixx_class Icc (𝓟 [a, b]) (𝓟 [a, b]) := filter.tendsto_Icc_Icc_Icc instance tendsto_Ioc_interval_interval {a b : α} : tendsto_Ixx_class Ioc (𝓟 [a, b]) (𝓟 [a, b]) := filter.tendsto_Ioc_Icc_Icc instance tendsto_interval_of_Icc {l : filter α} [tendsto_Ixx_class Icc l l] : tendsto_Ixx_class interval l l := begin refine ⟨λ s hs, mem_map.2 $ mem_prod_self_iff.2 _⟩, obtain ⟨t, htl, hts⟩ : ∃ t ∈ l, ∀ p ∈ (t : set α) ×ˢ t, Icc (p : α × α).1 p.2 ∈ s, from mem_prod_self_iff.1 (mem_map.1 (tendsto_fst.Icc tendsto_snd hs)), refine ⟨t, htl, λ p hp, _⟩, cases le_total p.1 p.2, { rw [mem_preimage, interval_of_le h], exact hts p hp }, { rw [mem_preimage, interval_of_ge h], exact hts ⟨p.2, p.1⟩ ⟨hp.2, hp.1⟩ } end lemma tendsto.interval {l : filter α} [tendsto_Ixx_class Icc l l] {f g : β → α} {lb : filter β} (hf : tendsto f lb l) (hg : tendsto g lb l) : tendsto (λ x, [f x, g x]) lb (l.lift' powerset) := tendsto_Ixx_class.tendsto_Ixx.comp $ hf.prod_mk hg end linear_order end filter
c0b1c2cbec0889510de325cb5e4475ca5b210af8
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/algebra/order/smul.lean
734d7ca1d021324bc47a2ec0918e13174bd547f0
[ "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
12,973
lean
/- Copyright (c) 2020 Frédéric Dupuis. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Frédéric Dupuis -/ import algebra.module.pi import algebra.module.prod import algebra.order.monoid.prod import algebra.order.pi import data.set.pointwise.smul import tactic.positivity /-! # Ordered scalar product > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. In this file we define * `ordered_smul R M` : an ordered additive commutative monoid `M` is an `ordered_smul` over an `ordered_semiring` `R` if the scalar product respects the order relation on the monoid and on the ring. There is a correspondence between this structure and convex cones, which is proven in `analysis/convex/cone.lean`. ## Implementation notes * We choose to define `ordered_smul` as a `Prop`-valued mixin, so that it can be used for actions, modules, and algebras (the axioms for an "ordered algebra" are exactly that the algebra is ordered as a module). * To get ordered modules and ordered vector spaces, it suffices to replace the `order_add_comm_monoid` and the `ordered_semiring` as desired. ## References * https://en.wikipedia.org/wiki/Ordered_module ## Tags ordered module, ordered scalar, ordered smul, ordered action, ordered vector space -/ open_locale pointwise /-- The ordered scalar product property is when an ordered additive commutative monoid with a partial order has a scalar multiplication which is compatible with the order. -/ @[protect_proj] class ordered_smul (R M : Type*) [ordered_semiring R] [ordered_add_comm_monoid M] [smul_with_zero R M] : Prop := (smul_lt_smul_of_pos : ∀ {a b : M}, ∀ {c : R}, a < b → 0 < c → c • a < c • b) (lt_of_smul_lt_smul_of_pos : ∀ {a b : M}, ∀ {c : R}, c • a < c • b → 0 < c → a < b) variables {ι 𝕜 R M N : Type*} namespace order_dual instance [has_zero R] [add_zero_class M] [h : smul_with_zero R M] : smul_with_zero R Mᵒᵈ := { zero_smul := λ m, order_dual.rec (zero_smul _) m, smul_zero := λ r, order_dual.rec smul_zero r, ..order_dual.has_smul } instance [monoid R] [mul_action R M] : mul_action R Mᵒᵈ := { one_smul := λ m, order_dual.rec (one_smul _) m, mul_smul := λ r, order_dual.rec mul_smul r, ..order_dual.has_smul } instance [monoid_with_zero R] [add_monoid M] [mul_action_with_zero R M] : mul_action_with_zero R Mᵒᵈ := { ..order_dual.mul_action, ..order_dual.smul_with_zero } instance [monoid_with_zero R] [add_monoid M] [distrib_mul_action R M] : distrib_mul_action R Mᵒᵈ := { smul_add := λ k a, order_dual.rec (λ a' b, order_dual.rec (smul_add _ _) b) a, smul_zero := λ r, order_dual.rec (@smul_zero _ M _ _) r } instance [ordered_semiring R] [ordered_add_comm_monoid M] [smul_with_zero R M] [ordered_smul R M] : ordered_smul R Mᵒᵈ := { smul_lt_smul_of_pos := λ a b, @ordered_smul.smul_lt_smul_of_pos R M _ _ _ _ b a, lt_of_smul_lt_smul_of_pos := λ a b, @ordered_smul.lt_of_smul_lt_smul_of_pos R M _ _ _ _ b a } end order_dual section ordered_smul variables [ordered_semiring R] [ordered_add_comm_monoid M] [smul_with_zero R M] [ordered_smul R M] {s : set M} {a b : M} {c : R} lemma smul_lt_smul_of_pos : a < b → 0 < c → c • a < c • b := ordered_smul.smul_lt_smul_of_pos lemma smul_le_smul_of_nonneg (h₁ : a ≤ b) (h₂ : 0 ≤ c) : c • a ≤ c • b := begin rcases h₁.eq_or_lt with rfl|hab, { refl }, { rcases h₂.eq_or_lt with rfl|hc, { rw [zero_smul, zero_smul] }, { exact (smul_lt_smul_of_pos hab hc).le } } end lemma smul_nonneg (hc : 0 ≤ c) (ha : 0 ≤ a) : 0 ≤ c • a := calc (0 : M) = c • (0 : M) : (smul_zero c).symm ... ≤ c • a : smul_le_smul_of_nonneg ha hc lemma smul_nonpos_of_nonneg_of_nonpos (hc : 0 ≤ c) (ha : a ≤ 0) : c • a ≤ 0 := @smul_nonneg R Mᵒᵈ _ _ _ _ _ _ hc ha lemma eq_of_smul_eq_smul_of_pos_of_le (h₁ : c • a = c • b) (hc : 0 < c) (hle : a ≤ b) : a = b := hle.lt_or_eq.resolve_left $ λ hlt, (smul_lt_smul_of_pos hlt hc).ne h₁ lemma lt_of_smul_lt_smul_of_nonneg (h : c • a < c • b) (hc : 0 ≤ c) : a < b := hc.eq_or_lt.elim (λ hc, false.elim $ lt_irrefl (0:M) $ by rwa [← hc, zero_smul, zero_smul] at h) (ordered_smul.lt_of_smul_lt_smul_of_pos h) lemma smul_lt_smul_iff_of_pos (hc : 0 < c) : c • a < c • b ↔ a < b := ⟨λ h, lt_of_smul_lt_smul_of_nonneg h hc.le, λ h, smul_lt_smul_of_pos h hc⟩ lemma smul_pos_iff_of_pos (hc : 0 < c) : 0 < c • a ↔ 0 < a := calc 0 < c • a ↔ c • 0 < c • a : by rw smul_zero ... ↔ 0 < a : smul_lt_smul_iff_of_pos hc alias smul_pos_iff_of_pos ↔ _ smul_pos lemma monotone_smul_left (hc : 0 ≤ c) : monotone (has_smul.smul c : M → M) := λ a b h, smul_le_smul_of_nonneg h hc lemma strict_mono_smul_left (hc : 0 < c) : strict_mono (has_smul.smul c : M → M) := λ a b h, smul_lt_smul_of_pos h hc lemma smul_lower_bounds_subset_lower_bounds_smul (hc : 0 ≤ c) : c • lower_bounds s ⊆ lower_bounds (c • s) := (monotone_smul_left hc).image_lower_bounds_subset_lower_bounds_image lemma smul_upper_bounds_subset_upper_bounds_smul (hc : 0 ≤ c) : c • upper_bounds s ⊆ upper_bounds (c • s) := (monotone_smul_left hc).image_upper_bounds_subset_upper_bounds_image lemma bdd_below.smul_of_nonneg (hs : bdd_below s) (hc : 0 ≤ c) : bdd_below (c • s) := (monotone_smul_left hc).map_bdd_below hs lemma bdd_above.smul_of_nonneg (hs : bdd_above s) (hc : 0 ≤ c) : bdd_above (c • s) := (monotone_smul_left hc).map_bdd_above hs end ordered_smul /-- To prove that a linear ordered monoid is an ordered module, it suffices to verify only the first axiom of `ordered_smul`. -/ lemma ordered_smul.mk'' [ordered_semiring 𝕜] [linear_ordered_add_comm_monoid M] [smul_with_zero 𝕜 M] (h : ∀ ⦃c : 𝕜⦄, 0 < c → strict_mono (λ a : M, c • a)) : ordered_smul 𝕜 M := { smul_lt_smul_of_pos := λ a b c hab hc, h hc hab, lt_of_smul_lt_smul_of_pos := λ a b c hab hc, (h hc).lt_iff_lt.1 hab } instance nat.ordered_smul [linear_ordered_cancel_add_comm_monoid M] : ordered_smul ℕ M := ordered_smul.mk'' $ λ n hn a b hab, begin cases n, { cases hn }, induction n with n ih, { simp only [one_nsmul, hab], }, { simp only [succ_nsmul _ n.succ, add_lt_add hab (ih n.succ_pos)] } end instance int.ordered_smul [linear_ordered_add_comm_group M] : ordered_smul ℤ M := ordered_smul.mk'' $ λ n hn, begin cases n, { simp only [int.of_nat_eq_coe, int.coe_nat_pos, coe_nat_zsmul] at ⊢ hn, exact strict_mono_smul_left hn }, { cases (int.neg_succ_not_pos _).1 hn } end section linear_ordered_semiring variables [linear_ordered_semiring R] [linear_ordered_add_comm_monoid M] [smul_with_zero R M] [ordered_smul R M] {a : R} -- TODO: `linear_ordered_field M → ordered_smul ℚ M` instance linear_ordered_semiring.to_ordered_smul : ordered_smul R R := ordered_smul.mk'' $ λ c, strict_mono_mul_left_of_pos lemma smul_max (ha : 0 ≤ a) (b₁ b₂ : M) : a • max b₁ b₂ = max (a • b₁) (a • b₂) := (monotone_smul_left ha : monotone (_ : M → M)).map_max lemma smul_min (ha : 0 ≤ a) (b₁ b₂ : M) : a • min b₁ b₂ = min (a • b₁) (a • b₂) := (monotone_smul_left ha : monotone (_ : M → M)).map_min end linear_ordered_semiring section linear_ordered_semifield variables [linear_ordered_semifield 𝕜] [ordered_add_comm_monoid M] [ordered_add_comm_monoid N] [mul_action_with_zero 𝕜 M] [mul_action_with_zero 𝕜 N] /-- To prove that a vector space over a linear ordered field is ordered, it suffices to verify only the first axiom of `ordered_smul`. -/ lemma ordered_smul.mk' (h : ∀ ⦃a b : M⦄ ⦃c : 𝕜⦄, a < b → 0 < c → c • a ≤ c • b) : ordered_smul 𝕜 M := begin have hlt' : ∀ ⦃a b : M⦄ ⦃c : 𝕜⦄, a < b → 0 < c → c • a < c • b, { refine λ a b c hab hc, (h hab hc).lt_of_ne _, rw [ne.def, hc.ne'.is_unit.smul_left_cancel], exact hab.ne }, refine { smul_lt_smul_of_pos := hlt', .. }, intros a b c hab hc, obtain ⟨c, rfl⟩ := hc.ne'.is_unit, rw [← inv_smul_smul c a, ← inv_smul_smul c b], refine hlt' hab (pos_of_mul_pos_right _ hc.le), simp only [c.mul_inv, zero_lt_one] end instance [ordered_smul 𝕜 M] [ordered_smul 𝕜 N] : ordered_smul 𝕜 (M × N) := ordered_smul.mk' $ λ a b c h hc, ⟨smul_le_smul_of_nonneg h.1.1 hc.le, smul_le_smul_of_nonneg h.1.2 hc.le⟩ instance pi.ordered_smul {M : ι → Type*} [Π i, ordered_add_comm_monoid (M i)] [Π i, mul_action_with_zero 𝕜 (M i)] [∀ i, ordered_smul 𝕜 (M i)] : ordered_smul 𝕜 (Π i, M i) := ordered_smul.mk' $ λ v u c h hc i, smul_le_smul_of_nonneg (h.le i) hc.le /- Sometimes Lean fails to apply the dependent version to non-dependent functions, so we define another instance. -/ instance pi.ordered_smul' [ordered_smul 𝕜 M] : ordered_smul 𝕜 (ι → M) := pi.ordered_smul /- Sometimes Lean fails to unify the module with the scalars, so we define another instance. -/ instance pi.ordered_smul'' : ordered_smul 𝕜 (ι → 𝕜) := @pi.ordered_smul' ι 𝕜 𝕜 _ _ _ _ variables [ordered_smul 𝕜 M] {s : set M} {a b : M} {c : 𝕜} lemma smul_le_smul_iff_of_pos (hc : 0 < c) : c • a ≤ c • b ↔ a ≤ b := ⟨λ h, inv_smul_smul₀ hc.ne' a ▸ inv_smul_smul₀ hc.ne' b ▸ smul_le_smul_of_nonneg h (inv_nonneg.2 hc.le), λ h, smul_le_smul_of_nonneg h hc.le⟩ lemma inv_smul_le_iff (h : 0 < c) : c⁻¹ • a ≤ b ↔ a ≤ c • b := by { rw [←smul_le_smul_iff_of_pos h, smul_inv_smul₀ h.ne'], apply_instance } lemma inv_smul_lt_iff (h : 0 < c) : c⁻¹ • a < b ↔ a < c • b := by { rw [←smul_lt_smul_iff_of_pos h, smul_inv_smul₀ h.ne'], apply_instance } lemma le_inv_smul_iff (h : 0 < c) : a ≤ c⁻¹ • b ↔ c • a ≤ b := by { rw [←smul_le_smul_iff_of_pos h, smul_inv_smul₀ h.ne'], apply_instance } lemma lt_inv_smul_iff (h : 0 < c) : a < c⁻¹ • b ↔ c • a < b := by { rw [←smul_lt_smul_iff_of_pos h, smul_inv_smul₀ h.ne'], apply_instance } variables (M) /-- Left scalar multiplication as an order isomorphism. -/ @[simps] def order_iso.smul_left (hc : 0 < c) : M ≃o M := { to_fun := λ b, c • b, inv_fun := λ b, c⁻¹ • b, left_inv := inv_smul_smul₀ hc.ne', right_inv := smul_inv_smul₀ hc.ne', map_rel_iff' := λ b₁ b₂, smul_le_smul_iff_of_pos hc } variables {M} @[simp] lemma lower_bounds_smul_of_pos (hc : 0 < c) : lower_bounds (c • s) = c • lower_bounds s := (order_iso.smul_left _ hc).lower_bounds_image @[simp] lemma upper_bounds_smul_of_pos (hc : 0 < c) : upper_bounds (c • s) = c • upper_bounds s := (order_iso.smul_left _ hc).upper_bounds_image @[simp] lemma bdd_below_smul_iff_of_pos (hc : 0 < c) : bdd_below (c • s) ↔ bdd_below s := (order_iso.smul_left _ hc).bdd_below_image @[simp] lemma bdd_above_smul_iff_of_pos (hc : 0 < c) : bdd_above (c • s) ↔ bdd_above s := (order_iso.smul_left _ hc).bdd_above_image end linear_ordered_semifield namespace tactic section ordered_smul variables [ordered_semiring R] [ordered_add_comm_monoid M] [smul_with_zero R M] [ordered_smul R M] {a : R} {b : M} private lemma smul_nonneg_of_pos_of_nonneg (ha : 0 < a) (hb : 0 ≤ b) : 0 ≤ a • b := smul_nonneg ha.le hb private lemma smul_nonneg_of_nonneg_of_pos (ha : 0 ≤ a) (hb : 0 < b) : 0 ≤ a • b := smul_nonneg ha hb.le end ordered_smul section no_zero_smul_divisors variables [has_zero R] [has_zero M] [has_smul R M] [no_zero_smul_divisors R M] {a : R} {b : M} private lemma smul_ne_zero_of_pos_of_ne_zero [preorder R] (ha : 0 < a) (hb : b ≠ 0) : a • b ≠ 0 := smul_ne_zero ha.ne' hb private lemma smul_ne_zero_of_ne_zero_of_pos [preorder M] (ha : a ≠ 0) (hb : 0 < b) : a • b ≠ 0 := smul_ne_zero ha hb.ne' end no_zero_smul_divisors open positivity /-- Extension for the `positivity` tactic: scalar multiplication is nonnegative/positive/nonzero if both sides are. -/ @[positivity] meta def positivity_smul : expr → tactic strictness | e@`(%%a • %%b) := do strictness_a ← core a, strictness_b ← core b, match strictness_a, strictness_b with | positive pa, positive pb := positive <$> mk_app ``smul_pos [pa, pb] | positive pa, nonnegative pb := nonnegative <$> mk_app ``smul_nonneg_of_pos_of_nonneg [pa, pb] | nonnegative pa, positive pb := nonnegative <$> mk_app ``smul_nonneg_of_nonneg_of_pos [pa, pb] | nonnegative pa, nonnegative pb := nonnegative <$> mk_app ``smul_nonneg [pa, pb] | positive pa, nonzero pb := nonzero <$> to_expr ``(smul_ne_zero_of_pos_of_ne_zero %%pa %%pb) | nonzero pa, positive pb := nonzero <$> to_expr ``(smul_ne_zero_of_ne_zero_of_pos %%pa %%pb) | nonzero pa, nonzero pb := nonzero <$> to_expr ``(smul_ne_zero %%pa %%pb) | sa@_, sb@ _ := positivity_fail e a b sa sb end | e := pp e >>= fail ∘ format.bracket "The expression `" "` isn't of the form `a • b`" end tactic
4f7e5395917c1eb11584c4aa6562a7b13ec234c1
fecda8e6b848337561d6467a1e30cf23176d6ad0
/src/data/nat/gcd.lean
93cd345350f99b434bc33cd323c62be22e4cd88a
[ "Apache-2.0" ]
permissive
spolu/mathlib
bacf18c3d2a561d00ecdc9413187729dd1f705ed
480c92cdfe1cf3c2d083abded87e82162e8814f4
refs/heads/master
1,671,684,094,325
1,600,736,045,000
1,600,736,045,000
297,564,749
1
0
null
1,600,758,368,000
1,600,758,367,000
null
UTF-8
Lean
false
false
16,256
lean
/- Copyright (c) 2014 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Leonardo de Moura -/ import data.nat.basic /-! # Definitions and properties of `gcd`, `lcm`, and `coprime` -/ namespace nat /-! ### `gcd` -/ theorem gcd_dvd (m n : ℕ) : (gcd m n ∣ m) ∧ (gcd m n ∣ n) := gcd.induction m n (λn, by rw gcd_zero_left; exact ⟨dvd_zero n, dvd_refl n⟩) (λm n npos, by rw ←gcd_rec; exact λ ⟨IH₁, IH₂⟩, ⟨IH₂, (dvd_mod_iff IH₂).1 IH₁⟩) theorem gcd_dvd_left (m n : ℕ) : gcd m n ∣ m := (gcd_dvd m n).left theorem gcd_dvd_right (m n : ℕ) : gcd m n ∣ n := (gcd_dvd m n).right theorem gcd_le_left {m} (n) (h : 0 < m) : gcd m n ≤ m := le_of_dvd h $ gcd_dvd_left m n theorem gcd_le_right (m) {n} (h : 0 < n) : gcd m n ≤ n := le_of_dvd h $ gcd_dvd_right m n theorem dvd_gcd {m n k : ℕ} : k ∣ m → k ∣ n → k ∣ gcd m n := gcd.induction m n (λn _ kn, by rw gcd_zero_left; exact kn) (λn m mpos IH H1 H2, by rw gcd_rec; exact IH ((dvd_mod_iff H1).2 H2) H1) theorem dvd_gcd_iff {m n k : ℕ} : k ∣ gcd m n ↔ k ∣ m ∧ k ∣ n := iff.intro (λ h, ⟨dvd_trans h (gcd_dvd m n).left, dvd_trans h (gcd_dvd m n).right⟩) (λ h, dvd_gcd h.left h.right) theorem gcd_comm (m n : ℕ) : gcd m n = gcd n m := dvd_antisymm (dvd_gcd (gcd_dvd_right m n) (gcd_dvd_left m n)) (dvd_gcd (gcd_dvd_right n m) (gcd_dvd_left n m)) theorem gcd_eq_left_iff_dvd {m n : ℕ} : m ∣ n ↔ gcd m n = m := ⟨λ h, by rw [gcd_rec, mod_eq_zero_of_dvd h, gcd_zero_left], λ h, h ▸ gcd_dvd_right m n⟩ theorem gcd_eq_right_iff_dvd {m n : ℕ} : m ∣ n ↔ gcd n m = m := by rw gcd_comm; apply gcd_eq_left_iff_dvd theorem gcd_assoc (m n k : ℕ) : gcd (gcd m n) k = gcd m (gcd n k) := dvd_antisymm (dvd_gcd (dvd.trans (gcd_dvd_left (gcd m n) k) (gcd_dvd_left m n)) (dvd_gcd (dvd.trans (gcd_dvd_left (gcd m n) k) (gcd_dvd_right m n)) (gcd_dvd_right (gcd m n) k))) (dvd_gcd (dvd_gcd (gcd_dvd_left m (gcd n k)) (dvd.trans (gcd_dvd_right m (gcd n k)) (gcd_dvd_left n k))) (dvd.trans (gcd_dvd_right m (gcd n k)) (gcd_dvd_right n k))) @[simp] theorem gcd_one_right (n : ℕ) : gcd n 1 = 1 := eq.trans (gcd_comm n 1) $ gcd_one_left n theorem gcd_mul_left (m n k : ℕ) : gcd (m * n) (m * k) = m * gcd n k := gcd.induction n k (λk, by repeat {rw mul_zero <|> rw gcd_zero_left}) (λk n H IH, by rwa [←mul_mod_mul_left, ←gcd_rec, ←gcd_rec] at IH) theorem gcd_mul_right (m n k : ℕ) : gcd (m * n) (k * n) = gcd m k * n := by rw [mul_comm m n, mul_comm k n, mul_comm (gcd m k) n, gcd_mul_left] theorem gcd_pos_of_pos_left {m : ℕ} (n : ℕ) (mpos : 0 < m) : 0 < gcd m n := pos_of_dvd_of_pos (gcd_dvd_left m n) mpos theorem gcd_pos_of_pos_right (m : ℕ) {n : ℕ} (npos : 0 < n) : 0 < gcd m n := pos_of_dvd_of_pos (gcd_dvd_right m n) npos theorem eq_zero_of_gcd_eq_zero_left {m n : ℕ} (H : gcd m n = 0) : m = 0 := or.elim (eq_zero_or_pos m) id (assume H1 : 0 < m, absurd (eq.symm H) (ne_of_lt (gcd_pos_of_pos_left _ H1))) theorem eq_zero_of_gcd_eq_zero_right {m n : ℕ} (H : gcd m n = 0) : n = 0 := by rw gcd_comm at H; exact eq_zero_of_gcd_eq_zero_left H theorem gcd_div {m n k : ℕ} (H1 : k ∣ m) (H2 : k ∣ n) : gcd (m / k) (n / k) = gcd m n / k := or.elim (eq_zero_or_pos k) (λk0, by rw [k0, nat.div_zero, nat.div_zero, nat.div_zero, gcd_zero_right]) (λH3, nat.eq_of_mul_eq_mul_right H3 $ by rw [ nat.div_mul_cancel (dvd_gcd H1 H2), ←gcd_mul_right, nat.div_mul_cancel H1, nat.div_mul_cancel H2]) theorem gcd_dvd_gcd_of_dvd_left {m k : ℕ} (n : ℕ) (H : m ∣ k) : gcd m n ∣ gcd k n := dvd_gcd (dvd.trans (gcd_dvd_left m n) H) (gcd_dvd_right m n) theorem gcd_dvd_gcd_of_dvd_right {m k : ℕ} (n : ℕ) (H : m ∣ k) : gcd n m ∣ gcd n k := dvd_gcd (gcd_dvd_left n m) (dvd.trans (gcd_dvd_right n m) H) theorem gcd_dvd_gcd_mul_left (m n k : ℕ) : gcd m n ∣ gcd (k * m) n := gcd_dvd_gcd_of_dvd_left _ (dvd_mul_left _ _) theorem gcd_dvd_gcd_mul_right (m n k : ℕ) : gcd m n ∣ gcd (m * k) n := gcd_dvd_gcd_of_dvd_left _ (dvd_mul_right _ _) theorem gcd_dvd_gcd_mul_left_right (m n k : ℕ) : gcd m n ∣ gcd m (k * n) := gcd_dvd_gcd_of_dvd_right _ (dvd_mul_left _ _) theorem gcd_dvd_gcd_mul_right_right (m n k : ℕ) : gcd m n ∣ gcd m (n * k) := gcd_dvd_gcd_of_dvd_right _ (dvd_mul_right _ _) theorem gcd_eq_left {m n : ℕ} (H : m ∣ n) : gcd m n = m := dvd_antisymm (gcd_dvd_left _ _) (dvd_gcd (dvd_refl _) H) theorem gcd_eq_right {m n : ℕ} (H : n ∣ m) : gcd m n = n := by rw [gcd_comm, gcd_eq_left H] @[simp] lemma gcd_mul_left_left (m n : ℕ) : gcd (m * n) n = n := dvd_antisymm (gcd_dvd_right _ _) (dvd_gcd (dvd_mul_left _ _) (dvd_refl _)) @[simp] lemma gcd_mul_left_right (m n : ℕ) : gcd n (m * n) = n := by rw [gcd_comm, gcd_mul_left_left] @[simp] lemma gcd_mul_right_left (m n : ℕ) : gcd (n * m) n = n := by rw [mul_comm, gcd_mul_left_left] @[simp] lemma gcd_mul_right_right (m n : ℕ) : gcd n (n * m) = n := by rw [gcd_comm, gcd_mul_right_left] @[simp] lemma gcd_gcd_self_right_left (m n : ℕ) : gcd m (gcd m n) = gcd m n := dvd_antisymm (gcd_dvd_right _ _) (dvd_gcd (gcd_dvd_left _ _) (dvd_refl _)) @[simp] lemma gcd_gcd_self_right_right (m n : ℕ) : gcd m (gcd n m) = gcd n m := by rw [gcd_comm n m, gcd_gcd_self_right_left] @[simp] lemma gcd_gcd_self_left_right (m n : ℕ) : gcd (gcd n m) m = gcd n m := by rw [gcd_comm, gcd_gcd_self_right_right] @[simp] lemma gcd_gcd_self_left_left (m n : ℕ) : gcd (gcd m n) m = gcd m n := by rw [gcd_comm m n, gcd_gcd_self_left_right] /-! ### `lcm` -/ theorem lcm_comm (m n : ℕ) : lcm m n = lcm n m := by delta lcm; rw [mul_comm, gcd_comm] theorem lcm_zero_left (m : ℕ) : lcm 0 m = 0 := by delta lcm; rw [zero_mul, nat.zero_div] theorem lcm_zero_right (m : ℕ) : lcm m 0 = 0 := lcm_comm 0 m ▸ lcm_zero_left m theorem lcm_one_left (m : ℕ) : lcm 1 m = m := by delta lcm; rw [one_mul, gcd_one_left, nat.div_one] theorem lcm_one_right (m : ℕ) : lcm m 1 = m := lcm_comm 1 m ▸ lcm_one_left m theorem lcm_self (m : ℕ) : lcm m m = m := or.elim (eq_zero_or_pos m) (λh, by rw [h, lcm_zero_left]) (λh, by delta lcm; rw [gcd_self, nat.mul_div_cancel _ h]) theorem dvd_lcm_left (m n : ℕ) : m ∣ lcm m n := dvd.intro (n / gcd m n) (nat.mul_div_assoc _ $ gcd_dvd_right m n).symm theorem dvd_lcm_right (m n : ℕ) : n ∣ lcm m n := lcm_comm n m ▸ dvd_lcm_left n m theorem gcd_mul_lcm (m n : ℕ) : gcd m n * lcm m n = m * n := by delta lcm; rw [nat.mul_div_cancel' (dvd.trans (gcd_dvd_left m n) (dvd_mul_right m n))] theorem lcm_dvd {m n k : ℕ} (H1 : m ∣ k) (H2 : n ∣ k) : lcm m n ∣ k := or.elim (eq_zero_or_pos k) (λh, by rw h; exact dvd_zero _) (λkpos, dvd_of_mul_dvd_mul_left (gcd_pos_of_pos_left n (pos_of_dvd_of_pos H1 kpos)) $ by rw [gcd_mul_lcm, ←gcd_mul_right, mul_comm n k]; exact dvd_gcd (mul_dvd_mul_left _ H2) (mul_dvd_mul_right H1 _)) theorem lcm_assoc (m n k : ℕ) : lcm (lcm m n) k = lcm m (lcm n k) := dvd_antisymm (lcm_dvd (lcm_dvd (dvd_lcm_left m (lcm n k)) (dvd.trans (dvd_lcm_left n k) (dvd_lcm_right m (lcm n k)))) (dvd.trans (dvd_lcm_right n k) (dvd_lcm_right m (lcm n k)))) (lcm_dvd (dvd.trans (dvd_lcm_left m n) (dvd_lcm_left (lcm m n) k)) (lcm_dvd (dvd.trans (dvd_lcm_right m n) (dvd_lcm_left (lcm m n) k)) (dvd_lcm_right (lcm m n) k))) /-! ### `coprime` -/ instance (m n : ℕ) : decidable (coprime m n) := by unfold coprime; apply_instance theorem coprime.gcd_eq_one {m n : ℕ} : coprime m n → gcd m n = 1 := id theorem coprime.symm {m n : ℕ} : coprime n m → coprime m n := (gcd_comm m n).trans theorem coprime_of_dvd {m n : ℕ} (H : ∀ k, 1 < k → k ∣ m → ¬ k ∣ n) : coprime m n := or.elim (eq_zero_or_pos (gcd m n)) (λg0, by rw [eq_zero_of_gcd_eq_zero_left g0, eq_zero_of_gcd_eq_zero_right g0] at H; exact false.elim (H 2 dec_trivial (dvd_zero _) (dvd_zero _))) (λ(g1 : 1 ≤ _), eq.symm $ (lt_or_eq_of_le g1).resolve_left $ λg2, H _ g2 (gcd_dvd_left _ _) (gcd_dvd_right _ _)) theorem coprime_of_dvd' {m n : ℕ} (H : ∀ k, k ∣ m → k ∣ n → k ∣ 1) : coprime m n := coprime_of_dvd $ λk kl km kn, not_le_of_gt kl $ le_of_dvd zero_lt_one (H k km kn) theorem coprime.dvd_of_dvd_mul_right {m n k : ℕ} (H1 : coprime k n) (H2 : k ∣ m * n) : k ∣ m := let t := dvd_gcd (dvd_mul_left k m) H2 in by rwa [gcd_mul_left, H1.gcd_eq_one, mul_one] at t theorem coprime.dvd_of_dvd_mul_left {m n k : ℕ} (H1 : coprime k m) (H2 : k ∣ m * n) : k ∣ n := by rw mul_comm at H2; exact H1.dvd_of_dvd_mul_right H2 theorem coprime.gcd_mul_left_cancel {k : ℕ} (m : ℕ) {n : ℕ} (H : coprime k n) : gcd (k * m) n = gcd m n := have H1 : coprime (gcd (k * m) n) k, by rw [coprime, gcd_assoc, H.symm.gcd_eq_one, gcd_one_right], dvd_antisymm (dvd_gcd (H1.dvd_of_dvd_mul_left (gcd_dvd_left _ _)) (gcd_dvd_right _ _)) (gcd_dvd_gcd_mul_left _ _ _) theorem coprime.gcd_mul_right_cancel (m : ℕ) {k n : ℕ} (H : coprime k n) : gcd (m * k) n = gcd m n := by rw [mul_comm m k, H.gcd_mul_left_cancel m] theorem coprime.gcd_mul_left_cancel_right {k m : ℕ} (n : ℕ) (H : coprime k m) : gcd m (k * n) = gcd m n := by rw [gcd_comm m n, gcd_comm m (k * n), H.gcd_mul_left_cancel n] theorem coprime.gcd_mul_right_cancel_right {k m : ℕ} (n : ℕ) (H : coprime k m) : gcd m (n * k) = gcd m n := by rw [mul_comm n k, H.gcd_mul_left_cancel_right n] theorem coprime_div_gcd_div_gcd {m n : ℕ} (H : 0 < gcd m n) : coprime (m / gcd m n) (n / gcd m n) := by delta coprime; rw [gcd_div (gcd_dvd_left m n) (gcd_dvd_right m n), nat.div_self H] theorem not_coprime_of_dvd_of_dvd {m n d : ℕ} (dgt1 : 1 < d) (Hm : d ∣ m) (Hn : d ∣ n) : ¬ coprime m n := λ (co : gcd m n = 1), not_lt_of_ge (le_of_dvd zero_lt_one $ by rw ←co; exact dvd_gcd Hm Hn) dgt1 theorem exists_coprime {m n : ℕ} (H : 0 < gcd m n) : ∃ m' n', coprime m' n' ∧ m = m' * gcd m n ∧ n = n' * gcd m n := ⟨_, _, coprime_div_gcd_div_gcd H, (nat.div_mul_cancel (gcd_dvd_left m n)).symm, (nat.div_mul_cancel (gcd_dvd_right m n)).symm⟩ theorem exists_coprime' {m n : ℕ} (H : 0 < gcd m n) : ∃ g m' n', 0 < g ∧ coprime m' n' ∧ m = m' * g ∧ n = n' * g := let ⟨m', n', h⟩ := exists_coprime H in ⟨_, m', n', H, h⟩ theorem coprime.mul {m n k : ℕ} (H1 : coprime m k) (H2 : coprime n k) : coprime (m * n) k := (H1.gcd_mul_left_cancel n).trans H2 theorem coprime.mul_right {k m n : ℕ} (H1 : coprime k m) (H2 : coprime k n) : coprime k (m * n) := (H1.symm.mul H2.symm).symm theorem coprime.coprime_dvd_left {m k n : ℕ} (H1 : m ∣ k) (H2 : coprime k n) : coprime m n := eq_one_of_dvd_one (by delta coprime at H2; rw ← H2; exact gcd_dvd_gcd_of_dvd_left _ H1) theorem coprime.coprime_dvd_right {m k n : ℕ} (H1 : n ∣ m) (H2 : coprime k m) : coprime k n := (H2.symm.coprime_dvd_left H1).symm theorem coprime.coprime_mul_left {k m n : ℕ} (H : coprime (k * m) n) : coprime m n := H.coprime_dvd_left (dvd_mul_left _ _) theorem coprime.coprime_mul_right {k m n : ℕ} (H : coprime (m * k) n) : coprime m n := H.coprime_dvd_left (dvd_mul_right _ _) theorem coprime.coprime_mul_left_right {k m n : ℕ} (H : coprime m (k * n)) : coprime m n := H.coprime_dvd_right (dvd_mul_left _ _) theorem coprime.coprime_mul_right_right {k m n : ℕ} (H : coprime m (n * k)) : coprime m n := H.coprime_dvd_right (dvd_mul_right _ _) theorem coprime.coprime_div_left {m n a : ℕ} (cmn : coprime m n) (dvd : a ∣ m) : coprime (m / a) n := begin by_cases a_split : (a = 0), { subst a_split, rw zero_dvd_iff at dvd, simpa [dvd] using cmn, }, { rcases dvd with ⟨k, rfl⟩, rw nat.mul_div_cancel_left _ (nat.pos_of_ne_zero a_split), exact coprime.coprime_mul_left cmn, }, end theorem coprime.coprime_div_right {m n a : ℕ} (cmn : coprime m n) (dvd : a ∣ n) : coprime m (n / a) := (coprime.coprime_div_left cmn.symm dvd).symm lemma coprime_mul_iff_left {k m n : ℕ} : coprime (m * n) k ↔ coprime m k ∧ coprime n k := ⟨λ h, ⟨coprime.coprime_mul_right h, coprime.coprime_mul_left h⟩, λ ⟨h, _⟩, by rwa [coprime, coprime.gcd_mul_left_cancel n h]⟩ lemma coprime_mul_iff_right {k m n : ℕ} : coprime k (m * n) ↔ coprime k m ∧ coprime k n := by { repeat { rw [coprime, nat.gcd_comm k] }, exact coprime_mul_iff_left } lemma coprime.gcd_left (k : ℕ) {m n : ℕ} (hmn : coprime m n) : coprime (gcd k m) n := hmn.coprime_dvd_left $ gcd_dvd_right k m lemma coprime.gcd_right (k : ℕ) {m n : ℕ} (hmn : coprime m n) : coprime m (gcd k n) := hmn.coprime_dvd_right $ gcd_dvd_right k n lemma coprime.gcd_both (k l : ℕ) {m n : ℕ} (hmn : coprime m n) : coprime (gcd k m) (gcd l n) := (hmn.gcd_left k).gcd_right l lemma coprime.mul_dvd_of_dvd_of_dvd {a n m : ℕ} (hmn : coprime m n) (hm : m ∣ a) (hn : n ∣ a) : m * n ∣ a := let ⟨k, hk⟩ := hm in hk.symm ▸ mul_dvd_mul_left _ (hmn.symm.dvd_of_dvd_mul_left (hk ▸ hn)) theorem coprime_one_left : ∀ n, coprime 1 n := gcd_one_left theorem coprime_one_right : ∀ n, coprime n 1 := gcd_one_right theorem coprime.pow_left {m k : ℕ} (n : ℕ) (H1 : coprime m k) : coprime (m ^ n) k := nat.rec_on n (coprime_one_left _) (λn IH, H1.mul IH) theorem coprime.pow_right {m k : ℕ} (n : ℕ) (H1 : coprime k m) : coprime k (m ^ n) := (H1.symm.pow_left n).symm theorem coprime.pow {k l : ℕ} (m n : ℕ) (H1 : coprime k l) : coprime (k ^ m) (l ^ n) := (H1.pow_left _).pow_right _ theorem coprime.eq_one_of_dvd {k m : ℕ} (H : coprime k m) (d : k ∣ m) : k = 1 := by rw [← H.gcd_eq_one, gcd_eq_left d] @[simp] theorem coprime_zero_left (n : ℕ) : coprime 0 n ↔ n = 1 := by simp [coprime] @[simp] theorem coprime_zero_right (n : ℕ) : coprime n 0 ↔ n = 1 := by simp [coprime] @[simp] theorem coprime_one_left_iff (n : ℕ) : coprime 1 n ↔ true := by simp [coprime] @[simp] theorem coprime_one_right_iff (n : ℕ) : coprime n 1 ↔ true := by simp [coprime] @[simp] theorem coprime_self (n : ℕ) : coprime n n ↔ n = 1 := by simp [coprime] /-- Represent a divisor of `m * n` as a product of a divisor of `m` and a divisor of `n`. -/ def prod_dvd_and_dvd_of_dvd_prod {m n k : ℕ} (H : k ∣ m * n) : { d : {m' // m' ∣ m} × {n' // n' ∣ n} // k = d.1 * d.2 } := begin cases h0 : (gcd k m), case nat.zero { have : k = 0 := eq_zero_of_gcd_eq_zero_left h0, subst this, have : m = 0 := eq_zero_of_gcd_eq_zero_right h0, subst this, exact ⟨⟨⟨0, dvd_refl 0⟩, ⟨n, dvd_refl n⟩⟩, (zero_mul n).symm⟩ }, case nat.succ : tmp { have hpos : 0 < gcd k m := h0.symm ▸ nat.zero_lt_succ _; clear h0 tmp, have hd : gcd k m * (k / gcd k m) = k := (nat.mul_div_cancel' (gcd_dvd_left k m)), refine ⟨⟨⟨gcd k m, gcd_dvd_right k m⟩, ⟨k / gcd k m, _⟩⟩, hd.symm⟩, apply dvd_of_mul_dvd_mul_left hpos, rw [hd, ← gcd_mul_right], exact dvd_gcd (dvd_mul_right _ _) H } end theorem gcd_mul_dvd_mul_gcd (k m n : ℕ) : gcd k (m * n) ∣ gcd k m * gcd k n := begin rcases (prod_dvd_and_dvd_of_dvd_prod $ gcd_dvd_right k (m * n)) with ⟨⟨⟨m', hm'⟩, ⟨n', hn'⟩⟩, h⟩, replace h : gcd k (m * n) = m' * n' := h, rw h, have hm'n' : m' * n' ∣ k := h ▸ gcd_dvd_left _ _, apply mul_dvd_mul, { have hm'k : m' ∣ k := dvd_trans (dvd_mul_right m' n') hm'n', exact dvd_gcd hm'k hm' }, { have hn'k : n' ∣ k := dvd_trans (dvd_mul_left n' m') hm'n', exact dvd_gcd hn'k hn' } end theorem coprime.gcd_mul (k : ℕ) {m n : ℕ} (h : coprime m n) : gcd k (m * n) = gcd k m * gcd k n := dvd_antisymm (gcd_mul_dvd_mul_gcd k m n) ((h.gcd_both k k).mul_dvd_of_dvd_of_dvd (gcd_dvd_gcd_mul_right_right _ _ _) (gcd_dvd_gcd_mul_left_right _ _ _)) theorem pow_dvd_pow_iff {a b n : ℕ} (n0 : 0 < n) : a ^ n ∣ b ^ n ↔ a ∣ b := begin refine ⟨λ h, _, λ h, pow_dvd_pow_of_dvd h _⟩, cases eq_zero_or_pos (gcd a b) with g0 g0, { simp [eq_zero_of_gcd_eq_zero_right g0] }, rcases exists_coprime' g0 with ⟨g, a', b', g0', co, rfl, rfl⟩, rw [mul_pow, mul_pow] at h, replace h := dvd_of_mul_dvd_mul_right (pos_pow_of_pos _ g0') h, have := pow_dvd_pow a' n0, rw [pow_one, (co.pow n n).eq_one_of_dvd h] at this, simp [eq_one_of_dvd_one this] end end nat
91c829b497927243608bdfaa749e5dedb5799ffa
69d4931b605e11ca61881fc4f66db50a0a875e39
/src/linear_algebra/finsupp.lean
26628fd6aa530d2cbabdc712b53942cdef06ba3a
[ "Apache-2.0" ]
permissive
abentkamp/mathlib
d9a75d291ec09f4637b0f30cc3880ffb07549ee5
5360e476391508e092b5a1e5210bd0ed22dc0755
refs/heads/master
1,682,382,954,948
1,622,106,077,000
1,622,106,077,000
149,285,665
0
0
null
null
null
null
UTF-8
Lean
false
false
32,917
lean
/- Copyright (c) 2019 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl -/ import data.finsupp.basic import linear_algebra.basic /-! # Properties of the module `α →₀ M` Given an `R`-module `M`, the `R`-module structure on `α →₀ M` is defined in `data.finsupp.basic`. In this file we define `finsupp.supported s` to be the set `{f : α →₀ M | f.support ⊆ s}` interpreted as a submodule of `α →₀ M`. We also define `linear_map` versions of various maps: * `finsupp.lsingle a : M →ₗ[R] ι →₀ M`: `finsupp.single a` as a linear map; * `finsupp.lapply a : (ι →₀ M) →ₗ[R] M`: the map `λ f, f a` as a linear map; * `finsupp.lsubtype_domain (s : set α) : (α →₀ M) →ₗ[R] (s →₀ M)`: restriction to a subtype as a linear map; * `finsupp.restrict_dom`: `finsupp.filter` as a linear map to `finsupp.supported s`; * `finsupp.lsum`: `finsupp.sum` or `finsupp.lift_add_hom` as a `linear_map`; * `finsupp.total α M R (v : ι → M)`: sends `l : ι → R` to the linear combination of `v i` with coefficients `l i`; * `finsupp.total_on`: a restricted version of `finsupp.total` with domain `finsupp.supported R R s` and codomain `submodule.span R (v '' s)`; * `finsupp.supported_equiv_finsupp`: a linear equivalence between the functions `α →₀ M` supported on `s` and the functions `s →₀ M`; * `finsupp.lmap_domain`: a linear map version of `finsupp.map_domain`; * `finsupp.dom_lcongr`: a `linear_equiv` version of `finsupp.dom_congr`; * `finsupp.congr`: if the sets `s` and `t` are equivalent, then `supported M R s` is equivalent to `supported M R t`; * `finsupp.lcongr`: a `linear_equiv`alence between `α →₀ M` and `β →₀ N` constructed using `e : α ≃ β` and `e' : M ≃ₗ[R] N`. ## Tags function with finite support, module, linear algebra -/ noncomputable theory open set linear_map submodule open_locale classical big_operators namespace finsupp variables {α : Type*} {M : Type*} {N : Type*} {P : Type*} {R : Type*} {S : Type*} variables [semiring R] [semiring S] [add_comm_monoid M] [module R M] variables [add_comm_monoid N] [module R N] variables [add_comm_monoid P] [module R P] /-- Interpret `finsupp.single a` as a linear map. -/ def lsingle (a : α) : M →ₗ[R] (α →₀ M) := { map_smul' := assume a b, (smul_single _ _ _).symm, ..finsupp.single_add_hom a } /-- Two `R`-linear maps from `finsupp X M` which agree on each `single x y` agree everywhere. -/ lemma lhom_ext ⦃φ ψ : (α →₀ M) →ₗ[R] N⦄ (h : ∀ a b, φ (single a b) = ψ (single a b)) : φ = ψ := linear_map.to_add_monoid_hom_injective $ add_hom_ext h /-- Two `R`-linear maps from `finsupp X M` which agree on each `single x y` agree everywhere. We formulate this fact using equality of linear maps `φ.comp (lsingle a)` and `ψ.comp (lsingle a)` so that the `ext` tactic can apply a type-specific extensionality lemma to prove equality of these maps. E.g., if `M = R`, then it suffices to verify `φ (single a 1) = ψ (single a 1)`. -/ @[ext] lemma lhom_ext' ⦃φ ψ : (α →₀ M) →ₗ[R] N⦄ (h : ∀ a, φ.comp (lsingle a) = ψ.comp (lsingle a)) : φ = ψ := lhom_ext $ λ a, linear_map.congr_fun (h a) /-- Interpret `λ (f : α →₀ M), f a` as a linear map. -/ def lapply (a : α) : (α →₀ M) →ₗ[R] M := { map_smul' := assume a b, rfl, ..finsupp.apply_add_hom a } section lsubtype_domain variables (s : set α) /-- Interpret `finsupp.subtype_domain s` as a linear map. -/ def lsubtype_domain : (α →₀ M) →ₗ[R] (s →₀ M) := ⟨subtype_domain (λx, x ∈ s), assume a b, subtype_domain_add, assume c a, ext $ assume a, rfl⟩ lemma lsubtype_domain_apply (f : α →₀ M) : (lsubtype_domain s : (α →₀ M) →ₗ[R] (s →₀ M)) f = subtype_domain (λx, x ∈ s) f := rfl end lsubtype_domain @[simp] lemma lsingle_apply (a : α) (b : M) : (lsingle a : M →ₗ[R] (α →₀ M)) b = single a b := rfl @[simp] lemma lapply_apply (a : α) (f : α →₀ M) : (lapply a : (α →₀ M) →ₗ[R] M) f = f a := rfl @[simp] lemma ker_lsingle (a : α) : (lsingle a : M →ₗ[R] (α →₀ M)).ker = ⊥ := ker_eq_bot_of_injective (single_injective a) lemma lsingle_range_le_ker_lapply (s t : set α) (h : disjoint s t) : (⨆a∈s, (lsingle a : M →ₗ[R] (α →₀ M)).range) ≤ (⨅a∈t, ker (lapply a)) := begin refine supr_le (assume a₁, supr_le $ assume h₁, range_le_iff_comap.2 _), simp only [(ker_comp _ _).symm, eq_top_iff, set_like.le_def, mem_ker, comap_infi, mem_infi], assume b hb a₂ h₂, have : a₁ ≠ a₂ := assume eq, h ⟨h₁, eq.symm ▸ h₂⟩, exact single_eq_of_ne this end lemma infi_ker_lapply_le_bot : (⨅a, ker (lapply a : (α →₀ M) →ₗ[R] M)) ≤ ⊥ := begin simp only [set_like.le_def, mem_infi, mem_ker, mem_bot, lapply_apply], exact assume a h, finsupp.ext h end lemma supr_lsingle_range : (⨆a, (lsingle a : M →ₗ[R] (α →₀ M)).range) = ⊤ := begin refine (eq_top_iff.2 $ set_like.le_def.2 $ assume f _, _), rw [← sum_single f], exact sum_mem _ (assume a ha, submodule.mem_supr_of_mem a ⟨_, rfl⟩), end lemma disjoint_lsingle_lsingle (s t : set α) (hs : disjoint s t) : disjoint (⨆a∈s, (lsingle a : M →ₗ[R] (α →₀ M)).range) (⨆a∈t, (lsingle a).range) := begin refine disjoint.mono (lsingle_range_le_ker_lapply _ _ $ disjoint_compl_right) (lsingle_range_le_ker_lapply _ _ $ disjoint_compl_right) (le_trans (le_infi $ assume i, _) infi_ker_lapply_le_bot), classical, by_cases his : i ∈ s, { by_cases hit : i ∈ t, { exact (hs ⟨his, hit⟩).elim }, exact inf_le_right_of_le (infi_le_of_le i $ infi_le _ hit) }, exact inf_le_left_of_le (infi_le_of_le i $ infi_le _ his) end lemma span_single_image (s : set M) (a : α) : submodule.span R (single a '' s) = (submodule.span R s).map (lsingle a) := by rw ← span_image; refl variables (M R) /-- `finsupp.supported M R s` is the `R`-submodule of all `p : α →₀ M` such that `p.support ⊆ s`. -/ def supported (s : set α) : submodule R (α →₀ M) := begin refine ⟨ {p | ↑p.support ⊆ s }, _, _, _ ⟩, { simp only [subset_def, finset.mem_coe, set.mem_set_of_eq, mem_support_iff, zero_apply], assume h ha, exact (ha rfl).elim }, { assume p q hp hq, refine subset.trans (subset.trans (finset.coe_subset.2 support_add) _) (union_subset hp hq), rw [finset.coe_union] }, { assume a p hp, refine subset.trans (finset.coe_subset.2 support_smul) hp } end variables {M} lemma mem_supported {s : set α} (p : α →₀ M) : p ∈ (supported M R s) ↔ ↑p.support ⊆ s := iff.rfl lemma mem_supported' {s : set α} (p : α →₀ M) : p ∈ supported M R s ↔ ∀ x ∉ s, p x = 0 := by haveI := classical.dec_pred (λ (x : α), x ∈ s); simp [mem_supported, set.subset_def, not_imp_comm] lemma single_mem_supported {s : set α} {a : α} (b : M) (h : a ∈ s) : single a b ∈ supported M R s := set.subset.trans support_single_subset (finset.singleton_subset_set_iff.2 h) lemma supported_eq_span_single (s : set α) : supported R R s = span R ((λ i, single i 1) '' s) := begin refine (span_eq_of_le _ _ (set_like.le_def.2 $ λ l hl, _)).symm, { rintro _ ⟨_, hp, rfl ⟩ , exact single_mem_supported R 1 hp }, { rw ← l.sum_single, refine sum_mem _ (λ i il, _), convert @smul_mem R (α →₀ R) _ _ _ _ (single i 1) (l i) _, { simp }, apply subset_span, apply set.mem_image_of_mem _ (hl il) } end variables (M R) /-- Interpret `finsupp.filter s` as a linear map from `α →₀ M` to `supported M R s`. -/ def restrict_dom (s : set α) : (α →₀ M) →ₗ supported M R s := linear_map.cod_restrict _ { to_fun := filter (∈ s), map_add' := λ l₁ l₂, filter_add, map_smul' := λ a l, filter_smul } (λ l, (mem_supported' _ _).2 $ λ x, filter_apply_neg (∈ s) l) variables {M R} section @[simp] theorem restrict_dom_apply (s : set α) (l : α →₀ M) : ((restrict_dom M R s : (α →₀ M) →ₗ supported M R s) l : α →₀ M) = finsupp.filter (∈ s) l := rfl end theorem restrict_dom_comp_subtype (s : set α) : (restrict_dom M R s).comp (submodule.subtype _) = linear_map.id := begin ext l a, by_cases a ∈ s; simp [h], exact ((mem_supported' R l.1).1 l.2 a h).symm end theorem range_restrict_dom (s : set α) : (restrict_dom M R s).range = ⊤ := range_eq_top.2 $ function.right_inverse.surjective $ linear_map.congr_fun (restrict_dom_comp_subtype s) theorem supported_mono {s t : set α} (st : s ⊆ t) : supported M R s ≤ supported M R t := λ l h, set.subset.trans h st @[simp] theorem supported_empty : supported M R (∅ : set α) = ⊥ := eq_bot_iff.2 $ λ l h, (submodule.mem_bot R).2 $ by ext; simp [*, mem_supported'] at * @[simp] theorem supported_univ : supported M R (set.univ : set α) = ⊤ := eq_top_iff.2 $ λ l _, set.subset_univ _ theorem supported_Union {δ : Type*} (s : δ → set α) : supported M R (⋃ i, s i) = ⨆ i, supported M R (s i) := begin refine le_antisymm _ (supr_le $ λ i, supported_mono $ set.subset_Union _ _), haveI := classical.dec_pred (λ x, x ∈ (⋃ i, s i)), suffices : ((submodule.subtype _).comp (restrict_dom M R (⋃ i, s i))).range ≤ ⨆ i, supported M R (s i), { rwa [linear_map.range_comp, range_restrict_dom, map_top, range_subtype] at this }, rw [range_le_iff_comap, eq_top_iff], rintro l ⟨⟩, apply finsupp.induction l, {exact zero_mem _}, refine λ x a l hl a0, add_mem _ _, by_cases (∃ i, x ∈ s i); simp [h], { cases h with i hi, exact le_supr (λ i, supported M R (s i)) i (single_mem_supported R _ hi) } end theorem supported_union (s t : set α) : supported M R (s ∪ t) = supported M R s ⊔ supported M R t := by erw [set.union_eq_Union, supported_Union, supr_bool_eq]; refl theorem supported_Inter {ι : Type*} (s : ι → set α) : supported M R (⋂ i, s i) = ⨅ i, supported M R (s i) := submodule.ext $ λ x, by simp [mem_supported, subset_Inter_iff] theorem supported_inter (s t : set α) : supported M R (s ∩ t) = supported M R s ⊓ supported M R t := by rw [set.inter_eq_Inter, supported_Inter, infi_bool_eq]; refl theorem disjoint_supported_supported {s t : set α} (h : disjoint s t) : disjoint (supported M R s) (supported M R t) := disjoint_iff.2 $ by rw [← supported_inter, disjoint_iff_inter_eq_empty.1 h, supported_empty] theorem disjoint_supported_supported_iff [nontrivial M] {s t : set α} : disjoint (supported M R s) (supported M R t) ↔ disjoint s t := begin refine ⟨λ h x hx, _, disjoint_supported_supported⟩, rcases exists_ne (0 : M) with ⟨y, hy⟩, have := h ⟨single_mem_supported R y hx.1, single_mem_supported R y hx.2⟩, rw [mem_bot, single_eq_zero] at this, exact hy this end /-- Interpret `finsupp.restrict_support_equiv` as a linear equivalence between `supported M R s` and `s →₀ M`. -/ def supported_equiv_finsupp (s : set α) : (supported M R s) ≃ₗ[R] (s →₀ M) := begin let F : (supported M R s) ≃ (s →₀ M) := restrict_support_equiv s M, refine F.to_linear_equiv _, have : (F : (supported M R s) → (↥s →₀ M)) = ((lsubtype_domain s : (α →₀ M) →ₗ[R] (s →₀ M)).comp (submodule.subtype (supported M R s))) := rfl, rw this, exact linear_map.is_linear _ end section lsum variables (S) [module S N] [smul_comm_class R S N] /-- Lift a family of linear maps `M →ₗ[R] N` indexed by `x : α` to a linear map from `α →₀ M` to `N` using `finsupp.sum`. This is an upgraded version of `finsupp.lift_add_hom`. See note [bundled maps over different rings] for why separate `R` and `S` semirings are used. -/ def lsum : (α → M →ₗ[R] N) ≃ₗ[S] ((α →₀ M) →ₗ[R] N) := { to_fun := λ F, { to_fun := λ d, d.sum (λ i, F i), map_add' := (lift_add_hom (λ x, (F x).to_add_monoid_hom)).map_add, map_smul' := λ c f, by simp [sum_smul_index', smul_sum] }, inv_fun := λ F x, F.comp (lsingle x), left_inv := λ F, by { ext x y, simp }, right_inv := λ F, by { ext x y, simp }, map_add' := λ F G, by { ext x y, simp }, map_smul' := λ F G, by { ext x y, simp } } @[simp] lemma coe_lsum (f : α → M →ₗ[R] N) : (lsum S f : (α →₀ M) → N) = λ d, d.sum (λ i, f i) := rfl theorem lsum_apply (f : α → M →ₗ[R] N) (l : α →₀ M) : finsupp.lsum S f l = l.sum (λ b, f b) := rfl theorem lsum_single (f : α → M →ₗ[R] N) (i : α) (m : M) : finsupp.lsum S f (finsupp.single i m) = f i m := finsupp.sum_single_index (f i).map_zero theorem lsum_symm_apply (f : (α →₀ M) →ₗ[R] N) (x : α) : (lsum S).symm f x = f.comp (lsingle x) := rfl end lsum section variables (M) (R) (X : Type*) /-- A slight rearrangement from `lsum` gives us the bijection underlying the free-forgetful adjunction for R-modules. -/ noncomputable def lift : (X → M) ≃+ ((X →₀ R) →ₗ[R] M) := (add_equiv.arrow_congr (equiv.refl X) (ring_lmap_equiv_self R M ℕ).to_add_equiv.symm).trans (lsum _ : _ ≃ₗ[ℕ] _).to_add_equiv @[simp] lemma lift_symm_apply (f) (x) : ((lift M R X).symm f) x = f (single x 1) := rfl @[simp] lemma lift_apply (f) (g) : ((lift M R X) f) g = g.sum (λ x r, r • f x) := rfl end section lmap_domain variables {α' : Type*} {α'' : Type*} (M R) /-- Interpret `finsupp.map_domain` as a linear map. -/ def lmap_domain (f : α → α') : (α →₀ M) →ₗ[R] (α' →₀ M) := ⟨map_domain f, assume a b, map_domain_add, map_domain_smul⟩ @[simp] theorem lmap_domain_apply (f : α → α') (l : α →₀ M) : (lmap_domain M R f : (α →₀ M) →ₗ[R] (α' →₀ M)) l = map_domain f l := rfl @[simp] theorem lmap_domain_id : (lmap_domain M R id : (α →₀ M) →ₗ[R] α →₀ M) = linear_map.id := linear_map.ext $ λ l, map_domain_id theorem lmap_domain_comp (f : α → α') (g : α' → α'') : lmap_domain M R (g ∘ f) = (lmap_domain M R g).comp (lmap_domain M R f) := linear_map.ext $ λ l, map_domain_comp theorem supported_comap_lmap_domain (f : α → α') (s : set α') : supported M R (f ⁻¹' s) ≤ (supported M R s).comap (lmap_domain M R f) := λ l (hl : ↑l.support ⊆ f ⁻¹' s), show ↑(map_domain f l).support ⊆ s, begin rw [← set.image_subset_iff, ← finset.coe_image] at hl, exact set.subset.trans map_domain_support hl end theorem lmap_domain_supported [nonempty α] (f : α → α') (s : set α) : (supported M R s).map (lmap_domain M R f) = supported M R (f '' s) := begin inhabit α, refine le_antisymm (map_le_iff_le_comap.2 $ le_trans (supported_mono $ set.subset_preimage_image _ _) (supported_comap_lmap_domain _ _ _ _)) _, intros l hl, refine ⟨(lmap_domain M R (function.inv_fun_on f s) : (α' →₀ M) →ₗ α →₀ M) l, λ x hx, _, _⟩, { rcases finset.mem_image.1 (map_domain_support hx) with ⟨c, hc, rfl⟩, exact function.inv_fun_on_mem (by simpa using hl hc) }, { rw [← linear_map.comp_apply, ← lmap_domain_comp], refine (map_domain_congr $ λ c hc, _).trans map_domain_id, exact function.inv_fun_on_eq (by simpa using hl hc) } end theorem lmap_domain_disjoint_ker (f : α → α') {s : set α} (H : ∀ a b ∈ s, f a = f b → a = b) : disjoint (supported M R s) (lmap_domain M R f).ker := begin rintro l ⟨h₁, h₂⟩, rw [set_like.mem_coe, mem_ker, lmap_domain_apply, map_domain] at h₂, simp, ext x, haveI := classical.dec_pred (λ x, x ∈ s), by_cases xs : x ∈ s, { have : finsupp.sum l (λ a, finsupp.single (f a)) (f x) = 0, {rw h₂, refl}, rw [finsupp.sum_apply, finsupp.sum, finset.sum_eq_single x] at this, { simpa [finsupp.single_apply] }, { intros y hy xy, simp [mt (H _ _ (h₁ hy) xs) xy] }, { simp {contextual := tt} } }, { by_contra h, exact xs (h₁ $ finsupp.mem_support_iff.2 h) } end end lmap_domain section total variables (α) {α' : Type*} (M) {M' : Type*} (R) [add_comm_monoid M'] [module R M'] (v : α → M) {v' : α' → M'} /-- Interprets (l : α →₀ R) as linear combination of the elements in the family (v : α → M) and evaluates this linear combination. -/ protected def total : (α →₀ R) →ₗ[R] M := finsupp.lsum ℕ (λ i, linear_map.id.smul_right (v i)) variables {α M v} theorem total_apply (l : α →₀ R) : finsupp.total α M R v l = l.sum (λ i a, a • v i) := rfl theorem total_apply_of_mem_supported {l : α →₀ R} {s : finset α} (hs : l ∈ supported R R (↑s : set α)) : finsupp.total α M R v l = s.sum (λ i, l i • v i) := finset.sum_subset hs $ λ x _ hxg, show l x • v x = 0, by rw [not_mem_support_iff.1 hxg, zero_smul] @[simp] theorem total_single (c : R) (a : α) : finsupp.total α M R v (single a c) = c • (v a) := by simp [total_apply, sum_single_index] theorem total_unique [unique α] (l : α →₀ R) (v) : finsupp.total α M R v l = l (default α) • v (default α) := by rw [← total_single, ← unique_single l] theorem total_range (h : function.surjective v) : (finsupp.total α M R v).range = ⊤ := begin apply range_eq_top.2, intros x, apply exists.elim (h x), exact λ i hi, ⟨single i 1, by simp [hi]⟩ end lemma range_total : (finsupp.total α M R v).range = span R (range v) := begin ext x, split, { intros hx, rw [linear_map.mem_range] at hx, rcases hx with ⟨l, hl⟩, rw ← hl, rw finsupp.total_apply, unfold finsupp.sum, apply sum_mem (span R (range v)), exact λ i hi, submodule.smul_mem _ _ (subset_span (mem_range_self i)) }, { apply span_le.2, intros x hx, rcases hx with ⟨i, hi⟩, rw [set_like.mem_coe, linear_map.mem_range], use finsupp.single i 1, simp [hi] } end theorem lmap_domain_total (f : α → α') (g : M →ₗ[R] M') (h : ∀ i, g (v i) = v' (f i)) : (finsupp.total α' M' R v').comp (lmap_domain R R f) = g.comp (finsupp.total α M R v) := by ext l; simp [total_apply, finsupp.sum_map_domain_index, add_smul, h] theorem total_emb_domain (f : α ↪ α') (l : α →₀ R) : (finsupp.total α' M' R v') (emb_domain f l) = (finsupp.total α M' R (v' ∘ f)) l := by simp [total_apply, finsupp.sum, support_emb_domain, emb_domain_apply] theorem total_map_domain (f : α → α') (hf : function.injective f) (l : α →₀ R) : (finsupp.total α' M' R v') (map_domain f l) = (finsupp.total α M' R (v' ∘ f)) l := begin have : map_domain f l = emb_domain ⟨f, hf⟩ l, { rw emb_domain_eq_map_domain ⟨f, hf⟩, refl }, rw this, apply total_emb_domain R ⟨f, hf⟩ l end theorem span_eq_map_total (s : set α): span R (v '' s) = submodule.map (finsupp.total α M R v) (supported R R s) := begin apply span_eq_of_le, { intros x hx, rw set.mem_image at hx, apply exists.elim hx, intros i hi, exact ⟨_, finsupp.single_mem_supported R 1 hi.1, by simp [hi.2]⟩ }, { refine map_le_iff_le_comap.2 (λ z hz, _), have : ∀i, z i • v i ∈ span R (v '' s), { intro c, haveI := classical.dec_pred (λ x, x ∈ s), by_cases c ∈ s, { exact smul_mem _ _ (subset_span (set.mem_image_of_mem _ h)) }, { simp [(finsupp.mem_supported' R _).1 hz _ h] } }, refine sum_mem _ _, simp [this] } end theorem mem_span_iff_total {s : set α} {x : M} : x ∈ span R (v '' s) ↔ ∃ l ∈ supported R R s, finsupp.total α M R v l = x := by rw span_eq_map_total; simp variables (α) (M) (v) /-- `finsupp.total_on M v s` interprets `p : α →₀ R` as a linear combination of a subset of the vectors in `v`, mapping it to the span of those vectors. The subset is indicated by a set `s : set α` of indices. -/ protected def total_on (s : set α) : supported R R s →ₗ[R] span R (v '' s) := linear_map.cod_restrict _ ((finsupp.total _ _ _ v).comp (submodule.subtype (supported R R s))) $ λ ⟨l, hl⟩, (mem_span_iff_total _).2 ⟨l, hl, rfl⟩ variables {α} {M} {v} theorem total_on_range (s : set α) : (finsupp.total_on α M R v s).range = ⊤ := begin rw [finsupp.total_on, linear_map.range_eq_map, linear_map.map_cod_restrict, ← linear_map.range_le_iff_comap, range_subtype, map_top, linear_map.range_comp, range_subtype], exact (span_eq_map_total _ _).le end theorem total_comp (f : α' → α) : (finsupp.total α' M R (v ∘ f)) = (finsupp.total α M R v).comp (lmap_domain R R f) := by { ext, simp [total_apply] } lemma total_comap_domain (f : α → α') (l : α' →₀ R) (hf : set.inj_on f (f ⁻¹' ↑l.support)) : finsupp.total α M R v (finsupp.comap_domain f l hf) = (l.support.preimage f hf).sum (λ i, (l (f i)) • (v i)) := by rw finsupp.total_apply; refl lemma total_on_finset {s : finset α} {f : α → R} (g : α → M) (hf : ∀ a, f a ≠ 0 → a ∈ s): finsupp.total α M R g (finsupp.on_finset s f hf) = finset.sum s (λ (x : α), f x • g x) := begin simp only [finsupp.total_apply, finsupp.sum, finsupp.on_finset_apply, finsupp.support_on_finset], rw finset.sum_filter_of_ne, intros x hx h, contrapose! h, simp [h], end end total /-- An equivalence of domains induces a linear equivalence of finitely supported functions. This is `finsupp.dom_congr` as a `linear_equiv`.-/ protected def dom_lcongr {α₁ α₂ : Type*} (e : α₁ ≃ α₂) : (α₁ →₀ M) ≃ₗ[R] (α₂ →₀ M) := (finsupp.dom_congr e : (α₁ →₀ M) ≃+ (α₂ →₀ M)).to_linear_equiv (lmap_domain M R e).map_smul @[simp] lemma dom_lcongr_apply {α₁ : Type*} {α₂ : Type*} (e : α₁ ≃ α₂) (v : α₁ →₀ M) : (finsupp.dom_lcongr e : _ ≃ₗ[R] _) v = finsupp.dom_congr e v := rfl @[simp] lemma dom_lcongr_refl : finsupp.dom_lcongr (equiv.refl α) = linear_equiv.refl R (α →₀ M) := linear_equiv.ext $ λ _, map_domain_id lemma dom_lcongr_trans {α₁ α₂ α₃ : Type*} (f : α₁ ≃ α₂) (f₂ : α₂ ≃ α₃) : (finsupp.dom_lcongr f).trans (finsupp.dom_lcongr f₂) = (finsupp.dom_lcongr (f.trans f₂) : (_ →₀ M) ≃ₗ[R] _) := linear_equiv.ext $ λ _, map_domain_comp.symm @[simp] lemma dom_lcongr_symm {α₁ α₂ : Type*} (f : α₁ ≃ α₂) : ((finsupp.dom_lcongr f).symm : (_ →₀ M) ≃ₗ[R] _) = finsupp.dom_lcongr f.symm := linear_equiv.ext $ λ x, rfl @[simp] theorem dom_lcongr_single {α₁ : Type*} {α₂ : Type*} (e : α₁ ≃ α₂) (i : α₁) (m : M) : (finsupp.dom_lcongr e : _ ≃ₗ[R] _) (finsupp.single i m) = finsupp.single (e i) m := by simp [finsupp.dom_lcongr, finsupp.dom_congr, map_domain_single] /-- An equivalence of sets induces a linear equivalence of `finsupp`s supported on those sets. -/ noncomputable def congr {α' : Type*} (s : set α) (t : set α') (e : s ≃ t) : supported M R s ≃ₗ[R] supported M R t := begin haveI := classical.dec_pred (λ x, x ∈ s), haveI := classical.dec_pred (λ x, x ∈ t), refine linear_equiv.trans (finsupp.supported_equiv_finsupp s) (linear_equiv.trans _ (finsupp.supported_equiv_finsupp t).symm), exact finsupp.dom_lcongr e end /-- `finsupp.map_range` as a `linear_map`. -/ @[simps] def map_range.linear_map (f : M →ₗ[R] N) : (α →₀ M) →ₗ[R] (α →₀ N) := { to_fun := (map_range f f.map_zero : (α →₀ M) → (α →₀ N)), map_smul' := λ c v, map_range_smul c v (f.map_smul c), ..map_range.add_monoid_hom f.to_add_monoid_hom } @[simp] lemma map_range.linear_map_id : map_range.linear_map linear_map.id = (linear_map.id : (α →₀ M) →ₗ[R] _):= linear_map.ext map_range_id lemma map_range.linear_map_comp (f : N →ₗ[R] P) (f₂ : M →ₗ[R] N) : (map_range.linear_map (f.comp f₂) : (α →₀ _) →ₗ[R] _) = (map_range.linear_map f).comp (map_range.linear_map f₂) := linear_map.ext $ map_range_comp _ _ _ _ _ /-- `finsupp.map_range` as a `linear_equiv`. -/ @[simps apply] def map_range.linear_equiv (e : M ≃ₗ[R] N) : (α →₀ M) ≃ₗ[R] (α →₀ N) := { to_fun := map_range e e.map_zero, inv_fun := map_range e.symm e.symm.map_zero, ..map_range.linear_map e.to_linear_map, ..map_range.add_equiv e.to_add_equiv} @[simp] lemma map_range.linear_equiv_refl : map_range.linear_equiv (linear_equiv.refl R M) = linear_equiv.refl R (α →₀ M) := linear_equiv.ext map_range_id lemma map_range.linear_equiv_trans (f : M ≃ₗ[R] N) (f₂ : N ≃ₗ[R] P) : (map_range.linear_equiv (f.trans f₂) : linear_equiv R (α →₀ _) _) = (map_range.linear_equiv f).trans (map_range.linear_equiv f₂) := linear_equiv.ext $ map_range_comp _ _ _ _ _ @[simp] lemma map_range.linear_equiv_symm (f : M ≃ₗ[R] N) : ((map_range.linear_equiv f).symm : (α →₀ _) ≃ₗ[R] _) = map_range.linear_equiv f.symm := linear_equiv.ext $ λ x, rfl /-- An equivalence of domain and a linear equivalence of codomain induce a linear equivalence of the corresponding finitely supported functions. -/ def lcongr {ι κ : Sort*} (e₁ : ι ≃ κ) (e₂ : M ≃ₗ[R] N) : (ι →₀ M) ≃ₗ[R] (κ →₀ N) := (finsupp.dom_lcongr e₁).trans (map_range.linear_equiv e₂) @[simp] theorem lcongr_single {ι κ : Sort*} (e₁ : ι ≃ κ) (e₂ : M ≃ₗ[R] N) (i : ι) (m : M) : lcongr e₁ e₂ (finsupp.single i m) = finsupp.single (e₁ i) (e₂ m) := by simp [lcongr] @[simp] lemma lcongr_apply_apply {ι κ : Sort*} (e₁ : ι ≃ κ) (e₂ : M ≃ₗ[R] N) (f : ι →₀ M) (k : κ) : lcongr e₁ e₂ f k = e₂ (f (e₁.symm k)) := begin apply finsupp.induction_linear f, { simp, }, { intros f g hf hg, simp [map_add, hf, hg], }, { intros i m, simp only [finsupp.lcongr_single], simp only [finsupp.single, equiv.eq_symm_apply, finsupp.coe_mk], split_ifs; simp, }, end theorem lcongr_symm_single {ι κ : Sort*} (e₁ : ι ≃ κ) (e₂ : M ≃ₗ[R] N) (k : κ) (n : N) : (lcongr e₁ e₂).symm (finsupp.single k n) = finsupp.single (e₁.symm k) (e₂.symm n) := begin apply_fun lcongr e₁ e₂ using (lcongr e₁ e₂).injective, simp, end @[simp] lemma lcongr_symm {ι κ : Sort*} (e₁ : ι ≃ κ) (e₂ : M ≃ₗ[R] N) : (lcongr e₁ e₂).symm = lcongr e₁.symm e₂.symm := begin ext f i, simp only [equiv.symm_symm, finsupp.lcongr_apply_apply], apply finsupp.induction_linear f, { simp, }, { intros f g hf hg, simp [map_add, hf, hg], }, { intros k m, simp only [finsupp.lcongr_symm_single], simp only [finsupp.single, equiv.symm_apply_eq, finsupp.coe_mk], split_ifs; simp, }, end section sum variables (R) /-- The linear equivalence between `(α ⊕ β) →₀ M` and `(α →₀ M) × (β →₀ M)`. This is the `linear_equiv` version of `finsupp.sum_finsupp_equiv_prod_finsupp`. -/ @[simps apply symm_apply] def sum_finsupp_lequiv_prod_finsupp {α β : Type*} : ((α ⊕ β) →₀ M) ≃ₗ[R] (α →₀ M) × (β →₀ M) := { map_smul' := by { intros, ext; simp only [add_equiv.to_fun_eq_coe, prod.smul_fst, prod.smul_snd, smul_apply, snd_sum_finsupp_add_equiv_prod_finsupp, fst_sum_finsupp_add_equiv_prod_finsupp] }, .. sum_finsupp_add_equiv_prod_finsupp } lemma fst_sum_finsupp_lequiv_prod_finsupp {α β : Type*} (f : (α ⊕ β) →₀ M) (x : α) : (sum_finsupp_lequiv_prod_finsupp R f).1 x = f (sum.inl x) := rfl lemma snd_sum_finsupp_lequiv_prod_finsupp {α β : Type*} (f : (α ⊕ β) →₀ M) (y : β) : (sum_finsupp_lequiv_prod_finsupp R f).2 y = f (sum.inr y) := rfl lemma sum_finsupp_lequiv_prod_finsupp_symm_inl {α β : Type*} (fg : (α →₀ M) × (β →₀ M)) (x : α) : ((sum_finsupp_lequiv_prod_finsupp R).symm fg) (sum.inl x) = fg.1 x := rfl lemma sum_finsupp_lequiv_prod_finsupp_symm_inr {α β : Type*} (fg : (α →₀ M) × (β →₀ M)) (y : β) : ((sum_finsupp_lequiv_prod_finsupp R).symm fg) (sum.inr y) = fg.2 y := rfl end sum section sigma variables {η : Type*} [fintype η] {ιs : η → Type*} [has_zero α] variables (R) /-- On a `fintype η`, `finsupp.split` is a linear equivalence between `(Σ (j : η), ιs j) →₀ M` and `Π j, (ιs j →₀ M)`. This is the `linear_equiv` version of `finsupp.sigma_finsupp_add_equiv_pi_finsupp`. -/ noncomputable def sigma_finsupp_lequiv_pi_finsupp {M : Type*} {ιs : η → Type*} [add_comm_monoid M] [module R M] : ((Σ j, ιs j) →₀ M) ≃ₗ[R] Π j, (ιs j →₀ M) := { map_smul' := λ c f, by { ext, simp }, .. sigma_finsupp_add_equiv_pi_finsupp } @[simp] lemma sigma_finsupp_lequiv_pi_finsupp_apply {M : Type*} {ιs : η → Type*} [add_comm_monoid M] [module R M] (f : (Σ j, ιs j) →₀ M) (j i) : sigma_finsupp_lequiv_pi_finsupp R f j i = f ⟨j, i⟩ := rfl @[simp] lemma sigma_finsupp_lequiv_pi_finsupp_symm_apply {M : Type*} {ιs : η → Type*} [add_comm_monoid M] [module R M] (f : Π j, (ιs j →₀ M)) (ji) : (finsupp.sigma_finsupp_lequiv_pi_finsupp R).symm f ji = f ji.1 ji.2 := rfl end sigma section prod /-- The linear equivalence between `α × β →₀ M` and `α →₀ β →₀ M`. This is the `linear_equiv` version of `finsupp.finsupp_prod_equiv`. -/ noncomputable def finsupp_prod_lequiv {α β : Type*} (R : Type*) {M : Type*} [semiring R] [add_comm_monoid M] [module R M] : (α × β →₀ M) ≃ₗ[R] (α →₀ β →₀ M) := { map_add' := λ f g, by { ext, simp [finsupp_prod_equiv, curry_apply] }, map_smul' := λ c f, by { ext, simp [finsupp_prod_equiv, curry_apply] }, .. finsupp_prod_equiv } @[simp] lemma finsupp_prod_lequiv_apply {α β R M : Type*} [semiring R] [add_comm_monoid M] [module R M] (f : α × β →₀ M) (x y) : finsupp_prod_lequiv R f x y = f (x, y) := by rw [finsupp_prod_lequiv, linear_equiv.coe_mk, finsupp_prod_equiv, finsupp.curry_apply] @[simp] lemma finsupp_prod_lequiv_symm_apply {α β R M : Type*} [semiring R] [add_comm_monoid M] [module R M] (f : α →₀ β →₀ M) (xy) : (finsupp_prod_lequiv R).symm f xy = f xy.1 xy.2 := by conv_rhs { rw [← (finsupp_prod_lequiv R).apply_symm_apply f, finsupp_prod_lequiv_apply, prod.mk.eta] } end prod end finsupp variables {R : Type*} {M : Type*} {N : Type*} variables [semiring R] [add_comm_monoid M] [module R M] [add_comm_monoid N] [module R N] lemma linear_map.map_finsupp_total (f : M →ₗ[R] N) {ι : Type*} {g : ι → M} (l : ι →₀ R) : f (finsupp.total ι M R g l) = finsupp.total ι N R (f ∘ g) l := by simp only [finsupp.total_apply, finsupp.total_apply, finsupp.sum, f.map_sum, f.map_smul] lemma submodule.exists_finset_of_mem_supr {ι : Sort*} (p : ι → submodule R M) {m : M} (hm : m ∈ ⨆ i, p i) : ∃ s : finset ι, m ∈ ⨆ i ∈ s, p i := begin obtain ⟨f, hf, rfl⟩ : ∃ f ∈ finsupp.supported R R (⋃ i, ↑(p i)), finsupp.total M M R id f = m, { have aux : (id : M → M) '' (⋃ (i : ι), ↑(p i)) = (⋃ (i : ι), ↑(p i)) := set.image_id _, rwa [supr_eq_span, ← aux, finsupp.mem_span_iff_total R] at hm }, let t : finset M := f.support, have ht : ∀ x : {x // x ∈ t}, ∃ i, ↑x ∈ p i, { intros x, rw finsupp.mem_supported at hf, specialize hf x.2, rwa set.mem_Union at hf }, choose g hg using ht, let s : finset ι := finset.univ.image g, use s, simp only [mem_supr, supr_le_iff], assume N hN, rw [finsupp.total_apply, finsupp.sum, ← set_like.mem_coe], apply N.sum_mem, assume x hx, apply submodule.smul_mem, let i : ι := g ⟨x, hx⟩, have hi : i ∈ s, { rw finset.mem_image, exact ⟨⟨x, hx⟩, finset.mem_univ _, rfl⟩ }, exact hN i hi (hg _), end lemma mem_span_finset {s : finset M} {x : M} : x ∈ span R (↑s : set M) ↔ ∃ f : M → R, ∑ i in s, f i • i = x := ⟨λ hx, let ⟨v, hvs, hvx⟩ := (finsupp.mem_span_iff_total _).1 (show x ∈ span R (id '' (↑s : set M)), by rwa set.image_id) in ⟨v, hvx ▸ (finsupp.total_apply_of_mem_supported _ hvs).symm⟩, λ ⟨f, hf⟩, hf ▸ sum_mem _ (λ i hi, smul_mem _ _ $ subset_span hi)⟩ /-- An element `m ∈ M` is contained in the `R`-submodule spanned by a set `s ⊆ M`, if and only if `m` can be written as a finite `R`-linear combination of elements of `s`. The implementation uses `finsupp.sum`. -/ lemma mem_span_set {m : M} {s : set M} : m ∈ submodule.span R s ↔ ∃ c : M →₀ R, (c.support : set M) ⊆ s ∧ c.sum (λ mi r, r • mi) = m := begin conv_lhs { rw ←set.image_id s }, simp_rw ←exists_prop, exact finsupp.mem_span_iff_total R, end /-- If `subsingleton R`, then `M ≃ₗ[R] ι →₀ R` for any type `ι`. -/ @[simps] def module.subsingleton_equiv (R M ι: Type*) [semiring R] [subsingleton R] [add_comm_monoid M] [module R M] : M ≃ₗ[R] ι →₀ R := { to_fun := λ m, 0, inv_fun := λ f, 0, left_inv := λ m, by { letI := module.subsingleton R M, simp only [eq_iff_true_of_subsingleton] }, right_inv := λ f, by simp only [eq_iff_true_of_subsingleton], map_add' := λ m n, (add_zero 0).symm, map_smul' := λ r m, (smul_zero r).symm }
d262cb9b71a16fda97502f28609bef121bf3b0c0
7cef822f3b952965621309e88eadf618da0c8ae9
/src/algebra/punit_instances.lean
244d33a863dc46015238177b71ba8bc90cd7bc28
[ "Apache-2.0" ]
permissive
rmitta/mathlib
8d90aee30b4db2b013e01f62c33f297d7e64a43d
883d974b608845bad30ae19e27e33c285200bf84
refs/heads/master
1,585,776,832,544
1,576,874,096,000
1,576,874,096,000
153,663,165
0
2
Apache-2.0
1,544,806,490,000
1,539,884,365,000
Lean
UTF-8
Lean
false
false
3,470
lean
/- Copyright (c) 2019 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau Instances on punit. -/ import algebra.module algebra.group universes u open lattice namespace punit variables (x y : punit.{u+1}) (s : set punit.{u+1}) @[to_additive add_comm_group] instance : comm_group punit := by refine { mul := λ _ _, star, one := star, inv := λ _, star, .. }; intros; exact subsingleton.elim _ _ instance : comm_ring punit := by refine { .. punit.comm_group, .. punit.add_comm_group, .. }; intros; exact subsingleton.elim _ _ instance : complete_boolean_algebra punit := by refine { le := λ _ _, true, le_antisymm := λ _ _ _ _, subsingleton.elim _ _, lt := λ _ _, false, lt_iff_le_not_le := λ _ _, iff_of_false not_false (λ H, H.2 trivial), top := star, bot := star, sup := λ _ _, star, inf := λ _ _, star, Sup := λ _, star, Inf := λ _, star, sub := λ _ _, star, .. punit.comm_ring, .. }; intros; trivial instance : canonically_ordered_monoid punit := by refine { lt_of_add_lt_add_left := λ _ _ _, id, le_iff_exists_add := λ _ _, iff_of_true _ ⟨star, subsingleton.elim _ _⟩, .. punit.comm_ring, .. punit.lattice.complete_boolean_algebra, .. }; intros; trivial instance : decidable_linear_ordered_cancel_comm_monoid punit := { add_left_cancel := λ _ _ _ _, subsingleton.elim _ _, add_right_cancel := λ _ _ _ _, subsingleton.elim _ _, le_of_add_le_add_left := λ _ _ _ _, trivial, le_total := λ _ _, or.inl trivial, decidable_le := λ _ _, decidable.true, decidable_eq := punit.decidable_eq, decidable_lt := λ _ _, decidable.false, .. punit.canonically_ordered_monoid } instance (R : Type u) [ring R] : module R punit := module.of_core $ by refine { smul := λ _ _, star, .. punit.comm_ring, .. }; intros; exact subsingleton.elim _ _ @[simp] lemma zero_eq : (0 : punit) = star := rfl @[simp, to_additive] lemma one_eq : (1 : punit) = star := rfl @[simp] lemma add_eq : x + y = star := rfl @[simp, to_additive] lemma mul_eq : x * y = star := rfl @[simp] lemma neg_eq : -x = star := rfl @[simp, to_additive] lemma inv_eq : x⁻¹ = star := rfl @[simp] lemma smul_eq : x • y = star := rfl @[simp] lemma top_eq : (⊤ : punit) = star := rfl @[simp] lemma bot_eq : (⊥ : punit) = star := rfl @[simp] lemma sup_eq : x ⊔ y = star := rfl @[simp] lemma inf_eq : x ⊓ y = star := rfl @[simp] lemma Sup_eq : Sup s = star := rfl @[simp] lemma Inf_eq : Inf s = star := rfl @[simp] protected lemma le : x ≤ y := trivial @[simp] lemma not_lt : ¬(x < y) := not_false instance {α : Type*} [has_mul α] (f : α → punit) : is_mul_hom f := ⟨λ _ _, subsingleton.elim _ _⟩ instance {α : Type*} [has_add α] (f : α → punit) : is_add_hom f := ⟨λ _ _, subsingleton.elim _ _⟩ instance {α : Type*} [monoid α] (f : α → punit) : is_monoid_hom f := { map_one := subsingleton.elim _ _ } instance {α : Type*} [add_monoid α] (f : α → punit) : is_add_monoid_hom f := { map_zero := subsingleton.elim _ _ } instance {α : Type*} [group α] (f : α → punit) : is_group_hom f := { } instance {α : Type*} [add_group α] (f : α → punit) : is_add_group_hom f := { } instance {α : Type*} [semiring α] (f : α → punit) : is_semiring_hom f := { .. punit.is_monoid_hom f, .. punit.is_add_monoid_hom f } instance {α : Type*} [ring α] (f : α → punit) : is_ring_hom f := { .. punit.is_semiring_hom f } end punit
fc80b56e13e002e1f2993ae81bd9d7b6d7545b75
f5373ccdc976e6390397d9f4220a74c76f706f4a
/src/lean_gym/api_instances.lean
d560e3cb17c2ee16829063ec2364e0d60dcde849
[]
no_license
jasonrute/lean_gym_prototype
fcd91fdc454f9e351bbe258c765f50276407547e
ab29624d14e4e069e15afe0b1d90248b5b394b86
refs/heads/master
1,682,628,526,780
1,590,539,315,000
1,590,539,315,000
264,938,525
3
0
null
null
null
null
UTF-8
Lean
false
false
9,195
lean
/- This file is autogenerated by a script -/ import lean_gym.api import tools.json open json meta instance lean_tactic_has_to_json : has_to_json lean_tactic := has_to_json.mk $ λ s, match s with | (lean_tactic.skip ) := json.jobject [("skip", json.jobject [])] | (lean_tactic.apply sexp) := json.jobject [("apply", json.jobject [("sexp", to_json sexp)])] | (lean_tactic.cases sexp) := json.jobject [("cases", json.jobject [("sexp", to_json sexp)])] | (lean_tactic.intro ) := json.jobject [("intro", json.jobject [])] | (lean_tactic.split ) := json.jobject [("split", json.jobject [])] | (lean_tactic.left ) := json.jobject [("left", json.jobject [])] | (lean_tactic.right ) := json.jobject [("right", json.jobject [])] | (lean_tactic.exfalso ) := json.jobject [("exfalso", json.jobject [])] end private meta def decode_json_lean_tactic : json → exceptional lean_tactic | (json.jobject [("skip", json.jobject kvs)]) := do decoder_check_empty kvs, return $ lean_tactic.skip | (json.jobject [("apply", json.jobject kvs)]) := do (sexp, kvs) <- decoder_get_field_value string "sexp" kvs, decoder_check_empty kvs, return $ lean_tactic.apply sexp | (json.jobject [("cases", json.jobject kvs)]) := do (sexp, kvs) <- decoder_get_field_value string "sexp" kvs, decoder_check_empty kvs, return $ lean_tactic.cases sexp | (json.jobject [("intro", json.jobject kvs)]) := do decoder_check_empty kvs, return $ lean_tactic.intro | (json.jobject [("split", json.jobject kvs)]) := do decoder_check_empty kvs, return $ lean_tactic.split | (json.jobject [("left", json.jobject kvs)]) := do decoder_check_empty kvs, return $ lean_tactic.left | (json.jobject [("right", json.jobject kvs)]) := do decoder_check_empty kvs, return $ lean_tactic.right | (json.jobject [("exfalso", json.jobject kvs)]) := do decoder_check_empty kvs, return $ lean_tactic.exfalso | j := exceptional.fail $ "Unexpected form for " ++ "lean_tactic" ++ ", found: " ++ (to_string j) meta instance lean_tactic_has_from_json : has_from_json lean_tactic := ⟨decode_json_lean_tactic⟩ meta instance lean_state_control_has_to_json : has_to_json lean_state_control := has_to_json.mk $ λ s, match s with | (lean_state_control.jump_to_state state_index) := json.jobject [("jump_to_state", json.jobject [("state_index", to_json state_index)])] | (lean_state_control.change_top_goal sexp) := json.jobject [("change_top_goal", json.jobject [("sexp", to_json sexp)])] | (lean_state_control.change_top_goal_pp sexp) := json.jobject [("change_top_goal_pp", json.jobject [("sexp", to_json sexp)])] end private meta def decode_json_lean_state_control : json → exceptional lean_state_control | (json.jobject [("jump_to_state", json.jobject kvs)]) := do (state_index, kvs) <- decoder_get_field_value nat "state_index" kvs, decoder_check_empty kvs, return $ lean_state_control.jump_to_state state_index | (json.jobject [("change_top_goal", json.jobject kvs)]) := do (sexp, kvs) <- decoder_get_field_value string "sexp" kvs, decoder_check_empty kvs, return $ lean_state_control.change_top_goal sexp | (json.jobject [("change_top_goal_pp", json.jobject kvs)]) := do (sexp, kvs) <- decoder_get_field_value string "sexp" kvs, decoder_check_empty kvs, return $ lean_state_control.change_top_goal_pp sexp | j := exceptional.fail $ "Unexpected form for " ++ "lean_state_control" ++ ", found: " ++ (to_string j) meta instance lean_state_control_has_from_json : has_from_json lean_state_control := ⟨decode_json_lean_state_control⟩ meta instance lean_server_request_has_to_json : has_to_json lean_server_request := has_to_json.mk $ λ s, match s with | (lean_server_request.apply_tactic tactic) := json.jobject [("apply_tactic", json.jobject [("tactic", to_json tactic)])] | (lean_server_request.change_state control) := json.jobject [("change_state", json.jobject [("control", to_json control)])] | (lean_server_request.exit msg) := json.jobject [("exit", json.jobject [("msg", to_json msg)])] end private meta def decode_json_lean_server_request : json → exceptional lean_server_request | (json.jobject [("apply_tactic", json.jobject kvs)]) := do (tactic, kvs) <- decoder_get_field_value lean_tactic "tactic" kvs, decoder_check_empty kvs, return $ lean_server_request.apply_tactic tactic | (json.jobject [("change_state", json.jobject kvs)]) := do (control, kvs) <- decoder_get_field_value lean_state_control "control" kvs, decoder_check_empty kvs, return $ lean_server_request.change_state control | (json.jobject [("exit", json.jobject kvs)]) := do (msg, kvs) <- decoder_get_field_value string "msg" kvs, decoder_check_empty kvs, return $ lean_server_request.exit msg | j := exceptional.fail $ "Unexpected form for " ++ "lean_server_request" ++ ", found: " ++ (to_string j) meta instance lean_server_request_has_from_json : has_from_json lean_server_request := ⟨decode_json_lean_server_request⟩ meta instance lean_tactic_result_has_to_json : has_to_json lean_tactic_result := has_to_json.mk $ λ s, match s with | (lean_tactic_result.success basic_goal_information) := json.jobject [("success", json.jobject [("basic_goal_information", to_json basic_goal_information)])] | (lean_tactic_result.failure msg) := json.jobject [("failure", json.jobject [("msg", to_json msg)])] | (lean_tactic_result.server_error msg) := json.jobject [("server_error", json.jobject [("msg", to_json msg)])] end private meta def decode_json_lean_tactic_result : json → exceptional lean_tactic_result | (json.jobject [("success", json.jobject kvs)]) := do (basic_goal_information, kvs) <- decoder_get_field_value string "basic_goal_information" kvs, decoder_check_empty kvs, return $ lean_tactic_result.success basic_goal_information | (json.jobject [("failure", json.jobject kvs)]) := do (msg, kvs) <- decoder_get_field_value string "msg" kvs, decoder_check_empty kvs, return $ lean_tactic_result.failure msg | (json.jobject [("server_error", json.jobject kvs)]) := do (msg, kvs) <- decoder_get_field_value string "msg" kvs, decoder_check_empty kvs, return $ lean_tactic_result.server_error msg | j := exceptional.fail $ "Unexpected form for " ++ "lean_tactic_result" ++ ", found: " ++ (to_string j) meta instance lean_tactic_result_has_from_json : has_from_json lean_tactic_result := ⟨decode_json_lean_tactic_result⟩ meta instance lean_state_result_has_to_json : has_to_json lean_state_result := has_to_json.mk $ λ s, match s with | (lean_state_result.success basic_state_information) := json.jobject [("success", json.jobject [("basic_state_information", to_json basic_state_information)])] | (lean_state_result.server_error msg) := json.jobject [("server_error", json.jobject [("msg", to_json msg)])] end private meta def decode_json_lean_state_result : json → exceptional lean_state_result | (json.jobject [("success", json.jobject kvs)]) := do (basic_state_information, kvs) <- decoder_get_field_value string "basic_state_information" kvs, decoder_check_empty kvs, return $ lean_state_result.success basic_state_information | (json.jobject [("server_error", json.jobject kvs)]) := do (msg, kvs) <- decoder_get_field_value string "msg" kvs, decoder_check_empty kvs, return $ lean_state_result.server_error msg | j := exceptional.fail $ "Unexpected form for " ++ "lean_state_result" ++ ", found: " ++ (to_string j) meta instance lean_state_result_has_from_json : has_from_json lean_state_result := ⟨decode_json_lean_state_result⟩ meta instance lean_server_response_has_to_json : has_to_json lean_server_response := has_to_json.mk $ λ s, match s with | (lean_server_response.apply_tactic result) := json.jobject [("apply_tactic", json.jobject [("result", to_json result)])] | (lean_server_response.change_state result) := json.jobject [("change_state", json.jobject [("result", to_json result)])] | (lean_server_response.exit msg) := json.jobject [("exit", json.jobject [("msg", to_json msg)])] | (lean_server_response.error msg) := json.jobject [("error", json.jobject [("msg", to_json msg)])] end private meta def decode_json_lean_server_response : json → exceptional lean_server_response | (json.jobject [("apply_tactic", json.jobject kvs)]) := do (result, kvs) <- decoder_get_field_value lean_tactic_result "result" kvs, decoder_check_empty kvs, return $ lean_server_response.apply_tactic result | (json.jobject [("change_state", json.jobject kvs)]) := do (result, kvs) <- decoder_get_field_value lean_state_result "result" kvs, decoder_check_empty kvs, return $ lean_server_response.change_state result | (json.jobject [("exit", json.jobject kvs)]) := do (msg, kvs) <- decoder_get_field_value string "msg" kvs, decoder_check_empty kvs, return $ lean_server_response.exit msg | (json.jobject [("error", json.jobject kvs)]) := do (msg, kvs) <- decoder_get_field_value string "msg" kvs, decoder_check_empty kvs, return $ lean_server_response.error msg | j := exceptional.fail $ "Unexpected form for " ++ "lean_server_response" ++ ", found: " ++ (to_string j) meta instance lean_server_response_has_from_json : has_from_json lean_server_response := ⟨decode_json_lean_server_response⟩
e9ef6de22f49b74139ce5e344b36cb7d994fd0a8
d642a6b1261b2cbe691e53561ac777b924751b63
/src/topology/algebra/open_subgroup.lean
2566ce50bf63c8ce3a73bfb90be03c56793bbf9a
[ "Apache-2.0" ]
permissive
cipher1024/mathlib
fee56b9954e969721715e45fea8bcb95f9dc03fe
d077887141000fefa5a264e30fa57520e9f03522
refs/heads/master
1,651,806,490,504
1,573,508,694,000
1,573,508,694,000
107,216,176
0
0
Apache-2.0
1,647,363,136,000
1,508,213,014,000
Lean
UTF-8
Lean
false
false
5,917
lean
import order.filter.lift import linear_algebra.basic import topology.opens topology.algebra.ring section open topological_space variables (G : Type*) [group G] [topological_space G] /-- The type of open subgroups of a topological group. -/ @[to_additive open_add_subgroup] def open_subgroup := { U : set G // is_open U ∧ is_subgroup U } @[to_additive] instance open_subgroup.has_coe : has_coe (open_subgroup G) (opens G) := ⟨λ U, ⟨U.1, U.2.1⟩⟩ end -- Tell Lean that `open_add_subgroup` is a namespace namespace open_add_subgroup end open_add_subgroup namespace open_subgroup open function lattice topological_space variables {G : Type*} [group G] [topological_space G] variables {U V : open_subgroup G} @[to_additive] instance : has_mem G (open_subgroup G) := ⟨λ g U, g ∈ (U : set G)⟩ @[to_additive] lemma ext : (U = V) ↔ ((U : set G) = V) := by cases U; cases V; split; intro h; try {congr}; assumption @[ext, to_additive] lemma ext' (h : (U : set G) = V) : (U = V) := ext.mpr h @[to_additive] lemma coe_injective : injective (λ U : open_subgroup G, (U : set G)) := λ U V h, ext' h @[to_additive is_add_subgroup] instance : is_subgroup (U : set G) := U.2.2 variable (U) @[to_additive] protected lemma is_open : is_open (U : set G) := U.2.1 @[to_additive] protected lemma one_mem : (1 : G) ∈ U := is_submonoid.one_mem (U : set G) @[to_additive] protected lemma inv_mem {g : G} (h : g ∈ U) : g⁻¹ ∈ U := @is_subgroup.inv_mem G _ U _ g h @[to_additive] protected lemma mul_mem {g₁ g₂ : G} (h₁ : g₁ ∈ U) (h₂ : g₂ ∈ U) : g₁ * g₂ ∈ U := @is_submonoid.mul_mem G _ U _ g₁ g₂ h₁ h₂ @[to_additive] lemma mem_nhds_one : (U : set G) ∈ nhds (1 : G) := mem_nhds_sets U.is_open U.one_mem variable {U} @[to_additive] instance : inhabited (open_subgroup G) := { default := ⟨set.univ, ⟨is_open_univ, by apply_instance⟩⟩ } @[to_additive] lemma is_open_of_nonempty_open_subset [topological_monoid G] {s : set G} [is_subgroup s] (h : ∃ U : opens G, nonempty U ∧ (U : set G) ⊆ s) : is_open s := begin rw is_open_iff_forall_mem_open, intros x hx, rcases h with ⟨U, ⟨g, hg⟩, hU⟩, use (λ y, y * (x⁻¹ * g)) ⁻¹' U, split, { intros u hu, erw set.mem_preimage at hu, replace hu := hU hu, replace hg := hU hg, have : (x⁻¹ * g)⁻¹ ∈ s, { simp [*, is_subgroup.inv_mem, is_submonoid.mul_mem], }, convert is_submonoid.mul_mem hu this, simp [mul_assoc] }, split, { apply continuous_mul continuous_id continuous_const, { exact U.property }, { apply_instance } }, { erw set.mem_preimage, convert hg, rw [← mul_assoc, mul_right_inv, one_mul] } end @[to_additive is_open_of_open_add_subgroup] lemma is_open_of_open_subgroup [topological_monoid G] {s : set G} [is_subgroup s] (h : ∃ U : open_subgroup G, (U : set G) ⊆ s) : is_open s := is_open_of_nonempty_open_subset $ let ⟨U, hU⟩ := h in ⟨U, ⟨⟨1, U.one_mem⟩⟩, hU⟩ @[to_additive] lemma is_closed [topological_monoid G] (U : open_subgroup G) : is_closed (U : set G) := begin show is_open (-(U : set G)), rw is_open_iff_forall_mem_open, intros x hx, use (λ y, y * x⁻¹) ⁻¹' U, split, { intros u hux, erw set.mem_preimage at hux, rw set.mem_compl_iff at hx ⊢, intro hu, apply hx, convert is_submonoid.mul_mem (is_subgroup.inv_mem hux) hu, simp }, split, { exact (continuous_mul_right _) _ U.is_open }, { simpa using is_submonoid.one_mem (U : set G) } end section variables {H : Type*} [group H] [topological_space H] @[to_additive] def prod (U : open_subgroup G) (V : open_subgroup H) : open_subgroup (G × H) := ⟨(U : set G).prod (V : set H), is_open_prod U.is_open V.is_open, by apply_instance⟩ end @[to_additive] instance : partial_order (open_subgroup G) := partial_order.lift _ coe_injective (by apply_instance) @[to_additive] instance : semilattice_inf_top (open_subgroup G) := { inf := λ U V, ⟨(U : set G) ∩ V, is_open_inter U.is_open V.is_open, by apply_instance⟩, inf_le_left := λ U V, set.inter_subset_left _ _, inf_le_right := λ U V, set.inter_subset_right _ _, le_inf := λ U V W hV hW, set.subset_inter hV hW, top := default _, le_top := λ U, set.subset_univ _, ..open_subgroup.partial_order } @[to_additive] instance [topological_monoid G] : semilattice_sup_top (open_subgroup G) := { sup := λ U V, { val := group.closure ((U : set G) ∪ V), property := begin haveI subgrp := _, refine ⟨_, subgrp⟩, { refine is_open_of_open_subgroup _, exact ⟨U, set.subset.trans (set.subset_union_left _ _) group.subset_closure⟩ }, { apply_instance } end }, le_sup_left := λ U V, set.subset.trans (set.subset_union_left _ _) group.subset_closure, le_sup_right := λ U V, set.subset.trans (set.subset_union_right _ _) group.subset_closure, sup_le := λ U V W hU hV, group.closure_subset $ set.union_subset hU hV, ..open_subgroup.lattice.semilattice_inf_top } @[simp, to_additive] lemma coe_inf : (↑(U ⊓ V) : set G) = (U : set G) ∩ V := rfl @[to_additive] lemma le_iff : U ≤ V ↔ (U : set G) ⊆ V := iff.rfl end open_subgroup namespace submodule open open_add_subgroup variables {R : Type*} {M : Type*} [comm_ring R] variables [add_comm_group M] [topological_space M] [topological_add_group M] [module R M] lemma is_open_of_open_submodule {P : submodule R M} (h : ∃ U : submodule R M, is_open (U : set M) ∧ U ≤ P) : is_open (P : set M) := let ⟨U, h₁, h₂⟩ := h in is_open_of_open_add_subgroup ⟨⟨U, h₁, by apply_instance⟩, h₂⟩ end submodule namespace ideal variables {R : Type*} [comm_ring R] variables [topological_space R] [topological_ring R] lemma is_open_of_open_subideal {I : ideal R} (h : ∃ U : ideal R, is_open (U : set R) ∧ U ≤ I) : is_open (I : set R) := submodule.is_open_of_open_submodule h end ideal
b0d85962bede50c79d922c7f2cb6729d1679652d
37683ecbb27d7c2037bfd9ad7e06d662f460a005
/algebra/quotient_group.hlean
3acc798e86bbb09526145bc7379e78a721efd047
[ "Apache-2.0" ]
permissive
GRSEB9S/Spectral-1
b2443b09cae7aac1247b1f88c846c532ac802b8e
dd14277e0bfc6270a488eb3b9ec231484065b9d8
refs/heads/master
1,631,315,269,407
1,522,048,315,000
1,522,799,803,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
28,856
hlean
/- Copyright (c) 2015 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn, Egbert Rijke, Jeremy Avigad Constructions with groups -/ import hit.set_quotient .subgroup ..move_to_lib types.equiv open eq algebra is_trunc set_quotient relation sigma sigma.ops prod trunc function equiv is_equiv open property namespace group variables {G G' : Group} (H : property G) [is_subgroup G H] (N : property G) [is_normal_subgroup G N] {g g' h h' k : G} (N' : property G') [is_normal_subgroup G' N'] variables {A B : AbGroup} /- Quotient Group -/ definition homotopy_of_homomorphism_eq {f g : G →g G'}(p : f = g) : f ~ g := λx : G , ap010 group_fun p x definition quotient_rel [constructor] (g h : G) : Prop := g * h⁻¹ ∈ N variable {N} -- We prove that quotient_rel is an equivalence relation theorem quotient_rel_refl (g : G) : quotient_rel N g g := transport (λx, N x) !mul.right_inv⁻¹ (subgroup_one_mem N) theorem quotient_rel_symm (r : quotient_rel N g h) : quotient_rel N h g := transport (λx, N x) (!mul_inv ⬝ ap (λx, x * _) !inv_inv) begin apply subgroup_inv_mem r end theorem quotient_rel_trans (r : quotient_rel N g h) (s : quotient_rel N h k) : quotient_rel N g k := have H1 : N ((g * h⁻¹) * (h * k⁻¹)), from subgroup_mul_mem r s, have H2 : (g * h⁻¹) * (h * k⁻¹) = g * k⁻¹, from calc (g * h⁻¹) * (h * k⁻¹) = ((g * h⁻¹) * h) * k⁻¹ : by rewrite [mul.assoc (g * h⁻¹)] ... = g * k⁻¹ : by rewrite inv_mul_cancel_right, show N (g * k⁻¹), by rewrite [-H2]; exact H1 theorem is_equivalence_quotient_rel : is_equivalence (quotient_rel N) := is_equivalence.mk quotient_rel_refl (λg h, quotient_rel_symm) (λg h k, quotient_rel_trans) -- We prove that quotient_rel respects inverses and multiplication, so -- it is a congruence relation theorem quotient_rel_resp_inv (r : quotient_rel N g h) : quotient_rel N g⁻¹ h⁻¹ := have H1 : g⁻¹ * (h * g⁻¹) * g ∈ N, from is_normal_subgroup' g (quotient_rel_symm r), have H2 : g⁻¹ * (h * g⁻¹) * g = g⁻¹ * h⁻¹⁻¹, from calc g⁻¹ * (h * g⁻¹) * g = g⁻¹ * h * g⁻¹ * g : by rewrite -mul.assoc ... = g⁻¹ * h : inv_mul_cancel_right ... = g⁻¹ * h⁻¹⁻¹ : by rewrite algebra.inv_inv, show g⁻¹ * h⁻¹⁻¹ ∈ N, by rewrite [-H2]; exact H1 theorem quotient_rel_resp_mul (r : quotient_rel N g h) (r' : quotient_rel N g' h') : quotient_rel N (g * g') (h * h') := have H1 : g * ((g' * h'⁻¹) * h⁻¹) ∈ N, from normal_subgroup_insert r' r, have H2 : g * ((g' * h'⁻¹) * h⁻¹) = (g * g') * (h * h')⁻¹, from calc g * ((g' * h'⁻¹) * h⁻¹) = g * (g' * (h'⁻¹ * h⁻¹)) : by rewrite [mul.assoc] ... = (g * g') * (h'⁻¹ * h⁻¹) : mul.assoc ... = (g * g') * (h * h')⁻¹ : by rewrite [mul_inv], show N ((g * g') * (h * h')⁻¹), from transport (λx, N x) H2 H1 local attribute is_equivalence_quotient_rel [instance] variable (N) definition qg : Type := set_quotient (quotient_rel N) variable {N} local attribute qg [reducible] definition quotient_one [constructor] : qg N := class_of one definition quotient_inv [unfold 3] : qg N → qg N := quotient_unary_map has_inv.inv (λg g' r, quotient_rel_resp_inv r) definition quotient_mul [unfold 3 4] : qg N → qg N → qg N := quotient_binary_map has_mul.mul (λg g' r h h' r', quotient_rel_resp_mul r r') section local notation 1 := quotient_one local postfix ⁻¹ := quotient_inv local infix * := quotient_mul theorem quotient_mul_assoc (g₁ g₂ g₃ : qg N) : g₁ * g₂ * g₃ = g₁ * (g₂ * g₃) := begin refine set_quotient.rec_prop _ g₁, refine set_quotient.rec_prop _ g₂, refine set_quotient.rec_prop _ g₃, clear g₁ g₂ g₃, intro g₁ g₂ g₃, exact ap class_of !mul.assoc end theorem quotient_one_mul (g : qg N) : 1 * g = g := begin refine set_quotient.rec_prop _ g, clear g, intro g, exact ap class_of !one_mul end theorem quotient_mul_one (g : qg N) : g * 1 = g := begin refine set_quotient.rec_prop _ g, clear g, intro g, exact ap class_of !mul_one end theorem quotient_mul_left_inv (g : qg N) : g⁻¹ * g = 1 := begin refine set_quotient.rec_prop _ g, clear g, intro g, exact ap class_of !mul.left_inv end theorem quotient_mul_comm {G : AbGroup} {N : property G} [is_normal_subgroup G N] (g h : qg N) : g * h = h * g := begin refine set_quotient.rec_prop _ g, clear g, intro g, refine set_quotient.rec_prop _ h, clear h, intro h, apply ap class_of, esimp, apply mul.comm end end variable (N) definition group_qg [constructor] : group (qg N) := group.mk _ quotient_mul quotient_mul_assoc quotient_one quotient_one_mul quotient_mul_one quotient_inv quotient_mul_left_inv definition quotient_group [constructor] : Group := Group.mk _ (group_qg N) definition ab_group_qg [constructor] {G : AbGroup} (N : property G) [is_normal_subgroup G N] : ab_group (qg N) := ⦃ab_group, group_qg N, mul_comm := quotient_mul_comm⦄ definition quotient_ab_group [constructor] {G : AbGroup} (N : property G) [is_subgroup G N] : AbGroup := AbGroup.mk _ (@ab_group_qg G N (is_normal_subgroup_ab _)) definition qg_map [constructor] : G →g quotient_group N := homomorphism.mk class_of (λ g h, idp) definition ab_qg_map {G : AbGroup} (N : property G) [is_subgroup G N] : G →g quotient_ab_group N := @qg_map _ N (is_normal_subgroup_ab _) definition is_surjective_ab_qg_map {A : AbGroup} (N : property A) [is_subgroup A N] : is_surjective (ab_qg_map N) := begin intro x, induction x, fapply image.mk, exact a, reflexivity, apply is_prop.elimo end namespace quotient notation `⟦`:max a `⟧`:0 := qg_map _ a end quotient open quotient variables {N N'} definition qg_map_eq_one (g : G) (H : N g) : qg_map N g = 1 := begin apply eq_of_rel, have e : (g * 1⁻¹ = g), from calc g * 1⁻¹ = g * 1 : one_inv ... = g : mul_one, unfold quotient_rel, rewrite e, exact H end definition ab_qg_map_eq_one {K : property A} [is_subgroup A K] (g :A) (H : K g) : ab_qg_map K g = 1 := begin apply eq_of_rel, have e : (g * 1⁻¹ = g), from calc g * 1⁻¹ = g * 1 : one_inv ... = g : mul_one, unfold quotient_rel, xrewrite e, exact H end --- there should be a smarter way to do this!! Please have a look, Floris. definition rel_of_qg_map_eq_one (g : G) (H : qg_map N g = 1) : g ∈ N := begin have e : (g * 1⁻¹ = g), from calc g * 1⁻¹ = g * 1 : one_inv ... = g : mul_one, rewrite (inverse e), apply rel_of_eq _ H end definition rel_of_ab_qg_map_eq_one {K : property A} [is_subgroup A K] (a :A) (H : ab_qg_map K a = 1) : a ∈ K := begin have e : (a * 1⁻¹ = a), from calc a * 1⁻¹ = a * 1 : one_inv ... = a : mul_one, rewrite (inverse e), have is_normal_subgroup A K, from is_normal_subgroup_ab _, apply rel_of_eq (quotient_rel K) H end definition quotient_group_elim_fun [unfold 6] (f : G →g G') (H : Π⦃g⦄, N g → f g = 1) (g : quotient_group N) : G' := begin refine set_quotient.elim f _ g, intro g h K, apply eq_of_mul_inv_eq_one, have e : f (g * h⁻¹) = f g * (f h)⁻¹, from calc f (g * h⁻¹) = f g * (f h⁻¹) : to_respect_mul ... = f g * (f h)⁻¹ : to_respect_inv, rewrite (inverse e), apply H, exact K end definition quotient_group_elim [constructor] (f : G →g G') (H : Π⦃g⦄, g ∈ N → f g = 1) : quotient_group N →g G' := begin fapply homomorphism.mk, -- define function { exact quotient_group_elim_fun f H }, { intro g h, induction g using set_quotient.rec_prop with g, induction h using set_quotient.rec_prop with h, krewrite (inverse (to_respect_mul (qg_map N) g h)), unfold qg_map, esimp, exact to_respect_mul f g h } end example {K : property A} [is_subgroup A K] : quotient_ab_group K = @quotient_group A K (is_normal_subgroup_ab _) := rfl definition quotient_ab_group_elim [constructor] {K : property A} [is_subgroup A K] (f : A →g B) (H : Π⦃g⦄, g ∈ K → f g = 1) : quotient_ab_group K →g B := @quotient_group_elim A B K (is_normal_subgroup_ab _) f H definition quotient_group_compute (f : G →g G') (H : Π⦃g⦄, N g → f g = 1) (g : G) : quotient_group_elim f H (qg_map N g) = f g := begin reflexivity end definition gelim_unique (f : G →g G') (H : Π⦃g⦄, g ∈ N → f g = 1) (k : quotient_group N →g G') : ( k ∘g qg_map N ~ f ) → k ~ quotient_group_elim f H := begin intro K cg, induction cg using set_quotient.rec_prop with g, exact K g end definition ab_gelim_unique {K : property A} [is_subgroup A K] (f : A →g B) (H : Π (a :A), a ∈ K → f a = 1) (k : quotient_ab_group K →g B) : ( k ∘g ab_qg_map K ~ f) → k ~ quotient_ab_group_elim f H := --@quotient_group_elim A B K (is_normal_subgroup_ab _) f H := @gelim_unique _ _ K (is_normal_subgroup_ab _) f H _ definition qg_universal_property (f : G →g G') (H : Π⦃g⦄, N g → f g = 1) : is_contr (Σ(g : quotient_group N →g G'), g ∘ qg_map N ~ f) := begin fapply is_contr.mk, -- give center of contraction { fapply sigma.mk, exact quotient_group_elim f H, exact quotient_group_compute f H }, -- give contraction { intro pair, induction pair with g p, fapply sigma_eq, {esimp, apply homomorphism_eq, symmetry, exact gelim_unique f H g p}, {fapply is_prop.elimo} } end definition ab_qg_universal_property {K : property A} [is_subgroup A K] (f : A →g B) (H : Π (a :A), K a → f a = 1) : is_contr ((Σ(g : quotient_ab_group K →g B), g ∘g ab_qg_map K ~ f) ) := begin fapply @qg_universal_property _ _ K (is_normal_subgroup_ab _), exact H end definition quotient_group_functor_contr {K L : property A} [is_subgroup A K] [is_subgroup A L] (H : Π (a : A), K a → L a) : is_contr ((Σ(g : quotient_ab_group K →g quotient_ab_group L), g ∘g ab_qg_map K ~ ab_qg_map L) ) := begin fapply ab_qg_universal_property, intro a p, fapply ab_qg_map_eq_one, exact H a p end definition quotient_group_functor_id {K : property A} [is_subgroup A K] (H : Π (a : A), K a → K a) : center' (@quotient_group_functor_contr _ K K _ _ H) = ⟨gid (quotient_ab_group K), λ x, rfl⟩ := begin note p := @quotient_group_functor_contr _ K K _ _ H, fapply eq_of_is_contr, end section quotient_group_iso_ua set_option pp.universes true definition subgroup_rel_eq' {K L : property A} [HK : is_subgroup A K] [HL : is_subgroup A L] (htpy : Π (a : A), K a ≃ L a) : K = L := begin induction HK with Rone Rmul Rinv, induction HL with Rone' Rmul' Rinv', esimp at *, assert q : K = L, begin fapply eq_of_homotopy, intro a, fapply tua, exact htpy a, end, induction q, assert q : Rone = Rone', begin fapply is_prop.elim, end, induction q, assert q2 : @Rmul = @Rmul', begin fapply is_prop.elim, end, induction q2, assert q : @Rinv = @Rinv', begin fapply is_prop.elim, end, induction q, reflexivity end definition subgroup_rel_eq {K L : property A} [is_subgroup A K] [is_subgroup A L] (K_in_L : Π (a : A), a ∈ K → a ∈ L) (L_in_K : Π (a : A), a ∈ L → a ∈ K) : K = L := begin have htpy : Π (a : A), K a ≃ L a, begin intro a, apply @equiv_of_is_prop (a ∈ K) (a ∈ L) _ _ (K_in_L a) (L_in_K a), end, exact subgroup_rel_eq' htpy, end definition eq_of_ab_qg_group' {K L : property A} [HK : is_subgroup A K] [HL : is_subgroup A L] (p : K = L) : quotient_ab_group K = quotient_ab_group L := begin revert HK, revert HL, induction p, intros, have HK = HL, begin apply @is_prop.elim _ _ HK HL end, rewrite this end definition iso_of_eq {B : AbGroup} (p : A = B) : A ≃g B := begin induction p, fapply isomorphism.mk, exact gid A, fapply adjointify, exact id, intro a, reflexivity, intro a, reflexivity end definition iso_of_ab_qg_group' {K L : property A} [is_subgroup A K] [is_subgroup A L] (p : K = L) : quotient_ab_group K ≃g quotient_ab_group L := iso_of_eq (eq_of_ab_qg_group' p) /- definition htpy_of_ab_qg_group' {K L : property A} [HK : is_subgroup A K] [HL : is_subgroup A L] (p : K = L) : (iso_of_ab_qg_group' p) ∘g ab_qg_map K ~ ab_qg_map L := begin revert HK, revert HL, induction p, intros HK HL, unfold iso_of_ab_qg_group', unfold ab_qg_map -- have HK = HL, begin apply @is_prop.elim _ _ HK HL end, -- rewrite this -- induction p, reflexivity end -/ definition eq_of_ab_qg_group {K L : property A} [is_subgroup A K] [is_subgroup A L] (K_in_L : Π (a : A), K a → L a) (L_in_K : Π (a : A), L a → K a) : quotient_ab_group K = quotient_ab_group L := eq_of_ab_qg_group' (subgroup_rel_eq K_in_L L_in_K) definition iso_of_ab_qg_group {K L : property A} [is_subgroup A K] [is_subgroup A L] (K_in_L : Π (a : A), K a → L a) (L_in_K : Π (a : A), L a → K a) : quotient_ab_group K ≃g quotient_ab_group L := iso_of_eq (eq_of_ab_qg_group K_in_L L_in_K) /- definition htpy_of_ab_qg_group {K L : property A} [is_subgroup A K] [is_subgroup A L] (K_in_L : Π (a : A), K a → L a) (L_in_K : Π (a : A), L a → K a) : iso_of_ab_qg_group K_in_L L_in_K ∘g ab_qg_map K ~ ab_qg_map L := begin fapply htpy_of_ab_qg_group' end -/ end quotient_group_iso_ua section quotient_group_iso variables {K L : property A} [is_subgroup A K] [is_subgroup A L] (H1 : Π (a : A), K a → L a) (H2 : Π (a : A), L a → K a) include H1 include H2 definition quotient_group_iso_contr_KL_map : quotient_ab_group K →g quotient_ab_group L := pr1 (center' (quotient_group_functor_contr H1)) definition quotient_group_iso_contr_KL_triangle : quotient_group_iso_contr_KL_map H1 H2 ∘g ab_qg_map K ~ ab_qg_map L := pr2 (center' (quotient_group_functor_contr H1)) definition quotient_group_iso_contr_KK : is_contr (Σ (g : quotient_ab_group K →g quotient_ab_group K), g ∘g ab_qg_map K ~ ab_qg_map K) := @quotient_group_functor_contr A K K _ _ (λ a, H2 a ∘ H1 a) definition quotient_group_iso_contr_LK : quotient_ab_group L →g quotient_ab_group K := pr1 (center' (@quotient_group_functor_contr A L K _ _ H2)) definition quotient_group_iso_contr_LL : quotient_ab_group L →g quotient_ab_group L := pr1 (center' (@quotient_group_functor_contr A L L _ _ (λ a, H1 a ∘ H2 a))) /- definition quotient_group_iso : quotient_ab_group K ≃g quotient_ab_group L := begin fapply isomorphism.mk, exact pr1 (center' (quotient_group_iso_contr_KL H1 H2)), fapply adjointify, exact quotient_group_iso_contr_LK H1 H2, intro x, induction x, reflexivity, end -/ definition quotient_group_iso_contr_aux : is_contr (Σ(gh : Σ (g : quotient_ab_group K →g quotient_ab_group L), g ∘g ab_qg_map K ~ ab_qg_map L), is_equiv (group_fun (pr1 gh))) := begin fapply is_trunc_sigma, exact quotient_group_functor_contr H1, intro a, induction a with g h, fapply is_contr_of_inhabited_prop, fapply adjointify, rexact group_fun (pr1 (center' (@quotient_group_functor_contr A L K _ _ H2))), note htpy := homotopy_of_eq (ap group_fun (ap sigma.pr1 (@quotient_group_functor_id _ L _ (λ a, (H1 a) ∘ (H2 a))))), have KK : is_contr ((Σ(g' : quotient_ab_group K →g quotient_ab_group K), g' ∘g ab_qg_map K ~ ab_qg_map K) ), from quotient_group_functor_contr (λ a, (H2 a) ∘ (H1 a)), -- have KK_path : ⟨g, h⟩ = ⟨id, λ a, refl (ab_qg_map K a)⟩, from eq_of_is_contr ⟨g, h⟩ ⟨id, λ a, refl (ab_qg_map K a)⟩, repeat exact sorry end /- definition quotient_group_iso_contr {K L : property A} [is_subgroup A K] [is_subgroup A L] (H1 : Π (a : A), K a → L a) (H2 : Π (a : A), L a → K a) : is_contr (Σ (g : quotient_ab_group K ≃g quotient_ab_group L), g ∘g ab_qg_map K ~ ab_qg_map L) := begin refine @is_trunc_equiv_closed (Σ(gh : Σ (g : quotient_ab_group K →g quotient_ab_group L), g ∘g ab_qg_map K ~ ab_qg_map L), is_equiv (group_fun (pr1 gh))) (Σ (g : quotient_ab_group K ≃g quotient_ab_group L), g ∘g ab_qg_map K ~ ab_qg_map L) -2 _ (quotient_group_iso_contr_aux H1 H2), exact calc (Σ gh, is_equiv (group_fun gh.1)) ≃ Σ (g : quotient_ab_group K →g quotient_ab_group L) (h : g ∘g ab_qg_map K ~ ab_qg_map L), is_equiv (group_fun g) : by exact (sigma_assoc_equiv (λ gh, is_equiv (group_fun gh.1)))⁻¹ ... ≃ (Σ (g : quotient_ab_group K ≃g quotient_ab_group L), g ∘g ab_qg_map K ~ ab_qg_map L) : _ end -/ end quotient_group_iso definition quotient_group_functor [constructor] (φ : G →g G') (h : Πg, g ∈ N → φ g ∈ N') : quotient_group N →g quotient_group N' := begin apply quotient_group_elim (qg_map N' ∘g φ), intro g Ng, esimp, refine qg_map_eq_one (φ g) (h g Ng) end ------------------------------------------------ -- FIRST ISOMORPHISM THEOREM ------------------------------------------------ definition kernel_quotient_extension {A B : AbGroup} (f : A →g B) : quotient_ab_group (kernel f) →g B := begin unfold quotient_ab_group, fapply @quotient_group_elim A B _ (@is_normal_subgroup_ab _ (kernel f) _) f, intro a, intro p, exact p end definition kernel_quotient_extension_triangle {A B : AbGroup} (f : A →g B) : kernel_quotient_extension f ∘ ab_qg_map (kernel f) ~ f := begin intro a, apply @quotient_group_compute _ _ _ (@is_normal_subgroup_ab _ (kernel f) _) end definition is_embedding_kernel_quotient_extension {A B : AbGroup} (f : A →g B) : is_embedding (kernel_quotient_extension f) := begin fapply is_embedding_of_is_mul_hom, intro x, note H := is_surjective_ab_qg_map (kernel f) x, induction H, induction p, intro q, apply @qg_map_eq_one _ _ (@is_normal_subgroup_ab _ (kernel f) _), refine _ ⬝ q, symmetry, rexact kernel_quotient_extension_triangle f a end definition ab_group_quotient_homomorphism (A B : AbGroup)(K : property A)(L : property B) [is_subgroup A K] [is_subgroup B L] (f : A →g B) (p : Π(a:A), a ∈ K → f a ∈ L) : quotient_ab_group K →g quotient_ab_group L := begin fapply @quotient_group_elim, exact (ab_qg_map L) ∘g f, intro a, intro k, exact @ab_qg_map_eq_one B L _ (f a) (p a k), end definition ab_group_kernel_factor {A B C: AbGroup} (f : A →g B)(g : A →g C){i : C →g B}(H : f = i ∘g g ) : kernel g ⊆ kernel f := begin intro a, intro p, exact calc f a = i (g a) : homotopy_of_eq (ap group_fun H) a ... = i 1 : ap i p ... = 1 : respect_one i end definition ab_group_triv_kernel_factor {A B C: AbGroup} (f : A →g B)(g : A →g C){i : C →g B}(H : f = i ∘g g ) : kernel f ⊆ '{1} → kernel g ⊆ '{1} := λ p, subproperty.trans (ab_group_kernel_factor f g H) p definition is_embedding_of_kernel_subproperty_one {A B : AbGroup} (f : A →g B) : kernel f ⊆ '{1} → is_embedding f := λ p, is_embedding_of_is_mul_hom _ (take x, assume h : f x = 1, show x = 1, from eq_of_mem_singleton (p _ h)) definition kernel_subproperty_one {A B : AbGroup} (f : A →g B) : is_embedding f → kernel f ⊆ '{1} := λ h x hx, have x = 1, from eq_one_of_is_mul_hom hx, show x ∈ '{1}, from mem_singleton_of_eq this definition ab_group_kernel_equivalent {A B : AbGroup} (C : AbGroup) (f : A →g B)(g : A →g C)(i : C →g B)(H : f = i ∘g g )(K : is_embedding i) : Π a:A, a ∈ kernel g ↔ a ∈ kernel f := exteq_of_subproperty_of_subproperty (show kernel g ⊆ kernel f, from ab_group_kernel_factor f g H) (show kernel f ⊆ kernel g, from take a, suppose f a = 1, have i (g a) = i 1, from calc i (g a) = f a : (homotopy_of_eq (ap group_fun H) a)⁻¹ ... = 1 : this ... = i 1 : (respect_one i)⁻¹, is_injective_of_is_embedding this) definition ab_group_kernel_image_lift (A B : AbGroup) (f : A →g B) : Π a : A, a ∈ kernel (image_lift f) ↔ a ∈ kernel f := begin fapply ab_group_kernel_equivalent (ab_Image f) (f) (image_lift(f)) (image_incl(f)), exact image_factor f, exact is_embedding_of_is_injective (image_incl_injective(f)), end definition ab_group_kernel_quotient_to_image {A B : AbGroup} (f : A →g B) : quotient_ab_group (kernel f) →g ab_Image (f) := begin fapply quotient_ab_group_elim (image_lift f), intro a, intro p, apply iff.mpr (ab_group_kernel_image_lift _ _ f a) p end definition ab_group_kernel_quotient_to_image_domain_triangle {A B : AbGroup} (f : A →g B) : ab_group_kernel_quotient_to_image (f) ∘g ab_qg_map (kernel f) ~ image_lift(f) := begin intros a, esimp, end definition ab_group_kernel_quotient_to_image_codomain_triangle {A B : AbGroup} (f : A →g B) : image_incl f ∘g ab_group_kernel_quotient_to_image f ~ kernel_quotient_extension f := begin intro x, induction x, reflexivity, fapply is_prop.elimo end definition is_surjective_kernel_quotient_to_image {A B : AbGroup} (f : A →g B) : is_surjective (ab_group_kernel_quotient_to_image f) := begin fapply is_surjective_factor (group_fun (ab_qg_map (kernel f))), exact image_lift f, apply @quotient_group_compute _ _ _ (@is_normal_subgroup_ab _ (kernel f) _), exact is_surjective_image_lift f end definition is_embedding_kernel_quotient_to_image {A B : AbGroup} (f : A →g B) : is_embedding (ab_group_kernel_quotient_to_image f) := begin fapply is_embedding_factor (ab_group_kernel_quotient_to_image f) (image_incl f) (kernel_quotient_extension f), exact ab_group_kernel_quotient_to_image_codomain_triangle f, exact is_embedding_kernel_quotient_extension f end definition ab_group_first_iso_thm {A B : AbGroup} (f : A →g B) : quotient_ab_group (kernel f) ≃g ab_Image f := begin fapply isomorphism.mk, exact ab_group_kernel_quotient_to_image f, fapply is_equiv_of_is_surjective_of_is_embedding, exact is_embedding_kernel_quotient_to_image f, exact is_surjective_kernel_quotient_to_image f end definition codomain_surjection_is_quotient {A B : AbGroup} (f : A →g B)( H : is_surjective f) : quotient_ab_group (kernel f) ≃g B := begin exact (ab_group_first_iso_thm f) ⬝g (iso_surjection_ab_image_incl f H) end definition codomain_surjection_is_quotient_triangle {A B : AbGroup} (f : A →g B)( H : is_surjective f) : codomain_surjection_is_quotient (f)(H) ∘g ab_qg_map (kernel f) ~ f := begin intro a, esimp end -- print iff.mpr /- set generating normal subgroup -/ section parameters {A₁ : AbGroup} (S : A₁ → Prop) variable {A₂ : AbGroup} inductive generating_relation' : A₁ → Type := | rincl : Π{g}, S g → generating_relation' g | rmul : Π{g h}, generating_relation' g → generating_relation' h → generating_relation' (g * h) | rinv : Π{g}, generating_relation' g → generating_relation' g⁻¹ | rone : generating_relation' 1 open generating_relation' definition generating_relation (g : A₁) : Prop := ∥ generating_relation' g ∥ local abbreviation R := generating_relation definition gr_one : R 1 := tr (rone S) definition gr_inv (g : A₁) : R g → R g⁻¹ := trunc_functor -1 rinv definition gr_mul (g h : A₁) : R g → R h → R (g * h) := trunc_functor2 rmul definition normal_generating_relation [instance] : is_subgroup A₁ generating_relation := ⦃ is_subgroup, one_mem := gr_one, inv_mem := gr_inv, mul_mem := gr_mul⦄ parameter (A₁) definition quotient_ab_group_gen : AbGroup := quotient_ab_group generating_relation definition gqg_map [constructor] : A₁ →g quotient_ab_group_gen := ab_qg_map _ parameter {A₁} definition gqg_eq_of_rel {g h : A₁} (H : S (g * h⁻¹)) : gqg_map g = gqg_map h := eq_of_rel (tr (rincl H)) -- this one might work if the previous one doesn't (maybe make this the default one?) definition gqg_eq_of_rel' {g h : A₁} (H : S (g * h⁻¹)) : class_of g = class_of h :> quotient_ab_group_gen := gqg_eq_of_rel H definition gqg_elim [constructor] (f : A₁ →g A₂) (H : Π⦃g⦄, S g → f g = 1) : quotient_ab_group_gen →g A₂ := begin apply quotient_ab_group_elim f, intro g r, induction r with r, induction r with g s g h r r' IH1 IH2 g r IH, { exact H s }, { exact !respect_mul ⬝ ap011 mul IH1 IH2 ⬝ !one_mul }, { exact !respect_inv ⬝ ap inv IH ⬝ !one_inv }, { apply respect_one } end definition gqg_elim_compute (f : A₁ →g A₂) (H : Π⦃g⦄, S g → f g = 1) : gqg_elim f H ∘ gqg_map ~ f := begin intro g, reflexivity end definition gqg_elim_unique (f : A₁ →g A₂) (H : Π⦃g⦄, S g → f g = 1) (k : quotient_ab_group_gen →g A₂) : ( k ∘g gqg_map ~ f ) → k ~ gqg_elim f H := !ab_gelim_unique end end group namespace group variables {G H K : Group} {R : property G} [is_normal_subgroup G R] {S : property H} [is_normal_subgroup H S] {T : property K} [is_normal_subgroup K T] theorem quotient_group_functor_compose (ψ : H →g K) (φ : G →g H) (hψ : Πg, g ∈ S → ψ g ∈ T) (hφ : Πg, g ∈ R → φ g ∈ S) : quotient_group_functor ψ hψ ∘g quotient_group_functor φ hφ ~ quotient_group_functor (ψ ∘g φ) (λg, proof hψ (φ g) qed ∘ hφ g) := begin intro g, induction g using set_quotient.rec_prop with g hg, reflexivity end definition quotient_group_functor_gid : quotient_group_functor (gid G) (λg, id) ~ gid (quotient_group R) := begin intro g, induction g using set_quotient.rec_prop with g hg, reflexivity end definition quotient_group_functor_homotopy {ψ φ : G →g H} (hψ : Πg, R g → S (ψ g)) (hφ : Πg, g ∈ R → φ g ∈ S) (p : φ ~ ψ) : quotient_group_functor φ hφ ~ quotient_group_functor ψ hψ := begin intro g, induction g using set_quotient.rec_prop with g hg, exact ap set_quotient.class_of (p g) end end group namespace group variables {G H K : AbGroup} {R : property G} [is_subgroup G R] {S : property H} [is_subgroup H S] {T : property K} [is_subgroup K T] definition quotient_ab_group_functor [constructor] (φ : G →g H) (h : Πg, g ∈ R → φ g ∈ S) : quotient_ab_group R →g quotient_ab_group S := @quotient_group_functor G H R (is_normal_subgroup_ab _) S (is_normal_subgroup_ab _) φ h definition quotient_ab_group_functor_mul (ψ φ : G →g H) (hψ : Πg, g ∈ R → ψ g ∈ S) (hφ : Πg, g ∈ R → φ g ∈ S) : homomorphism_mul (quotient_ab_group_functor ψ hψ) (quotient_ab_group_functor φ hφ) ~ quotient_ab_group_functor (homomorphism_mul ψ φ) (λg hg, is_subgroup.mul_mem (hψ g hg) (hφ g hg)) := begin intro g, induction g using set_quotient.rec_prop with g hg, reflexivity end theorem quotient_ab_group_functor_compose (ψ : H →g K) (φ : G →g H) (hψ : Πg, g ∈ S → ψ g ∈ T) (hφ : Πg, g ∈ R → φ g ∈ S) : quotient_ab_group_functor ψ hψ ∘g quotient_ab_group_functor φ hφ ~ quotient_ab_group_functor (ψ ∘g φ) (λg, proof hψ (φ g) qed ∘ hφ g) := @quotient_group_functor_compose G H K R _ S _ T _ ψ φ hψ hφ definition quotient_ab_group_functor_gid : quotient_ab_group_functor (gid G) (λg, id) ~ gid (quotient_ab_group R) := @quotient_group_functor_gid G R _ definition quotient_ab_group_functor_homotopy {ψ φ : G →g H} (hψ : Πg, R g → S (ψ g)) (hφ : Πg, g ∈ R → φ g ∈ S) (p : φ ~ ψ) : quotient_ab_group_functor φ hφ ~ quotient_ab_group_functor ψ hψ := @quotient_group_functor_homotopy G H R _ S _ ψ φ hψ hφ p end group
d2a050ef7858e574cd615ea5dea7d2a8c13f4eb2
d9d511f37a523cd7659d6f573f990e2a0af93c6f
/src/testing/slim_check/sampleable.lean
69b312ac6a9ceb39410b02de701c8f9c62d017c1
[ "Apache-2.0" ]
permissive
hikari0108/mathlib
b7ea2b7350497ab1a0b87a09d093ecc025a50dfa
a9e7d333b0cfd45f13a20f7b96b7d52e19fa2901
refs/heads/master
1,690,483,608,260
1,631,541,580,000
1,631,541,580,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
31,399
lean
/- Copyright (c) 2020 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Simon Hudon -/ import data.lazy_list.basic import data.tree import data.int.basic import control.bifunctor import control.ulift import tactic.linarith import testing.slim_check.gen /-! # `sampleable` Class This class permits the creation samples of a given type controlling the size of those values using the `gen` monad`. It also helps minimize examples by creating smaller versions of given values. When testing a proposition like `∀ n : ℕ, prime n → n ≤ 100`, `slim_check` requires that `ℕ` have an instance of `sampleable` and for `prime n` to be decidable. `slim_check` will then use the instance of `sampleable` to generate small examples of ℕ and progressively increase in size. For each example `n`, `prime n` is tested. If it is false, the example will be rejected (not a test success nor a failure) and `slim_check` will move on to other examples. If `prime n` is true, `n ≤ 100` will be tested. If it is false, `n` is a counter-example of `∀ n : ℕ, prime n → n ≤ 100` and the test fails. If `n ≤ 100` is true, the test passes and `slim_check` moves on to trying more examples. This is a port of the Haskell QuickCheck library. ## Main definitions * `sampleable` class * `sampleable_functor` and `sampleable_bifunctor` class * `sampleable_ext` class ### `sampleable` `sampleable α` provides ways of creating examples of type `α`, and given such an example `x : α`, gives us a way to shrink it and find simpler examples. ### `sampleable_ext` `sampleable_ext` generalizes the behavior of `sampleable` and makes it possible to express instances for types that do not lend themselves to introspection, such as `ℕ → ℕ`. If we test a quantification over functions the counter-examples cannot be shrunken or printed meaningfully. For that purpose, `sampleable_ext` provides a proxy representation `proxy_repr` that can be printed and shrunken as well as interpreted (using `interp`) as an object of the right type. ### `sampleable_functor` and `sampleable_bifunctor` `sampleable_functor F` and `sampleable_bifunctor F` makes it possible to create samples of and shrink `F α` given a sampling function and a shrinking function for arbitrary `α`. This allows us to separate the logic for generating the shape of a collection from the logic for generating its contents. Specifically, the contents could be generated using either `sampleable` or `sampleable_ext` instance and the `sampleable_(bi)functor` does not need to use that information ## Shrinking Shrinking happens when `slim_check` find a counter-example to a property. It is likely that the example will be more complicated than necessary so `slim_check` proceeds to shrink it as much as possible. Although equally valid, a smaller counter-example is easier for a user to understand and use. The `sampleable` class, beside having the `sample` function, has a `shrink` function so that we can use specialized knowledge while shrinking a value. It is not responsible for the whole shrinking process however. It only has to take one step in the shrinking process. `slim_check` will repeatedly call `shrink` until no more steps can be taken. Because `shrink` guarantees that the size of the candidates it produces is strictly smaller than the argument, we know that `slim_check` is guaranteed to terminate. ## Tags random testing ## References * https://hackage.haskell.org/package/QuickCheck -/ universes u v w namespace slim_check variables (α : Type u) local infix ` ≺ `:50 := has_well_founded.r /-- `sizeof_lt x y` compares the sizes of `x` and `y`. -/ def sizeof_lt {α} [has_sizeof α] (x y : α) := sizeof x < sizeof y /-- `shrink_fn α` is the type of functions that shrink an argument of type `α` -/ @[reducible] def shrink_fn (α : Type*) [has_sizeof α] := Π x : α, lazy_list { y : α // sizeof_lt y x } /-- `sampleable α` provides ways of creating examples of type `α`, and given such an example `x : α`, gives us a way to shrink it and find simpler examples. -/ class sampleable := [wf : has_sizeof α] (sample [] : gen α) (shrink : Π x : α, lazy_list { y : α // @sizeof _ wf y < @sizeof _ wf x } := λ _, lazy_list.nil) attribute [instance, priority 100] has_well_founded_of_has_sizeof default_has_sizeof attribute [instance, priority 200] sampleable.wf /-- `sampleable_functor F` makes it possible to create samples of and shrink `F α` given a sampling function and a shrinking function for arbitrary `α` -/ class sampleable_functor (F : Type u → Type v) [functor F] := [wf : Π α [has_sizeof α], has_sizeof (F α)] (sample [] : ∀ {α}, gen α → gen (F α)) (shrink : ∀ α [has_sizeof α], shrink_fn α → shrink_fn (F α)) (p_repr : ∀ α, has_repr α → has_repr (F α)) /-- `sampleable_bifunctor F` makes it possible to create samples of and shrink `F α β` given a sampling function and a shrinking function for arbitrary `α` and `β` -/ class sampleable_bifunctor (F : Type u → Type v → Type w) [bifunctor F] := [wf : Π α β [has_sizeof α] [has_sizeof β], has_sizeof (F α β)] (sample [] : ∀ {α β}, gen α → gen β → gen (F α β)) (shrink : ∀ α β [has_sizeof α] [has_sizeof β], shrink_fn α → shrink_fn β → shrink_fn (F α β)) (p_repr : ∀ α β, has_repr α → has_repr β → has_repr (F α β)) export sampleable (sample shrink) /-- This function helps infer the proxy representation and interpretation in `sampleable_ext` instances. -/ meta def sampleable.mk_trivial_interp : tactic unit := tactic.refine ``(id) /-- `sampleable_ext` generalizes the behavior of `sampleable` and makes it possible to express instances for types that do not lend themselves to introspection, such as `ℕ → ℕ`. If we test a quantification over functions the counter-examples cannot be shrunken or printed meaningfully. For that purpose, `sampleable_ext` provides a proxy representation `proxy_repr` that can be printed and shrunken as well as interpreted (using `interp`) as an object of the right type. -/ class sampleable_ext (α : Sort u) := (proxy_repr : Type v) [wf : has_sizeof proxy_repr] (interp [] : proxy_repr → α . sampleable.mk_trivial_interp) [p_repr : has_repr proxy_repr] (sample [] : gen proxy_repr) (shrink : shrink_fn proxy_repr) attribute [instance, priority 100] sampleable_ext.p_repr sampleable_ext.wf open nat lazy_list section prio open sampleable_ext set_option default_priority 50 instance sampleable_ext.of_sampleable {α} [sampleable α] [has_repr α] : sampleable_ext α := { proxy_repr := α, sample := sampleable.sample α, shrink := shrink } instance sampleable.functor {α} {F} [functor F] [sampleable_functor F] [sampleable α] : sampleable (F α) := { wf := _, sample := sampleable_functor.sample F (sampleable.sample α), shrink := sampleable_functor.shrink α sampleable.shrink } instance sampleable.bifunctor {α β} {F} [bifunctor F] [sampleable_bifunctor F] [sampleable α] [sampleable β] : sampleable (F α β) := { wf := _, sample := sampleable_bifunctor.sample F (sampleable.sample α) (sampleable.sample β), shrink := sampleable_bifunctor.shrink α β sampleable.shrink sampleable.shrink } set_option default_priority 100 instance sampleable_ext.functor {α} {F} [functor F] [sampleable_functor F] [sampleable_ext α] : sampleable_ext (F α) := { wf := _, proxy_repr := F (proxy_repr α), interp := functor.map (interp _), sample := sampleable_functor.sample F (sampleable_ext.sample α), shrink := sampleable_functor.shrink _ sampleable_ext.shrink, p_repr := sampleable_functor.p_repr _ sampleable_ext.p_repr } instance sampleable_ext.bifunctor {α β} {F} [bifunctor F] [sampleable_bifunctor F] [sampleable_ext α] [sampleable_ext β] : sampleable_ext (F α β) := { wf := _, proxy_repr := F (proxy_repr α) (proxy_repr β), interp := bifunctor.bimap (interp _) (interp _), sample := sampleable_bifunctor.sample F (sampleable_ext.sample α) (sampleable_ext.sample β), shrink := sampleable_bifunctor.shrink _ _ sampleable_ext.shrink sampleable_ext.shrink, p_repr := sampleable_bifunctor.p_repr _ _ sampleable_ext.p_repr sampleable_ext.p_repr } end prio /-- `nat.shrink' k n` creates a list of smaller natural numbers by successively dividing `n` by 2 and subtracting the difference from `k`. For example, `nat.shrink 100 = [50, 75, 88, 94, 97, 99]`. -/ def nat.shrink' (k : ℕ) : Π n : ℕ, n ≤ k → list { m : ℕ // has_well_founded.r m k } → list { m : ℕ // has_well_founded.r m k } | n hn ls := if h : n ≤ 1 then ls.reverse else have h₂ : 0 < n, by linarith, have 1 * n / 2 < n, from nat.div_lt_of_lt_mul (nat.mul_lt_mul_of_pos_right (by norm_num) h₂), have n / 2 < n, by simpa, let m := n / 2 in have h₀ : m ≤ k, from le_trans (le_of_lt this) hn, have h₃ : 0 < m, by simp only [m, lt_iff_add_one_le, zero_add]; rw [nat.le_div_iff_mul_le]; linarith, have h₁ : k - m < k, from nat.sub_lt (lt_of_lt_of_le h₂ hn) h₃, nat.shrink' m h₀ (⟨k - m, h₁⟩ :: ls) /-- `nat.shrink n` creates a list of smaller natural numbers by successively dividing by 2 and subtracting the difference from `n`. For example, `nat.shrink 100 = [50, 75, 88, 94, 97, 99]`. -/ def nat.shrink (n : ℕ) : list { m : ℕ // has_well_founded.r m n } := if h : n > 0 then have ∀ k, 1 < k → n / k < n, from λ k hk, nat.div_lt_of_lt_mul (suffices 1 * n < k * n, by simpa, nat.mul_lt_mul_of_pos_right hk h), ⟨n/11, this _ (by norm_num)⟩ :: ⟨n/3, this _ (by norm_num)⟩ :: nat.shrink' n n (le_refl _) [] else [] open gen /-- Transport a `sampleable` instance from a type `α` to a type `β` using functions between the two, going in both directions. Function `g` is used to define the well-founded order that `shrink` is expected to follow. -/ def sampleable.lift (α : Type u) {β : Type u} [sampleable α] (f : α → β) (g : β → α) (h : ∀ (a : α), sizeof (g (f a)) ≤ sizeof a) : sampleable β := { wf := ⟨ sizeof ∘ g ⟩, sample := f <$> sample α, shrink := λ x, have ∀ a, sizeof a < sizeof (g x) → sizeof (g (f a)) < sizeof (g x), by introv h'; solve_by_elim [lt_of_le_of_lt], subtype.map f this <$> shrink (g x) } instance nat.sampleable : sampleable ℕ := { sample := sized $ λ sz, freq [(1, coe <$> choose_any (fin $ succ (sz^3))), (3, coe <$> choose_any (fin $ succ sz))] dec_trivial, shrink := λ x, lazy_list.of_list $ nat.shrink x } /-- `iterate_shrink p x` takes a decidable predicate `p` and a value `x` of some sampleable type and recursively shrinks `x`. It first calls `shrink x` to get a list of candidate sample, finds the first that satisfies `p` and recursively tries to shrink that one. -/ def iterate_shrink {α} [has_to_string α] [sampleable α] (p : α → Prop) [decidable_pred p] : α → option α := well_founded.fix has_well_founded.wf $ λ x f_rec, do trace sformat!"{x} : {(shrink x).to_list}" $ pure (), y ← (shrink x).find (λ a, p a), f_rec y y.property <|> some y.val . instance fin.sampleable {n} [fact $ 0 < n] : sampleable (fin n) := sampleable.lift ℕ fin.of_nat' subtype.val $ λ i, (mod_le _ _ : i % n ≤ i) @[priority 100] instance fin.sampleable' {n} : sampleable (fin (succ n)) := sampleable.lift ℕ fin.of_nat subtype.val $ λ i, (mod_le _ _ : i % succ n ≤ i) instance pnat.sampleable : sampleable ℕ+ := sampleable.lift ℕ nat.succ_pnat pnat.nat_pred $ λ a, by unfold_wf; simp only [pnat.nat_pred, succ_pnat, pnat.mk_coe, nat.sub_zero, succ_sub_succ_eq_sub] /-- Redefine `sizeof` for `int` to make it easier to use with `nat` -/ def int.has_sizeof : has_sizeof ℤ := ⟨ int.nat_abs ⟩ local attribute [instance, priority 2000] int.has_sizeof instance int.sampleable : sampleable ℤ := { wf := _, sample := sized $ λ sz, freq [(1, subtype.val <$> choose (-(sz^3 + 1) : ℤ) (sz^3 + 1) (neg_le_self dec_trivial)), (3, subtype.val <$> choose (-(sz + 1)) (sz + 1) (neg_le_self dec_trivial))] dec_trivial, shrink := λ x, lazy_list.of_list $ (nat.shrink $ int.nat_abs x).bind $ λ ⟨y,h⟩, [⟨y, h⟩, ⟨-y, by dsimp [sizeof,has_sizeof.sizeof]; rw int.nat_abs_neg; exact h ⟩] } instance bool.sampleable : sampleable bool := { wf := ⟨ λ b, if b then 1 else 0 ⟩, sample := do { x ← choose_any bool, return x }, shrink := λ b, if h : b then lazy_list.singleton ⟨ff, by cases h; unfold_wf⟩ else lazy_list.nil } /-- Provided two shrinking functions `prod.shrink` shrinks a pair `(x, y)` by first shrinking `x` and pairing the results with `y` and then shrinking `y` and pairing the results with `x`. All pairs either contain `x` untouched or `y` untouched. We rely on shrinking being repeated for `x` to get maximally shrunken and then for `y` to get shrunken too. -/ def prod.shrink {α β} [has_sizeof α] [has_sizeof β] (shr_a : shrink_fn α) (shr_b : shrink_fn β) : shrink_fn (α × β) | ⟨x₀,x₁⟩ := let xs₀ : lazy_list { y : α × β // sizeof_lt y (x₀,x₁) } := (shr_a x₀).map $ subtype.map (λ a, (a, x₁)) (λ x h, by dsimp [sizeof_lt]; unfold_wf; apply h), xs₁ : lazy_list { y : α × β // sizeof_lt y (x₀,x₁) } := (shr_b x₁).map $ subtype.map (λ a, (x₀, a)) (λ x h, by dsimp [sizeof_lt]; unfold_wf; apply h) in xs₀.append xs₁ instance prod.sampleable : sampleable_bifunctor.{u v} prod := { wf := _, sample := λ α β sama samb, do { ⟨x⟩ ← (uliftable.up $ sama : gen (ulift.{max u v} α)), ⟨y⟩ ← (uliftable.up $ samb : gen (ulift.{max u v} β)), pure (x,y) }, shrink := @prod.shrink, p_repr := @prod.has_repr } instance sigma.sampleable {α β} [sampleable α] [sampleable β] : sampleable (Σ _ : α, β) := sampleable.lift (α × β) (λ ⟨x,y⟩, ⟨x,y⟩) (λ ⟨x,y⟩, ⟨x,y⟩) $ λ ⟨x,y⟩, le_refl _ /-- shrinking function for sum types -/ def sum.shrink {α β} [has_sizeof α] [has_sizeof β] (shrink_α : shrink_fn α) (shrink_β : shrink_fn β) : shrink_fn (α ⊕ β) | (sum.inr x) := (shrink_β x).map $ subtype.map sum.inr $ λ a, by dsimp [sizeof_lt]; unfold_wf; solve_by_elim | (sum.inl x) := (shrink_α x).map $ subtype.map sum.inl $ λ a, by dsimp [sizeof_lt]; unfold_wf; solve_by_elim instance sum.sampleable : sampleable_bifunctor.{u v} sum := { wf := _, sample := λ (α : Type u) (β : Type v) sam_α sam_β, (@uliftable.up_map gen.{u} gen.{max u v} _ _ _ _ (@sum.inl α β) sam_α <|> @uliftable.up_map gen.{v} gen.{max v u} _ _ _ _ (@sum.inr α β) sam_β), shrink := λ α β Iα Iβ shr_α shr_β, @sum.shrink _ _ Iα Iβ shr_α shr_β, p_repr := @sum.has_repr } instance rat.sampleable : sampleable ℚ := sampleable.lift (ℤ × ℕ+) (λ x, prod.cases_on x rat.mk_pnat) (λ r, (r.num, ⟨r.denom, r.pos⟩)) $ begin intro i, rcases i with ⟨x,⟨y,hy⟩⟩; unfold_wf; dsimp [rat.mk_pnat], mono*, { rw [← int.coe_nat_le, ← int.abs_eq_nat_abs, ← int.abs_eq_nat_abs], apply int.abs_div_le_abs }, { change _ - 1 ≤ y-1, apply nat.sub_le_sub_right, apply nat.div_le_of_le_mul, suffices : 1 * y ≤ x.nat_abs.gcd y * y, { simpa }, apply nat.mul_le_mul_right, apply gcd_pos_of_pos_right _ hy } end /-- `sampleable_char` can be specialized into customized `sampleable char` instances. The resulting instance has `1 / length` chances of making an unrestricted choice of characters and it otherwise chooses a character from `characters` with uniform probabilities. -/ def sampleable_char (length : nat) (characters : string) : sampleable char := { sample := do { x ← choose_nat 0 length dec_trivial, if x.val = 0 then do n ← sample ℕ, pure $ char.of_nat n else do i ← choose_nat 0 (characters.length - 1) dec_trivial, pure (characters.mk_iterator.nextn i).curr }, shrink := λ _, lazy_list.nil } instance char.sampleable : sampleable char := sampleable_char 3 " 0123abcABC:,;`\\/" variables {α} section list_shrink variables [has_sizeof α] (shr : Π x : α, lazy_list { y : α // sizeof_lt y x }) lemma list.sizeof_drop_lt_sizeof_of_lt_length {xs : list α} {k} (hk : 0 < k) (hk' : k < xs.length) : sizeof (list.drop k xs) < sizeof xs := begin induction xs with x xs generalizing k, { cases hk' }, cases k, { cases hk }, have : sizeof xs < sizeof (x :: xs), { unfold_wf, linarith }, cases k, { simp only [this, list.drop] }, { simp only [list.drop], transitivity, { solve_by_elim [xs_ih, lt_of_succ_lt_succ hk', zero_lt_succ] }, { assumption } } end lemma list.sizeof_cons_lt_right (a b : α) {xs : list α} (h : sizeof a < sizeof b) : sizeof (a :: xs) < sizeof (b :: xs) := by unfold_wf; assumption lemma list.sizeof_cons_lt_left (x : α) {xs xs' : list α} (h : sizeof xs < sizeof xs') : sizeof (x :: xs) < sizeof (x :: xs') := by unfold_wf; assumption lemma list.sizeof_append_lt_left {xs ys ys' : list α} (h : sizeof ys < sizeof ys') : sizeof (xs ++ ys) < sizeof (xs ++ ys') := begin induction xs, { apply h }, { unfold_wf, simp only [list.sizeof, add_lt_add_iff_left], exact xs_ih } end lemma list.one_le_sizeof (xs : list α) : 1 ≤ sizeof xs := by cases xs; unfold_wf; linarith /-- `list.shrink_removes` shrinks a list by removing chunks of size `k` in the middle of the list. -/ def list.shrink_removes (k : ℕ) (hk : 0 < k) : Π (xs : list α) n, n = xs.length → lazy_list { ys : list α // sizeof_lt ys xs } | xs n hn := if hkn : k > n then lazy_list.nil else if hkn' : k = n then have 1 < xs.sizeof, by { subst_vars, cases xs, { contradiction }, unfold_wf, apply lt_of_lt_of_le, show 1 < 1 + has_sizeof.sizeof xs_hd + 1, { linarith }, { mono, apply list.one_le_sizeof, } }, lazy_list.singleton ⟨[], this ⟩ else have h₂ : k < xs.length, from hn ▸ lt_of_le_of_ne (le_of_not_gt hkn) hkn', match list.split_at k xs, rfl : Π ys, ys = list.split_at k xs → _ with | ⟨xs₁,xs₂⟩, h := have h₄ : xs₁ = xs.take k, by simp only [list.split_at_eq_take_drop, prod.mk.inj_iff] at h; tauto, have h₃ : xs₂ = xs.drop k, by simp only [list.split_at_eq_take_drop, prod.mk.inj_iff] at h; tauto, have sizeof xs₂ < sizeof xs, by rw h₃; solve_by_elim [list.sizeof_drop_lt_sizeof_of_lt_length], have h₁ : n - k = xs₂.length, by simp only [h₃, ←hn, list.length_drop], have h₅ : ∀ (a : list α), sizeof_lt a xs₂ → sizeof_lt (xs₁ ++ a) xs, by intros a h; rw [← list.take_append_drop k xs, ← h₃, ← h₄]; solve_by_elim [list.sizeof_append_lt_left], lazy_list.cons ⟨xs₂, this⟩ $ subtype.map ((++) xs₁) h₅ <$> list.shrink_removes xs₂ (n - k) h₁ end /-- `list.shrink_one xs` shrinks list `xs` by shrinking only one item in the list. -/ def list.shrink_one : shrink_fn (list α) | [] := lazy_list.nil | (x :: xs) := lazy_list.append (subtype.map (λ x', x' :: xs) (λ a, list.sizeof_cons_lt_right _ _) <$> shr x) (subtype.map ((::) x) (λ _, list.sizeof_cons_lt_left _) <$> list.shrink_one xs) /-- `list.shrink_with shrink_f xs` shrinks `xs` by first considering `xs` with chunks removed in the middle (starting with chunks of size `xs.length` and halving down to `1`) and then shrinks only one element of the list. This strategy is taken directly from Haskell's QuickCheck -/ def list.shrink_with (xs : list α) : lazy_list { ys : list α // sizeof_lt ys xs } := let n := xs.length in lazy_list.append ((lazy_list.cons n $ (shrink n).reverse.map subtype.val).bind (λ k, if hk : 0 < k then list.shrink_removes k hk xs n rfl else lazy_list.nil )) (list.shrink_one shr _) end list_shrink instance list.sampleable : sampleable_functor list.{u} := { wf := _, sample := λ α sam_α, list_of sam_α, shrink := λ α Iα shr_α, @list.shrink_with _ Iα shr_α, p_repr := @list.has_repr } instance Prop.sampleable_ext : sampleable_ext Prop := { proxy_repr := bool, interp := coe, sample := choose_any bool, shrink := λ _, lazy_list.nil } /-- `no_shrink` is a type annotation to signal that a certain type is not to be shrunk. It can be useful in combination with other types: e.g. `xs : list (no_shrink ℤ)` will result in the list being cut down but individual integers being kept as is. -/ def no_shrink (α : Type*) := α instance no_shrink.inhabited {α} [inhabited α] : inhabited (no_shrink α) := ⟨ (default α : α) ⟩ /-- Introduction of the `no_shrink` type. -/ def no_shrink.mk {α} (x : α) : no_shrink α := x /-- Selector of the `no_shrink` type. -/ def no_shrink.get {α} (x : no_shrink α) : α := x instance no_shrink.sampleable {α} [sampleable α] : sampleable (no_shrink α) := { sample := no_shrink.mk <$> sample α } instance string.sampleable : sampleable string := { sample := do { x ← list_of (sample char), pure x.as_string }, .. sampleable.lift (list char) list.as_string string.to_list $ λ _, le_refl _ } /-- implementation of `sampleable (tree α)` -/ def tree.sample (sample : gen α) : ℕ → gen (tree α) | n := if h : n > 0 then have n / 2 < n, from div_lt_self h (by norm_num), tree.node <$> sample <*> tree.sample (n / 2) <*> tree.sample (n / 2) else pure tree.nil /-- `rec_shrink x f_rec` takes the recursive call `f_rec` introduced by `well_founded.fix` and turns it into a shrinking function whose result is adequate to use in a recursive call. -/ def rec_shrink {α : Type*} [has_sizeof α] (t : α) (sh : Π x : α, sizeof_lt x t → lazy_list { y : α // sizeof_lt y x }) : shrink_fn { t' : α // sizeof_lt t' t } | ⟨t',ht'⟩ := (λ t'' : { y : α // sizeof_lt y t' }, ⟨⟨t''.val, lt_trans t''.property ht'⟩, t''.property⟩ ) <$> sh t' ht' lemma tree.one_le_sizeof {α} [has_sizeof α] (t : tree α) : 1 ≤ sizeof t := by cases t; unfold_wf; linarith instance : functor tree := { map := @tree.map } /-- Recursion principle for shrinking tree-like structures. -/ def rec_shrink_with [has_sizeof α] (shrink_a : Π x : α, shrink_fn { y : α // sizeof_lt y x } → list (lazy_list { y : α // sizeof_lt y x })) : shrink_fn α := well_founded.fix (sizeof_measure_wf _) $ λ t f_rec, lazy_list.join (lazy_list.of_list $ shrink_a t $ λ ⟨t', h⟩, rec_shrink _ f_rec _) lemma rec_shrink_with_eq [has_sizeof α] (shrink_a : Π x : α, shrink_fn { y : α // sizeof_lt y x } → list (lazy_list { y : α // sizeof_lt y x })) (x : α) : rec_shrink_with shrink_a x = lazy_list.join (lazy_list.of_list $ shrink_a x $ λ t', rec_shrink _ (λ x h', rec_shrink_with shrink_a x) _) := begin conv_lhs { rw [rec_shrink_with, well_founded.fix_eq], }, congr, ext ⟨y, h⟩, refl end /-- `tree.shrink_with shrink_f t` shrinks `xs` by using the empty tree, each subtrees, and by shrinking the subtree to recombine them. This strategy is taken directly from Haskell's QuickCheck -/ def tree.shrink_with [has_sizeof α] (shrink_a : shrink_fn α) : shrink_fn (tree α) := rec_shrink_with $ λ t, match t with | tree.nil := λ f_rec, [] | (tree.node x t₀ t₁) := λ f_rec, have h₂ : sizeof_lt tree.nil (tree.node x t₀ t₁), by clear _match; have := tree.one_le_sizeof t₀; dsimp [sizeof_lt, sizeof, has_sizeof.sizeof] at *; unfold_wf; linarith, have h₀ : sizeof_lt t₀ (tree.node x t₀ t₁), by dsimp [sizeof_lt]; unfold_wf; linarith, have h₁ : sizeof_lt t₁ (tree.node x t₀ t₁), by dsimp [sizeof_lt]; unfold_wf; linarith, [lazy_list.of_list [⟨tree.nil, h₂⟩, ⟨t₀, h₀⟩, ⟨t₁, h₁⟩], (prod.shrink shrink_a (prod.shrink f_rec f_rec) (x, ⟨t₀, h₀⟩, ⟨t₁, h₁⟩)).map $ λ ⟨⟨y,⟨t'₀, _⟩,⟨t'₁, _⟩⟩,hy⟩, ⟨tree.node y t'₀ t'₁, by revert hy; dsimp [sizeof_lt]; unfold_wf; intro; linarith⟩] end instance sampleable_tree : sampleable_functor tree := { wf := _, sample := λ α sam_α, sized $ tree.sample sam_α, shrink := λ α Iα shr_α, @tree.shrink_with _ Iα shr_α, p_repr := @tree.has_repr } /-- Type tag that signals to `slim_check` to use small values for a given type. -/ def small (α : Type*) := α /-- Add the `small` type tag -/ def small.mk {α} (x : α) : small α := x /-- Type tag that signals to `slim_check` to use large values for a given type. -/ def large (α : Type*) := α /-- Add the `large` type tag -/ def large.mk {α} (x : α) : large α := x instance small.functor : functor small := id.monad.to_functor instance large.functor : functor large := id.monad.to_functor instance small.inhabited [inhabited α] : inhabited (small α) := ⟨ (default α : α) ⟩ instance large.inhabited [inhabited α] : inhabited (large α) := ⟨ (default α : α) ⟩ instance small.sampleable_functor : sampleable_functor small := { wf := _, sample := λ α samp, gen.resize (λ n, n / 5 + 5) samp, shrink := λ α _, id, p_repr := λ α, id } instance large.sampleable_functor : sampleable_functor large := { wf := _, sample := λ α samp, gen.resize (λ n, n * 5) samp, shrink := λ α _, id, p_repr := λ α, id } instance ulift.sampleable_functor : sampleable_functor ulift.{u v} := { wf := λ α h, ⟨ λ ⟨x⟩, @sizeof α h x ⟩, sample := λ α samp, uliftable.up_map ulift.up $ samp, shrink := λ α _ shr ⟨x⟩, (shr x).map (subtype.map ulift.up (λ a h, h)), p_repr := λ α h, ⟨ @repr α h ∘ ulift.down ⟩ } /-! ## Subtype instances The following instances are meant to improve the testing of properties of the form `∀ i j, i ≤ j, ...` The naive way to test them is to choose two numbers `i` and `j` and check that the proper ordering is satisfied. Instead, the following instances make it so that `j` will be chosen with considerations to the required ordering constraints. The benefit is that we will not have to discard any choice of `j`. -/ /-! ### Subtypes of `ℕ` -/ instance nat_le.sampleable {y} : slim_check.sampleable { x : ℕ // x ≤ y } := { sample := do { ⟨x,h⟩ ← slim_check.gen.choose_nat 0 y dec_trivial, pure ⟨x, h.2⟩}, shrink := λ ⟨x, h⟩, (λ a : subtype _, subtype.rec_on a $ λ x' h', ⟨⟨x', le_trans (le_of_lt h') h⟩, h'⟩) <$> shrink x } instance nat_ge.sampleable {x} : slim_check.sampleable { y : ℕ // x ≤ y } := { sample := do { (y : ℕ) ← slim_check.sampleable.sample ℕ, pure ⟨x+y, by norm_num⟩ }, shrink := λ ⟨y, h⟩, (λ a : { y' // sizeof y' < sizeof (y - x) }, subtype.rec_on a $ λ δ h', ⟨⟨x + δ, nat.le_add_right _ _⟩, nat.add_lt_of_lt_sub_left h'⟩) <$> shrink (y - x) } /- there is no `nat_lt.sampleable` instance because if `y = 0`, there is no valid choice to satisfy `x < y` -/ instance nat_gt.sampleable {x} : slim_check.sampleable { y : ℕ // x < y } := { sample := do { (y : ℕ) ← slim_check.sampleable.sample ℕ, pure ⟨x+y+1, by linarith⟩ }, shrink := λ x, shrink _ } /-! ### Subtypes of any `linear_ordered_add_comm_group` -/ instance le.sampleable {y : α} [sampleable α] [linear_ordered_add_comm_group α] : slim_check.sampleable { x : α // x ≤ y } := { sample := do { x ← sample α, pure ⟨y - abs x, sub_le_self _ (abs_nonneg _) ⟩ }, shrink := λ _, lazy_list.nil } instance ge.sampleable {x : α} [sampleable α] [linear_ordered_add_comm_group α] : slim_check.sampleable { y : α // x ≤ y } := { sample := do { y ← sample α, pure ⟨x + abs y, by norm_num [abs_nonneg]⟩ }, shrink := λ _, lazy_list.nil } /-! ### Subtypes of `ℤ` Specializations of `le.sampleable` and `ge.sampleable` for `ℤ` to help instance search. -/ instance int_le.sampleable {y : ℤ} : slim_check.sampleable { x : ℤ // x ≤ y } := sampleable.lift ℕ (λ n, ⟨y - n, int.sub_left_le_of_le_add $ by simp⟩) (λ ⟨i, h⟩, (y - i).nat_abs) (λ n, by unfold_wf; simp [int_le.sampleable._match_1]; ring) instance int_ge.sampleable {x : ℤ} : slim_check.sampleable { y : ℤ // x ≤ y } := sampleable.lift ℕ (λ n, ⟨x + n, by simp⟩) (λ ⟨i, h⟩, (i - x).nat_abs) (λ n, by unfold_wf; simp [int_ge.sampleable._match_1]; ring) instance int_lt.sampleable {y} : slim_check.sampleable { x : ℤ // x < y } := sampleable.lift ℕ (λ n, ⟨y - (n+1), int.sub_left_lt_of_lt_add $ by linarith [int.coe_nat_nonneg n]⟩) (λ ⟨i, h⟩, (y - i - 1).nat_abs) (λ n, by unfold_wf; simp [int_lt.sampleable._match_1]; ring) instance int_gt.sampleable {x} : slim_check.sampleable { y : ℤ // x < y } := sampleable.lift ℕ (λ n, ⟨x + (n+1), by linarith⟩) (λ ⟨i, h⟩, (i - x - 1).nat_abs) (λ n, by unfold_wf; simp [int_gt.sampleable._match_1]; ring) /-! ### Subtypes of any `list` -/ instance perm.slim_check {xs : list α} : slim_check.sampleable { ys : list α // list.perm xs ys } := { sample := permutation_of xs, shrink := λ _, lazy_list.nil } instance perm'.slim_check {xs : list α} : slim_check.sampleable { ys : list α // list.perm ys xs } := { sample := subtype.map id (@list.perm.symm α _) <$> permutation_of xs, shrink := λ _, lazy_list.nil } setup_tactic_parser open tactic /-- Print (at most) 10 samples of a given type to stdout for debugging. -/ def print_samples {t : Type u} [has_repr t] (g : gen t) : io unit := do xs ← io.run_rand $ uliftable.down $ do { xs ← (list.range 10).mmap $ g.run ∘ ulift.up, pure ⟨xs.map repr⟩ }, xs.mmap' io.put_str_ln /-- Create a `gen α` expression from the argument of `#sample` -/ meta def mk_generator (e : expr) : tactic (expr × expr) := do t ← infer_type e, match t with | `(gen %%t) := do repr_inst ← mk_app ``has_repr [t] >>= mk_instance, pure (repr_inst, e) | _ := do samp_inst ← to_expr ``(sampleable_ext %%e) >>= mk_instance, repr_inst ← mk_mapp ``sampleable_ext.p_repr [e, samp_inst], gen ← mk_mapp ``sampleable_ext.sample [none, samp_inst], pure (repr_inst, gen) end /-- `#sample my_type`, where `my_type` has an instance of `sampleable`, prints ten random values of type `my_type` of using an increasing size parameter. ```lean #sample nat -- prints -- 0 -- 0 -- 2 -- 24 -- 64 -- 76 -- 5 -- 132 -- 8 -- 449 -- or some other sequence of numbers #sample list int -- prints -- [] -- [1, 1] -- [-7, 9, -6] -- [36] -- [-500, 105, 260] -- [-290] -- [17, 156] -- [-2364, -7599, 661, -2411, -3576, 5517, -3823, -968] -- [-643] -- [11892, 16329, -15095, -15461] -- or whatever ``` -/ @[user_command] meta def sample_cmd (_ : parse $ tk "#sample") : lean.parser unit := do e ← texpr, of_tactic $ do e ← i_to_expr e, (repr_inst, gen) ← mk_generator e, print_samples ← mk_mapp ``print_samples [none, repr_inst, gen], sample ← eval_expr (io unit) print_samples, unsafe_run_io sample end slim_check
15520b4bceae2884b58cf940fc9bd0b536c93e57
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/Lean3Lib/init/meta/pexpr_auto.lean
e72f3221cd5201180ff50e594f8e08888bb7be1e
[]
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
468
lean
/- Copyright (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.meta.expr namespace Mathlib /-- Quoted expressions. They can be converted into expressions by using a tactic. -/ /-- Choice macros are used to implement overloading. -/ /-- Information about unelaborated structure instance expressions. -/ end Mathlib
f8af9c543f519352b5fe698ab86f909f5f10183f
94e33a31faa76775069b071adea97e86e218a8ee
/src/order/conditionally_complete_lattice.lean
eb077cb2759a79f6e7ae80ef67c253ccf78a891f
[ "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
50,783
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 -/ import order.bounds import data.set.intervals.basic import data.set.finite import data.set.lattice /-! # 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. -/ set_option old_structure_cmd true open function order_dual set variables {α β γ : Type*} {ι : Sort*} 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.has_Inf αᵒᵈ _).Inf⟩ noncomputable instance {α : Type*} [preorder α] [has_Inf α] : has_Inf (with_bot α) := ⟨(@with_top.has_Sup αᵒᵈ _ _).Sup⟩ @[simp] theorem with_top.cInf_empty {α : Type*} [has_Inf α] : Inf (∅ : set (with_top α)) = ⊤ := if_pos $ set.empty_subset _ @[simp] theorem with_bot.cSup_empty {α : Type*} [has_Sup α] : Sup (∅ : set (with_bot α)) = ⊥ := if_pos $ set.empty_subset _ end -- section /-- 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*) extends lattice α, has_Sup α, has_Inf α := (le_cSup : ∀ s a, bdd_above s → a ∈ s → a ≤ Sup s) (cSup_le : ∀ s a, set.nonempty s → a ∈ upper_bounds s → Sup s ≤ a) (cInf_le : ∀ s a, bdd_below s → a ∈ s → Inf s ≤ a) (le_cInf : ∀ s a, set.nonempty s → a ∈ lower_bounds s → a ≤ Inf s) /-- A conditionally complete linear order is a linear order 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 linear orders, 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_linear_order (α : Type*) extends conditionally_complete_lattice α, linear_order α renaming max → sup min → inf /-- A conditionally complete linear order with `bot` is a linear order with least element, in which every nonempty subset which is bounded above has a supremum, and every nonempty subset (necessarily bounded below) has an infimum. A typical example is the natural numbers. To differentiate the statements from the corresponding statements in (unconditional) complete linear orders, 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.-/ @[ancestor conditionally_complete_linear_order has_bot] class conditionally_complete_linear_order_bot (α : Type*) extends conditionally_complete_linear_order α, has_bot α := (bot_le : ∀ x : α, ⊥ ≤ x) (cSup_empty : Sup ∅ = ⊥) @[priority 100] -- see Note [lower instance priority] instance conditionally_complete_linear_order_bot.to_order_bot [h : conditionally_complete_linear_order_bot α] : order_bot α := { ..h } /-- 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 complete_lattice.to_conditionally_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 complete_linear_order.to_conditionally_complete_linear_order_bot {α : Type*} [complete_linear_order α] : conditionally_complete_linear_order_bot α := { cSup_empty := Sup_empty, ..complete_lattice.to_conditionally_complete_lattice, .. ‹complete_linear_order α› } section open_locale classical /-- A well founded linear order is conditionally complete, with a bottom element. -/ @[reducible] noncomputable def is_well_order.conditionally_complete_linear_order_bot (α : Type*) [i₁ : linear_order α] [i₂ : order_bot α] [h : is_well_order α (<)] : conditionally_complete_linear_order_bot α := { Inf := λ s, if hs : s.nonempty then h.wf.min s hs else ⊥, cInf_le := λ s a hs has, begin have s_ne : s.nonempty := ⟨a, has⟩, simpa [s_ne] using not_lt.1 (h.wf.not_lt_min s s_ne has), end, le_cInf := λ s a hs has, begin simp only [hs, dif_pos], exact has (h.wf.min_mem s hs), end, Sup := λ s, if hs : (upper_bounds s).nonempty then h.wf.min _ hs else ⊥, le_cSup := λ s a hs has, begin have h's : (upper_bounds s).nonempty := hs, simp only [h's, dif_pos], exact h.wf.min_mem _ h's has, end, cSup_le := λ s a hs has, begin have h's : (upper_bounds s).nonempty := ⟨a, has⟩, simp only [h's, dif_pos], simpa using h.wf.not_lt_min _ h's has, end, cSup_empty := by simpa using eq_bot_iff.2 (not_lt.1 $ h.wf.not_lt_min _ _ $ mem_univ ⊥), ..i₁, ..i₂, ..linear_order.to_lattice } end section order_dual instance (α : Type*) [conditionally_complete_lattice α] : conditionally_complete_lattice αᵒᵈ := { le_cSup := @conditionally_complete_lattice.cInf_le α _, cSup_le := @conditionally_complete_lattice.le_cInf α _, le_cInf := @conditionally_complete_lattice.cSup_le α _, cInf_le := @conditionally_complete_lattice.le_cSup α _, ..order_dual.has_Inf α, ..order_dual.has_Sup α, ..order_dual.lattice α } instance (α : Type*) [conditionally_complete_linear_order α] : conditionally_complete_linear_order αᵒᵈ := { ..order_dual.conditionally_complete_lattice α, ..order_dual.linear_order α } end order_dual 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.nonempty) (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.nonempty) (h₂ : ∀ b ∈ s, a ≤ b) : a ≤ Inf s := conditionally_complete_lattice.le_cInf s a h₁ h₂ theorem le_cSup_of_le (hs : bdd_above s) (hb : b ∈ s) (h : a ≤ b) : a ≤ Sup s := le_trans h (le_cSup hs hb) theorem cInf_le_of_le (hs : bdd_below s) (hb : b ∈ s) (h : b ≤ a) : Inf s ≤ a := le_trans (cInf_le hs hb) h theorem cSup_le_cSup (ht : bdd_above t) (hs : s.nonempty) (h : s ⊆ t) : Sup s ≤ Sup t := cSup_le hs (λ a ha, le_cSup ht (h ha)) theorem cInf_le_cInf (ht : bdd_below t) (hs : s.nonempty) (h : s ⊆ t) : Inf t ≤ Inf s := le_cInf hs (λ a ha, cInf_le ht (h ha)) theorem le_cSup_iff (h : bdd_above s) (hs : s.nonempty) : a ≤ Sup s ↔ ∀ b, b ∈ upper_bounds s → a ≤ b := ⟨λ h b hb, le_trans h (cSup_le hs hb), λ hb, hb _ (λ x, le_cSup h)⟩ theorem cInf_le_iff (h : bdd_below s) (hs : s.nonempty) : Inf s ≤ a ↔ ∀ b ∈ lower_bounds s, b ≤ a := ⟨λ h b hb, le_trans (le_cInf hs hb) h, λ hb, hb _ (λ x, cInf_le h)⟩ lemma is_lub_cSup (ne : s.nonempty) (H : bdd_above s) : is_lub s (Sup s) := ⟨λ x, le_cSup H, λ x, cSup_le ne⟩ lemma is_lub_csupr [nonempty ι] {f : ι → α} (H : bdd_above (range f)) : is_lub (range f) (⨆ i, f i) := is_lub_cSup (range_nonempty f) H lemma is_lub_csupr_set {f : β → α} {s : set β} (H : bdd_above (f '' s)) (Hne : s.nonempty) : is_lub (f '' s) (⨆ i : s, f i) := by { rw ← Sup_image', exact is_lub_cSup (Hne.image _) H } lemma is_glb_cInf (ne : s.nonempty) (H : bdd_below s) : is_glb s (Inf s) := ⟨λ x, cInf_le H, λ x, le_cInf ne⟩ lemma is_glb_cinfi [nonempty ι] {f : ι → α} (H : bdd_below (range f)) : is_glb (range f) (⨅ i, f i) := is_glb_cInf (range_nonempty f) H lemma is_glb_cinfi_set {f : β → α} {s : set β} (H : bdd_below (f '' s)) (Hne : s.nonempty) : is_glb (f '' s) (⨅ i : s, f i) := @is_lub_csupr_set αᵒᵈ _ _ _ _ H Hne lemma csupr_le_iff [nonempty ι] {f : ι → α} {a : α} (hf : bdd_above (range f)) : supr f ≤ a ↔ ∀ i, f i ≤ a := (is_lub_le_iff $ is_lub_csupr hf).trans forall_range_iff lemma le_cinfi_iff [nonempty ι] {f : ι → α} {a : α} (hf : bdd_below (range f)) : a ≤ infi f ↔ ∀ i, a ≤ f i := (le_is_glb_iff $ is_glb_cinfi hf).trans forall_range_iff lemma csupr_set_le_iff {ι : Type*} {s : set ι} {f : ι → α} {a : α} (hs : s.nonempty) (hf : bdd_above (f '' s)) : (⨆ i : s, f i) ≤ a ↔ ∀ i ∈ s, f i ≤ a := (is_lub_le_iff $ is_lub_csupr_set hf hs).trans ball_image_iff lemma le_cinfi_set_iff {ι : Type*} {s : set ι} {f : ι → α} {a : α} (hs : s.nonempty) (hf : bdd_below (f '' s)) : a ≤ (⨅ i : s, f i) ↔ ∀ i ∈ s, a ≤ f i := (le_is_glb_iff $ is_glb_cinfi_set hf hs).trans ball_image_iff lemma is_lub.cSup_eq (H : is_lub s a) (ne : s.nonempty) : Sup s = a := (is_lub_cSup ne ⟨a, H.1⟩).unique H lemma is_lub.csupr_eq [nonempty ι] {f : ι → α} (H : is_lub (range f) a) : (⨆ i, f i) = a := H.cSup_eq (range_nonempty f) lemma is_lub.csupr_set_eq {s : set β} {f : β → α} (H : is_lub (f '' s) a) (Hne : s.nonempty) : (⨆ i : s, f i) = a := is_lub.cSup_eq (image_eq_range f s ▸ H) (image_eq_range f s ▸ Hne.image f) /-- A greatest element of a set is the supremum of this set. -/ lemma is_greatest.cSup_eq (H : is_greatest s a) : Sup s = a := H.is_lub.cSup_eq H.nonempty lemma is_greatest.Sup_mem (H : is_greatest s a) : Sup s ∈ s := H.cSup_eq.symm ▸ H.1 lemma is_glb.cInf_eq (H : is_glb s a) (ne : s.nonempty) : Inf s = a := (is_glb_cInf ne ⟨a, H.1⟩).unique H lemma is_glb.cinfi_eq [nonempty ι] {f : ι → α} (H : is_glb (range f) a) : (⨅ i, f i) = a := H.cInf_eq (range_nonempty f) lemma is_glb.cinfi_set_eq {s : set β} {f : β → α} (H : is_glb (f '' s) a) (Hne : s.nonempty) : (⨅ i : s, f i) = a := is_glb.cInf_eq (image_eq_range f s ▸ H) (image_eq_range f s ▸ Hne.image f) /-- A least element of a set is the infimum of this set. -/ lemma is_least.cInf_eq (H : is_least s a) : Inf s = a := H.is_glb.cInf_eq H.nonempty lemma is_least.Inf_mem (H : is_least s a) : Inf s ∈ s := H.cInf_eq.symm ▸ H.1 lemma subset_Icc_cInf_cSup (hb : bdd_below s) (ha : bdd_above s) : s ⊆ Icc (Inf s) (Sup s) := λ x hx, ⟨cInf_le hb hx, le_cSup ha hx⟩ theorem cSup_le_iff (hb : bdd_above s) (hs : s.nonempty) : Sup s ≤ a ↔ ∀ b ∈ s, b ≤ a := is_lub_le_iff (is_lub_cSup hs hb) theorem le_cInf_iff (hb : bdd_below s) (hs : s.nonempty) : a ≤ Inf s ↔ ∀ b ∈ s, a ≤ b := le_is_glb_iff (is_glb_cInf hs hb) lemma cSup_lower_bounds_eq_cInf {s : set α} (h : bdd_below s) (hs : s.nonempty) : Sup (lower_bounds s) = Inf s := (is_lub_cSup h $ hs.mono $ λ x hx y hy, hy hx).unique (is_glb_cInf hs h).is_lub lemma cInf_upper_bounds_eq_cSup {s : set α} (h : bdd_above s) (hs : s.nonempty) : Inf (upper_bounds s) = Sup s := (is_glb_cInf h $ hs.mono $ λ x hx y hy, hy hx).unique (is_lub_cSup hs h).is_glb lemma not_mem_of_lt_cInf {x : α} {s : set α} (h : x < Inf s) (hs : bdd_below s) : x ∉ s := λ hx, lt_irrefl _ (h.trans_le (cInf_le hs hx)) lemma not_mem_of_cSup_lt {x : α} {s : set α} (h : Sup s < x) (hs : bdd_above s) : x ∉ s := @not_mem_of_lt_cInf αᵒᵈ _ x s h hs /--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 `Sup_eq_of_forall_le_of_forall_lt_exists_gt` for a version in complete lattices. -/ theorem cSup_eq_of_forall_le_of_forall_lt_exists_gt (hs : s.nonempty) (H : ∀ a ∈ s, a ≤ b) (H' : ∀ w, w < b → ∃ a ∈ s, w < a) : Sup s = b := eq_of_le_of_not_lt (cSup_le hs H) $ λ hb, let ⟨a, ha, ha'⟩ := H' _ hb in lt_irrefl _ $ ha'.trans_le $ le_cSup ⟨b, H⟩ ha /--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 `Inf_eq_of_forall_ge_of_forall_gt_exists_lt` for a version in complete lattices. -/ theorem cInf_eq_of_forall_ge_of_forall_gt_exists_lt : s.nonempty → (∀ a ∈ s, b ≤ a) → (∀ w, b < w → ∃ a ∈ s, a < w) → Inf s = b := @cSup_eq_of_forall_le_of_forall_lt_exists_gt αᵒᵈ _ _ _ /--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 (hs : bdd_above s) (ha : a ∈ s) (h : b < a) : b < Sup s := lt_of_lt_of_le h (le_cSup hs ha) /--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_cSup_of_lt αᵒᵈ _ _ _ _ /-- If all elements of a nonempty set `s` are less than or equal to all elements of a nonempty set `t`, then there exists an element between these sets. -/ lemma exists_between_of_forall_le (sne : s.nonempty) (tne : t.nonempty) (hst : ∀ (x ∈ s) (y ∈ t), x ≤ y) : (upper_bounds s ∩ lower_bounds t).nonempty := ⟨Inf t, λ x hx, le_cInf tne $ hst x hx, λ y hy, cInf_le (sne.mono hst) hy⟩ /--The supremum of a singleton is the element of the singleton-/ @[simp] theorem cSup_singleton (a : α) : Sup {a} = a := is_greatest_singleton.cSup_eq /--The infimum of a singleton is the element of the singleton-/ @[simp] theorem cInf_singleton (a : α) : Inf {a} = a := is_least_singleton.cInf_eq @[simp] theorem cSup_pair (a b : α) : Sup {a, b} = a ⊔ b := (@is_lub_pair _ _ a b).cSup_eq (insert_nonempty _ _) @[simp] theorem cInf_pair (a b : α) : Inf {a, b} = a ⊓ b := (@is_glb_pair _ _ a b).cInf_eq (insert_nonempty _ _) /--If a set is bounded below and above, and nonempty, its infimum is less than or equal to its supremum.-/ theorem cInf_le_cSup (hb : bdd_below s) (ha : bdd_above s) (ne : s.nonempty) : Inf s ≤ Sup s := is_glb_le_is_lub (is_glb_cInf ne hb) (is_lub_cSup ne ha) ne /--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 (hs : bdd_above s) (sne : s.nonempty) (ht : bdd_above t) (tne : t.nonempty) : Sup (s ∪ t) = Sup s ⊔ Sup t := ((is_lub_cSup sne hs).union (is_lub_cSup tne ht)).cSup_eq sne.inl /--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 (hs : bdd_below s) (sne : s.nonempty) (ht : bdd_below t) (tne : t.nonempty) : Inf (s ∪ t) = Inf s ⊓ Inf t := @cSup_union αᵒᵈ _ _ _ hs sne ht tne /--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 (hs : bdd_above s) (ht : bdd_above t) (hst : (s ∩ t).nonempty) : Sup (s ∩ t) ≤ Sup s ⊓ Sup t := cSup_le hst $ λ x hx, le_inf (le_cSup hs hx.1) (le_cSup ht hx.2) /--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).nonempty → Inf s ⊔ Inf t ≤ Inf (s ∩ t) := @cSup_inter_le αᵒᵈ _ _ _ /-- 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 (hs : bdd_above s) (sne : s.nonempty) : Sup (insert a s) = a ⊔ Sup s := ((is_lub_cSup sne hs).insert a).cSup_eq (insert_nonempty a s) /-- 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 (hs : bdd_below s) (sne : s.nonempty) : Inf (insert a s) = a ⊓ Inf s := @cSup_insert αᵒᵈ _ _ _ hs sne @[simp] lemma cInf_Icc (h : a ≤ b) : Inf (Icc a b) = a := (is_glb_Icc h).cInf_eq (nonempty_Icc.2 h) @[simp] lemma cInf_Ici : Inf (Ici a) = a := is_least_Ici.cInf_eq @[simp] lemma cInf_Ico (h : a < b) : Inf (Ico a b) = a := (is_glb_Ico h).cInf_eq (nonempty_Ico.2 h) @[simp] lemma cInf_Ioc [densely_ordered α] (h : a < b) : Inf (Ioc a b) = a := (is_glb_Ioc h).cInf_eq (nonempty_Ioc.2 h) @[simp] lemma cInf_Ioi [no_max_order α] [densely_ordered α] : Inf (Ioi a) = a := cInf_eq_of_forall_ge_of_forall_gt_exists_lt nonempty_Ioi (λ _, le_of_lt) (λ w hw, by simpa using exists_between hw) @[simp] lemma cInf_Ioo [densely_ordered α] (h : a < b) : Inf (Ioo a b) = a := (is_glb_Ioo h).cInf_eq (nonempty_Ioo.2 h) @[simp] lemma cSup_Icc (h : a ≤ b) : Sup (Icc a b) = b := (is_lub_Icc h).cSup_eq (nonempty_Icc.2 h) @[simp] lemma cSup_Ico [densely_ordered α] (h : a < b) : Sup (Ico a b) = b := (is_lub_Ico h).cSup_eq (nonempty_Ico.2 h) @[simp] lemma cSup_Iic : Sup (Iic a) = a := is_greatest_Iic.cSup_eq @[simp] lemma cSup_Iio [no_min_order α] [densely_ordered α] : Sup (Iio a) = a := cSup_eq_of_forall_le_of_forall_lt_exists_gt nonempty_Iio (λ _, le_of_lt) (λ w hw, by simpa [and_comm] using exists_between hw) @[simp] lemma cSup_Ioc (h : a < b) : Sup (Ioc a b) = b := (is_lub_Ioc h).cSup_eq (nonempty_Ioc.2 h) @[simp] lemma cSup_Ioo [densely_ordered α] (h : a < b) : Sup (Ioo a b) = b := (is_lub_Ioo h).cSup_eq (nonempty_Ioo.2 h) /--The indexed supremum of a function is bounded above by a uniform bound-/ lemma csupr_le [nonempty ι] {f : ι → α} {c : α} (H : ∀ x, f x ≤ c) : supr f ≤ c := cSup_le (range_nonempty f) (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 _) lemma le_csupr_of_le {f : ι → α} (H : bdd_above (range f)) (c : ι) (h : a ≤ f c) : a ≤ supr f := le_trans h (le_csupr H c) /--The indexed supremum of two functions are comparable if the functions are pointwise comparable-/ lemma csupr_mono {f g : ι → α} (B : bdd_above (range g)) (H : ∀ x, f x ≤ g x) : supr f ≤ supr g := begin casesI is_empty_or_nonempty ι, { rw [supr_of_empty', supr_of_empty'] }, { exact csupr_le (λ x, le_csupr_of_le B x (H x)) }, end lemma le_csupr_set {f : β → α} {s : set β} (H : bdd_above (f '' s)) {c : β} (hc : c ∈ s) : f c ≤ ⨆ i : s, f i := (le_cSup H $ mem_image_of_mem f hc).trans_eq Sup_image' /--The indexed infimum of two functions are comparable if the functions are pointwise comparable-/ lemma cinfi_mono {f g : ι → α} (B : bdd_below (range f)) (H : ∀ x, f x ≤ g x) : infi f ≤ infi g := @csupr_mono αᵒᵈ _ _ _ _ B H /--The indexed minimum of a function is bounded below by a uniform lower bound-/ lemma le_cinfi [nonempty ι] {f : ι → α} {c : α} (H : ∀ x, c ≤ f x) : c ≤ infi f := @csupr_le αᵒᵈ _ _ _ _ _ H /--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 := @le_csupr αᵒᵈ _ _ _ H c lemma cinfi_le_of_le {f : ι → α} (H : bdd_below (range f)) (c : ι) (h : f c ≤ a) : infi f ≤ a := @le_csupr_of_le αᵒᵈ _ _ _ _ H c h lemma cinfi_set_le {f : β → α} {s : set β} (H : bdd_below (f '' s)) {c : β} (hc : c ∈ s) : (⨅ i : s, f i) ≤ f c := @le_csupr_set αᵒᵈ _ _ _ _ H _ hc @[simp] theorem csupr_const [hι : nonempty ι] {a : α} : (⨆ b : ι, a) = a := by rw [supr, range_const, cSup_singleton] @[simp] theorem cinfi_const [hι : nonempty ι] {a : α} : (⨅ b:ι, a) = a := @csupr_const αᵒᵈ _ _ _ _ @[simp] theorem supr_unique [unique ι] {s : ι → α} : (⨆ i, s i) = s default := have ∀ i, s i = s default := λ i, congr_arg s (unique.eq_default i), by simp only [this, csupr_const] @[simp] theorem infi_unique [unique ι] {s : ι → α} : (⨅ i, s i) = s default := @supr_unique αᵒᵈ _ _ _ _ @[simp] lemma csupr_pos {p : Prop} {f : p → α} (hp : p) : (⨆ h : p, f h) = f hp := by haveI := unique_prop hp; exact supr_unique @[simp] lemma cinfi_pos {p : Prop} {f : p → α} (hp : p) : (⨅ h : p, f h) = f hp := @csupr_pos αᵒᵈ _ _ _ hp lemma csupr_set {s : set β} {f : β → α} : (⨆ x : s, f x) = Sup (f '' s) := begin rw supr, congr, ext, rw [mem_image, mem_range, set_coe.exists], simp_rw [subtype.coe_mk, exists_prop], end lemma cinfi_set {s : set β} {f : β → α} : (⨅ x : s, f x) = Inf (f '' s) := @csupr_set αᵒᵈ _ _ _ _ /--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 `supr_eq_of_forall_le_of_forall_lt_exists_gt` for a version in complete lattices. -/ theorem csupr_eq_of_forall_le_of_forall_lt_exists_gt [nonempty ι] {f : ι → α} (h₁ : ∀ i, f i ≤ b) (h₂ : ∀ w, w < b → (∃ i, w < f i)) : (⨆ (i : ι), f i) = b := cSup_eq_of_forall_le_of_forall_lt_exists_gt (range_nonempty f) (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 `infi_eq_of_forall_ge_of_forall_gt_exists_lt` for a version in complete lattices. -/ theorem cinfi_eq_of_forall_ge_of_forall_gt_exists_lt [nonempty ι] {f : ι → α} (h₁ : ∀ i, b ≤ f i) (h₂ : ∀ w, b < w → (∃ i, f i < w)) : (⨅ (i : ι), f i) = b := @csupr_eq_of_forall_le_of_forall_lt_exists_gt αᵒᵈ _ _ _ _ ‹_› ‹_› ‹_› /-- Nested intervals lemma: if `f` is a monotone sequence, `g` is an antitone sequence, and `f n ≤ g n` for all `n`, then `⨆ n, f n` belongs to all the intervals `[f n, g n]`. -/ lemma monotone.csupr_mem_Inter_Icc_of_antitone [semilattice_sup β] {f g : β → α} (hf : monotone f) (hg : antitone g) (h : f ≤ g) : (⨆ n, f n) ∈ ⋂ n, Icc (f n) (g n) := begin refine mem_Inter.2 (λ n, _), haveI : nonempty β := ⟨n⟩, have : ∀ m, f m ≤ g n := λ m, hf.forall_le_of_antitone hg h m n, exact ⟨le_csupr ⟨g $ n, forall_range_iff.2 this⟩ _, csupr_le this⟩ end /-- Nested intervals lemma: if `[f n, g n]` is an antitone sequence of nonempty closed intervals, then `⨆ n, f n` belongs to all the intervals `[f n, g n]`. -/ lemma csupr_mem_Inter_Icc_of_antitone_Icc [semilattice_sup β] {f g : β → α} (h : antitone (λ n, Icc (f n) (g n))) (h' : ∀ n, f n ≤ g n) : (⨆ n, f n) ∈ ⋂ n, Icc (f n) (g n) := monotone.csupr_mem_Inter_Icc_of_antitone (λ m n hmn, ((Icc_subset_Icc_iff (h' n)).1 (h hmn)).1) (λ m n hmn, ((Icc_subset_Icc_iff (h' n)).1 (h hmn)).2) h' lemma finset.nonempty.sup'_eq_cSup_image {s : finset β} (hs : s.nonempty) (f : β → α) : s.sup' hs f = Sup (f '' s) := eq_of_forall_ge_iff $ λ a, by simp [cSup_le_iff (s.finite_to_set.image f).bdd_above (hs.to_set.image f)] lemma finset.nonempty.sup'_id_eq_cSup {s : finset α} (hs : s.nonempty) : s.sup' hs id = Sup s := by rw [hs.sup'_eq_cSup_image, image_id] /--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_eq_of_is_forall_le_of_forall_le_imp_ge (hs : s.nonempty) (h_is_ub : ∀ a ∈ s, a ≤ b) (h_b_le_ub : ∀ub, (∀ a ∈ s, a ≤ ub) → (b ≤ ub)) : Sup s = b := (cSup_le hs h_is_ub).antisymm (h_b_le_ub _ $ λ a, le_cSup ⟨b, h_is_ub⟩) end conditionally_complete_lattice instance pi.conditionally_complete_lattice {ι : Type*} {α : Π i : ι, Type*} [Π i, conditionally_complete_lattice (α i)] : conditionally_complete_lattice (Π i, α i) := { le_cSup := λ s f ⟨g, hg⟩ hf i, le_cSup ⟨g i, set.forall_range_iff.2 $ λ ⟨f', hf'⟩, hg hf' i⟩ ⟨⟨f, hf⟩, rfl⟩, cSup_le := λ s f hs hf i, cSup_le (by haveI := hs.to_subtype; apply range_nonempty) $ λ b ⟨⟨g, hg⟩, hb⟩, hb ▸ hf hg i, cInf_le := λ s f ⟨g, hg⟩ hf i, cInf_le ⟨g i, set.forall_range_iff.2 $ λ ⟨f', hf'⟩, hg hf' i⟩ ⟨⟨f, hf⟩, rfl⟩, le_cInf := λ s f hs hf i, le_cInf (by haveI := hs.to_subtype; apply range_nonempty) $ λ b ⟨⟨g, hg⟩, hb⟩, hb ▸ hf hg i, .. pi.lattice, .. pi.has_Sup, .. pi.has_Inf } section conditionally_complete_linear_order variables [conditionally_complete_linear_order α] {s t : set α} {a b : α} lemma finset.nonempty.cSup_eq_max' {s : finset α} (h : s.nonempty) : Sup ↑s = s.max' h := eq_of_forall_ge_iff $ λ a, (cSup_le_iff s.bdd_above h.to_set).trans (s.max'_le_iff h).symm lemma finset.nonempty.cInf_eq_min' {s : finset α} (h : s.nonempty) : Inf ↑s = s.min' h := @finset.nonempty.cSup_eq_max' αᵒᵈ _ s h lemma finset.nonempty.cSup_mem {s : finset α} (h : s.nonempty) : Sup (s : set α) ∈ s := by { rw h.cSup_eq_max', exact s.max'_mem _ } lemma finset.nonempty.cInf_mem {s : finset α} (h : s.nonempty) : Inf (s : set α) ∈ s := @finset.nonempty.cSup_mem αᵒᵈ _ _ h lemma set.nonempty.cSup_mem (h : s.nonempty) (hs : s.finite) : Sup s ∈ s := by { lift s to finset α using hs, exact finset.nonempty.cSup_mem h } lemma set.nonempty.cInf_mem (h : s.nonempty) (hs : s.finite) : Inf s ∈ s := @set.nonempty.cSup_mem αᵒᵈ _ _ h hs lemma set.finite.cSup_lt_iff (hs : s.finite) (h : s.nonempty) : Sup s < a ↔ ∀ x ∈ s, x < a := ⟨λ h x hx, (le_cSup hs.bdd_above hx).trans_lt h, λ H, H _ $ h.cSup_mem hs⟩ lemma set.finite.lt_cInf_iff (hs : s.finite) (h : s.nonempty) : a < Inf s ↔ ∀ x ∈ s, a < x := @set.finite.cSup_lt_iff αᵒᵈ _ _ _ hs h /-- 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 (hs : s.nonempty) (hb : b < Sup s) : ∃ a ∈ s, b < a := by { contrapose! hb, exact cSup_le hs hb } /-- 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 [nonempty ι] {f : ι → α} (h : b < supr f) : ∃ i, b < f i := let ⟨_, ⟨i, rfl⟩, h⟩ := exists_lt_of_lt_cSup (range_nonempty f) 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 (hs : s.nonempty) (hb : Inf s < b) : ∃ a ∈ s, a < b := @exists_lt_of_lt_cSup αᵒᵈ _ _ _ hs hb /-- 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 [nonempty ι] {f : ι → α} (h : infi f < a) : ∃ i, f i < a := @exists_lt_of_lt_csupr αᵒᵈ _ _ _ _ _ h open function variables [is_well_order α (<)] lemma Inf_eq_argmin_on (hs : s.nonempty) : Inf s = argmin_on id (@is_well_order.wf α (<) _) s hs := is_least.cInf_eq ⟨argmin_on_mem _ _ _ _, λ a ha, argmin_on_le id _ _ ha⟩ lemma is_least_Inf (hs : s.nonempty) : is_least s (Inf s) := by { rw Inf_eq_argmin_on hs, exact ⟨argmin_on_mem _ _ _ _, λ a ha, argmin_on_le id _ _ ha⟩ } lemma le_cInf_iff' (hs : s.nonempty) : b ≤ Inf s ↔ b ∈ lower_bounds s := le_is_glb_iff (is_least_Inf hs).is_glb lemma Inf_mem (hs : s.nonempty) : Inf s ∈ s := (is_least_Inf hs).1 lemma monotone_on.map_Inf {β : Type*} [conditionally_complete_lattice β] {f : α → β} (hf : monotone_on f s) (hs : s.nonempty) : f (Inf s) = Inf (f '' s) := (hf.map_is_least (is_least_Inf hs)).cInf_eq.symm lemma monotone.map_Inf {β : Type*} [conditionally_complete_lattice β] {f : α → β} (hf : monotone f) (hs : s.nonempty) : f (Inf s) = Inf (f '' s) := (hf.map_is_least (is_least_Inf hs)).cInf_eq.symm end conditionally_complete_linear_order /-! ### Lemmas about a conditionally complete linear order with bottom element In this case we have `Sup ∅ = ⊥`, so we can drop some `nonempty`/`set.nonempty` assumptions. -/ section conditionally_complete_linear_order_bot variables [conditionally_complete_linear_order_bot α] @[simp] lemma cSup_empty : (Sup ∅ : α) = ⊥ := conditionally_complete_linear_order_bot.cSup_empty @[simp] lemma csupr_of_empty [is_empty ι] (f : ι → α) : (⨆ i, f i) = ⊥ := by rw [supr_of_empty', cSup_empty] @[simp] lemma csupr_false (f : false → α) : (⨆ i, f i) = ⊥ := csupr_of_empty f @[simp] lemma cInf_univ : Inf (univ : set α) = ⊥ := is_least_univ.cInf_eq lemma is_lub_cSup' {s : set α} (hs : bdd_above s) : is_lub s (Sup s) := begin rcases eq_empty_or_nonempty s with (rfl|hne), { simp only [cSup_empty, is_lub_empty] }, { exact is_lub_cSup hne hs } end lemma cSup_le_iff' {s : set α} (hs : bdd_above s) {a : α} : Sup s ≤ a ↔ ∀ x ∈ s, x ≤ a := is_lub_le_iff (is_lub_cSup' hs) lemma cSup_le' {s : set α} {a : α} (h : a ∈ upper_bounds s) : Sup s ≤ a := (cSup_le_iff' ⟨a, h⟩).2 h theorem le_cSup_iff' {s : set α} {a : α} (h : bdd_above s) : a ≤ Sup s ↔ ∀ b, b ∈ upper_bounds s → a ≤ b := ⟨λ h b hb, le_trans h (cSup_le' hb), λ hb, hb _ (λ x, le_cSup h)⟩ lemma le_csupr_iff' {s : ι → α} {a : α} (h : bdd_above (range s)) : a ≤ supr s ↔ ∀ b, (∀ i, s i ≤ b) → a ≤ b := by simp [supr, h, le_cSup_iff', upper_bounds] theorem le_cInf_iff'' {s : set α} {a : α} (ne : s.nonempty) : a ≤ Inf s ↔ ∀ (b : α), b ∈ s → a ≤ b := le_cInf_iff ⟨⊥, λ a _, bot_le⟩ ne theorem cInf_le' {s : set α} {a : α} (h : a ∈ s) : Inf s ≤ a := cInf_le ⟨⊥, λ a _, bot_le⟩ h lemma exists_lt_of_lt_cSup' {s : set α} {a : α} (h : a < Sup s) : ∃ b ∈ s, a < b := by { contrapose! h, exact cSup_le' h } lemma csupr_le_iff' {f : ι → α} (h : bdd_above (range f)) {a : α} : (⨆ i, f i) ≤ a ↔ ∀ i, f i ≤ a := (cSup_le_iff' h).trans forall_range_iff lemma csupr_le' {f : ι → α} {a : α} (h : ∀ i, f i ≤ a) : (⨆ i, f i) ≤ a := cSup_le' $ forall_range_iff.2 h lemma exists_lt_of_lt_csupr' {f : ι → α} {a : α} (h : a < ⨆ i, f i) : ∃ i, a < f i := by { contrapose! h, exact csupr_le' h } lemma csupr_mono' {ι'} {f : ι → α} {g : ι' → α} (hg : bdd_above (range g)) (h : ∀ i, ∃ i', f i ≤ g i') : supr f ≤ supr g := csupr_le' $ λ i, exists.elim (h i) (le_csupr_of_le hg) lemma cInf_le_cInf' {s t : set α} (h₁ : t.nonempty) (h₂ : t ⊆ s) : Inf s ≤ Inf t := cInf_le_cInf (order_bot.bdd_below s) h₁ h₂ end conditionally_complete_linear_order_bot namespace with_top 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.nonempty) : 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 le_rfl }, { exact false.elim (not_top_le_coe a (ha h)) } }, { rintro (⟨⟩|b) hb, { exact le_top }, refine some_le_some.2 (cSup_le _ _), { rcases hs with ⟨⟨⟩|b, hb⟩, { exact absurd hb h }, { exact ⟨b, hb⟩ } }, { intros a ha, exact some_le_some.1 (hb ha) } }, { rintro (⟨⟩|b) hb, { exact le_rfl }, { 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 cases s.eq_empty_or_nonempty with hs hs, { 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 _ _), { classical, contrapose! h, rintros (⟨⟩|a) ha, { exact mem_singleton ⊤ }, { exact (h ⟨a, ha⟩).elim }}, { 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 := λ s, (is_lub_Sup s).1, Sup_le := λ s, (is_lub_Sup s).2, Inf := Inf, le_Inf := λ s, (is_glb_Inf s).2, Inf_le := λ s, (is_glb_Inf s).1, .. 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 cases s.eq_empty_or_nonempty with hs hs, { rw [hs, cSup_empty], simp only [set.mem_empty_eq, supr_bot, supr_false], refl }, apply le_antisymm, { refine (coe_le_iff.2 $ λ b hb, cSup_le hs $ λ a has, coe_le_coe.1 $ hb ▸ _), exact le_supr₂_of_le a has le_rfl }, { exact supr₂_le (λ a ha, coe_le_coe.2 $ le_cSup hb ha) } end lemma coe_Inf {s : set α} (hs : s.nonempty) : (↑(Inf s) : with_top α) = ⨅ a ∈ s, ↑a := begin obtain ⟨x, hx⟩ := hs, have : (⨅ a ∈ s, ↑a : with_top α) ≤ x := infi₂_le_of_le x hx le_rfl, rcases le_coe_iff.1 this with ⟨r, r_eq, hr⟩, refine le_antisymm (le_infi₂ $ λ a ha, coe_le_coe.2 $ cInf_le (order_bot.bdd_below s) ha) _, { rw r_eq, apply coe_le_coe.2 (le_cInf ⟨x, hx⟩ (λ a has, coe_le_coe.1 _)), rw ←r_eq, exact infi₂_le_of_le a has le_rfl } end end with_top namespace monotone variables [preorder α] [conditionally_complete_lattice β] {f : α → β} (h_mono : monotone f) /-! A monotone function into a conditionally complete lattice preserves the ordering properties of `Sup` and `Inf`. -/ lemma le_cSup_image {s : set α} {c : α} (hcs : c ∈ s) (h_bdd : bdd_above s) : f c ≤ Sup (f '' s) := le_cSup (map_bdd_above h_mono h_bdd) (mem_image_of_mem f hcs) lemma cSup_image_le {s : set α} (hs : s.nonempty) {B : α} (hB: B ∈ upper_bounds s) : Sup (f '' s) ≤ f B := cSup_le (nonempty.image f hs) (h_mono.mem_upper_bounds_image hB) lemma cInf_image_le {s : set α} {c : α} (hcs : c ∈ s) (h_bdd : bdd_below s) : Inf (f '' s) ≤ f c := @le_cSup_image αᵒᵈ βᵒᵈ _ _ _ (λ x y hxy, h_mono hxy) _ _ hcs h_bdd lemma le_cInf_image {s : set α} (hs : s.nonempty) {B : α} (hB: B ∈ lower_bounds s) : f B ≤ Inf (f '' s) := @cSup_image_le αᵒᵈ βᵒᵈ _ _ _ (λ x y hxy, h_mono hxy) _ hs _ hB end monotone namespace galois_connection variables [conditionally_complete_lattice α] [conditionally_complete_lattice β] [nonempty ι] {l : α → β} {u : β → α} lemma l_cSup (gc : galois_connection l u) {s : set α} (hne : s.nonempty) (hbdd : bdd_above s) : l (Sup s) = ⨆ x : s, l x := eq.symm $ is_lub.csupr_set_eq (gc.is_lub_l_image $ is_lub_cSup hne hbdd) hne lemma l_cSup' (gc : galois_connection l u) {s : set α} (hne : s.nonempty) (hbdd : bdd_above s) : l (Sup s) = Sup (l '' s) := by rw [gc.l_cSup hne hbdd, csupr_set] lemma l_csupr (gc : galois_connection l u) {f : ι → α} (hf : bdd_above (range f)) : l (⨆ i, f i) = ⨆ i, l (f i) := by rw [supr, gc.l_cSup (range_nonempty _) hf, supr_range'] lemma l_csupr_set (gc : galois_connection l u) {s : set γ} {f : γ → α} (hf : bdd_above (f '' s)) (hne : s.nonempty) : l (⨆ i : s, f i) = ⨆ i : s, l (f i) := by { haveI := hne.to_subtype, rw image_eq_range at hf, exact gc.l_csupr hf } lemma u_cInf (gc : galois_connection l u) {s : set β} (hne : s.nonempty) (hbdd : bdd_below s) : u (Inf s) = ⨅ x : s, u x := gc.dual.l_cSup hne hbdd lemma u_cInf' (gc : galois_connection l u) {s : set β} (hne : s.nonempty) (hbdd : bdd_below s) : u (Inf s) = Inf (u '' s) := gc.dual.l_cSup' hne hbdd lemma u_cinfi (gc : galois_connection l u) {f : ι → β} (hf : bdd_below (range f)) : u (⨅ i, f i) = ⨅ i, u (f i) := gc.dual.l_csupr hf lemma u_cinfi_set (gc : galois_connection l u) {s : set γ} {f : γ → β} (hf : bdd_below (f '' s)) (hne : s.nonempty) : u (⨅ i : s, f i) = ⨅ i : s, u (f i) := gc.dual.l_csupr_set hf hne end galois_connection namespace order_iso variables [conditionally_complete_lattice α] [conditionally_complete_lattice β] [nonempty ι] lemma map_cSup (e : α ≃o β) {s : set α} (hne : s.nonempty) (hbdd : bdd_above s) : e (Sup s) = ⨆ x : s, e x := e.to_galois_connection.l_cSup hne hbdd lemma map_cSup' (e : α ≃o β) {s : set α} (hne : s.nonempty) (hbdd : bdd_above s) : e (Sup s) = Sup (e '' s) := e.to_galois_connection.l_cSup' hne hbdd lemma map_csupr (e : α ≃o β) {f : ι → α} (hf : bdd_above (range f)) : e (⨆ i, f i) = ⨆ i, e (f i) := e.to_galois_connection.l_csupr hf lemma map_csupr_set (e : α ≃o β) {s : set γ} {f : γ → α} (hf : bdd_above (f '' s)) (hne : s.nonempty) : e (⨆ i : s, f i) = ⨆ i : s, e (f i) := e.to_galois_connection.l_csupr_set hf hne lemma map_cInf (e : α ≃o β) {s : set α} (hne : s.nonempty) (hbdd : bdd_below s) : e (Inf s) = ⨅ x : s, e x := e.dual.map_cSup hne hbdd lemma map_cInf' (e : α ≃o β) {s : set α} (hne : s.nonempty) (hbdd : bdd_below s) : e (Inf s) = Inf (e '' s) := e.dual.map_cSup' hne hbdd lemma map_cinfi (e : α ≃o β) {f : ι → α} (hf : bdd_below (range f)) : e (⨅ i, f i) = ⨅ i, e (f i) := e.dual.map_csupr hf lemma map_cinfi_set (e : α ≃o β) {s : set γ} {f : γ → α} (hf : bdd_below (f '' s)) (hne : s.nonempty) : e (⨅ i : s, f i) = ⨅ i : s, e (f i) := e.dual.map_csupr_set hf hne end order_iso /-! ### Supremum/infimum of `set.image2` A collection of lemmas showing what happens to the suprema/infima of `s` and `t` when mapped under a binary function whose partial evaluations are lower/upper adjoints of Galois connections. -/ section variables [conditionally_complete_lattice α] [conditionally_complete_lattice β] [conditionally_complete_lattice γ] {f : α → β → γ} {s : set α} {t : set β} variables {l u : α → β → γ} {l₁ u₁ : β → γ → α} {l₂ u₂ : α → γ → β} lemma cSup_image2_eq_cSup_cSup (h₁ : ∀ b, galois_connection (swap l b) (u₁ b)) (h₂ : ∀ a, galois_connection (l a) (u₂ a)) (hs₀ : s.nonempty) (hs₁ : bdd_above s) (ht₀ : t.nonempty) (ht₁ : bdd_above t) : Sup (image2 l s t) = l (Sup s) (Sup t) := begin refine eq_of_forall_ge_iff (λ c, _), rw [cSup_le_iff (hs₁.image2 (λ _, (h₁ _).monotone_l) (λ _, (h₂ _).monotone_l) ht₁) (hs₀.image2 ht₀), forall_image2_iff, forall₂_swap, (h₂ _).le_iff_le, cSup_le_iff ht₁ ht₀], simp_rw [←(h₂ _).le_iff_le, (h₁ _).le_iff_le, cSup_le_iff hs₁ hs₀], end lemma cSup_image2_eq_cSup_cInf (h₁ : ∀ b, galois_connection (swap l b) (u₁ b)) (h₂ : ∀ a, galois_connection (l a ∘ of_dual) (to_dual ∘ u₂ a)) : s.nonempty → bdd_above s → t.nonempty → bdd_below t → Sup (image2 l s t) = l (Sup s) (Inf t) := @cSup_image2_eq_cSup_cSup _ βᵒᵈ _ _ _ _ _ _ _ _ _ h₁ h₂ lemma cSup_image2_eq_cInf_cSup (h₁ : ∀ b, galois_connection (swap l b ∘ of_dual) (to_dual ∘ u₁ b)) (h₂ : ∀ a, galois_connection (l a) (u₂ a)) : s.nonempty → bdd_below s → t.nonempty → bdd_above t → Sup (image2 l s t) = l (Inf s) (Sup t) := @cSup_image2_eq_cSup_cSup αᵒᵈ _ _ _ _ _ _ _ _ _ _ h₁ h₂ lemma cSup_image2_eq_cInf_cInf (h₁ : ∀ b, galois_connection (swap l b ∘ of_dual) (to_dual ∘ u₁ b)) (h₂ : ∀ a, galois_connection (l a ∘ of_dual) (to_dual ∘ u₂ a)) : s.nonempty → bdd_below s → t.nonempty → bdd_below t → Sup (image2 l s t) = l (Inf s) (Inf t) := @cSup_image2_eq_cSup_cSup αᵒᵈ βᵒᵈ _ _ _ _ _ _ _ _ _ h₁ h₂ lemma cInf_image2_eq_cInf_cInf (h₁ : ∀ b, galois_connection (l₁ b) (swap u b)) (h₂ : ∀ a, galois_connection (l₂ a) (u a)) : s.nonempty → bdd_below s → t.nonempty → bdd_below t → Inf (image2 u s t) = u (Inf s) (Inf t) := @cSup_image2_eq_cSup_cSup αᵒᵈ βᵒᵈ γᵒᵈ _ _ _ _ _ _ l₁ l₂ (λ _, (h₁ _).dual) (λ _, (h₂ _).dual) lemma cInf_image2_eq_cInf_cSup (h₁ : ∀ b, galois_connection (l₁ b) (swap u b)) (h₂ : ∀ a, galois_connection (to_dual ∘ l₂ a) (u a ∘ of_dual)) : s.nonempty → bdd_below s → t.nonempty → bdd_above t → Inf (image2 u s t) = u (Inf s) (Sup t) := @cInf_image2_eq_cInf_cInf _ βᵒᵈ _ _ _ _ _ _ _ _ _ h₁ h₂ lemma cInf_image2_eq_cSup_cInf (h₁ : ∀ b, galois_connection (to_dual ∘ l₁ b) (swap u b ∘ of_dual)) (h₂ : ∀ a, galois_connection (l₂ a) (u a)) : s.nonempty → bdd_above s → t.nonempty → bdd_below t → Inf (image2 u s t) = u (Sup s) (Inf t) := @cInf_image2_eq_cInf_cInf αᵒᵈ _ _ _ _ _ _ _ _ _ _ h₁ h₂ lemma cInf_image2_eq_cSup_cSup (h₁ : ∀ b, galois_connection (to_dual ∘ l₁ b) (swap u b ∘ of_dual)) (h₂ : ∀ a, galois_connection (to_dual ∘ l₂ a) (u a ∘ of_dual)) : s.nonempty → bdd_above s → t.nonempty → bdd_above t → Inf (image2 u s t) = u (Sup s) (Sup t) := @cInf_image2_eq_cInf_cInf αᵒᵈ βᵒᵈ _ _ _ _ _ _ _ _ _ h₁ h₂ end /-! ### Relation between `Sup` / `Inf` and `finset.sup'` / `finset.inf'` Like the `Sup` of a `conditionally_complete_lattice`, `finset.sup'` also requires the set to be non-empty. As a result, we can translate between the two. -/ namespace finset lemma sup'_eq_cSup_image [conditionally_complete_lattice β] (s : finset α) (H) (f : α → β) : s.sup' H f = Sup (f '' s) := begin apply le_antisymm, { refine (finset.sup'_le _ _ $ λ a ha, _), refine le_cSup ⟨s.sup' H f, _⟩ ⟨a, ha, rfl⟩, rintros i ⟨j, hj, rfl⟩, exact finset.le_sup' _ hj }, { apply cSup_le ((coe_nonempty.mpr H).image _), rintros _ ⟨a, ha, rfl⟩, exact finset.le_sup' _ ha, } end lemma inf'_eq_cInf_image [conditionally_complete_lattice β] (s : finset α) (H) (f : α → β) : s.inf' H f = Inf (f '' s) := @sup'_eq_cSup_image _ βᵒᵈ _ _ _ _ lemma sup'_id_eq_cSup [conditionally_complete_lattice α] (s : finset α) (H) : s.sup' H id = Sup s := by rw [sup'_eq_cSup_image s H, set.image_id] lemma inf'_id_eq_cInf [conditionally_complete_lattice α] (s : finset α) (H) : s.inf' H id = Inf s := @sup'_id_eq_cSup αᵒᵈ _ _ _ end finset 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_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' ⟨a, 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.has_Sup, ..with_top.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 αᵒᵈ _).cInf_le, cSup_le := (@with_top.conditionally_complete_lattice αᵒᵈ _).le_cInf, cInf_le := (@with_top.conditionally_complete_lattice αᵒᵈ _).le_cSup, le_cInf := (@with_top.conditionally_complete_lattice αᵒᵈ _).cSup_le, ..with_bot.lattice, ..with_bot.has_Sup, ..with_bot.has_Inf } noncomputable instance with_top.with_bot.complete_lattice {α : Type*} [conditionally_complete_lattice α] : complete_lattice (with_top (with_bot α)) := { le_Sup := λ S a haS, (with_top.is_lub_Sup' ⟨a, haS⟩).1 haS, Sup_le := λ S a ha, begin cases S.eq_empty_or_nonempty with h, { 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 le_rfl, 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.has_Inf, ..with_top.has_Sup, ..with_top.bounded_order, ..with_top.lattice } noncomputable instance with_top.with_bot.complete_linear_order {α : Type*} [conditionally_complete_linear_order α] : complete_linear_order (with_top (with_bot α)) := { .. with_top.with_bot.complete_lattice, .. with_top.linear_order } end with_top_bot section group variables {ι' : Sort*} [nonempty ι] [nonempty ι'] [conditionally_complete_lattice α] [group α] @[to_additive] lemma le_mul_cinfi [covariant_class α α (*) (≤)] {a : α} {g : α} {h : ι → α} (H : ∀ j, a ≤ g * h j) : a ≤ g * infi h := inv_mul_le_iff_le_mul.mp $ le_cinfi $ λ hi, inv_mul_le_iff_le_mul.mpr $ H _ @[to_additive] lemma mul_csupr_le [covariant_class α α (*) (≤)] {a : α} {g : α} {h : ι → α} (H : ∀ j, g * h j ≤ a) : g * supr h ≤ a := @le_mul_cinfi αᵒᵈ _ _ _ _ _ _ _ _ H @[to_additive] lemma le_cinfi_mul [covariant_class α α (function.swap (*)) (≤)] {a : α} {g : ι → α} {h : α} (H : ∀ i, a ≤ g i * h) : a ≤ infi g * h := mul_inv_le_iff_le_mul.mp $ le_cinfi $ λ gi, mul_inv_le_iff_le_mul.mpr $ H _ @[to_additive] lemma csupr_mul_le [covariant_class α α (function.swap (*)) (≤)] {a : α} {g : ι → α} {h : α} (H : ∀ i, g i * h ≤ a) : supr g * h ≤ a := @le_cinfi_mul αᵒᵈ _ _ _ _ _ _ _ _ H @[to_additive] lemma le_cinfi_mul_cinfi [covariant_class α α (*) (≤)] [covariant_class α α (function.swap (*)) (≤)] {a : α} {g : ι → α} {h : ι' → α} (H : ∀ i j, a ≤ g i * h j) : a ≤ infi g * infi h := le_cinfi_mul $ λ i, le_mul_cinfi $ H _ @[to_additive] lemma csupr_mul_csupr_le [covariant_class α α (*) (≤)] [covariant_class α α (function.swap (*)) (≤)] {a : α} {g : ι → α} {h : ι' → α} (H : ∀ i j, g i * h j ≤ a) : supr g * supr h ≤ a := csupr_mul_le $ λ i, mul_csupr_le $ H _ end group
5ea678c89c6cedd7190cf2a27ced3874ef4b0788
6dc0c8ce7a76229dd81e73ed4474f15f88a9e294
/stage0/src/Lean/Elab/Print.lean
254e640886e4b3d831bf208565837d3c31f66025
[ "Apache-2.0" ]
permissive
williamdemeo/lean4
72161c58fe65c3ad955d6a3050bb7d37c04c0d54
6d00fcf1d6d873e195f9220c668ef9c58e9c4a35
refs/heads/master
1,678,305,356,877
1,614,708,995,000
1,614,708,995,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
5,700
lean
/- Copyright (c) 2020 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Util.FoldConsts import Lean.Elab.Command namespace Lean.Elab.Command private def throwUnknownId (id : Name) : CommandElabM Unit := throwError! "unknown identifier '{mkConst id}'" private def levelParamsToMessageData (levelParams : List Name) : MessageData := match levelParams with | [] => "" | u::us => do let mut m := m!".\{{u}" for u in us do m := m ++ ", " ++ u return m ++ "}" private def mkHeader (kind : String) (id : Name) (levelParams : List Name) (type : Expr) (safety : DefinitionSafety) : CommandElabM MessageData := do let m : MessageData := match safety with | DefinitionSafety.unsafe => "unsafe " | DefinitionSafety.partial => "partial " | DefinitionSafety.safe => "" let m := if isProtected (← getEnv) id then m ++ "protected " else m let (m, id) := match privateToUserName? id with | some id => (m ++ "private ", id) | none => (m, id) let m := m ++ kind ++ " " ++ id ++ levelParamsToMessageData levelParams ++ " : " ++ type pure m private def mkHeader' (kind : String) (id : Name) (levelParams : List Name) (type : Expr) (isUnsafe : Bool) : CommandElabM MessageData := mkHeader kind id levelParams type (if isUnsafe then DefinitionSafety.unsafe else DefinitionSafety.safe) private def printDefLike (kind : String) (id : Name) (levelParams : List Name) (type : Expr) (value : Expr) (safety := DefinitionSafety.safe) : CommandElabM Unit := do let m ← mkHeader kind id levelParams type safety let m := m ++ " :=" ++ Format.line ++ value logInfo m private def printAxiomLike (kind : String) (id : Name) (levelParams : List Name) (type : Expr) (isUnsafe := false) : CommandElabM Unit := do logInfo (← mkHeader' kind id levelParams type isUnsafe) private def printQuot (kind : QuotKind) (id : Name) (levelParams : List Name) (type : Expr) : CommandElabM Unit := do printAxiomLike "Quotient primitive" id levelParams type private def printInduct (id : Name) (levelParams : List Name) (numParams : Nat) (numIndices : Nat) (type : Expr) (ctors : List Name) (isUnsafe : Bool) : CommandElabM Unit := do let mut m ← mkHeader' "inductive" id levelParams type isUnsafe m := m ++ Format.line ++ "constructors:" for ctor in ctors do let cinfo ← getConstInfo ctor m := m ++ Format.line ++ ctor ++ " : " ++ cinfo.type logInfo m private def printIdCore (id : Name) : CommandElabM Unit := do match (← getEnv).find? id with | ConstantInfo.axiomInfo { levelParams := us, type := t, isUnsafe := u, .. } => printAxiomLike "axiom" id us t u | ConstantInfo.defnInfo { levelParams := us, type := t, value := v, safety := s, .. } => printDefLike "def" id us t v s | ConstantInfo.thmInfo { levelParams := us, type := t, value := v, .. } => printDefLike "theorem" id us t v | ConstantInfo.opaqueInfo { levelParams := us, type := t, isUnsafe := u, .. } => printAxiomLike "constant" id us t u | ConstantInfo.quotInfo { kind := kind, levelParams := us, type := t, .. } => printQuot kind id us t | ConstantInfo.ctorInfo { levelParams := us, type := t, isUnsafe := u, .. } => printAxiomLike "constructor" id us t u | ConstantInfo.recInfo { levelParams := us, type := t, isUnsafe := u, .. } => printAxiomLike "recursor" id us t u | ConstantInfo.inductInfo { levelParams := us, numParams := numParams, numIndices := numIndices, type := t, ctors := ctors, isUnsafe := u, .. } => printInduct id us numParams numIndices t ctors u | none => throwUnknownId id private def printId (id : Name) : CommandElabM Unit := do let cs ← resolveGlobalConst id cs.forM printIdCore @[builtinCommandElab «print»] def elabPrint : CommandElab | `(#print%$tk $id:ident) => withRef tk <| printId id.getId | `(#print%$tk $s:strLit) => logInfoAt tk s.isStrLit?.get! | _ => throwError "invalid #print command" namespace CollectAxioms structure State where visited : NameSet := {} axioms : Array Name := #[] abbrev M := ReaderT Environment $ StateM State partial def collect (c : Name) : M Unit := do let collectExpr (e : Expr) : M Unit := e.getUsedConstants.forM collect let s ← get unless s.visited.contains c do modify fun s => { s with visited := s.visited.insert c } let env ← read match env.find? c with | some (ConstantInfo.axiomInfo _) => modify fun s => { s with axioms := s.axioms.push c } | some (ConstantInfo.defnInfo v) => collectExpr v.type *> collectExpr v.value | some (ConstantInfo.thmInfo v) => collectExpr v.type *> collectExpr v.value | some (ConstantInfo.opaqueInfo v) => collectExpr v.type *> collectExpr v.value | some (ConstantInfo.quotInfo _) => pure () | some (ConstantInfo.ctorInfo v) => collectExpr v.type | some (ConstantInfo.recInfo v) => collectExpr v.type | some (ConstantInfo.inductInfo v) => collectExpr v.type *> v.ctors.forM collect | none => pure () end CollectAxioms private def printAxiomsOf (constName : Name) : CommandElabM Unit := do let env ← getEnv let (_, s) := ((CollectAxioms.collect constName).run env).run {} if s.axioms.isEmpty then logInfo m!"'{constName}' does not depend on any axioms" else logInfo m!"'{constName}' depends on axioms: {s.axioms.toList}" @[builtinCommandElab «printAxioms»] def elabPrintAxioms : CommandElab | `(#print%$tk axioms $id) => withRef tk do let cs ← resolveGlobalConst id.getId cs.forM printAxiomsOf | _ => throwUnsupportedSyntax end Lean.Elab.Command
ed11780b06b3350412511ab51dd9358912e07e4d
9dc8cecdf3c4634764a18254e94d43da07142918
/src/topology/support.lean
191aae66dafee33ee0dd4e4bdbcc389afbc9320e
[ "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
12,027
lean
/- Copyright (c) 2022 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn, Patrick Massot -/ import topology.separation /-! # The topological support of a function In this file we define the topological support of a function `f`, `tsupport f`, as the closure of the support of `f`. Furthermore, we say that `f` has compact support if the topological support of `f` is compact. ## Main definitions * `function.mul_tsupport` & `function.tsupport` * `function.has_compact_mul_support` & `function.has_compact_support` ## Implementation Notes * We write all lemmas for multiplicative functions, and use `@[to_additive]` to get the more common additive versions. * We do not put the definitions in the `function` namespace, following many other topological definitions that are in the root namespace (compare `embedding` vs `function.embedding`). -/ open function set filter open_locale topological_space variables {X α α' β γ δ M E R : Type*} section one variables [has_one α] variables [topological_space X] /-- The topological support of a function is the closure of its support, i.e. the closure of the set of all elements where the function is not equal to 1. -/ @[to_additive /-" The topological support of a function is the closure of its support. i.e. the closure of the set of all elements where the function is nonzero. "-/] def mul_tsupport (f : X → α) : set X := closure (mul_support f) @[to_additive] lemma subset_mul_tsupport (f : X → α) : mul_support f ⊆ mul_tsupport f := subset_closure @[to_additive] lemma is_closed_mul_tsupport (f : X → α) : is_closed (mul_tsupport f) := is_closed_closure @[to_additive] lemma mul_tsupport_eq_empty_iff {f : X → α} : mul_tsupport f = ∅ ↔ f = 1 := by rw [mul_tsupport, closure_empty_iff, mul_support_eq_empty_iff] @[to_additive] lemma image_eq_zero_of_nmem_mul_tsupport {f : X → α} {x : X} (hx : x ∉ mul_tsupport f) : f x = 1 := mul_support_subset_iff'.mp (subset_mul_tsupport f) x hx @[to_additive] lemma range_subset_insert_image_mul_tsupport (f : X → α) : range f ⊆ insert 1 (f '' mul_tsupport f) := (range_subset_insert_image_mul_support f).trans $ insert_subset_insert $ image_subset _ subset_closure @[to_additive] lemma range_eq_image_mul_tsupport_or (f : X → α) : range f = f '' mul_tsupport f ∨ range f = insert 1 (f '' mul_tsupport f) := (wcovby_insert _ _).eq_or_eq (image_subset_range _ _) (range_subset_insert_image_mul_tsupport f) lemma tsupport_mul_subset_left {α : Type*} [mul_zero_class α] {f g : X → α} : tsupport (λ x, f x * g x) ⊆ tsupport f := closure_mono (support_mul_subset_left _ _) lemma tsupport_mul_subset_right {α : Type*} [mul_zero_class α] {f g : X → α} : tsupport (λ x, f x * g x) ⊆ tsupport g := closure_mono (support_mul_subset_right _ _) end one lemma tsupport_smul_subset_left {M α} [topological_space X] [has_zero M] [has_zero α] [smul_with_zero M α] (f : X → M) (g : X → α) : tsupport (λ x, f x • g x) ⊆ tsupport f := closure_mono $ support_smul_subset_left f g section variables [topological_space α] [topological_space α'] variables [has_one β] [has_one γ] [has_one δ] variables {g : β → γ} {f : α → β} {f₂ : α → γ} {m : β → γ → δ} {x : α} @[to_additive] lemma not_mem_mul_tsupport_iff_eventually_eq : x ∉ mul_tsupport f ↔ f =ᶠ[𝓝 x] 1 := by simp_rw [mul_tsupport, mem_closure_iff_nhds, not_forall, not_nonempty_iff_eq_empty, ← disjoint_iff_inter_eq_empty, disjoint_mul_support_iff, eventually_eq_iff_exists_mem] @[to_additive] lemma continuous_of_mul_tsupport [topological_space β] {f : α → β} (hf : ∀ x ∈ mul_tsupport f, continuous_at f x) : continuous f := continuous_iff_continuous_at.2 $ λ x, (em _).elim (hf x) $ λ hx, (@continuous_at_const _ _ _ _ _ 1).congr (not_mem_mul_tsupport_iff_eventually_eq.mp hx).symm /-- A function `f` *has compact multiplicative support* or is *compactly supported* if the closure of the multiplicative support of `f` is compact. In a T₂ space this is equivalent to `f` being equal to `1` outside a compact set. -/ @[to_additive /-" A function `f` *has compact support* or is *compactly supported* if the closure of the support of `f` is compact. In a T₂ space this is equivalent to `f` being equal to `0` outside a compact set. "-/] def has_compact_mul_support (f : α → β) : Prop := is_compact (mul_tsupport f) @[to_additive] lemma has_compact_mul_support_def : has_compact_mul_support f ↔ is_compact (closure (mul_support f)) := by refl @[to_additive] lemma exists_compact_iff_has_compact_mul_support [t2_space α] : (∃ K : set α, is_compact K ∧ ∀ x ∉ K, f x = 1) ↔ has_compact_mul_support f := by simp_rw [← nmem_mul_support, ← mem_compl_iff, ← subset_def, compl_subset_compl, has_compact_mul_support_def, exists_compact_superset_iff] @[to_additive] lemma has_compact_mul_support.intro [t2_space α] {K : set α} (hK : is_compact K) (hfK : ∀ x ∉ K, f x = 1) : has_compact_mul_support f := exists_compact_iff_has_compact_mul_support.mp ⟨K, hK, hfK⟩ @[to_additive] lemma has_compact_mul_support.is_compact (hf : has_compact_mul_support f) : is_compact (mul_tsupport f) := hf @[to_additive] lemma has_compact_mul_support_iff_eventually_eq : has_compact_mul_support f ↔ f =ᶠ[coclosed_compact α] 1 := ⟨ λ h, mem_coclosed_compact.mpr ⟨mul_tsupport f, is_closed_mul_tsupport _, h, λ x, not_imp_comm.mpr $ λ hx, subset_mul_tsupport f hx⟩, λ h, let ⟨C, hC⟩ := mem_coclosed_compact'.mp h in compact_of_is_closed_subset hC.2.1 (is_closed_mul_tsupport _) (closure_minimal hC.2.2 hC.1)⟩ @[to_additive] lemma has_compact_mul_support.is_compact_range [topological_space β] (h : has_compact_mul_support f) (hf : continuous f) : is_compact (range f) := begin cases range_eq_image_mul_tsupport_or f with h2 h2; rw [h2], exacts [h.image hf, (h.image hf).insert 1] end @[to_additive] lemma has_compact_mul_support.mono' {f' : α → γ} (hf : has_compact_mul_support f) (hff' : mul_support f' ⊆ mul_tsupport f) : has_compact_mul_support f' := compact_of_is_closed_subset hf is_closed_closure $ closure_minimal hff' is_closed_closure @[to_additive] lemma has_compact_mul_support.mono {f' : α → γ} (hf : has_compact_mul_support f) (hff' : mul_support f' ⊆ mul_support f) : has_compact_mul_support f' := hf.mono' $ hff'.trans subset_closure @[to_additive] lemma has_compact_mul_support.comp_left (hf : has_compact_mul_support f) (hg : g 1 = 1) : has_compact_mul_support (g ∘ f) := hf.mono $ mul_support_comp_subset hg f @[to_additive] lemma has_compact_mul_support_comp_left (hg : ∀ {x}, g x = 1 ↔ x = 1) : has_compact_mul_support (g ∘ f) ↔ has_compact_mul_support f := by simp_rw [has_compact_mul_support_def, mul_support_comp_eq g @hg f] @[to_additive] lemma has_compact_mul_support.comp_closed_embedding (hf : has_compact_mul_support f) {g : α' → α} (hg : closed_embedding g) : has_compact_mul_support (f ∘ g) := begin rw [has_compact_mul_support_def, function.mul_support_comp_eq_preimage], refine compact_of_is_closed_subset (hg.is_compact_preimage hf) is_closed_closure _, rw [hg.to_embedding.closure_eq_preimage_closure_image], exact preimage_mono (closure_mono $ image_preimage_subset _ _) end @[to_additive] lemma has_compact_mul_support.comp₂_left (hf : has_compact_mul_support f) (hf₂ : has_compact_mul_support f₂) (hm : m 1 1 = 1) : has_compact_mul_support (λ x, m (f x) (f₂ x)) := begin rw [has_compact_mul_support_iff_eventually_eq] at hf hf₂ ⊢, filter_upwards [hf, hf₂] using λ x hx hx₂, by simp_rw [hx, hx₂, pi.one_apply, hm] end end section monoid variables [topological_space α] [monoid β] variables {f f' : α → β} {x : α} @[to_additive] lemma has_compact_mul_support.mul (hf : has_compact_mul_support f) (hf' : has_compact_mul_support f') : has_compact_mul_support (f * f') := by apply hf.comp₂_left hf' (mul_one 1) -- `by apply` speeds up elaboration end monoid section distrib_mul_action variables [topological_space α] [monoid_with_zero R] [add_monoid M] [distrib_mul_action R M] variables {f : α → R} {f' : α → M} {x : α} lemma has_compact_support.smul_left (hf : has_compact_support f') : has_compact_support (f • f') := begin rw [has_compact_support_iff_eventually_eq] at hf ⊢, refine hf.mono (λ x hx, by simp_rw [pi.smul_apply', hx, pi.zero_apply, smul_zero]) end end distrib_mul_action section smul_with_zero variables [topological_space α] [has_zero R] [has_zero M] [smul_with_zero R M] variables {f : α → R} {f' : α → M} {x : α} lemma has_compact_support.smul_right (hf : has_compact_support f) : has_compact_support (f • f') := begin rw [has_compact_support_iff_eventually_eq] at hf ⊢, refine hf.mono (λ x hx, by simp_rw [pi.smul_apply', hx, pi.zero_apply, zero_smul]) end lemma has_compact_support.smul_left' (hf : has_compact_support f') : has_compact_support (f • f') := begin rw [has_compact_support_iff_eventually_eq] at hf ⊢, refine hf.mono (λ x hx, by simp_rw [pi.smul_apply', hx, pi.zero_apply, smul_zero']) end end smul_with_zero section mul_zero_class variables [topological_space α] [mul_zero_class β] variables {f f' : α → β} {x : α} lemma has_compact_support.mul_right (hf : has_compact_support f) : has_compact_support (f * f') := begin rw [has_compact_support_iff_eventually_eq] at hf ⊢, refine hf.mono (λ x hx, by simp_rw [pi.mul_apply, hx, pi.zero_apply, zero_mul]) end lemma has_compact_support.mul_left (hf : has_compact_support f') : has_compact_support (f * f') := begin rw [has_compact_support_iff_eventually_eq] at hf ⊢, refine hf.mono (λ x hx, by simp_rw [pi.mul_apply, hx, pi.zero_apply, mul_zero]) end end mul_zero_class namespace locally_finite variables {ι : Type*} {U : ι → set X} [topological_space X] [has_one R] /-- If a family of functions `f` has locally-finite multiplicative support, subordinate to a family of open sets, then for any point we can find a neighbourhood on which only finitely-many members of `f` are not equal to 1. -/ @[to_additive /-" If a family of functions `f` has locally-finite support, subordinate to a family of open sets, then for any point we can find a neighbourhood on which only finitely-many members of `f` are non-zero. "-/] lemma exists_finset_nhd_mul_support_subset {f : ι → X → R} (hlf : locally_finite (λ i, mul_support (f i))) (hso : ∀ i, mul_tsupport (f i) ⊆ U i) (ho : ∀ i, is_open (U i)) (x : X) : ∃ (is : finset ι) {n : set X} (hn₁ : n ∈ 𝓝 x) (hn₂ : n ⊆ ⋂ i ∈ is, U i), ∀ (z ∈ n), mul_support (λ i, f i z) ⊆ is := begin obtain ⟨n, hn, hnf⟩ := hlf x, classical, let is := hnf.to_finset.filter (λ i, x ∈ U i), let js := hnf.to_finset.filter (λ j, x ∉ U j), refine ⟨is, n ∩ (⋂ j ∈ js, (mul_tsupport (f j))ᶜ) ∩ (⋂ i ∈ is, U i), inter_mem (inter_mem hn _) _, inter_subset_right _ _, λ z hz, _⟩, { exact (bInter_finset_mem js).mpr (λ j hj, is_closed.compl_mem_nhds (is_closed_mul_tsupport _) (set.not_mem_subset (hso j) (finset.mem_filter.mp hj).2)), }, { exact (bInter_finset_mem is).mpr (λ i hi, (ho i).mem_nhds (finset.mem_filter.mp hi).2) }, { have hzn : z ∈ n, { rw inter_assoc at hz, exact mem_of_mem_inter_left hz, }, replace hz := mem_of_mem_inter_right (mem_of_mem_inter_left hz), simp only [finset.mem_filter, finite.mem_to_finset, mem_set_of_eq, mem_Inter, and_imp] at hz, suffices : mul_support (λ i, f i z) ⊆ hnf.to_finset, { refine hnf.to_finset.subset_coe_filter_of_subset_forall _ this (λ i hi, _), specialize hz i ⟨z, ⟨hi, hzn⟩⟩, contrapose hz, simp [hz, subset_mul_tsupport (f i) hi], }, intros i hi, simp only [finite.coe_to_finset, mem_set_of_eq], exact ⟨z, ⟨hi, hzn⟩⟩, }, end end locally_finite
af0e03c12163f93bd9ab8b1e73fb45a6ef38f284
2bafba05c98c1107866b39609d15e849a4ca2bb8
/src/week_4/solutions/Part_A_sets.lean
c313cb0fa24a4de27bd917aa3403e32260d30070
[ "Apache-2.0" ]
permissive
ImperialCollegeLondon/formalising-mathematics
b54c83c94b5c315024ff09997fcd6b303892a749
7cf1d51c27e2038d2804561d63c74711924044a1
refs/heads/master
1,651,267,046,302
1,638,888,459,000
1,638,888,459,000
331,592,375
284
24
Apache-2.0
1,669,593,705,000
1,611,224,849,000
Lean
UTF-8
Lean
false
false
9,387
lean
import tactic -- import the tactics import data.set.basic -- import the sets import data.set.lattice -- infinite unions and intersections /- # Sets ## Introduction In contrast to group theory, where we made our own definition of a group and developed our own API (i.e. the lemmas we need to prove basic results in group theory), here we will use Lean's API. The first thing to learn is that this is not some development of set theory, or ZFC, or whatever "set theory" brings to mind. This is all about the theory of _subsets_ of a set, or, more precisely, subsets of a type. Just like `subgroup G` was the type of subgroups of `G`, `set X` is the type of subsets of `X`. Don't ask me why it's not called `subset X`. I guess the idea is that if `S : set X` then `S` is a set of elements of `X` or, more precisely, a set of terms of `X`. And, also like `subgroup G`, if `S : set X` then `S` is a term, not a type. This is a bit weird because in type theory our model is that types are sets, and terms are their elements, and `a : X` means that `a` is an element of `X`. The way subsets work is like this. If `S : set X` and if `a : X` then there's a predicate `a ∈ S`, which means that `a` is in the subset `S` of `X`. Note that the _type_ of `a` is still `X`, it's just that `a` happens to be in `S` as well. This is why we can't have `S` as a type: then we would want to write `a : S` and `a : X`, but terms in type theory can only have one type. ## Implementation You don't need to know about implentation -- that's the point of the API. Any new definition, like `set X`, should be accessed and reasoned with using its API, the collection of lemmas that comes with it. But here's what's actually going on. Under the hood, if `S : set X` then `S` is a function from `X` to `Prop`. The idea is that a subset of `X` is represented internally as a function to `{true, false}` which sends all the elements of `S` to `true` and all the other elements to `false`. In fact `set X := X → Prop` is the internal definition of `set`. Internally, the statement `a ∈ S` is just encoded as the proposition `S a`. ## Notation There is a lot of it. Say `(X Y : Type)` The empty set is `∅ : set X`. Hover over the symbol to find out how to write it in Lean. The set corresponding to all of `X` is `set.univ : set X`, or just `univ : set X` if you have written `open set` earlier in the file. If `S : set X` then its complement is `Sᶜ : set X`. Now say `f : X → Y`. If `S : set X` then `f '' S : set Y` is the image of `S`. If `T : set Y` then `f ⁻¹' T : set X` is the preimage of `T`. The range of `f` could be written `f '' univ`, however there is also `range f`. Finally remember `subset_def : S ⊆ T ↔ ∀ x, x ∈ S → x ∈ T` -/ variables (X Y Z : Type) (f : X → Y) (g : Y → Z) (S : set X) (y : Y) open set /-! ## image `y ∈ f '' S` is definitionally equal to `∃ x : X, x ∈ S ∧ f x = y`, but if you want to rewrite to change one to the other, we have `mem_image f S y : y ∈ f '' S ↔ ∃ (x : X), x ∈ S ∧ f x = y` -/ -- here are four proofs of image_id, each taking more short cuts -- than the last. In practice I might write the first proof -- and then "golf" it down so it becomes closer to the fourth one. -- Go through the first proof and then take a look at some -- of the shortcuts I introduce. lemma image_id (S : set X) : id '' S = S := begin ext x, split, { intro h, rw mem_image at h, cases h with y hy, cases hy with hyS hid, rw id.def at hid, rw ← hid, exact hyS }, { intro hxS, rw mem_image, use x, split, { exact hxS }, { rw id.def } } end example : id '' S = S := begin ext x, split, { intro h, -- don't need to `rw mem_image` because it's definitional -- rcases can do multiple `cases` at once. Note that ⟨a, b, c⟩ = ⟨a, ⟨b, c⟩⟩ rcases h with ⟨y, hyS, hid⟩, -- don't need to `rw id.def` because it's definitional rw ← hid, exact hyS }, { intro hxS, use x, -- if the goal is `⊢ P ∧ Q` and you have a proof of `P`, you can `use` it use hxS, -- `⊢ id x = x` is true by definition refl } end example : id '' S = S := begin ext x, split, { -- the `rintro` tactic will do `intro, cases` -- and will even do both `cases` at once! rintro ⟨y, hyS, hid⟩, rw ← hid, exact hyS }, { intro hxS, -- two `use`s can go together use [x, hxS], refl } end -- this is the shortest explicit tactic proof I know which doesn't -- cheat and use the corresponding lemma in Lean's maths library: example : id '' S = S := begin ext x, split, { -- `hid` says `(something) = y` so why not just _define_ y to be this! rintro ⟨y, hyS, rfl⟩, -- rfl deletes `y` from the context and subs in `id x` exact hyS }, { intro hxS, -- we can just build this term exact ⟨x, hxS, rfl⟩ }, end -- Other proofs which won't teach you as much: example : id '' S = S := begin -- it's in the library already apply image_id', end example : id '' S = S := begin simp -- `image_id'` is tagged `@[simp]` so `simp` finds it. end -- This tactic also finds `image_id'` in the library example : id '' S = S := begin finish, end -- So does this one. example : id '' S = S := begin tidy end -- The disadvantages of these last few proofs : (a) `finish` and `tidy` are -- slow (b) they won't teach you much and (c) if the theorems are not -- already in Lean's maths library then the tactics might not be of much use. -- Let's see what you make of these lemmas about sets. lemma image_comp (S : set X) : (g ∘ f) '' S = g '' (f '' S) := begin ext z, split, { rintro ⟨x, hxS, hxz⟩, use [f x, x, hxS, hxz] }, -- pointy brackets are right associative: ⟨a, b, c⟩ means ⟨a, ⟨b, c⟩⟩ { rintro ⟨y, ⟨x, hxS, rfl⟩, rfl⟩, exact ⟨x, hxS, rfl⟩ } end open function -- don't forget you can use `dsimp` to tidy up evaluated lambdas lemma image_injective : injective f → injective (λ S, f '' S) := begin intro hf, intros S T h, dsimp at h, -- not necessary, but nice to be tidy. ext x, -- too lazy to write down the same proof twice: suffices : ∀ S T : set X, f '' S = f '' T → x ∈ S → x ∈ T, { split, apply this _ _ h, apply this _ _ h.symm, }, clear h S T, -- not necessary, but we don't need them any more. intros S T h hxS, have hfx : f x ∈ f '' T, { rw ← h, use [x, hxS] }, rcases hfx with ⟨y, hyT, hfy⟩, convert hyT, apply hf, exact hfy.symm, end /-! ## preimage The notation : `f ⁻¹' T`. The useful lemma: `mem_preimage : x ∈ f ⁻¹' T ↔ f x ∈ T` but in fact both sides are equal by definition. -/ example (S : set X) : S = id ⁻¹' S := begin refl, end -- Do take a look at the model solutions to this one (which I'll upload -- after the workshop ) example (T : set Z) : (g ∘ f) ⁻¹' T = f ⁻¹' (g ⁻¹' T) := begin refl, end lemma preimage_injective (hf : surjective f) : injective (λ T, f ⁻¹' T) := begin intros T U h, ext y, -- trick so we only have to go in one direction suffices : ∀ {T U}, f ⁻¹' T = f ⁻¹' U → y ∈ T → y ∈ U, { exact ⟨this h, this h.symm⟩ }, intros T U h hyT, rcases hf y with ⟨x, rfl⟩, rwa [← mem_preimage, ← h], end lemma image_surjective (hf : surjective f) : surjective (λ S, f '' S) := begin intro T, use f ⁻¹' T, dsimp only, ext y, split, { rintro ⟨x, hx, rfl⟩, exact hx }, { intro hyT, rcases hf y with ⟨x, rfl⟩, use [x, hyT] } end lemma preimage_surjective (hf : injective f) : surjective (λ S, f ⁻¹' S) := begin intro S, use f '' S, ext x, split, { rintro ⟨y, hyS, h⟩, rwa ← (hf h) }, { intro h, use [x, h, rfl] } end /-! ## Union If `(ι : Type)` and `(F : ι → set X)` then the `F i` for `i : ι` are a family of subsets of `X`, so we can take their union. This is `Union F` (note the capital U -- small u means union of two things, capital means union of arbitrary number of things). But the notation used in the lemmas is `⋃ (i : ι), F i`. The key lemma you need to prove everything is that something is an element of the union iff it's an element of one of the sets. `mem_Union : (x ∈ ⋃ (i : ι), F i) ↔ ∃ j : ι, x ∈ F j` -/ variables (ι : Type) (F : ι → set X) (x : X) lemma image_Union (F : ι → set X) (f : X → Y) : f '' (⋃ (i : ι), F i) = ⋃ (i : ι), f '' (F i) := begin ext y, split, { rintro ⟨x, hxF, rfl⟩, rw mem_Union at hxF ⊢, cases hxF with i hi, use [i, x, hi] }, { intro h, rw mem_Union at h, rcases h with ⟨i, x, hxi, rfl⟩, use x, rw mem_Union, use i, assumption } end /-! ## bUnion If as well as `F : ι → set X` you have `Z : set ι` then you might just want to take the union over `F i` as `i` runs through `Z`. This is called a "bounded union" or `bUnion`, and the notation is `⋃ (i ∈ Z), F i`. The lemma for elements of a bounded union is: `mem_bUnion_iff : (x ∈ ⋃ (i ∈ J), F i) ↔ ∃ (j ∈ J), x ∈ F j` -/ lemma preimage_bUnion (F : ι → set Y) (Z : set ι) : f ⁻¹' (⋃ (i ∈ Z), F i) = ⋃ (i ∈ Z), f ⁻¹' (F i) := begin ext y, rw [mem_preimage, mem_bUnion_iff, mem_bUnion_iff], refl, end
e66828b8caf54e6f1f07c8c991bcbacb1d671826
5d166a16ae129621cb54ca9dde86c275d7d2b483
/tests/lean/run/inductive_nonrec_after_rec.lean
5068e984122e01e74ac58edef39fa21ebe881419
[ "Apache-2.0" ]
permissive
jcarlson23/lean
b00098763291397e0ac76b37a2dd96bc013bd247
8de88701247f54d325edd46c0eed57aeacb64baf
refs/heads/master
1,611,571,813,719
1,497,020,963,000
1,497,021,515,000
93,882,536
1
0
null
1,497,029,896,000
1,497,029,896,000
null
UTF-8
Lean
false
false
2,003
lean
universe variables u inductive tree (α : Type u) | leaf {} : tree | node : tree → α → tree → tree open tree def tree.size {α : Type u} : tree α → nat | leaf := 0 | (node l a r) := tree.size l + tree.size r + 1 #eval tree.size (@leaf nat) #eval tree.size (tree.node leaf 1 leaf) #eval tree.size (tree.node (tree.node leaf 1 leaf) 2 leaf) lemma ex1 : tree.size (tree.node (tree.node leaf 1 leaf) 2 leaf) = 2 := rfl def tree.elems_core {α : Type u} : tree α → list α → list α | leaf lst := lst | (node l a r) lst := let lst₁ := tree.elems_core l lst, lst₂ := a :: lst₁ in tree.elems_core r lst₂ def tree.elems {α : Type u} (t : tree α) : list α := (tree.elems_core t [])^.reverse #eval tree.elems (tree.node (tree.node (tree.node leaf 0 leaf) 1 leaf) 2 leaf) lemma ex2 : tree.elems (tree.node (tree.node (tree.node leaf 0 leaf) 1 leaf) 2 leaf) = [0, 1, 2] := rfl lemma ex3 (t₁ t₂ : tree nat) : t₁ = leaf → t₂ = node leaf 1 leaf → t₁ ≠ t₂ := begin [smt] intros end lemma ex4 (t₁ t₂ : tree nat) : t₁ = leaf → t₂ = node leaf 1 leaf → t₁ ≠ t₂ := begin intros, subst t₁, subst t₂, tactic.intro1, contradiction end lemma ex5 (a b : nat) (t₁ t₂ t₃ t₄ : tree nat) : node t₁ a t₂ = node t₃ b t₄ → t₁ = t₃ ∧ a = b ∧ t₂ = t₄ := begin [smt] intros end lemma ex6 (a b : nat) (t₁ t₂ t₃ t₄ : tree nat) : node t₁ a t₂ = node t₃ b t₄ → t₁ = t₃ ∧ a = b ∧ t₂ = t₄ := begin intro h, injection h with h₁ h₂ h₃, split, assumption, split, assumption, assumption end lemma ex7 {α : Type u} (t : tree α) : t ≠ leaf → tree.size t > 0 := begin induction t, {intros, contradiction}, {intros, unfold size, apply nat.zero_lt_succ } end inductive tree_list (α : Type u) : Type u | leaf : tree_list | node : list tree_list → α → tree_list
287dabec1ec1a79b1fb2c37f3b25e4614d7f2134
492a7e27d49633a89f7ce6e1e28f676b062fcbc9
/src/monoidal_categories_reboot/monoidal_category.lean
602686dbac8697d8f88f6843c74f2869d39cdaf7
[ "Apache-2.0" ]
permissive
semorrison/monoidal-categories-reboot
9edba30277de48a234b63813cf85b171772ce36f
48b5f1d535daba4e591672042a298ac36be2e6dd
refs/heads/master
1,642,472,396,149
1,560,587,477,000
1,560,587,477,000
156,465,626
0
1
null
1,541,549,278,000
1,541,549,278,000
null
UTF-8
Lean
false
false
18,738
lean
-- -- Copyright (c) 2018 Michael Jendrusch. All rights reserved. -- -- Released under Apache 2.0 license as described in the file LICENSE. -- -- Authors: Michael Jendrusch, Scott Morrison -- import .tensor_product -- import category_theory.natural_isomorphism -- import tactic -- TODO switch this back to tactic.basic once relevant PRs land. -- import tactic.slice -- open category_theory -- open tactic -- universes v u -- open category_theory.category -- namespace category_theory -- section -- TODO these should be the original lemmas!? -- variables {C : Sort u} [𝒞 : category.{v} C] -- include 𝒞 -- variables {X Y Z : C} -- lemma cancel_epi' (f : X ⟶ Y) [epi f] {g h : Y ⟶ Z} (p : f ≫ g = f ≫ h) : g = h := -- epi.left_cancellation g h p -- lemma cancel_mono' (f : X ⟶ Y) [mono f] {g h : Z ⟶ X} (p : g ≫ f = h ≫ f) : g = h := -- mono.right_cancellation g h p -- end -- section -- variables {C : Sort u} [𝒞 : category.{v} C] -- include 𝒞 -- variables {X Y Z : C} (f g : X ⟶ Y) (h : Y ⟶ Z) -- instance inv_is_iso [is_iso f] : is_iso (inv f) := -- { inv := f } -- instance comp_is_iso [is_iso f] [is_iso h] : is_iso (f ≫ h) := -- { inv := inv h ≫ inv f } -- @[simp] lemma inv_id : inv (𝟙 X) = 𝟙 X := rfl -- @[simp] lemma inv_comp [is_iso f] [is_iso h] : inv (f ≫ h) = inv h ≫ inv f := rfl -- @[simp] lemma is_iso.inv_inv [is_iso f] : inv (inv f) = f := rfl -- @[simp] lemma iso.inv_inv (f : X ≅ Y) : inv (f.inv) = f.hom := rfl -- @[simp] lemma iso.inv_hom (f : X ≅ Y) : inv (f.hom) = f.inv := rfl -- lemma eq_of_inv_eq [is_iso f] [is_iso g] (p : inv f = inv g) : f = g := -- begin -- apply cancel_epi' (inv f), -- conv_rhs { rw p }, -- simp, -- end -- end -- end category_theory -- open category_theory -- namespace category_theory.monoidal -- class monoidal_category (C : Sort u) extends category.{v} C := -- -- curried tensor product of objects: -- (tensor_obj : C → C → C) -- -- curried tensor product of morphisms: -- (tensor_hom : -- Π {X₁ Y₁ X₂ Y₂ : C}, hom X₁ Y₁ → hom X₂ Y₂ → hom (tensor_obj X₁ X₂) (tensor_obj Y₁ Y₂)) -- -- tensor product laws: -- (tensor_map_id' : -- ∀ (X₁ X₂ : C), tensor_hom (𝟙 X₁) (𝟙 X₂) = 𝟙 (tensor_obj X₁ X₂) . obviously) -- (tensor_map_comp' : -- ∀ {X₁ Y₁ Z₁ X₂ Y₂ Z₂ : C} (f₁ : X₁ ⟶ Y₁) (f₂ : X₂ ⟶ Y₂) (g₁ : Y₁ ⟶ Z₁) (g₂ : Y₂ ⟶ Z₂), -- tensor_hom (f₁ ≫ g₁) (f₂ ≫ g₂) = (tensor_hom f₁ f₂) ≫ (tensor_hom g₁ g₂) . obviously) -- -- tensor unit: -- (tensor_unit : C) -- -- associator: -- (associator : -- Π X Y Z : C, (tensor_obj (tensor_obj X Y) Z) ≅ (tensor_obj X (tensor_obj Y Z))) -- (associator_naturality' : -- assoc_natural tensor_obj @tensor_hom associator . obviously) -- -- left unitor: -- (left_unitor : Π X : C, tensor_obj tensor_unit X ≅ X) -- (left_unitor_naturality' : -- left_unitor_natural tensor_obj @tensor_hom tensor_unit left_unitor . obviously) -- -- right unitor: -- (right_unitor : Π X : C, tensor_obj X tensor_unit ≅ X) -- (right_unitor_naturality' : -- right_unitor_natural tensor_obj @tensor_hom tensor_unit right_unitor . obviously) -- -- pentagon identity: -- (pentagon' : pentagon @tensor_hom associator . obviously) -- -- triangle identity: -- (triangle' : -- triangle @tensor_hom left_unitor right_unitor associator . obviously) -- restate_axiom monoidal_category.tensor_map_id' -- attribute [simp] monoidal_category.tensor_map_id -- restate_axiom monoidal_category.tensor_map_comp' -- attribute [simp] monoidal_category.tensor_map_comp -- restate_axiom monoidal_category.associator_naturality' -- restate_axiom monoidal_category.left_unitor_naturality' -- restate_axiom monoidal_category.right_unitor_naturality' -- restate_axiom monoidal_category.pentagon' -- restate_axiom monoidal_category.triangle' -- attribute [simp] monoidal_category.triangle -- open monoidal_category -- infixr ` ⊗ `:70 := tensor_obj -- infixr ` ⊗ `:70 := tensor_hom -- def tensor_iso {C : Sort u} {X Y X' Y' : C} [monoidal_category.{v} C] (f : X ≅ Y) (g : X' ≅ Y') : -- X ⊗ X' ≅ Y ⊗ Y' := -- { hom := f.hom ⊗ g.hom, -- inv := f.inv ⊗ g.inv, -- hom_inv_id' := by rw [←tensor_map_comp, iso.hom_inv_id, iso.hom_inv_id, ←tensor_map_id], -- inv_hom_id' := by rw [←tensor_map_comp, iso.inv_hom_id, iso.inv_hom_id, ←tensor_map_id] } -- infixr ` ⊗ `:70 := tensor_iso -- section -- variables {C : Sort u} [𝒞 : monoidal_category.{v} C] -- include 𝒞 -- instance tensor_is_iso {W X Y Z : C} (f : W ⟶ X) [is_iso f] (g : Y ⟶ Z) [is_iso g] : is_iso (f ⊗ g) := -- { ..(as_iso f ⊗ as_iso g) } -- @[simp] lemma inv_tensor {W X Y Z : C} (f : W ⟶ X) [is_iso f] (g : Y ⟶ Z) [is_iso g] : -- inv (f ⊗ g) = inv f ⊗ inv g -- := rfl -- variables {U V W X Y Z : C} -- -- When `rewrite_search` lands, add @[search] attributes to -- -- monoidal_category.tensor_map_id monoidal_category.tensor_map_comp monoidal_category.associator_naturality -- -- monoidal_category.left_unitor_naturality monoidal_category.right_unitor_naturality -- -- monoidal_category.pentagon monoidal_category.triangle -- -- interchange interchange_left_identity interchange_right_identity interchange_identities -- -- triangle_1 triangle_2 triangle_3 triangle_4 -- -- left_unitor_product left_unitor_product_inv -- -- right_unitor_product right_unitor_product_inv -- -- pentagon_inv -- -- associator_inv_naturality -- -- left_unitor_inv_naturality -- -- right_unitor_inv_naturality -- lemma interchange (f : U ⟶ V) (g : V ⟶ W) (h : X ⟶ Y) (k : Y ⟶ Z) -- : (f ≫ g) ⊗ (h ≫ k) = (f ⊗ h) ≫ (g ⊗ k) := -- tensor_map_comp C f h g k -- @[simp] lemma interchange_left_identity (f : W ⟶ X) (g : X ⟶ Y) : -- (f ≫ g) ⊗ (𝟙 Z) = (f ⊗ (𝟙 Z)) ≫ (g ⊗ (𝟙 Z)) := -- by { rw ←interchange, simp } -- @[simp] lemma interchange_right_identity (f : W ⟶ X) (g : X ⟶ Y) : -- (𝟙 Z) ⊗ (f ≫ g) = (𝟙 Z ⊗ f) ≫ (𝟙 Z ⊗ g) := -- by { rw ←interchange, simp } -- lemma interchange_identities (f : W ⟶ X) (g : Y ⟶ Z) : -- ((𝟙 Y) ⊗ f) ≫ (g ⊗ (𝟙 X)) = (g ⊗ (𝟙 W)) ≫ ((𝟙 Z) ⊗ f) := -- by { rw [←interchange, ←interchange], simp } -- lemma left_unitor_inv_naturality {X X' : C} (f : X ⟶ X') : -- f ≫ (left_unitor X').inv = (left_unitor X).inv ≫ (𝟙 _ ⊗ f) := -- begin -- apply cancel_mono' (left_unitor X').hom, -- simp only [assoc, comp_id, iso.inv_hom_id], -- conv_rhs { congr, skip, rw [left_unitor_naturality] }, -- conv_rhs { rw [←category.assoc], congr, rw [iso.inv_hom_id] }, -- conv_rhs { rw [category.id_comp] } -- end -- lemma right_unitor_inv_naturality {X X' : C} (f : X ⟶ X') : -- f ≫ (right_unitor X').inv = (right_unitor X).inv ≫ (f ⊗ 𝟙 _) := -- begin -- apply cancel_mono' (right_unitor X').hom, -- simp only [assoc, comp_id, iso.inv_hom_id], -- conv_rhs { congr, skip, rw [right_unitor_naturality] }, -- conv_rhs { rw [←category.assoc], congr, rw [iso.inv_hom_id] }, -- conv_rhs { rw [category.id_comp] } -- end -- @[simp] lemma tensor_left_iff -- {X Y : C} (f g : X ⟶ Y) : -- ((𝟙 (tensor_unit C)) ⊗ f = (𝟙 (tensor_unit C)) ⊗ g) ↔ (f = g) := -- begin -- split, -- { intro h, -- have h' := congr_arg (λ k, (left_unitor _).inv ≫ k) h, -- dsimp at h', -- rw ←left_unitor_inv_naturality at h', -- rw ←left_unitor_inv_naturality at h', -- apply cancel_mono' _ h', }, -- { intro h, subst h, } -- end -- @[simp] lemma tensor_right_iff -- {X Y : C} (f g : X ⟶ Y) : -- (f ⊗ (𝟙 (tensor_unit C)) = g ⊗ (𝟙 (tensor_unit C))) ↔ (f = g) := -- begin -- split, -- { intro h, -- have h' := congr_arg (λ k, (right_unitor _).inv ≫ k) h, -- dsimp at h', -- rw ←right_unitor_inv_naturality at h', -- rw ←right_unitor_inv_naturality at h', -- apply cancel_mono' _ h', }, -- { intro h, subst h, } -- end -- -- We now prove: -- -- ((associator (tensor_unit C) X Y).hom) ≫ -- -- ((left_unitor (X ⊗ Y)).hom) -- -- = ((left_unitor X).hom ⊗ (𝟙 Y)) -- -- (and the corresponding fact for right unitors) -- -- following the proof on nLab. -- lemma left_unitor_product_aux_perimeter (X Y : C) : -- ((associator (tensor_unit C) (tensor_unit C) X).hom ⊗ (𝟙 Y)) ≫ -- (associator (tensor_unit C) ((tensor_unit C) ⊗ X) Y).hom ≫ -- ((𝟙 (tensor_unit C)) ⊗ (associator (tensor_unit C) X Y).hom) ≫ -- ((𝟙 (tensor_unit C)) ⊗ (left_unitor (X ⊗ Y)).hom) -- = (((right_unitor (tensor_unit C)).hom ⊗ (𝟙 X)) ⊗ (𝟙 Y)) ≫ -- (associator (tensor_unit C) X Y).hom := -- begin -- conv_lhs { congr, skip, rw [←category.assoc] }, -- conv_lhs { rw [←category.assoc], congr, rw [monoidal_category.pentagon] }, -- conv_rhs { rw [associator_naturality], congr, skip, congr, skip, rw [tensor_map_id] }, -- conv_rhs { congr, skip, rw [←monoidal_category.triangle] }, -- conv_rhs { rw [←category.assoc] } -- end -- lemma left_unitor_product_aux_triangle (X Y : C) : -- ((associator (tensor_unit C) (tensor_unit C) X).hom ⊗ (𝟙 Y)) ≫ -- (((𝟙 (tensor_unit C)) ⊗ (left_unitor X).hom) ⊗ (𝟙 Y)) -- = ((right_unitor (tensor_unit C)).hom ⊗ (𝟙 X)) ⊗ (𝟙 Y) := -- begin -- conv_lhs { rw [←interchange_left_identity] }, -- conv_rhs { congr, rw [←monoidal_category.triangle] } -- end -- lemma left_unitor_product_aux_square (X Y : C) : -- (associator (tensor_unit C) ((tensor_unit C) ⊗ X) Y).hom ≫ -- ((𝟙 (tensor_unit C)) ⊗ (left_unitor X).hom ⊗ (𝟙 Y)) -- = (((𝟙 (tensor_unit C)) ⊗ (left_unitor X).hom) ⊗ (𝟙 Y)) ≫ -- (associator (tensor_unit C) X Y).hom := -- begin -- conv_rhs { rw [associator_naturality] } -- end -- lemma left_unitor_product_aux (X Y : C) : -- ((𝟙 (tensor_unit C)) ⊗ (associator (tensor_unit C) X Y).hom) ≫ -- ((𝟙 (tensor_unit C)) ⊗ (left_unitor (X ⊗ Y)).hom) -- = (𝟙 (tensor_unit C)) ⊗ ((left_unitor X).hom ⊗ (𝟙 Y)) := -- begin -- rw ←(cancel_epi (associator (tensor_unit C) ((tensor_unit C) ⊗ X) Y).hom), -- rw left_unitor_product_aux_square, -- rw ←(cancel_epi ((associator (tensor_unit C) (tensor_unit C) X).hom ⊗ (𝟙 Y))), -- slice_rhs 1 2 { rw left_unitor_product_aux_triangle }, -- conv_lhs { rw [left_unitor_product_aux_perimeter] } -- end -- lemma right_unitor_product_aux_perimeter (X Y : C) : -- ((associator X Y (tensor_unit C)).hom ⊗ (𝟙 (tensor_unit C))) ≫ -- (associator X (Y ⊗ (tensor_unit C)) (tensor_unit C)).hom ≫ -- ((𝟙 X) ⊗ (associator Y (tensor_unit C) (tensor_unit C)).hom) ≫ -- ((𝟙 X) ⊗ (𝟙 Y) ⊗ (left_unitor (tensor_unit C)).hom) -- = ((right_unitor (X ⊗ Y)).hom ⊗ (𝟙 (tensor_unit C))) ≫ -- (associator X Y (tensor_unit C)).hom := -- begin -- transitivity (((associator X Y _).hom ⊗ 𝟙 _) ≫ (associator X _ _).hom ≫ -- (𝟙 X ⊗ (associator Y _ _).hom)) ≫ -- (𝟙 X ⊗ 𝟙 Y ⊗ (monoidal_category.left_unitor _).hom), -- { conv_lhs { congr, skip, rw [←category.assoc] }, -- conv_rhs { rw [category.assoc] } }, -- { conv_lhs { congr, rw [monoidal_category.pentagon] }, -- conv_rhs { congr, rw [←monoidal_category.triangle] }, -- conv_rhs { rw [category.assoc] }, -- conv_rhs { congr, skip, congr, congr, rw [←tensor_map_id] }, -- conv_rhs { congr, skip, rw [associator_naturality] }, -- conv_rhs { rw [←category.assoc] } } -- end -- lemma right_unitor_product_aux_triangle (X Y : C) : -- ((𝟙 X) ⊗ (associator Y (tensor_unit C) (tensor_unit C)).hom) ≫ -- ((𝟙 X) ⊗ (𝟙 Y) ⊗ (left_unitor (tensor_unit C)).hom) -- = (𝟙 X) ⊗ (right_unitor Y).hom ⊗ (𝟙 (tensor_unit C)) := -- begin -- conv_lhs { rw [←interchange_right_identity] }, -- conv_rhs { congr, skip, rw [←monoidal_category.triangle] } -- end -- lemma right_unitor_product_aux_square (X Y : C) : -- (associator X (Y ⊗ (tensor_unit C)) (tensor_unit C)).hom ≫ -- ((𝟙 X) ⊗ (right_unitor Y).hom ⊗ (𝟙 (tensor_unit C))) -- = (((𝟙 X) ⊗ (right_unitor Y).hom) ⊗ (𝟙 (tensor_unit C))) ≫ -- (associator X Y (tensor_unit C)).hom := -- begin -- conv_rhs { rw [associator_naturality] } -- end -- lemma right_unitor_product_aux (X Y : C) : -- ((associator X Y (tensor_unit C)).hom ⊗ (𝟙 (tensor_unit C))) ≫ -- (((𝟙 X) ⊗ (right_unitor Y).hom) ⊗ (𝟙 (tensor_unit C))) -- = ((right_unitor (X ⊗ Y)).hom ⊗ (𝟙 (tensor_unit C))) := -- begin -- rw ←(cancel_mono (associator X Y (tensor_unit C)).hom), -- slice_lhs 2 3 { rw ←right_unitor_product_aux_square }, -- conv_lhs { congr, skip, congr, skip, rw [←right_unitor_product_aux_triangle] }, -- conv_rhs { rw [←right_unitor_product_aux_perimeter] } -- end -- -- See Proposition 2.2.4 of http://www-math.mit.edu/~etingof/egnobookfinal.pdf -- @[simp] lemma left_unitor_product (X Y : C) : -- ((associator (tensor_unit C) X Y).hom) ≫ ((left_unitor (X ⊗ Y)).hom) = -- ((left_unitor X).hom ⊗ (𝟙 Y)) := -- by rw [←tensor_left_iff, interchange_right_identity, left_unitor_product_aux] -- @[simp] lemma left_unitor_product_inv (X Y : C) : -- ((left_unitor (X ⊗ Y)).inv) ≫ ((associator (tensor_unit C) X Y).inv) = -- ((left_unitor X).inv ⊗ (𝟙 Y)) := -- eq_of_inv_eq _ _ (by simp) -- @[simp] lemma right_unitor_product (X Y : C) : -- ((associator X Y (tensor_unit C)).hom) ≫ ((𝟙 X) ⊗ (right_unitor Y).hom) = -- ((right_unitor (X ⊗ Y)).hom) := -- by rw [←tensor_right_iff, interchange_left_identity, right_unitor_product_aux] -- @[simp] lemma right_unitor_product_inv (X Y : C) : -- ((𝟙 X) ⊗ (right_unitor Y).inv) ≫ ((associator X Y (tensor_unit C)).inv) = -- ((right_unitor (X ⊗ Y)).inv) := -- eq_of_inv_eq _ _ (by simp) -- lemma associator_inv_naturality {X Y Z X' Y' Z' : C} (f : X ⟶ X') (g : Y ⟶ Y') (h : Z ⟶ Z') : -- (f ⊗ (g ⊗ h)) ≫ (associator X' Y' Z').inv = (associator X Y Z).inv ≫ ((f ⊗ g) ⊗ h) := -- begin -- apply cancel_mono' (associator X' Y' Z').hom, -- simp only [assoc, comp_id, iso.inv_hom_id], -- conv_rhs { congr, skip, rw [associator_naturality] }, -- conv_rhs { rw [←category.assoc], congr, rw [iso.inv_hom_id] }, -- conv_rhs { rw [category.id_comp] } -- end -- lemma pentagon_inv (W X Y Z : C) : -- ((𝟙 W) ⊗ (associator X Y Z).inv) ≫ (associator W (X ⊗ Y) Z).inv ≫ ((associator W X Y).inv ⊗ (𝟙 Z)) -- = (associator W X (Y ⊗ Z)).inv ≫ (associator (W ⊗ X) Y Z).inv := -- begin -- apply eq_of_inv_eq, -- dsimp, -- rw [category.assoc, monoidal_category.pentagon] -- end -- @[simp] lemma triangle_1 (X Y : C) : -- (associator X (tensor_unit C) Y).hom ≫ ((𝟙 X) ⊗ (left_unitor Y).hom) = (right_unitor X).hom ⊗ 𝟙 Y := -- monoidal_category.triangle C X Y -- @[simp] lemma triangle_2 (X Y : C) : -- (associator X (tensor_unit C) Y).inv ≫ ((right_unitor X).hom ⊗ 𝟙 Y) = ((𝟙 X) ⊗ (left_unitor Y).hom) := -- begin -- conv_lhs { congr, skip, rw [←triangle_1] }, -- conv_lhs { rw [←category.assoc], congr, rw [iso.inv_hom_id] }, -- conv_lhs { rw [category.id_comp] } -- end -- @[simp] lemma triangle_3 (X Y : C) : -- ((right_unitor X).inv ⊗ 𝟙 Y) ≫ (associator X (tensor_unit C) Y).hom = ((𝟙 X) ⊗ (left_unitor Y).inv) := -- begin -- apply cancel_mono' (𝟙 X ⊗ (left_unitor Y).hom), -- simp only [assoc, triangle_1], -- conv_lhs { rw [←interchange_left_identity, iso.inv_hom_id] }, -- conv_rhs { rw [←interchange_right_identity, iso.inv_hom_id] } -- end -- @[simp] lemma triangle_4 (X Y : C) : -- ((𝟙 X) ⊗ (left_unitor Y).inv) ≫ (associator X (tensor_unit C) Y).inv = ((right_unitor X).inv ⊗ 𝟙 Y) := -- begin -- apply cancel_mono' ((right_unitor X).hom ⊗ 𝟙 Y), -- simp only [triangle_2, assoc], -- conv_lhs { rw [←interchange_right_identity, iso.inv_hom_id] }, -- conv_rhs { rw [←interchange_left_identity, iso.inv_hom_id] } -- end -- end -- namespace monoidal_category -- -- In order to be able to describe the tensor product as a functor, we -- -- need to be up in at least `Type 0` for both objects and morphisms, -- -- so that we can construct products. -- variables (C : Type u) [𝒞 : monoidal_category.{v+1} C] -- include 𝒞 -- def monoidal_category.tensor : (C × C) ⥤ C := -- { obj := λ X, tensor_obj X.1 X.2, -- map := λ {X Y : C × C} (f : X ⟶ Y), tensor_hom f.1 f.2 } -- def left_assoc_tensor : (C × C × C) ⥤ C := -- { obj := λ X, (X.1 ⊗ X.2.1) ⊗ X.2.2, -- map := λ {X Y : C × C × C} (f : X ⟶ Y), (f.1 ⊗ f.2.1) ⊗ f.2.2 } -- @[simp] lemma left_assoc_tensor_obj (X) : -- (left_assoc_tensor C).obj X = (X.1 ⊗ X.2.1) ⊗ X.2.2 := rfl -- @[simp] lemma left_assoc_tensor_map {X Y} (f : X ⟶ Y) : -- (left_assoc_tensor C).map f = (f.1 ⊗ f.2.1) ⊗ f.2.2 := rfl -- def right_assoc_tensor : (C × C × C) ⥤ C := -- { obj := λ X, X.1 ⊗ (X.2.1 ⊗ X.2.2), -- map := λ {X Y : C × C × C} (f : X ⟶ Y), f.1 ⊗ (f.2.1 ⊗ f.2.2) } -- @[simp] lemma right_assoc_tensor_obj (X) : -- (right_assoc_tensor C).obj X = X.1 ⊗ (X.2.1 ⊗ X.2.2) := rfl -- @[simp] lemma right_assoc_tensor_map {X Y} (f : X ⟶ Y) : -- (right_assoc_tensor C).map f = f.1 ⊗ (f.2.1 ⊗ f.2.2) := rfl -- def tensor_unit_left : C ⥤ C := -- { obj := λ X, tensor_unit C ⊗ X, -- map := λ {X Y : C} (f : X ⟶ Y), (𝟙 (tensor_unit C)) ⊗ f } -- def tensor_unit_right : C ⥤ C := -- { obj := λ X, X ⊗ tensor_unit C, -- map := λ {X Y : C} (f : X ⟶ Y), f ⊗ (𝟙 (tensor_unit C)) } -- -- We can express the associator and the unitors, given componentwise above, -- -- as natural isomorphisms. -- def associator_nat_iso : -- left_assoc_tensor C ≅ right_assoc_tensor C := -- nat_iso.of_components -- (by intros; dsimp; apply monoidal_category.associator) -- (by intros; dsimp; apply monoidal_category.associator_naturality) -- def left_unitor_nat_iso : -- tensor_unit_left C ≅ functor.id C := -- nat_iso.of_components -- (by intros; dsimp; apply monoidal_category.left_unitor) -- (by intros; dsimp; apply monoidal_category.left_unitor_naturality) -- def right_unitor_nat_iso : -- tensor_unit_right C ≅ functor.id C := -- nat_iso.of_components -- (by intros; dsimp; apply monoidal_category.right_unitor) -- (by intros; dsimp; apply monoidal_category.right_unitor_naturality) -- end monoidal_category -- end category_theory.monoidal
699e43230aba666c3399ed48883e54a2719bc98c
d1a52c3f208fa42c41df8278c3d280f075eb020c
/tests/lean/343.lean
eb2b5c8e8fdbf37a4208b636345be1f0d48e92fa
[ "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
621
lean
structure CatIsh where Obj : Type o Hom : Obj → Obj → Type m infixr:75 " ~> " => (CatIsh.Hom _) structure FunctorIsh (C D : CatIsh) where onObj : C.Obj → D.Obj onHom : ∀ {s d : C.Obj}, (s ~> d) → (onObj s ~> onObj d) abbrev Catish : CatIsh := { Obj := CatIsh Hom := FunctorIsh } universe m o unif_hint (mvar : CatIsh) where Catish.{m, o} =?= mvar |- mvar.Obj =?= CatIsh.{m,o} structure CtxSyntaxLayerParamsObj where Ct : CatIsh def CtxSyntaxLayerParams : CatIsh := { Obj := CtxSyntaxLayerParamsObj Hom := sorry } def CtxSyntaxLayerTy := CtxSyntaxLayerParams ~> Catish
3a732c458fb788307b34ccdcf05895ac0574513b
7cef822f3b952965621309e88eadf618da0c8ae9
/src/topology/sheaves/presheaf.lean
29ee3515f44f08e5753bdf9a6e240e11f9ffe494
[ "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
2,207
lean
/- Copyright (c) 2018 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison, Mario Carneiro, Reid Barton -/ import topology.category.Top.opens import category_theory.whiskering universes v u open category_theory open topological_space open opposite variables (C : Type u) [𝒞 : category.{v} C] include 𝒞 namespace Top def presheaf (X : Top.{v}) := (opens X)ᵒᵖ ⥤ C instance category_presheaf (X : Top.{v}) : category (X.presheaf C) := by dsimp [presheaf]; apply_instance namespace presheaf variables {C} def pushforward {X Y : Top.{v}} (f : X ⟶ Y) (ℱ : X.presheaf C) : Y.presheaf C := (opens.map f).op ⋙ ℱ infix ` _* `: 80 := pushforward def pushforward_eq {X Y : Top.{v}} {f g : X ⟶ Y} (h : f = g) (ℱ : X.presheaf C) : f _* ℱ ≅ g _* ℱ := iso_whisker_right (nat_iso.op (opens.map_iso f g h).symm) ℱ lemma pushforward_eq_eq {X Y : Top.{v}} {f g : X ⟶ Y} (h₁ h₂ : f = g) (ℱ : X.presheaf C) : ℱ.pushforward_eq h₁ = ℱ.pushforward_eq h₂ := rfl namespace pushforward variables {X : Top.{v}} (ℱ : X.presheaf C) def id : (𝟙 X) _* ℱ ≅ ℱ := (iso_whisker_right (nat_iso.op (opens.map_id X).symm) ℱ) ≪≫ functor.left_unitor _ @[simp] lemma id_hom_app' (U) (p) : (id ℱ).hom.app (op ⟨U, p⟩) = ℱ.map (𝟙 (op ⟨U, p⟩)) := by { dsimp [id], simp, } local attribute [tidy] tactic.op_induction' @[simp] lemma id_hom_app (U) : (id ℱ).hom.app U = ℱ.map (eq_to_hom (opens.op_map_id_obj U)) := by tidy @[simp] lemma id_inv_app' (U) (p) : (id ℱ).inv.app (op ⟨U, p⟩) = ℱ.map (𝟙 (op ⟨U, p⟩)) := by { dsimp [id], simp, } def comp {Y Z : Top.{v}} (f : X ⟶ Y) (g : Y ⟶ Z) : (f ≫ g) _* ℱ ≅ g _* (f _* ℱ) := iso_whisker_right (nat_iso.op (opens.map_comp f g).symm) ℱ @[simp] lemma comp_hom_app {Y Z : Top.{v}} (f : X ⟶ Y) (g : Y ⟶ Z) (U) : (comp ℱ f g).hom.app U = 𝟙 _ := begin dsimp [pushforward, comp], tidy, end @[simp] lemma comp_inv_app {Y Z : Top.{v}} (f : X ⟶ Y) (g : Y ⟶ Z) (U) : (comp ℱ f g).inv.app U = 𝟙 _ := begin dsimp [pushforward, comp], tidy, end end pushforward end presheaf end Top
255e163469a1c0bbba94b57ce5a7072d136fba6c
9dc8cecdf3c4634764a18254e94d43da07142918
/src/data/finsupp/order.lean
80ac71bacb21819152758a0b4442258731d048d8
[ "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,284
lean
/- Copyright (c) 2021 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin, Aaron Anderson -/ import data.finsupp.defs /-! # Pointwise order on finitely supported functions This file lifts order structures on `α` to `ι →₀ α`. ## Main declarations * `finsupp.order_embedding_to_fun`: The order embedding from finitely supported functions to functions. * `finsupp.order_iso_multiset`: The order isomorphism between `ℕ`-valued finitely supported functions and multisets. -/ noncomputable theory open_locale classical big_operators open finset variables {ι α : Type*} namespace finsupp /-! ### Order structures -/ section has_zero variables [has_zero α] section has_le variables [has_le α] instance : has_le (ι →₀ α) := ⟨λ f g, ∀ i, f i ≤ g i⟩ lemma le_def {f g : ι →₀ α} : f ≤ g ↔ ∀ i, f i ≤ g i := iff.rfl /-- The order on `finsupp`s over a partial order embeds into the order on functions -/ def order_embedding_to_fun : (ι →₀ α) ↪o (ι → α) := { to_fun := λ f, f, inj' := λ f g h, finsupp.ext $ λ i, by { dsimp at h, rw h }, map_rel_iff' := λ a b, (@le_def _ _ _ _ a b).symm } @[simp] lemma order_embedding_to_fun_apply {f : ι →₀ α} {i : ι} : order_embedding_to_fun f i = f i := rfl end has_le section preorder variables [preorder α] instance : preorder (ι →₀ α) := { le_refl := λ f i, le_rfl, le_trans := λ f g h hfg hgh i, (hfg i).trans (hgh i), .. finsupp.has_le } lemma monotone_to_fun : monotone (finsupp.to_fun : (ι →₀ α) → (ι → α)) := λ f g h a, le_def.1 h a end preorder instance [partial_order α] : partial_order (ι →₀ α) := { le_antisymm := λ f g hfg hgf, ext $ λ i, (hfg i).antisymm (hgf i), .. finsupp.preorder } instance [semilattice_inf α] : semilattice_inf (ι →₀ α) := { inf := zip_with (⊓) inf_idem, inf_le_left := λ f g i, inf_le_left, inf_le_right := λ f g i, inf_le_right, le_inf := λ f g i h1 h2 s, le_inf (h1 s) (h2 s), ..finsupp.partial_order, } @[simp] lemma inf_apply [semilattice_inf α] {i : ι} {f g : ι →₀ α} : (f ⊓ g) i = f i ⊓ g i := rfl instance [semilattice_sup α] : semilattice_sup (ι →₀ α) := { sup := zip_with (⊔) sup_idem, le_sup_left := λ f g i, le_sup_left, le_sup_right := λ f g i, le_sup_right, sup_le := λ f g h hf hg i, sup_le (hf i) (hg i), ..finsupp.partial_order } @[simp] lemma sup_apply [semilattice_sup α] {i : ι} {f g : ι →₀ α} : (f ⊔ g) i = f i ⊔ g i := rfl instance lattice [lattice α] : lattice (ι →₀ α) := { .. finsupp.semilattice_inf, .. finsupp.semilattice_sup } end has_zero /-! ### Algebraic order structures -/ instance [ordered_add_comm_monoid α] : ordered_add_comm_monoid (ι →₀ α) := { add_le_add_left := λ a b h c s, add_le_add_left (h s) (c s), .. finsupp.add_comm_monoid, .. finsupp.partial_order } instance [ordered_cancel_add_comm_monoid α] : ordered_cancel_add_comm_monoid (ι →₀ α) := { le_of_add_le_add_left := λ f g i h s, le_of_add_le_add_left (h s), .. finsupp.ordered_add_comm_monoid } instance [ordered_add_comm_monoid α] [contravariant_class α α (+) (≤)] : contravariant_class (ι →₀ α) (ι →₀ α) (+) (≤) := ⟨λ f g h H x, le_of_add_le_add_left $ H x⟩ section canonically_ordered_add_monoid variables [canonically_ordered_add_monoid α] instance : order_bot (ι →₀ α) := { bot := 0, bot_le := by simp only [le_def, coe_zero, pi.zero_apply, implies_true_iff, zero_le]} protected lemma bot_eq_zero : (⊥ : ι →₀ α) = 0 := rfl @[simp] lemma add_eq_zero_iff (f g : ι →₀ α) : f + g = 0 ↔ f = 0 ∧ g = 0 := by simp [ext_iff, forall_and_distrib] lemma le_iff' (f g : ι →₀ α) {s : finset ι} (hf : f.support ⊆ s) : f ≤ g ↔ ∀ i ∈ s, f i ≤ g i := ⟨λ h s hs, h s, λ h s, if H : s ∈ f.support then h s (hf H) else (not_mem_support_iff.1 H).symm ▸ zero_le (g s)⟩ lemma le_iff (f g : ι →₀ α) : f ≤ g ↔ ∀ i ∈ f.support, f i ≤ g i := le_iff' f g $ subset.refl _ instance decidable_le [decidable_rel (@has_le.le α _)] : decidable_rel (@has_le.le (ι →₀ α) _) := λ f g, decidable_of_iff _ (le_iff f g).symm @[simp] lemma single_le_iff {i : ι} {x : α} {f : ι →₀ α} : single i x ≤ f ↔ x ≤ f i := (le_iff' _ _ support_single_subset).trans $ by simp variables [has_sub α] [has_ordered_sub α] {f g : ι →₀ α} {i : ι} {a b : α} /-- This is called `tsub` for truncated subtraction, to distinguish it with subtraction in an additive group. -/ instance tsub : has_sub (ι →₀ α) := ⟨zip_with (λ m n, m - n) (tsub_self 0)⟩ instance : has_ordered_sub (ι →₀ α) := ⟨λ n m k, forall_congr $ λ x, tsub_le_iff_right⟩ instance : canonically_ordered_add_monoid (ι →₀ α) := { exists_add_of_le := λ f g h, ⟨g - f, ext $ λ x, (add_tsub_cancel_of_le $ h x).symm⟩, le_self_add := λ f g x, le_self_add, .. finsupp.order_bot, .. finsupp.ordered_add_comm_monoid } @[simp] lemma coe_tsub (f g : ι →₀ α) : ⇑(f - g) = f - g := rfl lemma tsub_apply (f g : ι →₀ α) (a : ι) : (f - g) a = f a - g a := rfl @[simp] lemma single_tsub : single i (a - b) = single i a - single i b := begin ext j, obtain rfl | h := eq_or_ne i j, { rw [tsub_apply, single_eq_same, single_eq_same, single_eq_same] }, { rw [tsub_apply, single_eq_of_ne h, single_eq_of_ne h, single_eq_of_ne h, tsub_self] } end lemma support_tsub {f1 f2 : ι →₀ α} : (f1 - f2).support ⊆ f1.support := by simp only [subset_iff, tsub_eq_zero_iff_le, mem_support_iff, ne.def, coe_tsub, pi.sub_apply, not_imp_not, zero_le, implies_true_iff] {contextual := tt} lemma subset_support_tsub {f1 f2 : ι →₀ α} : f1.support \ f2.support ⊆ (f1 - f2).support := by simp [subset_iff] {contextual := tt} end canonically_ordered_add_monoid section canonically_linear_ordered_add_monoid variables [canonically_linear_ordered_add_monoid α] [decidable_eq ι] {f g : ι →₀ α} @[simp] lemma support_inf : (f ⊓ g).support = f.support ∩ g.support := begin ext, simp only [inf_apply, mem_support_iff, ne.def, finset.mem_union, finset.mem_filter, finset.mem_inter], simp only [inf_eq_min, ←nonpos_iff_eq_zero, min_le_iff, not_or_distrib], end @[simp] lemma support_sup : (f ⊔ g).support = f.support ∪ g.support := begin ext, simp only [finset.mem_union, mem_support_iff, sup_apply, ne.def, ←bot_eq_zero], rw [_root_.sup_eq_bot_iff, not_and_distrib], end lemma disjoint_iff : disjoint f g ↔ disjoint f.support g.support := begin rw [disjoint_iff, disjoint_iff, finsupp.bot_eq_zero, ← finsupp.support_eq_empty, finsupp.support_inf], refl, end end canonically_linear_ordered_add_monoid /-! ### Some lemmas about `ℕ` -/ section nat lemma sub_single_one_add {a : ι} {u u' : ι →₀ ℕ} (h : u a ≠ 0) : u - single a 1 + u' = u + u' - single a 1 := tsub_add_eq_add_tsub $ single_le_iff.mpr $ nat.one_le_iff_ne_zero.mpr h lemma add_sub_single_one {a : ι} {u u' : ι →₀ ℕ} (h : u' a ≠ 0) : u + (u' - single a 1) = u + u' - single a 1 := (add_tsub_assoc_of_le (single_le_iff.mpr $ nat.one_le_iff_ne_zero.mpr h) _).symm end nat end finsupp
a9f32d32a291a5b7b70f0a761cd6ed2621d3e3ed
14d3c04048fcbea3818a26103a6e4f1c99fc6c62
/src/test.lean
44fd9a4fef38c3ff7c18d3d2a3767d9498d82814
[]
no_license
gihanmarasingha/myint
866a880ae7ade3de7d1e8550e6d2c4be94f1b85f
eba85880a500a7977cc4e23c9fa51877dfc82b58
refs/heads/master
1,682,793,960,074
1,619,541,459,000
1,619,541,459,000
360,702,700
0
0
null
null
null
null
UTF-8
Lean
false
false
3,391
lean
import tactic data.rat data.nat.prime data.real.irrational import analysis.special_functions.pow section sqrt2 open rat /- We prove that sqrt 2 is irrational. To make things simple, we work with natural numbers instead of rational numbers. The idea is to derive a contradiction from the assumption that `(a^2 = 2 * (b ^ 2))` for coprime natural nubmers `a` and `b`. -/ -- First an auxiliary result to show `2 ∣ x` if `x * x = 2 * y`. lemma aux {x y : ℕ} (h : x * x = 2 * y) : 2 ∣ x := (or_self (2 ∣ x)).mp $ (nat.prime.dvd_mul nat.prime_two).mp ⟨y, h⟩ -- Proof of the irrationality of sqrt 2. example (a b : ℕ) (cop : nat.coprime a b) : ¬(a^2 = 2*b^2) := begin simp only [pow_two], intro h, have twodiva : 2 ∣ a := aux h, have twodiva' := twodiva, -- make a copy! cases twodiva' with m hm, rw [hm, mul_assoc] at h, have hdiv : m * (2* m) = b * b, from mul_left_cancel' two_ne_zero h, rw [mul_comm, mul_assoc] at hdiv, have twodivb : 2 ∣ b := aux hdiv.symm, exact nat.not_coprime_of_dvd_of_dvd one_lt_two twodiva twodivb cop, end /- example : ¬(∃ x : ℚ, x * x= 2) := λ h, exists.elim h $ λ x, num_denom_cases_on' x (λ n d dne0 cop, _ ) -/ /- example : ¬(∃ x : ℚ, x * x= 2) := λ h, exists.elim h $ λ x, ( or.elim (em (x = 0)) (λ hx0, by { rw [hx0, mul_zero], intro z2, exact two_ne_zero z2.symm, }) (λ hxne0, num_denom_cases_on' x _) ) -/ end sqrt2 section irr_pow_irr open real /- We show there exist irrational numbers `a` and `b` such that `a ^ b` is rational. -/ -- A proof using `convert`. example : ∃ a b : ℝ, irrational a ∧ irrational b ∧ ¬(irrational (a ^ b)) := begin have irrs2 := irrational_sqrt_two, by_cases h : irrational ((sqrt 2)^(sqrt 2)), { use [(sqrt 2)^(sqrt 2), sqrt 2], split, { exact h }, clear h, split, { exact irrs2 }, have ss_nat : sqrt 2 ^ 2 = 2 := sqr_sqrt zero_le_two, rw [←rpow_mul (sqrt_nonneg 2), ←pow_two, ss_nat], intro h₂, apply rat.not_irrational 2, convert h₂, have sqr_sqrt2 : (sqrt 2)^(2 : ℝ) = 2, { conv_rhs { rw ←ss_nat}, simp [←rpow_nat_cast], }, simp [sqr_sqrt2], }, { use [sqrt 2, sqrt 2], tauto, } end -- A proof without `convert`. example : ∃ a b : ℝ, irrational a ∧ irrational b ∧ ¬(irrational (a ^ b)) := begin have irrs2 := irrational_sqrt_two, by_cases h : irrational ((sqrt 2)^(sqrt 2)), { use [(sqrt 2)^(sqrt 2), sqrt 2], split, { exact h }, clear h, split, { exact irrs2 }, have ss_nat : sqrt 2 ^ 2 = 2 := sqr_sqrt zero_le_two, rw [←rpow_mul (sqrt_nonneg 2), ←pow_two, ss_nat], rw (show (sqrt 2)^(2 : ℝ) = 2, by { conv_rhs { rw ←ss_nat}, simp [←rpow_nat_cast], } ), have := rat.not_irrational 2, simpa, }, { use [sqrt 2, sqrt 2], tauto, } end -- A short proof. example : ∃ a b : ℝ, irrational a ∧ irrational b ∧ ¬(irrational (a ^ b)) := begin have irrs2 := irrational_sqrt_two, by_cases h : irrational ((sqrt 2)^(sqrt 2)), { use [(sqrt 2)^(sqrt 2), sqrt 2], split, { exact h }, clear h, split, { exact irrs2 }, have ss_nat : sqrt 2 ^ 2 = 2 := sqr_sqrt zero_le_two, rw [←rpow_mul (sqrt_nonneg 2), ←pow_two, ss_nat], rw (show (sqrt 2)^(2 : ℝ) = 2, by { conv_rhs { rw ←ss_nat}, simp [←rpow_nat_cast], } ), convert rat.not_irrational 2, simp, }, { use [sqrt 2, sqrt 2], tauto, } end end irr_pow_irr
2b99ad90ef83726a1dea0e9f16017ea7dce9421c
947fa6c38e48771ae886239b4edce6db6e18d0fb
/src/measure_theory/function/strongly_measurable.lean
f7e62a731a501d0ad03fe438ebb70ca843bbcbef
[ "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
87,418
lean
/- Copyright (c) 2021 Rémy Degenne. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Rémy Degenne, Sébastien Gouëzel -/ import measure_theory.function.ess_sup import measure_theory.integral.mean_inequalities import topology.continuous_function.compact import topology.metric_space.metrizable import measure_theory.function.simple_func_dense /-! # Strongly measurable and finitely strongly measurable functions A function `f` is said to be strongly measurable if `f` is the sequential limit of simple functions. It is said to be finitely strongly measurable with respect to a measure `μ` if the supports of those simple functions have finite measure. We also provide almost everywhere versions of these notions. Almost everywhere strongly measurable functions form the largest class of functions that can be integrated using the Bochner integral. If the target space has a second countable topology, strongly measurable and measurable are equivalent. If the measure is sigma-finite, strongly measurable and finitely strongly measurable are equivalent. The main property of finitely strongly measurable functions is `fin_strongly_measurable.exists_set_sigma_finite`: there exists a measurable set `t` such that the function is supported on `t` and `μ.restrict t` is sigma-finite. As a consequence, we can prove some results for those functions as if the measure was sigma-finite. ## Main definitions * `strongly_measurable f`: `f : α → β` is the limit of a sequence `fs : ℕ → simple_func α β`. * `fin_strongly_measurable f μ`: `f : α → β` is the limit of a sequence `fs : ℕ → simple_func α β` such that for all `n ∈ ℕ`, the measure of the support of `fs n` is finite. * `ae_strongly_measurable f μ`: `f` is almost everywhere equal to a `strongly_measurable` function. * `ae_fin_strongly_measurable f μ`: `f` is almost everywhere equal to a `fin_strongly_measurable` function. * `ae_fin_strongly_measurable.sigma_finite_set`: a measurable set `t` such that `f =ᵐ[μ.restrict tᶜ] 0` and `μ.restrict t` is sigma-finite. ## Main statements * `ae_fin_strongly_measurable.exists_set_sigma_finite`: there exists a measurable set `t` such that `f =ᵐ[μ.restrict tᶜ] 0` and `μ.restrict t` is sigma-finite. We provide a solid API for strongly measurable functions, and for almost everywhere strongly measurable functions, as a basis for the Bochner integral. ## References * Hytönen, Tuomas, Jan Van Neerven, Mark Veraar, and Lutz Weis. Analysis in Banach spaces. Springer, 2016. -/ open measure_theory filter topological_space function set measure_theory.measure open_locale ennreal topological_space measure_theory nnreal big_operators /-- The typeclass `second_countable_topology_either α β` registers the fact that at least one of the two spaces has second countable topology. This is the right assumption to ensure that continuous maps from `α` to `β` are strongly measurable. -/ class second_countable_topology_either (α β : Type*) [topological_space α] [topological_space β] : Prop := (out : second_countable_topology α ∨ second_countable_topology β) @[priority 100] instance second_countable_topology_either_of_left (α β : Type*) [topological_space α] [topological_space β] [second_countable_topology α] : second_countable_topology_either α β := { out := or.inl (by apply_instance) } @[priority 100] instance second_countable_topology_either_of_right (α β : Type*) [topological_space α] [topological_space β] [second_countable_topology β] : second_countable_topology_either α β := { out := or.inr (by apply_instance) } variables {α β γ ι : Type*} [encodable ι] namespace measure_theory local infixr ` →ₛ `:25 := simple_func section definitions variable [topological_space β] /-- A function is `strongly_measurable` if it is the limit of simple functions. -/ def strongly_measurable [measurable_space α] (f : α → β) : Prop := ∃ fs : ℕ → α →ₛ β, ∀ x, tendsto (λ n, fs n x) at_top (𝓝 (f x)) localized "notation `strongly_measurable[` m `]` := @measure_theory.strongly_measurable _ _ _ m" in measure_theory /-- A function is `fin_strongly_measurable` with respect to a measure if it is the limit of simple functions with support with finite measure. -/ def fin_strongly_measurable [has_zero β] {m0 : measurable_space α} (f : α → β) (μ : measure α) : Prop := ∃ fs : ℕ → α →ₛ β, (∀ n, μ (support (fs n)) < ∞) ∧ (∀ x, tendsto (λ n, fs n x) at_top (𝓝 (f x))) /-- A function is `ae_strongly_measurable` with respect to a measure `μ` if it is almost everywhere equal to the limit of a sequence of simple functions. -/ def ae_strongly_measurable {m0 : measurable_space α} (f : α → β) (μ : measure α) : Prop := ∃ g, strongly_measurable g ∧ f =ᵐ[μ] g /-- A function is `ae_fin_strongly_measurable` with respect to a measure if it is almost everywhere equal to the limit of a sequence of simple functions with support with finite measure. -/ def ae_fin_strongly_measurable [has_zero β] {m0 : measurable_space α} (f : α → β) (μ : measure α) : Prop := ∃ g, fin_strongly_measurable g μ ∧ f =ᵐ[μ] g end definitions open_locale measure_theory /-! ## Strongly measurable functions -/ lemma strongly_measurable.ae_strongly_measurable {α β} {m0 : measurable_space α} [topological_space β] {f : α → β} {μ : measure α} (hf : strongly_measurable f) : ae_strongly_measurable f μ := ⟨f, hf, eventually_eq.refl _ _⟩ @[simp] lemma subsingleton.strongly_measurable {α β} [measurable_space α] [topological_space β] [subsingleton β] (f : α → β) : strongly_measurable f := begin let f_sf : α →ₛ β := ⟨f, λ x, _, set.subsingleton.finite set.subsingleton_of_subsingleton⟩, { exact ⟨λ n, f_sf, λ x, tendsto_const_nhds⟩, }, { have h_univ : f ⁻¹' {x} = set.univ, by { ext1 y, simp, }, rw h_univ, exact measurable_set.univ, }, end lemma simple_func.strongly_measurable {α β} {m : measurable_space α} [topological_space β] (f : α →ₛ β) : strongly_measurable f := ⟨λ _, f, λ x, tendsto_const_nhds⟩ lemma strongly_measurable_of_is_empty [is_empty α] {m : measurable_space α} [topological_space β] (f : α → β) : strongly_measurable f := ⟨λ n, simple_func.of_is_empty, is_empty_elim⟩ lemma strongly_measurable_const {α β} {m : measurable_space α} [topological_space β] {b : β} : strongly_measurable (λ a : α, b) := ⟨λ n, simple_func.const α b, λ a, tendsto_const_nhds⟩ @[to_additive] lemma strongly_measurable_one {α β} {m : measurable_space α} [topological_space β] [has_one β] : strongly_measurable (1 : α → β) := @strongly_measurable_const _ _ _ _ 1 /-- A version of `strongly_measurable_const` that assumes `f x = f y` for all `x, y`. This version works for functions between empty types. -/ lemma strongly_measurable_const' {α β} {m : measurable_space α} [topological_space β] {f : α → β} (hf : ∀ x y, f x = f y) : strongly_measurable f := begin casesI is_empty_or_nonempty α, { exact strongly_measurable_of_is_empty f }, { convert strongly_measurable_const, exact funext (λ x, hf x h.some) } end @[simp] lemma subsingleton.strongly_measurable' {α β} [measurable_space α] [topological_space β] [subsingleton α] (f : α → β) : strongly_measurable f := strongly_measurable_const' (λ x y, by rw subsingleton.elim x y) namespace strongly_measurable variables {f g : α → β} section basic_properties_in_any_topological_space variables [topological_space β] /-- A sequence of simple functions such that `∀ x, tendsto (λ n, hf.approx n x) at_top (𝓝 (f x))`. That property is given by `strongly_measurable.tendsto_approx`. -/ protected noncomputable def approx {m : measurable_space α} (hf : strongly_measurable f) : ℕ → α →ₛ β := hf.some protected lemma tendsto_approx {m : measurable_space α} (hf : strongly_measurable f) : ∀ x, tendsto (λ n, hf.approx n x) at_top (𝓝 (f x)) := hf.some_spec /-- Similar to `strongly_measurable.approx`, but enforces that the norm of every function in the sequence is less than `c` everywhere. If `∥f x∥ ≤ c` this sequence of simple functions verifies `tendsto (λ n, hf.approx_bounded n x) at_top (𝓝 (f x))`. -/ noncomputable def approx_bounded {m : measurable_space α} [has_norm β] [has_smul ℝ β] (hf : strongly_measurable f) (c : ℝ) : ℕ → simple_func α β := λ n, (hf.approx n).map (λ x, (min 1 (c / ∥x∥)) • x) lemma tendsto_approx_bounded_of_norm_le {β} {f : α → β} [normed_add_comm_group β] [normed_space ℝ β] {m : measurable_space α} (hf : strongly_measurable[m] f) {c : ℝ} {x : α} (hfx : ∥f x∥ ≤ c) : tendsto (λ n, hf.approx_bounded c n x) at_top (𝓝 (f x)) := begin have h_tendsto := hf.tendsto_approx x, simp only [strongly_measurable.approx_bounded, simple_func.coe_map, function.comp_app], by_cases hfx0 : ∥f x∥ = 0, { rw norm_eq_zero at hfx0, rw hfx0 at h_tendsto ⊢, have h_tendsto_norm : tendsto (λ n, ∥hf.approx n x∥) at_top (𝓝 0), { convert h_tendsto.norm, rw norm_zero, }, refine squeeze_zero_norm (λ n, _) h_tendsto_norm, calc ∥min 1 (c / ∥hf.approx n x∥) • hf.approx n x∥ = ∥min 1 (c / ∥hf.approx n x∥)∥ * ∥hf.approx n x∥ : norm_smul _ _ ... ≤ ∥(1 : ℝ)∥ * ∥hf.approx n x∥ : begin refine mul_le_mul_of_nonneg_right _ (norm_nonneg _), rw [norm_one, real.norm_of_nonneg], { exact min_le_left _ _, }, { exact le_min zero_le_one (div_nonneg ((norm_nonneg _).trans hfx) (norm_nonneg _)), }, end ... = ∥hf.approx n x∥ : by rw [norm_one, one_mul], }, rw ← one_smul ℝ (f x), refine tendsto.smul _ h_tendsto, have : min 1 (c / ∥f x∥) = 1, { rw [min_eq_left_iff, one_le_div (lt_of_le_of_ne (norm_nonneg _) (ne.symm hfx0))], exact hfx, }, nth_rewrite 0 this.symm, refine tendsto.min tendsto_const_nhds _, refine tendsto.div tendsto_const_nhds h_tendsto.norm hfx0, end lemma tendsto_approx_bounded_ae {β} {f : α → β} [normed_add_comm_group β] [normed_space ℝ β] {m m0 : measurable_space α} {μ : measure α} (hf : strongly_measurable[m] f) {c : ℝ} (hf_bound : ∀ᵐ x ∂μ, ∥f x∥ ≤ c) : ∀ᵐ x ∂μ, tendsto (λ n, hf.approx_bounded c n x) at_top (𝓝 (f x)) := by filter_upwards [hf_bound] with x hfx using tendsto_approx_bounded_of_norm_le hf hfx lemma norm_approx_bounded_le {β} {f : α → β} [seminormed_add_comm_group β] [normed_space ℝ β] {m : measurable_space α} {c : ℝ} (hf : strongly_measurable[m] f) (hc : 0 ≤ c) (n : ℕ) (x : α) : ∥hf.approx_bounded c n x∥ ≤ c := begin simp only [strongly_measurable.approx_bounded, simple_func.coe_map, function.comp_app], refine (norm_smul _ _).le.trans _, by_cases h0 : ∥hf.approx n x∥ = 0, { simp only [h0, div_zero, min_eq_right, zero_le_one, norm_zero, mul_zero], exact hc, }, cases le_total (∥hf.approx n x∥) c, { rw min_eq_left _, { simpa only [norm_one, one_mul] using h, }, { rwa one_le_div (lt_of_le_of_ne (norm_nonneg _) (ne.symm h0)), }, }, { rw min_eq_right _, { rw [norm_div, norm_norm, mul_comm, mul_div, div_eq_mul_inv, mul_comm, ← mul_assoc, inv_mul_cancel h0, one_mul, real.norm_of_nonneg hc], }, { rwa div_le_one (lt_of_le_of_ne (norm_nonneg _) (ne.symm h0)), }, }, end end basic_properties_in_any_topological_space lemma fin_strongly_measurable_of_set_sigma_finite [topological_space β] [has_zero β] {m : measurable_space α} {μ : measure α} (hf_meas : strongly_measurable f) {t : set α} (ht : measurable_set t) (hft_zero : ∀ x ∈ tᶜ, f x = 0) (htμ : sigma_finite (μ.restrict t)) : fin_strongly_measurable f μ := begin haveI : sigma_finite (μ.restrict t) := htμ, let S := spanning_sets (μ.restrict t), have hS_meas : ∀ n, measurable_set (S n), from measurable_spanning_sets (μ.restrict t), let f_approx := hf_meas.approx, let fs := λ n, simple_func.restrict (f_approx n) (S n ∩ t), have h_fs_t_compl : ∀ n, ∀ x ∉ t, fs n x = 0, { intros n x hxt, rw simple_func.restrict_apply _ ((hS_meas n).inter ht), refine set.indicator_of_not_mem _ _, simp [hxt], }, refine ⟨fs, _, λ x, _⟩, { simp_rw simple_func.support_eq, refine λ n, (measure_bUnion_finset_le _ _).trans_lt _, refine ennreal.sum_lt_top_iff.mpr (λ y hy, _), rw simple_func.restrict_preimage_singleton _ ((hS_meas n).inter ht), swap, { rw finset.mem_filter at hy, exact hy.2, }, refine (measure_mono (set.inter_subset_left _ _)).trans_lt _, have h_lt_top := measure_spanning_sets_lt_top (μ.restrict t) n, rwa measure.restrict_apply' ht at h_lt_top, }, { by_cases hxt : x ∈ t, swap, { rw [funext (λ n, h_fs_t_compl n x hxt), hft_zero x hxt], exact tendsto_const_nhds, }, have h : tendsto (λ n, (f_approx n) x) at_top (𝓝 (f x)), from hf_meas.tendsto_approx x, obtain ⟨n₁, hn₁⟩ : ∃ n, ∀ m, n ≤ m → fs m x = f_approx m x, { obtain ⟨n, hn⟩ : ∃ n, ∀ m, n ≤ m → x ∈ S m ∩ t, { suffices : ∃ n, ∀ m, n ≤ m → x ∈ S m, { obtain ⟨n, hn⟩ := this, exact ⟨n, λ m hnm, set.mem_inter (hn m hnm) hxt⟩, }, suffices : ∃ n, x ∈ S n, { rcases this with ⟨n, hn⟩, exact ⟨n, λ m hnm, monotone_spanning_sets (μ.restrict t) hnm hn⟩, }, rw [← set.mem_Union, Union_spanning_sets (μ.restrict t)], trivial, }, refine ⟨n, λ m hnm, _⟩, simp_rw [fs, simple_func.restrict_apply _ ((hS_meas m).inter ht), set.indicator_of_mem (hn m hnm)], }, rw tendsto_at_top' at h ⊢, intros s hs, obtain ⟨n₂, hn₂⟩ := h s hs, refine ⟨max n₁ n₂, λ m hm, _⟩, rw hn₁ m ((le_max_left _ _).trans hm.le), exact hn₂ m ((le_max_right _ _).trans hm.le), }, end /-- If the measure is sigma-finite, all strongly measurable functions are `fin_strongly_measurable`. -/ protected lemma fin_strongly_measurable [topological_space β] [has_zero β] {m0 : measurable_space α} (hf : strongly_measurable f) (μ : measure α) [sigma_finite μ] : fin_strongly_measurable f μ := hf.fin_strongly_measurable_of_set_sigma_finite measurable_set.univ (by simp) (by rwa measure.restrict_univ) /-- A strongly measurable function is measurable. -/ protected lemma measurable {m : measurable_space α} [topological_space β] [pseudo_metrizable_space β] [measurable_space β] [borel_space β] (hf : strongly_measurable f) : measurable f := measurable_of_tendsto_metrizable (λ n, (hf.approx n).measurable) (tendsto_pi_nhds.mpr hf.tendsto_approx) /-- A strongly measurable function is almost everywhere measurable. -/ protected lemma ae_measurable {m : measurable_space α} [topological_space β] [pseudo_metrizable_space β] [measurable_space β] [borel_space β] {μ : measure α} (hf : strongly_measurable f) : ae_measurable f μ := hf.measurable.ae_measurable lemma _root_.continuous.comp_strongly_measurable {m : measurable_space α} [topological_space β] [topological_space γ] {g : β → γ} {f : α → β} (hg : continuous g) (hf : strongly_measurable f) : strongly_measurable (λ x, g (f x)) := ⟨λ n, simple_func.map g (hf.approx n), λ x, (hg.tendsto _).comp (hf.tendsto_approx x)⟩ @[to_additive] lemma measurable_set_mul_support {m : measurable_space α} [has_one β] [topological_space β] [metrizable_space β] (hf : strongly_measurable f) : measurable_set (mul_support f) := by { borelize β, exact measurable_set_mul_support hf.measurable } protected lemma mono {m m' : measurable_space α} [topological_space β] (hf : strongly_measurable[m'] f) (h_mono : m' ≤ m) : strongly_measurable[m] f := begin let f_approx : ℕ → @simple_func α m β := λ n, { to_fun := hf.approx n, measurable_set_fiber' := λ x, h_mono _ (simple_func.measurable_set_fiber' _ x), finite_range' := simple_func.finite_range (hf.approx n) }, exact ⟨f_approx, hf.tendsto_approx⟩, end protected lemma prod_mk {m : measurable_space α} [topological_space β] [topological_space γ] {f : α → β} {g : α → γ} (hf : strongly_measurable f) (hg : strongly_measurable g) : strongly_measurable (λ x, (f x, g x)) := begin refine ⟨λ n, simple_func.pair (hf.approx n) (hg.approx n), λ x, _⟩, rw nhds_prod_eq, exact tendsto.prod_mk (hf.tendsto_approx x) (hg.tendsto_approx x), end lemma comp_measurable [topological_space β] {m : measurable_space α} {m' : measurable_space γ} {f : α → β} {g : γ → α} (hf : strongly_measurable f) (hg : measurable g) : strongly_measurable (f ∘ g) := ⟨λ n, simple_func.comp (hf.approx n) g hg, λ x, hf.tendsto_approx (g x)⟩ lemma of_uncurry_left [topological_space β] {mα : measurable_space α} {mγ : measurable_space γ} {f : α → γ → β} (hf : strongly_measurable (uncurry f)) {x : α} : strongly_measurable (f x) := hf.comp_measurable measurable_prod_mk_left lemma of_uncurry_right [topological_space β] {mα : measurable_space α} {mγ : measurable_space γ} {f : α → γ → β} (hf : strongly_measurable (uncurry f)) {y : γ} : strongly_measurable (λ x, f x y) := hf.comp_measurable measurable_prod_mk_right section arithmetic variables {mα : measurable_space α} [topological_space β] include mα @[to_additive] protected lemma mul [has_mul β] [has_continuous_mul β] (hf : strongly_measurable f) (hg : strongly_measurable g) : strongly_measurable (f * g) := ⟨λ n, hf.approx n * hg.approx n, λ x, (hf.tendsto_approx x).mul (hg.tendsto_approx x)⟩ @[to_additive] lemma mul_const [has_mul β] [has_continuous_mul β] (hf : strongly_measurable f) (c : β) : strongly_measurable (λ x, f x * c) := hf.mul strongly_measurable_const @[to_additive] lemma const_mul [has_mul β] [has_continuous_mul β] (hf : strongly_measurable f) (c : β) : strongly_measurable (λ x, c * f x) := strongly_measurable_const.mul hf @[to_additive] protected lemma inv [group β] [topological_group β] (hf : strongly_measurable f) : strongly_measurable f⁻¹ := ⟨λ n, (hf.approx n)⁻¹, λ x, (hf.tendsto_approx x).inv⟩ @[to_additive] protected lemma div [has_div β] [has_continuous_div β] (hf : strongly_measurable f) (hg : strongly_measurable g) : strongly_measurable (f / g) := ⟨λ n, hf.approx n / hg.approx n, λ x, (hf.tendsto_approx x).div' (hg.tendsto_approx x)⟩ @[to_additive] protected lemma smul {𝕜} [topological_space 𝕜] [has_smul 𝕜 β] [has_continuous_smul 𝕜 β] {f : α → 𝕜} {g : α → β} (hf : strongly_measurable f) (hg : strongly_measurable g) : strongly_measurable (λ x, f x • g x) := continuous_smul.comp_strongly_measurable (hf.prod_mk hg) protected lemma const_smul {𝕜} [has_smul 𝕜 β] [has_continuous_const_smul 𝕜 β] (hf : strongly_measurable f) (c : 𝕜) : strongly_measurable (c • f) := ⟨λ n, c • (hf.approx n), λ x, (hf.tendsto_approx x).const_smul c⟩ protected lemma const_smul' {𝕜} [has_smul 𝕜 β] [has_continuous_const_smul 𝕜 β] (hf : strongly_measurable f) (c : 𝕜) : strongly_measurable (λ x, c • (f x)) := hf.const_smul c @[to_additive] protected lemma smul_const {𝕜} [topological_space 𝕜] [has_smul 𝕜 β] [has_continuous_smul 𝕜 β] {f : α → 𝕜} (hf : strongly_measurable f) (c : β) : strongly_measurable (λ x, f x • c) := continuous_smul.comp_strongly_measurable (hf.prod_mk strongly_measurable_const) end arithmetic section mul_action variables [topological_space β] {G : Type*} [group G] [mul_action G β] [has_continuous_const_smul G β] lemma _root_.strongly_measurable_const_smul_iff {m : measurable_space α} (c : G) : strongly_measurable (λ x, c • f x) ↔ strongly_measurable f := ⟨λ h, by simpa only [inv_smul_smul] using h.const_smul' c⁻¹, λ h, h.const_smul c⟩ variables {G₀ : Type*} [group_with_zero G₀] [mul_action G₀ β] [has_continuous_const_smul G₀ β] lemma _root_.strongly_measurable_const_smul_iff₀ {m : measurable_space α} {c : G₀} (hc : c ≠ 0) : strongly_measurable (λ x, c • f x) ↔ strongly_measurable f := begin refine ⟨λ h, _, λ h, h.const_smul c⟩, convert h.const_smul' c⁻¹, simp [smul_smul, inv_mul_cancel hc] end end mul_action section order variables [measurable_space α] [topological_space β] open filter open_locale filter protected lemma sup [has_sup β] [has_continuous_sup β] (hf : strongly_measurable f) (hg : strongly_measurable g) : strongly_measurable (f ⊔ g) := ⟨λ n, hf.approx n ⊔ hg.approx n, λ x, (hf.tendsto_approx x).sup_right_nhds (hg.tendsto_approx x)⟩ protected lemma inf [has_inf β] [has_continuous_inf β] (hf : strongly_measurable f) (hg : strongly_measurable g) : strongly_measurable (f ⊓ g) := ⟨λ n, hf.approx n ⊓ hg.approx n, λ x, (hf.tendsto_approx x).inf_right_nhds (hg.tendsto_approx x)⟩ end order /-! ### Big operators: `∏` and `∑` -/ section monoid variables {M : Type*} [monoid M] [topological_space M] [has_continuous_mul M] {m : measurable_space α} include m @[to_additive] lemma _root_.list.strongly_measurable_prod' (l : list (α → M)) (hl : ∀ f ∈ l, strongly_measurable f) : strongly_measurable l.prod := begin induction l with f l ihl, { exact strongly_measurable_one }, rw [list.forall_mem_cons] at hl, rw [list.prod_cons], exact hl.1.mul (ihl hl.2) end @[to_additive] lemma _root_.list.strongly_measurable_prod (l : list (α → M)) (hl : ∀ f ∈ l, strongly_measurable f) : strongly_measurable (λ x, (l.map (λ f : α → M, f x)).prod) := by simpa only [← pi.list_prod_apply] using l.strongly_measurable_prod' hl end monoid section comm_monoid variables {M : Type*} [comm_monoid M] [topological_space M] [has_continuous_mul M] {m : measurable_space α} include m @[to_additive] lemma _root_.multiset.strongly_measurable_prod' (l : multiset (α → M)) (hl : ∀ f ∈ l, strongly_measurable f) : strongly_measurable l.prod := by { rcases l with ⟨l⟩, simpa using l.strongly_measurable_prod' (by simpa using hl) } @[to_additive] lemma _root_.multiset.strongly_measurable_prod (s : multiset (α → M)) (hs : ∀ f ∈ s, strongly_measurable f) : strongly_measurable (λ x, (s.map (λ f : α → M, f x)).prod) := by simpa only [← pi.multiset_prod_apply] using s.strongly_measurable_prod' hs @[to_additive] lemma _root_.finset.strongly_measurable_prod' {ι : Type*} {f : ι → α → M} (s : finset ι) (hf : ∀i ∈ s, strongly_measurable (f i)) : strongly_measurable (∏ i in s, f i) := finset.prod_induction _ _ (λ a b ha hb, ha.mul hb) (@strongly_measurable_one α M _ _ _) hf @[to_additive] lemma _root_.finset.strongly_measurable_prod {ι : Type*} {f : ι → α → M} (s : finset ι) (hf : ∀i ∈ s, strongly_measurable (f i)) : strongly_measurable (λ a, ∏ i in s, f i a) := by simpa only [← finset.prod_apply] using s.strongly_measurable_prod' hf end comm_monoid /-- The range of a strongly measurable function is separable. -/ lemma is_separable_range {m : measurable_space α} [topological_space β] (hf : strongly_measurable f) : topological_space.is_separable (range f) := begin have : is_separable (closure (⋃ n, range (hf.approx n))) := (is_separable_Union (λ n, (simple_func.finite_range (hf.approx n)).is_separable)).closure, apply this.mono, rintros _ ⟨x, rfl⟩, apply mem_closure_of_tendsto (hf.tendsto_approx x), apply eventually_of_forall (λ n, _), apply mem_Union_of_mem n, exact mem_range_self _ end lemma separable_space_range_union_singleton {m : measurable_space α} [topological_space β] [pseudo_metrizable_space β] (hf : strongly_measurable f) {b : β} : separable_space (range f ∪ {b} : set β) := begin letI := pseudo_metrizable_space_pseudo_metric β, exact (hf.is_separable_range.union (finite_singleton _).is_separable).separable_space end section second_countable_strongly_measurable variables {mα : measurable_space α} [measurable_space β] include mα /-- In a space with second countable topology, measurable implies strongly measurable. -/ lemma _root_.measurable.strongly_measurable [topological_space β] [pseudo_metrizable_space β] [second_countable_topology β] [opens_measurable_space β] (hf : measurable f) : strongly_measurable f := begin letI := pseudo_metrizable_space_pseudo_metric β, rcases is_empty_or_nonempty β; resetI, { exact subsingleton.strongly_measurable f, }, { inhabit β, exact ⟨simple_func.approx_on f hf set.univ default (set.mem_univ _), λ x, simple_func.tendsto_approx_on hf (set.mem_univ _) (by simp)⟩, }, end /-- In a space with second countable topology, strongly measurable and measurable are equivalent. -/ lemma _root_.strongly_measurable_iff_measurable [topological_space β] [metrizable_space β] [borel_space β] [second_countable_topology β] : strongly_measurable f ↔ measurable f := ⟨λ h, h.measurable, λ h, measurable.strongly_measurable h⟩ lemma _root_.strongly_measurable_id [topological_space α] [pseudo_metrizable_space α] [opens_measurable_space α] [second_countable_topology α] : strongly_measurable (id : α → α) := measurable_id.strongly_measurable end second_countable_strongly_measurable /-- A function is strongly measurable if and only if it is measurable and has separable range. -/ theorem _root_.strongly_measurable_iff_measurable_separable {m : measurable_space α} [topological_space β] [pseudo_metrizable_space β] [measurable_space β] [borel_space β] : strongly_measurable f ↔ (measurable f ∧ is_separable (range f)) := begin refine ⟨λ H, ⟨H.measurable, H.is_separable_range⟩, _⟩, rintros ⟨H, H'⟩, letI := pseudo_metrizable_space_pseudo_metric β, let g := cod_restrict f (closure (range f)) (λ x, subset_closure (mem_range_self x)), have fg : f = (coe : closure (range f) → β) ∘ g, by { ext x, refl }, have T : measurable_embedding (coe : closure (range f) → β), { apply closed_embedding.measurable_embedding, exact closed_embedding_subtype_coe is_closed_closure }, have g_meas : measurable g, { rw fg at H, exact T.measurable_comp_iff.1 H }, haveI : second_countable_topology (closure (range f)), { suffices : separable_space (closure (range f)), by exactI uniform_space.second_countable_of_separable _, exact (is_separable.closure H').separable_space }, have g_smeas : strongly_measurable g := measurable.strongly_measurable g_meas, rw fg, exact continuous_subtype_coe.comp_strongly_measurable g_smeas, end /-- A continuous function is strongly measurable when either the source space or the target space is second-countable. -/ lemma _root_.continuous.strongly_measurable [measurable_space α] [topological_space α] [opens_measurable_space α] {β : Type*} [topological_space β] [pseudo_metrizable_space β] [h : second_countable_topology_either α β] {f : α → β} (hf : continuous f) : strongly_measurable f := begin borelize β, casesI h.out, { rw strongly_measurable_iff_measurable_separable, refine ⟨hf.measurable, _⟩, rw ← image_univ, exact (is_separable_of_separable_space univ).image hf }, { exact hf.measurable.strongly_measurable } end /-- If `g` is a topological embedding, then `f` is strongly measurable iff `g ∘ f` is. -/ lemma _root_.embedding.comp_strongly_measurable_iff {m : measurable_space α} [topological_space β] [pseudo_metrizable_space β] [topological_space γ] [pseudo_metrizable_space γ] {g : β → γ} {f : α → β} (hg : embedding g) : strongly_measurable (λ x, g (f x)) ↔ strongly_measurable f := begin letI := pseudo_metrizable_space_pseudo_metric γ, borelize [β, γ], refine ⟨λ H, strongly_measurable_iff_measurable_separable.2 ⟨_, _⟩, λ H, hg.continuous.comp_strongly_measurable H⟩, { let G : β → range g := cod_restrict g (range g) mem_range_self, have hG : closed_embedding G := { closed_range := begin convert is_closed_univ, apply eq_univ_of_forall, rintros ⟨-, ⟨x, rfl⟩⟩, exact mem_range_self x end, .. hg.cod_restrict _ _ }, have : measurable (G ∘ f) := measurable.subtype_mk H.measurable, exact hG.measurable_embedding.measurable_comp_iff.1 this }, { have : is_separable (g ⁻¹' (range (g ∘ f))) := hg.is_separable_preimage H.is_separable_range, convert this, ext x, simp [hg.inj.eq_iff] } end /-- A sequential limit of strongly measurable functions is strongly measurable. -/ lemma _root_.strongly_measurable_of_tendsto {ι : Type*} {m : measurable_space α} [topological_space β] [pseudo_metrizable_space β] (u : filter ι) [ne_bot u] [is_countably_generated u] {f : ι → α → β} {g : α → β} (hf : ∀ i, strongly_measurable (f i)) (lim : tendsto f u (𝓝 g)) : strongly_measurable g := begin borelize β, refine strongly_measurable_iff_measurable_separable.2 ⟨_, _⟩, { exact measurable_of_tendsto_metrizable' u (λ i, (hf i).measurable) lim }, { rcases u.exists_seq_tendsto with ⟨v, hv⟩, have : is_separable (closure (⋃ i, range (f (v i)))) := (is_separable_Union (λ i, (hf (v i)).is_separable_range)).closure, apply this.mono, rintros _ ⟨x, rfl⟩, rw [tendsto_pi_nhds] at lim, apply mem_closure_of_tendsto ((lim x).comp hv), apply eventually_of_forall (λ n, _), apply mem_Union_of_mem n, exact mem_range_self _ } end protected lemma piecewise {m : measurable_space α} [topological_space β] {s : set α} {_ : decidable_pred (∈ s)} (hs : measurable_set s) (hf : strongly_measurable f) (hg : strongly_measurable g) : strongly_measurable (set.piecewise s f g) := begin refine ⟨λ n, simple_func.piecewise s hs (hf.approx n) (hg.approx n), λ x, _⟩, by_cases hx : x ∈ s, { simpa [hx] using hf.tendsto_approx x }, { simpa [hx] using hg.tendsto_approx x }, end /-- this is slightly different from `strongly_measurable.piecewise`. It can be used to show `strongly_measurable (ite (x=0) 0 1)` by `exact strongly_measurable.ite (measurable_set_singleton 0) strongly_measurable_const strongly_measurable_const`, but replacing `strongly_measurable.ite` by `strongly_measurable.piecewise` in that example proof does not work. -/ protected lemma ite {m : measurable_space α} [topological_space β] {p : α → Prop} {_ : decidable_pred p} (hp : measurable_set {a : α | p a}) (hf : strongly_measurable f) (hg : strongly_measurable g) : strongly_measurable (λ x, ite (p x) (f x) (g x)) := strongly_measurable.piecewise hp hf hg lemma _root_.strongly_measurable_of_strongly_measurable_union_cover {m : measurable_space α} [topological_space β] {f : α → β} (s t : set α) (hs : measurable_set s) (ht : measurable_set t) (h : univ ⊆ s ∪ t) (hc : strongly_measurable (λ a : s, f a)) (hd : strongly_measurable (λ a : t, f a)) : strongly_measurable f := begin classical, let f : ℕ → α →ₛ β := λ n, { to_fun := λ x, if hx : x ∈ s then hc.approx n ⟨x, hx⟩ else hd.approx n ⟨x, by simpa [hx] using h (mem_univ x)⟩, measurable_set_fiber' := begin assume x, convert (hs.subtype_image ((hc.approx n).measurable_set_fiber x)).union ((ht.subtype_image ((hd.approx n).measurable_set_fiber x)).diff hs), ext1 y, simp only [mem_union_eq, mem_preimage, mem_singleton_iff, mem_image, set_coe.exists, subtype.coe_mk, exists_and_distrib_right, exists_eq_right, mem_diff], by_cases hy : y ∈ s, { rw dif_pos hy, simp only [hy, exists_true_left, not_true, and_false, or_false]}, { rw dif_neg hy, have A : y ∈ t, by simpa [hy] using h (mem_univ y), simp only [A, hy, false_or, is_empty.exists_iff, not_false_iff, and_true, exists_true_left] } end, finite_range' := begin apply ((hc.approx n).finite_range.union (hd.approx n).finite_range).subset, rintros - ⟨y, rfl⟩, dsimp, by_cases hy : y ∈ s, { left, rw dif_pos hy, exact mem_range_self _ }, { right, rw dif_neg hy, exact mem_range_self _ } end }, refine ⟨f, λ y, _⟩, by_cases hy : y ∈ s, { convert hc.tendsto_approx ⟨y, hy⟩ using 1, ext1 n, simp only [dif_pos hy, simple_func.apply_mk] }, { have A : y ∈ t, by simpa [hy] using h (mem_univ y), convert hd.tendsto_approx ⟨y, A⟩ using 1, ext1 n, simp only [dif_neg hy, simple_func.apply_mk] } end lemma _root_.strongly_measurable_of_restrict_of_restrict_compl {m : measurable_space α} [topological_space β] {f : α → β} {s : set α} (hs : measurable_set s) (h₁ : strongly_measurable (s.restrict f)) (h₂ : strongly_measurable (sᶜ.restrict f)) : strongly_measurable f := strongly_measurable_of_strongly_measurable_union_cover s sᶜ hs hs.compl (union_compl_self s).ge h₁ h₂ protected lemma indicator {m : measurable_space α} [topological_space β] [has_zero β] (hf : strongly_measurable f) {s : set α} (hs : measurable_set s) : strongly_measurable (s.indicator f) := hf.piecewise hs strongly_measurable_const protected lemma dist {m : measurable_space α} {β : Type*} [pseudo_metric_space β] {f g : α → β} (hf : strongly_measurable f) (hg : strongly_measurable g) : strongly_measurable (λ x, dist (f x) (g x)) := continuous_dist.comp_strongly_measurable (hf.prod_mk hg) protected lemma norm {m : measurable_space α} {β : Type*} [seminormed_add_comm_group β] {f : α → β} (hf : strongly_measurable f) : strongly_measurable (λ x, ∥f x∥) := continuous_norm.comp_strongly_measurable hf protected lemma nnnorm {m : measurable_space α} {β : Type*} [seminormed_add_comm_group β] {f : α → β} (hf : strongly_measurable f) : strongly_measurable (λ x, ∥f x∥₊) := continuous_nnnorm.comp_strongly_measurable hf protected lemma ennnorm {m : measurable_space α} {β : Type*} [seminormed_add_comm_group β] {f : α → β} (hf : strongly_measurable f) : measurable (λ a, (∥f a∥₊ : ℝ≥0∞)) := (ennreal.continuous_coe.comp_strongly_measurable hf.nnnorm).measurable protected lemma real_to_nnreal {m : measurable_space α} {f : α → ℝ} (hf : strongly_measurable f) : strongly_measurable (λ x, (f x).to_nnreal) := continuous_real_to_nnreal.comp_strongly_measurable hf lemma _root_.measurable_embedding.strongly_measurable_extend {f : α → β} {g : α → γ} {g' : γ → β} {mα : measurable_space α} {mγ : measurable_space γ} [topological_space β] (hg : measurable_embedding g) (hf : strongly_measurable f) (hg' : strongly_measurable g') : strongly_measurable (function.extend g f g') := begin refine ⟨λ n, simple_func.extend (hf.approx n) g hg (hg'.approx n), _⟩, assume x, by_cases hx : ∃ y, g y = x, { rcases hx with ⟨y, rfl⟩, simpa only [simple_func.extend_apply, hg.injective, extend_apply] using hf.tendsto_approx y }, { simpa only [hx, simple_func.extend_apply', not_false_iff, extend_apply'] using hg'.tendsto_approx x } end lemma _root_.measurable_embedding.exists_strongly_measurable_extend {f : α → β} {g : α → γ} {mα : measurable_space α} {mγ : measurable_space γ} [topological_space β] (hg : measurable_embedding g) (hf : strongly_measurable f) (hne : γ → nonempty β) : ∃ f' : γ → β, strongly_measurable f' ∧ f' ∘ g = f := ⟨function.extend g f (λ x, classical.choice (hne x)), hg.strongly_measurable_extend hf (strongly_measurable_const' $ λ _ _, rfl), funext $ λ x, extend_apply hg.injective _ _ _⟩ protected lemma inner {𝕜 : Type*} {E : Type*} [is_R_or_C 𝕜] [inner_product_space 𝕜 E] {m : measurable_space α} {f g : α → E} (hf : strongly_measurable f) (hg : strongly_measurable g) : strongly_measurable (λ t, @inner 𝕜 _ _(f t) (g t)) := continuous.comp_strongly_measurable continuous_inner (hf.prod_mk hg) lemma measurable_set_eq_fun {m : measurable_space α} {E} [topological_space E] [metrizable_space E] {f g : α → E} (hf : strongly_measurable f) (hg : strongly_measurable g) : measurable_set {x | f x = g x} := begin borelize E × E, exact (hf.prod_mk hg).measurable is_closed_diagonal.measurable_set end lemma measurable_set_lt {m : measurable_space α} [topological_space β] [linear_order β] [order_closed_topology β] [pseudo_metrizable_space β] {f g : α → β} (hf : strongly_measurable f) (hg : strongly_measurable g) : measurable_set {a | f a < g a} := begin borelize β × β, exact (hf.prod_mk hg).measurable is_open_lt_prod.measurable_set end lemma measurable_set_le {m : measurable_space α} [topological_space β] [preorder β] [order_closed_topology β] [pseudo_metrizable_space β] {f g : α → β} (hf : strongly_measurable f) (hg : strongly_measurable g) : measurable_set {a | f a ≤ g a} := begin borelize β × β, exact (hf.prod_mk hg).measurable is_closed_le_prod.measurable_set end lemma strongly_measurable_in_set {m : measurable_space α} [topological_space β] [has_zero β] {s : set α} {f : α → β} (hs : measurable_set s) (hf : strongly_measurable f) (hf_zero : ∀ x ∉ s, f x = 0) : ∃ fs : ℕ → α →ₛ β, (∀ x, tendsto (λ n, fs n x) at_top (𝓝 (f x))) ∧ (∀ (x ∉ s) n, fs n x = 0) := begin let g_seq_s : ℕ → @simple_func α m β := λ n, (hf.approx n).restrict s, have hg_eq : ∀ x ∈ s, ∀ n, g_seq_s n x = hf.approx n x, { intros x hx n, rw [simple_func.coe_restrict _ hs, set.indicator_of_mem hx], }, have hg_zero : ∀ x ∉ s, ∀ n, g_seq_s n x = 0, { intros x hx n, rw [simple_func.coe_restrict _ hs, set.indicator_of_not_mem hx], }, refine ⟨g_seq_s, λ x, _, hg_zero⟩, by_cases hx : x ∈ s, { simp_rw hg_eq x hx, exact hf.tendsto_approx x, }, { simp_rw [hg_zero x hx, hf_zero x hx], exact tendsto_const_nhds, }, end /-- If the restriction to a set `s` of a σ-algebra `m` is included in the restriction to `s` of another σ-algebra `m₂` (hypothesis `hs`), the set `s` is `m` measurable and a function `f` supported on `s` is `m`-strongly-measurable, then `f` is also `m₂`-strongly-measurable. -/ lemma strongly_measurable_of_measurable_space_le_on {α E} {m m₂ : measurable_space α} [topological_space E] [has_zero E] {s : set α} {f : α → E} (hs_m : measurable_set[m] s) (hs : ∀ t, measurable_set[m] (s ∩ t) → measurable_set[m₂] (s ∩ t)) (hf : strongly_measurable[m] f) (hf_zero : ∀ x ∉ s, f x = 0) : strongly_measurable[m₂] f := begin have hs_m₂ : measurable_set[m₂] s, { rw ← set.inter_univ s, refine hs set.univ _, rwa [set.inter_univ], }, obtain ⟨g_seq_s, hg_seq_tendsto, hg_seq_zero⟩ := strongly_measurable_in_set hs_m hf hf_zero, let g_seq_s₂ : ℕ → @simple_func α m₂ E := λ n, { to_fun := g_seq_s n, measurable_set_fiber' := λ x, begin rw [← set.inter_univ ((g_seq_s n) ⁻¹' {x}), ← set.union_compl_self s, set.inter_union_distrib_left, set.inter_comm ((g_seq_s n) ⁻¹' {x})], refine measurable_set.union (hs _ (hs_m.inter _)) _, { exact @simple_func.measurable_set_fiber _ _ m _ _, }, by_cases hx : x = 0, { suffices : (g_seq_s n) ⁻¹' {x} ∩ sᶜ = sᶜ, by { rw this, exact hs_m₂.compl, }, ext1 y, rw [hx, set.mem_inter_iff, set.mem_preimage, set.mem_singleton_iff], exact ⟨λ h, h.2, λ h, ⟨hg_seq_zero y h n, h⟩⟩, }, { suffices : (g_seq_s n) ⁻¹' {x} ∩ sᶜ = ∅, by { rw this, exact measurable_set.empty, }, ext1 y, simp only [mem_inter_eq, mem_preimage, mem_singleton_iff, mem_compl_eq, mem_empty_eq, iff_false, not_and, not_not_mem], refine imp_of_not_imp_not _ _ (λ hys, _), rw hg_seq_zero y hys n, exact ne.symm hx, }, end, finite_range' := @simple_func.finite_range _ _ m (g_seq_s n), }, have hg_eq : ∀ x n, g_seq_s₂ n x = g_seq_s n x := λ x n, rfl, refine ⟨g_seq_s₂, λ x, _⟩, simp_rw hg_eq, exact hg_seq_tendsto x, end /-- If a function `f` is strongly measurable w.r.t. a sub-σ-algebra `m` and the measure is σ-finite on `m`, then there exists spanning measurable sets with finite measure on which `f` has bounded norm. In particular, `f` is integrable on each of those sets. -/ lemma exists_spanning_measurable_set_norm_le [seminormed_add_comm_group β] {m m0 : measurable_space α} (hm : m ≤ m0) (hf : strongly_measurable[m] f) (μ : measure α) [sigma_finite (μ.trim hm)] : ∃ s : ℕ → set α, (∀ n, measurable_set[m] (s n) ∧ μ (s n) < ∞ ∧ ∀ x ∈ s n, ∥f x∥ ≤ n) ∧ (⋃ i, s i) = set.univ := begin let sigma_finite_sets := spanning_sets (μ.trim hm), let norm_sets := λ (n : ℕ), {x | ∥f x∥ ≤ n}, have norm_sets_spanning : (⋃ n, norm_sets n) = set.univ, { ext1 x, simp only [set.mem_Union, set.mem_set_of_eq, set.mem_univ, iff_true], exact ⟨⌈∥f x∥⌉₊, nat.le_ceil (∥f x∥)⟩, }, let sets := λ n, sigma_finite_sets n ∩ norm_sets n, have h_meas : ∀ n, measurable_set[m] (sets n), { refine λ n, measurable_set.inter _ _, { exact measurable_spanning_sets (μ.trim hm) n, }, { exact hf.norm.measurable_set_le strongly_measurable_const, }, }, have h_finite : ∀ n, μ (sets n) < ∞, { refine λ n, (measure_mono (set.inter_subset_left _ _)).trans_lt _, exact (le_trim hm).trans_lt (measure_spanning_sets_lt_top (μ.trim hm) n), }, refine ⟨sets, λ n, ⟨h_meas n, h_finite n, _⟩, _⟩, { exact λ x hx, hx.2, }, { have : (⋃ i, sigma_finite_sets i ∩ norm_sets i) = (⋃ i, sigma_finite_sets i) ∩ (⋃ i, norm_sets i), { refine set.Union_inter_of_monotone (monotone_spanning_sets (μ.trim hm)) (λ i j hij x, _), simp only [norm_sets, set.mem_set_of_eq], refine λ hif, hif.trans _, exact_mod_cast hij, }, rw [this, norm_sets_spanning, Union_spanning_sets (μ.trim hm), set.inter_univ], }, end end strongly_measurable /-! ## Finitely strongly measurable functions -/ lemma fin_strongly_measurable_zero {α β} {m : measurable_space α} {μ : measure α} [has_zero β] [topological_space β] : fin_strongly_measurable (0 : α → β) μ := ⟨0, by simp only [pi.zero_apply, simple_func.coe_zero, support_zero', measure_empty, with_top.zero_lt_top, forall_const], λ n, tendsto_const_nhds⟩ namespace fin_strongly_measurable variables {m0 : measurable_space α} {μ : measure α} {f g : α → β} lemma ae_fin_strongly_measurable [has_zero β] [topological_space β] (hf : fin_strongly_measurable f μ) : ae_fin_strongly_measurable f μ := ⟨f, hf, ae_eq_refl f⟩ section sequence variables [has_zero β] [topological_space β] (hf : fin_strongly_measurable f μ) /-- A sequence of simple functions such that `∀ x, tendsto (λ n, hf.approx n x) at_top (𝓝 (f x))` and `∀ n, μ (support (hf.approx n)) < ∞`. These properties are given by `fin_strongly_measurable.tendsto_approx` and `fin_strongly_measurable.fin_support_approx`. -/ protected noncomputable def approx : ℕ → α →ₛ β := hf.some protected lemma fin_support_approx : ∀ n, μ (support (hf.approx n)) < ∞ := hf.some_spec.1 protected lemma tendsto_approx : ∀ x, tendsto (λ n, hf.approx n x) at_top (𝓝 (f x)) := hf.some_spec.2 end sequence protected lemma strongly_measurable [has_zero β] [topological_space β] (hf : fin_strongly_measurable f μ) : strongly_measurable f := ⟨hf.approx, hf.tendsto_approx⟩ lemma exists_set_sigma_finite [has_zero β] [topological_space β] [t2_space β] (hf : fin_strongly_measurable f μ) : ∃ t, measurable_set t ∧ (∀ x ∈ tᶜ, f x = 0) ∧ sigma_finite (μ.restrict t) := begin rcases hf with ⟨fs, hT_lt_top, h_approx⟩, let T := λ n, support (fs n), have hT_meas : ∀ n, measurable_set (T n), from λ n, simple_func.measurable_set_support (fs n), let t := ⋃ n, T n, refine ⟨t, measurable_set.Union hT_meas, _, _⟩, { have h_fs_zero : ∀ n, ∀ x ∈ tᶜ, fs n x = 0, { intros n x hxt, rw [set.mem_compl_iff, set.mem_Union, not_exists] at hxt, simpa using (hxt n), }, refine λ x hxt, tendsto_nhds_unique (h_approx x) _, rw funext (λ n, h_fs_zero n x hxt), exact tendsto_const_nhds, }, { refine ⟨⟨⟨λ n, tᶜ ∪ T n, λ n, trivial, λ n, _, _⟩⟩⟩, { rw [measure.restrict_apply' (measurable_set.Union hT_meas), set.union_inter_distrib_right, set.compl_inter_self t, set.empty_union], exact (measure_mono (set.inter_subset_left _ _)).trans_lt (hT_lt_top n), }, { rw ← set.union_Union tᶜ T, exact set.compl_union_self _ } } end /-- A finitely strongly measurable function is measurable. -/ protected lemma measurable [has_zero β] [topological_space β] [pseudo_metrizable_space β] [measurable_space β] [borel_space β] (hf : fin_strongly_measurable f μ) : measurable f := hf.strongly_measurable.measurable section arithmetic variables [topological_space β] protected lemma mul [monoid_with_zero β] [has_continuous_mul β] (hf : fin_strongly_measurable f μ) (hg : fin_strongly_measurable g μ) : fin_strongly_measurable (f * g) μ := begin refine ⟨λ n, hf.approx n * hg.approx n, _, λ x, (hf.tendsto_approx x).mul (hg.tendsto_approx x)⟩, intro n, exact (measure_mono (support_mul_subset_left _ _)).trans_lt (hf.fin_support_approx n), end protected lemma add [add_monoid β] [has_continuous_add β] (hf : fin_strongly_measurable f μ) (hg : fin_strongly_measurable g μ) : fin_strongly_measurable (f + g) μ := ⟨λ n, hf.approx n + hg.approx n, λ n, (measure_mono (function.support_add _ _)).trans_lt ((measure_union_le _ _).trans_lt (ennreal.add_lt_top.mpr ⟨hf.fin_support_approx n, hg.fin_support_approx n⟩)), λ x, (hf.tendsto_approx x).add (hg.tendsto_approx x)⟩ protected lemma neg [add_group β] [topological_add_group β] (hf : fin_strongly_measurable f μ) : fin_strongly_measurable (-f) μ := begin refine ⟨λ n, -hf.approx n, λ n, _, λ x, (hf.tendsto_approx x).neg⟩, suffices : μ (function.support (λ x, - (hf.approx n) x)) < ∞, by convert this, rw function.support_neg (hf.approx n), exact hf.fin_support_approx n, end protected lemma sub [add_group β] [has_continuous_sub β] (hf : fin_strongly_measurable f μ) (hg : fin_strongly_measurable g μ) : fin_strongly_measurable (f - g) μ := ⟨λ n, hf.approx n - hg.approx n, λ n, (measure_mono (function.support_sub _ _)).trans_lt ((measure_union_le _ _).trans_lt (ennreal.add_lt_top.mpr ⟨hf.fin_support_approx n, hg.fin_support_approx n⟩)), λ x, (hf.tendsto_approx x).sub (hg.tendsto_approx x)⟩ protected lemma const_smul {𝕜} [topological_space 𝕜] [add_monoid β] [monoid 𝕜] [distrib_mul_action 𝕜 β] [has_continuous_smul 𝕜 β] (hf : fin_strongly_measurable f μ) (c : 𝕜) : fin_strongly_measurable (c • f) μ := begin refine ⟨λ n, c • (hf.approx n), λ n, _, λ x, (hf.tendsto_approx x).const_smul c⟩, rw simple_func.coe_smul, refine (measure_mono (support_smul_subset_right c _)).trans_lt (hf.fin_support_approx n), end end arithmetic section order variables [topological_space β] [has_zero β] protected lemma sup [semilattice_sup β] [has_continuous_sup β] (hf : fin_strongly_measurable f μ) (hg : fin_strongly_measurable g μ) : fin_strongly_measurable (f ⊔ g) μ := begin refine ⟨λ n, hf.approx n ⊔ hg.approx n, λ n, _, λ x, (hf.tendsto_approx x).sup_right_nhds (hg.tendsto_approx x)⟩, refine (measure_mono (support_sup _ _)).trans_lt _, exact measure_union_lt_top_iff.mpr ⟨hf.fin_support_approx n, hg.fin_support_approx n⟩, end protected lemma inf [semilattice_inf β] [has_continuous_inf β] (hf : fin_strongly_measurable f μ) (hg : fin_strongly_measurable g μ) : fin_strongly_measurable (f ⊓ g) μ := begin refine ⟨λ n, hf.approx n ⊓ hg.approx n, λ n, _, λ x, (hf.tendsto_approx x).inf_right_nhds (hg.tendsto_approx x)⟩, refine (measure_mono (support_inf _ _)).trans_lt _, exact measure_union_lt_top_iff.mpr ⟨hf.fin_support_approx n, hg.fin_support_approx n⟩, end end order end fin_strongly_measurable lemma fin_strongly_measurable_iff_strongly_measurable_and_exists_set_sigma_finite {α β} {f : α → β} [topological_space β] [t2_space β] [has_zero β] {m : measurable_space α} {μ : measure α} : fin_strongly_measurable f μ ↔ (strongly_measurable f ∧ (∃ t, measurable_set t ∧ (∀ x ∈ tᶜ, f x = 0) ∧ sigma_finite (μ.restrict t))) := ⟨λ hf, ⟨hf.strongly_measurable, hf.exists_set_sigma_finite⟩, λ hf, hf.1.fin_strongly_measurable_of_set_sigma_finite hf.2.some_spec.1 hf.2.some_spec.2.1 hf.2.some_spec.2.2⟩ lemma ae_fin_strongly_measurable_zero {α β} {m : measurable_space α} (μ : measure α) [has_zero β] [topological_space β] : ae_fin_strongly_measurable (0 : α → β) μ := ⟨0, fin_strongly_measurable_zero, eventually_eq.rfl⟩ /-! ## Almost everywhere strongly measurable functions -/ lemma ae_strongly_measurable_const {α β} {m : measurable_space α} {μ : measure α} [topological_space β] {b : β} : ae_strongly_measurable (λ a : α, b) μ := strongly_measurable_const.ae_strongly_measurable @[to_additive] lemma ae_strongly_measurable_one {α β} {m : measurable_space α} {μ : measure α} [topological_space β] [has_one β] : ae_strongly_measurable (1 : α → β) μ := strongly_measurable_one.ae_strongly_measurable @[simp] lemma subsingleton.ae_strongly_measurable {m : measurable_space α} [topological_space β] [subsingleton β] {μ : measure α} (f : α → β) : ae_strongly_measurable f μ := (subsingleton.strongly_measurable f).ae_strongly_measurable @[simp] lemma subsingleton.ae_strongly_measurable' {m : measurable_space α} [topological_space β] [subsingleton α] {μ : measure α} (f : α → β) : ae_strongly_measurable f μ := (subsingleton.strongly_measurable' f).ae_strongly_measurable @[simp] lemma ae_strongly_measurable_zero_measure [measurable_space α] [topological_space β] (f : α → β) : ae_strongly_measurable f (0 : measure α) := begin nontriviality α, inhabit α, exact ⟨λ x, f default, strongly_measurable_const, rfl⟩ end lemma simple_func.ae_strongly_measurable {m : measurable_space α} {μ : measure α} [topological_space β] (f : α →ₛ β) : ae_strongly_measurable f μ := f.strongly_measurable.ae_strongly_measurable namespace ae_strongly_measurable variables {m : measurable_space α} {μ : measure α} [topological_space β] [topological_space γ] {f g : α → β} section mk /-- A `strongly_measurable` function such that `f =ᵐ[μ] hf.mk f`. See lemmas `strongly_measurable_mk` and `ae_eq_mk`. -/ protected noncomputable def mk (f : α → β) (hf : ae_strongly_measurable f μ) : α → β := hf.some lemma strongly_measurable_mk (hf : ae_strongly_measurable f μ) : strongly_measurable (hf.mk f) := hf.some_spec.1 lemma measurable_mk [pseudo_metrizable_space β] [measurable_space β] [borel_space β] (hf : ae_strongly_measurable f μ) : measurable (hf.mk f) := hf.strongly_measurable_mk.measurable lemma ae_eq_mk (hf : ae_strongly_measurable f μ) : f =ᵐ[μ] hf.mk f := hf.some_spec.2 protected lemma ae_measurable {β} [measurable_space β] [topological_space β] [pseudo_metrizable_space β] [borel_space β] {f : α → β} (hf : ae_strongly_measurable f μ) : ae_measurable f μ := ⟨hf.mk f, hf.strongly_measurable_mk.measurable, hf.ae_eq_mk⟩ end mk lemma congr (hf : ae_strongly_measurable f μ) (h : f =ᵐ[μ] g) : ae_strongly_measurable g μ := ⟨hf.mk f, hf.strongly_measurable_mk, h.symm.trans hf.ae_eq_mk⟩ lemma _root_.ae_strongly_measurable_congr (h : f =ᵐ[μ] g) : ae_strongly_measurable f μ ↔ ae_strongly_measurable g μ := ⟨λ hf, hf.congr h, λ hg, hg.congr h.symm⟩ lemma mono_measure {ν : measure α} (hf : ae_strongly_measurable f μ) (h : ν ≤ μ) : ae_strongly_measurable f ν := ⟨hf.mk f, hf.strongly_measurable_mk, eventually.filter_mono (ae_mono h) hf.ae_eq_mk⟩ protected lemma mono' {ν : measure α} (h : ae_strongly_measurable f μ) (h' : ν ≪ μ) : ae_strongly_measurable f ν := ⟨h.mk f, h.strongly_measurable_mk, h' h.ae_eq_mk⟩ lemma mono_set {s t} (h : s ⊆ t) (ht : ae_strongly_measurable f (μ.restrict t)) : ae_strongly_measurable f (μ.restrict s) := ht.mono_measure (restrict_mono h le_rfl) protected lemma restrict (hfm : ae_strongly_measurable f μ) {s} : ae_strongly_measurable f (μ.restrict s) := hfm.mono_measure measure.restrict_le_self lemma ae_mem_imp_eq_mk {s} (h : ae_strongly_measurable f (μ.restrict s)) : ∀ᵐ x ∂μ, x ∈ s → f x = h.mk f x := ae_imp_of_ae_restrict h.ae_eq_mk /-- The composition of a continuous function and an ae strongly measurable function is ae strongly measurable. -/ lemma _root_.continuous.comp_ae_strongly_measurable {g : β → γ} {f : α → β} (hg : continuous g) (hf : ae_strongly_measurable f μ) : ae_strongly_measurable (λ x, g (f x)) μ := ⟨_, hg.comp_strongly_measurable hf.strongly_measurable_mk, eventually_eq.fun_comp hf.ae_eq_mk g⟩ /-- A continuous function from `α` to `β` is ae strongly measurable when one of the two spaces is second countable. -/ lemma _root_.continuous.ae_strongly_measurable [topological_space α] [opens_measurable_space α] [pseudo_metrizable_space β] [second_countable_topology_either α β] (hf : continuous f) : ae_strongly_measurable f μ := hf.strongly_measurable.ae_strongly_measurable protected lemma prod_mk {f : α → β} {g : α → γ} (hf : ae_strongly_measurable f μ) (hg : ae_strongly_measurable g μ) : ae_strongly_measurable (λ x, (f x, g x)) μ := ⟨λ x, (hf.mk f x, hg.mk g x), hf.strongly_measurable_mk.prod_mk hg.strongly_measurable_mk, hf.ae_eq_mk.prod_mk hg.ae_eq_mk⟩ /-- In a space with second countable topology, measurable implies ae strongly measurable. -/ lemma _root_.measurable.ae_strongly_measurable {m : measurable_space α} {μ : measure α} [measurable_space β] [pseudo_metrizable_space β] [second_countable_topology β] [opens_measurable_space β] (hf : measurable f) : ae_strongly_measurable f μ := hf.strongly_measurable.ae_strongly_measurable section arithmetic @[to_additive] protected lemma mul [has_mul β] [has_continuous_mul β] (hf : ae_strongly_measurable f μ) (hg : ae_strongly_measurable g μ) : ae_strongly_measurable (f * g) μ := ⟨hf.mk f * hg.mk g, hf.strongly_measurable_mk.mul hg.strongly_measurable_mk, hf.ae_eq_mk.mul hg.ae_eq_mk⟩ @[to_additive] protected lemma mul_const [has_mul β] [has_continuous_mul β] (hf : ae_strongly_measurable f μ) (c : β) : ae_strongly_measurable (λ x, f x * c) μ := hf.mul ae_strongly_measurable_const @[to_additive] protected lemma const_mul [has_mul β] [has_continuous_mul β] (hf : ae_strongly_measurable f μ) (c : β) : ae_strongly_measurable (λ x, c * f x) μ := ae_strongly_measurable_const.mul hf @[to_additive] protected lemma inv [group β] [topological_group β] (hf : ae_strongly_measurable f μ) : ae_strongly_measurable (f⁻¹) μ := ⟨(hf.mk f)⁻¹, hf.strongly_measurable_mk.inv, hf.ae_eq_mk.inv⟩ @[to_additive] protected lemma div [group β] [topological_group β] (hf : ae_strongly_measurable f μ) (hg : ae_strongly_measurable g μ) : ae_strongly_measurable (f / g) μ := ⟨hf.mk f / hg.mk g, hf.strongly_measurable_mk.div hg.strongly_measurable_mk, hf.ae_eq_mk.div hg.ae_eq_mk⟩ @[to_additive] protected lemma smul {𝕜} [topological_space 𝕜] [has_smul 𝕜 β] [has_continuous_smul 𝕜 β] {f : α → 𝕜} {g : α → β} (hf : ae_strongly_measurable f μ) (hg : ae_strongly_measurable g μ) : ae_strongly_measurable (λ x, f x • g x) μ := continuous_smul.comp_ae_strongly_measurable (hf.prod_mk hg) protected lemma const_smul {𝕜} [has_smul 𝕜 β] [has_continuous_const_smul 𝕜 β] (hf : ae_strongly_measurable f μ) (c : 𝕜) : ae_strongly_measurable (c • f) μ := ⟨c • hf.mk f, hf.strongly_measurable_mk.const_smul c, hf.ae_eq_mk.const_smul c⟩ protected lemma const_smul' {𝕜} [has_smul 𝕜 β] [has_continuous_const_smul 𝕜 β] (hf : ae_strongly_measurable f μ) (c : 𝕜) : ae_strongly_measurable (λ x, c • (f x)) μ := hf.const_smul c @[to_additive] protected lemma smul_const {𝕜} [topological_space 𝕜] [has_smul 𝕜 β] [has_continuous_smul 𝕜 β] {f : α → 𝕜} (hf : ae_strongly_measurable f μ) (c : β) : ae_strongly_measurable (λ x, f x • c) μ := continuous_smul.comp_ae_strongly_measurable (hf.prod_mk ae_strongly_measurable_const) end arithmetic section order protected lemma sup [semilattice_sup β] [has_continuous_sup β] (hf : ae_strongly_measurable f μ) (hg : ae_strongly_measurable g μ) : ae_strongly_measurable (f ⊔ g) μ := ⟨hf.mk f ⊔ hg.mk g, hf.strongly_measurable_mk.sup hg.strongly_measurable_mk, hf.ae_eq_mk.sup hg.ae_eq_mk⟩ protected lemma inf [semilattice_inf β] [has_continuous_inf β] (hf : ae_strongly_measurable f μ) (hg : ae_strongly_measurable g μ) : ae_strongly_measurable (f ⊓ g) μ := ⟨hf.mk f ⊓ hg.mk g, hf.strongly_measurable_mk.inf hg.strongly_measurable_mk, hf.ae_eq_mk.inf hg.ae_eq_mk⟩ end order /-! ### Big operators: `∏` and `∑` -/ section monoid variables {M : Type*} [monoid M] [topological_space M] [has_continuous_mul M] @[to_additive] lemma _root_.list.ae_strongly_measurable_prod' (l : list (α → M)) (hl : ∀ f ∈ l, ae_strongly_measurable f μ) : ae_strongly_measurable l.prod μ := begin induction l with f l ihl, { exact ae_strongly_measurable_one }, rw [list.forall_mem_cons] at hl, rw [list.prod_cons], exact hl.1.mul (ihl hl.2) end @[to_additive] lemma _root_.list.ae_strongly_measurable_prod (l : list (α → M)) (hl : ∀ f ∈ l, ae_strongly_measurable f μ) : ae_strongly_measurable (λ x, (l.map (λ f : α → M, f x)).prod) μ := by simpa only [← pi.list_prod_apply] using l.ae_strongly_measurable_prod' hl end monoid section comm_monoid variables {M : Type*} [comm_monoid M] [topological_space M] [has_continuous_mul M] @[to_additive] lemma _root_.multiset.ae_strongly_measurable_prod' (l : multiset (α → M)) (hl : ∀ f ∈ l, ae_strongly_measurable f μ) : ae_strongly_measurable l.prod μ := by { rcases l with ⟨l⟩, simpa using l.ae_strongly_measurable_prod' (by simpa using hl) } @[to_additive] lemma _root_.multiset.ae_strongly_measurable_prod (s : multiset (α → M)) (hs : ∀ f ∈ s, ae_strongly_measurable f μ) : ae_strongly_measurable (λ x, (s.map (λ f : α → M, f x)).prod) μ := by simpa only [← pi.multiset_prod_apply] using s.ae_strongly_measurable_prod' hs @[to_additive] lemma _root_.finset.ae_strongly_measurable_prod' {ι : Type*} {f : ι → α → M} (s : finset ι) (hf : ∀i ∈ s, ae_strongly_measurable (f i) μ) : ae_strongly_measurable (∏ i in s, f i) μ := multiset.ae_strongly_measurable_prod' _ $ λ g hg, let ⟨i, hi, hg⟩ := multiset.mem_map.1 hg in (hg ▸ hf _ hi) @[to_additive] lemma _root_.finset.ae_strongly_measurable_prod {ι : Type*} {f : ι → α → M} (s : finset ι) (hf : ∀i ∈ s, ae_strongly_measurable (f i) μ) : ae_strongly_measurable (λ a, ∏ i in s, f i a) μ := by simpa only [← finset.prod_apply] using s.ae_strongly_measurable_prod' hf end comm_monoid section second_countable_ae_strongly_measurable variables [measurable_space β] /-- In a space with second countable topology, measurable implies strongly measurable. -/ lemma _root_.ae_measurable.ae_strongly_measurable [pseudo_metrizable_space β] [opens_measurable_space β] [second_countable_topology β] (hf : ae_measurable f μ) : ae_strongly_measurable f μ := ⟨hf.mk f, hf.measurable_mk.strongly_measurable, hf.ae_eq_mk⟩ lemma _root_.ae_strongly_measurable_id {α : Type*} [topological_space α] [pseudo_metrizable_space α] {m : measurable_space α} [opens_measurable_space α] [second_countable_topology α] {μ : measure α} : ae_strongly_measurable (id : α → α) μ := ae_measurable_id.ae_strongly_measurable /-- In a space with second countable topology, strongly measurable and measurable are equivalent. -/ lemma _root_.ae_strongly_measurable_iff_ae_measurable [pseudo_metrizable_space β] [borel_space β] [second_countable_topology β] : ae_strongly_measurable f μ ↔ ae_measurable f μ := ⟨λ h, h.ae_measurable, λ h, h.ae_strongly_measurable⟩ end second_countable_ae_strongly_measurable protected lemma dist {β : Type*} [pseudo_metric_space β] {f g : α → β} (hf : ae_strongly_measurable f μ) (hg : ae_strongly_measurable g μ) : ae_strongly_measurable (λ x, dist (f x) (g x)) μ := continuous_dist.comp_ae_strongly_measurable (hf.prod_mk hg) protected lemma norm {β : Type*} [seminormed_add_comm_group β] {f : α → β} (hf : ae_strongly_measurable f μ) : ae_strongly_measurable (λ x, ∥f x∥) μ := continuous_norm.comp_ae_strongly_measurable hf protected lemma nnnorm {β : Type*} [seminormed_add_comm_group β] {f : α → β} (hf : ae_strongly_measurable f μ) : ae_strongly_measurable (λ x, ∥f x∥₊) μ := continuous_nnnorm.comp_ae_strongly_measurable hf protected lemma ennnorm {β : Type*} [seminormed_add_comm_group β] {f : α → β} (hf : ae_strongly_measurable f μ) : ae_measurable (λ a, (∥f a∥₊ : ℝ≥0∞)) μ := (ennreal.continuous_coe.comp_ae_strongly_measurable hf.nnnorm).ae_measurable protected lemma edist {β : Type*} [seminormed_add_comm_group β] {f g : α → β} (hf : ae_strongly_measurable f μ) (hg : ae_strongly_measurable g μ) : ae_measurable (λ a, edist (f a) (g a)) μ := (continuous_edist.comp_ae_strongly_measurable (hf.prod_mk hg)).ae_measurable protected lemma real_to_nnreal {f : α → ℝ} (hf : ae_strongly_measurable f μ) : ae_strongly_measurable (λ x, (f x).to_nnreal) μ := continuous_real_to_nnreal.comp_ae_strongly_measurable hf section variables {𝕜 : Type*} {E : Type*} [is_R_or_C 𝕜] [inner_product_space 𝕜 E] local notation `⟪`x`, `y`⟫` := @inner 𝕜 _ _ x y protected lemma re {f : α → 𝕜} (hf : ae_strongly_measurable f μ) : ae_strongly_measurable (λ x, is_R_or_C.re (f x)) μ := is_R_or_C.continuous_re.comp_ae_strongly_measurable hf protected lemma im {f : α → 𝕜} (hf : ae_strongly_measurable f μ) : ae_strongly_measurable (λ x, is_R_or_C.im (f x)) μ := is_R_or_C.continuous_im.comp_ae_strongly_measurable hf protected lemma inner {m : measurable_space α} {μ : measure α} {f g : α → E} (hf : ae_strongly_measurable f μ) (hg : ae_strongly_measurable g μ) : ae_strongly_measurable (λ x, ⟪f x, g x⟫) μ := continuous_inner.comp_ae_strongly_measurable (hf.prod_mk hg) end lemma _root_.ae_strongly_measurable_indicator_iff [has_zero β] {s : set α} (hs : measurable_set s) : ae_strongly_measurable (indicator s f) μ ↔ ae_strongly_measurable f (μ.restrict s) := begin split, { intro h, exact (h.mono_measure measure.restrict_le_self).congr (indicator_ae_eq_restrict hs) }, { intro h, refine ⟨indicator s (h.mk f), h.strongly_measurable_mk.indicator hs, _⟩, have A : s.indicator f =ᵐ[μ.restrict s] s.indicator (h.mk f) := (indicator_ae_eq_restrict hs).trans (h.ae_eq_mk.trans $ (indicator_ae_eq_restrict hs).symm), have B : s.indicator f =ᵐ[μ.restrict sᶜ] s.indicator (h.mk f) := (indicator_ae_eq_restrict_compl hs).trans (indicator_ae_eq_restrict_compl hs).symm, exact ae_of_ae_restrict_of_ae_restrict_compl _ A B }, end protected lemma indicator [has_zero β] (hfm : ae_strongly_measurable f μ) {s : set α} (hs : measurable_set s) : ae_strongly_measurable (s.indicator f) μ := (ae_strongly_measurable_indicator_iff hs).mpr hfm.restrict lemma _root_.ae_strongly_measurable_of_ae_strongly_measurable_trim {α} {m m0 : measurable_space α} {μ : measure α} (hm : m ≤ m0) {f : α → β} (hf : ae_strongly_measurable f (μ.trim hm)) : ae_strongly_measurable f μ := ⟨hf.mk f, strongly_measurable.mono hf.strongly_measurable_mk hm, ae_eq_of_ae_eq_trim hf.ae_eq_mk⟩ lemma comp_ae_measurable {γ : Type*} {mγ : measurable_space γ} {mα : measurable_space α} {f : γ → α} {μ : measure γ} (hg : ae_strongly_measurable g (measure.map f μ)) (hf : ae_measurable f μ) : ae_strongly_measurable (g ∘ f) μ := ⟨(hg.mk g) ∘ hf.mk f, hg.strongly_measurable_mk.comp_measurable hf.measurable_mk, (ae_eq_comp hf hg.ae_eq_mk).trans ((hf.ae_eq_mk).fun_comp (hg.mk g))⟩ lemma comp_measurable {γ : Type*} {mγ : measurable_space γ} {mα : measurable_space α} {f : γ → α} {μ : measure γ} (hg : ae_strongly_measurable g (measure.map f μ)) (hf : measurable f) : ae_strongly_measurable (g ∘ f) μ := hg.comp_ae_measurable hf.ae_measurable lemma comp_measurable' {γ : Type*} {mγ : measurable_space γ} {mα : measurable_space α} {f : γ → α} {μ : measure γ} {ν : measure α} (hg : ae_strongly_measurable g ν) (hf : measurable f) (h : μ.map f ≪ ν) : ae_strongly_measurable (g ∘ f) μ := (hg.mono' h).comp_measurable hf lemma is_separable_ae_range (hf : ae_strongly_measurable f μ) : ∃ (t : set β), is_separable t ∧ ∀ᵐ x ∂μ, f x ∈ t := begin refine ⟨range (hf.mk f), hf.strongly_measurable_mk.is_separable_range, _⟩, filter_upwards [hf.ae_eq_mk] with x hx, simp [hx] end /-- A function is almost everywhere strongly measurable if and only if it is almost everywhere measurable, and up to a zero measure set its range is contained in a separable set. -/ theorem _root_.ae_strongly_measurable_iff_ae_measurable_separable [pseudo_metrizable_space β] [measurable_space β] [borel_space β] : ae_strongly_measurable f μ ↔ (ae_measurable f μ ∧ ∃ (t : set β), is_separable t ∧ ∀ᵐ x ∂μ, f x ∈ t) := begin refine ⟨λ H, ⟨H.ae_measurable, H.is_separable_ae_range⟩, _⟩, rintros ⟨H, ⟨t, t_sep, ht⟩⟩, rcases eq_empty_or_nonempty t with rfl|h₀, { simp only [mem_empty_eq, eventually_false_iff_eq_bot, ae_eq_bot] at ht, rw ht, exact ae_strongly_measurable_zero_measure f }, { obtain ⟨g, g_meas, gt, fg⟩ : ∃ (g : α → β), measurable g ∧ range g ⊆ t ∧ f =ᵐ[μ] g := H.exists_ae_eq_range_subset ht h₀, refine ⟨g, _, fg⟩, exact strongly_measurable_iff_measurable_separable.2 ⟨g_meas, t_sep.mono gt⟩ } end lemma _root_.measurable_embedding.ae_strongly_measurable_map_iff {γ : Type*} {mγ : measurable_space γ} {mα : measurable_space α} {f : γ → α} {μ : measure γ} (hf : measurable_embedding f) {g : α → β} : ae_strongly_measurable g (measure.map f μ) ↔ ae_strongly_measurable (g ∘ f) μ := begin refine ⟨λ H, H.comp_measurable hf.measurable, _⟩, rintro ⟨g₁, hgm₁, heq⟩, rcases hf.exists_strongly_measurable_extend hgm₁ (λ x, ⟨g x⟩) with ⟨g₂, hgm₂, rfl⟩, exact ⟨g₂, hgm₂, hf.ae_map_iff.2 heq⟩ end lemma _root_.embedding.ae_strongly_measurable_comp_iff [pseudo_metrizable_space β] [pseudo_metrizable_space γ] {g : β → γ} {f : α → β} (hg : embedding g) : ae_strongly_measurable (λ x, g (f x)) μ ↔ ae_strongly_measurable f μ := begin letI := pseudo_metrizable_space_pseudo_metric γ, borelize [β, γ], refine ⟨λ H, ae_strongly_measurable_iff_ae_measurable_separable.2 ⟨_, _⟩, λ H, hg.continuous.comp_ae_strongly_measurable H⟩, { let G : β → range g := cod_restrict g (range g) mem_range_self, have hG : closed_embedding G := { closed_range := begin convert is_closed_univ, apply eq_univ_of_forall, rintros ⟨-, ⟨x, rfl⟩⟩, exact mem_range_self x end, .. hg.cod_restrict _ _ }, have : ae_measurable (G ∘ f) μ := ae_measurable.subtype_mk H.ae_measurable, exact hG.measurable_embedding.ae_measurable_comp_iff.1 this }, { rcases (ae_strongly_measurable_iff_ae_measurable_separable.1 H).2 with ⟨t, ht, h't⟩, exact ⟨g⁻¹' t, hg.is_separable_preimage ht, h't⟩ } end lemma _root_.measure_theory.measure_preserving.ae_strongly_measurable_comp_iff {β : Type*} {f : α → β} {mα : measurable_space α} {μa : measure α} {mβ : measurable_space β} {μb : measure β} (hf : measure_preserving f μa μb) (h₂ : measurable_embedding f) {g : β → γ} : ae_strongly_measurable (g ∘ f) μa ↔ ae_strongly_measurable g μb := by rw [← hf.map_eq, h₂.ae_strongly_measurable_map_iff] /-- An almost everywhere sequential limit of almost everywhere strongly measurable functions is almost everywhere strongly measurable. -/ lemma _root_.ae_strongly_measurable_of_tendsto_ae {ι : Type*} [pseudo_metrizable_space β] (u : filter ι) [ne_bot u] [is_countably_generated u] {f : ι → α → β} {g : α → β} (hf : ∀ i, ae_strongly_measurable (f i) μ) (lim : ∀ᵐ x ∂μ, tendsto (λ n, f n x) u (𝓝 (g x))) : ae_strongly_measurable g μ := begin borelize β, refine ae_strongly_measurable_iff_ae_measurable_separable.2 ⟨_, _⟩, { exact ae_measurable_of_tendsto_metrizable_ae _ (λ n, (hf n).ae_measurable) lim }, { rcases u.exists_seq_tendsto with ⟨v, hv⟩, have : ∀ (n : ℕ), ∃ (t : set β), is_separable t ∧ f (v n) ⁻¹' t ∈ μ.ae := λ n, (ae_strongly_measurable_iff_ae_measurable_separable.1 (hf (v n))).2, choose t t_sep ht using this, refine ⟨closure (⋃ i, (t i)), (is_separable_Union (λ i, (t_sep i))).closure, _⟩, filter_upwards [ae_all_iff.2 ht, lim] with x hx h'x, apply mem_closure_of_tendsto ((h'x).comp hv), apply eventually_of_forall (λ n, _), apply mem_Union_of_mem n, exact hx n } end /-- If a sequence of almost everywhere strongly measurable functions converges almost everywhere, one can select a strongly measurable function as the almost everywhere limit. -/ lemma _root_.exists_strongly_measurable_limit_of_tendsto_ae [pseudo_metrizable_space β] {f : ℕ → α → β} (hf : ∀ n, ae_strongly_measurable (f n) μ) (h_ae_tendsto : ∀ᵐ x ∂μ, ∃ l : β, tendsto (λ n, f n x) at_top (𝓝 l)) : ∃ (f_lim : α → β) (hf_lim_meas : strongly_measurable f_lim), ∀ᵐ x ∂μ, tendsto (λ n, f n x) at_top (𝓝 (f_lim x)) := begin borelize β, obtain ⟨g, g_meas, hg⟩ : ∃ (g : α → β) (g_meas : measurable g), ∀ᵐ x ∂μ, tendsto (λ n, f n x) at_top (𝓝 (g x)) := measurable_limit_of_tendsto_metrizable_ae (λ n, (hf n).ae_measurable) h_ae_tendsto, have Hg : ae_strongly_measurable g μ := ae_strongly_measurable_of_tendsto_ae _ hf hg, refine ⟨Hg.mk g, Hg.strongly_measurable_mk, _⟩, filter_upwards [hg, Hg.ae_eq_mk] with x hx h'x, rwa h'x at hx, end lemma sum_measure [pseudo_metrizable_space β] {m : measurable_space α} {μ : ι → measure α} (h : ∀ i, ae_strongly_measurable f (μ i)) : ae_strongly_measurable f (measure.sum μ) := begin borelize β, refine ae_strongly_measurable_iff_ae_measurable_separable.2 ⟨ae_measurable.sum_measure (λ i, (h i).ae_measurable), _⟩, have A : ∀ (i : ι), ∃ (t : set β), is_separable t ∧ f ⁻¹' t ∈ (μ i).ae := λ i, (ae_strongly_measurable_iff_ae_measurable_separable.1 (h i)).2, choose t t_sep ht using A, refine ⟨(⋃ i, t i), is_separable_Union t_sep, _⟩, simp only [measure.ae_sum_eq, mem_Union, eventually_supr], assume i, filter_upwards [ht i] with x hx, exact ⟨i, hx⟩ end @[simp] lemma _root_.ae_strongly_measurable_sum_measure_iff [pseudo_metrizable_space β] {m : measurable_space α} {μ : ι → measure α} : ae_strongly_measurable f (sum μ) ↔ ∀ i, ae_strongly_measurable f (μ i) := ⟨λ h i, h.mono_measure (measure.le_sum _ _), sum_measure⟩ @[simp] lemma _root_.ae_strongly_measurable_add_measure_iff [pseudo_metrizable_space β] {ν : measure α} : ae_strongly_measurable f (μ + ν) ↔ ae_strongly_measurable f μ ∧ ae_strongly_measurable f ν := by { rw [← sum_cond, ae_strongly_measurable_sum_measure_iff, bool.forall_bool, and.comm], refl } lemma add_measure [pseudo_metrizable_space β] {ν : measure α} {f : α → β} (hμ : ae_strongly_measurable f μ) (hν : ae_strongly_measurable f ν) : ae_strongly_measurable f (μ + ν) := ae_strongly_measurable_add_measure_iff.2 ⟨hμ, hν⟩ protected lemma Union [pseudo_metrizable_space β] {s : ι → set α} (h : ∀ i, ae_strongly_measurable f (μ.restrict (s i))) : ae_strongly_measurable f (μ.restrict (⋃ i, s i)) := (sum_measure h).mono_measure $ restrict_Union_le @[simp] lemma _root_.ae_strongly_measurable_Union_iff [pseudo_metrizable_space β] {s : ι → set α} : ae_strongly_measurable f (μ.restrict (⋃ i, s i)) ↔ ∀ i, ae_strongly_measurable f (μ.restrict (s i)) := ⟨λ h i, h.mono_measure $ restrict_mono (subset_Union _ _) le_rfl, ae_strongly_measurable.Union⟩ @[simp] lemma _root_.ae_strongly_measurable_union_iff [pseudo_metrizable_space β] {s t : set α} : ae_strongly_measurable f (μ.restrict (s ∪ t)) ↔ ae_strongly_measurable f (μ.restrict s) ∧ ae_strongly_measurable f (μ.restrict t) := by simp only [union_eq_Union, ae_strongly_measurable_Union_iff, bool.forall_bool, cond, and.comm] lemma smul_measure {R : Type*} [monoid R] [distrib_mul_action R ℝ≥0∞] [is_scalar_tower R ℝ≥0∞ ℝ≥0∞] (h : ae_strongly_measurable f μ) (c : R) : ae_strongly_measurable f (c • μ) := ⟨h.mk f, h.strongly_measurable_mk, ae_smul_measure h.ae_eq_mk c⟩ section normed_space variables {𝕜 : Type*} [nontrivially_normed_field 𝕜] [complete_space 𝕜] variables {E : Type*} [normed_add_comm_group E] [normed_space 𝕜 E] lemma _root_.ae_strongly_measurable_smul_const_iff {f : α → 𝕜} {c : E} (hc : c ≠ 0) : ae_strongly_measurable (λ x, f x • c) μ ↔ ae_strongly_measurable f μ := (closed_embedding_smul_left hc).to_embedding.ae_strongly_measurable_comp_iff end normed_space section mul_action variables {G : Type*} [group G] [mul_action G β] [has_continuous_const_smul G β] lemma _root_.ae_strongly_measurable_const_smul_iff (c : G) : ae_strongly_measurable (λ x, c • f x) μ ↔ ae_strongly_measurable f μ := ⟨λ h, by simpa only [inv_smul_smul] using h.const_smul' c⁻¹, λ h, h.const_smul c⟩ variables {G₀ : Type*} [group_with_zero G₀] [mul_action G₀ β] [has_continuous_const_smul G₀ β] lemma _root_.ae_strongly_measurable_const_smul_iff₀ {c : G₀} (hc : c ≠ 0) : ae_strongly_measurable (λ x, c • f x) μ ↔ ae_strongly_measurable f μ := begin refine ⟨λ h, _, λ h, h.const_smul c⟩, convert h.const_smul' c⁻¹, simp [smul_smul, inv_mul_cancel hc] end end mul_action section continuous_linear_map_nontrivially_normed_field variables {𝕜 : Type*} [nontrivially_normed_field 𝕜] variables {E : Type*} [normed_add_comm_group E] [normed_space 𝕜 E] variables {F : Type*} [normed_add_comm_group F] [normed_space 𝕜 F] variables {G : Type*} [normed_add_comm_group G] [normed_space 𝕜 G] lemma _root_.strongly_measurable.apply_continuous_linear_map {m : measurable_space α} {φ : α → F →L[𝕜] E} (hφ : strongly_measurable φ) (v : F) : strongly_measurable (λ a, φ a v) := (continuous_linear_map.apply 𝕜 E v).continuous.comp_strongly_measurable hφ lemma apply_continuous_linear_map {φ : α → F →L[𝕜] E} (hφ : ae_strongly_measurable φ μ) (v : F) : ae_strongly_measurable (λ a, φ a v) μ := (continuous_linear_map.apply 𝕜 E v).continuous.comp_ae_strongly_measurable hφ lemma _root_.continuous_linear_map.ae_strongly_measurable_comp₂ (L : E →L[𝕜] F →L[𝕜] G) {f : α → E} {g : α → F} (hf : ae_strongly_measurable f μ) (hg : ae_strongly_measurable g μ) : ae_strongly_measurable (λ x, L (f x) (g x)) μ := L.continuous₂.comp_ae_strongly_measurable $ hf.prod_mk hg end continuous_linear_map_nontrivially_normed_field lemma _root_.ae_strongly_measurable_with_density_iff {E : Type*} [normed_add_comm_group E] [normed_space ℝ E] {f : α → ℝ≥0} (hf : measurable f) {g : α → E} : ae_strongly_measurable g (μ.with_density (λ x, (f x : ℝ≥0∞))) ↔ ae_strongly_measurable (λ x, (f x : ℝ) • g x) μ := begin split, { rintros ⟨g', g'meas, hg'⟩, have A : measurable_set {x : α | f x ≠ 0} := (hf (measurable_set_singleton 0)).compl, refine ⟨λ x, (f x : ℝ) • g' x, hf.coe_nnreal_real.strongly_measurable.smul g'meas, _⟩, apply @ae_of_ae_restrict_of_ae_restrict_compl _ _ _ {x | f x ≠ 0}, { rw [eventually_eq, ae_with_density_iff hf.coe_nnreal_ennreal] at hg', rw ae_restrict_iff' A, filter_upwards [hg'] with a ha h'a, have : (f a : ℝ≥0∞) ≠ 0, by simpa only [ne.def, ennreal.coe_eq_zero] using h'a, rw ha this }, { filter_upwards [ae_restrict_mem A.compl] with x hx, simp only [not_not, mem_set_of_eq, mem_compl_eq] at hx, simp [hx] } }, { rintros ⟨g', g'meas, hg'⟩, refine ⟨λ x, (f x : ℝ)⁻¹ • g' x, hf.coe_nnreal_real.inv.strongly_measurable.smul g'meas, _⟩, rw [eventually_eq, ae_with_density_iff hf.coe_nnreal_ennreal], filter_upwards [hg'] with x hx h'x, rw [← hx, smul_smul, _root_.inv_mul_cancel, one_smul], simp only [ne.def, ennreal.coe_eq_zero] at h'x, simpa only [nnreal.coe_eq_zero, ne.def] using h'x } end end ae_strongly_measurable /-! ## Almost everywhere finitely strongly measurable functions -/ namespace ae_fin_strongly_measurable variables {m : measurable_space α} {μ : measure α} [topological_space β] {f g : α → β} section mk variables [has_zero β] /-- A `fin_strongly_measurable` function such that `f =ᵐ[μ] hf.mk f`. See lemmas `fin_strongly_measurable_mk` and `ae_eq_mk`. -/ protected noncomputable def mk (f : α → β) (hf : ae_fin_strongly_measurable f μ) : α → β := hf.some lemma fin_strongly_measurable_mk (hf : ae_fin_strongly_measurable f μ) : fin_strongly_measurable (hf.mk f) μ := hf.some_spec.1 lemma ae_eq_mk (hf : ae_fin_strongly_measurable f μ) : f =ᵐ[μ] hf.mk f := hf.some_spec.2 protected lemma ae_measurable {β} [has_zero β] [measurable_space β] [topological_space β] [pseudo_metrizable_space β] [borel_space β] {f : α → β} (hf : ae_fin_strongly_measurable f μ) : ae_measurable f μ := ⟨hf.mk f, hf.fin_strongly_measurable_mk.measurable, hf.ae_eq_mk⟩ end mk section arithmetic protected lemma mul [monoid_with_zero β] [has_continuous_mul β] (hf : ae_fin_strongly_measurable f μ) (hg : ae_fin_strongly_measurable g μ) : ae_fin_strongly_measurable (f * g) μ := ⟨hf.mk f * hg.mk g, hf.fin_strongly_measurable_mk.mul hg.fin_strongly_measurable_mk, hf.ae_eq_mk.mul hg.ae_eq_mk⟩ protected lemma add [add_monoid β] [has_continuous_add β] (hf : ae_fin_strongly_measurable f μ) (hg : ae_fin_strongly_measurable g μ) : ae_fin_strongly_measurable (f + g) μ := ⟨hf.mk f + hg.mk g, hf.fin_strongly_measurable_mk.add hg.fin_strongly_measurable_mk, hf.ae_eq_mk.add hg.ae_eq_mk⟩ protected lemma neg [add_group β] [topological_add_group β] (hf : ae_fin_strongly_measurable f μ) : ae_fin_strongly_measurable (-f) μ := ⟨-hf.mk f, hf.fin_strongly_measurable_mk.neg, hf.ae_eq_mk.neg⟩ protected lemma sub [add_group β] [has_continuous_sub β] (hf : ae_fin_strongly_measurable f μ) (hg : ae_fin_strongly_measurable g μ) : ae_fin_strongly_measurable (f - g) μ := ⟨hf.mk f - hg.mk g, hf.fin_strongly_measurable_mk.sub hg.fin_strongly_measurable_mk, hf.ae_eq_mk.sub hg.ae_eq_mk⟩ protected lemma const_smul {𝕜} [topological_space 𝕜] [add_monoid β] [monoid 𝕜] [distrib_mul_action 𝕜 β] [has_continuous_smul 𝕜 β] (hf : ae_fin_strongly_measurable f μ) (c : 𝕜) : ae_fin_strongly_measurable (c • f) μ := ⟨c • hf.mk f, hf.fin_strongly_measurable_mk.const_smul c, hf.ae_eq_mk.const_smul c⟩ end arithmetic section order variables [has_zero β] protected lemma sup [semilattice_sup β] [has_continuous_sup β] (hf : ae_fin_strongly_measurable f μ) (hg : ae_fin_strongly_measurable g μ) : ae_fin_strongly_measurable (f ⊔ g) μ := ⟨hf.mk f ⊔ hg.mk g, hf.fin_strongly_measurable_mk.sup hg.fin_strongly_measurable_mk, hf.ae_eq_mk.sup hg.ae_eq_mk⟩ protected lemma inf [semilattice_inf β] [has_continuous_inf β] (hf : ae_fin_strongly_measurable f μ) (hg : ae_fin_strongly_measurable g μ) : ae_fin_strongly_measurable (f ⊓ g) μ := ⟨hf.mk f ⊓ hg.mk g, hf.fin_strongly_measurable_mk.inf hg.fin_strongly_measurable_mk, hf.ae_eq_mk.inf hg.ae_eq_mk⟩ end order variables [has_zero β] [t2_space β] lemma exists_set_sigma_finite (hf : ae_fin_strongly_measurable f μ) : ∃ t, measurable_set t ∧ f =ᵐ[μ.restrict tᶜ] 0 ∧ sigma_finite (μ.restrict t) := begin rcases hf with ⟨g, hg, hfg⟩, obtain ⟨t, ht, hgt_zero, htμ⟩ := hg.exists_set_sigma_finite, refine ⟨t, ht, _, htμ⟩, refine eventually_eq.trans (ae_restrict_of_ae hfg) _, rw [eventually_eq, ae_restrict_iff' ht.compl], exact eventually_of_forall hgt_zero, end /-- A measurable set `t` such that `f =ᵐ[μ.restrict tᶜ] 0` and `sigma_finite (μ.restrict t)`. -/ def sigma_finite_set (hf : ae_fin_strongly_measurable f μ) : set α := hf.exists_set_sigma_finite.some protected lemma measurable_set (hf : ae_fin_strongly_measurable f μ) : measurable_set hf.sigma_finite_set := hf.exists_set_sigma_finite.some_spec.1 lemma ae_eq_zero_compl (hf : ae_fin_strongly_measurable f μ) : f =ᵐ[μ.restrict hf.sigma_finite_setᶜ] 0 := hf.exists_set_sigma_finite.some_spec.2.1 instance sigma_finite_restrict (hf : ae_fin_strongly_measurable f μ) : sigma_finite (μ.restrict hf.sigma_finite_set) := hf.exists_set_sigma_finite.some_spec.2.2 end ae_fin_strongly_measurable section second_countable_topology variables {G : Type*} {p : ℝ≥0∞} {m m0 : measurable_space α} {μ : measure α} [seminormed_add_comm_group G] [measurable_space G] [borel_space G] [second_countable_topology G] {f : α → G} /-- In a space with second countable topology and a sigma-finite measure, `fin_strongly_measurable` and `measurable` are equivalent. -/ lemma fin_strongly_measurable_iff_measurable {m0 : measurable_space α} (μ : measure α) [sigma_finite μ] : fin_strongly_measurable f μ ↔ measurable f := ⟨λ h, h.measurable, λ h, (measurable.strongly_measurable h).fin_strongly_measurable μ⟩ /-- In a space with second countable topology and a sigma-finite measure, `ae_fin_strongly_measurable` and `ae_measurable` are equivalent. -/ lemma ae_fin_strongly_measurable_iff_ae_measurable {m0 : measurable_space α} (μ : measure α) [sigma_finite μ] : ae_fin_strongly_measurable f μ ↔ ae_measurable f μ := by simp_rw [ae_fin_strongly_measurable, ae_measurable, fin_strongly_measurable_iff_measurable] end second_countable_topology lemma measurable_uncurry_of_continuous_of_measurable {α β ι : Type*} [topological_space ι] [metrizable_space ι] [measurable_space ι] [second_countable_topology ι] [opens_measurable_space ι] {mβ : measurable_space β} [topological_space β] [pseudo_metrizable_space β] [borel_space β] {m : measurable_space α} {u : ι → α → β} (hu_cont : ∀ x, continuous (λ i, u i x)) (h : ∀ i, measurable (u i)) : measurable (function.uncurry u) := begin obtain ⟨t_sf, ht_sf⟩ : ∃ t : ℕ → simple_func ι ι, ∀ j x, tendsto (λ n, u (t n j) x) at_top (𝓝 $ u j x), { have h_str_meas : strongly_measurable (id : ι → ι), from strongly_measurable_id, refine ⟨h_str_meas.approx, λ j x, _⟩, exact ((hu_cont x).tendsto j).comp (h_str_meas.tendsto_approx j), }, let U := λ (n : ℕ) (p : ι × α), u (t_sf n p.fst) p.snd, have h_tendsto : tendsto U at_top (𝓝 (λ p, u p.fst p.snd)), { rw tendsto_pi_nhds, exact λ p, ht_sf p.fst p.snd, }, refine measurable_of_tendsto_metrizable (λ n, _) h_tendsto, haveI : encodable (t_sf n).range, from fintype.to_encodable ↥(t_sf n).range, have h_meas : measurable (λ (p : (t_sf n).range × α), u ↑p.fst p.snd), { have : (λ (p : ↥((t_sf n).range) × α), u ↑(p.fst) p.snd) = (λ (p : α × ((t_sf n).range)), u ↑(p.snd) p.fst) ∘ prod.swap := rfl, rw [this, @measurable_swap_iff α ↥((t_sf n).range) β m], exact measurable_from_prod_encodable (λ j, h j), }, have : (λ p : ι × α, u (t_sf n p.fst) p.snd) = (λ p : ↥(t_sf n).range × α, u p.fst p.snd) ∘ (λ p : ι × α, (⟨t_sf n p.fst, simple_func.mem_range_self _ _⟩, p.snd)) := rfl, simp_rw [U, this], refine h_meas.comp (measurable.prod_mk _ measurable_snd), exact ((t_sf n).measurable.comp measurable_fst).subtype_mk, end lemma strongly_measurable_uncurry_of_continuous_of_strongly_measurable {α β ι : Type*} [topological_space ι] [metrizable_space ι] [measurable_space ι] [second_countable_topology ι] [opens_measurable_space ι] [topological_space β] [pseudo_metrizable_space β] [measurable_space α] {u : ι → α → β} (hu_cont : ∀ x, continuous (λ i, u i x)) (h : ∀ i, strongly_measurable (u i)) : strongly_measurable (function.uncurry u) := begin borelize β, obtain ⟨t_sf, ht_sf⟩ : ∃ t : ℕ → simple_func ι ι, ∀ j x, tendsto (λ n, u (t n j) x) at_top (𝓝 $ u j x), { have h_str_meas : strongly_measurable (id : ι → ι), from strongly_measurable_id, refine ⟨h_str_meas.approx, λ j x, _⟩, exact ((hu_cont x).tendsto j).comp (h_str_meas.tendsto_approx j), }, let U := λ (n : ℕ) (p : ι × α), u (t_sf n p.fst) p.snd, have h_tendsto : tendsto U at_top (𝓝 (λ p, u p.fst p.snd)), { rw tendsto_pi_nhds, exact λ p, ht_sf p.fst p.snd, }, refine strongly_measurable_of_tendsto _ (λ n, _) h_tendsto, haveI : encodable (t_sf n).range, from fintype.to_encodable ↥(t_sf n).range, have h_str_meas : strongly_measurable (λ (p : (t_sf n).range × α), u ↑p.fst p.snd), { refine strongly_measurable_iff_measurable_separable.2 ⟨_, _⟩, { have : (λ (p : ↥((t_sf n).range) × α), u ↑(p.fst) p.snd) = (λ (p : α × ((t_sf n).range)), u ↑(p.snd) p.fst) ∘ prod.swap := rfl, rw [this, measurable_swap_iff], exact measurable_from_prod_encodable (λ j, (h j).measurable), }, { have : is_separable (⋃ (i : (t_sf n).range), range (u i)) := is_separable_Union (λ i, (h i).is_separable_range), apply this.mono, rintros _ ⟨⟨i, x⟩, rfl⟩, simp only [mem_Union, mem_range], exact ⟨i, x, rfl⟩ } }, have : (λ p : ι × α, u (t_sf n p.fst) p.snd) = (λ p : ↥(t_sf n).range × α, u p.fst p.snd) ∘ (λ p : ι × α, (⟨t_sf n p.fst, simple_func.mem_range_self _ _⟩, p.snd)) := rfl, simp_rw [U, this], refine h_str_meas.comp_measurable (measurable.prod_mk _ measurable_snd), exact ((t_sf n).measurable.comp measurable_fst).subtype_mk, end end measure_theory
8da8abf51f85536fae23ee77488b3fa1824f820f
c777c32c8e484e195053731103c5e52af26a25d1
/src/topology/separation.lean
95001a4d61cde0127258168a11b9315eb8a937d9
[ "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
92,577
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Mario Carneiro -/ import topology.subset_properties import topology.connected import topology.nhds_set import topology.inseparable /-! # Separation properties of topological spaces. > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file defines the predicate `separated_nhds`, and common separation axioms (under the Kolmogorov classification). ## Main definitions * `separated_nhds`: Two `set`s are separated by neighbourhoods if they are contained in disjoint open sets. * `t0_space`: A T₀/Kolmogorov space is a space where, for every two points `x ≠ y`, there is an open set that contains one, but not the other. * `t1_space`: A T₁/Fréchet space is a space where every singleton set is closed. This is equivalent to, for every pair `x ≠ y`, there existing an open set containing `x` but not `y` (`t1_space_iff_exists_open` shows that these conditions are equivalent.) * `t2_space`: A T₂/Hausdorff space is a space where, for every two points `x ≠ y`, there is two disjoint open sets, one containing `x`, and the other `y`. * `t2_5_space`: A T₂.₅/Urysohn space is a space where, for every two points `x ≠ y`, there is two open sets, one containing `x`, and the other `y`, whose closures are disjoint. * `t3_space`: A T₃ space, is one where given any closed `C` and `x ∉ C`, there is disjoint open sets containing `x` and `C` respectively. In `mathlib`, T₃ implies T₂.₅. * `normal_space`: A T₄ space (sometimes referred to as normal, but authors vary on whether this includes T₂; `mathlib` does), is one where given two disjoint closed sets, we can find two open sets that separate them. In `mathlib`, T₄ implies T₃. * `t5_space`: A T₅ space, also known as a *completely normal Hausdorff space* ## Main results ### T₀ spaces * `is_closed.exists_closed_singleton` Given a closed set `S` in a compact T₀ space, there is some `x ∈ S` such that `{x}` is closed. * `exists_open_singleton_of_open_finset` Given an open `finset` `S` in a T₀ space, there is some `x ∈ S` such that `{x}` is open. ### T₁ spaces * `is_closed_map_const`: The constant map is a closed map. * `discrete_of_t1_of_finite`: A finite T₁ space must have the discrete topology. ### T₂ spaces * `t2_iff_nhds`: A space is T₂ iff the neighbourhoods of distinct points generate the bottom filter. * `t2_iff_is_closed_diagonal`: A space is T₂ iff the `diagonal` of `α` (that is, the set of all points of the form `(a, a) : α × α`) is closed under the product topology. * `finset_disjoint_finset_opens_of_t2`: Any two disjoint finsets are `separated_nhds`. * Most topological constructions preserve Hausdorffness; these results are part of the typeclass inference system (e.g. `embedding.t2_space`) * `set.eq_on.closure`: If two functions are equal on some set `s`, they are equal on its closure. * `is_compact.is_closed`: All compact sets are closed. * `locally_compact_of_compact_nhds`: If every point has a compact neighbourhood, then the space is locally compact. * `totally_separated_space_of_t1_of_basis_clopen`: If `α` has a clopen basis, then it is a `totally_separated_space`. * `loc_compact_t2_tot_disc_iff_tot_sep`: A locally compact T₂ space is totally disconnected iff it is totally separated. If the space is also compact: * `normal_of_compact_t2`: A compact T₂ space is a `normal_space`. * `connected_components_eq_Inter_clopen`: The connected component of a point is the intersection of all its clopen neighbourhoods. * `compact_t2_tot_disc_iff_tot_sep`: Being a `totally_disconnected_space` is equivalent to being a `totally_separated_space`. * `connected_components.t2`: `connected_components α` is T₂ for `α` T₂ and compact. ### T₃ spaces * `disjoint_nested_nhds`: Given two points `x ≠ y`, we can find neighbourhoods `x ∈ V₁ ⊆ U₁` and `y ∈ V₂ ⊆ U₂`, with the `Vₖ` closed and the `Uₖ` open, such that the `Uₖ` are disjoint. ## References https://en.wikipedia.org/wiki/Separation_axiom -/ open function set filter topological_space open_locale topology filter classical universes u v variables {α : Type u} {β : Type v} [topological_space α] section separation /-- `separated_nhds` is a predicate on pairs of sub`set`s of a topological space. It holds if the two sub`set`s are contained in disjoint open sets. -/ def separated_nhds : set α → set α → Prop := λ (s t : set α), ∃ U V : (set α), (is_open U) ∧ is_open V ∧ (s ⊆ U) ∧ (t ⊆ V) ∧ disjoint U V lemma separated_nhds_iff_disjoint {s t : set α} : separated_nhds s t ↔ disjoint (𝓝ˢ s) (𝓝ˢ t) := by simp only [(has_basis_nhds_set s).disjoint_iff (has_basis_nhds_set t), separated_nhds, exists_prop, ← exists_and_distrib_left, and.assoc, and.comm, and.left_comm] namespace separated_nhds variables {s s₁ s₂ t t₁ t₂ u : set α} @[symm] lemma symm : separated_nhds s t → separated_nhds t s := λ ⟨U, V, oU, oV, aU, bV, UV⟩, ⟨V, U, oV, oU, bV, aU, disjoint.symm UV⟩ lemma comm (s t : set α) : separated_nhds s t ↔ separated_nhds t s := ⟨symm, symm⟩ lemma preimage [topological_space β] {f : α → β} {s t : set β} (h : separated_nhds s t) (hf : continuous f) : separated_nhds (f ⁻¹' s) (f ⁻¹' t) := let ⟨U, V, oU, oV, sU, tV, UV⟩ := h in ⟨f ⁻¹' U, f ⁻¹' V, oU.preimage hf, oV.preimage hf, preimage_mono sU, preimage_mono tV, UV.preimage f⟩ protected lemma disjoint (h : separated_nhds s t) : disjoint s t := let ⟨U, V, hU, hV, hsU, htV, hd⟩ := h in hd.mono hsU htV lemma disjoint_closure_left (h : separated_nhds s t) : disjoint (closure s) t := let ⟨U, V, hU, hV, hsU, htV, hd⟩ := h in (hd.closure_left hV).mono (closure_mono hsU) htV lemma disjoint_closure_right (h : separated_nhds s t) : disjoint s (closure t) := h.symm.disjoint_closure_left.symm lemma empty_right (s : set α) : separated_nhds s ∅ := ⟨_, _, is_open_univ, is_open_empty, λ a h, mem_univ a, λ a h, by cases h, disjoint_empty _⟩ lemma empty_left (s : set α) : separated_nhds ∅ s := (empty_right _).symm lemma mono (h : separated_nhds s₂ t₂) (hs : s₁ ⊆ s₂) (ht : t₁ ⊆ t₂) : separated_nhds s₁ t₁ := let ⟨U, V, hU, hV, hsU, htV, hd⟩ := h in ⟨U, V, hU, hV, hs.trans hsU, ht.trans htV, hd⟩ lemma union_left : separated_nhds s u → separated_nhds t u → separated_nhds (s ∪ t) u := by simpa only [separated_nhds_iff_disjoint, nhds_set_union, disjoint_sup_left] using and.intro lemma union_right (ht : separated_nhds s t) (hu : separated_nhds s u) : separated_nhds s (t ∪ u) := (ht.symm.union_left hu.symm).symm end separated_nhds /-- A T₀ space, also known as a Kolmogorov space, is a topological space such that for every pair `x ≠ y`, there is an open set containing one but not the other. We formulate the definition in terms of the `inseparable` relation. -/ class t0_space (α : Type u) [topological_space α] : Prop := (t0 : ∀ ⦃x y : α⦄, inseparable x y → x = y) lemma t0_space_iff_inseparable (α : Type u) [topological_space α] : t0_space α ↔ ∀ (x y : α), inseparable x y → x = y := ⟨λ ⟨h⟩, h, λ h, ⟨h⟩⟩ lemma t0_space_iff_not_inseparable (α : Type u) [topological_space α] : t0_space α ↔ ∀ (x y : α), x ≠ y → ¬inseparable x y := by simp only [t0_space_iff_inseparable, ne.def, not_imp_not] lemma inseparable.eq [t0_space α] {x y : α} (h : inseparable x y) : x = y := t0_space.t0 h protected lemma inducing.injective [topological_space β] [t0_space α] {f : α → β} (hf : inducing f) : injective f := λ x y h, inseparable.eq $ hf.inseparable_iff.1 $ h ▸ inseparable.refl _ protected lemma inducing.embedding [topological_space β] [t0_space α] {f : α → β} (hf : inducing f) : embedding f := ⟨hf, hf.injective⟩ lemma embedding_iff_inducing [topological_space β] [t0_space α] {f : α → β} : embedding f ↔ inducing f := ⟨embedding.to_inducing, inducing.embedding⟩ lemma t0_space_iff_nhds_injective (α : Type u) [topological_space α] : t0_space α ↔ injective (𝓝 : α → filter α) := t0_space_iff_inseparable α lemma nhds_injective [t0_space α] : injective (𝓝 : α → filter α) := (t0_space_iff_nhds_injective α).1 ‹_› lemma inseparable_iff_eq [t0_space α] {x y : α} : inseparable x y ↔ x = y := nhds_injective.eq_iff @[simp] lemma nhds_eq_nhds_iff [t0_space α] {a b : α} : 𝓝 a = 𝓝 b ↔ a = b := nhds_injective.eq_iff @[simp] lemma inseparable_eq_eq [t0_space α] : inseparable = @eq α := funext₂ $ λ x y, propext inseparable_iff_eq lemma t0_space_iff_exists_is_open_xor_mem (α : Type u) [topological_space α] : t0_space α ↔ ∀ x y, x ≠ y → ∃ U:set α, is_open U ∧ (xor (x ∈ U) (y ∈ U)) := by simp only [t0_space_iff_not_inseparable, xor_iff_not_iff, not_forall, exists_prop, inseparable_iff_forall_open] lemma exists_is_open_xor_mem [t0_space α] {x y : α} (h : x ≠ y) : ∃ U : set α, is_open U ∧ xor (x ∈ U) (y ∈ U) := (t0_space_iff_exists_is_open_xor_mem α).1 ‹_› x y h /-- Specialization forms a partial order on a t0 topological space. -/ def specialization_order (α : Type*) [topological_space α] [t0_space α] : partial_order α := { .. specialization_preorder α, .. partial_order.lift (order_dual.to_dual ∘ 𝓝) nhds_injective } instance : t0_space (separation_quotient α) := ⟨λ x' y', quotient.induction_on₂' x' y' $ λ x y h, separation_quotient.mk_eq_mk.2 $ separation_quotient.inducing_mk.inseparable_iff.1 h⟩ theorem minimal_nonempty_closed_subsingleton [t0_space α] {s : set α} (hs : is_closed s) (hmin : ∀ t ⊆ s, t.nonempty → is_closed t → t = s) : s.subsingleton := begin refine λ x hx y hy, of_not_not (λ hxy, _), rcases exists_is_open_xor_mem hxy with ⟨U, hUo, hU⟩, wlog h : x ∈ U ∧ y ∉ U, { exact this hmin y hy x hx (ne.symm hxy) U hUo hU.symm (hU.resolve_left h), }, cases h with hxU hyU, have : s \ U = s := hmin (s \ U) (diff_subset _ _) ⟨y, hy, hyU⟩ (hs.sdiff hUo), exact (this.symm.subset hx).2 hxU end theorem minimal_nonempty_closed_eq_singleton [t0_space α] {s : set α} (hs : is_closed s) (hne : s.nonempty) (hmin : ∀ t ⊆ s, t.nonempty → is_closed t → t = s) : ∃ x, s = {x} := exists_eq_singleton_iff_nonempty_subsingleton.2 ⟨hne, minimal_nonempty_closed_subsingleton hs hmin⟩ /-- Given a closed set `S` in a compact T₀ space, there is some `x ∈ S` such that `{x}` is closed. -/ theorem is_closed.exists_closed_singleton {α : Type*} [topological_space α] [t0_space α] [compact_space α] {S : set α} (hS : is_closed S) (hne : S.nonempty) : ∃ (x : α), x ∈ S ∧ is_closed ({x} : set α) := begin obtain ⟨V, Vsub, Vne, Vcls, hV⟩ := hS.exists_minimal_nonempty_closed_subset hne, rcases minimal_nonempty_closed_eq_singleton Vcls Vne hV with ⟨x, rfl⟩, exact ⟨x, Vsub (mem_singleton x), Vcls⟩ end theorem minimal_nonempty_open_subsingleton [t0_space α] {s : set α} (hs : is_open s) (hmin : ∀ t ⊆ s, t.nonempty → is_open t → t = s) : s.subsingleton := begin refine λ x hx y hy, of_not_not (λ hxy, _), rcases exists_is_open_xor_mem hxy with ⟨U, hUo, hU⟩, wlog h : x ∈ U ∧ y ∉ U, { exact this hs hmin y hy x hx (ne.symm hxy) U hUo hU.symm (hU.resolve_left h), }, cases h with hxU hyU, have : s ∩ U = s := hmin (s ∩ U) (inter_subset_left _ _) ⟨x, hx, hxU⟩ (hs.inter hUo), exact hyU (this.symm.subset hy).2 end theorem minimal_nonempty_open_eq_singleton [t0_space α] {s : set α} (hs : is_open s) (hne : s.nonempty) (hmin : ∀ t ⊆ s, t.nonempty → is_open t → t = s) : ∃ x, s = {x} := exists_eq_singleton_iff_nonempty_subsingleton.2 ⟨hne, minimal_nonempty_open_subsingleton hs hmin⟩ /-- Given an open finite set `S` in a T₀ space, there is some `x ∈ S` such that `{x}` is open. -/ theorem exists_open_singleton_of_open_finite [t0_space α] {s : set α} (hfin : s.finite) (hne : s.nonempty) (ho : is_open s) : ∃ x ∈ s, is_open ({x} : set α) := begin lift s to finset α using hfin, induction s using finset.strong_induction_on with s ihs, rcases em (∃ t ⊂ s, t.nonempty ∧ is_open (t : set α)) with ⟨t, hts, htne, hto⟩|ht, { rcases ihs t hts htne hto with ⟨x, hxt, hxo⟩, exact ⟨x, hts.1 hxt, hxo⟩ }, { rcases minimal_nonempty_open_eq_singleton ho hne _ with ⟨x, hx⟩, { exact ⟨x, hx.symm ▸ rfl, hx ▸ ho⟩ }, refine λ t hts htne hto, of_not_not (λ hts', ht _), lift t to finset α using s.finite_to_set.subset hts, exact ⟨t, ssubset_iff_subset_ne.2 ⟨hts, mt finset.coe_inj.2 hts'⟩, htne, hto⟩ } end theorem exists_open_singleton_of_fintype [t0_space α] [finite α] [nonempty α] : ∃ x : α, is_open ({x} : set α) := let ⟨x, _, h⟩ := exists_open_singleton_of_open_finite (set.to_finite _) univ_nonempty is_open_univ in ⟨x, h⟩ lemma t0_space_of_injective_of_continuous [topological_space β] {f : α → β} (hf : function.injective f) (hf' : continuous f) [t0_space β] : t0_space α := ⟨λ x y h, hf $ (h.map hf').eq⟩ protected lemma embedding.t0_space [topological_space β] [t0_space β] {f : α → β} (hf : embedding f) : t0_space α := t0_space_of_injective_of_continuous hf.inj hf.continuous instance subtype.t0_space [t0_space α] {p : α → Prop} : t0_space (subtype p) := embedding_subtype_coe.t0_space theorem t0_space_iff_or_not_mem_closure (α : Type u) [topological_space α] : t0_space α ↔ (∀ a b : α, a ≠ b → (a ∉ closure ({b} : set α) ∨ b ∉ closure ({a} : set α))) := by simp only [t0_space_iff_not_inseparable, inseparable_iff_mem_closure, not_and_distrib] instance [topological_space β] [t0_space α] [t0_space β] : t0_space (α × β) := ⟨λ x y h, prod.ext (h.map continuous_fst).eq (h.map continuous_snd).eq⟩ instance {ι : Type*} {π : ι → Type*} [Π i, topological_space (π i)] [Π i, t0_space (π i)] : t0_space (Π i, π i) := ⟨λ x y h, funext $ λ i, (h.map (continuous_apply i)).eq⟩ lemma t0_space.of_cover (h : ∀ x y, inseparable x y → ∃ s : set α, x ∈ s ∧ y ∈ s ∧ t0_space s) : t0_space α := begin refine ⟨λ x y hxy, _⟩, rcases h x y hxy with ⟨s, hxs, hys, hs⟩, resetI, lift x to s using hxs, lift y to s using hys, rw ← subtype_inseparable_iff at hxy, exact congr_arg coe hxy.eq end lemma t0_space.of_open_cover (h : ∀ x, ∃ s : set α, x ∈ s ∧ is_open s ∧ t0_space s) : t0_space α := t0_space.of_cover $ λ x y hxy, let ⟨s, hxs, hso, hs⟩ := h x in ⟨s, hxs, (hxy.mem_open_iff hso).1 hxs, hs⟩ /-- A T₁ space, also known as a Fréchet space, is a topological space where every singleton set is closed. Equivalently, for every pair `x ≠ y`, there is an open set containing `x` and not `y`. -/ class t1_space (α : Type u) [topological_space α] : Prop := (t1 : ∀x, is_closed ({x} : set α)) lemma is_closed_singleton [t1_space α] {x : α} : is_closed ({x} : set α) := t1_space.t1 x lemma is_open_compl_singleton [t1_space α] {x : α} : is_open ({x}ᶜ : set α) := is_closed_singleton.is_open_compl lemma is_open_ne [t1_space α] {x : α} : is_open {y | y ≠ x} := is_open_compl_singleton @[to_additive] lemma continuous.is_open_mul_support [t1_space α] [has_one α] [topological_space β] {f : β → α} (hf : continuous f) : is_open (mul_support f) := is_open_ne.preimage hf lemma ne.nhds_within_compl_singleton [t1_space α] {x y : α} (h : x ≠ y) : 𝓝[{y}ᶜ] x = 𝓝 x := is_open_ne.nhds_within_eq h lemma ne.nhds_within_diff_singleton [t1_space α] {x y : α} (h : x ≠ y) (s : set α) : 𝓝[s \ {y}] x = 𝓝[s] x := begin rw [diff_eq, inter_comm, nhds_within_inter_of_mem], exact mem_nhds_within_of_mem_nhds (is_open_ne.mem_nhds h) end lemma is_open_set_of_eventually_nhds_within [t1_space α] {p : α → Prop} : is_open {x | ∀ᶠ y in 𝓝[≠] x, p y} := begin refine is_open_iff_mem_nhds.mpr (λ a ha, _), filter_upwards [eventually_nhds_nhds_within.mpr ha] with b hb, by_cases a = b, { subst h, exact hb }, { rw (ne.symm h).nhds_within_compl_singleton at hb, exact hb.filter_mono nhds_within_le_nhds } end protected lemma set.finite.is_closed [t1_space α] {s : set α} (hs : set.finite s) : is_closed s := begin rw ← bUnion_of_singleton s, exact is_closed_bUnion hs (λ i hi, is_closed_singleton) end lemma topological_space.is_topological_basis.exists_mem_of_ne [t1_space α] {b : set (set α)} (hb : is_topological_basis b) {x y : α} (h : x ≠ y) : ∃ a ∈ b, x ∈ a ∧ y ∉ a := begin rcases hb.is_open_iff.1 is_open_ne x h with ⟨a, ab, xa, ha⟩, exact ⟨a, ab, xa, λ h, ha h rfl⟩, end lemma filter.coclosed_compact_le_cofinite [t1_space α] : filter.coclosed_compact α ≤ filter.cofinite := λ s hs, compl_compl s ▸ hs.is_compact.compl_mem_coclosed_compact_of_is_closed hs.is_closed variable (α) /-- In a `t1_space`, relatively compact sets form a bornology. Its cobounded filter is `filter.coclosed_compact`. See also `bornology.in_compact` the bornology of sets contained in a compact set. -/ def bornology.relatively_compact [t1_space α] : bornology α := { cobounded := filter.coclosed_compact α, le_cofinite := filter.coclosed_compact_le_cofinite } variable {α} lemma bornology.relatively_compact.is_bounded_iff [t1_space α] {s : set α} : @bornology.is_bounded _ (bornology.relatively_compact α) s ↔ is_compact (closure s) := begin change sᶜ ∈ filter.coclosed_compact α ↔ _, rw filter.mem_coclosed_compact, split, { rintros ⟨t, ht₁, ht₂, hst⟩, rw compl_subset_compl at hst, exact is_compact_of_is_closed_subset ht₂ is_closed_closure (closure_minimal hst ht₁) }, { intros h, exact ⟨closure s, is_closed_closure, h, compl_subset_compl.mpr subset_closure⟩ } end protected lemma finset.is_closed [t1_space α] (s : finset α) : is_closed (s : set α) := s.finite_to_set.is_closed lemma t1_space_tfae (α : Type u) [topological_space α] : tfae [t1_space α, ∀ x, is_closed ({x} : set α), ∀ x, is_open ({x}ᶜ : set α), continuous (@cofinite_topology.of α), ∀ ⦃x y : α⦄, x ≠ y → {y}ᶜ ∈ 𝓝 x, ∀ ⦃x y : α⦄, x ≠ y → ∃ s ∈ 𝓝 x, y ∉ s, ∀ ⦃x y : α⦄, x ≠ y → ∃ (U : set α) (hU : is_open U), x ∈ U ∧ y ∉ U, ∀ ⦃x y : α⦄, x ≠ y → disjoint (𝓝 x) (pure y), ∀ ⦃x y : α⦄, x ≠ y → disjoint (pure x) (𝓝 y), ∀ ⦃x y : α⦄, x ⤳ y → x = y] := begin tfae_have : 1 ↔ 2, from ⟨λ h, h.1, λ h, ⟨h⟩⟩, tfae_have : 2 ↔ 3, by simp only [is_open_compl_iff], tfae_have : 5 ↔ 3, { refine forall_swap.trans _, simp only [is_open_iff_mem_nhds, mem_compl_iff, mem_singleton_iff] }, tfae_have : 5 ↔ 6, by simp only [← subset_compl_singleton_iff, exists_mem_subset_iff], tfae_have : 5 ↔ 7, by simp only [(nhds_basis_opens _).mem_iff, subset_compl_singleton_iff, exists_prop, and.assoc, and.left_comm], tfae_have : 5 ↔ 8, by simp only [← principal_singleton, disjoint_principal_right], tfae_have : 8 ↔ 9, from forall_swap.trans (by simp only [disjoint.comm, ne_comm]), tfae_have : 1 → 4, { simp only [continuous_def, cofinite_topology.is_open_iff'], rintro H s (rfl|hs), exacts [is_open_empty, compl_compl s ▸ (@set.finite.is_closed _ _ H _ hs).is_open_compl] }, tfae_have : 4 → 2, from λ h x, (cofinite_topology.is_closed_iff.2 $ or.inr (finite_singleton _)).preimage h, tfae_have : 2 ↔ 10, { simp only [← closure_subset_iff_is_closed, specializes_iff_mem_closure, subset_def, mem_singleton_iff, eq_comm] }, tfae_finish end lemma t1_space_iff_continuous_cofinite_of {α : Type*} [topological_space α] : t1_space α ↔ continuous (@cofinite_topology.of α) := (t1_space_tfae α).out 0 3 lemma cofinite_topology.continuous_of [t1_space α] : continuous (@cofinite_topology.of α) := t1_space_iff_continuous_cofinite_of.mp ‹_› lemma t1_space_iff_exists_open : t1_space α ↔ ∀ (x y), x ≠ y → (∃ (U : set α) (hU : is_open U), x ∈ U ∧ y ∉ U) := (t1_space_tfae α).out 0 6 lemma t1_space_iff_disjoint_pure_nhds : t1_space α ↔ ∀ ⦃x y : α⦄, x ≠ y → disjoint (pure x) (𝓝 y) := (t1_space_tfae α).out 0 8 lemma t1_space_iff_disjoint_nhds_pure : t1_space α ↔ ∀ ⦃x y : α⦄, x ≠ y → disjoint (𝓝 x) (pure y) := (t1_space_tfae α).out 0 7 lemma t1_space_iff_specializes_imp_eq : t1_space α ↔ ∀ ⦃x y : α⦄, x ⤳ y → x = y := (t1_space_tfae α).out 0 9 lemma disjoint_pure_nhds [t1_space α] {x y : α} (h : x ≠ y) : disjoint (pure x) (𝓝 y) := t1_space_iff_disjoint_pure_nhds.mp ‹_› h lemma disjoint_nhds_pure [t1_space α] {x y : α} (h : x ≠ y) : disjoint (𝓝 x) (pure y) := t1_space_iff_disjoint_nhds_pure.mp ‹_› h lemma specializes.eq [t1_space α] {x y : α} (h : x ⤳ y) : x = y := t1_space_iff_specializes_imp_eq.1 ‹_› h lemma specializes_iff_eq [t1_space α] {x y : α} : x ⤳ y ↔ x = y := ⟨specializes.eq, λ h, h ▸ specializes_rfl⟩ @[simp] lemma specializes_eq_eq [t1_space α] : (⤳) = @eq α := funext₂ $ λ x y, propext specializes_iff_eq @[simp] lemma pure_le_nhds_iff [t1_space α] {a b : α} : pure a ≤ 𝓝 b ↔ a = b := specializes_iff_pure.symm.trans specializes_iff_eq @[simp] lemma nhds_le_nhds_iff [t1_space α] {a b : α} : 𝓝 a ≤ 𝓝 b ↔ a = b := specializes_iff_eq instance {α : Type*} : t1_space (cofinite_topology α) := t1_space_iff_continuous_cofinite_of.mpr continuous_id lemma t1_space_antitone {α : Type*} : antitone (@t1_space α) := begin simp only [antitone, t1_space_iff_continuous_cofinite_of, continuous_iff_le_induced], exact λ t₁ t₂ h, h.trans end lemma continuous_within_at_update_of_ne [t1_space α] [decidable_eq α] [topological_space β] {f : α → β} {s : set α} {x y : α} {z : β} (hne : y ≠ x) : continuous_within_at (function.update f x z) s y ↔ continuous_within_at f s y := eventually_eq.congr_continuous_within_at (mem_nhds_within_of_mem_nhds $ mem_of_superset (is_open_ne.mem_nhds hne) $ λ y' hy', function.update_noteq hy' _ _) (function.update_noteq hne _ _) lemma continuous_at_update_of_ne [t1_space α] [decidable_eq α] [topological_space β] {f : α → β} {x y : α} {z : β} (hne : y ≠ x) : continuous_at (function.update f x z) y ↔ continuous_at f y := by simp only [← continuous_within_at_univ, continuous_within_at_update_of_ne hne] lemma continuous_on_update_iff [t1_space α] [decidable_eq α] [topological_space β] {f : α → β} {s : set α} {x : α} {y : β} : continuous_on (function.update f x y) s ↔ continuous_on f (s \ {x}) ∧ (x ∈ s → tendsto f (𝓝[s \ {x}] x) (𝓝 y)) := begin rw [continuous_on, ← and_forall_ne x, and_comm], refine and_congr ⟨λ H z hz, _, λ H z hzx hzs, _⟩ (forall_congr $ λ hxs, _), { specialize H z hz.2 hz.1, rw continuous_within_at_update_of_ne hz.2 at H, exact H.mono (diff_subset _ _) }, { rw continuous_within_at_update_of_ne hzx, refine (H z ⟨hzs, hzx⟩).mono_of_mem (inter_mem_nhds_within _ _), exact is_open_ne.mem_nhds hzx }, { exact continuous_within_at_update_same } end lemma t1_space_of_injective_of_continuous [topological_space β] {f : α → β} (hf : function.injective f) (hf' : continuous f) [t1_space β] : t1_space α := t1_space_iff_specializes_imp_eq.2 $ λ x y h, hf (h.map hf').eq protected lemma embedding.t1_space [topological_space β] [t1_space β] {f : α → β} (hf : embedding f) : t1_space α := t1_space_of_injective_of_continuous hf.inj hf.continuous instance subtype.t1_space {α : Type u} [topological_space α] [t1_space α] {p : α → Prop} : t1_space (subtype p) := embedding_subtype_coe.t1_space instance [topological_space β] [t1_space α] [t1_space β] : t1_space (α × β) := ⟨λ ⟨a, b⟩, @singleton_prod_singleton _ _ a b ▸ is_closed_singleton.prod is_closed_singleton⟩ instance {ι : Type*} {π : ι → Type*} [Π i, topological_space (π i)] [Π i, t1_space (π i)] : t1_space (Π i, π i) := ⟨λ f, univ_pi_singleton f ▸ is_closed_set_pi (λ i hi, is_closed_singleton)⟩ @[priority 100] -- see Note [lower instance priority] instance t1_space.t0_space [t1_space α] : t0_space α := ⟨λ x y h, h.specializes.eq⟩ @[simp] lemma compl_singleton_mem_nhds_iff [t1_space α] {x y : α} : {x}ᶜ ∈ 𝓝 y ↔ y ≠ x := is_open_compl_singleton.mem_nhds_iff lemma compl_singleton_mem_nhds [t1_space α] {x y : α} (h : y ≠ x) : {x}ᶜ ∈ 𝓝 y := compl_singleton_mem_nhds_iff.mpr h @[simp] lemma closure_singleton [t1_space α] {a : α} : closure ({a} : set α) = {a} := is_closed_singleton.closure_eq lemma set.subsingleton.closure [t1_space α] {s : set α} (hs : s.subsingleton) : (closure s).subsingleton := hs.induction_on (by simp) $ λ x, by simp @[simp] lemma subsingleton_closure [t1_space α] {s : set α} : (closure s).subsingleton ↔ s.subsingleton := ⟨λ h, h.anti subset_closure, λ h, h.closure⟩ lemma is_closed_map_const {α β} [topological_space α] [topological_space β] [t1_space β] {y : β} : is_closed_map (function.const α y) := is_closed_map.of_nonempty $ λ s hs h2s, by simp_rw [h2s.image_const, is_closed_singleton] lemma nhds_within_insert_of_ne [t1_space α] {x y : α} {s : set α} (hxy : x ≠ y) : 𝓝[insert y s] x = 𝓝[s] x := begin refine le_antisymm (λ t ht, _) (nhds_within_mono x $ subset_insert y s), obtain ⟨o, ho, hxo, host⟩ := mem_nhds_within.mp ht, refine mem_nhds_within.mpr ⟨o \ {y}, ho.sdiff is_closed_singleton, ⟨hxo, hxy⟩, _⟩, rw [inter_insert_of_not_mem $ not_mem_diff_of_mem (mem_singleton y)], exact (inter_subset_inter (diff_subset _ _) subset.rfl).trans host end /-- If `t` is a subset of `s`, except for one point, then `insert x s` is a neighborhood of `x` within `t`. -/ lemma insert_mem_nhds_within_of_subset_insert [t1_space α] {x y : α} {s t : set α} (hu : t ⊆ insert y s) : insert x s ∈ 𝓝[t] x := begin rcases eq_or_ne x y with rfl|h, { exact mem_of_superset self_mem_nhds_within hu }, refine nhds_within_mono x hu _, rw [nhds_within_insert_of_ne h], exact mem_of_superset self_mem_nhds_within (subset_insert x s) end lemma bInter_basis_nhds [t1_space α] {ι : Sort*} {p : ι → Prop} {s : ι → set α} {x : α} (h : (𝓝 x).has_basis p s) : (⋂ i (h : p i), s i) = {x} := begin simp only [eq_singleton_iff_unique_mem, mem_Inter], refine ⟨λ i hi, mem_of_mem_nhds $ h.mem_of_mem hi, λ y hy, _⟩, contrapose! hy, rcases h.mem_iff.1 (compl_singleton_mem_nhds hy.symm) with ⟨i, hi, hsub⟩, exact ⟨i, hi, λ h, hsub h rfl⟩ end @[simp] lemma compl_singleton_mem_nhds_set_iff [t1_space α] {x : α} {s : set α} : {x}ᶜ ∈ 𝓝ˢ s ↔ x ∉ s := by rwa [is_open_compl_singleton.mem_nhds_set, subset_compl_singleton_iff] @[simp] lemma nhds_set_le_iff [t1_space α] {s t : set α} : 𝓝ˢ s ≤ 𝓝ˢ t ↔ s ⊆ t := begin refine ⟨_, λ h, monotone_nhds_set h⟩, simp_rw [filter.le_def], intros h x hx, specialize h {x}ᶜ, simp_rw [compl_singleton_mem_nhds_set_iff] at h, by_contra hxt, exact h hxt hx, end @[simp] lemma nhds_set_inj_iff [t1_space α] {s t : set α} : 𝓝ˢ s = 𝓝ˢ t ↔ s = t := by { simp_rw [le_antisymm_iff], exact and_congr nhds_set_le_iff nhds_set_le_iff } lemma injective_nhds_set [t1_space α] : function.injective (𝓝ˢ : set α → filter α) := λ s t hst, nhds_set_inj_iff.mp hst lemma strict_mono_nhds_set [t1_space α] : strict_mono (𝓝ˢ : set α → filter α) := monotone_nhds_set.strict_mono_of_injective injective_nhds_set @[simp] lemma nhds_le_nhds_set_iff [t1_space α] {s : set α} {x : α} : 𝓝 x ≤ 𝓝ˢ s ↔ x ∈ s := by rw [← nhds_set_singleton, nhds_set_le_iff, singleton_subset_iff] /-- Removing a non-isolated point from a dense set, one still obtains a dense set. -/ lemma dense.diff_singleton [t1_space α] {s : set α} (hs : dense s) (x : α) [ne_bot (𝓝[≠] x)] : dense (s \ {x}) := hs.inter_of_open_right (dense_compl_singleton x) is_open_compl_singleton /-- Removing a finset from a dense set in a space without isolated points, one still obtains a dense set. -/ lemma dense.diff_finset [t1_space α] [∀ (x : α), ne_bot (𝓝[≠] x)] {s : set α} (hs : dense s) (t : finset α) : dense (s \ t) := begin induction t using finset.induction_on with x s hxs ih hd, { simpa using hs }, { rw [finset.coe_insert, ← union_singleton, ← diff_diff], exact ih.diff_singleton _, } end /-- Removing a finite set from a dense set in a space without isolated points, one still obtains a dense set. -/ lemma dense.diff_finite [t1_space α] [∀ (x : α), ne_bot (𝓝[≠] x)] {s : set α} (hs : dense s) {t : set α} (ht : t.finite) : dense (s \ t) := begin convert hs.diff_finset ht.to_finset, exact (finite.coe_to_finset _).symm, end /-- If a function to a `t1_space` tends to some limit `b` at some point `a`, then necessarily `b = f a`. -/ lemma eq_of_tendsto_nhds [topological_space β] [t1_space β] {f : α → β} {a : α} {b : β} (h : tendsto f (𝓝 a) (𝓝 b)) : f a = b := by_contra $ assume (hfa : f a ≠ b), have fact₁ : {f a}ᶜ ∈ 𝓝 b := compl_singleton_mem_nhds hfa.symm, have fact₂ : tendsto f (pure a) (𝓝 b) := h.comp (tendsto_id'.2 $ pure_le_nhds a), fact₂ fact₁ (eq.refl $ f a) lemma filter.tendsto.eventually_ne [topological_space β] [t1_space β] {α : Type*} {g : α → β} {l : filter α} {b₁ b₂ : β} (hg : tendsto g l (𝓝 b₁)) (hb : b₁ ≠ b₂) : ∀ᶠ z in l, g z ≠ b₂ := hg.eventually (is_open_compl_singleton.eventually_mem hb) lemma continuous_at.eventually_ne [topological_space β] [t1_space β] {g : α → β} {a : α} {b : β} (hg1 : continuous_at g a) (hg2 : g a ≠ b) : ∀ᶠ z in 𝓝 a, g z ≠ b := hg1.tendsto.eventually_ne hg2 /-- To prove a function to a `t1_space` is continuous at some point `a`, it suffices to prove that `f` admits *some* limit at `a`. -/ lemma continuous_at_of_tendsto_nhds [topological_space β] [t1_space β] {f : α → β} {a : α} {b : β} (h : tendsto f (𝓝 a) (𝓝 b)) : continuous_at f a := show tendsto f (𝓝 a) (𝓝 $ f a), by rwa eq_of_tendsto_nhds h @[simp] lemma tendsto_const_nhds_iff [t1_space α] {l : filter β} [ne_bot l] {c d : α} : tendsto (λ x, c) l (𝓝 d) ↔ c = d := by simp_rw [tendsto, filter.map_const, pure_le_nhds_iff] /-- A point with a finite neighborhood has to be isolated. -/ lemma is_open_singleton_of_finite_mem_nhds {α : Type*} [topological_space α] [t1_space α] (x : α) {s : set α} (hs : s ∈ 𝓝 x) (hsf : s.finite) : is_open ({x} : set α) := begin have A : {x} ⊆ s, by simp only [singleton_subset_iff, mem_of_mem_nhds hs], have B : is_closed (s \ {x}) := (hsf.subset (diff_subset _ _)).is_closed, have C : (s \ {x})ᶜ ∈ 𝓝 x, from B.is_open_compl.mem_nhds (λ h, h.2 rfl), have D : {x} ∈ 𝓝 x, by simpa only [← diff_eq, diff_diff_cancel_left A] using inter_mem hs C, rwa [← mem_interior_iff_mem_nhds, ← singleton_subset_iff, subset_interior_iff_is_open] at D end /-- If the punctured neighborhoods of a point form a nontrivial filter, then any neighborhood is infinite. -/ lemma infinite_of_mem_nhds {α} [topological_space α] [t1_space α] (x : α) [hx : ne_bot (𝓝[≠] x)] {s : set α} (hs : s ∈ 𝓝 x) : set.infinite s := begin refine λ hsf, hx.1 _, rw [← is_open_singleton_iff_punctured_nhds], exact is_open_singleton_of_finite_mem_nhds x hs hsf end lemma discrete_of_t1_of_finite {X : Type*} [topological_space X] [t1_space X] [finite X] : discrete_topology X := begin apply singletons_open_iff_discrete.mp, intros x, rw [← is_closed_compl_iff], exact (set.to_finite _).is_closed end lemma preconnected_space.trivial_of_discrete [preconnected_space α] [discrete_topology α] : subsingleton α := begin rw ←not_nontrivial_iff_subsingleton, rintro ⟨x, y, hxy⟩, rw [ne.def, ←mem_singleton_iff, (is_clopen_discrete _).eq_univ $ singleton_nonempty y] at hxy, exact hxy (mem_univ x) end lemma is_preconnected.infinite_of_nontrivial [t1_space α] {s : set α} (h : is_preconnected s) (hs : s.nontrivial) : s.infinite := begin refine mt (λ hf, (subsingleton_coe s).mp _) (not_subsingleton_iff.mpr hs), haveI := @discrete_of_t1_of_finite s _ _ hf.to_subtype, exact @preconnected_space.trivial_of_discrete _ _ (subtype.preconnected_space h) _ end lemma connected_space.infinite [connected_space α] [nontrivial α] [t1_space α] : infinite α := infinite_univ_iff.mp $ is_preconnected_univ.infinite_of_nontrivial nontrivial_univ lemma singleton_mem_nhds_within_of_mem_discrete {s : set α} [discrete_topology s] {x : α} (hx : x ∈ s) : {x} ∈ 𝓝[s] x := begin have : ({⟨x, hx⟩} : set s) ∈ 𝓝 (⟨x, hx⟩ : s), by simp [nhds_discrete], simpa only [nhds_within_eq_map_subtype_coe hx, image_singleton] using @image_mem_map _ _ _ (coe : s → α) _ this end /-- The neighbourhoods filter of `x` within `s`, under the discrete topology, is equal to the pure `x` filter (which is the principal filter at the singleton `{x}`.) -/ lemma nhds_within_of_mem_discrete {s : set α} [discrete_topology s] {x : α} (hx : x ∈ s) : 𝓝[s] x = pure x := le_antisymm (le_pure_iff.2 $ singleton_mem_nhds_within_of_mem_discrete hx) (pure_le_nhds_within hx) lemma filter.has_basis.exists_inter_eq_singleton_of_mem_discrete {ι : Type*} {p : ι → Prop} {t : ι → set α} {s : set α} [discrete_topology s] {x : α} (hb : (𝓝 x).has_basis p t) (hx : x ∈ s) : ∃ i (hi : p i), t i ∩ s = {x} := begin rcases (nhds_within_has_basis hb s).mem_iff.1 (singleton_mem_nhds_within_of_mem_discrete hx) with ⟨i, hi, hix⟩, exact ⟨i, hi, subset.antisymm hix $ singleton_subset_iff.2 ⟨mem_of_mem_nhds $ hb.mem_of_mem hi, hx⟩⟩ end /-- A point `x` in a discrete subset `s` of a topological space admits a neighbourhood that only meets `s` at `x`. -/ lemma nhds_inter_eq_singleton_of_mem_discrete {s : set α} [discrete_topology s] {x : α} (hx : x ∈ s) : ∃ U ∈ 𝓝 x, U ∩ s = {x} := by simpa using (𝓝 x).basis_sets.exists_inter_eq_singleton_of_mem_discrete hx /-- For point `x` in a discrete subset `s` of a topological space, there is a set `U` such that 1. `U` is a punctured neighborhood of `x` (ie. `U ∪ {x}` is a neighbourhood of `x`), 2. `U` is disjoint from `s`. -/ lemma disjoint_nhds_within_of_mem_discrete {s : set α} [discrete_topology s] {x : α} (hx : x ∈ s) : ∃ U ∈ 𝓝[≠] x, disjoint U s := let ⟨V, h, h'⟩ := nhds_inter_eq_singleton_of_mem_discrete hx in ⟨{x}ᶜ ∩ V, inter_mem_nhds_within _ h, (disjoint_iff_inter_eq_empty.mpr (by { rw [inter_assoc, h', compl_inter_self] }))⟩ /-- Let `X` be a topological space and let `s, t ⊆ X` be two subsets. If there is an inclusion `t ⊆ s`, then the topological space structure on `t` induced by `X` is the same as the one obtained by the induced topological space structure on `s`. -/ lemma topological_space.subset_trans {X : Type*} [tX : topological_space X] {s t : set X} (ts : t ⊆ s) : (subtype.topological_space : topological_space t) = (subtype.topological_space : topological_space s).induced (set.inclusion ts) := begin change tX.induced ((coe : s → X) ∘ (set.inclusion ts)) = topological_space.induced (set.inclusion ts) (tX.induced _), rw ← induced_compose, end /-- A T₂ space, also known as a Hausdorff space, is one in which for every `x ≠ y` there exists disjoint open sets around `x` and `y`. This is the most widely used of the separation axioms. -/ @[mk_iff] class t2_space (α : Type u) [topological_space α] : Prop := (t2 : ∀ x y, x ≠ y → ∃ u v : set α, is_open u ∧ is_open v ∧ x ∈ u ∧ y ∈ v ∧ disjoint u v) /-- Two different points can be separated by open sets. -/ lemma t2_separation [t2_space α] {x y : α} (h : x ≠ y) : ∃ u v : set α, is_open u ∧ is_open v ∧ x ∈ u ∧ y ∈ v ∧ disjoint u v := t2_space.t2 x y h lemma t2_space_iff_disjoint_nhds : t2_space α ↔ ∀ x y : α, x ≠ y → disjoint (𝓝 x) (𝓝 y) := begin refine (t2_space_iff α).trans (forall₃_congr $ λ x y hne, _), simp only [(nhds_basis_opens x).disjoint_iff (nhds_basis_opens y), exists_prop, ← exists_and_distrib_left, and.assoc, and_comm, and.left_comm] end @[simp] lemma disjoint_nhds_nhds [t2_space α] {x y : α} : disjoint (𝓝 x) (𝓝 y) ↔ x ≠ y := ⟨λ hd he, by simpa [he, nhds_ne_bot.ne] using hd, t2_space_iff_disjoint_nhds.mp ‹_› x y⟩ lemma pairwise_disjoint_nhds [t2_space α] : pairwise (disjoint on (𝓝 : α → filter α)) := λ x y, disjoint_nhds_nhds.2 protected lemma set.pairwise_disjoint_nhds [t2_space α] (s : set α) : s.pairwise_disjoint 𝓝 := pairwise_disjoint_nhds.set_pairwise s /-- Points of a finite set can be separated by open sets from each other. -/ lemma set.finite.t2_separation [t2_space α] {s : set α} (hs : s.finite) : ∃ U : α → set α, (∀ x, x ∈ U x ∧ is_open (U x)) ∧ s.pairwise_disjoint U := s.pairwise_disjoint_nhds.exists_mem_filter_basis hs nhds_basis_opens lemma is_open_set_of_disjoint_nhds_nhds : is_open {p : α × α | disjoint (𝓝 p.1) (𝓝 p.2)} := begin simp only [is_open_iff_mem_nhds, prod.forall, mem_set_of_eq], intros x y h, obtain ⟨U, hU, V, hV, hd⟩ := ((nhds_basis_opens x).disjoint_iff (nhds_basis_opens y)).mp h, exact mem_nhds_prod_iff.mpr ⟨U, hU.2.mem_nhds hU.1, V, hV.2.mem_nhds hV.1, λ ⟨x', y'⟩ ⟨hx', hy'⟩, disjoint_of_disjoint_of_mem hd (hU.2.mem_nhds hx') (hV.2.mem_nhds hy')⟩ end @[priority 100] -- see Note [lower instance priority] instance t2_space.t1_space [t2_space α] : t1_space α := t1_space_iff_disjoint_pure_nhds.mpr $ λ x y hne, (disjoint_nhds_nhds.2 hne).mono_left $ pure_le_nhds _ /-- A space is T₂ iff the neighbourhoods of distinct points generate the bottom filter. -/ lemma t2_iff_nhds : t2_space α ↔ ∀ {x y : α}, ne_bot (𝓝 x ⊓ 𝓝 y) → x = y := by simp only [t2_space_iff_disjoint_nhds, disjoint_iff, ne_bot_iff, ne.def, not_imp_comm] lemma eq_of_nhds_ne_bot [t2_space α] {x y : α} (h : ne_bot (𝓝 x ⊓ 𝓝 y)) : x = y := t2_iff_nhds.mp ‹_› h lemma t2_space_iff_nhds : t2_space α ↔ ∀ {x y : α}, x ≠ y → ∃ (U ∈ 𝓝 x) (V ∈ 𝓝 y), disjoint U V := by simp only [t2_space_iff_disjoint_nhds, filter.disjoint_iff] lemma t2_separation_nhds [t2_space α] {x y : α} (h : x ≠ y) : ∃ u v, u ∈ 𝓝 x ∧ v ∈ 𝓝 y ∧ disjoint u v := let ⟨u, v, open_u, open_v, x_in, y_in, huv⟩ := t2_separation h in ⟨u, v, open_u.mem_nhds x_in, open_v.mem_nhds y_in, huv⟩ lemma t2_separation_compact_nhds [locally_compact_space α] [t2_space α] {x y : α} (h : x ≠ y) : ∃ u v, u ∈ 𝓝 x ∧ v ∈ 𝓝 y ∧ is_compact u ∧ is_compact v ∧ disjoint u v := by simpa only [exists_prop, ← exists_and_distrib_left, and_comm, and.assoc, and.left_comm] using ((compact_basis_nhds x).disjoint_iff (compact_basis_nhds y)).1 (disjoint_nhds_nhds.2 h) lemma t2_iff_ultrafilter : t2_space α ↔ ∀ {x y : α} (f : ultrafilter α), ↑f ≤ 𝓝 x → ↑f ≤ 𝓝 y → x = y := t2_iff_nhds.trans $ by simp only [←exists_ultrafilter_iff, and_imp, le_inf_iff, exists_imp_distrib] lemma t2_iff_is_closed_diagonal : t2_space α ↔ is_closed (diagonal α) := by simp only [t2_space_iff_disjoint_nhds, ← is_open_compl_iff, is_open_iff_mem_nhds, prod.forall, nhds_prod_eq, compl_diagonal_mem_prod, mem_compl_iff, mem_diagonal_iff] lemma is_closed_diagonal [t2_space α] : is_closed (diagonal α) := t2_iff_is_closed_diagonal.mp ‹_› section separated open separated_nhds finset lemma finset_disjoint_finset_opens_of_t2 [t2_space α] : ∀ (s t : finset α), disjoint s t → separated_nhds (s : set α) t := begin refine induction_on_union _ (λ a b hi d, (hi d.symm).symm) (λ a d, empty_right a) (λ a b ab, _) _, { obtain ⟨U, V, oU, oV, aU, bV, UV⟩ := t2_separation (finset.disjoint_singleton.1 ab), refine ⟨U, V, oU, oV, _, _, UV⟩; exact singleton_subset_set_iff.mpr ‹_› }, { intros a b c ac bc d, apply_mod_cast union_left (ac (disjoint_of_subset_left (a.subset_union_left b) d)) (bc _), exact disjoint_of_subset_left (a.subset_union_right b) d }, end lemma point_disjoint_finset_opens_of_t2 [t2_space α] {x : α} {s : finset α} (h : x ∉ s) : separated_nhds ({x} : set α) s := by exact_mod_cast finset_disjoint_finset_opens_of_t2 {x} s (finset.disjoint_singleton_left.mpr h) end separated lemma tendsto_nhds_unique [t2_space α] {f : β → α} {l : filter β} {a b : α} [ne_bot l] (ha : tendsto f l (𝓝 a)) (hb : tendsto f l (𝓝 b)) : a = b := eq_of_nhds_ne_bot $ ne_bot_of_le $ le_inf ha hb lemma tendsto_nhds_unique' [t2_space α] {f : β → α} {l : filter β} {a b : α} (hl : ne_bot l) (ha : tendsto f l (𝓝 a)) (hb : tendsto f l (𝓝 b)) : a = b := eq_of_nhds_ne_bot $ ne_bot_of_le $ le_inf ha hb lemma tendsto_nhds_unique_of_eventually_eq [t2_space α] {f g : β → α} {l : filter β} {a b : α} [ne_bot l] (ha : tendsto f l (𝓝 a)) (hb : tendsto g l (𝓝 b)) (hfg : f =ᶠ[l] g) : a = b := tendsto_nhds_unique (ha.congr' hfg) hb lemma tendsto_nhds_unique_of_frequently_eq [t2_space α] {f g : β → α} {l : filter β} {a b : α} (ha : tendsto f l (𝓝 a)) (hb : tendsto g l (𝓝 b)) (hfg : ∃ᶠ x in l, f x = g x) : a = b := have ∃ᶠ z : α × α in 𝓝 (a, b), z.1 = z.2 := (ha.prod_mk_nhds hb).frequently hfg, not_not.1 $ λ hne, this (is_closed_diagonal.is_open_compl.mem_nhds hne) /-- A T₂.₅ space, also known as a Urysohn space, is a topological space where for every pair `x ≠ y`, there are two open sets, with the intersection of closures empty, one containing `x` and the other `y` . -/ class t2_5_space (α : Type u) [topological_space α]: Prop := (t2_5 : ∀ ⦃x y : α⦄ (h : x ≠ y), disjoint ((𝓝 x).lift' closure) ((𝓝 y).lift' closure)) @[simp] lemma disjoint_lift'_closure_nhds [t2_5_space α] {x y : α} : disjoint ((𝓝 x).lift' closure) ((𝓝 y).lift' closure) ↔ x ≠ y := ⟨λ h hxy, by simpa [hxy, nhds_ne_bot.ne] using h, λ h, t2_5_space.t2_5 h⟩ @[priority 100] -- see Note [lower instance priority] instance t2_5_space.t2_space [t2_5_space α] : t2_space α := t2_space_iff_disjoint_nhds.2 $ λ x y hne, (disjoint_lift'_closure_nhds.2 hne).mono (le_lift'_closure _) (le_lift'_closure _) lemma exists_nhds_disjoint_closure [t2_5_space α] {x y : α} (h : x ≠ y) : ∃ (s ∈ 𝓝 x) (t ∈ 𝓝 y), disjoint (closure s) (closure t) := ((𝓝 x).basis_sets.lift'_closure.disjoint_iff (𝓝 y).basis_sets.lift'_closure).1 $ disjoint_lift'_closure_nhds.2 h lemma exists_open_nhds_disjoint_closure [t2_5_space α] {x y : α} (h : x ≠ y) : ∃ u : set α, x ∈ u ∧ is_open u ∧ ∃ v : set α, y ∈ v ∧ is_open v ∧ disjoint (closure u) (closure v) := by simpa only [exists_prop, and.assoc] using ((nhds_basis_opens x).lift'_closure.disjoint_iff (nhds_basis_opens y).lift'_closure).1 (disjoint_lift'_closure_nhds.2 h) section lim variables [t2_space α] {f : filter α} /-! ### Properties of `Lim` and `lim` In this section we use explicit `nonempty α` instances for `Lim` and `lim`. This way the lemmas are useful without a `nonempty α` instance. -/ lemma Lim_eq {a : α} [ne_bot f] (h : f ≤ 𝓝 a) : @Lim _ _ ⟨a⟩ f = a := tendsto_nhds_unique (le_nhds_Lim ⟨a, h⟩) h lemma Lim_eq_iff [ne_bot f] (h : ∃ (a : α), f ≤ nhds a) {a} : @Lim _ _ ⟨a⟩ f = a ↔ f ≤ 𝓝 a := ⟨λ c, c ▸ le_nhds_Lim h, Lim_eq⟩ lemma ultrafilter.Lim_eq_iff_le_nhds [compact_space α] {x : α} {F : ultrafilter α} : F.Lim = x ↔ ↑F ≤ 𝓝 x := ⟨λ h, h ▸ F.le_nhds_Lim, Lim_eq⟩ lemma is_open_iff_ultrafilter' [compact_space α] (U : set α) : is_open U ↔ (∀ F : ultrafilter α, F.Lim ∈ U → U ∈ F.1) := begin rw is_open_iff_ultrafilter, refine ⟨λ h F hF, h F.Lim hF F F.le_nhds_Lim, _⟩, intros cond x hx f h, rw [← (ultrafilter.Lim_eq_iff_le_nhds.2 h)] at hx, exact cond _ hx end lemma filter.tendsto.lim_eq {a : α} {f : filter β} [ne_bot f] {g : β → α} (h : tendsto g f (𝓝 a)) : @lim _ _ _ ⟨a⟩ f g = a := Lim_eq h lemma filter.lim_eq_iff {f : filter β} [ne_bot f] {g : β → α} (h : ∃ a, tendsto g f (𝓝 a)) {a} : @lim _ _ _ ⟨a⟩ f g = a ↔ tendsto g f (𝓝 a) := ⟨λ c, c ▸ tendsto_nhds_lim h, filter.tendsto.lim_eq⟩ lemma continuous.lim_eq [topological_space β] {f : β → α} (h : continuous f) (a : β) : @lim _ _ _ ⟨f a⟩ (𝓝 a) f = f a := (h.tendsto a).lim_eq @[simp] lemma Lim_nhds (a : α) : @Lim _ _ ⟨a⟩ (𝓝 a) = a := Lim_eq le_rfl @[simp] lemma lim_nhds_id (a : α) : @lim _ _ _ ⟨a⟩ (𝓝 a) id = a := Lim_nhds a @[simp] lemma Lim_nhds_within {a : α} {s : set α} (h : a ∈ closure s) : @Lim _ _ ⟨a⟩ (𝓝[s] a) = a := by haveI : ne_bot (𝓝[s] a) := mem_closure_iff_cluster_pt.1 h; exact Lim_eq inf_le_left @[simp] lemma lim_nhds_within_id {a : α} {s : set α} (h : a ∈ closure s) : @lim _ _ _ ⟨a⟩ (𝓝[s] a) id = a := Lim_nhds_within h end lim /-! ### `t2_space` constructions We use two lemmas to prove that various standard constructions generate Hausdorff spaces from Hausdorff spaces: * `separated_by_continuous` says that two points `x y : α` can be separated by open neighborhoods provided that there exists a continuous map `f : α → β` with a Hausdorff codomain such that `f x ≠ f y`. We use this lemma to prove that topological spaces defined using `induced` are Hausdorff spaces. * `separated_by_open_embedding` says that for an open embedding `f : α → β` of a Hausdorff space `α`, the images of two distinct points `x y : α`, `x ≠ y` can be separated by open neighborhoods. We use this lemma to prove that topological spaces defined using `coinduced` are Hausdorff spaces. -/ @[priority 100] -- see Note [lower instance priority] instance discrete_topology.to_t2_space {α : Type*} [topological_space α] [discrete_topology α] : t2_space α := ⟨λ x y h, ⟨{x}, {y}, is_open_discrete _, is_open_discrete _, rfl, rfl, disjoint_singleton.2 h⟩⟩ lemma separated_by_continuous {α : Type*} {β : Type*} [topological_space α] [topological_space β] [t2_space β] {f : α → β} (hf : continuous f) {x y : α} (h : f x ≠ f y) : ∃u v : set α, is_open u ∧ is_open v ∧ x ∈ u ∧ y ∈ v ∧ disjoint u v := let ⟨u, v, uo, vo, xu, yv, uv⟩ := t2_separation h in ⟨f ⁻¹' u, f ⁻¹' v, uo.preimage hf, vo.preimage hf, xu, yv, uv.preimage _⟩ lemma separated_by_open_embedding {α β : Type*} [topological_space α] [topological_space β] [t2_space α] {f : α → β} (hf : open_embedding f) {x y : α} (h : x ≠ y) : ∃ u v : set β, is_open u ∧ is_open v ∧ f x ∈ u ∧ f y ∈ v ∧ disjoint u v := let ⟨u, v, uo, vo, xu, yv, uv⟩ := t2_separation h in ⟨f '' u, f '' v, hf.is_open_map _ uo, hf.is_open_map _ vo, mem_image_of_mem _ xu, mem_image_of_mem _ yv, disjoint_image_of_injective hf.inj uv⟩ instance {α : Type*} {p : α → Prop} [t : topological_space α] [t2_space α] : t2_space (subtype p) := ⟨assume x y h, separated_by_continuous continuous_subtype_val (mt subtype.eq h)⟩ instance {α : Type*} {β : Type*} [t₁ : topological_space α] [t2_space α] [t₂ : topological_space β] [t2_space β] : t2_space (α × β) := ⟨assume ⟨x₁,x₂⟩ ⟨y₁,y₂⟩ h, or.elim (not_and_distrib.mp (mt prod.ext_iff.mpr h)) (λ h₁, separated_by_continuous continuous_fst h₁) (λ h₂, separated_by_continuous continuous_snd h₂)⟩ lemma embedding.t2_space [topological_space β] [t2_space β] {f : α → β} (hf : embedding f) : t2_space α := ⟨λ x y h, separated_by_continuous hf.continuous (hf.inj.ne h)⟩ instance {α : Type*} {β : Type*} [t₁ : topological_space α] [t2_space α] [t₂ : topological_space β] [t2_space β] : t2_space (α ⊕ β) := begin constructor, rintros (x|x) (y|y) h, { replace h : x ≠ y := λ c, (c.subst h) rfl, exact separated_by_open_embedding open_embedding_inl h }, { exact ⟨_, _, is_open_range_inl, is_open_range_inr, ⟨x, rfl⟩, ⟨y, rfl⟩, is_compl_range_inl_range_inr.disjoint⟩ }, { exact ⟨_, _, is_open_range_inr, is_open_range_inl, ⟨x, rfl⟩, ⟨y, rfl⟩, is_compl_range_inl_range_inr.disjoint.symm⟩ }, { replace h : x ≠ y := λ c, (c.subst h) rfl, exact separated_by_open_embedding open_embedding_inr h } end instance Pi.t2_space {α : Type*} {β : α → Type v} [t₂ : Πa, topological_space (β a)] [∀a, t2_space (β a)] : t2_space (Πa, β a) := ⟨assume x y h, let ⟨i, hi⟩ := not_forall.mp (mt funext h) in separated_by_continuous (continuous_apply i) hi⟩ instance sigma.t2_space {ι : Type*} {α : ι → Type*} [Πi, topological_space (α i)] [∀a, t2_space (α a)] : t2_space (Σi, α i) := begin constructor, rintros ⟨i, x⟩ ⟨j, y⟩ neq, rcases em (i = j) with (rfl|h), { replace neq : x ≠ y := λ c, (c.subst neq) rfl, exact separated_by_open_embedding open_embedding_sigma_mk neq }, { exact ⟨_, _, is_open_range_sigma_mk, is_open_range_sigma_mk, ⟨x, rfl⟩, ⟨y, rfl⟩, set.disjoint_left.mpr $ by tidy⟩ } end variables {γ : Type*} [topological_space β] [topological_space γ] lemma is_closed_eq [t2_space α] {f g : β → α} (hf : continuous f) (hg : continuous g) : is_closed {x:β | f x = g x} := continuous_iff_is_closed.mp (hf.prod_mk hg) _ is_closed_diagonal lemma is_open_ne_fun [t2_space α] {f g : β → α} (hf : continuous f) (hg : continuous g) : is_open {x:β | f x ≠ g x} := is_open_compl_iff.mpr $ is_closed_eq hf hg /-- If two continuous maps are equal on `s`, then they are equal on the closure of `s`. See also `set.eq_on.of_subset_closure` for a more general version. -/ lemma set.eq_on.closure [t2_space α] {s : set β} {f g : β → α} (h : eq_on f g s) (hf : continuous f) (hg : continuous g) : eq_on f g (closure s) := closure_minimal h (is_closed_eq hf hg) /-- If two continuous functions are equal on a dense set, then they are equal. -/ lemma continuous.ext_on [t2_space α] {s : set β} (hs : dense s) {f g : β → α} (hf : continuous f) (hg : continuous g) (h : eq_on f g s) : f = g := funext $ λ x, h.closure hf hg (hs x) lemma eq_on_closure₂' [t2_space α] {s : set β} {t : set γ} {f g : β → γ → α} (h : ∀ (x ∈ s) (y ∈ t), f x y = g x y) (hf₁ : ∀ x, continuous (f x)) (hf₂ : ∀ y, continuous (λ x, f x y)) (hg₁ : ∀ x, continuous (g x)) (hg₂ : ∀ y, continuous (λ x, g x y)) : ∀ (x ∈ closure s) (y ∈ closure t), f x y = g x y := suffices closure s ⊆ ⋂ y ∈ closure t, {x | f x y = g x y}, by simpa only [subset_def, mem_Inter], closure_minimal (λ x hx, mem_Inter₂.2 $ set.eq_on.closure (h x hx) (hf₁ _) (hg₁ _)) $ is_closed_bInter $ λ y hy, is_closed_eq (hf₂ _) (hg₂ _) lemma eq_on_closure₂ [t2_space α] {s : set β} {t : set γ} {f g : β → γ → α} (h : ∀ (x ∈ s) (y ∈ t), f x y = g x y) (hf : continuous (uncurry f)) (hg : continuous (uncurry g)) : ∀ (x ∈ closure s) (y ∈ closure t), f x y = g x y := eq_on_closure₂' h (λ x, continuous_uncurry_left x hf) (λ x, continuous_uncurry_right x hf) (λ y, continuous_uncurry_left y hg) (λ y, continuous_uncurry_right y hg) /-- If `f x = g x` for all `x ∈ s` and `f`, `g` are continuous on `t`, `s ⊆ t ⊆ closure s`, then `f x = g x` for all `x ∈ t`. See also `set.eq_on.closure`. -/ lemma set.eq_on.of_subset_closure [t2_space α] {s t : set β} {f g : β → α} (h : eq_on f g s) (hf : continuous_on f t) (hg : continuous_on g t) (hst : s ⊆ t) (hts : t ⊆ closure s) : eq_on f g t := begin intros x hx, haveI : (𝓝[s] x).ne_bot, from mem_closure_iff_cluster_pt.mp (hts hx), exact tendsto_nhds_unique_of_eventually_eq ((hf x hx).mono_left $ nhds_within_mono _ hst) ((hg x hx).mono_left $ nhds_within_mono _ hst) (h.eventually_eq_of_mem self_mem_nhds_within) end lemma function.left_inverse.closed_range [t2_space α] {f : α → β} {g : β → α} (h : function.left_inverse f g) (hf : continuous f) (hg : continuous g) : is_closed (range g) := have eq_on (g ∘ f) id (closure $ range g), from h.right_inv_on_range.eq_on.closure (hg.comp hf) continuous_id, is_closed_of_closure_subset $ λ x hx, calc x = g (f x) : (this hx).symm ... ∈ _ : mem_range_self _ lemma function.left_inverse.closed_embedding [t2_space α] {f : α → β} {g : β → α} (h : function.left_inverse f g) (hf : continuous f) (hg : continuous g) : closed_embedding g := ⟨h.embedding hf hg, h.closed_range hf hg⟩ lemma is_compact_is_compact_separated [t2_space α] {s t : set α} (hs : is_compact s) (ht : is_compact t) (hst : disjoint s t) : separated_nhds s t := by simp only [separated_nhds, prod_subset_compl_diagonal_iff_disjoint.symm] at ⊢ hst; exact generalized_tube_lemma hs ht is_closed_diagonal.is_open_compl hst /-- In a `t2_space`, every compact set is closed. -/ lemma is_compact.is_closed [t2_space α] {s : set α} (hs : is_compact s) : is_closed s := is_open_compl_iff.1 $ is_open_iff_forall_mem_open.mpr $ assume x hx, let ⟨u, v, uo, vo, su, xv, uv⟩ := is_compact_is_compact_separated hs is_compact_singleton (disjoint_singleton_right.2 hx) in ⟨v, (uv.mono_left $ show s ≤ u, from su).subset_compl_left, vo, by simpa using xv⟩ @[simp] lemma filter.coclosed_compact_eq_cocompact [t2_space α] : coclosed_compact α = cocompact α := by simp [coclosed_compact, cocompact, infi_and', and_iff_right_of_imp is_compact.is_closed] @[simp] lemma bornology.relatively_compact_eq_in_compact [t2_space α] : bornology.relatively_compact α = bornology.in_compact α := by rw bornology.ext_iff; exact filter.coclosed_compact_eq_cocompact /-- If `V : ι → set α` is a decreasing family of compact sets then any neighborhood of `⋂ i, V i` contains some `V i`. This is a version of `exists_subset_nhd_of_compact'` where we don't need to assume each `V i` closed because it follows from compactness since `α` is assumed to be Hausdorff. -/ lemma exists_subset_nhds_of_is_compact [t2_space α] {ι : Type*} [nonempty ι] {V : ι → set α} (hV : directed (⊇) V) (hV_cpct : ∀ i, is_compact (V i)) {U : set α} (hU : ∀ x ∈ ⋂ i, V i, U ∈ 𝓝 x) : ∃ i, V i ⊆ U := exists_subset_nhds_of_is_compact' hV hV_cpct (λ i, (hV_cpct i).is_closed) hU lemma compact_exhaustion.is_closed [t2_space α] (K : compact_exhaustion α) (n : ℕ) : is_closed (K n) := (K.is_compact n).is_closed lemma is_compact.inter [t2_space α] {s t : set α} (hs : is_compact s) (ht : is_compact t) : is_compact (s ∩ t) := hs.inter_right $ ht.is_closed lemma is_compact_closure_of_subset_compact [t2_space α] {s t : set α} (ht : is_compact t) (h : s ⊆ t) : is_compact (closure s) := is_compact_of_is_closed_subset ht is_closed_closure (closure_minimal h ht.is_closed) @[simp] lemma exists_compact_superset_iff [t2_space α] {s : set α} : (∃ K, is_compact K ∧ s ⊆ K) ↔ is_compact (closure s) := ⟨λ ⟨K, hK, hsK⟩, is_compact_closure_of_subset_compact hK hsK, λ h, ⟨closure s, h, subset_closure⟩⟩ lemma image_closure_of_is_compact [t2_space β] {s : set α} (hs : is_compact (closure s)) {f : α → β} (hf : continuous_on f (closure s)) : f '' closure s = closure (f '' s) := subset.antisymm hf.image_closure $ closure_minimal (image_subset f subset_closure) (hs.image_of_continuous_on hf).is_closed /-- If a compact set is covered by two open sets, then we can cover it by two compact subsets. -/ lemma is_compact.binary_compact_cover [t2_space α] {K U V : set α} (hK : is_compact K) (hU : is_open U) (hV : is_open V) (h2K : K ⊆ U ∪ V) : ∃ K₁ K₂ : set α, is_compact K₁ ∧ is_compact K₂ ∧ K₁ ⊆ U ∧ K₂ ⊆ V ∧ K = K₁ ∪ K₂ := begin obtain ⟨O₁, O₂, h1O₁, h1O₂, h2O₁, h2O₂, hO⟩ := is_compact_is_compact_separated (hK.diff hU) (hK.diff hV) (by rwa [disjoint_iff_inter_eq_empty, diff_inter_diff, diff_eq_empty]), exact ⟨_, _, hK.diff h1O₁, hK.diff h1O₂, by rwa [diff_subset_comm], by rwa [diff_subset_comm], by rw [← diff_inter, hO.inter_eq, diff_empty]⟩ end lemma continuous.is_closed_map [compact_space α] [t2_space β] {f : α → β} (h : continuous f) : is_closed_map f := λ s hs, (hs.is_compact.image h).is_closed lemma continuous.closed_embedding [compact_space α] [t2_space β] {f : α → β} (h : continuous f) (hf : function.injective f) : closed_embedding f := closed_embedding_of_continuous_injective_closed h hf h.is_closed_map section open finset function /-- For every finite open cover `Uᵢ` of a compact set, there exists a compact cover `Kᵢ ⊆ Uᵢ`. -/ lemma is_compact.finite_compact_cover [t2_space α] {s : set α} (hs : is_compact s) {ι} (t : finset ι) (U : ι → set α) (hU : ∀ i ∈ t, is_open (U i)) (hsC : s ⊆ ⋃ i ∈ t, U i) : ∃ K : ι → set α, (∀ i, is_compact (K i)) ∧ (∀i, K i ⊆ U i) ∧ s = ⋃ i ∈ t, K i := begin classical, induction t using finset.induction with x t hx ih generalizing U hU s hs hsC, { refine ⟨λ _, ∅, λ i, is_compact_empty, λ i, empty_subset _, _⟩, simpa only [subset_empty_iff, Union_false, Union_empty] using hsC }, simp only [finset.set_bUnion_insert] at hsC, simp only [finset.mem_insert] at hU, have hU' : ∀ i ∈ t, is_open (U i) := λ i hi, hU i (or.inr hi), rcases hs.binary_compact_cover (hU x (or.inl rfl)) (is_open_bUnion hU') hsC with ⟨K₁, K₂, h1K₁, h1K₂, h2K₁, h2K₂, hK⟩, rcases ih U hU' h1K₂ h2K₂ with ⟨K, h1K, h2K, h3K⟩, refine ⟨update K x K₁, _, _, _⟩, { intros i, by_cases hi : i = x, { simp only [update_same, hi, h1K₁] }, { rw [← ne.def] at hi, simp only [update_noteq hi, h1K] }}, { intros i, by_cases hi : i = x, { simp only [update_same, hi, h2K₁] }, { rw [← ne.def] at hi, simp only [update_noteq hi, h2K] }}, { simp only [set_bUnion_insert_update _ hx, hK, h3K] } end end lemma locally_compact_of_compact_nhds [t2_space α] (h : ∀ x : α, ∃ s, s ∈ 𝓝 x ∧ is_compact s) : locally_compact_space α := ⟨assume x n hn, let ⟨u, un, uo, xu⟩ := mem_nhds_iff.mp hn in let ⟨k, kx, kc⟩ := h x in -- K is compact but not necessarily contained in N. -- K \ U is again compact and doesn't contain x, so -- we may find open sets V, W separating x from K \ U. -- Then K \ W is a compact neighborhood of x contained in U. let ⟨v, w, vo, wo, xv, kuw, vw⟩ := is_compact_is_compact_separated is_compact_singleton (kc.diff uo) (disjoint_singleton_left.2 $ λ h, h.2 xu) in have wn : wᶜ ∈ 𝓝 x, from mem_nhds_iff.mpr ⟨v, vw.subset_compl_right, vo, singleton_subset_iff.mp xv⟩, ⟨k \ w, filter.inter_mem kx wn, subset.trans (diff_subset_comm.mp kuw) un, kc.diff wo⟩⟩ @[priority 100] -- see Note [lower instance priority] instance locally_compact_of_compact [t2_space α] [compact_space α] : locally_compact_space α := locally_compact_of_compact_nhds (assume x, ⟨univ, is_open_univ.mem_nhds trivial, is_compact_univ⟩) /-- In a locally compact T₂ space, every point has an open neighborhood with compact closure -/ lemma exists_open_with_compact_closure [locally_compact_space α] [t2_space α] (x : α) : ∃ (U : set α), is_open U ∧ x ∈ U ∧ is_compact (closure U) := begin rcases exists_compact_mem_nhds x with ⟨K, hKc, hxK⟩, rcases mem_nhds_iff.1 hxK with ⟨t, h1t, h2t, h3t⟩, exact ⟨t, h2t, h3t, is_compact_closure_of_subset_compact hKc h1t⟩ end /-- In a locally compact T₂ space, every compact set has an open neighborhood with compact closure. -/ lemma exists_open_superset_and_is_compact_closure [locally_compact_space α] [t2_space α] {K : set α} (hK : is_compact K) : ∃ V, is_open V ∧ K ⊆ V ∧ is_compact (closure V) := begin rcases exists_compact_superset hK with ⟨K', hK', hKK'⟩, refine ⟨interior K', is_open_interior, hKK', is_compact_closure_of_subset_compact hK' interior_subset⟩, end /-- In a locally compact T₂ space, given a compact set `K` inside an open set `U`, we can find a open set `V` between these sets with compact closure: `K ⊆ V` and the closure of `V` is inside `U`. -/ lemma exists_open_between_and_is_compact_closure [locally_compact_space α] [t2_space α] {K U : set α} (hK : is_compact K) (hU : is_open U) (hKU : K ⊆ U) : ∃ V, is_open V ∧ K ⊆ V ∧ closure V ⊆ U ∧ is_compact (closure V) := begin rcases exists_compact_between hK hU hKU with ⟨V, hV, hKV, hVU⟩, exact ⟨interior V, is_open_interior, hKV, (closure_minimal interior_subset hV.is_closed).trans hVU, is_compact_closure_of_subset_compact hV interior_subset⟩, end lemma is_preirreducible_iff_subsingleton [t2_space α] {S : set α} : is_preirreducible S ↔ S.subsingleton := begin refine ⟨λ h x hx y hy, _, set.subsingleton.is_preirreducible⟩, by_contradiction e, obtain ⟨U, V, hU, hV, hxU, hyV, h'⟩ := t2_separation e, exact ((h U V hU hV ⟨x, hx, hxU⟩ ⟨y, hy, hyV⟩).mono $ inter_subset_right _ _).not_disjoint h', end alias is_preirreducible_iff_subsingleton ↔ is_preirreducible.subsingleton _ attribute [protected] is_preirreducible.subsingleton lemma is_irreducible_iff_singleton [t2_space α] {S : set α} : is_irreducible S ↔ ∃ x, S = {x} := by rw [is_irreducible, is_preirreducible_iff_subsingleton, exists_eq_singleton_iff_nonempty_subsingleton] /-- There does not exist a nontrivial preirreducible T₂ space. -/ lemma not_preirreducible_nontrivial_t2 (α) [topological_space α] [preirreducible_space α] [nontrivial α] [t2_space α] : false := (preirreducible_space.is_preirreducible_univ α).subsingleton.not_nontrivial nontrivial_univ end separation section regular_space /-- A topological space is called a *regular space* if for any closed set `s` and `a ∉ s`, there exist disjoint open sets `U ⊇ s` and `V ∋ a`. We formulate this condition in terms of `disjoint`ness of filters `𝓝ˢ s` and `𝓝 a`. -/ @[mk_iff] class regular_space (X : Type u) [topological_space X] : Prop := (regular : ∀ {s : set X} {a}, is_closed s → a ∉ s → disjoint (𝓝ˢ s) (𝓝 a)) lemma regular_space_tfae (X : Type u) [topological_space X] : tfae [regular_space X, ∀ (s : set X) (a ∉ closure s), disjoint (𝓝ˢ s) (𝓝 a), ∀ (a : X) (s : set X), disjoint (𝓝ˢ s) (𝓝 a) ↔ a ∉ closure s, ∀ (a : X) (s ∈ 𝓝 a), ∃ t ∈ 𝓝 a, is_closed t ∧ t ⊆ s, ∀ a : X, (𝓝 a).lift' closure ≤ 𝓝 a, ∀ a : X, (𝓝 a).lift' closure = 𝓝 a] := begin tfae_have : 1 ↔ 5, { rw [regular_space_iff, (@compl_surjective (set X) _).forall, forall_swap], simp only [is_closed_compl_iff, mem_compl_iff, not_not, @and_comm (_ ∈ _), (nhds_basis_opens _).lift'_closure.le_basis_iff (nhds_basis_opens _), and_imp, (nhds_basis_opens _).disjoint_iff_right, exists_prop, ← subset_interior_iff_mem_nhds_set, interior_compl, compl_subset_compl] }, tfae_have : 5 → 6, from λ h a, (h a).antisymm (𝓝 _).le_lift'_closure, tfae_have : 6 → 4, { intros H a s hs, rw [← H] at hs, rcases (𝓝 a).basis_sets.lift'_closure.mem_iff.mp hs with ⟨U, hU, hUs⟩, exact ⟨closure U, mem_of_superset hU subset_closure, is_closed_closure, hUs⟩ }, tfae_have : 4 → 2, { intros H s a ha, have ha' : sᶜ ∈ 𝓝 a, by rwa [← mem_interior_iff_mem_nhds, interior_compl], rcases H _ _ ha' with ⟨U, hU, hUc, hUs⟩, refine disjoint_of_disjoint_of_mem disjoint_compl_left _ hU, rwa [← subset_interior_iff_mem_nhds_set, hUc.is_open_compl.interior_eq, subset_compl_comm] }, tfae_have : 2 → 3, { refine λ H a s, ⟨λ hd has, mem_closure_iff_nhds_ne_bot.mp has _, H s a⟩, exact (hd.symm.mono_right $ @principal_le_nhds_set _ _ s).eq_bot }, tfae_have : 3 → 1, from λ H, ⟨λ s a hs ha, (H _ _).mpr $ hs.closure_eq.symm ▸ ha⟩, tfae_finish end lemma regular_space.of_lift'_closure (h : ∀ a : α, (𝓝 a).lift' closure = 𝓝 a) : regular_space α := iff.mpr ((regular_space_tfae α).out 0 5) h lemma regular_space.of_basis {ι : α → Sort*} {p : Π a, ι a → Prop} {s : Π a, ι a → set α} (h₁ : ∀ a, (𝓝 a).has_basis (p a) (s a)) (h₂ : ∀ a i, p a i → is_closed (s a i)) : regular_space α := regular_space.of_lift'_closure $ λ a, (h₁ a).lift'_closure_eq_self (h₂ a) lemma regular_space.of_exists_mem_nhds_is_closed_subset (h : ∀ (a : α) (s ∈ 𝓝 a), ∃ t ∈ 𝓝 a, is_closed t ∧ t ⊆ s) : regular_space α := iff.mpr ((regular_space_tfae α).out 0 3) h variables [regular_space α] {a : α} {s : set α} lemma disjoint_nhds_set_nhds : disjoint (𝓝ˢ s) (𝓝 a) ↔ a ∉ closure s := iff.mp ((regular_space_tfae α).out 0 2) ‹_› _ _ lemma disjoint_nhds_nhds_set : disjoint (𝓝 a) (𝓝ˢ s) ↔ a ∉ closure s := disjoint.comm.trans disjoint_nhds_set_nhds lemma exists_mem_nhds_is_closed_subset {a : α} {s : set α} (h : s ∈ 𝓝 a) : ∃ t ∈ 𝓝 a, is_closed t ∧ t ⊆ s := iff.mp ((regular_space_tfae α).out 0 3) ‹_› _ _ h lemma closed_nhds_basis (a : α) : (𝓝 a).has_basis (λ s : set α, s ∈ 𝓝 a ∧ is_closed s) id := has_basis_self.2 (λ _, exists_mem_nhds_is_closed_subset) lemma lift'_nhds_closure (a : α) : (𝓝 a).lift' closure = 𝓝 a := (closed_nhds_basis a).lift'_closure_eq_self (λ s hs, hs.2) lemma filter.has_basis.nhds_closure {ι : Sort*} {a : α} {p : ι → Prop} {s : ι → set α} (h : (𝓝 a).has_basis p s) : (𝓝 a).has_basis p (λ i, closure (s i)) := lift'_nhds_closure a ▸ h.lift'_closure lemma has_basis_nhds_closure (a : α) : (𝓝 a).has_basis (λ s, s ∈ 𝓝 a) closure := (𝓝 a).basis_sets.nhds_closure lemma has_basis_opens_closure (a : α) : (𝓝 a).has_basis (λ s, a ∈ s ∧ is_open s) closure := (nhds_basis_opens a).nhds_closure lemma topological_space.is_topological_basis.nhds_basis_closure {B : set (set α)} (hB : topological_space.is_topological_basis B) (a : α) : (𝓝 a).has_basis (λ s : set α, a ∈ s ∧ s ∈ B) closure := by simpa only [and_comm] using hB.nhds_has_basis.nhds_closure lemma topological_space.is_topological_basis.exists_closure_subset {B : set (set α)} (hB : topological_space.is_topological_basis B) {a : α} {s : set α} (h : s ∈ 𝓝 a) : ∃ t ∈ B, a ∈ t ∧ closure t ⊆ s := by simpa only [exists_prop, and.assoc] using hB.nhds_has_basis.nhds_closure.mem_iff.mp h lemma disjoint_nhds_nhds_iff_not_specializes {a b : α} : disjoint (𝓝 a) (𝓝 b) ↔ ¬a ⤳ b := by rw [← nhds_set_singleton, disjoint_nhds_set_nhds, specializes_iff_mem_closure] lemma specializes_comm {a b : α} : a ⤳ b ↔ b ⤳ a := by simp only [← disjoint_nhds_nhds_iff_not_specializes.not_left, disjoint.comm] alias specializes_comm ↔ specializes.symm _ lemma specializes_iff_inseparable {a b : α} : a ⤳ b ↔ inseparable a b := ⟨λ h, h.antisymm h.symm, le_of_eq⟩ lemma is_closed_set_of_specializes : is_closed {p : α × α | p.1 ⤳ p.2} := by simp only [← is_open_compl_iff, compl_set_of, ← disjoint_nhds_nhds_iff_not_specializes, is_open_set_of_disjoint_nhds_nhds] lemma is_closed_set_of_inseparable : is_closed {p : α × α | inseparable p.1 p.2} := by simp only [← specializes_iff_inseparable, is_closed_set_of_specializes] protected lemma inducing.regular_space [topological_space β] {f : β → α} (hf : inducing f) : regular_space β := regular_space.of_basis (λ b, by { rw [hf.nhds_eq_comap b], exact (closed_nhds_basis _).comap _ }) $ λ b s hs, hs.2.preimage hf.continuous lemma regular_space_induced (f : β → α) : @regular_space β (induced f ‹_›) := by { letI := induced f ‹_›, exact inducing.regular_space ⟨rfl⟩ } lemma regular_space_Inf {X} {T : set (topological_space X)} (h : ∀ t ∈ T, @regular_space X t) : @regular_space X (Inf T) := begin letI := Inf T, have : ∀ a, (𝓝 a).has_basis (λ If : Σ I : set T, I → set X, If.1.finite ∧ ∀ i : If.1, If.2 i ∈ @nhds X i a ∧ is_closed[↑i] (If.2 i)) (λ If, ⋂ i : If.1, If.snd i), { intro a, rw [nhds_Inf, ← infi_subtype''], exact has_basis_infi (λ t : T, @closed_nhds_basis X t (h t t.2) a) }, refine regular_space.of_basis this (λ a If hIf, is_closed_Inter $ λ i, _), exact (hIf.2 i).2.mono (Inf_le (i : T).2) end lemma regular_space_infi {ι X} {t : ι → topological_space X} (h : ∀ i, @regular_space X (t i)) : @regular_space X (infi t) := regular_space_Inf $ forall_range_iff.mpr h lemma regular_space.inf {X} {t₁ t₂ : topological_space X} (h₁ : @regular_space X t₁) (h₂ : @regular_space X t₂) : @regular_space X (t₁ ⊓ t₂) := by { rw [inf_eq_infi], exact regular_space_infi (bool.forall_bool.2 ⟨h₂, h₁⟩) } instance {p : α → Prop} : regular_space (subtype p) := embedding_subtype_coe.to_inducing.regular_space instance [topological_space β] [regular_space β] : regular_space (α × β) := (regular_space_induced prod.fst).inf (regular_space_induced prod.snd) instance {ι : Type*} {π : ι → Type*} [Π i, topological_space (π i)] [∀ i, regular_space (π i)] : regular_space (Π i, π i) := regular_space_infi $ λ i, regular_space_induced _ end regular_space section t3 /-- A T₃ space is a T₀ space which is a regular space. Any T₃ space is a T₁ space, a T₂ space, and a T₂.₅ space. -/ class t3_space (α : Type u) [topological_space α] extends t0_space α, regular_space α : Prop @[priority 100] -- see Note [lower instance priority] instance t3_space.t2_5_space [t3_space α] : t2_5_space α := begin refine ⟨λ x y hne, _⟩, rw [lift'_nhds_closure, lift'_nhds_closure], have aux : x ∉ closure {y} ∨ y ∉ closure {x}, from (t0_space_iff_or_not_mem_closure α).mp infer_instance x y hne, wlog H : x ∉ closure ({y} : set α), { refine (this y x hne.symm aux.symm (aux.resolve_left H)).symm }, { rwa [← disjoint_nhds_nhds_set, nhds_set_singleton] at H }, end protected lemma embedding.t3_space [topological_space β] [t3_space β] {f : α → β} (hf : embedding f) : t3_space α := { to_t0_space := hf.t0_space, to_regular_space := hf.to_inducing.regular_space } instance subtype.t3_space [t3_space α] {p : α → Prop} : t3_space (subtype p) := embedding_subtype_coe.t3_space instance [topological_space β] [t3_space α] [t3_space β] : t3_space (α × β) := ⟨⟩ instance {ι : Type*} {π : ι → Type*} [Π i, topological_space (π i)] [Π i, t3_space (π i)] : t3_space (Π i, π i) := ⟨⟩ /-- Given two points `x ≠ y`, we can find neighbourhoods `x ∈ V₁ ⊆ U₁` and `y ∈ V₂ ⊆ U₂`, with the `Vₖ` closed and the `Uₖ` open, such that the `Uₖ` are disjoint. -/ lemma disjoint_nested_nhds [t3_space α] {x y : α} (h : x ≠ y) : ∃ (U₁ V₁ ∈ 𝓝 x) (U₂ V₂ ∈ 𝓝 y), is_closed V₁ ∧ is_closed V₂ ∧ is_open U₁ ∧ is_open U₂ ∧ V₁ ⊆ U₁ ∧ V₂ ⊆ U₂ ∧ disjoint U₁ U₂ := begin rcases t2_separation h with ⟨U₁, U₂, U₁_op, U₂_op, x_in, y_in, H⟩, rcases exists_mem_nhds_is_closed_subset (U₁_op.mem_nhds x_in) with ⟨V₁, V₁_in, V₁_closed, h₁⟩, rcases exists_mem_nhds_is_closed_subset (U₂_op.mem_nhds y_in) with ⟨V₂, V₂_in, V₂_closed, h₂⟩, exact ⟨U₁, mem_of_superset V₁_in h₁, V₁, V₁_in, U₂, mem_of_superset V₂_in h₂, V₂, V₂_in, V₁_closed, V₂_closed, U₁_op, U₂_op, h₁, h₂, H⟩ end open separation_quotient /-- The `separation_quotient` of a regular space is a T₃ space. -/ instance [regular_space α] : t3_space (separation_quotient α) := { regular := λ s, surjective_mk.forall.2 $ λ a hs ha, by { rw [← disjoint_comap_iff surjective_mk, comap_mk_nhds_mk, comap_mk_nhds_set], exact regular_space.regular (hs.preimage continuous_mk) ha } } end t3 section normality /-- A T₄ space, also known as a normal space (although this condition sometimes omits T₂), is one in which for every pair of disjoint closed sets `C` and `D`, there exist disjoint open sets containing `C` and `D` respectively. -/ class normal_space (α : Type u) [topological_space α] extends t1_space α : Prop := (normal : ∀ s t : set α, is_closed s → is_closed t → disjoint s t → separated_nhds s t) theorem normal_separation [normal_space α] {s t : set α} (H1 : is_closed s) (H2 : is_closed t) (H3 : disjoint s t) : separated_nhds s t := normal_space.normal s t H1 H2 H3 theorem normal_exists_closure_subset [normal_space α] {s t : set α} (hs : is_closed s) (ht : is_open t) (hst : s ⊆ t) : ∃ u, is_open u ∧ s ⊆ u ∧ closure u ⊆ t := begin have : disjoint s tᶜ, from set.disjoint_left.mpr (λ x hxs hxt, hxt (hst hxs)), rcases normal_separation hs (is_closed_compl_iff.2 ht) this with ⟨s', t', hs', ht', hss', htt', hs't'⟩, refine ⟨s', hs', hss', subset.trans (closure_minimal _ (is_closed_compl_iff.2 ht')) (compl_subset_comm.1 htt')⟩, exact λ x hxs hxt, hs't'.le_bot ⟨hxs, hxt⟩ end @[priority 100] -- see Note [lower instance priority] instance normal_space.t3_space [normal_space α] : t3_space α := { regular := λ s x hs hxs, let ⟨u, v, hu, hv, hsu, hxv, huv⟩ := normal_separation hs is_closed_singleton (disjoint_singleton_right.mpr hxs) in disjoint_of_disjoint_of_mem huv (hu.mem_nhds_set.2 hsu) (hv.mem_nhds $ hxv rfl) } -- We can't make this an instance because it could cause an instance loop. lemma normal_of_compact_t2 [compact_space α] [t2_space α] : normal_space α := ⟨λ s t hs ht, is_compact_is_compact_separated hs.is_compact ht.is_compact⟩ protected lemma closed_embedding.normal_space [topological_space β] [normal_space β] {f : α → β} (hf : closed_embedding f) : normal_space α := { to_t1_space := hf.to_embedding.t1_space, normal := begin intros s t hs ht hst, have H : separated_nhds (f '' s) (f '' t), from normal_space.normal (f '' s) (f '' t) (hf.is_closed_map s hs) (hf.is_closed_map t ht) (disjoint_image_of_injective hf.inj hst), exact (H.preimage hf.continuous).mono (subset_preimage_image _ _) (subset_preimage_image _ _) end } namespace separation_quotient /-- The `separation_quotient` of a normal space is a T₄ space. We don't have separate typeclasses for normal spaces (without T₁ assumption) and T₄ spaces, so we use the same class for assumption and for conclusion. One can prove this using a homeomorphism between `α` and `separation_quotient α`. We give an alternative proof that works without assuming that `α` is a T₁ space. -/ instance [normal_space α] : normal_space (separation_quotient α) := { normal := λ s t hs ht hd, separated_nhds_iff_disjoint.2 $ begin rw [← disjoint_comap_iff surjective_mk, comap_mk_nhds_set, comap_mk_nhds_set], exact separated_nhds_iff_disjoint.1 (normal_separation (hs.preimage continuous_mk) (ht.preimage continuous_mk) (hd.preimage mk)) end } end separation_quotient variable (α) /-- A T₃ topological space with second countable topology is a normal space. This lemma is not an instance to avoid a loop. -/ lemma normal_space_of_t3_second_countable [second_countable_topology α] [t3_space α] : normal_space α := begin have key : ∀ {s t : set α}, is_closed t → disjoint s t → ∃ U : set (countable_basis α), (s ⊆ ⋃ u ∈ U, ↑u) ∧ (∀ u ∈ U, disjoint (closure ↑u) t) ∧ ∀ n : ℕ, is_closed (⋃ (u ∈ U) (h : encodable.encode u ≤ n), closure (u : set α)), { intros s t hc hd, rw disjoint_left at hd, have : ∀ x ∈ s, ∃ U ∈ countable_basis α, x ∈ U ∧ disjoint (closure U) t, { intros x hx, rcases (is_basis_countable_basis α).exists_closure_subset (hc.is_open_compl.mem_nhds (hd hx)) with ⟨u, hu, hxu, hut⟩, exact ⟨u, hu, hxu, disjoint_left.2 hut⟩ }, choose! U hu hxu hd, set V : s → countable_basis α := maps_to.restrict _ _ _ hu, refine ⟨range V, _, forall_range_iff.2 $ subtype.forall.2 hd, λ n, _⟩, { rw bUnion_range, exact λ x hx, mem_Union.2 ⟨⟨x, hx⟩, hxu x hx⟩ }, { simp only [← supr_eq_Union, supr_and'], exact is_closed_bUnion (((finite_le_nat n).preimage_embedding (encodable.encode' _)).subset $ inter_subset_right _ _) (λ u hu, is_closed_closure) } }, refine ⟨λ s t hs ht hd, _⟩, rcases key ht hd with ⟨U, hsU, hUd, hUc⟩, rcases key hs hd.symm with ⟨V, htV, hVd, hVc⟩, refine ⟨⋃ u ∈ U, ↑u \ ⋃ (v ∈ V) (hv : encodable.encode v ≤ encodable.encode u), closure ↑v, ⋃ v ∈ V, ↑v \ ⋃ (u ∈ U) (hu : encodable.encode u ≤ encodable.encode v), closure ↑u, is_open_bUnion $ λ u hu, (is_open_of_mem_countable_basis u.2).sdiff (hVc _), is_open_bUnion $ λ v hv, (is_open_of_mem_countable_basis v.2).sdiff (hUc _), λ x hx, _, λ x hx, _, _⟩, { rcases mem_Union₂.1 (hsU hx) with ⟨u, huU, hxu⟩, refine mem_bUnion huU ⟨hxu, _⟩, simp only [mem_Union], rintro ⟨v, hvV, -, hxv⟩, exact (hVd v hvV).le_bot ⟨hxv, hx⟩ }, { rcases mem_Union₂.1 (htV hx) with ⟨v, hvV, hxv⟩, refine mem_bUnion hvV ⟨hxv, _⟩, simp only [mem_Union], rintro ⟨u, huU, -, hxu⟩, exact (hUd u huU).le_bot ⟨hxu, hx⟩ }, { simp only [disjoint_left, mem_Union, mem_diff, not_exists, not_and, not_forall, not_not], rintro a ⟨u, huU, hau, haV⟩ v hvV hav, cases le_total (encodable.encode u) (encodable.encode v) with hle hle, exacts [⟨u, huU, hle, subset_closure hau⟩, (haV _ hvV hle $ subset_closure hav).elim] } end end normality section completely_normal /-- A topological space `α` is a *completely normal Hausdorff space* if each subspace `s : set α` is a normal Hausdorff space. Equivalently, `α` is a `T₁` space and for any two sets `s`, `t` such that `closure s` is disjoint with `t` and `s` is disjoint with `closure t`, there exist disjoint neighbourhoods of `s` and `t`. -/ class t5_space (α : Type u) [topological_space α] extends t1_space α : Prop := (completely_normal : ∀ ⦃s t : set α⦄, disjoint (closure s) t → disjoint s (closure t) → disjoint (𝓝ˢ s) (𝓝ˢ t)) export t5_space (completely_normal) lemma embedding.t5_space [topological_space β] [t5_space β] {e : α → β} (he : embedding e) : t5_space α := begin haveI := he.t1_space, refine ⟨λ s t hd₁ hd₂, _⟩, simp only [he.to_inducing.nhds_set_eq_comap], refine disjoint_comap (completely_normal _ _), { rwa [← subset_compl_iff_disjoint_left, image_subset_iff, preimage_compl, ← he.closure_eq_preimage_closure_image, subset_compl_iff_disjoint_left] }, { rwa [← subset_compl_iff_disjoint_right, image_subset_iff, preimage_compl, ← he.closure_eq_preimage_closure_image, subset_compl_iff_disjoint_right] } end /-- A subspace of a `T₅` space is a `T₅` space. -/ instance [t5_space α] {p : α → Prop} : t5_space {x // p x} := embedding_subtype_coe.t5_space /-- A `T₅` space is a `T₄` space. -/ @[priority 100] -- see Note [lower instance priority] instance t5_space.to_normal_space [t5_space α] : normal_space α := ⟨λ s t hs ht hd, separated_nhds_iff_disjoint.2 $ completely_normal (by rwa [hs.closure_eq]) (by rwa [ht.closure_eq])⟩ open separation_quotient /-- The `separation_quotient` of a completely normal space is a T₅ space. We don't have separate typeclasses for completely normal spaces (without T₁ assumption) and T₅ spaces, so we use the same class for assumption and for conclusion. One can prove this using a homeomorphism between `α` and `separation_quotient α`. We give an alternative proof that works without assuming that `α` is a T₁ space. -/ instance [t5_space α] : t5_space (separation_quotient α) := { completely_normal := λ s t hd₁ hd₂, begin rw [← disjoint_comap_iff surjective_mk, comap_mk_nhds_set, comap_mk_nhds_set], apply t5_space.completely_normal; rw [← preimage_mk_closure], exacts [hd₁.preimage mk, hd₂.preimage mk] end } end completely_normal /-- In a compact t2 space, the connected component of a point equals the intersection of all its clopen neighbourhoods. -/ lemma connected_component_eq_Inter_clopen [t2_space α] [compact_space α] (x : α) : connected_component x = ⋂ Z : {Z : set α // is_clopen Z ∧ x ∈ Z}, Z := begin apply eq_of_subset_of_subset connected_component_subset_Inter_clopen, -- Reduce to showing that the clopen intersection is connected. refine is_preconnected.subset_connected_component _ (mem_Inter.2 (λ Z, Z.2.2)), -- We do this by showing that any disjoint cover by two closed sets implies -- that one of these closed sets must contain our whole thing. -- To reduce to the case where the cover is disjoint on all of `α` we need that `s` is closed have hs : is_closed (⋂ (Z : {Z : set α // is_clopen Z ∧ x ∈ Z}), Z : set α) := is_closed_Inter (λ Z, Z.2.1.2), rw (is_preconnected_iff_subset_of_fully_disjoint_closed hs), intros a b ha hb hab ab_disj, haveI := @normal_of_compact_t2 α _ _ _, -- Since our space is normal, we get two larger disjoint open sets containing the disjoint -- closed sets. If we can show that our intersection is a subset of any of these we can then -- "descend" this to show that it is a subset of either a or b. rcases normal_separation ha hb ab_disj with ⟨u, v, hu, hv, hau, hbv, huv⟩, -- If we can find a clopen set around x, contained in u ∪ v, we get a disjoint decomposition -- Z = Z ∩ u ∪ Z ∩ v of clopen sets. The intersection of all clopen neighbourhoods will then lie -- in whichever of u or v x lies in and hence will be a subset of either a or b. rsuffices ⟨Z, H⟩ : ∃ (Z : set α), is_clopen Z ∧ x ∈ Z ∧ Z ⊆ u ∪ v, { have H1 := is_clopen_inter_of_disjoint_cover_clopen H.1 H.2.2 hu hv huv, rw [union_comm] at H, have H2 := is_clopen_inter_of_disjoint_cover_clopen H.1 H.2.2 hv hu huv.symm, by_cases (x ∈ u), -- The x ∈ u case. { left, suffices : (⋂ (Z : {Z : set α // is_clopen Z ∧ x ∈ Z}), ↑Z) ⊆ u, { replace hab : (⋂ (Z : {Z // is_clopen Z ∧ x ∈ Z}), ↑Z) ≤ a ∪ b := hab, replace this : (⋂ (Z : {Z // is_clopen Z ∧ x ∈ Z}), ↑Z) ≤ u := this, exact disjoint.left_le_of_le_sup_right hab (huv.mono this hbv) }, { apply subset.trans _ (inter_subset_right Z u), apply Inter_subset (λ Z : {Z : set α // is_clopen Z ∧ x ∈ Z}, ↑Z) ⟨Z ∩ u, H1, mem_inter H.2.1 h⟩ } }, -- If x ∉ u, we get x ∈ v since x ∈ u ∪ v. The rest is then like the x ∈ u case. have h1 : x ∈ v, { cases (mem_union x u v).1 (mem_of_subset_of_mem (subset.trans hab (union_subset_union hau hbv)) (mem_Inter.2 (λ i, i.2.2))) with h1 h1, { exfalso, exact h h1}, { exact h1} }, right, suffices : (⋂ (Z : {Z : set α // is_clopen Z ∧ x ∈ Z}), ↑Z) ⊆ v, { replace this : (⋂ (Z : {Z // is_clopen Z ∧ x ∈ Z}), ↑Z) ≤ v := this, exact (huv.symm.mono this hau).left_le_of_le_sup_left hab }, { apply subset.trans _ (inter_subset_right Z v), apply Inter_subset (λ Z : {Z : set α // is_clopen Z ∧ x ∈ Z}, ↑Z) ⟨Z ∩ v, H2, mem_inter H.2.1 h1⟩ } }, -- Now we find the required Z. We utilize the fact that X \ u ∪ v will be compact, -- so there must be some finite intersection of clopen neighbourhoods of X disjoint to it, -- but a finite intersection of clopen sets is clopen so we let this be our Z. have H1 := (hu.union hv).is_closed_compl.is_compact.inter_Inter_nonempty (λ Z : {Z : set α // is_clopen Z ∧ x ∈ Z}, Z) (λ Z, Z.2.1.2), rw [←not_disjoint_iff_nonempty_inter, imp_not_comm, not_forall] at H1, cases H1 (disjoint_compl_left_iff_subset.2 $ hab.trans $ union_subset_union hau hbv) with Zi H2, refine ⟨(⋂ (U ∈ Zi), subtype.val U), _, _, _⟩, { exact is_clopen_bInter_finset (λ Z hZ, Z.2.1) }, { exact mem_Inter₂.2 (λ Z hZ, Z.2.2) }, { rwa [←disjoint_compl_left_iff_subset, disjoint_iff_inter_eq_empty, ←not_nonempty_iff_eq_empty] } end section profinite /-- A T1 space with a clopen basis is totally separated. -/ lemma totally_separated_space_of_t1_of_basis_clopen [t1_space α] (h : is_topological_basis {s : set α | is_clopen s}) : totally_separated_space α := begin constructor, rintros x - y - hxy, rcases h.mem_nhds_iff.mp (is_open_ne.mem_nhds hxy) with ⟨U, hU, hxU, hyU⟩, exact ⟨U, Uᶜ, hU.is_open, hU.compl.is_open, hxU, λ h, hyU h rfl, (union_compl_self U).superset, disjoint_compl_right⟩ end variables [t2_space α] [compact_space α] /-- A compact Hausdorff space is totally disconnected if and only if it is totally separated, this is also true for locally compact spaces. -/ theorem compact_t2_tot_disc_iff_tot_sep : totally_disconnected_space α ↔ totally_separated_space α := begin split, { intro h, constructor, rintros x - y -, contrapose!, intros hyp, suffices : x ∈ connected_component y, by simpa [totally_disconnected_space_iff_connected_component_singleton.1 h y, mem_singleton_iff], rw [connected_component_eq_Inter_clopen, mem_Inter], rintro ⟨w : set α, hw : is_clopen w, hy : y ∈ w⟩, by_contra hx, exact hyp wᶜ w hw.2.is_open_compl hw.1 hx hy (@is_compl_compl _ w _).symm.codisjoint.top_le disjoint_compl_left }, apply totally_separated_space.totally_disconnected_space, end variables [totally_disconnected_space α] lemma nhds_basis_clopen (x : α) : (𝓝 x).has_basis (λ s : set α, x ∈ s ∧ is_clopen s) id := ⟨λ U, begin split, { have : connected_component x = {x}, from totally_disconnected_space_iff_connected_component_singleton.mp ‹_› x, rw connected_component_eq_Inter_clopen at this, intros hU, let N := {Z // is_clopen Z ∧ x ∈ Z}, rsuffices ⟨⟨s, hs, hs'⟩, hs''⟩ : ∃ Z : N, Z.val ⊆ U, { exact ⟨s, ⟨hs', hs⟩, hs''⟩ }, haveI : nonempty N := ⟨⟨univ, is_clopen_univ, mem_univ x⟩⟩, have hNcl : ∀ Z : N, is_closed Z.val := (λ Z, Z.property.1.2), have hdir : directed superset (λ Z : N, Z.val), { rintros ⟨s, hs, hxs⟩ ⟨t, ht, hxt⟩, exact ⟨⟨s ∩ t, hs.inter ht, ⟨hxs, hxt⟩⟩, inter_subset_left s t, inter_subset_right s t⟩ }, have h_nhd: ∀ y ∈ (⋂ Z : N, Z.val), U ∈ 𝓝 y, { intros y y_in, erw [this, mem_singleton_iff] at y_in, rwa y_in }, exact exists_subset_nhds_of_compact_space hdir hNcl h_nhd }, { rintro ⟨V, ⟨hxV, V_op, -⟩, hUV : V ⊆ U⟩, rw mem_nhds_iff, exact ⟨V, hUV, V_op, hxV⟩ } end⟩ lemma is_topological_basis_clopen : is_topological_basis {s : set α | is_clopen s} := begin apply is_topological_basis_of_open_of_nhds (λ U (hU : is_clopen U), hU.1), intros x U hxU U_op, have : U ∈ 𝓝 x, from is_open.mem_nhds U_op hxU, rcases (nhds_basis_clopen x).mem_iff.mp this with ⟨V, ⟨hxV, hV⟩, hVU : V ⊆ U⟩, use V, tauto end /-- Every member of an open set in a compact Hausdorff totally disconnected space is contained in a clopen set contained in the open set. -/ lemma compact_exists_clopen_in_open {x : α} {U : set α} (is_open : is_open U) (memU : x ∈ U) : ∃ (V : set α) (hV : is_clopen V), x ∈ V ∧ V ⊆ U := (is_topological_basis.mem_nhds_iff is_topological_basis_clopen).1 (is_open.mem_nhds memU) end profinite section locally_compact variables {H : Type*} [topological_space H] [locally_compact_space H] [t2_space H] /-- A locally compact Hausdorff totally disconnected space has a basis with clopen elements. -/ lemma loc_compact_Haus_tot_disc_of_zero_dim [totally_disconnected_space H] : is_topological_basis {s : set H | is_clopen s} := begin refine is_topological_basis_of_open_of_nhds (λ u hu, hu.1) _, rintros x U memU hU, obtain ⟨s, comp, xs, sU⟩ := exists_compact_subset hU memU, obtain ⟨t, h, ht, xt⟩ := mem_interior.1 xs, let u : set s := (coe : s → H)⁻¹' (interior s), have u_open_in_s : is_open u := is_open_interior.preimage continuous_subtype_coe, let X : s := ⟨x, h xt⟩, have Xu : X ∈ u := xs, haveI : compact_space s := is_compact_iff_compact_space.1 comp, obtain ⟨V : set s, clopen_in_s, Vx, V_sub⟩ := compact_exists_clopen_in_open u_open_in_s Xu, have V_clopen : is_clopen ((coe : s → H) '' V), { refine ⟨_, (comp.is_closed.closed_embedding_subtype_coe.closed_iff_image_closed).1 clopen_in_s.2⟩, let v : set u := (coe : u → s)⁻¹' V, have : (coe : u → H) = (coe : s → H) ∘ (coe : u → s) := rfl, have f0 : embedding (coe : u → H) := embedding_subtype_coe.comp embedding_subtype_coe, have f1 : open_embedding (coe : u → H), { refine ⟨f0, _⟩, { have : set.range (coe : u → H) = interior s, { rw [this, set.range_comp, subtype.range_coe, subtype.image_preimage_coe], apply set.inter_eq_self_of_subset_left interior_subset, }, rw this, apply is_open_interior } }, have f2 : is_open v := clopen_in_s.1.preimage continuous_subtype_coe, have f3 : (coe : s → H) '' V = (coe : u → H) '' v, { rw [this, image_comp coe coe, subtype.image_preimage_coe, inter_eq_self_of_subset_left V_sub] }, rw f3, apply f1.is_open_map v f2 }, refine ⟨coe '' V, V_clopen, by simp [Vx, h xt], _⟩, transitivity s, { simp }, assumption end /-- A locally compact Hausdorff space is totally disconnected if and only if it is totally separated. -/ theorem loc_compact_t2_tot_disc_iff_tot_sep : totally_disconnected_space H ↔ totally_separated_space H := begin split, { introI h, exact totally_separated_space_of_t1_of_basis_clopen loc_compact_Haus_tot_disc_of_zero_dim }, apply totally_separated_space.totally_disconnected_space, end end locally_compact /-- `connected_components α` is Hausdorff when `α` is Hausdorff and compact -/ instance connected_components.t2 [t2_space α] [compact_space α] : t2_space (connected_components α) := begin -- Proof follows that of: https://stacks.math.columbia.edu/tag/0900 -- Fix 2 distinct connected components, with points a and b refine ⟨connected_components.surjective_coe.forall₂.2 $ λ a b ne, _⟩, rw connected_components.coe_ne_coe at ne, have h := connected_component_disjoint ne, -- write ↑b as the intersection of all clopen subsets containing it rw [connected_component_eq_Inter_clopen b, disjoint_iff_inter_eq_empty] at h, -- Now we show that this can be reduced to some clopen containing `↑b` being disjoint to `↑a` obtain ⟨U, V, hU, ha, hb, rfl⟩ : ∃ (U : set α) (V : set (connected_components α)), is_clopen U ∧ connected_component a ∩ U = ∅ ∧ connected_component b ⊆ U ∧ coe ⁻¹' V = U, { cases is_closed_connected_component.is_compact.elim_finite_subfamily_closed _ _ h with fin_a ha, swap, { exact λ Z, Z.2.1.2 }, -- This clopen and its complement will separate the connected components of `a` and `b` set U : set α := (⋂ (i : {Z // is_clopen Z ∧ b ∈ Z}) (H : i ∈ fin_a), i), have hU : is_clopen U := is_clopen_bInter_finset (λ i j, i.2.1), exact ⟨U, coe '' U, hU, ha, subset_Inter₂ (λ Z _, Z.2.1.connected_component_subset Z.2.2), (connected_components_preimage_image U).symm ▸ hU.bUnion_connected_component_eq⟩ }, rw connected_components.quotient_map_coe.is_clopen_preimage at hU, refine ⟨Vᶜ, V, hU.compl.is_open, hU.is_open, _, hb mem_connected_component, disjoint_compl_left⟩, exact λ h, flip set.nonempty.ne_empty ha ⟨a, mem_connected_component, h⟩, end
4bb31413b3d65130f30e72c4dd595208d30e6457
26bff4ed296b8373c92b6b025f5d60cdf02104b9
/hott/algebra/precategory/iso.hlean
c12309f0554a9431815211b17720b62eb96a4e0a
[ "Apache-2.0" ]
permissive
guiquanz/lean
b8a878ea24f237b84b0e6f6be2f300e8bf028229
242f8ba0486860e53e257c443e965a82ee342db3
refs/heads/master
1,526,680,092,098
1,427,492,833,000
1,427,493,281,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
14,265
hlean
/- Copyright (c) 2015 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Module: algebra.precategory.iso Author: Floris van Doorn, Jakob von Raumer -/ import algebra.precategory.basic types.sigma arity open eq category prod equiv is_equiv sigma sigma.ops is_trunc namespace iso structure split_mono [class] {ob : Type} [C : precategory ob] {a b : ob} (f : a ⟶ b) := {retraction_of : b ⟶ a} (retraction_comp : retraction_of ∘ f = id) structure split_epi [class] {ob : Type} [C : precategory ob] {a b : ob} (f : a ⟶ b) := {section_of : b ⟶ a} (comp_section : f ∘ section_of = id) structure is_iso [class] {ob : Type} [C : precategory ob] {a b : ob} (f : a ⟶ b) := {inverse : b ⟶ a} (left_inverse : inverse ∘ f = id) (right_inverse : f ∘ inverse = id) attribute is_iso.inverse [quasireducible] attribute is_iso [multiple-instances] open split_mono split_epi is_iso definition retraction_of [reducible] := @split_mono.retraction_of definition retraction_comp [reducible] := @split_mono.retraction_comp definition section_of [reducible] := @split_epi.section_of definition comp_section [reducible] := @split_epi.comp_section definition inverse [reducible] := @is_iso.inverse definition left_inverse [reducible] := @is_iso.left_inverse definition right_inverse [reducible] := @is_iso.right_inverse postfix `⁻¹` := inverse --a second notation for the inverse, which is not overloaded postfix [parsing-only] `⁻¹ʰ`:std.prec.max_plus := inverse -- input using \-1h variables {ob : Type} [C : precategory ob] variables {a b c : ob} {g : b ⟶ c} {f : a ⟶ b} {h : b ⟶ a} include C definition split_mono_of_is_iso [instance] [priority 300] [reducible] (f : a ⟶ b) [H : is_iso f] : split_mono f := split_mono.mk !left_inverse definition split_epi_of_is_iso [instance] [priority 300] [reducible] (f : a ⟶ b) [H : is_iso f] : split_epi f := split_epi.mk !right_inverse definition is_iso_id [instance] [priority 500] (a : ob) : is_iso (ID a) := is_iso.mk !id_comp !id_comp definition is_iso_inverse [instance] [priority 200] (f : a ⟶ b) [H : is_iso f] : is_iso f⁻¹ := is_iso.mk !right_inverse !left_inverse definition left_inverse_eq_right_inverse {f : a ⟶ b} {g g' : hom b a} (Hl : g ∘ f = id) (Hr : f ∘ g' = id) : g = g' := by rewrite [-(id_right g), -Hr, assoc, Hl, id_left] definition retraction_eq [H : split_mono f] (H2 : f ∘ h = id) : retraction_of f = h := left_inverse_eq_right_inverse !retraction_comp H2 definition section_eq [H : split_epi f] (H2 : h ∘ f = id) : section_of f = h := (left_inverse_eq_right_inverse H2 !comp_section)⁻¹ definition inverse_eq_right [H : is_iso f] (H2 : f ∘ h = id) : f⁻¹ = h := left_inverse_eq_right_inverse !left_inverse H2 definition inverse_eq_left [H : is_iso f] (H2 : h ∘ f = id) : f⁻¹ = h := (left_inverse_eq_right_inverse H2 !right_inverse)⁻¹ definition retraction_eq_section (f : a ⟶ b) [Hl : split_mono f] [Hr : split_epi f] : retraction_of f = section_of f := retraction_eq !comp_section definition is_iso_of_split_epi_of_split_mono (f : a ⟶ b) [Hl : split_mono f] [Hr : split_epi f] : is_iso f := is_iso.mk ((retraction_eq_section f) ▹ (retraction_comp f)) (comp_section f) definition inverse_unique (H H' : is_iso f) : @inverse _ _ _ _ f H = @inverse _ _ _ _ f H' := inverse_eq_left !left_inverse definition inverse_involutive (f : a ⟶ b) [H : is_iso f] [H : is_iso (f⁻¹)] : (f⁻¹)⁻¹ = f := inverse_eq_right !left_inverse definition retraction_id (a : ob) : retraction_of (ID a) = id := retraction_eq !id_comp definition section_id (a : ob) : section_of (ID a) = id := section_eq !id_comp definition id_inverse (a : ob) [H : is_iso (ID a)] : (ID a)⁻¹ = id := inverse_eq_left !id_comp definition split_mono_comp [instance] [priority 150] (g : b ⟶ c) (f : a ⟶ b) [Hf : split_mono f] [Hg : split_mono g] : split_mono (g ∘ f) := split_mono.mk (show (retraction_of f ∘ retraction_of g) ∘ g ∘ f = id, by rewrite [-assoc, assoc _ g f, retraction_comp, id_left, retraction_comp]) definition split_epi_comp [instance] [priority 150] (g : b ⟶ c) (f : a ⟶ b) [Hf : split_epi f] [Hg : split_epi g] : split_epi (g ∘ f) := split_epi.mk (show (g ∘ f) ∘ section_of f ∘ section_of g = id, by rewrite [-assoc, {f ∘ _}assoc, comp_section, id_left, comp_section]) definition is_iso_comp [instance] [priority 150] (g : b ⟶ c) (f : a ⟶ b) [Hf : is_iso f] [Hg : is_iso g] : is_iso (g ∘ f) := !is_iso_of_split_epi_of_split_mono -- "is_iso f" is equivalent to a certain sigma type -- definition is_iso.sigma_char (f : hom a b) : -- (Σ (g : hom b a), (g ∘ f = id) × (f ∘ g = id)) ≃ is_iso f := -- begin -- fapply equiv.MK, -- {intro S, apply is_iso.mk, -- exact (pr₁ S.2), -- exact (pr₂ S.2)}, -- {intro H, cases H with (g, η, ε), -- exact (sigma.mk g (pair η ε))}, -- {intro H, cases H, apply idp}, -- {intro S, cases S with (g, ηε), cases ηε, apply idp}, -- end definition is_hprop_is_iso [instance] (f : hom a b) : is_hprop (is_iso f) := begin apply is_hprop.mk, intros (H, H'), cases H with (g, li, ri), cases H' with (g', li', ri'), fapply (apD0111 (@is_iso.mk ob C a b f)), apply left_inverse_eq_right_inverse, apply li, apply ri', apply is_hprop.elim, apply is_hprop.elim, end /- iso objects -/ structure iso (a b : ob) := (to_hom : hom a b) [struct : is_iso to_hom] infix `≅`:50 := iso.iso attribute iso.struct [instance] [priority 400] namespace iso attribute to_hom [coercion] definition MK (f : a ⟶ b) (g : b ⟶ a) (H1 : g ∘ f = id) (H2 : f ∘ g = id) := @mk _ _ _ _ f (is_iso.mk H1 H2) definition to_inv (f : a ≅ b) : b ⟶ a := (to_hom f)⁻¹ protected definition refl (a : ob) : a ≅ a := mk (ID a) protected definition symm ⦃a b : ob⦄ (H : a ≅ b) : b ≅ a := mk (to_hom H)⁻¹ protected definition trans ⦃a b c : ob⦄ (H1 : a ≅ b) (H2 : b ≅ c) : a ≅ c := mk (to_hom H2 ∘ to_hom H1) protected definition eq_mk' {f f' : a ⟶ b} [H : is_iso f] [H' : is_iso f'] (p : f = f') : iso.mk f = iso.mk f' := apD011 iso.mk p !is_hprop.elim protected definition eq_mk {f f' : a ≅ b} (p : to_hom f = to_hom f') : f = f' := by (cases f; cases f'; apply (iso.eq_mk' p)) -- The structure for isomorphism can be characterized up to equivalence by a sigma type. definition sigma_char ⦃a b : ob⦄ : (Σ (f : hom a b), is_iso f) ≃ (a ≅ b) := begin fapply (equiv.mk), {intro S, apply iso.mk, apply (S.2)}, {fapply adjointify, {intro p, cases p with (f, H), exact (sigma.mk f H)}, {intro p, cases p, apply idp}, {intro S, cases S, apply idp}}, end end iso -- The type of isomorphisms between two objects is a set definition is_hset_iso [instance] : is_hset (a ≅ b) := begin apply is_trunc_is_equiv_closed, apply (equiv.to_is_equiv (!iso.sigma_char)), end definition iso_of_eq (p : a = b) : a ≅ b := eq.rec_on p (iso.refl a) definition hom_of_eq [reducible] (p : a = b) : a ⟶ b := iso.to_hom (iso_of_eq p) definition inv_of_eq [reducible] (p : a = b) : b ⟶ a := iso.to_inv (iso_of_eq p) definition iso_of_eq_inv (p : a = b) : iso_of_eq p⁻¹ = iso.symm (iso_of_eq p) := eq.rec_on p idp definition iso_of_eq_con (p : a = b) (q : b = c) : iso_of_eq (p ⬝ q) = iso.trans (iso_of_eq p) (iso_of_eq q) := eq.rec_on q (eq.rec_on p (iso.eq_mk !id_comp⁻¹)) section open funext variables {X : Type} {x y : X} {F G : X → ob} definition transport_hom_of_eq (p : F = G) (f : hom (F x) (F y)) : p ▹ f = hom_of_eq (apD10 p y) ∘ f ∘ inv_of_eq (apD10 p x) := eq.rec_on p !id_leftright⁻¹ definition transport_hom (p : F ∼ G) (f : hom (F x) (F y)) : eq_of_homotopy p ▹ f = hom_of_eq (p y) ∘ f ∘ inv_of_eq (p x) := calc eq_of_homotopy p ▹ f = hom_of_eq (apD10 (eq_of_homotopy p) y) ∘ f ∘ inv_of_eq (apD10 (eq_of_homotopy p) x) : transport_hom_of_eq ... = hom_of_eq (p y) ∘ f ∘ inv_of_eq (p x) : {retr apD10 p} end structure mono [class] (f : a ⟶ b) := (elim : ∀c (g h : hom c a), f ∘ g = f ∘ h → g = h) structure epi [class] (f : a ⟶ b) := (elim : ∀c (g h : hom b c), g ∘ f = h ∘ f → g = h) definition mono_of_split_mono [instance] (f : a ⟶ b) [H : split_mono f] : mono f := mono.mk (λ c g h H, calc g = id ∘ g : by rewrite id_left ... = (retraction_of f ∘ f) ∘ g : by rewrite retraction_comp ... = (retraction_of f ∘ f) ∘ h : by rewrite [-assoc, H, -assoc] ... = id ∘ h : by rewrite retraction_comp ... = h : by rewrite id_left) definition epi_of_split_epi [instance] (f : a ⟶ b) [H : split_epi f] : epi f := epi.mk (λ c g h H, calc g = g ∘ id : by rewrite id_right ... = g ∘ f ∘ section_of f : by rewrite -comp_section ... = h ∘ f ∘ section_of f : by rewrite [assoc, H, -assoc] ... = h ∘ id : by rewrite comp_section ... = h : by rewrite id_right) definition mono_comp [instance] (g : b ⟶ c) (f : a ⟶ b) [Hf : mono f] [Hg : mono g] : mono (g ∘ f) := mono.mk (λ d h₁ h₂ H, have H2 : g ∘ (f ∘ h₁) = g ∘ (f ∘ h₂), begin rewrite *assoc, exact H end, !mono.elim (!mono.elim H2)) definition epi_comp [instance] (g : b ⟶ c) (f : a ⟶ b) [Hf : epi f] [Hg : epi g] : epi (g ∘ f) := epi.mk (λ d h₁ h₂ H, have H2 : (h₁ ∘ g) ∘ f = (h₂ ∘ g) ∘ f, begin rewrite -*assoc, exact H end, !epi.elim (!epi.elim H2)) end iso namespace iso /- rewrite lemmas for inverses, modified from https://github.com/JasonGross/HoTT-categories/blob/master/theories/Categories/Category/Morphisms.v -/ section variables {ob : Type} [C : precategory ob] include C variables {a b c d : ob} (f : b ⟶ a) (r : c ⟶ d) (q : b ⟶ c) (p : a ⟶ b) (g : d ⟶ c) variable [Hq : is_iso q] include Hq definition comp.right_inverse : q ∘ q⁻¹ = id := !right_inverse definition comp.left_inverse : q⁻¹ ∘ q = id := !left_inverse definition inverse_comp_cancel_left : q⁻¹ ∘ (q ∘ p) = p := by rewrite [assoc, left_inverse, id_left] definition comp_inverse_cancel_left : q ∘ (q⁻¹ ∘ g) = g := by rewrite [assoc, right_inverse, id_left] definition comp_inverse_cancel_right : (r ∘ q) ∘ q⁻¹ = r := by rewrite [-assoc, right_inverse, id_right] definition inverse_comp_cancel_right : (f ∘ q⁻¹) ∘ q = f := by rewrite [-assoc, left_inverse, id_right] definition comp_inverse [Hp : is_iso p] [Hpq : is_iso (q ∘ p)] : (q ∘ p)⁻¹ʰ = p⁻¹ʰ ∘ q⁻¹ʰ := inverse_eq_left (show (p⁻¹ʰ ∘ q⁻¹ʰ) ∘ q ∘ p = id, from by rewrite [-assoc, inverse_comp_cancel_left, left_inverse]) definition inverse_comp_inverse_left [H' : is_iso g] : (q⁻¹ ∘ g)⁻¹ = g⁻¹ ∘ q := inverse_involutive q ▹ comp_inverse q⁻¹ g definition inverse_comp_inverse_right [H' : is_iso f] : (q ∘ f⁻¹)⁻¹ = f ∘ q⁻¹ := inverse_involutive f ▹ comp_inverse q f⁻¹ definition inverse_comp_inverse_inverse [H' : is_iso r] : (q⁻¹ ∘ r⁻¹)⁻¹ = r ∘ q := inverse_involutive r ▹ inverse_comp_inverse_left q r⁻¹ end section variables {ob : Type} {C : precategory ob} include C variables {d c b a : ob} {i : b ⟶ c} {f : b ⟶ a} {r : c ⟶ d} {q : b ⟶ c} {p : a ⟶ b} {g : d ⟶ c} {h : c ⟶ b} {x : b ⟶ d} {z : a ⟶ c} {y : d ⟶ b} {w : c ⟶ a} variable [Hq : is_iso q] include Hq definition comp_eq_of_eq_inverse_comp (H : y = q⁻¹ ∘ g) : q ∘ y = g := H⁻¹ ▹ comp_inverse_cancel_left q g definition comp_eq_of_eq_comp_inverse (H : w = f ∘ q⁻¹) : w ∘ q = f := H⁻¹ ▹ inverse_comp_cancel_right f q definition inverse_comp_eq_of_eq_comp (H : z = q ∘ p) : q⁻¹ ∘ z = p := H⁻¹ ▹ inverse_comp_cancel_left q p definition comp_inverse_eq_of_eq_comp (H : x = r ∘ q) : x ∘ q⁻¹ = r := H⁻¹ ▹ comp_inverse_cancel_right r q definition eq_comp_of_inverse_comp_eq (H : q⁻¹ ∘ g = y) : g = q ∘ y := (comp_eq_of_eq_inverse_comp H⁻¹)⁻¹ definition eq_comp_of_comp_inverse_eq (H : f ∘ q⁻¹ = w) : f = w ∘ q := (comp_eq_of_eq_comp_inverse H⁻¹)⁻¹ definition eq_inverse_comp_of_comp_eq (H : q ∘ p = z) : p = q⁻¹ ∘ z := (inverse_comp_eq_of_eq_comp H⁻¹)⁻¹ definition eq_comp_inverse_of_comp_eq (H : r ∘ q = x) : r = x ∘ q⁻¹ := (comp_inverse_eq_of_eq_comp H⁻¹)⁻¹ definition eq_inverse_of_comp_eq_id' (H : h ∘ q = id) : h = q⁻¹ := (inverse_eq_left H)⁻¹ definition eq_inverse_of_comp_eq_id (H : q ∘ h = id) : h = q⁻¹ := (inverse_eq_right H)⁻¹ definition eq_of_comp_inverse_eq_id (H : i ∘ q⁻¹ = id) : i = q := eq_inverse_of_comp_eq_id' H ⬝ inverse_involutive q definition eq_of_inverse_comp_eq_id (H : q⁻¹ ∘ i = id) : i = q := eq_inverse_of_comp_eq_id H ⬝ inverse_involutive q definition eq_of_id_eq_comp_inverse (H : id = i ∘ q⁻¹) : q = i := (eq_of_comp_inverse_eq_id H⁻¹)⁻¹ definition eq_of_id_eq_inverse_comp (H : id = q⁻¹ ∘ i) : q = i := (eq_of_inverse_comp_eq_id H⁻¹)⁻¹ definition inverse_eq_of_id_eq_comp (H : id = h ∘ q) : q⁻¹ = h := (eq_inverse_of_comp_eq_id' H⁻¹)⁻¹ definition inverse_eq_of_id_eq_comp' (H : id = q ∘ h) : q⁻¹ = h := (eq_inverse_of_comp_eq_id H⁻¹)⁻¹ end end iso
2f440447744bb2563881bd0bc643d33bba737b88
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/analysis/analytic/basic.lean
de77aa78bad7bc5be2767af04f5d4ce4dac6db70
[ "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
50,586
lean
/- Copyright (c) 2020 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sébastien Gouëzel, Yury Kudryashov -/ import analysis.calculus.formal_multilinear_series import data.equiv.fin /-! # Analytic functions A function is analytic in one dimension around `0` if it can be written as a converging power series `Σ pₙ zⁿ`. This definition can be extended to any dimension (even in infinite dimension) by requiring that `pₙ` is a continuous `n`-multilinear map. In general, `pₙ` is not unique (in two dimensions, taking `p₂ (x, y) (x', y') = x y'` or `y x'` gives the same map when applied to a vector `(x, y) (x, y)`). A way to guarantee uniqueness is to take a symmetric `pₙ`, but this is not always possible in nonzero characteristic (in characteristic 2, the previous example has no symmetric representative). Therefore, we do not insist on symmetry or uniqueness in the definition, and we only require the existence of a converging series. The general framework is important to say that the exponential map on bounded operators on a Banach space is analytic, as well as the inverse on invertible operators. ## Main definitions Let `p` be a formal multilinear series from `E` to `F`, i.e., `p n` is a multilinear map on `E^n` for `n : ℕ`. * `p.radius`: the largest `r : ℝ≥0∞` such that `∥p n∥ * r^n` grows subexponentially, defined as a liminf. * `p.le_radius_of_bound`, `p.le_radius_of_bound_nnreal`, `p.le_radius_of_is_O`: if `∥p n∥ * r ^ n` is bounded above, then `r ≤ p.radius`; * `p.is_o_of_lt_radius`, `p.norm_mul_pow_le_mul_pow_of_lt_radius`, `p.is_o_one_of_lt_radius`, `p.norm_mul_pow_le_of_lt_radius`, `p.nnnorm_mul_pow_le_of_lt_radius`: if `r < p.radius`, then `∥p n∥ * r ^ n` tends to zero exponentially; * `p.lt_radius_of_is_O`: if `r ≠ 0` and `∥p n∥ * r ^ n = O(a ^ n)` for some `-1 < a < 1`, then `r < p.radius`; * `p.partial_sum n x`: the sum `∑_{i = 0}^{n-1} pᵢ xⁱ`. * `p.sum x`: the sum `∑'_{i = 0}^{∞} pᵢ xⁱ`. Additionally, let `f` be a function from `E` to `F`. * `has_fpower_series_on_ball f p x r`: on the ball of center `x` with radius `r`, `f (x + y) = ∑'_n pₙ yⁿ`. * `has_fpower_series_at f p x`: on some ball of center `x` with positive radius, holds `has_fpower_series_on_ball f p x r`. * `analytic_at 𝕜 f x`: there exists a power series `p` such that holds `has_fpower_series_at f p x`. We develop the basic properties of these notions, notably: * If a function admits a power series, it is continuous (see `has_fpower_series_on_ball.continuous_on` and `has_fpower_series_at.continuous_at` and `analytic_at.continuous_at`). * In a complete space, the sum of a formal power series with positive radius is well defined on the disk of convergence, see `formal_multilinear_series.has_fpower_series_on_ball`. * If a function admits a power series in a ball, then it is analytic at any point `y` of this ball, and the power series there can be expressed in terms of the initial power series `p` as `p.change_origin y`. See `has_fpower_series_on_ball.change_origin`. It follows in particular that the set of points at which a given function is analytic is open, see `is_open_analytic_at`. ## Implementation details We only introduce the radius of convergence of a power series, as `p.radius`. For a power series in finitely many dimensions, there is a finer (directional, coordinate-dependent) notion, describing the polydisk of convergence. This notion is more specific, and not necessary to build the general theory. We do not define it here. -/ noncomputable theory variables {𝕜 : Type*} [nondiscrete_normed_field 𝕜] {E : Type*} [normed_group E] [normed_space 𝕜 E] {F : Type*} [normed_group F] [normed_space 𝕜 F] {G : Type*} [normed_group G] [normed_space 𝕜 G] open_locale topological_space classical big_operators nnreal filter ennreal open set filter asymptotics /-! ### The radius of a formal multilinear series -/ namespace formal_multilinear_series variables (p : formal_multilinear_series 𝕜 E F) {r : ℝ≥0} /-- The radius of a formal multilinear series is the largest `r` such that the sum `Σ ∥pₙ∥ ∥y∥ⁿ` converges for all `∥y∥ < r`. This implies that `Σ pₙ yⁿ` converges for all `∥y∥ < r`, but these definitions are *not* equivalent in general. -/ def radius (p : formal_multilinear_series 𝕜 E F) : ℝ≥0∞ := ⨆ (r : ℝ≥0) (C : ℝ) (hr : ∀ n, ∥p n∥ * r ^ n ≤ C), (r : ℝ≥0∞) /-- If `∥pₙ∥ rⁿ` is bounded in `n`, then the radius of `p` is at least `r`. -/ lemma le_radius_of_bound (C : ℝ) {r : ℝ≥0} (h : ∀ (n : ℕ), ∥p n∥ * r^n ≤ C) : (r : ℝ≥0∞) ≤ p.radius := le_supr_of_le r $ le_supr_of_le C $ (le_supr (λ _, (r : ℝ≥0∞)) h) /-- If `∥pₙ∥ rⁿ` is bounded in `n`, then the radius of `p` is at least `r`. -/ lemma le_radius_of_bound_nnreal (C : ℝ≥0) {r : ℝ≥0} (h : ∀ (n : ℕ), ∥p n∥₊ * r^n ≤ C) : (r : ℝ≥0∞) ≤ p.radius := p.le_radius_of_bound C $ λ n, by exact_mod_cast (h n) /-- If `∥pₙ∥ rⁿ = O(1)`, as `n → ∞`, then the radius of `p` is at least `r`. -/ lemma le_radius_of_is_O (h : is_O (λ n, ∥p n∥ * r^n) (λ n, (1 : ℝ)) at_top) : ↑r ≤ p.radius := exists.elim (is_O_one_nat_at_top_iff.1 h) $ λ C hC, p.le_radius_of_bound C $ λ n, (le_abs_self _).trans (hC n) lemma le_radius_of_eventually_le (C) (h : ∀ᶠ n in at_top, ∥p n∥ * r ^ n ≤ C) : ↑r ≤ p.radius := p.le_radius_of_is_O $ is_O.of_bound C $ h.mono $ λ n hn, by simpa lemma le_radius_of_summable_nnnorm (h : summable (λ n, ∥p n∥₊ * r ^ n)) : ↑r ≤ p.radius := p.le_radius_of_bound_nnreal (∑' n, ∥p n∥₊ * r ^ n) $ λ n, le_tsum' h _ lemma le_radius_of_summable (h : summable (λ n, ∥p n∥ * r ^ n)) : ↑r ≤ p.radius := p.le_radius_of_summable_nnnorm $ by { simp only [← coe_nnnorm] at h, exact_mod_cast h } lemma radius_eq_top_of_forall_nnreal_is_O (h : ∀ r : ℝ≥0, is_O (λ n, ∥p n∥ * r^n) (λ n, (1 : ℝ)) at_top) : p.radius = ∞ := ennreal.eq_top_of_forall_nnreal_le $ λ r, p.le_radius_of_is_O (h r) lemma radius_eq_top_of_eventually_eq_zero (h : ∀ᶠ n in at_top, p n = 0) : p.radius = ∞ := p.radius_eq_top_of_forall_nnreal_is_O $ λ r, (is_O_zero _ _).congr' (h.mono $ λ n hn, by simp [hn]) eventually_eq.rfl lemma radius_eq_top_of_forall_image_add_eq_zero (n : ℕ) (hn : ∀ m, p (m + n) = 0) : p.radius = ∞ := p.radius_eq_top_of_eventually_eq_zero $ mem_at_top_sets.2 ⟨n, λ k hk, tsub_add_cancel_of_le hk ▸ hn _⟩ /-- For `r` strictly smaller than the radius of `p`, then `∥pₙ∥ rⁿ` tends to zero exponentially: for some `0 < a < 1`, `∥p n∥ rⁿ = o(aⁿ)`. -/ lemma is_o_of_lt_radius (h : ↑r < p.radius) : ∃ a ∈ Ioo (0 : ℝ) 1, is_o (λ n, ∥p n∥ * r ^ n) (pow a) at_top := begin rw (tfae_exists_lt_is_o_pow (λ n, ∥p n∥ * r ^ n) 1).out 1 4, simp only [radius, lt_supr_iff] at h, rcases h with ⟨t, C, hC, rt⟩, rw [ennreal.coe_lt_coe, ← nnreal.coe_lt_coe] at rt, have : 0 < (t : ℝ), from r.coe_nonneg.trans_lt rt, rw [← div_lt_one this] at rt, refine ⟨_, rt, C, or.inr zero_lt_one, λ n, _⟩, calc |∥p n∥ * r ^ n| = (∥p n∥ * t ^ n) * (r / t) ^ n : by field_simp [mul_right_comm, abs_mul, this.ne'] ... ≤ C * (r / t) ^ n : mul_le_mul_of_nonneg_right (hC n) (pow_nonneg (div_nonneg r.2 t.2) _) end /-- For `r` strictly smaller than the radius of `p`, then `∥pₙ∥ rⁿ = o(1)`. -/ lemma is_o_one_of_lt_radius (h : ↑r < p.radius) : is_o (λ n, ∥p n∥ * r ^ n) (λ _, 1 : ℕ → ℝ) at_top := let ⟨a, ha, hp⟩ := p.is_o_of_lt_radius h in hp.trans $ (is_o_pow_pow_of_lt_left ha.1.le ha.2).congr (λ n, rfl) one_pow /-- For `r` strictly smaller than the radius of `p`, then `∥pₙ∥ rⁿ` tends to zero exponentially: for some `0 < a < 1` and `C > 0`, `∥p n∥ * r ^ n ≤ C * a ^ n`. -/ lemma norm_mul_pow_le_mul_pow_of_lt_radius (h : ↑r < p.radius) : ∃ (a ∈ Ioo (0 : ℝ) 1) (C > 0), ∀ n, ∥p n∥ * r^n ≤ C * a^n := begin rcases ((tfae_exists_lt_is_o_pow (λ n, ∥p n∥ * r ^ n) 1).out 1 5).mp (p.is_o_of_lt_radius h) with ⟨a, ha, C, hC, H⟩, exact ⟨a, ha, C, hC, λ n, (le_abs_self _).trans (H n)⟩ end /-- If `r ≠ 0` and `∥pₙ∥ rⁿ = O(aⁿ)` for some `-1 < a < 1`, then `r < p.radius`. -/ lemma lt_radius_of_is_O (h₀ : r ≠ 0) {a : ℝ} (ha : a ∈ Ioo (-1 : ℝ) 1) (hp : is_O (λ n, ∥p n∥ * r ^ n) (pow a) at_top) : ↑r < p.radius := begin rcases ((tfae_exists_lt_is_o_pow (λ n, ∥p n∥ * r ^ n) 1).out 2 5).mp ⟨a, ha, hp⟩ with ⟨a, ha, C, hC, hp⟩, rw [← pos_iff_ne_zero, ← nnreal.coe_pos] at h₀, lift a to ℝ≥0 using ha.1.le, have : (r : ℝ) < r / a := by simpa only [div_one] using (div_lt_div_left h₀ zero_lt_one ha.1).2 ha.2, norm_cast at this, rw [← ennreal.coe_lt_coe] at this, refine this.trans_le (p.le_radius_of_bound C $ λ n, _), rw [nnreal.coe_div, div_pow, ← mul_div_assoc, div_le_iff (pow_pos ha.1 n)], exact (le_abs_self _).trans (hp n) end /-- For `r` strictly smaller than the radius of `p`, then `∥pₙ∥ rⁿ` is bounded. -/ lemma norm_mul_pow_le_of_lt_radius (p : formal_multilinear_series 𝕜 E F) {r : ℝ≥0} (h : (r : ℝ≥0∞) < p.radius) : ∃ C > 0, ∀ n, ∥p n∥ * r^n ≤ C := let ⟨a, ha, C, hC, h⟩ := p.norm_mul_pow_le_mul_pow_of_lt_radius h in ⟨C, hC, λ n, (h n).trans $ mul_le_of_le_one_right hC.lt.le (pow_le_one _ ha.1.le ha.2.le)⟩ /-- For `r` strictly smaller than the radius of `p`, then `∥pₙ∥ rⁿ` is bounded. -/ lemma norm_le_div_pow_of_pos_of_lt_radius (p : formal_multilinear_series 𝕜 E F) {r : ℝ≥0} (h0 : 0 < r) (h : (r : ℝ≥0∞) < p.radius) : ∃ C > 0, ∀ n, ∥p n∥ ≤ C / r ^ n := let ⟨C, hC, hp⟩ := p.norm_mul_pow_le_of_lt_radius h in ⟨C, hC, λ n, iff.mpr (le_div_iff (pow_pos h0 _)) (hp n)⟩ /-- For `r` strictly smaller than the radius of `p`, then `∥pₙ∥ rⁿ` is bounded. -/ lemma nnnorm_mul_pow_le_of_lt_radius (p : formal_multilinear_series 𝕜 E F) {r : ℝ≥0} (h : (r : ℝ≥0∞) < p.radius) : ∃ C > 0, ∀ n, ∥p n∥₊ * r^n ≤ C := let ⟨C, hC, hp⟩ := p.norm_mul_pow_le_of_lt_radius h in ⟨⟨C, hC.lt.le⟩, hC, by exact_mod_cast hp⟩ lemma le_radius_of_tendsto (p : formal_multilinear_series 𝕜 E F) {l : ℝ} (h : tendsto (λ n, ∥p n∥ * r^n) at_top (𝓝 l)) : ↑r ≤ p.radius := p.le_radius_of_is_O (is_O_one_of_tendsto _ h) lemma le_radius_of_summable_norm (p : formal_multilinear_series 𝕜 E F) (hs : summable (λ n, ∥p n∥ * r^n)) : ↑r ≤ p.radius := p.le_radius_of_tendsto hs.tendsto_at_top_zero lemma not_summable_norm_of_radius_lt_nnnorm (p : formal_multilinear_series 𝕜 E F) {x : E} (h : p.radius < ∥x∥₊) : ¬ summable (λ n, ∥p n∥ * ∥x∥^n) := λ hs, not_le_of_lt h (p.le_radius_of_summable_norm hs) lemma summable_norm_mul_pow (p : formal_multilinear_series 𝕜 E F) {r : ℝ≥0} (h : ↑r < p.radius) : summable (λ n : ℕ, ∥p n∥ * r ^ n) := begin obtain ⟨a, ha : a ∈ Ioo (0 : ℝ) 1, C, hC : 0 < C, hp⟩ := p.norm_mul_pow_le_mul_pow_of_lt_radius h, exact summable_of_nonneg_of_le (λ n, mul_nonneg (norm_nonneg _) (pow_nonneg r.coe_nonneg _)) hp ((summable_geometric_of_lt_1 ha.1.le ha.2).mul_left _), end lemma summable_norm_apply (p : formal_multilinear_series 𝕜 E F) {x : E} (hx : x ∈ emetric.ball (0 : E) p.radius) : summable (λ n : ℕ, ∥p n (λ _, x)∥) := begin rw mem_emetric_ball_zero_iff at hx, refine summable_of_nonneg_of_le (λ _, norm_nonneg _) (λ n, ((p n).le_op_norm _).trans_eq _) (p.summable_norm_mul_pow hx), simp end lemma summable_nnnorm_mul_pow (p : formal_multilinear_series 𝕜 E F) {r : ℝ≥0} (h : ↑r < p.radius) : summable (λ n : ℕ, ∥p n∥₊ * r ^ n) := by { rw ← nnreal.summable_coe, push_cast, exact p.summable_norm_mul_pow h } protected lemma summable [complete_space F] (p : formal_multilinear_series 𝕜 E F) {x : E} (hx : x ∈ emetric.ball (0 : E) p.radius) : summable (λ n : ℕ, p n (λ _, x)) := summable_of_summable_norm (p.summable_norm_apply hx) lemma radius_eq_top_of_summable_norm (p : formal_multilinear_series 𝕜 E F) (hs : ∀ r : ℝ≥0, summable (λ n, ∥p n∥ * r^n)) : p.radius = ∞ := ennreal.eq_top_of_forall_nnreal_le (λ r, p.le_radius_of_summable_norm (hs r)) lemma radius_eq_top_iff_summable_norm (p : formal_multilinear_series 𝕜 E F) : p.radius = ∞ ↔ ∀ r : ℝ≥0, summable (λ n, ∥p n∥ * r^n) := begin split, { intros h r, obtain ⟨a, ha : a ∈ Ioo (0 : ℝ) 1, C, hC : 0 < C, hp⟩ := p.norm_mul_pow_le_mul_pow_of_lt_radius (show (r:ℝ≥0∞) < p.radius, from h.symm ▸ ennreal.coe_lt_top), refine (summable_of_norm_bounded (λ n, (C : ℝ) * a ^ n) ((summable_geometric_of_lt_1 ha.1.le ha.2).mul_left _) (λ n, _)), specialize hp n, rwa real.norm_of_nonneg (mul_nonneg (norm_nonneg _) (pow_nonneg r.coe_nonneg n)) }, { exact p.radius_eq_top_of_summable_norm } end /-- If the radius of `p` is positive, then `∥pₙ∥` grows at most geometrically. -/ lemma le_mul_pow_of_radius_pos (p : formal_multilinear_series 𝕜 E F) (h : 0 < p.radius) : ∃ C r (hC : 0 < C) (hr : 0 < r), ∀ n, ∥p n∥ ≤ C * r ^ n := begin rcases ennreal.lt_iff_exists_nnreal_btwn.1 h with ⟨r, r0, rlt⟩, have rpos : 0 < (r : ℝ), by simp [ennreal.coe_pos.1 r0], rcases norm_le_div_pow_of_pos_of_lt_radius p rpos rlt with ⟨C, Cpos, hCp⟩, refine ⟨C, r ⁻¹, Cpos, by simp [rpos], λ n, _⟩, convert hCp n, exact inv_pow₀ _ _, end /-- The radius of the sum of two formal series is at least the minimum of their two radii. -/ lemma min_radius_le_radius_add (p q : formal_multilinear_series 𝕜 E F) : min p.radius q.radius ≤ (p + q).radius := begin refine ennreal.le_of_forall_nnreal_lt (λ r hr, _), rw lt_min_iff at hr, have := ((p.is_o_one_of_lt_radius hr.1).add (q.is_o_one_of_lt_radius hr.2)).is_O, refine (p + q).le_radius_of_is_O ((is_O_of_le _ $ λ n, _).trans this), rw [← add_mul, normed_field.norm_mul, normed_field.norm_mul, norm_norm], exact mul_le_mul_of_nonneg_right ((norm_add_le _ _).trans (le_abs_self _)) (norm_nonneg _) end @[simp] lemma radius_neg (p : formal_multilinear_series 𝕜 E F) : (-p).radius = p.radius := by simp [radius] /-- Given a formal multilinear series `p` and a vector `x`, then `p.sum x` is the sum `Σ pₙ xⁿ`. A priori, it only behaves well when `∥x∥ < p.radius`. -/ protected def sum (p : formal_multilinear_series 𝕜 E F) (x : E) : F := ∑' n : ℕ , p n (λ i, x) protected lemma has_sum [complete_space F] (p : formal_multilinear_series 𝕜 E F) {x : E} (hx : x ∈ emetric.ball (0 : E) p.radius) : has_sum (λ n : ℕ, p n (λ _, x)) (p.sum x) := (p.summable hx).has_sum /-- Given a formal multilinear series `p` and a vector `x`, then `p.partial_sum n x` is the sum `Σ pₖ xᵏ` for `k ∈ {0,..., n-1}`. -/ def partial_sum (p : formal_multilinear_series 𝕜 E F) (n : ℕ) (x : E) : F := ∑ k in finset.range n, p k (λ(i : fin k), x) /-- The partial sums of a formal multilinear series are continuous. -/ lemma partial_sum_continuous (p : formal_multilinear_series 𝕜 E F) (n : ℕ) : continuous (p.partial_sum n) := by continuity end formal_multilinear_series /-! ### Expanding a function as a power series -/ section variables {f g : E → F} {p pf pg : formal_multilinear_series 𝕜 E F} {x : E} {r r' : ℝ≥0∞} /-- Given a function `f : E → F` and a formal multilinear series `p`, we say that `f` has `p` as a power series on the ball of radius `r > 0` around `x` if `f (x + y) = ∑' pₙ yⁿ` for all `∥y∥ < r`. -/ structure has_fpower_series_on_ball (f : E → F) (p : formal_multilinear_series 𝕜 E F) (x : E) (r : ℝ≥0∞) : Prop := (r_le : r ≤ p.radius) (r_pos : 0 < r) (has_sum : ∀ {y}, y ∈ emetric.ball (0 : E) r → has_sum (λn:ℕ, p n (λ(i : fin n), y)) (f (x + y))) /-- Given a function `f : E → F` and a formal multilinear series `p`, we say that `f` has `p` as a power series around `x` if `f (x + y) = ∑' pₙ yⁿ` for all `y` in a neighborhood of `0`. -/ def has_fpower_series_at (f : E → F) (p : formal_multilinear_series 𝕜 E F) (x : E) := ∃ r, has_fpower_series_on_ball f p x r variable (𝕜) /-- Given a function `f : E → F`, we say that `f` is analytic at `x` if it admits a convergent power series expansion around `x`. -/ def analytic_at (f : E → F) (x : E) := ∃ (p : formal_multilinear_series 𝕜 E F), has_fpower_series_at f p x variable {𝕜} lemma has_fpower_series_on_ball.has_fpower_series_at (hf : has_fpower_series_on_ball f p x r) : has_fpower_series_at f p x := ⟨r, hf⟩ lemma has_fpower_series_at.analytic_at (hf : has_fpower_series_at f p x) : analytic_at 𝕜 f x := ⟨p, hf⟩ lemma has_fpower_series_on_ball.analytic_at (hf : has_fpower_series_on_ball f p x r) : analytic_at 𝕜 f x := hf.has_fpower_series_at.analytic_at lemma has_fpower_series_on_ball.has_sum_sub (hf : has_fpower_series_on_ball f p x r) {y : E} (hy : y ∈ emetric.ball x r) : has_sum (λ n : ℕ, p n (λ i, y - x)) (f y) := have y - x ∈ emetric.ball (0 : E) r, by simpa [edist_eq_coe_nnnorm_sub] using hy, by simpa only [add_sub_cancel'_right] using hf.has_sum this lemma has_fpower_series_on_ball.radius_pos (hf : has_fpower_series_on_ball f p x r) : 0 < p.radius := lt_of_lt_of_le hf.r_pos hf.r_le lemma has_fpower_series_at.radius_pos (hf : has_fpower_series_at f p x) : 0 < p.radius := let ⟨r, hr⟩ := hf in hr.radius_pos lemma has_fpower_series_on_ball.mono (hf : has_fpower_series_on_ball f p x r) (r'_pos : 0 < r') (hr : r' ≤ r) : has_fpower_series_on_ball f p x r' := ⟨le_trans hr hf.1, r'_pos, λ y hy, hf.has_sum (emetric.ball_subset_ball hr hy)⟩ protected lemma has_fpower_series_at.eventually (hf : has_fpower_series_at f p x) : ∀ᶠ r : ℝ≥0∞ in 𝓝[Ioi 0] 0, has_fpower_series_on_ball f p x r := let ⟨r, hr⟩ := hf in mem_of_superset (Ioo_mem_nhds_within_Ioi (left_mem_Ico.2 hr.r_pos)) $ λ r' hr', hr.mono hr'.1 hr'.2.le lemma has_fpower_series_on_ball.add (hf : has_fpower_series_on_ball f pf x r) (hg : has_fpower_series_on_ball g pg x r) : has_fpower_series_on_ball (f + g) (pf + pg) x r := { r_le := le_trans (le_min_iff.2 ⟨hf.r_le, hg.r_le⟩) (pf.min_radius_le_radius_add pg), r_pos := hf.r_pos, has_sum := λ y hy, (hf.has_sum hy).add (hg.has_sum hy) } lemma has_fpower_series_at.add (hf : has_fpower_series_at f pf x) (hg : has_fpower_series_at g pg x) : has_fpower_series_at (f + g) (pf + pg) x := begin rcases (hf.eventually.and hg.eventually).exists with ⟨r, hr⟩, exact ⟨r, hr.1.add hr.2⟩ end lemma analytic_at.add (hf : analytic_at 𝕜 f x) (hg : analytic_at 𝕜 g x) : analytic_at 𝕜 (f + g) x := let ⟨pf, hpf⟩ := hf, ⟨qf, hqf⟩ := hg in (hpf.add hqf).analytic_at lemma has_fpower_series_on_ball.neg (hf : has_fpower_series_on_ball f pf x r) : has_fpower_series_on_ball (-f) (-pf) x r := { r_le := by { rw pf.radius_neg, exact hf.r_le }, r_pos := hf.r_pos, has_sum := λ y hy, (hf.has_sum hy).neg } lemma has_fpower_series_at.neg (hf : has_fpower_series_at f pf x) : has_fpower_series_at (-f) (-pf) x := let ⟨rf, hrf⟩ := hf in hrf.neg.has_fpower_series_at lemma analytic_at.neg (hf : analytic_at 𝕜 f x) : analytic_at 𝕜 (-f) x := let ⟨pf, hpf⟩ := hf in hpf.neg.analytic_at lemma has_fpower_series_on_ball.sub (hf : has_fpower_series_on_ball f pf x r) (hg : has_fpower_series_on_ball g pg x r) : has_fpower_series_on_ball (f - g) (pf - pg) x r := by simpa only [sub_eq_add_neg] using hf.add hg.neg lemma has_fpower_series_at.sub (hf : has_fpower_series_at f pf x) (hg : has_fpower_series_at g pg x) : has_fpower_series_at (f - g) (pf - pg) x := by simpa only [sub_eq_add_neg] using hf.add hg.neg lemma analytic_at.sub (hf : analytic_at 𝕜 f x) (hg : analytic_at 𝕜 g x) : analytic_at 𝕜 (f - g) x := by simpa only [sub_eq_add_neg] using hf.add hg.neg lemma has_fpower_series_on_ball.coeff_zero (hf : has_fpower_series_on_ball f pf x r) (v : fin 0 → E) : pf 0 v = f x := begin have v_eq : v = (λ i, 0) := subsingleton.elim _ _, have zero_mem : (0 : E) ∈ emetric.ball (0 : E) r, by simp [hf.r_pos], have : ∀ i ≠ 0, pf i (λ j, 0) = 0, { assume i hi, have : 0 < i := pos_iff_ne_zero.2 hi, exact continuous_multilinear_map.map_coord_zero _ (⟨0, this⟩ : fin i) rfl }, have A := (hf.has_sum zero_mem).unique (has_sum_single _ this), simpa [v_eq] using A.symm, end lemma has_fpower_series_at.coeff_zero (hf : has_fpower_series_at f pf x) (v : fin 0 → E) : pf 0 v = f x := let ⟨rf, hrf⟩ := hf in hrf.coeff_zero v /-- If a function admits a power series expansion, then it is exponentially close to the partial sums of this power series on strict subdisks of the disk of convergence. This version provides an upper estimate that decreases both in `∥y∥` and `n`. See also `has_fpower_series_on_ball.uniform_geometric_approx` for a weaker version. -/ lemma has_fpower_series_on_ball.uniform_geometric_approx' {r' : ℝ≥0} (hf : has_fpower_series_on_ball f p x r) (h : (r' : ℝ≥0∞) < r) : ∃ (a ∈ Ioo (0 : ℝ) 1) (C > 0), (∀ y ∈ metric.ball (0 : E) r', ∀ n, ∥f (x + y) - p.partial_sum n y∥ ≤ C * (a * (∥y∥ / r')) ^ n) := begin obtain ⟨a, ha, C, hC, hp⟩ : ∃ (a ∈ Ioo (0 : ℝ) 1) (C > 0), ∀ n, ∥p n∥ * r' ^n ≤ C * a^n := p.norm_mul_pow_le_mul_pow_of_lt_radius (h.trans_le hf.r_le), refine ⟨a, ha, C / (1 - a), div_pos hC (sub_pos.2 ha.2), λ y hy n, _⟩, have yr' : ∥y∥ < r', by { rw ball_zero_eq at hy, exact hy }, have hr'0 : 0 < (r' : ℝ), from (norm_nonneg _).trans_lt yr', have : y ∈ emetric.ball (0 : E) r, { refine mem_emetric_ball_zero_iff.2 (lt_trans _ h), exact_mod_cast yr' }, rw [norm_sub_rev, ← mul_div_right_comm], have ya : a * (∥y∥ / ↑r') ≤ a, from mul_le_of_le_one_right ha.1.le (div_le_one_of_le yr'.le r'.coe_nonneg), suffices : ∥p.partial_sum n y - f (x + y)∥ ≤ C * (a * (∥y∥ / r')) ^ n / (1 - a * (∥y∥ / r')), { refine this.trans _, apply_rules [div_le_div_of_le_left, sub_pos.2, div_nonneg, mul_nonneg, pow_nonneg, hC.lt.le, ha.1.le, norm_nonneg, nnreal.coe_nonneg, ha.2, (sub_le_sub_iff_left _).2]; apply_instance }, apply norm_sub_le_of_geometric_bound_of_has_sum (ya.trans_lt ha.2) _ (hf.has_sum this), assume n, calc ∥(p n) (λ (i : fin n), y)∥ ≤ ∥p n∥ * (∏ i : fin n, ∥y∥) : continuous_multilinear_map.le_op_norm _ _ ... = (∥p n∥ * r' ^ n) * (∥y∥ / r') ^ n : by field_simp [hr'0.ne', mul_right_comm] ... ≤ (C * a ^ n) * (∥y∥ / r') ^ n : mul_le_mul_of_nonneg_right (hp n) (pow_nonneg (div_nonneg (norm_nonneg _) r'.coe_nonneg) _) ... ≤ C * (a * (∥y∥ / r')) ^ n : by rw [mul_pow, mul_assoc] end /-- If a function admits a power series expansion, then it is exponentially close to the partial sums of this power series on strict subdisks of the disk of convergence. -/ lemma has_fpower_series_on_ball.uniform_geometric_approx {r' : ℝ≥0} (hf : has_fpower_series_on_ball f p x r) (h : (r' : ℝ≥0∞) < r) : ∃ (a ∈ Ioo (0 : ℝ) 1) (C > 0), (∀ y ∈ metric.ball (0 : E) r', ∀ n, ∥f (x + y) - p.partial_sum n y∥ ≤ C * a ^ n) := begin obtain ⟨a, ha, C, hC, hp⟩ : ∃ (a ∈ Ioo (0 : ℝ) 1) (C > 0), (∀ y ∈ metric.ball (0 : E) r', ∀ n, ∥f (x + y) - p.partial_sum n y∥ ≤ C * (a * (∥y∥ / r')) ^ n), from hf.uniform_geometric_approx' h, refine ⟨a, ha, C, hC, λ y hy n, (hp y hy n).trans _⟩, have yr' : ∥y∥ < r', by rwa ball_zero_eq at hy, refine mul_le_mul_of_nonneg_left (pow_le_pow_of_le_left _ _ _) hC.lt.le, exacts [mul_nonneg ha.1.le (div_nonneg (norm_nonneg y) r'.coe_nonneg), mul_le_of_le_one_right ha.1.le (div_le_one_of_le yr'.le r'.coe_nonneg)] end /-- Taylor formula for an analytic function, `is_O` version. -/ lemma has_fpower_series_at.is_O_sub_partial_sum_pow (hf : has_fpower_series_at f p x) (n : ℕ) : is_O (λ y : E, f (x + y) - p.partial_sum n y) (λ y, ∥y∥ ^ n) (𝓝 0) := begin rcases hf with ⟨r, hf⟩, rcases ennreal.lt_iff_exists_nnreal_btwn.1 hf.r_pos with ⟨r', r'0, h⟩, obtain ⟨a, ha, C, hC, hp⟩ : ∃ (a ∈ Ioo (0 : ℝ) 1) (C > 0), (∀ y ∈ metric.ball (0 : E) r', ∀ n, ∥f (x + y) - p.partial_sum n y∥ ≤ C * (a * (∥y∥ / r')) ^ n), from hf.uniform_geometric_approx' h, refine is_O_iff.2 ⟨C * (a / r') ^ n, _⟩, replace r'0 : 0 < (r' : ℝ), by exact_mod_cast r'0, filter_upwards [metric.ball_mem_nhds (0 : E) r'0], intros y hy, simpa [mul_pow, mul_div_assoc, mul_assoc, div_mul_eq_mul_div] using hp y hy n end -- hack to speed up simp when dealing with complicated types local attribute [-instance] unique.subsingleton pi.subsingleton /-- If `f` has formal power series `∑ n, pₙ` on a ball of radius `r`, then for `y, z` in any smaller ball, the norm of the difference `f y - f z - p 1 (λ _, y - z)` is bounded above by `C * (max ∥y - x∥ ∥z - x∥) * ∥y - z∥`. This lemma formulates this property using `is_O` and `filter.principal` on `E × E`. -/ lemma has_fpower_series_on_ball.is_O_image_sub_image_sub_deriv_principal (hf : has_fpower_series_on_ball f p x r) (hr : r' < r) : is_O (λ y : E × E, f y.1 - f y.2 - (p 1 (λ _, y.1 - y.2))) (λ y, ∥y - (x, x)∥ * ∥y.1 - y.2∥) (𝓟 $ emetric.ball (x, x) r') := begin lift r' to ℝ≥0 using ne_top_of_lt hr, rcases (zero_le r').eq_or_lt with rfl|hr'0, { simp only [is_O_bot, emetric.ball_zero, principal_empty, ennreal.coe_zero] }, obtain ⟨a, ha, C, hC : 0 < C, hp⟩ : ∃ (a ∈ Ioo (0 : ℝ) 1) (C > 0), ∀ (n : ℕ), ∥p n∥ * ↑r' ^ n ≤ C * a ^ n, from p.norm_mul_pow_le_mul_pow_of_lt_radius (hr.trans_le hf.r_le), simp only [← le_div_iff (pow_pos (nnreal.coe_pos.2 hr'0) _)] at hp, set L : E × E → ℝ := λ y, (C * (a / r') ^ 2) * (∥y - (x, x)∥ * ∥y.1 - y.2∥) * (a / (1 - a) ^ 2 + 2 / (1 - a)), have hL : ∀ y ∈ emetric.ball (x, x) r', ∥f y.1 - f y.2 - (p 1 (λ _, y.1 - y.2))∥ ≤ L y, { intros y hy', have hy : y ∈ (emetric.ball x r).prod (emetric.ball x r), { rw [emetric.ball_prod_same], exact emetric.ball_subset_ball hr.le hy' }, set A : ℕ → F := λ n, p n (λ _, y.1 - x) - p n (λ _, y.2 - x), have hA : has_sum (λ n, A (n + 2)) (f y.1 - f y.2 - (p 1 (λ _, y.1 - y.2))), { convert (has_sum_nat_add_iff' 2).2 ((hf.has_sum_sub hy.1).sub (hf.has_sum_sub hy.2)) using 1, rw [finset.sum_range_succ, finset.sum_range_one, hf.coeff_zero, hf.coeff_zero, sub_self, zero_add, ← subsingleton.pi_single_eq (0 : fin 1) (y.1 - x), pi.single, ← subsingleton.pi_single_eq (0 : fin 1) (y.2 - x), pi.single, ← (p 1).map_sub, ← pi.single, subsingleton.pi_single_eq, sub_sub_sub_cancel_right] }, rw [emetric.mem_ball, edist_eq_coe_nnnorm_sub, ennreal.coe_lt_coe] at hy', set B : ℕ → ℝ := λ n, (C * (a / r') ^ 2) * (∥y - (x, x)∥ * ∥y.1 - y.2∥) * ((n + 2) * a ^ n), have hAB : ∀ n, ∥A (n + 2)∥ ≤ B n := λ n, calc ∥A (n + 2)∥ ≤ ∥p (n + 2)∥ * ↑(n + 2) * ∥y - (x, x)∥ ^ (n + 1) * ∥y.1 - y.2∥ : by simpa only [fintype.card_fin, pi_norm_const, prod.norm_def, pi.sub_def, prod.fst_sub, prod.snd_sub, sub_sub_sub_cancel_right] using (p $ n + 2).norm_image_sub_le (λ _, y.1 - x) (λ _, y.2 - x) ... = ∥p (n + 2)∥ * ∥y - (x, x)∥ ^ n * (↑(n + 2) * ∥y - (x, x)∥ * ∥y.1 - y.2∥) : by { rw [pow_succ ∥y - (x, x)∥], ac_refl } ... ≤ (C * a ^ (n + 2) / r' ^ (n + 2)) * r' ^ n * (↑(n + 2) * ∥y - (x, x)∥ * ∥y.1 - y.2∥) : by apply_rules [mul_le_mul_of_nonneg_right, mul_le_mul, hp, pow_le_pow_of_le_left, hy'.le, norm_nonneg, pow_nonneg, div_nonneg, mul_nonneg, nat.cast_nonneg, hC.le, r'.coe_nonneg, ha.1.le] ... = B n : by { field_simp [B, pow_succ, hr'0.ne'], simp only [mul_assoc, mul_comm, mul_left_comm] }, have hBL : has_sum B (L y), { apply has_sum.mul_left, simp only [add_mul], have : ∥a∥ < 1, by simp only [real.norm_eq_abs, abs_of_pos ha.1, ha.2], convert (has_sum_coe_mul_geometric_of_norm_lt_1 this).add ((has_sum_geometric_of_norm_lt_1 this).mul_left 2) }, exact hA.norm_le_of_bounded hBL hAB }, suffices : is_O L (λ y, ∥y - (x, x)∥ * ∥y.1 - y.2∥) (𝓟 (emetric.ball (x, x) r')), { refine (is_O.of_bound 1 (eventually_principal.2 $ λ y hy, _)).trans this, rw one_mul, exact (hL y hy).trans (le_abs_self _) }, simp_rw [L, mul_right_comm _ (_ * _)], exact (is_O_refl _ _).const_mul_left _, end /-- If `f` has formal power series `∑ n, pₙ` on a ball of radius `r`, then for `y, z` in any smaller ball, the norm of the difference `f y - f z - p 1 (λ _, y - z)` is bounded above by `C * (max ∥y - x∥ ∥z - x∥) * ∥y - z∥`. -/ lemma has_fpower_series_on_ball.image_sub_sub_deriv_le (hf : has_fpower_series_on_ball f p x r) (hr : r' < r) : ∃ C, ∀ (y z ∈ emetric.ball x r'), ∥f y - f z - (p 1 (λ _, y - z))∥ ≤ C * (max ∥y - x∥ ∥z - x∥) * ∥y - z∥ := by simpa only [is_O_principal, mul_assoc, normed_field.norm_mul, norm_norm, prod.forall, emetric.mem_ball, prod.edist_eq, max_lt_iff, and_imp] using hf.is_O_image_sub_image_sub_deriv_principal hr /-- If `f` has formal power series `∑ n, pₙ` at `x`, then `f y - f z - p 1 (λ _, y - z) = O(∥(y, z) - (x, x)∥ * ∥y - z∥)` as `(y, z) → (x, x)`. In particular, `f` is strictly differentiable at `x`. -/ lemma has_fpower_series_at.is_O_image_sub_norm_mul_norm_sub (hf : has_fpower_series_at f p x) : is_O (λ y : E × E, f y.1 - f y.2 - (p 1 (λ _, y.1 - y.2))) (λ y, ∥y - (x, x)∥ * ∥y.1 - y.2∥) (𝓝 (x, x)) := begin rcases hf with ⟨r, hf⟩, rcases ennreal.lt_iff_exists_nnreal_btwn.1 hf.r_pos with ⟨r', r'0, h⟩, refine (hf.is_O_image_sub_image_sub_deriv_principal h).mono _, exact le_principal_iff.2 (emetric.ball_mem_nhds _ r'0) end /-- If a function admits a power series expansion at `x`, then it is the uniform limit of the partial sums of this power series on strict subdisks of the disk of convergence, i.e., `f (x + y)` is the uniform limit of `p.partial_sum n y` there. -/ lemma has_fpower_series_on_ball.tendsto_uniformly_on {r' : ℝ≥0} (hf : has_fpower_series_on_ball f p x r) (h : (r' : ℝ≥0∞) < r) : tendsto_uniformly_on (λ n y, p.partial_sum n y) (λ y, f (x + y)) at_top (metric.ball (0 : E) r') := begin obtain ⟨a, ha, C, hC, hp⟩ : ∃ (a ∈ Ioo (0 : ℝ) 1) (C > 0), (∀ y ∈ metric.ball (0 : E) r', ∀ n, ∥f (x + y) - p.partial_sum n y∥ ≤ C * a ^ n), from hf.uniform_geometric_approx h, refine metric.tendsto_uniformly_on_iff.2 (λ ε εpos, _), have L : tendsto (λ n, (C : ℝ) * a^n) at_top (𝓝 ((C : ℝ) * 0)) := tendsto_const_nhds.mul (tendsto_pow_at_top_nhds_0_of_lt_1 ha.1.le ha.2), rw mul_zero at L, refine (L.eventually (gt_mem_nhds εpos)).mono (λ n hn y hy, _), rw dist_eq_norm, exact (hp y hy n).trans_lt hn end /-- If a function admits a power series expansion at `x`, then it is the locally uniform limit of the partial sums of this power series on the disk of convergence, i.e., `f (x + y)` is the locally uniform limit of `p.partial_sum n y` there. -/ lemma has_fpower_series_on_ball.tendsto_locally_uniformly_on (hf : has_fpower_series_on_ball f p x r) : tendsto_locally_uniformly_on (λ n y, p.partial_sum n y) (λ y, f (x + y)) at_top (emetric.ball (0 : E) r) := begin assume u hu x hx, rcases ennreal.lt_iff_exists_nnreal_btwn.1 hx with ⟨r', xr', hr'⟩, have : emetric.ball (0 : E) r' ∈ 𝓝 x := is_open.mem_nhds emetric.is_open_ball xr', refine ⟨emetric.ball (0 : E) r', mem_nhds_within_of_mem_nhds this, _⟩, simpa [metric.emetric_ball_nnreal] using hf.tendsto_uniformly_on hr' u hu end /-- If a function admits a power series expansion at `x`, then it is the uniform limit of the partial sums of this power series on strict subdisks of the disk of convergence, i.e., `f y` is the uniform limit of `p.partial_sum n (y - x)` there. -/ lemma has_fpower_series_on_ball.tendsto_uniformly_on' {r' : ℝ≥0} (hf : has_fpower_series_on_ball f p x r) (h : (r' : ℝ≥0∞) < r) : tendsto_uniformly_on (λ n y, p.partial_sum n (y - x)) f at_top (metric.ball (x : E) r') := begin convert (hf.tendsto_uniformly_on h).comp (λ y, y - x), { simp [(∘)] }, { ext z, simp [dist_eq_norm] } end /-- If a function admits a power series expansion at `x`, then it is the locally uniform limit of the partial sums of this power series on the disk of convergence, i.e., `f y` is the locally uniform limit of `p.partial_sum n (y - x)` there. -/ lemma has_fpower_series_on_ball.tendsto_locally_uniformly_on' (hf : has_fpower_series_on_ball f p x r) : tendsto_locally_uniformly_on (λ n y, p.partial_sum n (y - x)) f at_top (emetric.ball (x : E) r) := begin have A : continuous_on (λ (y : E), y - x) (emetric.ball (x : E) r) := (continuous_id.sub continuous_const).continuous_on, convert (hf.tendsto_locally_uniformly_on).comp (λ (y : E), y - x) _ A, { ext z, simp }, { assume z, simp [edist_eq_coe_nnnorm, edist_eq_coe_nnnorm_sub] } end /-- If a function admits a power series expansion on a disk, then it is continuous there. -/ lemma has_fpower_series_on_ball.continuous_on (hf : has_fpower_series_on_ball f p x r) : continuous_on f (emetric.ball x r) := hf.tendsto_locally_uniformly_on'.continuous_on $ λ n, ((p.partial_sum_continuous n).comp (continuous_id.sub continuous_const)).continuous_on lemma has_fpower_series_at.continuous_at (hf : has_fpower_series_at f p x) : continuous_at f x := let ⟨r, hr⟩ := hf in hr.continuous_on.continuous_at (emetric.ball_mem_nhds x (hr.r_pos)) lemma analytic_at.continuous_at (hf : analytic_at 𝕜 f x) : continuous_at f x := let ⟨p, hp⟩ := hf in hp.continuous_at /-- In a complete space, the sum of a converging power series `p` admits `p` as a power series. This is not totally obvious as we need to check the convergence of the series. -/ protected lemma formal_multilinear_series.has_fpower_series_on_ball [complete_space F] (p : formal_multilinear_series 𝕜 E F) (h : 0 < p.radius) : has_fpower_series_on_ball p.sum p 0 p.radius := { r_le := le_refl _, r_pos := h, has_sum := λ y hy, by { rw zero_add, exact p.has_sum hy } } lemma has_fpower_series_on_ball.sum [complete_space F] (h : has_fpower_series_on_ball f p x r) {y : E} (hy : y ∈ emetric.ball (0 : E) r) : f (x + y) = p.sum y := (h.has_sum hy).unique (p.has_sum (lt_of_lt_of_le hy h.r_le)) /-- The sum of a converging power series is continuous in its disk of convergence. -/ protected lemma formal_multilinear_series.continuous_on [complete_space F] : continuous_on p.sum (emetric.ball 0 p.radius) := begin cases (zero_le p.radius).eq_or_lt with h h, { simp [← h, continuous_on_empty] }, { exact (p.has_fpower_series_on_ball h).continuous_on } end end /-! ### Changing origin in a power series If a function is analytic in a disk `D(x, R)`, then it is analytic in any disk contained in that one. Indeed, one can write $$ f (x + y + z) = \sum_{n} p_n (y + z)^n = \sum_{n, k} \binom{n}{k} p_n y^{n-k} z^k = \sum_{k} \Bigl(\sum_{n} \binom{n}{k} p_n y^{n-k}\Bigr) z^k. $$ The corresponding power series has thus a `k`-th coefficient equal to $\sum_{n} \binom{n}{k} p_n y^{n-k}$. In the general case where `pₙ` is a multilinear map, this has to be interpreted suitably: instead of having a binomial coefficient, one should sum over all possible subsets `s` of `fin n` of cardinal `k`, and attribute `z` to the indices in `s` and `y` to the indices outside of `s`. In this paragraph, we implement this. The new power series is called `p.change_origin y`. Then, we check its convergence and the fact that its sum coincides with the original sum. The outcome of this discussion is that the set of points where a function is analytic is open. -/ namespace formal_multilinear_series section variables (p : formal_multilinear_series 𝕜 E F) {x y : E} {r R : ℝ≥0} /-- A term of `formal_multilinear_series.change_origin_series`. Given a formal multilinear series `p` and a point `x` in its ball of convergence, `p.change_origin x` is a formal multilinear series such that `p.sum (x+y) = (p.change_origin x).sum y` when this makes sense. Each term of `p.change_origin x` is itself an analytic function of `x` given by the series `p.change_origin_series`. Each term in `change_origin_series` is the sum of `change_origin_series_term`'s over all `s` of cardinality `l`. -/ def change_origin_series_term (k l : ℕ) (s : finset (fin (k + l))) (hs : s.card = l) : E [×l]→L[𝕜] E [×k]→L[𝕜] F := continuous_multilinear_map.curry_fin_finset 𝕜 E F hs (by erw [finset.card_compl, fintype.card_fin, hs, add_tsub_cancel_right]) (p $ k + l) lemma change_origin_series_term_apply (k l : ℕ) (s : finset (fin (k + l))) (hs : s.card = l) (x y : E) : p.change_origin_series_term k l s hs (λ _, x) (λ _, y) = p (k + l) (s.piecewise (λ _, x) (λ _, y)) := continuous_multilinear_map.curry_fin_finset_apply_const _ _ _ _ _ @[simp] lemma norm_change_origin_series_term (k l : ℕ) (s : finset (fin (k + l))) (hs : s.card = l) : ∥p.change_origin_series_term k l s hs∥ = ∥p (k + l)∥ := by simp only [change_origin_series_term, linear_isometry_equiv.norm_map] @[simp] lemma nnnorm_change_origin_series_term (k l : ℕ) (s : finset (fin (k + l))) (hs : s.card = l) : ∥p.change_origin_series_term k l s hs∥₊ = ∥p (k + l)∥₊ := by simp only [change_origin_series_term, linear_isometry_equiv.nnnorm_map] lemma nnnorm_change_origin_series_term_apply_le (k l : ℕ) (s : finset (fin (k + l))) (hs : s.card = l) (x y : E) : ∥p.change_origin_series_term k l s hs (λ _, x) (λ _, y)∥₊ ≤ ∥p (k + l)∥₊ * ∥x∥₊ ^ l * ∥y∥₊ ^ k := begin rw [← p.nnnorm_change_origin_series_term k l s hs, ← fin.prod_const, ← fin.prod_const], apply continuous_multilinear_map.le_of_op_nnnorm_le, apply continuous_multilinear_map.le_op_nnnorm end /-- The power series for `f.change_origin k`. Given a formal multilinear series `p` and a point `x` in its ball of convergence, `p.change_origin x` is a formal multilinear series such that `p.sum (x+y) = (p.change_origin x).sum y` when this makes sense. -/ def change_origin_series (k : ℕ) : formal_multilinear_series 𝕜 E (E [×k]→L[𝕜] F) := λ l, ∑ s : {s : finset (fin (k + l)) // finset.card s = l}, p.change_origin_series_term k l s s.2 lemma nnnorm_change_origin_series_le_tsum (k l : ℕ) : ∥p.change_origin_series k l∥₊ ≤ ∑' (x : {s : finset (fin (k + l)) // s.card = l}), ∥p (k + l)∥₊ := (nnnorm_sum_le _ _).trans_eq $ by simp only [tsum_fintype, nnnorm_change_origin_series_term] lemma nnnorm_change_origin_series_apply_le_tsum (k l : ℕ) (x : E) : ∥p.change_origin_series k l (λ _, x)∥₊ ≤ ∑' s : {s : finset (fin (k + l)) // s.card = l}, ∥p (k + l)∥₊ * ∥x∥₊ ^ l := begin rw [nnreal.tsum_mul_right, ← fin.prod_const], exact (p.change_origin_series k l).le_of_op_nnnorm_le _ (p.nnnorm_change_origin_series_le_tsum _ _) end /-- Changing the origin of a formal multilinear series `p`, so that `p.sum (x+y) = (p.change_origin x).sum y` when this makes sense. -/ def change_origin (x : E) : formal_multilinear_series 𝕜 E F := λ k, (p.change_origin_series k).sum x /-- An auxiliary equivalence useful in the proofs about `formal_multilinear_series.change_origin_series`: the set of triples `(k, l, s)`, where `s` is a `finset (fin (k + l))` of cardinality `l` is equivalent to the set of pairs `(n, s)`, where `s` is a `finset (fin n)`. The forward map sends `(k, l, s)` to `(k + l, s)` and the inverse map sends `(n, s)` to `(n - finset.card s, finset.card s, s)`. The actual definition is less readable because of problems with non-definitional equalities. -/ @[simps] def change_origin_index_equiv : (Σ k l : ℕ, {s : finset (fin (k + l)) // s.card = l}) ≃ Σ n : ℕ, finset (fin n) := { to_fun := λ s, ⟨s.1 + s.2.1, s.2.2⟩, inv_fun := λ s, ⟨s.1 - s.2.card, s.2.card, ⟨s.2.map (fin.cast $ (tsub_add_cancel_of_le $ card_finset_fin_le s.2).symm).to_equiv.to_embedding, finset.card_map _⟩⟩, left_inv := begin rintro ⟨k, l, ⟨s : finset (fin $ k + l), hs : s.card = l⟩⟩, dsimp only [subtype.coe_mk], -- Lean can't automatically generalize `k' = k + l - s.card`, `l' = s.card`, so we explicitly -- formulate the generalized goal suffices : ∀ k' l', k' = k → l' = l → ∀ (hkl : k + l = k' + l') hs', (⟨k', l', ⟨finset.map (fin.cast hkl).to_equiv.to_embedding s, hs'⟩⟩ : (Σ k l : ℕ, {s : finset (fin (k + l)) // s.card = l})) = ⟨k, l, ⟨s, hs⟩⟩, { apply this; simp only [hs, add_tsub_cancel_right] }, rintro _ _ rfl rfl hkl hs', simp only [equiv.refl_to_embedding, fin.cast_refl, finset.map_refl, eq_self_iff_true, order_iso.refl_to_equiv, and_self, heq_iff_eq] end, right_inv := begin rintro ⟨n, s⟩, simp [tsub_add_cancel_of_le (card_finset_fin_le s), fin.cast_to_equiv] end } lemma change_origin_series_summable_aux₁ {r r' : ℝ≥0} (hr : (r + r' : ℝ≥0∞) < p.radius) : summable (λ s : Σ k l : ℕ, {s : finset (fin (k + l)) // s.card = l}, ∥p (s.1 + s.2.1)∥₊ * r ^ s.2.1 * r' ^ s.1) := begin rw ← change_origin_index_equiv.symm.summable_iff, dsimp only [(∘), change_origin_index_equiv_symm_apply_fst, change_origin_index_equiv_symm_apply_snd_fst], have : ∀ n : ℕ, has_sum (λ s : finset (fin n), ∥p (n - s.card + s.card)∥₊ * r ^ s.card * r' ^ (n - s.card)) (∥p n∥₊ * (r + r') ^ n), { intro n, -- TODO: why `simp only [tsub_add_cancel_of_le (card_finset_fin_le _)]` fails? convert_to has_sum (λ s : finset (fin n), ∥p n∥₊ * (r ^ s.card * r' ^ (n - s.card))) _, { ext1 s, rw [tsub_add_cancel_of_le (card_finset_fin_le _), mul_assoc] }, rw ← fin.sum_pow_mul_eq_add_pow, exact (has_sum_fintype _).mul_left _ }, refine nnreal.summable_sigma.2 ⟨λ n, (this n).summable, _⟩, simp only [(this _).tsum_eq], exact p.summable_nnnorm_mul_pow hr end lemma change_origin_series_summable_aux₂ (hr : (r : ℝ≥0∞) < p.radius) (k : ℕ) : summable (λ s : Σ l : ℕ, {s : finset (fin (k + l)) // s.card = l}, ∥p (k + s.1)∥₊ * r ^ s.1) := begin rcases ennreal.lt_iff_exists_add_pos_lt.1 hr with ⟨r', h0, hr'⟩, simpa only [mul_inv_cancel_right₀ (pow_pos h0 _).ne'] using ((nnreal.summable_sigma.1 (p.change_origin_series_summable_aux₁ hr')).1 k).mul_right (r' ^ k)⁻¹ end lemma change_origin_series_summable_aux₃ {r : ℝ≥0} (hr : ↑r < p.radius) (k : ℕ) : summable (λ l : ℕ, ∥p.change_origin_series k l∥₊ * r ^ l) := begin refine nnreal.summable_of_le (λ n, _) (nnreal.summable_sigma.1 $ p.change_origin_series_summable_aux₂ hr k).2, simp only [nnreal.tsum_mul_right], exact mul_le_mul' (p.nnnorm_change_origin_series_le_tsum _ _) le_rfl end lemma le_change_origin_series_radius (k : ℕ) : p.radius ≤ (p.change_origin_series k).radius := ennreal.le_of_forall_nnreal_lt $ λ r hr, le_radius_of_summable_nnnorm _ (p.change_origin_series_summable_aux₃ hr k) lemma nnnorm_change_origin_le (k : ℕ) (h : (∥x∥₊ : ℝ≥0∞) < p.radius) : ∥p.change_origin x k∥₊ ≤ ∑' s : Σ l : ℕ, {s : finset (fin (k + l)) // s.card = l}, ∥p (k + s.1)∥₊ * ∥x∥₊ ^ s.1 := begin refine tsum_of_nnnorm_bounded _ (λ l, p.nnnorm_change_origin_series_apply_le_tsum k l x), have := p.change_origin_series_summable_aux₂ h k, refine has_sum.sigma this.has_sum (λ l, _), exact ((nnreal.summable_sigma.1 this).1 l).has_sum end /-- The radius of convergence of `p.change_origin x` is at least `p.radius - ∥x∥`. In other words, `p.change_origin x` is well defined on the largest ball contained in the original ball of convergence.-/ lemma change_origin_radius : p.radius - ∥x∥₊ ≤ (p.change_origin x).radius := begin refine ennreal.le_of_forall_pos_nnreal_lt (λ r h0 hr, _), rw [lt_tsub_iff_right, add_comm] at hr, have hr' : (∥x∥₊ : ℝ≥0∞) < p.radius, from (le_add_right le_rfl).trans_lt hr, apply le_radius_of_summable_nnnorm, have : ∀ k : ℕ, ∥p.change_origin x k∥₊ * r ^ k ≤ (∑' s : Σ l : ℕ, {s : finset (fin (k + l)) // s.card = l}, ∥p (k + s.1)∥₊ * ∥x∥₊ ^ s.1) * r ^ k, from λ k, mul_le_mul_right' (p.nnnorm_change_origin_le k hr') (r ^ k), refine nnreal.summable_of_le this _, simpa only [← nnreal.tsum_mul_right] using (nnreal.summable_sigma.1 (p.change_origin_series_summable_aux₁ hr)).2 end end -- From this point on, assume that the space is complete, to make sure that series that converge -- in norm also converge in `F`. variables [complete_space F] (p : formal_multilinear_series 𝕜 E F) {x y : E} {r R : ℝ≥0} lemma has_fpower_series_on_ball_change_origin (k : ℕ) (hr : 0 < p.radius) : has_fpower_series_on_ball (λ x, p.change_origin x k) (p.change_origin_series k) 0 p.radius := have _ := p.le_change_origin_series_radius k, ((p.change_origin_series k).has_fpower_series_on_ball (hr.trans_le this)).mono hr this /-- Summing the series `p.change_origin x` at a point `y` gives back `p (x + y)`-/ theorem change_origin_eval (h : (∥x∥₊ + ∥y∥₊ : ℝ≥0∞) < p.radius) : (p.change_origin x).sum y = (p.sum (x + y)) := begin have radius_pos : 0 < p.radius := lt_of_le_of_lt (zero_le _) h, have x_mem_ball : x ∈ emetric.ball (0 : E) p.radius, from mem_emetric_ball_zero_iff.2 ((le_add_right le_rfl).trans_lt h), have y_mem_ball : y ∈ emetric.ball (0 : E) (p.change_origin x).radius, { refine mem_emetric_ball_zero_iff.2 (lt_of_lt_of_le _ p.change_origin_radius), rwa [lt_tsub_iff_right, add_comm] }, have x_add_y_mem_ball : x + y ∈ emetric.ball (0 : E) p.radius, { refine mem_emetric_ball_zero_iff.2 (lt_of_le_of_lt _ h), exact_mod_cast nnnorm_add_le x y }, set f : (Σ (k l : ℕ), {s : finset (fin (k + l)) // s.card = l}) → F := λ s, p.change_origin_series_term s.1 s.2.1 s.2.2 s.2.2.2 (λ _, x) (λ _, y), have hsf : summable f, { refine summable_of_nnnorm_bounded _ (p.change_origin_series_summable_aux₁ h) _, rintro ⟨k, l, s, hs⟩, dsimp only [subtype.coe_mk], exact p.nnnorm_change_origin_series_term_apply_le _ _ _ _ _ _ }, have hf : has_sum f ((p.change_origin x).sum y), { refine has_sum.sigma_of_has_sum ((p.change_origin x).summable y_mem_ball).has_sum (λ k, _) hsf, { dsimp only [f], refine continuous_multilinear_map.has_sum_eval _ _, have := (p.has_fpower_series_on_ball_change_origin k radius_pos).has_sum x_mem_ball, rw zero_add at this, refine has_sum.sigma_of_has_sum this (λ l, _) _, { simp only [change_origin_series, continuous_multilinear_map.sum_apply], apply has_sum_fintype }, { refine summable_of_nnnorm_bounded _ (p.change_origin_series_summable_aux₂ (mem_emetric_ball_zero_iff.1 x_mem_ball) k) (λ s, _), refine (continuous_multilinear_map.le_op_nnnorm _ _).trans_eq _, simp } } }, refine hf.unique (change_origin_index_equiv.symm.has_sum_iff.1 _), refine has_sum.sigma_of_has_sum (p.has_sum x_add_y_mem_ball) (λ n, _) (change_origin_index_equiv.symm.summable_iff.2 hsf), erw [(p n).map_add_univ (λ _, x) (λ _, y)], convert has_sum_fintype _, ext1 s, dsimp only [f, change_origin_series_term, (∘), change_origin_index_equiv_symm_apply_fst, change_origin_index_equiv_symm_apply_snd_fst, change_origin_index_equiv_symm_apply_snd_snd_coe], rw continuous_multilinear_map.curry_fin_finset_apply_const, have : ∀ m (hm : n = m), p n (s.piecewise (λ _, x) (λ _, y)) = p m ((s.map (fin.cast hm).to_equiv.to_embedding).piecewise (λ _, x) (λ _, y)), { rintro m rfl, simp, congr /- probably different `decidable_eq` instances -/ }, apply this end end formal_multilinear_series section variables [complete_space F] {f : E → F} {p : formal_multilinear_series 𝕜 E F} {x y : E} {r : ℝ≥0∞} /-- If a function admits a power series expansion `p` on a ball `B (x, r)`, then it also admits a power series on any subball of this ball (even with a different center), given by `p.change_origin`. -/ theorem has_fpower_series_on_ball.change_origin (hf : has_fpower_series_on_ball f p x r) (h : (∥y∥₊ : ℝ≥0∞) < r) : has_fpower_series_on_ball f (p.change_origin y) (x + y) (r - ∥y∥₊) := { r_le := begin apply le_trans _ p.change_origin_radius, exact tsub_le_tsub hf.r_le (le_refl _) end, r_pos := by simp [h], has_sum := λ z hz, begin convert (p.change_origin y).has_sum _, { rw [mem_emetric_ball_zero_iff, lt_tsub_iff_right, add_comm] at hz, rw [p.change_origin_eval (hz.trans_le hf.r_le), add_assoc, hf.sum], refine mem_emetric_ball_zero_iff.2 (lt_of_le_of_lt _ hz), exact_mod_cast nnnorm_add_le y z }, { refine emetric.ball_subset_ball (le_trans _ p.change_origin_radius) hz, exact tsub_le_tsub hf.r_le le_rfl } end } /-- If a function admits a power series expansion `p` on an open ball `B (x, r)`, then it is analytic at every point of this ball. -/ lemma has_fpower_series_on_ball.analytic_at_of_mem (hf : has_fpower_series_on_ball f p x r) (h : y ∈ emetric.ball x r) : analytic_at 𝕜 f y := begin have : (∥y - x∥₊ : ℝ≥0∞) < r, by simpa [edist_eq_coe_nnnorm_sub] using h, have := hf.change_origin this, rw [add_sub_cancel'_right] at this, exact this.analytic_at end variables (𝕜 f) /-- For any function `f` from a normed vector space to a Banach space, the set of points `x` such that `f` is analytic at `x` is open. -/ lemma is_open_analytic_at : is_open {x | analytic_at 𝕜 f x} := begin rw is_open_iff_mem_nhds, rintro x ⟨p, r, hr⟩, exact mem_of_superset (emetric.ball_mem_nhds _ hr.r_pos) (λ y hy, hr.analytic_at_of_mem hy) end end
8ea15b2e18459e10dc0ee8fb2df8d488dc3a2e99
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/algebra/star/order.lean
7cee569d67e6fcdde25230ed3ab7e15d1a762d89
[ "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
8,348
lean
/- Copyright (c) 2023 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import algebra.star.basic import group_theory.submonoid.basic /-! # Star ordered rings > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. We define the class `star_ordered_ring R`, which says that the order on `R` respects the star operation, i.e. an element `r` is nonnegative iff it is in the `add_submonoid` generated by elements of the form `star s * s`. In many cases, including all C⋆-algebras, this can be reduced to `0 ≤ r ↔ ∃ s, r = star s * s`. However, this generality is slightly more convenient (e.g., it allows us to register a `star_ordered_ring` instance for `ℚ`), and more closely resembles the literature (see the seminal paper [*The positive cone in Banach algebras*][kelleyVaught1953]) In order to accodomate `non_unital_semiring R`, we actually don't characterize nonnegativity, but rather the entire `≤` relation with `star_ordered_ring.le_iff`. However, notice that when `R` is a `non_unital_ring`, these are equivalent (see `star_ordered_ring.nonneg_iff` and `star_ordered_ring.of_nonneg_iff`). ## TODO * In a Banach star algebra without a well-defined square root, the natural ordering is given by the positive cone which is the _closure_ of the sums of elements `star r * r`. A weaker version of `star_ordered_ring` could be defined for this case (again, see [*The positive cone in Banach algebras*][kelleyVaught1953]). Note that the current definition has the advantage of not requiring a topology. -/ universe u variable {R : Type u} /-- An ordered `*`-ring is a ring which is both an `ordered_add_comm_group` and a `*`-ring, and the nonnegative elements constitute precisely the `add_submonoid` generated by elements of the form `star s * s`. If you are working with a `non_unital_ring` and not a `non_unital_semiring`, it may be more convenient do declare instances using `star_ordered_ring.of_nonneg_iff'`. -/ class star_ordered_ring (R : Type u) [non_unital_semiring R] [partial_order R] extends star_ring R := (add_le_add_left : ∀ a b : R, a ≤ b → ∀ c : R, c + a ≤ c + b) (le_iff : ∀ x y : R, x ≤ y ↔ ∃ p, p ∈ add_submonoid.closure (set.range $ λ s, star s * s) ∧ y = x + p) namespace star_ordered_ring @[priority 100] -- see note [lower instance priority] instance to_ordered_add_comm_monoid [non_unital_semiring R] [partial_order R] [star_ordered_ring R] : ordered_add_comm_monoid R := { ..show non_unital_semiring R, by apply_instance, ..show partial_order R, by apply_instance, ..show star_ordered_ring R, by apply_instance } @[priority 100] -- see note [lower instance priority] instance to_has_exists_add_of_le [non_unital_semiring R] [partial_order R] [star_ordered_ring R] : has_exists_add_of_le R := { exists_add_of_le := λ a b h, match (le_iff _ _).mp h with ⟨p, _, hp⟩ := ⟨p, hp⟩ end } @[priority 100] -- see note [lower instance priority] instance to_ordered_add_comm_group [non_unital_ring R] [partial_order R] [star_ordered_ring R] : ordered_add_comm_group R := { ..show non_unital_ring R, by apply_instance, ..show partial_order R, by apply_instance, ..show star_ordered_ring R, by apply_instance } /-- To construct a `star_ordered_ring` instance it suffices to show that `x ≤ y` if and only if `y = x + star s * s` for some `s : R`. This is provided for convenience because it holds in some common scenarios (e.g.,`ℝ≥0`, `C(X, ℝ≥0)`) and obviates the hassle of `add_submonoid.closure_induction` when creating those instances. If you are working with a `non_unital_ring` and not a `non_unital_semiring`, see `star_ordered_ring.of_nonneg_iff` for a more convenient version. -/ @[reducible] -- set note [reducible non-instances] def of_le_iff [non_unital_semiring R] [partial_order R] [star_ring R] (h_add : ∀ {x y : R}, x ≤ y → ∀ z, z + x ≤ z + y) (h_le_iff : ∀ x y : R, x ≤ y ↔ ∃ s, y = x + star s * s) : star_ordered_ring R := { add_le_add_left := @h_add, le_iff := λ x y, begin refine ⟨λ h, _, _⟩, { obtain ⟨p, hp⟩ := (h_le_iff x y).mp h, exact ⟨star p * p, add_submonoid.subset_closure ⟨p, rfl⟩, hp⟩ }, { rintro ⟨p, hp, hpxy⟩, revert x y hpxy, refine add_submonoid.closure_induction hp _ (λ x y h, add_zero x ▸ h.ge) _, { rintro _ ⟨s, rfl⟩ x y rfl, nth_rewrite 0 [←add_zero x], refine h_add _ x, exact (h_le_iff _ _).mpr ⟨s, by rw [zero_add]⟩ }, { rintro a b ha hb x y rfl, nth_rewrite 0 [←add_zero x], refine h_add ((ha 0 _ (zero_add a).symm).trans (hb a _ rfl)) x } } end, .. ‹star_ring R› } /-- When `R` is a non-unital ring, to construct a `star_ordered_ring` instance it suffices to show that the nonnegative elements are precisely those elements in the `add_submonoid` generated by `star s * s` for `s : R`. -/ @[reducible] -- set note [reducible non-instances] def of_nonneg_iff [non_unital_ring R] [partial_order R] [star_ring R] (h_add : ∀ {x y : R}, x ≤ y → ∀ z, z + x ≤ z + y) (h_nonneg_iff : ∀ x : R, 0 ≤ x ↔ x ∈ add_submonoid.closure (set.range $ λ s : R, star s * s)) : star_ordered_ring R := { add_le_add_left := @h_add, le_iff := λ x y, begin haveI : covariant_class R R (+) (≤) := ⟨λ _ _ _ h, h_add h _⟩, simpa only [←sub_eq_iff_eq_add', sub_nonneg, exists_eq_right'] using h_nonneg_iff (y - x), end, .. ‹star_ring R› } /-- When `R` is a non-unital ring, to construct a `star_ordered_ring` instance it suffices to show that the nonnegative elements are precisely those elements of the form `star s * s` for `s : R`. This is provided for convenience because it holds in many common scenarios (e.g.,`ℝ`, `ℂ`, or any C⋆-algebra), and obviates the hassle of `add_submonoid.closure_induction` when creating those instances. -/ @[reducible] -- set note [reducible non-instances] def of_nonneg_iff' [non_unital_ring R] [partial_order R] [star_ring R] (h_add : ∀ {x y : R}, x ≤ y → ∀ z, z + x ≤ z + y) (h_nonneg_iff : ∀ x : R, 0 ≤ x ↔ ∃ s, x = star s * s) : star_ordered_ring R := of_le_iff @h_add begin haveI : covariant_class R R (+) (≤) := ⟨λ _ _ _ h, h_add h _⟩, simpa [sub_eq_iff_eq_add', sub_nonneg] using λ x y, h_nonneg_iff (y - x), end lemma nonneg_iff [non_unital_semiring R] [partial_order R] [star_ordered_ring R] {x : R} : 0 ≤ x ↔ x ∈ add_submonoid.closure (set.range $ λ s : R, star s * s) := by simp only [le_iff, zero_add, exists_eq_right'] end star_ordered_ring section non_unital_semiring variables [non_unital_semiring R] [partial_order R] [star_ordered_ring R] lemma star_mul_self_nonneg (r : R) : 0 ≤ star r * r := star_ordered_ring.nonneg_iff.mpr $ add_submonoid.subset_closure ⟨r, rfl⟩ lemma star_mul_self_nonneg' (r : R) : 0 ≤ r * star r := by { nth_rewrite_rhs 0 [←star_star r], exact star_mul_self_nonneg (star r) } lemma conjugate_nonneg {a : R} (ha : 0 ≤ a) (c : R) : 0 ≤ star c * a * c := begin rw star_ordered_ring.nonneg_iff at ha, refine add_submonoid.closure_induction ha (λ x hx, _) (by rw [mul_zero, zero_mul]) (λ x y hx hy, _), { obtain ⟨x, rfl⟩ := hx, convert star_mul_self_nonneg (x * c) using 1, rw [star_mul, ←mul_assoc, mul_assoc _ _ c] }, { calc 0 ≤ star c * x * c + 0 : by rw [add_zero]; exact hx ... ≤ star c * x * c + star c * y * c : star_ordered_ring.add_le_add_left _ _ hy _ ... ≤ _ : by rw [mul_add, add_mul] } end lemma conjugate_nonneg' {a : R} (ha : 0 ≤ a) (c : R) : 0 ≤ c * a * star c := by simpa only [star_star] using conjugate_nonneg ha (star c) lemma conjugate_le_conjugate {a b : R} (hab : a ≤ b) (c : R) : star c * a * c ≤ star c * b * c := begin rw [star_ordered_ring.le_iff] at hab ⊢, obtain ⟨p, hp, rfl⟩ := hab, simp_rw [←star_ordered_ring.nonneg_iff] at hp ⊢, exact ⟨star c * p * c, conjugate_nonneg hp c, by simp only [add_mul, mul_add]⟩, end lemma conjugate_le_conjugate' {a b : R} (hab : a ≤ b) (c : R) : c * a * star c ≤ c * b * star c := by simpa only [star_star] using conjugate_le_conjugate hab (star c) end non_unital_semiring
8926253d08d76da21002dc7ed3dec8a513793452
80746c6dba6a866de5431094bf9f8f841b043d77
/src/ring_theory/principal_ideal_domain.lean
102e2d1eda3a5a501bb57819a13a7c7fe68c2009
[ "Apache-2.0" ]
permissive
leanprover-fork/mathlib-backup
8b5c95c535b148fca858f7e8db75a76252e32987
0eb9db6a1a8a605f0cf9e33873d0450f9f0ae9b0
refs/heads/master
1,585,156,056,139
1,548,864,430,000
1,548,864,438,000
143,964,213
0
0
Apache-2.0
1,550,795,966,000
1,533,705,322,000
Lean
UTF-8
Lean
false
false
6,769
lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Chris Hughes, Morenikeji Neri -/ import algebra.euclidean_domain import ring_theory.ideals ring_theory.noetherian ring_theory.unique_factorization_domain variables {α : Type*} open set function ideal local attribute [instance] classical.prop_decidable class ideal.is_principal [comm_ring α] (S : ideal α) : Prop := (principal : ∃ a, S = span {a}) class principal_ideal_domain (α : Type*) extends integral_domain α := (principal : ∀ (S : ideal α), S.is_principal) attribute [instance] principal_ideal_domain.principal namespace ideal.is_principal variable [comm_ring α] noncomputable def generator (S : ideal α) [S.is_principal] : α := classical.some (principal S) lemma span_singleton_generator (S : ideal α) [S.is_principal] : span {generator S} = S := eq.symm (classical.some_spec (principal S)) @[simp] lemma generator_mem (S : ideal α) [S.is_principal] : generator S ∈ S := by conv {to_rhs, rw ← span_singleton_generator S}; exact subset_span (mem_singleton _) lemma mem_iff_generator_dvd (S : ideal α) [S.is_principal] {x : α} : x ∈ S ↔ generator S ∣ x := by rw [← mem_span_singleton, span_singleton_generator] lemma eq_bot_iff_generator_eq_zero (S : ideal α) [S.is_principal] : S = ⊥ ↔ generator S = 0 := by rw [← span_singleton_eq_bot, span_singleton_generator] end ideal.is_principal namespace is_prime open ideal.is_principal ideal lemma to_maximal_ideal [principal_ideal_domain α] {S : ideal α} [hpi : is_prime S] (hS : S ≠ ⊥) : is_maximal S := is_maximal_iff.2 ⟨(ne_top_iff_one S).1 hpi.1, begin assume T x hST hxS hxT, haveI := principal_ideal_domain.principal S, haveI := principal_ideal_domain.principal T, cases (mem_iff_generator_dvd _).1 (hST $ generator_mem S) with z hz, cases hpi.2 (show generator T * z ∈ S, from hz ▸ generator_mem S), { have hTS : T ≤ S, rwa [← span_singleton_generator T, span_le, singleton_subset_iff], exact (hxS $ hTS hxT).elim }, cases (mem_iff_generator_dvd _).1 h with y hy, have : generator S ≠ 0 := mt (eq_bot_iff_generator_eq_zero _).2 hS, rw [← mul_one (generator S), hy, mul_left_comm, domain.mul_left_inj this] at hz, exact hz.symm ▸ ideal.mul_mem_right _ (generator_mem T) end⟩ end is_prime section open euclidean_domain variable [euclidean_domain α] lemma mod_mem_iff {S : ideal α} {x y : α} (hy : y ∈ S) : x % y ∈ S ↔ x ∈ S := ⟨λ hxy, div_add_mod x y ▸ ideal.add_mem S (mul_mem_right S hy) hxy, λ hx, (mod_eq_sub_mul_div x y).symm ▸ ideal.sub_mem S hx (ideal.mul_mem_right S hy)⟩ instance euclidean_domain.to_principal_ideal_domain : principal_ideal_domain α := { principal := λ S, by exactI ⟨if h : {x : α | x ∈ S ∧ x ≠ 0} = ∅ then ⟨0, submodule.ext $ λ a, by rw [← @submodule.bot_coe α α _ _ ring.to_module, span_eq, submodule.mem_bot]; exact ⟨λ haS, by_contradiction $ λ ha0, eq_empty_iff_forall_not_mem.1 h a ⟨haS, ha0⟩, λ h₁, h₁.symm ▸ S.zero_mem⟩⟩ else have wf : well_founded euclidean_domain.r := euclidean_domain.r_well_founded α, have hmin : well_founded.min wf {x : α | x ∈ S ∧ x ≠ 0} h ∈ S ∧ well_founded.min wf {x : α | x ∈ S ∧ x ≠ 0} h ≠ 0, from well_founded.min_mem wf {x : α | x ∈ S ∧ x ≠ 0} h, ⟨well_founded.min wf {x : α | x ∈ S ∧ x ≠ 0} h, submodule.ext $ λ x, ⟨λ hx, div_add_mod x (well_founded.min wf {x : α | x ∈ S ∧ x ≠ 0} h) ▸ (mem_span_singleton.2 $ dvd_add (dvd_mul_right _ _) $ have (x % (well_founded.min wf {x : α | x ∈ S ∧ x ≠ 0} h) ∉ {x : α | x ∈ S ∧ x ≠ 0}), from λ h₁, well_founded.not_lt_min wf _ h h₁ (mod_lt x hmin.2), have x % well_founded.min wf {x : α | x ∈ S ∧ x ≠ 0} h = 0, by finish [(mod_mem_iff hmin.1).2 hx], by simp *), λ hx, let ⟨y, hy⟩ := mem_span_singleton.1 hx in hy.symm ▸ ideal.mul_mem_right _ hmin.1⟩⟩⟩ } end namespace principal_ideal_domain variables [principal_ideal_domain α] lemma is_noetherian_ring : is_noetherian_ring α := assume s : ideal α, begin cases (principal s).principal with a hs, refine ⟨finset.singleton a, submodule.ext' _⟩, rw hs, refl end section local attribute [instance] classical.prop_decidable open submodule lemma factors_decreasing (b₁ b₂ : α) (h₁ : b₁ ≠ 0) (h₂ : ¬ is_unit b₂) : submodule.span α ({b₁ * b₂} : set α) < submodule.span α {b₁} := lt_of_le_not_le (ideal.span_le.2 $ singleton_subset_iff.2 $ ideal.mem_span_singleton.2 ⟨b₂, rfl⟩) $ λ h, h₂ $ is_unit_of_dvd_one _ $ (mul_dvd_mul_iff_left h₁).1 $ by rwa [mul_one, ← ideal.span_singleton_le_span_singleton] end lemma is_maximal_of_irreducible {p : α} (hp : irreducible p) : is_maximal (span ({p} : set α)) := ⟨mt span_singleton_eq_top.1 hp.1, λ I hI, begin rcases principal I with ⟨a, rfl⟩, rw span_singleton_eq_top, unfreezeI, rcases span_singleton_le_span_singleton.1 (le_of_lt hI) with ⟨b, rfl⟩, refine (of_irreducible_mul hp).resolve_right (mt (λ hb, _) (not_le_of_lt hI)), rw [span_singleton_le_span_singleton, mul_dvd_of_is_unit_right hb] end⟩ lemma irreducible_iff_prime {p : α} : irreducible p ↔ prime p := ⟨λ hp, (span_singleton_prime $ nonzero_of_irreducible hp).1 $ (is_maximal_of_irreducible hp).is_prime, irreducible_of_prime⟩ lemma associates_irreducible_iff_prime : ∀{p : associates α}, irreducible p ↔ p.prime := associates.forall_associated.2 $ assume a, by rw [associates.irreducible_mk_iff, associates.prime_mk, irreducible_iff_prime] section local attribute [instance] classical.prop_decidable noncomputable def factors (a : α) : multiset α := if h : a = 0 then ∅ else classical.some (is_noetherian_ring.exists_factors is_noetherian_ring a h) lemma factors_spec (a : α) (h : a ≠ 0) : (∀b∈factors a, irreducible b) ∧ associated a (factors a).prod := begin unfold factors, rw [dif_neg h], exact classical.some_spec (is_noetherian_ring.exists_factors is_noetherian_ring a h) end /-- The unique factorization domain structure given by the principal ideal domain. This is not added as type class instance, since the `factors` might be computed in a different way. E.g. factors could return normalized values. -/ noncomputable def to_unique_factorization_domain : unique_factorization_domain α := { factors := factors, factors_prod := assume a ha, associated.symm (factors_spec a ha).2, prime_factors := assume a ha, by simpa [irreducible_iff_prime] using (factors_spec a ha).1 } end end principal_ideal_domain
91a196207f2557d403440a8f0803d10f67bb0197
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/run/array2.lean
9071235ef1ecff74f3180330c0b91dc5ca1b78f4
[ "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
300
lean
#check @d_array.mk local infix ` << `:20 := array.push_back def test1 := let v1 := mk_array 3 2, v2 := v1 << 3 << 4, v3 := (v2 << 5)^.write' 0 0 in (v1, v2, v3) #eval test1 def tst1 (n : nat) := let v1 := (mk_array n 1), v2 := v1.map (λ v, v + 1) in v2^.read' 1 #eval tst1 10
3b2a5fc3458ed32a88f731fa69c3fda71496e01a
129628888508a22919f176e3ba2033c3b52fa859
/src/quadratic_extns.lean
8411623c3a532020c2f33d1525f3f3a8cd8b5d2d
[ "Apache-2.0" ]
permissive
ImperialCollegeLondon/P11-Galois-Theory
1aa35b6aa71c08aec6da3296ba404bf246db8df3
ced2caa52300feb633316b3120c40ca957c8e8ff
refs/heads/master
1,671,253,848,362
1,600,080,687,000
1,600,080,687,000
160,926,153
4
0
null
null
null
null
UTF-8
Lean
false
false
3,786
lean
import data.rat import data.polynomial import data.int.basic import data.set import ring_theory.adjoin_root import ring_theory.polynomial import data.nat.prime import algebra.ring import .normal import data.finsupp import linear_algebra.finite_dimensional noncomputable theory universes u v open polynomial open finsupp open finite_dimensional variables {F : Type u} {L : Type v} variables [field F] [field L] [algebra F L] [finite_dimensional F L] lemma sub_eq_plus_minus (a : F) : (X - C a) = (X + C (-a)) := by { simp, ring } lemma zero_eq_zero_coe : (0 : with_bot ℕ) = ↑(0 : ℕ) := rfl lemma one_eq_one_coe : (1 : with_bot ℕ) = ↑(1 : ℕ) := rfl lemma two_eq_two_coe : (2 : with_bot ℕ) = ↑(2 : ℕ) := rfl lemma coe_sum_eq_sum_coe (a b : ℕ) : ↑(a + b) = ↑a + (↑b : with_bot ℕ) := rfl lemma ne_zero_of_degree_eq_n_gt {p : polynomial F} {n : nat} (hn : 0 < n) (hp : degree p = n) : (p ≠ 0) := begin have degree_gt_zero : 0 < degree p, { simp [hp, zero_eq_zero_coe, ←with_bot.some_eq_coe], exact hn, }, apply ne_zero_of_degree_gt degree_gt_zero, end lemma ne_zero_of_degree_one {p : polynomial F} (hp : degree p = 1) : (p ≠ 0) := ne_zero_of_degree_eq_n_gt zero_lt_one hp lemma ne_zero_of_degree_two {p : polynomial F} (hp : degree p = 2) : (p ≠ 0) := ne_zero_of_degree_eq_n_gt zero_lt_two hp lemma splits_of_degree_two_root (f : polynomial F) (f_deg2 : degree f = 2) (a : F) (ha : is_root f a) : (splits (algebra_map F L) f) := begin intros, let i := (algebra_map F L), let f1 := (X - C a), have f_nz : f ≠ 0, from ne_zero_of_degree_two f_deg2, have sub_eq_plus_minus : (X - C a) = (X + C (-a)), { simp, ring }, have d : f1 ∣ f, from iff.elim_right dvd_iff_is_root ha, have f1_deg_1 : degree f1 = 1, by simp [f1], have f1_nz : f1 ≠ 0, from ne_zero_of_degree_one f1_deg_1, have f1_monic : monic f1, { rw congr_arg monic sub_eq_plus_minus, -- this ought to be able to be done by simp apply (monic_X_add_C (-a)) }, let f2 := (f /ₘ f1), have f2_nz : f2 ≠ 0, { simp [div_by_monic_eq_zero_iff f1_monic f1_nz, f_deg2], rw [two_eq_two_coe], rw [one_eq_one_coe], simp [←with_bot.some_eq_coe] }, have f2_deg_1 : degree f2 = 1, -- this section is unwieldly { have equation : degree f1 + degree (f /ₘ f1) = degree f, { have deg_f1_lt_deg_f : degree f1 ≤ degree f, { simp [f1_deg_1, f_deg2], rw [two_eq_two_coe], rw [one_eq_one_coe], simp [←with_bot.some_eq_coe] }, apply degree_add_div_by_monic f1_monic deg_f1_lt_deg_f }, have equivalence : degree f1 + degree (f /ₘ f1) = degree f ↔ degree f2 = 1, { calc degree f1 + degree (f /ₘ f1) = degree f ↔ degree f1 + degree f2 = degree f : by simp [f2] ... ↔ 1 + degree f2 = 2 : by rw [f1_deg_1, f_deg2] ... ↔ ↑(1) + degree f2 = ↑(2) : by rw [two_eq_two_coe, one_eq_one_coe] ... ↔ ↑(1) + ↑(nat_degree f2) = ↑(2) : by rw [degree_eq_nat_degree f2_nz] ... ↔ ↑((1 : ℕ) + nat_degree f2) = ↑((2 : ℕ)) : by rw [coe_sum_eq_sum_coe] ... ↔ (1 + nat_degree f2) = (2) : with_bot.coe_eq_coe ... ↔ nat_degree f2 = 1 : by simp [bit0] ... ↔ degree f2 = 1 : by simp [←degree_eq_iff_nat_degree_eq f2_nz]}, rw [←equivalence], apply equation }, have s1 : splits i f1, by apply splits_of_degree_eq_one i f1_deg_1, have s2 : splits i f2, by apply splits_of_degree_eq_one i f2_deg_1, have mul_f : f = f1 * f2, { simp [f2, f1], exact (eq.symm (iff.elim_right mul_div_by_monic_eq_iff_is_root ha)) }, rw congr_arg (splits i) mul_f, apply splits_mul i s1 s2 end lemma degree_le_findim (x : L) {hx : is_integral F x} : degree (minimal_polynomial hx) ≤ findim F L := sorry theorem normal_of_degree_two_extension (h : findim F L = 2) : normal F L := sorry
54c483275ff1480e653cb0216b5458a2c3b64674
35677d2df3f081738fa6b08138e03ee36bc33cad
/src/analysis/calculus/mean_value.lean
6f0fdf8534396e7a220eddb001e4c0c28a44cc59
[ "Apache-2.0" ]
permissive
gebner/mathlib
eab0150cc4f79ec45d2016a8c21750244a2e7ff0
cc6a6edc397c55118df62831e23bfbd6e6c6b4ab
refs/heads/master
1,625,574,853,976
1,586,712,827,000
1,586,712,827,000
99,101,412
1
0
Apache-2.0
1,586,716,389,000
1,501,667,958,000
Lean
UTF-8
Lean
false
false
38,681
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 analysis.calculus.local_extr import analysis.convex.topology /-! # The mean value inequality and equalities In this file we prove the following facts: * `convex.norm_image_sub_le_of_norm_deriv_le` : if `f` is differentaible on a convex set `s` and the norm of its derivative is bounded by `C`, then `f` is Lipschitz continuous on `s` with constant `C`. * `image_le_of*`, `image_norm_le_of_*` : several similar lemmas deducing `f x ≤ B x` or `∥f x∥ ≤ B x` from upper estimates on `f'` or `∥f'∥`, respectively. These lemmas differ by their assumptions: * `of_liminf_*` lemmas assume that limit inferior of some ratio is less than `B' x`; * `of_deriv_right_*`, `of_norm_deriv_right_*` lemmas assume that the right derivative or its norm is less than `B' x`; * `of_*_lt_*` lemmas assume a strict inequality whenever `f x = B x` or `∥f x∥ = B x`; * `of_*_le_*` lemmas assume a non-strict inequality everywhere on `[a, b)`; * name of a lemma ends with `'` if (1) it assumes that `B` is continuous on `[a, b]` and has a right derivative at every point of `[a, b)`, and (2) the lemma has a counterpart assuming that `B` is differentiable everywhere on `ℝ` * `norm_image_sub_le_*_segment` : if derivative of `f` on `[a, b]` is bounded above by a constant `C`, then `∥f x - f a∥ ≤ C * ∥x - a∥`; several versions deal with right derivative and derivative within `[a, b]` (`has_deriv_within_at` or `deriv_within`). * `convex.is_const_of_fderiv_within_eq_zero` : if a function has derivative `0` on a convex set `s`, then it is a constant on `s`. * `exists_ratio_has_deriv_at_eq_ratio_slope` and `exists_ratio_deriv_eq_ratio_slope` : Cauchy's Mean Value Theorem. * `exists_has_deriv_at_eq_slope` and `exists_deriv_eq_slope` : Lagrange's Mean Value Theorem. * `convex.image_sub_lt_mul_sub_of_deriv_lt`, `convex.mul_sub_lt_image_sub_of_lt_deriv`, `convex.image_sub_le_mul_sub_of_deriv_le`, `convex.mul_sub_le_image_sub_of_le_deriv`, if `∀ x, C (</≤/>/≥) (f' x)`, then `C * (y - x) (</≤/>/≥) (f y - f x)` whenever `x < y`. * `convex.mono_of_deriv_nonneg`, `convex.antimono_of_deriv_nonpos`, `convex.strict_mono_of_deriv_pos`, `convex.strict_antimono_of_deriv_neg` : if the derivative of a function is non-negative/non-positive/positive/negative, then the function is monotone/monotonically decreasing/strictly monotone/strictly monotonically decreasing. * `convex_on_of_deriv_mono`, `convex_on_of_deriv2_nonneg` : if the derivative of a function is increasing or its second derivative is nonnegative, then the original function is convex. -/ set_option class.instance_max_depth 120 variables {E : Type*} [normed_group E] [normed_space ℝ E] {F : Type*} [normed_group F] [normed_space ℝ F] open metric set asymptotics continuous_linear_map filter open_locale classical topological_space /-! ### One-dimensional fencing inequalities -/ /-- General fencing theorem for continuous functions with an estimate on the derivative. Let `f` and `B` be continuous functions on `[a, b]` such that * `f a ≤ B a`; * `B` has right derivative `B'` at every point of `[a, b)`; * for each `x ∈ [a, b)` the right-side limit inferior of `(f z - f x) / (z - x)` is bounded above by a function `f'`; * we have `f' x < B' x` whenever `f x = B x`. Then `f x ≤ B x` everywhere on `[a, b]`. -/ lemma image_le_of_liminf_slope_right_lt_deriv_boundary' {f f' : ℝ → ℝ} {a b : ℝ} (hf : continuous_on f (Icc a b)) -- `hf'` actually says `liminf (z - x)⁻¹ * (f z - f x) ≤ f' x` (hf' : ∀ x ∈ Ico a b, ∀ r, f' x < r → ∃ᶠ z in nhds_within x (Ioi x), (z - x)⁻¹ * (f z - f x) < r) {B B' : ℝ → ℝ} (ha : f a ≤ B a) (hB : continuous_on B (Icc a b)) (hB' : ∀ x ∈ Ico a b, has_deriv_within_at B (B' x) (Ioi x) x) (bound : ∀ x ∈ Ico a b, f x = B x → f' x < B' x) : ∀ ⦃x⦄, x ∈ Icc a b → f x ≤ B x := begin change Icc a b ⊆ {x | f x ≤ B x}, set s := {x | f x ≤ B x} ∩ Icc a b, have A : continuous_on (λ x, (f x, B x)) (Icc a b), from hf.prod hB, have : is_closed s, { simp only [s, inter_comm], exact A.preimage_closed_of_closed is_closed_Icc order_closed_topology.is_closed_le' }, apply this.Icc_subset_of_forall_exists_gt ha, rintros x ⟨hxB, xab⟩ y hy, change f x ≤ B x at hxB, cases lt_or_eq_of_le hxB with hxB hxB, { -- If `f x < B x`, then all we need is continuity of both sides apply nonempty_of_mem_sets (nhds_within_Ioi_self_ne_bot x), refine inter_mem_sets _ (Ioc_mem_nhds_within_Ioi ⟨le_refl x, hy⟩), have : ∀ᶠ x in nhds_within x (Icc a b), f x < B x, from A x (Ico_subset_Icc_self xab) (mem_nhds_sets (is_open_lt continuous_fst continuous_snd) hxB), have : ∀ᶠ x in nhds_within x (Ioi x), f x < B x, from nhds_within_le_of_mem (Icc_mem_nhds_within_Ioi xab) this, refine mem_sets_of_superset this (set_of_subset_set_of.2 $ λ y, le_of_lt) }, { rcases dense (bound x xab hxB) with ⟨r, hfr, hrB⟩, specialize hf' x xab r hfr, have HB : ∀ᶠ z in nhds_within x (Ioi x), r < (z - x)⁻¹ * (B z - B x), from (has_deriv_within_at_iff_tendsto_slope' $ lt_irrefl x).1 (hB' x xab) (mem_nhds_sets is_open_Ioi hrB), obtain ⟨z, ⟨hfz, hzB⟩, hz⟩ : ∃ z, ((z - x)⁻¹ * (f z - f x) < r ∧ r < (z - x)⁻¹ * (B z - B x)) ∧ z ∈ Ioc x y, from ((hf'.and_eventually HB).and_eventually (Ioc_mem_nhds_within_Ioi ⟨le_refl _, hy⟩)).exists, have := le_of_lt (lt_trans hfz hzB), refine ⟨z, _, hz⟩, rw [mul_le_mul_left (inv_pos.2 $ sub_pos.2 hz.1), hxB, sub_le_sub_iff_right] at this, exact this } end /-- General fencing theorem for continuous functions with an estimate on the derivative. Let `f` and `B` be continuous functions on `[a, b]` such that * `f a ≤ B a`; * `B` has derivative `B'` everywhere on `ℝ`; * for each `x ∈ [a, b)` the right-side limit inferior of `(f z - f x) / (z - x)` is bounded above by a function `f'`; * we have `f' x < B' x` whenever `f x = B x`. Then `f x ≤ B x` everywhere on `[a, b]`. -/ lemma image_le_of_liminf_slope_right_lt_deriv_boundary {f f' : ℝ → ℝ} {a b : ℝ} (hf : continuous_on f (Icc a b)) -- `hf'` actually says `liminf (z - x)⁻¹ * (f z - f x) ≤ f' x` (hf' : ∀ x ∈ Ico a b, ∀ r, f' x < r → ∃ᶠ z in nhds_within x (Ioi x), (z - x)⁻¹ * (f z - f x) < r) {B B' : ℝ → ℝ} (ha : f a ≤ B a) (hB : ∀ x, has_deriv_at B (B' x) x) (bound : ∀ x ∈ Ico a b, f x = B x → f' x < B' x) : ∀ ⦃x⦄, x ∈ Icc a b → f x ≤ B x := image_le_of_liminf_slope_right_lt_deriv_boundary' hf hf' ha (λ x hx, (hB x).continuous_at.continuous_within_at) (λ x hx, (hB x).has_deriv_within_at) bound /-- General fencing theorem for continuous functions with an estimate on the derivative. Let `f` and `B` be continuous functions on `[a, b]` such that * `f a ≤ B a`; * `B` has right derivative `B'` at every point of `[a, b)`; * for each `x ∈ [a, b)` the right-side limit inferior of `(f z - f x) / (z - x)` is bounded above by `B'`. Then `f x ≤ B x` everywhere on `[a, b]`. -/ lemma image_le_of_liminf_slope_right_le_deriv_boundary {f : ℝ → ℝ} {a b : ℝ} (hf : continuous_on f (Icc a b)) {B B' : ℝ → ℝ} (ha : f a ≤ B a) (hB : continuous_on B (Icc a b)) (hB' : ∀ x ∈ Ico a b, has_deriv_within_at B (B' x) (Ioi x) x) -- `bound` actually says `liminf (z - x)⁻¹ * (f z - f x) ≤ B' x` (bound : ∀ x ∈ Ico a b, ∀ r, B' x < r → ∃ᶠ z in nhds_within x (Ioi x), (z - x)⁻¹ * (f z - f x) < r) : ∀ ⦃x⦄, x ∈ Icc a b → f x ≤ B x := begin have Hr : ∀ x ∈ Icc a b, ∀ r ∈ Ioi (0:ℝ), f x ≤ B x + r * (x - a), { intros x hx r hr, apply image_le_of_liminf_slope_right_lt_deriv_boundary' hf bound, { rwa [sub_self, mul_zero, add_zero] }, { exact hB.add (continuous_on_const.mul (continuous_id.continuous_on.sub continuous_on_const)) }, { assume x hx, exact (hB' x hx).add (((has_deriv_within_at_id x (Ioi x)).sub_const a).const_mul r) }, { assume x hx _, rw [mul_one], exact (lt_add_iff_pos_right _).2 hr }, exact hx }, assume x hx, have : continuous_within_at (λ r, B x + r * (x - a)) (Ioi 0) 0, from continuous_within_at_const.add (continuous_within_at_id.mul continuous_within_at_const), convert continuous_within_at_const.closure_le _ this (Hr x hx); simp [closure_Ioi] end /-- General fencing theorem for continuous functions with an estimate on the derivative. Let `f` and `B` be continuous functions on `[a, b]` such that * `f a ≤ B a`; * `B` has right derivative `B'` at every point of `[a, b)`; * `f` has right derivative `f'` at every point of `[a, b)`; * we have `f' x < B' x` whenever `f x = B x`. Then `f x ≤ B x` everywhere on `[a, b]`. -/ lemma image_le_of_deriv_right_lt_deriv_boundary' {f f' : ℝ → ℝ} {a b : ℝ} (hf : continuous_on f (Icc a b)) (hf' : ∀ x ∈ Ico a b, has_deriv_within_at f (f' x) (Ioi x) x) {B B' : ℝ → ℝ} (ha : f a ≤ B a) (hB : continuous_on B (Icc a b)) (hB' : ∀ x ∈ Ico a b, has_deriv_within_at B (B' x) (Ioi x) x) (bound : ∀ x ∈ Ico a b, f x = B x → f' x < B' x) : ∀ ⦃x⦄, x ∈ Icc a b → f x ≤ B x := image_le_of_liminf_slope_right_lt_deriv_boundary' hf (λ x hx r hr, (hf' x hx).liminf_right_slope_le hr) ha hB hB' bound /-- General fencing theorem for continuous functions with an estimate on the derivative. Let `f` and `B` be continuous functions on `[a, b]` such that * `f a ≤ B a`; * `B` has derivative `B'` everywhere on `ℝ`; * `f` has right derivative `f'` at every point of `[a, b)`; * we have `f' x < B' x` whenever `f x = B x`. Then `f x ≤ B x` everywhere on `[a, b]`. -/ lemma image_le_of_deriv_right_lt_deriv_boundary {f f' : ℝ → ℝ} {a b : ℝ} (hf : continuous_on f (Icc a b)) (hf' : ∀ x ∈ Ico a b, has_deriv_within_at f (f' x) (Ioi x) x) {B B' : ℝ → ℝ} (ha : f a ≤ B a) (hB : ∀ x, has_deriv_at B (B' x) x) (bound : ∀ x ∈ Ico a b, f x = B x → f' x < B' x) : ∀ ⦃x⦄, x ∈ Icc a b → f x ≤ B x := image_le_of_deriv_right_lt_deriv_boundary' hf hf' ha (λ x hx, (hB x).continuous_at.continuous_within_at) (λ x hx, (hB x).has_deriv_within_at) bound /-- General fencing theorem for continuous functions with an estimate on the derivative. Let `f` and `B` be continuous functions on `[a, b]` such that * `f a ≤ B a`; * `B` has derivative `B'` everywhere on `ℝ`; * `f` has right derivative `f'` at every point of `[a, b)`; * we have `f' x ≤ B' x` on `[a, b)`. Then `f x ≤ B x` everywhere on `[a, b]`. -/ lemma image_le_of_deriv_right_le_deriv_boundary {f f' : ℝ → ℝ} {a b : ℝ} (hf : continuous_on f (Icc a b)) (hf' : ∀ x ∈ Ico a b, has_deriv_within_at f (f' x) (Ioi x) x) {B B' : ℝ → ℝ} (ha : f a ≤ B a) (hB : continuous_on B (Icc a b)) (hB' : ∀ x ∈ Ico a b, has_deriv_within_at B (B' x) (Ioi x) x) (bound : ∀ x ∈ Ico a b, f' x ≤ B' x) : ∀ ⦃x⦄, x ∈ Icc a b → f x ≤ B x := image_le_of_liminf_slope_right_le_deriv_boundary hf ha hB hB' $ assume x hx r hr, (hf' x hx).liminf_right_slope_le (lt_of_le_of_lt (bound x hx) hr) /-! ### Vector-valued functions `f : ℝ → E` -/ section variables {f : ℝ → E} {a b : ℝ} /-- General fencing theorem for continuous functions with an estimate on the derivative. Let `f` and `B` be continuous functions on `[a, b]` such that * `∥f a∥ ≤ B a`; * `B` has right derivative at every point of `[a, b)`; * for each `x ∈ [a, b)` the right-side limit inferior of `(∥f z∥ - ∥f x∥) / (z - x)` is bounded above by a function `f'`; * we have `f' x < B' x` whenever `∥f x∥ = B x`. Then `∥f x∥ ≤ B x` everywhere on `[a, b]`. -/ lemma image_norm_le_of_liminf_right_slope_norm_lt_deriv_boundary {E : Type*} [normed_group E] {f : ℝ → E} {f' : ℝ → ℝ} (hf : continuous_on f (Icc a b)) -- `hf'` actually says `liminf ∥z - x∥⁻¹ * (∥f z∥ - ∥f x∥) ≤ f' x` (hf' : ∀ x ∈ Ico a b, ∀ r, f' x < r → ∃ᶠ z in nhds_within x (Ioi x), (z - x)⁻¹ * (∥f z∥ - ∥f x∥) < r) {B B' : ℝ → ℝ} (ha : ∥f a∥ ≤ B a) (hB : continuous_on B (Icc a b)) (hB' : ∀ x ∈ Ico a b, has_deriv_within_at B (B' x) (Ioi x) x) (bound : ∀ x ∈ Ico a b, ∥f x∥ = B x → f' x < B' x) : ∀ ⦃x⦄, x ∈ Icc a b → ∥f x∥ ≤ B x := image_le_of_liminf_slope_right_lt_deriv_boundary' (continuous_norm.comp_continuous_on hf) hf' ha hB hB' bound /-- General fencing theorem for continuous functions with an estimate on the norm of the derivative. Let `f` and `B` be continuous functions on `[a, b]` such that * `∥f a∥ ≤ B a`; * `f` and `B` have right derivatives `f'` and `B'` respectively at every point of `[a, b)`; * the norm of `f'` is strictly less than `B'` whenever `∥f x∥ = B x`. Then `∥f x∥ ≤ B x` everywhere on `[a, b]`. We use one-sided derivatives in the assumptions to make this theorem work for piecewise differentiable functions. -/ lemma image_norm_le_of_norm_deriv_right_lt_deriv_boundary' {f' : ℝ → E} (hf : continuous_on f (Icc a b)) (hf' : ∀ x ∈ Ico a b, has_deriv_within_at f (f' x) (Ioi x) x) {B B' : ℝ → ℝ} (ha : ∥f a∥ ≤ B a) (hB : continuous_on B (Icc a b)) (hB' : ∀ x ∈ Ico a b, has_deriv_within_at B (B' x) (Ioi x) x) (bound : ∀ x ∈ Ico a b, ∥f x∥ = B x → ∥f' x∥ < B' x) : ∀ ⦃x⦄, x ∈ Icc a b → ∥f x∥ ≤ B x := image_norm_le_of_liminf_right_slope_norm_lt_deriv_boundary hf (λ x hx r hr, (hf' x hx).liminf_right_slope_norm_le hr) ha hB hB' bound /-- General fencing theorem for continuous functions with an estimate on the norm of the derivative. Let `f` and `B` be continuous functions on `[a, b]` such that * `∥f a∥ ≤ B a`; * `f` has right derivative `f'` at every point of `[a, b)`; * `B` has derivative `B'` everywhere on `ℝ`; * the norm of `f'` is strictly less than `B'` whenever `∥f x∥ = B x`. Then `∥f x∥ ≤ B x` everywhere on `[a, b]`. We use one-sided derivatives in the assumptions to make this theorem work for piecewise differentiable functions. -/ lemma image_norm_le_of_norm_deriv_right_lt_deriv_boundary {f' : ℝ → E} (hf : continuous_on f (Icc a b)) (hf' : ∀ x ∈ Ico a b, has_deriv_within_at f (f' x) (Ioi x) x) {B B' : ℝ → ℝ} (ha : ∥f a∥ ≤ B a) (hB : ∀ x, has_deriv_at B (B' x) x) (bound : ∀ x ∈ Ico a b, ∥f x∥ = B x → ∥f' x∥ < B' x) : ∀ ⦃x⦄, x ∈ Icc a b → ∥f x∥ ≤ B x := image_norm_le_of_norm_deriv_right_lt_deriv_boundary' hf hf' ha (λ x hx, (hB x).continuous_at.continuous_within_at) (λ x hx, (hB x).has_deriv_within_at) bound /-- General fencing theorem for continuous functions with an estimate on the norm of the derivative. Let `f` and `B` be continuous functions on `[a, b]` such that * `∥f a∥ ≤ B a`; * `f` and `B` have right derivatives `f'` and `B'` respectively at every point of `[a, b)`; * we have `∥f' x∥ ≤ B x` everywhere on `[a, b)`. Then `∥f x∥ ≤ B x` everywhere on `[a, b]`. We use one-sided derivatives in the assumptions to make this theorem work for piecewise differentiable functions. -/ lemma image_norm_le_of_norm_deriv_right_le_deriv_boundary' {f' : ℝ → E} (hf : continuous_on f (Icc a b)) (hf' : ∀ x ∈ Ico a b, has_deriv_within_at f (f' x) (Ioi x) x) {B B' : ℝ → ℝ} (ha : ∥f a∥ ≤ B a) (hB : continuous_on B (Icc a b)) (hB' : ∀ x ∈ Ico a b, has_deriv_within_at B (B' x) (Ioi x) x) (bound : ∀ x ∈ Ico a b, ∥f' x∥ ≤ B' x) : ∀ ⦃x⦄, x ∈ Icc a b → ∥f x∥ ≤ B x := image_le_of_liminf_slope_right_le_deriv_boundary (continuous_norm.comp_continuous_on hf) ha hB hB' $ (λ x hx r hr, (hf' x hx).liminf_right_slope_norm_le (lt_of_le_of_lt (bound x hx) hr)) /-- General fencing theorem for continuous functions with an estimate on the norm of the derivative. Let `f` and `B` be continuous functions on `[a, b]` such that * `∥f a∥ ≤ B a`; * `f` has right derivative `f'` at every point of `[a, b)`; * `B` has derivative `B'` everywhere on `ℝ`; * we have `∥f' x∥ ≤ B x` everywhere on `[a, b)`. Then `∥f x∥ ≤ B x` everywhere on `[a, b]`. We use one-sided derivatives in the assumptions to make this theorem work for piecewise differentiable functions. -/ lemma image_norm_le_of_norm_deriv_right_le_deriv_boundary {f' : ℝ → E} (hf : continuous_on f (Icc a b)) (hf' : ∀ x ∈ Ico a b, has_deriv_within_at f (f' x) (Ioi x) x) {B B' : ℝ → ℝ} (ha : ∥f a∥ ≤ B a) (hB : ∀ x, has_deriv_at B (B' x) x) (bound : ∀ x ∈ Ico a b, ∥f' x∥ ≤ B' x) : ∀ ⦃x⦄, x ∈ Icc a b → ∥f x∥ ≤ B x := image_norm_le_of_norm_deriv_right_le_deriv_boundary' hf hf' ha (λ x hx, (hB x).continuous_at.continuous_within_at) (λ x hx, (hB x).has_deriv_within_at) bound /-- A function on `[a, b]` with the norm of the right derivative bounded by `C` satisfies `∥f x - f a∥ ≤ C * (x - a)`. -/ theorem norm_image_sub_le_of_norm_deriv_right_le_segment {f' : ℝ → E} {C : ℝ} (hf : continuous_on f (Icc a b)) (hf' : ∀ x ∈ Ico a b, has_deriv_within_at f (f' x) (Ioi x) x) (bound : ∀x ∈ Ico a b, ∥f' x∥ ≤ C) : ∀ x ∈ Icc a b, ∥f x - f a∥ ≤ C * (x - a) := begin let g := λ x, f x - f a, have hg : continuous_on g (Icc a b), from hf.sub continuous_on_const, have hg' : ∀ x ∈ Ico a b, has_deriv_within_at g (f' x) (Ioi x) x, { assume x hx, simpa using (hf' x hx).sub (has_deriv_within_at_const _ _ _) }, let B := λ x, C * (x - a), have hB : ∀ x, has_deriv_at B C x, { assume x, simpa using (has_deriv_at_const x C).mul ((has_deriv_at_id x).sub (has_deriv_at_const x a)) }, convert image_norm_le_of_norm_deriv_right_le_deriv_boundary hg hg' _ hB bound, { simp only [g, B] }, { simp only [g, B], rw [sub_self, _root_.norm_zero, sub_self, mul_zero] } end /-- A function on `[a, b]` with the norm of the derivative within `[a, b]` bounded by `C` satisfies `∥f x - f a∥ ≤ C * (x - a)`, `has_deriv_within_at` version. -/ theorem norm_image_sub_le_of_norm_deriv_le_segment' {f' : ℝ → E} {C : ℝ} (hf : ∀ x ∈ Icc a b, has_deriv_within_at f (f' x) (Icc a b) x) (bound : ∀x ∈ Ico a b, ∥f' x∥ ≤ C) : ∀ x ∈ Icc a b, ∥f x - f a∥ ≤ C * (x - a) := begin refine norm_image_sub_le_of_norm_deriv_right_le_segment (λ x hx, (hf x hx).continuous_within_at) (λ x hx, _) bound, apply (hf x $ Ico_subset_Icc_self hx).nhds_within, exact Icc_mem_nhds_within_Ioi hx end /-- A function on `[a, b]` with the norm of the derivative within `[a, b]` bounded by `C` satisfies `∥f x - f a∥ ≤ C * (x - a)`, `deriv_within` version. -/ theorem norm_image_sub_le_of_norm_deriv_le_segment {C : ℝ} (hf : differentiable_on ℝ f (Icc a b)) (bound : ∀x ∈ Ico a b, ∥deriv_within f (Icc a b) x∥ ≤ C) : ∀ x ∈ Icc a b, ∥f x - f a∥ ≤ C * (x - a) := begin refine norm_image_sub_le_of_norm_deriv_le_segment' _ bound, exact λ x hx, (hf x hx).has_deriv_within_at end /-- A function on `[0, 1]` with the norm of the derivative within `[0, 1]` bounded by `C` satisfies `∥f 1 - f 0∥ ≤ C`, `has_deriv_within_at` version. -/ theorem norm_image_sub_le_of_norm_deriv_le_segment_01' {f' : ℝ → E} {C : ℝ} (hf : ∀ x ∈ Icc (0:ℝ) 1, has_deriv_within_at f (f' x) (Icc (0:ℝ) 1) x) (bound : ∀x ∈ Ico (0:ℝ) 1, ∥f' x∥ ≤ C) : ∥f 1 - f 0∥ ≤ C := by simpa only [sub_zero, mul_one] using norm_image_sub_le_of_norm_deriv_le_segment' hf bound 1 (right_mem_Icc.2 zero_le_one) /-- A function on `[0, 1]` with the norm of the derivative within `[0, 1]` bounded by `C` satisfies `∥f 1 - f 0∥ ≤ C`, `deriv_within` version. -/ theorem norm_image_sub_le_of_norm_deriv_le_segment_01 {C : ℝ} (hf : differentiable_on ℝ f (Icc (0:ℝ) 1)) (bound : ∀x ∈ Ico (0:ℝ) 1, ∥deriv_within f (Icc (0:ℝ) 1) x∥ ≤ C) : ∥f 1 - f 0∥ ≤ C := by simpa only [sub_zero, mul_one] using norm_image_sub_le_of_norm_deriv_le_segment hf bound 1 (right_mem_Icc.2 zero_le_one) end /-! ### Vector-valued functions `f : E → F` -/ /-- The mean value theorem on a convex set: if the derivative of a function is bounded by C, then the function is C-Lipschitz -/ theorem convex.norm_image_sub_le_of_norm_deriv_le {f : E → F} {C : ℝ} {s : set E} {x y : E} (hf : differentiable_on ℝ f s) (bound : ∀x∈s, ∥fderiv_within ℝ f s x∥ ≤ C) (hs : convex s) (xs : x ∈ s) (ys : y ∈ s) : ∥f y - f x∥ ≤ C * ∥y - x∥ := begin /- By composition with t ↦ x + t • (y-x), we reduce to a statement for functions defined on [0,1], for which it is proved in `norm_image_sub_le_of_norm_deriv_le_segment`. We just have to check the differentiability of the composition and bounds on its derivative, which is straightforward but tedious for lack of automation. -/ have C0 : 0 ≤ C := le_trans (norm_nonneg _) (bound x xs), set g : ℝ → E := λ t, x + t • (y - x), have Dg : ∀ t, has_deriv_at g (y-x) t, { assume t, simpa only [one_smul] using ((has_deriv_at_id t).smul_const (y - x)).const_add x }, have segm : Icc 0 1 ⊆ g ⁻¹' s, { rw [← image_subset_iff, ← segment_eq_image'], apply hs.segment_subset xs ys }, have : f x = f (g 0), by { simp only [g], rw [zero_smul, add_zero] }, rw this, have : f y = f (g 1), by { simp only [g], rw [one_smul, add_sub_cancel'_right] }, rw this, have D2: ∀ t ∈ Icc (0:ℝ) 1, has_deriv_within_at (f ∘ g) ((fderiv_within ℝ f s (g t) : E → F) (y-x)) (Icc (0:ℝ) 1) t, { intros t ht, exact (hf (g t) $ segm ht).has_fderiv_within_at.comp_has_deriv_within_at _ (Dg t).has_deriv_within_at segm }, apply norm_image_sub_le_of_norm_deriv_le_segment_01' D2, assume t ht, refine le_trans (le_op_norm _ _) (mul_le_mul_of_nonneg_right _ (norm_nonneg _)), exact bound (g t) (segm $ Ico_subset_Icc_self ht) end /-- If a function has zero Fréchet derivative at every point of a convex set, then it is a constant on this set. -/ theorem convex.is_const_of_fderiv_within_eq_zero {s : set E} (hs : convex s) {f : E → F} (hf : differentiable_on ℝ f s) (hf' : ∀ x ∈ s, fderiv_within ℝ f s x = 0) {x y : E} (hx : x ∈ s) (hy : y ∈ s) : f x = f y := have bound : ∀ x ∈ s, ∥fderiv_within ℝ f s x∥ ≤ 0, from λ x hx, by simp only [hf' x hx, _root_.norm_zero], by simpa only [(dist_eq_norm _ _).symm, zero_mul, dist_le_zero, eq_comm] using hs.norm_image_sub_le_of_norm_deriv_le hf bound hx hy theorem is_const_of_fderiv_eq_zero {f : E → F} (hf : differentiable ℝ f) (hf' : ∀ x, fderiv ℝ f x = 0) (x y : E) : f x = f y := convex_univ.is_const_of_fderiv_within_eq_zero hf.differentiable_on (λ x _, by rw fderiv_within_univ; exact hf' x) trivial trivial /-! ### Functions `[a, b] → ℝ`. -/ section interval -- Declare all variables here to make sure they come in a correct order variables (f f' : ℝ → ℝ) {a b : ℝ} (hab : a < b) (hfc : continuous_on f (Icc a b)) (hff' : ∀ x ∈ Ioo a b, has_deriv_at f (f' x) x) (hfd : differentiable_on ℝ f (Ioo a b)) (g g' : ℝ → ℝ) (hgc : continuous_on g (Icc a b)) (hgg' : ∀ x ∈ Ioo a b, has_deriv_at g (g' x) x) (hgd : differentiable_on ℝ g (Ioo a b)) include hab hfc hff' hgc hgg' /-- Cauchy's Mean Value Theorem, `has_deriv_at` version. -/ lemma exists_ratio_has_deriv_at_eq_ratio_slope : ∃ c ∈ Ioo a b, (g b - g a) * f' c = (f b - f a) * g' c := begin let h := λ x, (g b - g a) * f x - (f b - f a) * g x, have hI : h a = h b, { simp only [h], ring }, let h' := λ x, (g b - g a) * f' x - (f b - f a) * g' x, have hhh' : ∀ x ∈ Ioo a b, has_deriv_at h (h' x) x, from λ x hx, ((hff' x hx).const_mul (g b - g a)).sub ((hgg' x hx).const_mul (f b - f a)), have hhc : continuous_on h (Icc a b), from (continuous_on_const.mul hfc).sub (continuous_on_const.mul hgc), rcases exists_has_deriv_at_eq_zero h h' hab hhc hI hhh' with ⟨c, cmem, hc⟩, exact ⟨c, cmem, sub_eq_zero.1 hc⟩ end omit hgc hgg' /-- Lagrange's Mean Value Theorem, `has_deriv_at` version -/ lemma exists_has_deriv_at_eq_slope : ∃ c ∈ Ioo a b, f' c = (f b - f a) / (b - a) := begin rcases exists_ratio_has_deriv_at_eq_ratio_slope f f' hab hfc hff' id 1 continuous_id.continuous_on (λ x hx, has_deriv_at_id x) with ⟨c, cmem, hc⟩, use [c, cmem], simp only [_root_.id, pi.one_apply, mul_one] at hc, rw [← hc, mul_div_cancel_left], exact ne_of_gt (sub_pos.2 hab) end omit hff' /-- Cauchy's Mean Value Theorem, `deriv` version. -/ lemma exists_ratio_deriv_eq_ratio_slope : ∃ c ∈ Ioo a b, (g b - g a) * (deriv f c) = (f b - f a) * (deriv g c) := exists_ratio_has_deriv_at_eq_ratio_slope f (deriv f) hab hfc (λ x hx, ((hfd x hx).differentiable_at $ mem_nhds_sets is_open_Ioo hx).has_deriv_at) g (deriv g) hgc (λ x hx, ((hgd x hx).differentiable_at $ mem_nhds_sets is_open_Ioo hx).has_deriv_at) /-- Lagrange's Mean Value Theorem, `deriv` version. -/ lemma exists_deriv_eq_slope : ∃ c ∈ Ioo a b, deriv f c = (f b - f a) / (b - a) := exists_has_deriv_at_eq_slope f (deriv f) hab hfc (λ x hx, ((hfd x hx).differentiable_at $ mem_nhds_sets is_open_Ioo hx).has_deriv_at) end interval /-- Let `f` be a function continuous on a convex (or, equivalently, connected) subset `D` of the real line. If `f` is differentiable on the interior of `D` and `C < f'`, then `f` grows faster than `C * x` on `D`, i.e., `C * (y - x) < f y - f x` whenever `x, y ∈ D`, `x < y`. -/ theorem convex.mul_sub_lt_image_sub_of_lt_deriv {D : set ℝ} (hD : convex D) {f : ℝ → ℝ} (hf : continuous_on f D) (hf' : differentiable_on ℝ f (interior D)) {C} (hf'_gt : ∀ x ∈ interior D, C < deriv f x) : ∀ x y ∈ D, x < y → C * (y - x) < f y - f x := begin assume x y hx hy hxy, have hxyD : Icc x y ⊆ D, from convex_real_iff.1 hD hx hy, have hxyD' : Ioo x y ⊆ interior D, from subset_sUnion_of_mem ⟨is_open_Ioo, subset.trans Ioo_subset_Icc_self hxyD⟩, obtain ⟨a, a_mem, ha⟩ : ∃ a ∈ Ioo x y, deriv f a = (f y - f x) / (y - x), from exists_deriv_eq_slope f hxy (hf.mono hxyD) (hf'.mono hxyD'), have : C < (f y - f x) / (y - x), by { rw [← ha], exact hf'_gt _ (hxyD' a_mem) }, exact (lt_div_iff (sub_pos.2 hxy)).1 this end /-- Let `f : ℝ → ℝ` be a differentiable function. If `C < f'`, then `f` grows faster than `C * x`, i.e., `C * (y - x) < f y - f x` whenever `x < y`. -/ theorem mul_sub_lt_image_sub_of_lt_deriv {f : ℝ → ℝ} (hf : differentiable ℝ f) {C} (hf'_gt : ∀ x, C < deriv f x) ⦃x y⦄ (hxy : x < y) : C * (y - x) < f y - f x := convex_univ.mul_sub_lt_image_sub_of_lt_deriv hf.continuous.continuous_on hf.differentiable_on (λ x _, hf'_gt x) x y trivial trivial hxy /-- Let `f` be a function continuous on a convex (or, equivalently, connected) subset `D` of the real line. If `f` is differentiable on the interior of `D` and `C ≤ f'`, then `f` grows at least as fast as `C * x` on `D`, i.e., `C * (y - x) ≤ f y - f x` whenever `x, y ∈ D`, `x ≤ y`. -/ theorem convex.mul_sub_le_image_sub_of_le_deriv {D : set ℝ} (hD : convex D) {f : ℝ → ℝ} (hf : continuous_on f D) (hf' : differentiable_on ℝ f (interior D)) {C} (hf'_ge : ∀ x ∈ interior D, C ≤ deriv f x) : ∀ x y ∈ D, x ≤ y → C * (y - x) ≤ f y - f x := begin assume x y hx hy hxy, cases eq_or_lt_of_le hxy with hxy' hxy', by rw [hxy', sub_self, sub_self, mul_zero], have hxyD : Icc x y ⊆ D, from convex_real_iff.1 hD hx hy, have hxyD' : Ioo x y ⊆ interior D, from subset_sUnion_of_mem ⟨is_open_Ioo, subset.trans Ioo_subset_Icc_self hxyD⟩, obtain ⟨a, a_mem, ha⟩ : ∃ a ∈ Ioo x y, deriv f a = (f y - f x) / (y - x), from exists_deriv_eq_slope f hxy' (hf.mono hxyD) (hf'.mono hxyD'), have : C ≤ (f y - f x) / (y - x), by { rw [← ha], exact hf'_ge _ (hxyD' a_mem) }, exact (le_div_iff (sub_pos.2 hxy')).1 this end /-- Let `f : ℝ → ℝ` be a differentiable function. If `C ≤ f'`, then `f` grows at least as fast as `C * x`, i.e., `C * (y - x) ≤ f y - f x` whenever `x ≤ y`. -/ theorem mul_sub_le_image_sub_of_le_deriv {f : ℝ → ℝ} (hf : differentiable ℝ f) {C} (hf'_ge : ∀ x, C ≤ deriv f x) ⦃x y⦄ (hxy : x ≤ y) : C * (y - x) ≤ f y - f x := convex_univ.mul_sub_le_image_sub_of_le_deriv hf.continuous.continuous_on hf.differentiable_on (λ x _, hf'_ge x) x y trivial trivial hxy /-- Let `f` be a function continuous on a convex (or, equivalently, connected) subset `D` of the real line. If `f` is differentiable on the interior of `D` and `f' < C`, then `f` grows slower than `C * x` on `D`, i.e., `f y - f x < C * (y - x)` whenever `x, y ∈ D`, `x < y`. -/ theorem convex.image_sub_lt_mul_sub_of_deriv_lt {D : set ℝ} (hD : convex D) {f : ℝ → ℝ} (hf : continuous_on f D) (hf' : differentiable_on ℝ f (interior D)) {C} (lt_hf' : ∀ x ∈ interior D, deriv f x < C) : ∀ x y ∈ D, x < y → f y - f x < C * (y - x) := begin assume x y hx hy hxy, have hf'_gt : ∀ x ∈ interior D, -C < deriv (λ y, -f y) x, { assume x hx, rw [deriv_neg, neg_lt_neg_iff], exact lt_hf' x hx }, simpa [-neg_lt_neg_iff] using neg_lt_neg (hD.mul_sub_lt_image_sub_of_lt_deriv hf.neg hf'.neg hf'_gt x y hx hy hxy) end /-- Let `f : ℝ → ℝ` be a differentiable function. If `f' < C`, then `f` grows slower than `C * x` on `D`, i.e., `f y - f x < C * (y - x)` whenever `x < y`. -/ theorem image_sub_lt_mul_sub_of_deriv_lt {f : ℝ → ℝ} (hf : differentiable ℝ f) {C} (lt_hf' : ∀ x, deriv f x < C) ⦃x y⦄ (hxy : x < y) : f y - f x < C * (y - x) := convex_univ.image_sub_lt_mul_sub_of_deriv_lt hf.continuous.continuous_on hf.differentiable_on (λ x _, lt_hf' x) x y trivial trivial hxy /-- Let `f` be a function continuous on a convex (or, equivalently, connected) subset `D` of the real line. If `f` is differentiable on the interior of `D` and `f' ≤ C`, then `f` grows at most as fast as `C * x` on `D`, i.e., `f y - f x ≤ C * (y - x)` whenever `x, y ∈ D`, `x ≤ y`. -/ theorem convex.image_sub_le_mul_sub_of_deriv_le {D : set ℝ} (hD : convex D) {f : ℝ → ℝ} (hf : continuous_on f D) (hf' : differentiable_on ℝ f (interior D)) {C} (le_hf' : ∀ x ∈ interior D, deriv f x ≤ C) : ∀ x y ∈ D, x ≤ y → f y - f x ≤ C * (y - x) := begin assume x y hx hy hxy, have hf'_ge : ∀ x ∈ interior D, -C ≤ deriv (λ y, -f y) x, { assume x hx, rw [deriv_neg, neg_le_neg_iff], exact le_hf' x hx }, simpa [-neg_le_neg_iff] using neg_le_neg (hD.mul_sub_le_image_sub_of_le_deriv hf.neg hf'.neg hf'_ge x y hx hy hxy) end /-- Let `f : ℝ → ℝ` be a differentiable function. If `f' ≤ C`, then `f` grows at most as fast as `C * x`, i.e., `f y - f x ≤ C * (y - x)` whenever `x ≤ y`. -/ theorem image_sub_le_mul_sub_of_deriv_le {f : ℝ → ℝ} (hf : differentiable ℝ f) {C} (le_hf' : ∀ x, deriv f x ≤ C) ⦃x y⦄ (hxy : x ≤ y) : f y - f x ≤ C * (y - x) := convex_univ.image_sub_le_mul_sub_of_deriv_le hf.continuous.continuous_on hf.differentiable_on (λ x _, le_hf' x) x y trivial trivial hxy /-- Let `f` be a function continuous on a convex (or, equivalently, connected) subset `D` of the real line. If `f` is differentiable on the interior of `D` and `f'` is positive, then `f` is a strictly monotonically increasing function on `D`. -/ theorem convex.strict_mono_of_deriv_pos {D : set ℝ} (hD : convex D) {f : ℝ → ℝ} (hf : continuous_on f D) (hf' : differentiable_on ℝ f (interior D)) (hf'_pos : ∀ x ∈ interior D, 0 < deriv f x) : ∀ x y ∈ D, x < y → f x < f y := by simpa only [zero_mul, sub_pos] using hD.mul_sub_lt_image_sub_of_lt_deriv hf hf' hf'_pos /-- Let `f : ℝ → ℝ` be a differentiable function. If `f'` is positive, then `f` is a strictly monotonically increasing function. -/ theorem strict_mono_of_deriv_pos {f : ℝ → ℝ} (hf : differentiable ℝ f) (hf'_pos : ∀ x, 0 < deriv f x) : strict_mono f := λ x y hxy, convex_univ.strict_mono_of_deriv_pos hf.continuous.continuous_on hf.differentiable_on (λ x _, hf'_pos x) x y trivial trivial hxy /-- Let `f` be a function continuous on a convex (or, equivalently, connected) subset `D` of the real line. If `f` is differentiable on the interior of `D` and `f'` is nonnegative, then `f` is a monotonically increasing function on `D`. -/ theorem convex.mono_of_deriv_nonneg {D : set ℝ} (hD : convex D) {f : ℝ → ℝ} (hf : continuous_on f D) (hf' : differentiable_on ℝ f (interior D)) (hf'_nonneg : ∀ x ∈ interior D, 0 ≤ deriv f x) : ∀ x y ∈ D, x ≤ y → f x ≤ f y := by simpa only [zero_mul, sub_nonneg] using hD.mul_sub_le_image_sub_of_le_deriv hf hf' hf'_nonneg /-- Let `f : ℝ → ℝ` be a differentiable function. If `f'` is nonnegative, then `f` is a monotonically increasing function. -/ theorem mono_of_deriv_nonneg {f : ℝ → ℝ} (hf : differentiable ℝ f) (hf' : ∀ x, 0 ≤ deriv f x) : monotone f := λ x y hxy, convex_univ.mono_of_deriv_nonneg hf.continuous.continuous_on hf.differentiable_on (λ x _, hf' x) x y trivial trivial hxy /-- Let `f` be a function continuous on a convex (or, equivalently, connected) subset `D` of the real line. If `f` is differentiable on the interior of `D` and `f'` is negative, then `f` is a strictly monotonically decreasing function on `D`. -/ theorem convex.strict_antimono_of_deriv_neg {D : set ℝ} (hD : convex D) {f : ℝ → ℝ} (hf : continuous_on f D) (hf' : differentiable_on ℝ f (interior D)) (hf'_neg : ∀ x ∈ interior D, deriv f x < 0) : ∀ x y ∈ D, x < y → f y < f x := by simpa only [zero_mul, sub_lt_zero] using hD.image_sub_lt_mul_sub_of_deriv_lt hf hf' hf'_neg /-- Let `f : ℝ → ℝ` be a differentiable function. If `f'` is negative, then `f` is a strictly monotonically decreasing function. -/ theorem strict_antimono_of_deriv_neg {f : ℝ → ℝ} (hf : differentiable ℝ f) (hf' : ∀ x, deriv f x < 0) : ∀ ⦃x y⦄, x < y → f y < f x := λ x y hxy, convex_univ.strict_antimono_of_deriv_neg hf.continuous.continuous_on hf.differentiable_on (λ x _, hf' x) x y trivial trivial hxy /-- Let `f` be a function continuous on a convex (or, equivalently, connected) subset `D` of the real line. If `f` is differentiable on the interior of `D` and `f'` is nonpositive, then `f` is a monotonically decreasing function on `D`. -/ theorem convex.antimono_of_deriv_nonpos {D : set ℝ} (hD : convex D) {f : ℝ → ℝ} (hf : continuous_on f D) (hf' : differentiable_on ℝ f (interior D)) (hf'_nonpos : ∀ x ∈ interior D, deriv f x ≤ 0) : ∀ x y ∈ D, x ≤ y → f y ≤ f x := by simpa only [zero_mul, sub_nonpos] using hD.image_sub_le_mul_sub_of_deriv_le hf hf' hf'_nonpos /-- Let `f : ℝ → ℝ` be a differentiable function. If `f'` is nonpositive, then `f` is a monotonically decreasing function. -/ theorem antimono_of_deriv_nonpos {f : ℝ → ℝ} (hf : differentiable ℝ f) (hf' : ∀ x, deriv f x ≤ 0) : ∀ ⦃x y⦄, x ≤ y → f y ≤ f x := λ x y hxy, convex_univ.antimono_of_deriv_nonpos hf.continuous.continuous_on hf.differentiable_on (λ x _, hf' x) x y trivial trivial hxy /-- If a function `f` is continuous on a convex set `D ⊆ ℝ`, is differentiable on its interior, and `f'` is monotone on the interior, then `f` is convex on `D`. -/ theorem convex_on_of_deriv_mono {D : set ℝ} (hD : convex D) {f : ℝ → ℝ} (hf : continuous_on f D) (hf' : differentiable_on ℝ f (interior D)) (hf'_mono : ∀ x y ∈ interior D, x ≤ y → deriv f x ≤ deriv f y) : convex_on D f := convex_on_real_of_slope_mono_adjacent hD begin intros x y z hx hz hxy hyz, -- First we prove some trivial inclusions have hxzD : Icc x z ⊆ D, from convex_real_iff.1 hD hx hz, have hxyD : Icc x y ⊆ D, from subset.trans (Icc_subset_Icc_right $ le_of_lt hyz) hxzD, have hxyD' : Ioo x y ⊆ interior D, from subset_sUnion_of_mem ⟨is_open_Ioo, subset.trans Ioo_subset_Icc_self hxyD⟩, have hyzD : Icc y z ⊆ D, from subset.trans (Icc_subset_Icc_left $ le_of_lt hxy) hxzD, have hyzD' : Ioo y z ⊆ interior D, from subset_sUnion_of_mem ⟨is_open_Ioo, subset.trans Ioo_subset_Icc_self hyzD⟩, -- Then we apply MVT to both `[x, y]` and `[y, z]` obtain ⟨a, ⟨hxa, hay⟩, ha⟩ : ∃ a ∈ Ioo x y, deriv f a = (f y - f x) / (y - x), from exists_deriv_eq_slope f hxy (hf.mono hxyD) (hf'.mono hxyD'), obtain ⟨b, ⟨hyb, hbz⟩, hb⟩ : ∃ b ∈ Ioo y z, deriv f b = (f z - f y) / (z - y), from exists_deriv_eq_slope f hyz (hf.mono hyzD) (hf'.mono hyzD'), rw [← ha, ← hb], exact hf'_mono a b (hxyD' ⟨hxa, hay⟩) (hyzD' ⟨hyb, hbz⟩) (le_of_lt $ lt_trans hay hyb) end /-- If a function `f` is continuous on a convex set `D ⊆ ℝ`, is differentiable on its interior, and `f'` is monotone on the interior, then `f` is convex on `ℝ`. -/ theorem convex_on_univ_of_deriv_mono {f : ℝ → ℝ} (hf : differentiable ℝ f) (hf'_mono : monotone (deriv f)) : convex_on univ f := convex_on_of_deriv_mono convex_univ hf.continuous.continuous_on hf.differentiable_on (λ x y _ _ h, hf'_mono h) /-- If a function `f` is continuous on a convex set `D ⊆ ℝ`, is twice differentiable on its interior, and `f''` is nonnegative on the interior, then `f` is convex on `D`. -/ theorem convex_on_of_deriv2_nonneg {D : set ℝ} (hD : convex D) {f : ℝ → ℝ} (hf : continuous_on f D) (hf' : differentiable_on ℝ f (interior D)) (hf'' : differentiable_on ℝ (deriv f) (interior D)) (hf''_nonneg : ∀ x ∈ interior D, 0 ≤ (deriv^[2] f x)) : convex_on D f := convex_on_of_deriv_mono hD hf hf' $ assume x y hx hy hxy, hD.interior.mono_of_deriv_nonneg hf''.continuous_on (by rwa [interior_interior]) (by rwa [interior_interior]) _ _ hx hy hxy /-- If a function `f` is twice differentiable on `ℝ`, and `f''` is nonnegative on `ℝ`, then `f` is convex on `ℝ`. -/ theorem convex_on_univ_of_deriv2_nonneg {f : ℝ → ℝ} (hf' : differentiable ℝ f) (hf'' : differentiable ℝ (deriv f)) (hf''_nonneg : ∀ x, 0 ≤ (deriv^[2] f x)) : convex_on univ f := convex_on_of_deriv2_nonneg convex_univ hf'.continuous.continuous_on hf'.differentiable_on hf''.differentiable_on (λ x _, hf''_nonneg x)
a85fa1bbf7f2ab243d9529618827bd5be4cfe7fc
75db7e3219bba2fbf41bf5b905f34fcb3c6ca3f2
/library/data/int/div.lean
8ea0bef1b064a91b9f26573a08586fd70387e73e
[ "Apache-2.0" ]
permissive
jroesch/lean
30ef0860fa905d35b9ad6f76de1a4f65c9af6871
3de4ec1a6ce9a960feb2a48eeea8b53246fa34f2
refs/heads/master
1,586,090,835,348
1,455,142,203,000
1,455,142,277,000
51,536,958
1
0
null
1,455,215,811,000
1,455,215,811,000
null
UTF-8
Lean
false
false
29,581
lean
/- Copyright (c) 2014 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Jeremy Avigad Definitions and properties of div and mod, following the SSReflect library. Following SSReflect and the SMTlib standard, we define a % b so that 0 ≤ a % b < |b| when b ≠ 0. -/ import data.int.order data.nat.div open [coercion] [reducible] nat open [declaration] [class] nat (succ) open eq.ops namespace int /- definitions -/ protected definition div (a b : ℤ) : ℤ := sign b * (match a with | of_nat m := of_nat (m / (nat_abs b)) | -[1+m] := -[1+ ((m:nat) / (nat_abs b))] end) definition int_has_div [reducible] [instance] [priority int.prio] : has_div int := has_div.mk int.div lemma of_nat_div_eq (m : nat) (b : ℤ) : (of_nat m) / b = sign b * of_nat (m / (nat_abs b)) := rfl lemma neg_succ_div_eq (m: nat) (b : ℤ) : -[1+m] / b = sign b * -[1+ (m / (nat_abs b))] := rfl lemma div_def (a b : ℤ) : a / b = sign b * (match a with | of_nat m := of_nat (m / (nat_abs b)) | -[1+m] := -[1+ ((m:nat) / (nat_abs b))] end) := rfl protected definition mod (a b : ℤ) : ℤ := a - a / b * b definition int_has_mod [reducible] [instance] [priority int.prio] : has_mod int := has_mod.mk int.mod lemma mod_def (a b : ℤ) : a % b = a - a / b * b := rfl notation [priority int.prio] a ≡ b `[mod `:0 c:0 `]` := a % c = b % c /- / -/ theorem of_nat_div (m n : nat) : of_nat (m / n) = (of_nat m) / (of_nat n) := nat.cases_on n (begin rewrite [of_nat_div_eq, of_nat_zero, sign_zero, zero_mul, nat.div_zero] end) (take (n : nat), by rewrite [of_nat_div_eq, sign_of_succ, one_mul]) theorem neg_succ_of_nat_div (m : nat) {b : ℤ} (H : b > 0) : -[1+m] / b = -(m / b + 1) := calc -[1+m] / b = sign b * _ : rfl ... = -[1+(m / (nat_abs b))] : by rewrite [sign_of_pos H, one_mul] ... = -(m / b + 1) : by rewrite [of_nat_div_eq, sign_of_pos H, one_mul] protected theorem div_neg (a b : ℤ) : a / -b = -(a / b) := begin induction a, rewrite [*of_nat_div_eq, sign_neg, neg_mul_eq_neg_mul, nat_abs_neg], rewrite [*neg_succ_div_eq, sign_neg, neg_mul_eq_neg_mul, nat_abs_neg], end theorem div_of_neg_of_pos {a b : ℤ} (Ha : a < 0) (Hb : b > 0) : a / b = -((-a - 1) / b + 1) := obtain (m : nat) (H1 : a = -[1+m]), from exists_eq_neg_succ_of_nat Ha, calc a / b = -(m / b + 1) : by rewrite [H1, neg_succ_of_nat_div _ Hb] ... = -((-a -1) / b + 1) : by rewrite [H1, neg_succ_of_nat_eq', neg_sub, sub_neg_eq_add, add.comm 1, add_sub_cancel] protected theorem div_nonneg {a b : ℤ} (Ha : a ≥ 0) (Hb : b ≥ 0) : a / b ≥ 0 := obtain (m : ℕ) (Hm : a = m), from exists_eq_of_nat Ha, obtain (n : ℕ) (Hn : b = n), from exists_eq_of_nat Hb, calc a / b = m / n : by rewrite [Hm, Hn] ... ≥ 0 : by rewrite -of_nat_div; apply trivial protected theorem div_nonpos {a b : ℤ} (Ha : a ≥ 0) (Hb : b ≤ 0) : a / b ≤ 0 := calc a / b = -(a / -b) : by rewrite [int.div_neg, neg_neg] ... ≤ 0 : neg_nonpos_of_nonneg (int.div_nonneg Ha (neg_nonneg_of_nonpos Hb)) theorem div_neg' {a b : ℤ} (Ha : a < 0) (Hb : b > 0) : a / b < 0 := have -a - 1 ≥ 0, from le_sub_one_of_lt (neg_pos_of_neg Ha), have (-a - 1) / b + 1 > 0, from lt_add_one_of_le (int.div_nonneg this (le_of_lt Hb)), calc a / b = -((-a - 1) / b + 1) : div_of_neg_of_pos Ha Hb ... < 0 : neg_neg_of_pos this protected theorem zero_div (b : ℤ) : 0 / b = 0 := by krewrite [of_nat_div_eq, nat.zero_div, of_nat_zero, mul_zero] protected theorem div_zero (a : ℤ) : a / 0 = 0 := by rewrite [div_def, sign_zero, zero_mul] protected theorem div_one (a : ℤ) : a / 1 = a := assert (1 : int) > 0, from dec_trivial, int.cases_on a (take m : nat, by rewrite [-of_nat_one, -of_nat_div, nat.div_one]) (take m : nat, by rewrite [!neg_succ_of_nat_div this, -of_nat_one, -of_nat_div, nat.div_one]) theorem eq_div_mul_add_mod (a b : ℤ) : a = a / b * b + a % b := !add.comm ▸ eq_add_of_sub_eq rfl theorem div_eq_zero_of_lt {a b : ℤ} : 0 ≤ a → a < b → a / b = 0 := int.cases_on a (take (m : nat), assume H, int.cases_on b (take (n : nat), assume H : m < n, show m / n = 0, by rewrite [-of_nat_div, nat.div_eq_zero_of_lt (lt_of_of_nat_lt_of_nat H)]) (take (n : nat), assume H : m < -[1+n], have H1 : ¬(m < -[1+n]), from dec_trivial, absurd H H1)) (take (m : nat), assume H : 0 ≤ -[1+m], have ¬ (0 ≤ -[1+m]), from dec_trivial, absurd H this) theorem div_eq_zero_of_lt_abs {a b : ℤ} (H1 : 0 ≤ a) (H2 : a < abs b) : a / b = 0 := lt.by_cases (suppose b < 0, assert a < -b, from abs_of_neg this ▸ H2, calc a / b = - (a / -b) : by rewrite [int.div_neg, neg_neg] ... = 0 : by rewrite [div_eq_zero_of_lt H1 this, neg_zero]) (suppose b = 0, this⁻¹ ▸ !int.div_zero) (suppose b > 0, have a < b, from abs_of_pos this ▸ H2, div_eq_zero_of_lt H1 this) private theorem add_mul_div_self_aux1 {a : ℤ} {k : ℕ} (n : ℕ) (H1 : a ≥ 0) (H2 : k > 0) : (a + n * k) / k = a / k + n := obtain (m : nat) (Hm : a = of_nat m), from exists_eq_of_nat H1, begin subst Hm, rewrite [-of_nat_mul, -of_nat_add, -*of_nat_div, -of_nat_add, !nat.add_mul_div_self H2] end private theorem add_mul_div_self_aux2 {a : ℤ} {k : ℕ} (n : ℕ) (H1 : a < 0) (H2 : k > 0) : (a + n * k) / k = a / k + n := obtain m (Hm : a = -[1+m]), from exists_eq_neg_succ_of_nat H1, or.elim (nat.lt_or_ge m (n * k)) (assume m_lt_nk : m < n * k, assert H3 : m + 1 ≤ n * k, from nat.succ_le_of_lt m_lt_nk, assert H4 : m / k + 1 ≤ n, from nat.succ_le_of_lt (nat.div_lt_of_lt_mul m_lt_nk), have (-[1+m] + n * k) / k = -[1+m] / k + n, from calc (-[1+m] + n * k) / k = of_nat ((k * n - (m + 1)) / k) : by rewrite [add.comm, neg_succ_of_nat_eq, of_nat_div, mul.comm k n, of_nat_sub H3] ... = of_nat (n - m / k - 1) : nat.mul_sub_div_of_lt (!nat.mul_comm ▸ m_lt_nk) ... = -[1+m] / k + n : by rewrite [nat.sub_sub, of_nat_sub H4, int.add_comm, sub_eq_add_neg, !neg_succ_of_nat_div (of_nat_lt_of_nat_of_lt H2), of_nat_add, of_nat_div], Hm⁻¹ ▸ this) (assume nk_le_m : n * k ≤ m, have -[1+m] / k + n = (-[1+m] + n * k) / k, from calc -[1+m] / k + n = -(of_nat ((m - n * k + n * k) / k) + 1) + n : by rewrite [neg_succ_of_nat_div m (of_nat_lt_of_nat_of_lt H2), nat.sub_add_cancel nk_le_m, of_nat_div] ... = -(of_nat ((m - n * k) / k + n) + 1) + n : nat.add_mul_div_self H2 ... = -(of_nat (m - n * k) / k + 1) : by rewrite [of_nat_add, *neg_add, add.right_comm, neg_add_cancel_right, of_nat_div] ... = -[1+(m - n * k)] / k : neg_succ_of_nat_div _ (of_nat_lt_of_nat_of_lt H2) ... = -(of_nat(m - n * k) + 1) / k : rfl ... = -(of_nat m - of_nat(n * k) + 1) / k : of_nat_sub nk_le_m ... = (-(of_nat m + 1) + n * k) / k : by rewrite [sub_eq_add_neg, -*add.assoc, *neg_add, neg_neg, add.right_comm] ... = (-[1+m] + n * k) / k : rfl, Hm⁻¹ ▸ this⁻¹) private theorem add_mul_div_self_aux3 (a : ℤ) {b c : ℤ} (H1 : b ≥ 0) (H2 : c > 0) : (a + b * c) / c = a / c + b := obtain (n : nat) (Hn : b = of_nat n), from exists_eq_of_nat H1, obtain (k : nat) (Hk : c = of_nat k), from exists_eq_of_nat (le_of_lt H2), have knz : k ≠ 0, from assume kz, !lt.irrefl (kz ▸ Hk ▸ H2), have kgt0 : (#nat k > 0), from nat.pos_of_ne_zero knz, have H3 : (a + n * k) / k = a / k + n, from or.elim (lt_or_ge a 0) (assume Ha : a < 0, add_mul_div_self_aux2 _ Ha kgt0) (assume Ha : a ≥ 0, add_mul_div_self_aux1 _ Ha kgt0), Hn⁻¹ ▸ Hk⁻¹ ▸ H3 private theorem add_mul_div_self_aux4 (a b : ℤ) {c : ℤ} (H : c > 0) : (a + b * c) / c = a / c + b := or.elim (le.total 0 b) (assume H1 : 0 ≤ b, add_mul_div_self_aux3 _ H1 H) (assume H1 : 0 ≥ b, eq.symm (calc a / c + b = (a + b * c + -b * c) / c + b : by rewrite [-neg_mul_eq_neg_mul, add_neg_cancel_right] ... = (a + b * c) / c + - b + b : add_mul_div_self_aux3 _ (neg_nonneg_of_nonpos H1) H ... = (a + b * c) / c : neg_add_cancel_right)) protected theorem add_mul_div_self (a b : ℤ) {c : ℤ} (H : c ≠ 0) : (a + b * c) / c = a / c + b := lt.by_cases (assume H1 : 0 < c, !add_mul_div_self_aux4 H1) (assume H1 : 0 = c, absurd H1⁻¹ H) (assume H1 : 0 > c, have H2 : -c > 0, from neg_pos_of_neg H1, calc (a + b * c) / c = - ((a + -b * -c) / -c) : by rewrite [int.div_neg, neg_mul_neg, neg_neg] ... = -(a / -c + -b) : !add_mul_div_self_aux4 H2 ... = a / c + b : by rewrite [int.div_neg, neg_add, *neg_neg]) protected theorem add_mul_div_self_left (a : ℤ) {b : ℤ} (c : ℤ) (H : b ≠ 0) : (a + b * c) / b = a / b + c := !mul.comm ▸ !int.add_mul_div_self H protected theorem mul_div_cancel (a : ℤ) {b : ℤ} (H : b ≠ 0) : a * b / b = a := calc a * b / b = (0 + a * b) / b : zero_add ... = 0 / b + a : !int.add_mul_div_self H ... = a : by rewrite [int.zero_div, zero_add] protected theorem mul_div_cancel_left {a : ℤ} (b : ℤ) (H : a ≠ 0) : a * b / a = b := !mul.comm ▸ int.mul_div_cancel b H protected theorem div_self {a : ℤ} (H : a ≠ 0) : a / a = 1 := !mul_one ▸ !int.mul_div_cancel_left H /- mod -/ theorem of_nat_mod (m n : nat) : m % n = of_nat (m % n) := have H : m = of_nat (m % n) + m / n * n, from calc m = of_nat (m / n * n + m % n) : nat.eq_div_mul_add_mod ... = of_nat (m / n) * n + of_nat (m % n) : rfl ... = m / n * n + of_nat (m % n) : of_nat_div ... = of_nat (m % n) + m / n * n : add.comm, calc m % n = m - m / n * n : rfl ... = of_nat (m % n) : sub_eq_of_eq_add H theorem neg_succ_of_nat_mod (m : ℕ) {b : ℤ} (bpos : b > 0) : -[1+m] % b = b - 1 - m % b := calc -[1+m] % b = -(m + 1) - -[1+m] / b * b : rfl ... = -(m + 1) - -(m / b + 1) * b : neg_succ_of_nat_div _ bpos ... = -m + -1 + (b + m / b * b) : by rewrite [neg_add, -neg_mul_eq_neg_mul, sub_neg_eq_add, right_distrib, one_mul, (add.comm b)] ... = b + -1 + (-m + m / b * b) : by rewrite [-*add.assoc, add.comm (-m), add.right_comm (-1), (add.comm b)] ... = b - 1 - m % b : by rewrite [(mod_def), *sub_eq_add_neg, neg_add, neg_neg] -- it seems the parser has difficulty here, because "mod" is a token? theorem mod_neg (a b : ℤ) : a % -b = a % b := calc a % -b = a - (a / -b) * -b : rfl ... = a - -(a / b) * -b : int.div_neg ... = a - a / b * b : neg_mul_neg ... = a % b : rfl theorem mod_abs (a b : ℤ) : a % (abs b) = a % b := abs.by_cases rfl !mod_neg theorem zero_mod (b : ℤ) : 0 % b = 0 := by rewrite [(mod_def), int.zero_div, zero_mul, sub_zero] theorem mod_zero (a : ℤ) : a % 0 = a := by rewrite [(mod_def), mul_zero, sub_zero] theorem mod_one (a : ℤ) : a % 1 = 0 := calc a % 1 = a - a / 1 * 1 : rfl ... = 0 : by rewrite [mul_one, int.div_one, sub_self] private lemma of_nat_mod_abs (m : ℕ) (b : ℤ) : m % (abs b) = of_nat (m % (nat_abs b)) := calc m % (abs b) = m % (nat_abs b) : of_nat_nat_abs ... = of_nat (m % (nat_abs b)) : of_nat_mod private lemma of_nat_mod_abs_lt (m : ℕ) {b : ℤ} (H : b ≠ 0) : m % (abs b) < (abs b) := have H1 : abs b > 0, from abs_pos_of_ne_zero H, have H2 : (#nat nat_abs b > 0), from lt_of_of_nat_lt_of_nat (!of_nat_nat_abs⁻¹ ▸ H1), calc m % (abs b) = of_nat (m % (nat_abs b)) : of_nat_mod_abs m b ... < nat_abs b : of_nat_lt_of_nat_of_lt (!nat.mod_lt H2) ... = abs b : of_nat_nat_abs _ theorem mod_eq_of_lt {a b : ℤ} (H1 : 0 ≤ a) (H2 : a < b) : a % b = a := obtain (m : nat) (Hm : a = of_nat m), from exists_eq_of_nat H1, obtain (n : nat) (Hn : b = of_nat n), from exists_eq_of_nat (le_of_lt (lt_of_le_of_lt H1 H2)), begin revert H2, rewrite [Hm, Hn, of_nat_mod, of_nat_lt_of_nat_iff, of_nat_eq_of_nat_iff], apply nat.mod_eq_of_lt end theorem mod_nonneg (a : ℤ) {b : ℤ} (H : b ≠ 0) : a % b ≥ 0 := have H1 : abs b > 0, from abs_pos_of_ne_zero H, have H2 : a % (abs b) ≥ 0, from int.cases_on a (take m : nat, (of_nat_mod_abs m b)⁻¹ ▸ of_nat_nonneg (nat.mod m (nat_abs b))) (take m : nat, have H3 : 1 + m % (abs b) ≤ (abs b), from (!add.comm ▸ add_one_le_of_lt (of_nat_mod_abs_lt m H)), calc -[1+m] % (abs b) = abs b - 1 - m % (abs b) : neg_succ_of_nat_mod _ H1 ... = abs b - (1 + m % (abs b)) : by rewrite [*sub_eq_add_neg, neg_add, add.assoc] ... ≥ 0 : iff.mpr !sub_nonneg_iff_le H3), !mod_abs ▸ H2 theorem mod_lt (a : ℤ) {b : ℤ} (H : b ≠ 0) : a % b < (abs b) := have H1 : abs b > 0, from abs_pos_of_ne_zero H, have H2 : a % (abs b) < abs b, from int.cases_on a (take m, of_nat_mod_abs_lt m H) (take m : nat, have H3 : abs b ≠ 0, from assume H', H (eq_zero_of_abs_eq_zero H'), have H4 : 1 + m % (abs b) > 0, from add_pos_of_pos_of_nonneg dec_trivial (mod_nonneg _ H3), calc -[1+m] % (abs b) = abs b - 1 - m % (abs b) : neg_succ_of_nat_mod _ H1 ... = abs b - (1 + m % (abs b)) : by rewrite [*sub_eq_add_neg, neg_add, add.assoc] ... < abs b : sub_lt_self _ H4), !mod_abs ▸ H2 theorem add_mul_mod_self {a b c : ℤ} : (a + b * c) % c = a % c := decidable.by_cases (assume cz : c = 0, by rewrite [cz, mul_zero, add_zero]) (assume cnz, by rewrite [(mod_def), !int.add_mul_div_self cnz, right_distrib, sub_add_eq_sub_sub_swap, add_sub_cancel]) theorem add_mul_mod_self_left (a b c : ℤ) : (a + b * c) % b = a % b := !mul.comm ▸ !add_mul_mod_self theorem add_mod_self {a b : ℤ} : (a + b) % b = a % b := by rewrite -(int.mul_one b) at {1}; apply add_mul_mod_self_left theorem add_mod_self_left {a b : ℤ} : (a + b) % a = b % a := !add.comm ▸ !add_mod_self theorem mod_add_mod (m n k : ℤ) : (m % n + k) % n = (m + k) % n := by rewrite [eq_div_mul_add_mod m n at {2}, add.assoc, add.comm (m / n * n), add_mul_mod_self] theorem add_mod_mod (m n k : ℤ) : (m + n % k) % k = (m + n) % k := by rewrite [add.comm, mod_add_mod, add.comm] theorem add_mod_eq_add_mod_right {m n k : ℤ} (i : ℤ) (H : m % n = k % n) : (m + i) % n = (k + i) % n := by rewrite [-mod_add_mod, -mod_add_mod k, H] theorem add_mod_eq_add_mod_left {m n k : ℤ} (i : ℤ) (H : m % n = k % n) : (i + m) % n = (i + k) % n := by rewrite [add.comm, add_mod_eq_add_mod_right _ H, add.comm] theorem mod_eq_mod_of_add_mod_eq_add_mod_right {m n k i : ℤ} (H : (m + i) % n = (k + i) % n) : m % n = k % n := assert H1 : (m + i + (-i)) % n = (k + i + (-i)) % n, from add_mod_eq_add_mod_right _ H, by rewrite [*add_neg_cancel_right at H1]; apply H1 theorem mod_eq_mod_of_add_mod_eq_add_mod_left {m n k i : ℤ} : (i + m) % n = (i + k) % n → m % n = k % n := by rewrite [add.comm i m, add.comm i k]; apply mod_eq_mod_of_add_mod_eq_add_mod_right theorem mul_mod_left (a b : ℤ) : (a * b) % b = 0 := by rewrite [-zero_add (a * b), add_mul_mod_self, zero_mod] theorem mul_mod_right (a b : ℤ) : (a * b) % a = 0 := !mul.comm ▸ !mul_mod_left theorem mod_self {a : ℤ} : a % a = 0 := decidable.by_cases (assume H : a = 0, H⁻¹ ▸ !mod_zero) (assume H : a ≠ 0, calc a % a = a - a / a * a : rfl ... = 0 : by rewrite [!int.div_self H, one_mul, sub_self]) theorem mod_lt_of_pos (a : ℤ) {b : ℤ} (H : b > 0) : a % b < b := !abs_of_pos H ▸ !mod_lt (ne.symm (ne_of_lt H)) /- properties of / and % -/ theorem mul_div_mul_of_pos_aux {a : ℤ} (b : ℤ) {c : ℤ} (H1 : a > 0) (H2 : c > 0) : a * b / (a * c) = b / c := have H3 : a * c ≠ 0, from ne.symm (ne_of_lt (mul_pos H1 H2)), have H4 : a * (b % c) < a * c, from mul_lt_mul_of_pos_left (!mod_lt_of_pos H2) H1, have H5 : a * (b % c) ≥ 0, from mul_nonneg (le_of_lt H1) (!mod_nonneg (ne.symm (ne_of_lt H2))), calc a * b / (a * c) = a * (b / c * c + b % c) / (a * c) : eq_div_mul_add_mod ... = (a * (b % c) + a * c * (b / c)) / (a * c) : by rewrite [!add.comm, int.left_distrib, mul.comm _ c, -!mul.assoc] ... = a * (b % c) / (a * c) + b / c : !int.add_mul_div_self_left H3 ... = 0 + b / c : {!div_eq_zero_of_lt H5 H4} ... = b / c : zero_add theorem mul_div_mul_of_pos {a : ℤ} (b c : ℤ) (H : a > 0) : a * b / (a * c) = b / c := lt.by_cases (assume H1 : c < 0, have H2 : -c > 0, from neg_pos_of_neg H1, calc a * b / (a * c) = - (a * b / (a * -c)) : by rewrite [-neg_mul_eq_mul_neg, int.div_neg, neg_neg] ... = - (b / -c) : mul_div_mul_of_pos_aux _ H H2 ... = b / c : by rewrite [int.div_neg, neg_neg]) (assume H1 : c = 0, calc a * b / (a * c) = 0 : by rewrite [H1, mul_zero, int.div_zero] ... = b / c : by rewrite [H1, int.div_zero]) (assume H1 : c > 0, mul_div_mul_of_pos_aux _ H H1) theorem mul_div_mul_of_pos_left (a : ℤ) {b : ℤ} (c : ℤ) (H : b > 0) : a * b / (c * b) = a / c := !mul.comm ▸ !mul.comm ▸ !mul_div_mul_of_pos H theorem mul_mod_mul_of_pos {a : ℤ} (b c : ℤ) (H : a > 0) : a * b % (a * c) = a * (b % c) := by rewrite [(mod_def), mod_def, !mul_div_mul_of_pos H, mul_sub_left_distrib, mul.left_comm] theorem lt_div_add_one_mul_self (a : ℤ) {b : ℤ} (H : b > 0) : a < (a / b + 1) * b := have H : a - a / b * b < b, from !mod_lt_of_pos H, calc a < a / b * b + b : iff.mpr !lt_add_iff_sub_lt_left H ... = (a / b + 1) * b : by rewrite [right_distrib, one_mul] theorem div_le_of_nonneg_of_nonneg {a b : ℤ} (Ha : a ≥ 0) (Hb : b ≥ 0) : a / b ≤ a := obtain (m : ℕ) (Hm : a = m), from exists_eq_of_nat Ha, obtain (n : ℕ) (Hn : b = n), from exists_eq_of_nat Hb, calc a / b = of_nat (m / n) : by rewrite [Hm, Hn, of_nat_div] ... ≤ m : of_nat_le_of_nat_of_le !nat.div_le_self ... = a : Hm theorem abs_div_le_abs (a b : ℤ) : abs (a / b) ≤ abs a := have H : ∀a b, b > 0 → abs (a / b) ≤ abs a, from take a b, assume H1 : b > 0, or.elim (le_or_gt 0 a) (assume H2 : 0 ≤ a, have H3 : 0 ≤ b, from le_of_lt H1, calc abs (a / b) = a / b : abs_of_nonneg (int.div_nonneg H2 H3) ... ≤ a : div_le_of_nonneg_of_nonneg H2 H3 ... = abs a : abs_of_nonneg H2) (assume H2 : a < 0, have H3 : -a - 1 ≥ 0, from le_sub_one_of_lt (neg_pos_of_neg H2), have H4 : (-a - 1) / b + 1 ≥ 0, from add_nonneg (int.div_nonneg H3 (le_of_lt H1)) (of_nat_le_of_nat_of_le !nat.zero_le), have H5 : (-a - 1) / b ≤ -a - 1, from div_le_of_nonneg_of_nonneg H3 (le_of_lt H1), calc abs (a / b) = abs ((-a - 1) / b + 1) : by rewrite [div_of_neg_of_pos H2 H1, abs_neg] ... = (-a - 1) / b + 1 : abs_of_nonneg H4 ... ≤ -a - 1 + 1 : add_le_add_right H5 _ ... = abs a : by rewrite [sub_add_cancel, abs_of_neg H2]), lt.by_cases (assume H1 : b < 0, calc abs (a / b) = abs (a / -b) : by rewrite [int.div_neg, abs_neg] ... ≤ abs a : H _ _ (neg_pos_of_neg H1)) (assume H1 : b = 0, calc abs (a / b) = 0 : by rewrite [H1, int.div_zero, abs_zero] ... ≤ abs a : abs_nonneg) (assume H1 : b > 0, H _ _ H1) theorem div_mul_cancel_of_mod_eq_zero {a b : ℤ} (H : a % b = 0) : a / b * b = a := by rewrite [eq_div_mul_add_mod a b at {2}, H, add_zero] theorem mul_div_cancel_of_mod_eq_zero {a b : ℤ} (H : a % b = 0) : b * (a / b) = a := !mul.comm ▸ div_mul_cancel_of_mod_eq_zero H /- dvd -/ theorem dvd_of_of_nat_dvd_of_nat {m n : ℕ} : of_nat m ∣ of_nat n → (#nat m ∣ n) := nat.by_cases_zero_pos n (assume H, dvd_zero m) (take n' : ℕ, assume H1 : (#nat n' > 0), have H2 : of_nat n' > 0, from of_nat_pos H1, assume H3 : of_nat m ∣ of_nat n', dvd.elim H3 (take c, assume H4 : of_nat n' = of_nat m * c, have H5 : c > 0, from pos_of_mul_pos_left (H4 ▸ H2) !of_nat_nonneg, obtain k (H6 : c = of_nat k), from exists_eq_of_nat (le_of_lt H5), have H7 : n' = (#nat m * k), from (of_nat.inj (H6 ▸ H4)), dvd.intro H7⁻¹)) theorem of_nat_dvd_of_nat_of_dvd {m n : ℕ} (H : #nat m ∣ n) : of_nat m ∣ of_nat n := dvd.elim H (take k, assume H1 : #nat n = m * k, dvd.intro (H1⁻¹ ▸ rfl)) theorem of_nat_dvd_of_nat_iff (m n : ℕ) : of_nat m ∣ of_nat n ↔ m ∣ n := iff.intro dvd_of_of_nat_dvd_of_nat of_nat_dvd_of_nat_of_dvd theorem dvd.antisymm {a b : ℤ} (H1 : a ≥ 0) (H2 : b ≥ 0) : a ∣ b → b ∣ a → a = b := begin rewrite [-abs_of_nonneg H1, -abs_of_nonneg H2, -*of_nat_nat_abs], rewrite [*of_nat_dvd_of_nat_iff, *of_nat_eq_of_nat_iff], apply nat.dvd.antisymm end theorem dvd_of_mod_eq_zero {a b : ℤ} (H : b % a = 0) : a ∣ b := dvd.intro (!mul.comm ▸ div_mul_cancel_of_mod_eq_zero H) theorem mod_eq_zero_of_dvd {a b : ℤ} (H : a ∣ b) : b % a = 0 := dvd.elim H (take z, assume H1 : b = a * z, H1⁻¹ ▸ !mul_mod_right) theorem dvd_iff_mod_eq_zero (a b : ℤ) : a ∣ b ↔ b % a = 0 := iff.intro mod_eq_zero_of_dvd dvd_of_mod_eq_zero definition dvd.decidable_rel [instance] : decidable_rel dvd := take a n, decidable_of_decidable_of_iff _ (iff.symm !dvd_iff_mod_eq_zero) protected theorem div_mul_cancel {a b : ℤ} (H : b ∣ a) : a / b * b = a := div_mul_cancel_of_mod_eq_zero (mod_eq_zero_of_dvd H) protected theorem mul_div_cancel' {a b : ℤ} (H : a ∣ b) : a * (b / a) = b := !mul.comm ▸ !int.div_mul_cancel H protected theorem mul_div_assoc (a : ℤ) {b c : ℤ} (H : c ∣ b) : (a * b) / c = a * (b / c) := decidable.by_cases (assume cz : c = 0, by rewrite [cz, *int.div_zero, mul_zero]) (assume cnz : c ≠ 0, obtain d (H' : b = d * c), from exists_eq_mul_left_of_dvd H, by rewrite [H', -mul.assoc, *(!int.mul_div_cancel cnz)]) theorem div_dvd_div {a b c : ℤ} (H1 : a ∣ b) (H2 : b ∣ c) : b / a ∣ c / a := have H3 : b = b / a * a, from (int.div_mul_cancel H1)⁻¹, have H4 : c = c / a * a, from (int.div_mul_cancel (dvd.trans H1 H2))⁻¹, decidable.by_cases (assume H5 : a = 0, have H6: c / a = 0, from (congr_arg _ H5 ⬝ !int.div_zero), H6⁻¹ ▸ !dvd_zero) (assume H5 : a ≠ 0, dvd_of_mul_dvd_mul_right H5 (H3 ▸ H4 ▸ H2)) protected theorem div_eq_iff_eq_mul_right {a b : ℤ} (c : ℤ) (H : b ≠ 0) (H' : b ∣ a) : a / b = c ↔ a = b * c := iff.intro (assume H1, by rewrite [-H1, int.mul_div_cancel' H']) (assume H1, by rewrite [H1, !int.mul_div_cancel_left H]) protected theorem div_eq_iff_eq_mul_left {a b : ℤ} (c : ℤ) (H : b ≠ 0) (H' : b ∣ a) : a / b = c ↔ a = c * b := !mul.comm ▸ !int.div_eq_iff_eq_mul_right H H' protected theorem eq_mul_of_div_eq_right {a b c : ℤ} (H1 : b ∣ a) (H2 : a / b = c) : a = b * c := calc a = b * (a / b) : int.mul_div_cancel' H1 ... = b * c : H2 protected theorem div_eq_of_eq_mul_right {a b c : ℤ} (H1 : b ≠ 0) (H2 : a = b * c) : a / b = c := calc a / b = b * c / b : H2 ... = c : !int.mul_div_cancel_left H1 protected theorem eq_mul_of_div_eq_left {a b c : ℤ} (H1 : b ∣ a) (H2 : a / b = c) : a = c * b := !mul.comm ▸ !int.eq_mul_of_div_eq_right H1 H2 protected theorem div_eq_of_eq_mul_left {a b c : ℤ} (H1 : b ≠ 0) (H2 : a = c * b) : a / b = c := int.div_eq_of_eq_mul_right H1 (!mul.comm ▸ H2) theorem neg_div_of_dvd {a b : ℤ} (H : b ∣ a) : -a / b = -(a / b) := decidable.by_cases (assume H1 : b = 0, by rewrite [H1, *int.div_zero, neg_zero]) (assume H1 : b ≠ 0, dvd.elim H (take c, assume H' : a = b * c, by rewrite [H', neg_mul_eq_mul_neg, *!int.mul_div_cancel_left H1])) protected theorem sign_eq_div_abs (a : ℤ) : sign a = a / (abs a) := decidable.by_cases (suppose a = 0, by subst a) (suppose a ≠ 0, have abs a ≠ 0, from assume H, this (eq_zero_of_abs_eq_zero H), have abs a ∣ a, from abs_dvd_of_dvd !dvd.refl, eq.symm (iff.mpr (!int.div_eq_iff_eq_mul_left `abs a ≠ 0` this) !eq_sign_mul_abs)) theorem le_of_dvd {a b : ℤ} (bpos : b > 0) (H : a ∣ b) : a ≤ b := or.elim !le_or_gt (suppose a ≤ 0, le.trans this (le_of_lt bpos)) (suppose a > 0, obtain c (Hc : b = a * c), from exists_eq_mul_right_of_dvd H, have a * c > 0, by rewrite -Hc; exact bpos, have c > 0, from pos_of_mul_pos_left this (le_of_lt `a > 0`), show a ≤ b, from calc a = a * 1 : mul_one ... ≤ a * c : mul_le_mul_of_nonneg_left (add_one_le_of_lt `c > 0`) (le_of_lt `a > 0`) ... = b : Hc) /- / and ordering -/ protected theorem div_mul_le (a : ℤ) {b : ℤ} (H : b ≠ 0) : a / b * b ≤ a := calc a = a / b * b + a % b : eq_div_mul_add_mod ... ≥ a / b * b : le_add_of_nonneg_right (!mod_nonneg H) protected theorem div_le_of_le_mul {a b c : ℤ} (H : c > 0) (H' : a ≤ b * c) : a / c ≤ b := le_of_mul_le_mul_right (calc a / c * c = a / c * c + 0 : add_zero ... ≤ a / c * c + a % c : add_le_add_left (!mod_nonneg (ne_of_gt H)) ... = a : eq_div_mul_add_mod ... ≤ b * c : H') H protected theorem div_le_self (a : ℤ) {b : ℤ} (H1 : a ≥ 0) (H2 : b ≥ 0) : a / b ≤ a := or.elim (lt_or_eq_of_le H2) (assume H3 : b > 0, have H4 : b ≥ 1, from add_one_le_of_lt H3, have H5 : a ≤ a * b, from calc a = a * 1 : mul_one ... ≤ a * b : !mul_le_mul_of_nonneg_left H4 H1, int.div_le_of_le_mul H3 H5) (assume H3 : 0 = b, by rewrite [-H3, int.div_zero]; apply H1) protected theorem mul_le_of_le_div {a b c : ℤ} (H1 : c > 0) (H2 : a ≤ b / c) : a * c ≤ b := calc a * c ≤ b / c * c : !mul_le_mul_of_nonneg_right H2 (le_of_lt H1) ... ≤ b : !int.div_mul_le (ne_of_gt H1) protected theorem le_div_of_mul_le {a b c : ℤ} (H1 : c > 0) (H2 : a * c ≤ b) : a ≤ b / c := have H3 : a * c < (b / c + 1) * c, from calc a * c ≤ b : H2 ... = b / c * c + b % c : eq_div_mul_add_mod ... < b / c * c + c : add_lt_add_left (!mod_lt_of_pos H1) ... = (b / c + 1) * c : by rewrite [right_distrib, one_mul], le_of_lt_add_one (lt_of_mul_lt_mul_right H3 (le_of_lt H1)) protected theorem le_div_iff_mul_le {a b c : ℤ} (H : c > 0) : a ≤ b / c ↔ a * c ≤ b := iff.intro (!int.mul_le_of_le_div H) (!int.le_div_of_mul_le H) protected theorem div_le_div {a b c : ℤ} (H : c > 0) (H' : a ≤ b) : a / c ≤ b / c := int.le_div_of_mul_le H (le.trans (!int.div_mul_le (ne_of_gt H)) H') protected theorem div_lt_of_lt_mul {a b c : ℤ} (H : c > 0) (H' : a < b * c) : a / c < b := lt_of_mul_lt_mul_right (calc a / c * c = a / c * c + 0 : add_zero ... ≤ a / c * c + a % c : add_le_add_left (!mod_nonneg (ne_of_gt H)) ... = a : eq_div_mul_add_mod ... < b * c : H') (le_of_lt H) protected theorem lt_mul_of_div_lt {a b c : ℤ} (H1 : c > 0) (H2 : a / c < b) : a < b * c := assert H3 : (a / c + 1) * c ≤ b * c, from !mul_le_mul_of_nonneg_right (add_one_le_of_lt H2) (le_of_lt H1), have H4 : a / c * c + c ≤ b * c, by rewrite [right_distrib at H3, one_mul at H3]; apply H3, calc a = a / c * c + a % c : eq_div_mul_add_mod ... < a / c * c + c : add_lt_add_left (!mod_lt_of_pos H1) ... ≤ b * c : H4 protected theorem div_lt_iff_lt_mul {a b c : ℤ} (H : c > 0) : a / c < b ↔ a < b * c := iff.intro (!int.lt_mul_of_div_lt H) (!int.div_lt_of_lt_mul H) protected theorem div_le_iff_le_mul_of_div {a b : ℤ} (c : ℤ) (H : b > 0) (H' : b ∣ a) : a / b ≤ c ↔ a ≤ c * b := by rewrite [propext (!le_iff_mul_le_mul_right H), !int.div_mul_cancel H'] protected theorem le_mul_of_div_le_of_div {a b c : ℤ} (H1 : b > 0) (H2 : b ∣ a) (H3 : a / b ≤ c) : a ≤ c * b := iff.mp (!int.div_le_iff_le_mul_of_div H1 H2) H3 theorem div_pos_of_pos_of_dvd {a b : ℤ} (H1 : a > 0) (H2 : b ≥ 0) (H3 : b ∣ a) : a / b > 0 := have H4 : b ≠ 0, from (assume H5 : b = 0, have H6 : a = 0, from eq_zero_of_zero_dvd (H5 ▸ H3), ne_of_gt H1 H6), have H6 : (a / b) * b > 0, by rewrite (int.div_mul_cancel H3); apply H1, pos_of_mul_pos_right H6 H2 theorem div_eq_div_of_dvd_of_dvd {a b c d : ℤ} (H1 : b ∣ a) (H2 : d ∣ c) (H3 : b ≠ 0) (H4 : d ≠ 0) (H5 : a * d = b * c) : a / b = c / d := begin apply int.div_eq_of_eq_mul_right H3, rewrite [-!int.mul_div_assoc H2], apply eq.symm, apply int.div_eq_of_eq_mul_left H4, apply eq.symm H5 end end int
3e5a049ebbfe34fa9da8986e29bb5195f68ba7e2
07c6143268cfb72beccd1cc35735d424ebcb187b
/src/data/num/lemmas.lean
241108a45357aa782e74bf62931c7b908ee8edd7
[ "Apache-2.0" ]
permissive
khoek/mathlib
bc49a842910af13a3c372748310e86467d1dc766
aa55f8b50354b3e11ba64792dcb06cccb2d8ee28
refs/heads/master
1,588,232,063,837
1,587,304,803,000
1,587,304,803,000
176,688,517
0
0
Apache-2.0
1,553,070,585,000
1,553,070,585,000
null
UTF-8
Lean
false
false
50,239
lean
/- Copyright (c) 2014 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Mario Carneiro Properties of the binary representation of integers. -/ import data.num.basic data.num.bitwise algebra.ordered_ring tactic.interactive data.int.basic data.nat.gcd namespace pos_num variables {α : Type*} @[simp, norm_cast] theorem cast_one [has_zero α] [has_one α] [has_add α] : ((1 : pos_num) : α) = 1 := rfl @[simp] theorem cast_one' [has_zero α] [has_one α] [has_add α] : (pos_num.one : α) = 1 := rfl @[simp, norm_cast] theorem cast_bit0 [has_zero α] [has_one α] [has_add α] (n : pos_num) : (n.bit0 : α) = _root_.bit0 n := rfl @[simp, norm_cast] theorem cast_bit1 [has_zero α] [has_one α] [has_add α] (n : pos_num) : (n.bit1 : α) = _root_.bit1 n := rfl @[simp, norm_cast] theorem cast_to_nat [add_monoid α] [has_one α] : ∀ n : pos_num, ((n : ℕ) : α) = n | 1 := nat.cast_one | (bit0 p) := (nat.cast_bit0 _).trans $ congr_arg _root_.bit0 p.cast_to_nat | (bit1 p) := (nat.cast_bit1 _).trans $ congr_arg _root_.bit1 p.cast_to_nat @[simp, norm_cast] theorem to_nat_to_int (n : pos_num) : ((n : ℕ) : ℤ) = n := by rw [← int.nat_cast_eq_coe_nat, cast_to_nat] @[simp, norm_cast] theorem cast_to_int [add_group α] [has_one α] (n : pos_num) : ((n : ℤ) : α) = n := by rw [← to_nat_to_int, int.cast_coe_nat, cast_to_nat] theorem succ_to_nat : ∀ n, (succ n : ℕ) = n + 1 | 1 := rfl | (bit0 p) := rfl | (bit1 p) := (congr_arg _root_.bit0 (succ_to_nat p)).trans $ show ↑p + 1 + ↑p + 1 = ↑p + ↑p + 1 + 1, by simp [add_left_comm] theorem one_add (n : pos_num) : 1 + n = succ n := by cases n; refl theorem add_one (n : pos_num) : n + 1 = succ n := by cases n; refl @[norm_cast] theorem add_to_nat : ∀ m n, ((m + n : pos_num) : ℕ) = m + n | 1 b := by rw [one_add b, succ_to_nat, add_comm]; refl | a 1 := by rw [add_one a, succ_to_nat]; refl | (bit0 a) (bit0 b) := (congr_arg _root_.bit0 (add_to_nat a b)).trans $ show ((a + b) + (a + b) : ℕ) = (a + a) + (b + b), by simp [add_left_comm] | (bit0 a) (bit1 b) := (congr_arg _root_.bit1 (add_to_nat a b)).trans $ show ((a + b) + (a + b) + 1 : ℕ) = (a + a) + (b + b + 1), by simp [add_left_comm] | (bit1 a) (bit0 b) := (congr_arg _root_.bit1 (add_to_nat a b)).trans $ show ((a + b) + (a + b) + 1 : ℕ) = (a + a + 1) + (b + b), by simp [add_comm, add_left_comm] | (bit1 a) (bit1 b) := show (succ (a + b) + succ (a + b) : ℕ) = (a + a + 1) + (b + b + 1), by rw [succ_to_nat, add_to_nat]; simp [add_left_comm] theorem add_succ : ∀ (m n : pos_num), m + succ n = succ (m + n) | 1 b := by simp [one_add] | (bit0 a) 1 := congr_arg bit0 (add_one a) | (bit1 a) 1 := congr_arg bit1 (add_one a) | (bit0 a) (bit0 b) := rfl | (bit0 a) (bit1 b) := congr_arg bit0 (add_succ a b) | (bit1 a) (bit0 b) := rfl | (bit1 a) (bit1 b) := congr_arg bit1 (add_succ a b) theorem bit0_of_bit0 : Π n, _root_.bit0 n = bit0 n | 1 := rfl | (bit0 p) := congr_arg bit0 (bit0_of_bit0 p) | (bit1 p) := show bit0 (succ (_root_.bit0 p)) = _, by rw bit0_of_bit0; refl theorem bit1_of_bit1 (n : pos_num) : _root_.bit1 n = bit1 n := show _root_.bit0 n + 1 = bit1 n, by rw [add_one, bit0_of_bit0]; refl @[norm_cast] theorem mul_to_nat (m) : ∀ n, ((m * n : pos_num) : ℕ) = m * n | 1 := (mul_one _).symm | (bit0 p) := show (↑(m * p) + ↑(m * p) : ℕ) = ↑m * (p + p), by rw [mul_to_nat, left_distrib] | (bit1 p) := (add_to_nat (bit0 (m * p)) m).trans $ show (↑(m * p) + ↑(m * p) + ↑m : ℕ) = ↑m * (p + p) + m, by rw [mul_to_nat, left_distrib] theorem to_nat_pos : ∀ n : pos_num, 0 < (n : ℕ) | 1 := zero_lt_one | (bit0 p) := let h := to_nat_pos p in add_pos h h | (bit1 p) := nat.succ_pos _ theorem cmp_to_nat_lemma {m n : pos_num} : (m:ℕ) < n → (bit1 m : ℕ) < bit0 n := show (m:ℕ) < n → (m + m + 1 + 1 : ℕ) ≤ n + n, by intro h; rw [nat.add_right_comm m m 1, add_assoc]; exact add_le_add h h theorem cmp_swap (m) : ∀n, (cmp m n).swap = cmp n m := by induction m with m IH m IH; intro n; cases n with n n; try {unfold cmp}; try {refl}; rw ←IH; cases cmp m n; refl theorem cmp_to_nat : ∀ (m n), (ordering.cases_on (cmp m n) ((m:ℕ) < n) (m = n) ((m:ℕ) > n) : Prop) | 1 1 := rfl | (bit0 a) 1 := let h : (1:ℕ) ≤ a := to_nat_pos a in add_le_add h h | (bit1 a) 1 := nat.succ_lt_succ $ to_nat_pos $ bit0 a | 1 (bit0 b) := let h : (1:ℕ) ≤ b := to_nat_pos b in add_le_add h h | 1 (bit1 b) := nat.succ_lt_succ $ to_nat_pos $ bit0 b | (bit0 a) (bit0 b) := begin have := cmp_to_nat a b, revert this, cases cmp a b; dsimp; intro, { exact add_lt_add this this }, { rw this }, { exact add_lt_add this this } end | (bit0 a) (bit1 b) := begin dsimp [cmp], have := cmp_to_nat a b, revert this, cases cmp a b; dsimp; intro, { exact nat.le_succ_of_le (add_lt_add this this) }, { rw this, apply nat.lt_succ_self }, { exact cmp_to_nat_lemma this } end | (bit1 a) (bit0 b) := begin dsimp [cmp], have := cmp_to_nat a b, revert this, cases cmp a b; dsimp; intro, { exact cmp_to_nat_lemma this }, { rw this, apply nat.lt_succ_self }, { exact nat.le_succ_of_le (add_lt_add this this) }, end | (bit1 a) (bit1 b) := begin have := cmp_to_nat a b, revert this, cases cmp a b; dsimp; intro, { exact nat.succ_lt_succ (add_lt_add this this) }, { rw this }, { exact nat.succ_lt_succ (add_lt_add this this) } end @[norm_cast] theorem lt_to_nat {m n : pos_num} : (m:ℕ) < n ↔ m < n := show (m:ℕ) < n ↔ cmp m n = ordering.lt, from match cmp m n, cmp_to_nat m n with | ordering.lt, h := by simp at h; simp [h] | ordering.eq, h := by simp at h; simp [h, lt_irrefl]; exact dec_trivial | ordering.gt, h := by simp [not_lt_of_gt h]; exact dec_trivial end @[norm_cast] theorem le_to_nat {m n : pos_num} : (m:ℕ) ≤ n ↔ m ≤ n := by rw ← not_lt; exact not_congr lt_to_nat end pos_num namespace num variables {α : Type*} open pos_num theorem add_zero (n : num) : n + 0 = n := by cases n; refl theorem zero_add (n : num) : 0 + n = n := by cases n; refl theorem add_one : ∀ n : num, n + 1 = succ n | 0 := rfl | (pos p) := by cases p; refl theorem add_succ : ∀ (m n : num), m + succ n = succ (m + n) | 0 n := by simp [zero_add] | (pos p) 0 := show pos (p + 1) = succ (pos p + 0), by rw [pos_num.add_one, add_zero]; refl | (pos p) (pos q) := congr_arg pos (pos_num.add_succ _ _) @[simp, norm_cast] theorem add_of_nat (m) : ∀ n, ((m + n : ℕ) : num) = m + n | 0 := (add_zero _).symm | (n+1) := show ((m + n : ℕ) + 1 : num) = m + (↑ n + 1), by rw [add_one, add_one, add_succ, add_of_nat] theorem bit0_of_bit0 : ∀ n : num, bit0 n = n.bit0 | 0 := rfl | (pos p) := congr_arg pos p.bit0_of_bit0 theorem bit1_of_bit1 : ∀ n : num, bit1 n = n.bit1 | 0 := rfl | (pos p) := congr_arg pos p.bit1_of_bit1 @[simp, norm_cast] theorem cast_zero [has_zero α] [has_one α] [has_add α] : ((0 : num) : α) = 0 := rfl @[simp] theorem cast_zero' [has_zero α] [has_one α] [has_add α] : (num.zero : α) = 0 := rfl @[simp, norm_cast] theorem cast_one [has_zero α] [has_one α] [has_add α] : ((1 : num) : α) = 1 := rfl @[simp] theorem cast_pos [has_zero α] [has_one α] [has_add α] (n : pos_num) : (num.pos n : α) = n := rfl theorem succ'_to_nat : ∀ n, (succ' n : ℕ) = n + 1 | 0 := (_root_.zero_add _).symm | (pos p) := pos_num.succ_to_nat _ theorem succ_to_nat (n) : (succ n : ℕ) = n + 1 := succ'_to_nat n @[simp, norm_cast] theorem cast_to_nat [add_monoid α] [has_one α] : ∀ n : num, ((n : ℕ) : α) = n | 0 := nat.cast_zero | (pos p) := p.cast_to_nat @[simp, norm_cast] theorem to_nat_to_int (n : num) : ((n : ℕ) : ℤ) = n := by rw [← int.nat_cast_eq_coe_nat, cast_to_nat] @[simp, norm_cast] theorem cast_to_int [add_group α] [has_one α] (n : num) : ((n : ℤ) : α) = n := by rw [← to_nat_to_int, int.cast_coe_nat, cast_to_nat] @[norm_cast] theorem to_of_nat : Π (n : ℕ), ((n : num) : ℕ) = n | 0 := rfl | (n+1) := by rw [nat.cast_add_one, add_one, succ_to_nat, to_of_nat] @[simp, norm_cast] theorem of_nat_cast [add_monoid α] [has_one α] (n : ℕ) : ((n : num) : α) = n := by rw [← cast_to_nat, to_of_nat] @[norm_cast] theorem of_nat_inj {m n : ℕ} : (m : num) = n ↔ m = n := ⟨λ h, function.injective_of_left_inverse to_of_nat h, congr_arg _⟩ @[norm_cast] theorem add_to_nat : ∀ m n, ((m + n : num) : ℕ) = m + n | 0 0 := rfl | 0 (pos q) := (_root_.zero_add _).symm | (pos p) 0 := rfl | (pos p) (pos q) := pos_num.add_to_nat _ _ @[norm_cast] theorem mul_to_nat : ∀ m n, ((m * n : num) : ℕ) = m * n | 0 0 := rfl | 0 (pos q) := (zero_mul _).symm | (pos p) 0 := rfl | (pos p) (pos q) := pos_num.mul_to_nat _ _ theorem cmp_to_nat : ∀ (m n), (ordering.cases_on (cmp m n) ((m:ℕ) < n) (m = n) ((m:ℕ) > n) : Prop) | 0 0 := rfl | 0 (pos b) := to_nat_pos _ | (pos a) 0 := to_nat_pos _ | (pos a) (pos b) := by { have := pos_num.cmp_to_nat a b; revert this; dsimp [cmp]; cases pos_num.cmp a b, exacts [id, congr_arg pos, id] } @[norm_cast] theorem lt_to_nat {m n : num} : (m:ℕ) < n ↔ m < n := show (m:ℕ) < n ↔ cmp m n = ordering.lt, from match cmp m n, cmp_to_nat m n with | ordering.lt, h := by simp at h; simp [h] | ordering.eq, h := by simp at h; simp [h, lt_irrefl]; exact dec_trivial | ordering.gt, h := by simp [not_lt_of_gt h]; exact dec_trivial end @[norm_cast] theorem le_to_nat {m n : num} : (m:ℕ) ≤ n ↔ m ≤ n := by rw ← not_lt; exact not_congr lt_to_nat end num namespace pos_num @[simp] theorem of_to_nat : Π (n : pos_num), ((n : ℕ) : num) = num.pos n | 1 := rfl | (bit0 p) := show ↑(p + p : ℕ) = num.pos p.bit0, by rw [num.add_of_nat, of_to_nat]; exact congr_arg num.pos p.bit0_of_bit0 | (bit1 p) := show ((p + p : ℕ) : num) + 1 = num.pos p.bit1, by rw [num.add_of_nat, of_to_nat]; exact congr_arg num.pos p.bit1_of_bit1 end pos_num namespace num @[simp, norm_cast] theorem of_to_nat : Π (n : num), ((n : ℕ) : num) = n | 0 := rfl | (pos p) := p.of_to_nat @[norm_cast] theorem to_nat_inj {m n : num} : (m : ℕ) = n ↔ m = n := ⟨λ h, function.injective_of_left_inverse of_to_nat h, congr_arg _⟩ meta def transfer_rw : tactic unit := `[repeat {rw ← to_nat_inj <|> rw ← lt_to_nat <|> rw ← le_to_nat}, repeat {rw add_to_nat <|> rw mul_to_nat <|> rw cast_one <|> rw cast_zero}] meta def transfer : tactic unit := `[intros, transfer_rw, try {simp}] instance : comm_semiring num := by refine { add := (+), zero := 0, zero_add := zero_add, add_zero := add_zero, mul := (*), one := 1, .. }; try {transfer}; simp [mul_add, mul_left_comm, mul_comm, add_comm] instance : ordered_cancel_add_comm_monoid num := { add_left_cancel := by {intros a b c, transfer_rw, apply add_left_cancel}, add_right_cancel := by {intros a b c, transfer_rw, apply add_right_cancel}, lt := (<), lt_iff_le_not_le := by {intros a b, transfer_rw, apply lt_iff_le_not_le}, le := (≤), le_refl := by transfer, le_trans := by {intros a b c, transfer_rw, apply le_trans}, le_antisymm := by {intros a b, transfer_rw, apply le_antisymm}, add_le_add_left := by {intros a b h c, revert h, transfer_rw, exact λ h, add_le_add_left h c}, le_of_add_le_add_left := by {intros a b c, transfer_rw, apply le_of_add_le_add_left}, ..num.comm_semiring } instance : decidable_linear_ordered_semiring num := { le_total := by {intros a b, transfer_rw, apply le_total}, zero_lt_one := dec_trivial, mul_lt_mul_of_pos_left := by {intros a b c, transfer_rw, apply mul_lt_mul_of_pos_left}, mul_lt_mul_of_pos_right := by {intros a b c, transfer_rw, apply mul_lt_mul_of_pos_right}, decidable_lt := num.decidable_lt, decidable_le := num.decidable_le, decidable_eq := num.decidable_eq, ..num.comm_semiring, ..num.ordered_cancel_add_comm_monoid } @[norm_cast] theorem dvd_to_nat (m n : num) : (m : ℕ) ∣ n ↔ m ∣ n := ⟨λ ⟨k, e⟩, ⟨k, by rw [← of_to_nat n, e]; simp⟩, λ ⟨k, e⟩, ⟨k, by simp [e, mul_to_nat]⟩⟩ end num namespace pos_num variables {α : Type*} open num @[norm_cast] theorem to_nat_inj {m n : pos_num} : (m : ℕ) = n ↔ m = n := ⟨λ h, num.pos.inj $ by rw [← pos_num.of_to_nat, ← pos_num.of_to_nat, h], congr_arg _⟩ theorem pred'_to_nat : ∀ n, (pred' n : ℕ) = nat.pred n | 1 := rfl | (bit0 n) := have nat.succ ↑(pred' n) = ↑n, by rw [pred'_to_nat n, nat.succ_pred_eq_of_pos (to_nat_pos n)], match pred' n, this : ∀ k : num, nat.succ ↑k = ↑n → ↑(num.cases_on k 1 bit1 : pos_num) = nat.pred (_root_.bit0 n) with | 0, (h : ((1:num):ℕ) = n) := by rw ← to_nat_inj.1 h; refl | num.pos p, (h : nat.succ ↑p = n) := by rw ← h; exact (nat.succ_add p p).symm end | (bit1 n) := rfl @[simp] theorem pred'_succ' (n) : pred' (succ' n) = n := num.to_nat_inj.1 $ by rw [pred'_to_nat, succ'_to_nat, nat.add_one, nat.pred_succ] @[simp] theorem succ'_pred' (n) : succ' (pred' n) = n := to_nat_inj.1 $ by rw [succ'_to_nat, pred'_to_nat, nat.add_one, nat.succ_pred_eq_of_pos (to_nat_pos _)] theorem size_to_nat : ∀ n, (size n : ℕ) = nat.size n | 1 := nat.size_one.symm | (bit0 n) := by rw [size, succ_to_nat, size_to_nat, cast_bit0, nat.size_bit0 $ ne_of_gt $ to_nat_pos n] | (bit1 n) := by rw [size, succ_to_nat, size_to_nat, cast_bit1, nat.size_bit1] theorem size_eq_nat_size : ∀ n, (size n : ℕ) = nat_size n | 1 := rfl | (bit0 n) := by rw [size, succ_to_nat, nat_size, size_eq_nat_size] | (bit1 n) := by rw [size, succ_to_nat, nat_size, size_eq_nat_size] theorem nat_size_to_nat (n) : nat_size n = nat.size n := by rw [← size_eq_nat_size, size_to_nat] theorem nat_size_pos (n) : 0 < nat_size n := by cases n; apply nat.succ_pos meta def transfer_rw : tactic unit := `[repeat {rw ← to_nat_inj <|> rw ← lt_to_nat <|> rw ← le_to_nat}, repeat {rw add_to_nat <|> rw mul_to_nat <|> rw cast_one <|> rw cast_zero}] meta def transfer : tactic unit := `[intros, transfer_rw, try {simp [add_comm, add_left_comm, mul_comm, mul_left_comm]}] instance : add_comm_semigroup pos_num := by refine {add := (+), ..}; transfer instance : comm_monoid pos_num := by refine {mul := (*), one := 1, ..}; transfer instance : distrib pos_num := by refine {add := (+), mul := (*), ..}; {transfer, simp [mul_add, mul_comm]} instance : decidable_linear_order pos_num := { lt := (<), lt_iff_le_not_le := by {intros a b, transfer_rw, apply lt_iff_le_not_le}, le := (≤), le_refl := by transfer, le_trans := by {intros a b c, transfer_rw, apply le_trans}, le_antisymm := by {intros a b, transfer_rw, apply le_antisymm}, le_total := by {intros a b, transfer_rw, apply le_total}, decidable_lt := by apply_instance, decidable_le := by apply_instance, decidable_eq := by apply_instance } @[simp] theorem cast_to_num (n : pos_num) : ↑n = num.pos n := by rw [← cast_to_nat, ← of_to_nat n] @[simp, norm_cast] theorem bit_to_nat (b n) : (bit b n : ℕ) = nat.bit b n := by cases b; refl @[simp, norm_cast] theorem cast_add [add_monoid α] [has_one α] (m n) : ((m + n : pos_num) : α) = m + n := by rw [← cast_to_nat, add_to_nat, nat.cast_add, cast_to_nat, cast_to_nat] @[simp, norm_cast, priority 500] theorem cast_succ [add_monoid α] [has_one α] (n : pos_num) : (succ n : α) = n + 1 := by rw [← add_one, cast_add, cast_one] @[simp, norm_cast] theorem cast_inj [add_monoid α] [has_one α] [char_zero α] {m n : pos_num} : (m:α) = n ↔ m = n := by rw [← cast_to_nat m, ← cast_to_nat n, nat.cast_inj, to_nat_inj] @[simp] theorem one_le_cast [linear_ordered_semiring α] (n : pos_num) : (1 : α) ≤ n := by rw [← cast_to_nat, ← nat.cast_one, nat.cast_le]; apply to_nat_pos @[simp] theorem cast_pos [linear_ordered_semiring α] (n : pos_num) : 0 < (n : α) := lt_of_lt_of_le zero_lt_one (one_le_cast n) @[simp, norm_cast] theorem cast_mul [semiring α] (m n) : ((m * n : pos_num) : α) = m * n := by rw [← cast_to_nat, mul_to_nat, nat.cast_mul, cast_to_nat, cast_to_nat] @[simp] theorem cmp_eq (m n) : cmp m n = ordering.eq ↔ m = n := begin have := cmp_to_nat m n, cases cmp m n; simp at this ⊢; try {exact this}; { simp [show m ≠ n, from λ e, by rw e at this; exact lt_irrefl _ this] } end @[simp, norm_cast] theorem cast_lt [linear_ordered_semiring α] {m n : pos_num} : (m:α) < n ↔ m < n := by rw [← cast_to_nat m, ← cast_to_nat n, nat.cast_lt, lt_to_nat] @[simp, norm_cast] theorem cast_le [linear_ordered_semiring α] {m n : pos_num} : (m:α) ≤ n ↔ m ≤ n := by rw ← not_lt; exact not_congr cast_lt end pos_num namespace num variables {α : Type*} open pos_num theorem bit_to_nat (b n) : (bit b n : ℕ) = nat.bit b n := by cases b; cases n; refl theorem cast_succ' [add_monoid α] [has_one α] (n) : (succ' n : α) = n + 1 := by rw [← pos_num.cast_to_nat, succ'_to_nat, nat.cast_add_one, cast_to_nat] theorem cast_succ [add_monoid α] [has_one α] (n) : (succ n : α) = n + 1 := cast_succ' n @[simp, norm_cast] theorem cast_add [semiring α] (m n) : ((m + n : num) : α) = m + n := by rw [← cast_to_nat, add_to_nat, nat.cast_add, cast_to_nat, cast_to_nat] @[simp, norm_cast] theorem cast_bit0 [semiring α] (n : num) : (n.bit0 : α) = _root_.bit0 n := by rw [← bit0_of_bit0, _root_.bit0, cast_add]; refl @[simp, norm_cast] theorem cast_bit1 [semiring α] (n : num) : (n.bit1 : α) = _root_.bit1 n := by rw [← bit1_of_bit1, _root_.bit1, bit0_of_bit0, cast_add, cast_bit0]; refl @[simp, norm_cast] theorem cast_mul [semiring α] : ∀ m n, ((m * n : num) : α) = m * n | 0 0 := (zero_mul _).symm | 0 (pos q) := (zero_mul _).symm | (pos p) 0 := (mul_zero _).symm | (pos p) (pos q) := pos_num.cast_mul _ _ theorem size_to_nat : ∀ n, (size n : ℕ) = nat.size n | 0 := nat.size_zero.symm | (pos p) := p.size_to_nat theorem size_eq_nat_size : ∀ n, (size n : ℕ) = nat_size n | 0 := rfl | (pos p) := p.size_eq_nat_size theorem nat_size_to_nat (n) : nat_size n = nat.size n := by rw [← size_eq_nat_size, size_to_nat] @[simp] theorem of_nat'_eq : ∀ n, num.of_nat' n = n := nat.binary_rec rfl $ λ b n IH, begin rw of_nat' at IH ⊢, rw [nat.binary_rec_eq, IH], { cases b; simp [nat.bit, bit0_of_bit0, bit1_of_bit1] }, { refl } end theorem zneg_to_znum (n : num) : -n.to_znum = n.to_znum_neg := by cases n; refl theorem zneg_to_znum_neg (n : num) : -n.to_znum_neg = n.to_znum := by cases n; refl theorem to_znum_inj {m n : num} : m.to_znum = n.to_znum ↔ m = n := ⟨λ h, by cases m; cases n; cases h; refl, congr_arg _⟩ @[simp, norm_cast squash] theorem cast_to_znum [has_zero α] [has_one α] [has_add α] [has_neg α] : ∀ n : num, (n.to_znum : α) = n | 0 := rfl | (num.pos p) := rfl @[simp] theorem cast_to_znum_neg [add_group α] [has_one α] : ∀ n : num, (n.to_znum_neg : α) = -n | 0 := neg_zero.symm | (num.pos p) := rfl @[simp] theorem add_to_znum (m n : num) : num.to_znum (m + n) = m.to_znum + n.to_znum := by cases m; cases n; refl end num namespace pos_num open num theorem pred_to_nat {n : pos_num} (h : n > 1) : (pred n : ℕ) = nat.pred n := begin unfold pred, have := pred'_to_nat n, cases e : pred' n, { have : (1:ℕ) ≤ nat.pred n := nat.pred_le_pred ((@cast_lt ℕ _ _ _).2 h), rw [← pred'_to_nat, e] at this, exact absurd this dec_trivial }, { rw [← pred'_to_nat, e], refl } end theorem sub'_one (a : pos_num) : sub' a 1 = (pred' a).to_znum := by cases a; refl theorem one_sub' (a : pos_num) : sub' 1 a = (pred' a).to_znum_neg := by cases a; refl theorem lt_iff_cmp {m n} : m < n ↔ cmp m n = ordering.lt := iff.rfl theorem le_iff_cmp {m n} : m ≤ n ↔ cmp m n ≠ ordering.gt := not_congr $ lt_iff_cmp.trans $ by rw ← cmp_swap; cases cmp m n; exact dec_trivial end pos_num namespace num variables {α : Type*} open pos_num theorem pred_to_nat : ∀ (n : num), (pred n : ℕ) = nat.pred n | 0 := rfl | (pos p) := by rw [pred, pos_num.pred'_to_nat]; refl theorem ppred_to_nat : ∀ (n : num), coe <$> ppred n = nat.ppred n | 0 := rfl | (pos p) := by rw [ppred, option.map_some, nat.ppred_eq_some.2]; rw [pos_num.pred'_to_nat, nat.succ_pred_eq_of_pos (pos_num.to_nat_pos _)]; refl theorem cmp_swap (m n) : (cmp m n).swap = cmp n m := by cases m; cases n; try {unfold cmp}; try {refl}; apply pos_num.cmp_swap theorem cmp_eq (m n) : cmp m n = ordering.eq ↔ m = n := begin have := cmp_to_nat m n, cases cmp m n; simp at this ⊢; try {exact this}; { simp [show m ≠ n, from λ e, by rw e at this; exact lt_irrefl _ this] } end @[simp, norm_cast] theorem cast_lt [linear_ordered_semiring α] {m n : num} : (m:α) < n ↔ m < n := by rw [← cast_to_nat m, ← cast_to_nat n, nat.cast_lt, lt_to_nat] @[simp, norm_cast] theorem cast_le [linear_ordered_semiring α] {m n : num} : (m:α) ≤ n ↔ m ≤ n := by rw ← not_lt; exact not_congr cast_lt @[simp, norm_cast] theorem cast_inj [linear_ordered_semiring α] {m n : num} : (m:α) = n ↔ m = n := by rw [← cast_to_nat m, ← cast_to_nat n, nat.cast_inj, to_nat_inj] theorem lt_iff_cmp {m n} : m < n ↔ cmp m n = ordering.lt := iff.rfl theorem le_iff_cmp {m n} : m ≤ n ↔ cmp m n ≠ ordering.gt := not_congr $ lt_iff_cmp.trans $ by rw ← cmp_swap; cases cmp m n; exact dec_trivial theorem bitwise_to_nat {f : num → num → num} {g : bool → bool → bool} (p : pos_num → pos_num → num) (gff : g ff ff = ff) (f00 : f 0 0 = 0) (f0n : ∀ n, f 0 (pos n) = cond (g ff tt) (pos n) 0) (fn0 : ∀ n, f (pos n) 0 = cond (g tt ff) (pos n) 0) (fnn : ∀ m n, f (pos m) (pos n) = p m n) (p11 : p 1 1 = cond (g tt tt) 1 0) (p1b : ∀ b n, p 1 (pos_num.bit b n) = bit (g tt b) (cond (g ff tt) (pos n) 0)) (pb1 : ∀ a m, p (pos_num.bit a m) 1 = bit (g a tt) (cond (g tt ff) (pos m) 0)) (pbb : ∀ a b m n, p (pos_num.bit a m) (pos_num.bit b n) = bit (g a b) (p m n)) : ∀ m n : num, (f m n : ℕ) = nat.bitwise g m n := begin intros, cases m with m; cases n with n; try { change zero with 0 }; try { change ((0:num):ℕ) with 0 }, { rw [f00, nat.bitwise_zero]; refl }, { unfold nat.bitwise, rw [f0n, nat.binary_rec_zero], cases g ff tt; refl }, { unfold nat.bitwise, generalize h : (pos m : ℕ) = m', revert h, apply nat.bit_cases_on m' _, intros b m' h, rw [fn0, nat.binary_rec_eq, nat.binary_rec_zero, ←h], cases g tt ff; refl, apply nat.bitwise_bit_aux gff }, { rw fnn, have : ∀b (n : pos_num), (cond b ↑n 0 : ℕ) = ↑(cond b (pos n) 0 : num) := by intros; cases b; refl, induction m with m IH m IH generalizing n; cases n with n n, any_goals { change one with 1 }, any_goals { change pos 1 with 1 }, any_goals { change pos_num.bit0 with pos_num.bit ff }, any_goals { change pos_num.bit1 with pos_num.bit tt }, any_goals { change ((1:num):ℕ) with nat.bit tt 0 }, all_goals { repeat { rw show ∀ b n, (pos (pos_num.bit b n) : ℕ) = nat.bit b ↑n, by intros; cases b; refl }, rw nat.bitwise_bit }, any_goals { assumption }, any_goals { rw [nat.bitwise_zero, p11], cases g tt tt; refl }, any_goals { rw [nat.bitwise_zero_left, this, ← bit_to_nat, p1b] }, any_goals { rw [nat.bitwise_zero_right _ gff, this, ← bit_to_nat, pb1] }, all_goals { rw [← show ∀ n, ↑(p m n) = nat.bitwise g ↑m ↑n, from IH], rw [← bit_to_nat, pbb] } } end @[simp, norm_cast] theorem lor_to_nat : ∀ m n, (lor m n : ℕ) = nat.lor m n := by apply bitwise_to_nat (λx y, pos (pos_num.lor x y)); intros; try {cases a}; try {cases b}; refl @[simp, norm_cast] theorem land_to_nat : ∀ m n, (land m n : ℕ) = nat.land m n := by apply bitwise_to_nat pos_num.land; intros; try {cases a}; try {cases b}; refl @[simp, norm_cast] theorem ldiff_to_nat : ∀ m n, (ldiff m n : ℕ) = nat.ldiff m n := by apply bitwise_to_nat pos_num.ldiff; intros; try {cases a}; try {cases b}; refl @[simp, norm_cast] theorem lxor_to_nat : ∀ m n, (lxor m n : ℕ) = nat.lxor m n := by apply bitwise_to_nat pos_num.lxor; intros; try {cases a}; try {cases b}; refl @[simp, norm_cast] theorem shiftl_to_nat (m n) : (shiftl m n : ℕ) = nat.shiftl m n := begin cases m; dunfold shiftl, {symmetry, apply nat.zero_shiftl}, simp, induction n with n IH, {refl}, simp [pos_num.shiftl, nat.shiftl_succ], rw ←IH end @[simp, norm_cast] theorem shiftr_to_nat (m n) : (shiftr m n : ℕ) = nat.shiftr m n := begin cases m with m; dunfold shiftr, {symmetry, apply nat.zero_shiftr}, induction n with n IH generalizing m, {cases m; refl}, cases m with m m; dunfold pos_num.shiftr, { rw [nat.shiftr_eq_div_pow], symmetry, apply nat.div_eq_of_lt, exact @nat.pow_lt_pow_of_lt_right 2 dec_trivial 0 (n+1) (nat.succ_pos _) }, { transitivity, apply IH, change nat.shiftr m n = nat.shiftr (bit1 m) (n+1), rw [add_comm n 1, nat.shiftr_add], apply congr_arg (λx, nat.shiftr x n), unfold nat.shiftr, change (bit1 ↑m : ℕ) with nat.bit tt m, rw nat.div2_bit }, { transitivity, apply IH, change nat.shiftr m n = nat.shiftr (bit0 m) (n + 1), rw [add_comm n 1, nat.shiftr_add], apply congr_arg (λx, nat.shiftr x n), unfold nat.shiftr, change (bit0 ↑m : ℕ) with nat.bit ff m, rw nat.div2_bit } end @[simp] theorem test_bit_to_nat (m n) : test_bit m n = nat.test_bit m n := begin cases m with m; unfold test_bit nat.test_bit, { change (zero : nat) with 0, rw nat.zero_shiftr, refl }, induction n with n IH generalizing m; cases m; dunfold pos_num.test_bit, {refl}, { exact (nat.bodd_bit _ _).symm }, { exact (nat.bodd_bit _ _).symm }, { change ff = nat.bodd (nat.shiftr 1 (n + 1)), rw [add_comm, nat.shiftr_add], change nat.shiftr 1 1 with 0, rw nat.zero_shiftr; refl }, { change pos_num.test_bit m n = nat.bodd (nat.shiftr (nat.bit tt m) (n + 1)), rw [add_comm, nat.shiftr_add], unfold nat.shiftr, rw nat.div2_bit, apply IH }, { change pos_num.test_bit m n = nat.bodd (nat.shiftr (nat.bit ff m) (n + 1)), rw [add_comm, nat.shiftr_add], unfold nat.shiftr, rw nat.div2_bit, apply IH }, end end num namespace znum variables {α : Type*} open pos_num @[simp, norm_cast] theorem cast_zero [has_zero α] [has_one α] [has_add α] [has_neg α] : ((0 : znum) : α) = 0 := rfl @[simp] theorem cast_zero' [has_zero α] [has_one α] [has_add α] [has_neg α] : (znum.zero : α) = 0 := rfl @[simp, norm_cast] theorem cast_one [has_zero α] [has_one α] [has_add α] [has_neg α] : ((1 : znum) : α) = 1 := rfl @[simp] theorem cast_pos [has_zero α] [has_one α] [has_add α] [has_neg α] (n : pos_num) : (pos n : α) = n := rfl @[simp] theorem cast_neg [has_zero α] [has_one α] [has_add α] [has_neg α] (n : pos_num) : (neg n : α) = -n := rfl @[simp, norm_cast] theorem cast_zneg [add_group α] [has_one α] : ∀ n, ((-n : znum) : α) = -n | 0 := neg_zero.symm | (pos p) := rfl | (neg p) := (neg_neg _).symm theorem neg_zero : (-0 : znum) = 0 := rfl theorem zneg_pos (n : pos_num) : -pos n = neg n := rfl theorem zneg_neg (n : pos_num) : -neg n = pos n := rfl theorem zneg_zneg (n : znum) : - -n = n := by cases n; refl theorem zneg_bit1 (n : znum) : -n.bit1 = (-n).bitm1 := by cases n; refl theorem zneg_bitm1 (n : znum) : -n.bitm1 = (-n).bit1 := by cases n; refl theorem zneg_succ (n : znum) : -n.succ = (-n).pred := by cases n; try {refl}; rw [succ, num.zneg_to_znum_neg]; refl theorem zneg_pred (n : znum) : -n.pred = (-n).succ := by rw [← zneg_zneg (succ (-n)), zneg_succ, zneg_zneg] @[simp, norm_cast] theorem neg_of_int : ∀ n, ((-n : ℤ) : znum) = -n | (n+1:ℕ) := rfl | 0 := rfl | -[1+n] := (zneg_zneg _).symm @[simp] theorem abs_to_nat : ∀ n, (abs n : ℕ) = int.nat_abs n | 0 := rfl | (pos p) := congr_arg int.nat_abs p.to_nat_to_int | (neg p) := show int.nat_abs ((p:ℕ):ℤ) = int.nat_abs (- p), by rw [p.to_nat_to_int, int.nat_abs_neg] @[simp] theorem abs_to_znum : ∀ n : num, abs n.to_znum = n | 0 := rfl | (num.pos p) := rfl @[simp, norm_cast] theorem cast_to_int [add_group α] [has_one α] : ∀ n : znum, ((n : ℤ) : α) = n | 0 := rfl | (pos p) := by rw [cast_pos, cast_pos, pos_num.cast_to_int] | (neg p) := by rw [cast_neg, cast_neg, int.cast_neg, pos_num.cast_to_int] theorem bit0_of_bit0 : ∀ n : znum, _root_.bit0 n = n.bit0 | 0 := rfl | (pos a) := congr_arg pos a.bit0_of_bit0 | (neg a) := congr_arg neg a.bit0_of_bit0 theorem bit1_of_bit1 : ∀ n : znum, _root_.bit1 n = n.bit1 | 0 := rfl | (pos a) := congr_arg pos a.bit1_of_bit1 | (neg a) := show pos_num.sub' 1 (_root_.bit0 a) = _, by rw [pos_num.one_sub', a.bit0_of_bit0]; refl @[simp, norm_cast] theorem cast_bit0 [add_group α] [has_one α] : ∀ n : znum, (n.bit0 : α) = bit0 n | 0 := (add_zero _).symm | (pos p) := by rw [znum.bit0, cast_pos, cast_pos]; refl | (neg p) := by rw [znum.bit0, cast_neg, cast_neg, pos_num.cast_bit0, _root_.bit0, _root_.bit0, neg_add_rev] @[simp, norm_cast] theorem cast_bit1 [add_group α] [has_one α] : ∀ n : znum, (n.bit1 : α) = bit1 n | 0 := by simp [znum.bit1, _root_.bit1, _root_.bit0] | (pos p) := by rw [znum.bit1, cast_pos, cast_pos]; refl | (neg p) := begin rw [znum.bit1, cast_neg, cast_neg], cases e : pred' p; have : p = _ := (succ'_pred' p).symm.trans (congr_arg num.succ' e), { change p=1 at this, subst p, simp [_root_.bit1, _root_.bit0] }, { rw [num.succ'] at this, subst p, have : (↑(-↑a:ℤ) : α) = -1 + ↑(-↑a + 1 : ℤ), {simp [add_comm]}, simpa [_root_.bit1, _root_.bit0, -add_comm] }, end @[simp] theorem cast_bitm1 [add_group α] [has_one α] (n : znum) : (n.bitm1 : α) = bit0 n - 1 := begin conv { to_lhs, rw ← zneg_zneg n }, rw [← zneg_bit1, cast_zneg, cast_bit1], have : ((-1 + n + n : ℤ) : α) = (n + n + -1 : ℤ), {simp [add_comm, add_left_comm]}, simpa [_root_.bit1, _root_.bit0, sub_eq_add_neg] end theorem add_zero (n : znum) : n + 0 = n := by cases n; refl theorem zero_add (n : znum) : 0 + n = n := by cases n; refl theorem add_one : ∀ n : znum, n + 1 = succ n | 0 := rfl | (pos p) := congr_arg pos p.add_one | (neg p) := by cases p; refl end znum namespace pos_num variables {α : Type*} theorem cast_to_znum : ∀ n : pos_num, (n : znum) = znum.pos n | 1 := rfl | (bit0 p) := (znum.bit0_of_bit0 p).trans $ congr_arg _ (cast_to_znum p) | (bit1 p) := (znum.bit1_of_bit1 p).trans $ congr_arg _ (cast_to_znum p) theorem cast_sub' [add_group α] [has_one α] : ∀ m n : pos_num, (sub' m n : α) = m - n | a 1 := by rw [sub'_one, num.cast_to_znum, ← num.cast_to_nat, pred'_to_nat, ← nat.sub_one]; simp [pos_num.cast_pos] | 1 b := by rw [one_sub', num.cast_to_znum_neg, ← neg_sub, neg_inj', ← num.cast_to_nat, pred'_to_nat, ← nat.sub_one]; simp [pos_num.cast_pos] | (bit0 a) (bit0 b) := begin rw [sub', znum.cast_bit0, cast_sub'], have : ((a + -b + (a + -b) : ℤ) : α) = a + a + (-b + -b), {simp [add_left_comm]}, simpa [_root_.bit0, sub_eq_add_neg] end | (bit0 a) (bit1 b) := begin rw [sub', znum.cast_bitm1, cast_sub'], have : ((-b + (a + (-b + -1)) : ℤ) : α) = (a + -1 + (-b + -b):ℤ), { simp [add_comm, add_left_comm] }, simpa [_root_.bit1, _root_.bit0, sub_eq_add_neg] end | (bit1 a) (bit0 b) := begin rw [sub', znum.cast_bit1, cast_sub'], have : ((-b + (a + (-b + 1)) : ℤ) : α) = (a + 1 + (-b + -b):ℤ), { simp [add_comm, add_left_comm] }, simpa [_root_.bit1, _root_.bit0, sub_eq_add_neg] end | (bit1 a) (bit1 b) := begin rw [sub', znum.cast_bit0, cast_sub'], have : ((-b + (a + -b) : ℤ) : α) = a + (-b + -b), {simp [add_left_comm]}, simpa [_root_.bit1, _root_.bit0, sub_eq_add_neg] end theorem to_nat_eq_succ_pred (n : pos_num) : (n:ℕ) = n.pred' + 1 := by rw [← num.succ'_to_nat, n.succ'_pred'] theorem to_int_eq_succ_pred (n : pos_num) : (n:ℤ) = (n.pred' : ℕ) + 1 := by rw [← n.to_nat_to_int, to_nat_eq_succ_pred]; refl end pos_num namespace num variables {α : Type*} @[simp] theorem cast_sub' [add_group α] [has_one α] : ∀ m n : num, (sub' m n : α) = m - n | 0 0 := (sub_zero _).symm | (pos a) 0 := (sub_zero _).symm | 0 (pos b) := (zero_sub _).symm | (pos a) (pos b) := pos_num.cast_sub' _ _ @[simp] theorem of_nat_to_znum : ∀ n : ℕ, to_znum n = n | 0 := rfl | (n+1) := by rw [nat.cast_add_one, nat.cast_add_one, znum.add_one, add_one, ← of_nat_to_znum]; cases (n:num); refl @[simp] theorem of_nat_to_znum_neg (n : ℕ) : to_znum_neg n = -n := by rw [← of_nat_to_znum, zneg_to_znum] theorem mem_of_znum' : ∀ {m : num} {n : znum}, m ∈ of_znum' n ↔ n = to_znum m | 0 0 := ⟨λ _, rfl, λ _, rfl⟩ | (pos m) 0 := ⟨λ h, by cases h, λ h, by cases h⟩ | m (znum.pos p) := option.some_inj.trans $ by cases m; split; intro h; try {cases h}; refl | m (znum.neg p) := ⟨λ h, by cases h, λ h, by cases m; cases h⟩ theorem of_znum'_to_nat : ∀ (n : znum), coe <$> of_znum' n = int.to_nat' n | 0 := rfl | (znum.pos p) := show _ = int.to_nat' p, by rw [← pos_num.to_nat_to_int p]; refl | (znum.neg p) := congr_arg (λ x, int.to_nat' (-x)) $ show ((p.pred' + 1 : ℕ) : ℤ) = p, by rw ← succ'_to_nat; simp @[simp] theorem of_znum_to_nat : ∀ (n : znum), (of_znum n : ℕ) = int.to_nat n | 0 := rfl | (znum.pos p) := show _ = int.to_nat p, by rw [← pos_num.to_nat_to_int p]; refl | (znum.neg p) := congr_arg (λ x, int.to_nat (-x)) $ show ((p.pred' + 1 : ℕ) : ℤ) = p, by rw ← succ'_to_nat; simp @[simp] theorem cast_of_znum [add_group α] [has_one α] (n : znum) : (of_znum n : α) = int.to_nat n := by rw [← cast_to_nat, of_znum_to_nat] @[simp, norm_cast] theorem sub_to_nat (m n) : ((m - n : num) : ℕ) = m - n := show (of_znum _ : ℕ) = _, by rw [of_znum_to_nat, cast_sub', ← to_nat_to_int, ← to_nat_to_int, int.to_nat_sub] end num namespace znum variables {α : Type*} @[simp, norm_cast] theorem cast_add [add_group α] [has_one α] : ∀ m n, ((m + n : znum) : α) = m + n | 0 a := by cases a; exact (_root_.zero_add _).symm | b 0 := by cases b; exact (_root_.add_zero _).symm | (pos a) (pos b) := pos_num.cast_add _ _ | (pos a) (neg b) := pos_num.cast_sub' _ _ | (neg a) (pos b) := (pos_num.cast_sub' _ _).trans $ show ↑b + -↑a = -↑a + ↑b, by rw [← pos_num.cast_to_int a, ← pos_num.cast_to_int b, ← int.cast_neg, ← int.cast_add (-a)]; simp [add_comm] | (neg a) (neg b) := show -(↑(a + b) : α) = -a + -b, by rw [ pos_num.cast_add, neg_eq_iff_neg_eq, neg_add_rev, neg_neg, neg_neg, ← pos_num.cast_to_int a, ← pos_num.cast_to_int b, ← int.cast_add]; simp [add_comm] @[simp] theorem cast_succ [add_group α] [has_one α] (n) : ((succ n : znum) : α) = n + 1 := by rw [← add_one, cast_add, cast_one] @[simp, norm_cast] theorem mul_to_int : ∀ m n, ((m * n : znum) : ℤ) = m * n | 0 a := by cases a; exact (_root_.zero_mul _).symm | b 0 := by cases b; exact (_root_.mul_zero _).symm | (pos a) (pos b) := pos_num.cast_mul a b | (pos a) (neg b) := show -↑(a * b) = ↑a * -↑b, by rw [pos_num.cast_mul, neg_mul_eq_mul_neg] | (neg a) (pos b) := show -↑(a * b) = -↑a * ↑b, by rw [pos_num.cast_mul, neg_mul_eq_neg_mul] | (neg a) (neg b) := show ↑(a * b) = -↑a * -↑b, by rw [pos_num.cast_mul, neg_mul_neg] theorem cast_mul [ring α] (m n) : ((m * n : znum) : α) = m * n := by rw [← cast_to_int, mul_to_int, int.cast_mul, cast_to_int, cast_to_int] @[simp, norm_cast] theorem of_to_int : Π (n : znum), ((n : ℤ) : znum) = n | 0 := rfl | (pos a) := by rw [cast_pos, ← pos_num.cast_to_nat, int.cast_coe_nat', ← num.of_nat_to_znum, pos_num.of_to_nat]; refl | (neg a) := by rw [cast_neg, neg_of_int, ← pos_num.cast_to_nat, int.cast_coe_nat', ← num.of_nat_to_znum_neg, pos_num.of_to_nat]; refl @[norm_cast] theorem to_of_int : Π (n : ℤ), ((n : znum) : ℤ) = n | (n : ℕ) := by rw [int.cast_coe_nat, ← num.of_nat_to_znum, num.cast_to_znum, ← num.cast_to_nat, int.nat_cast_eq_coe_nat, num.to_of_nat] | -[1+ n] := by rw [int.cast_neg_succ_of_nat, cast_zneg, add_one, cast_succ, int.neg_succ_of_nat_eq, ← num.of_nat_to_znum, num.cast_to_znum, ← num.cast_to_nat, int.nat_cast_eq_coe_nat, num.to_of_nat] theorem to_int_inj {m n : znum} : (m : ℤ) = n ↔ m = n := ⟨λ h, function.injective_of_left_inverse of_to_int h, congr_arg _⟩ @[simp, norm_cast] theorem of_int_cast [add_group α] [has_one α] (n : ℤ) : ((n : znum) : α) = n := by rw [← cast_to_int, to_of_int] @[simp, norm_cast] theorem of_nat_cast [add_group α] [has_one α] (n : ℕ) : ((n : znum) : α) = n := of_int_cast n @[simp] theorem of_int'_eq : ∀ n, znum.of_int' n = n | (n : ℕ) := to_int_inj.1 $ by simp [znum.of_int'] | -[1+ n] := to_int_inj.1 $ by simp [znum.of_int'] theorem cmp_to_int : ∀ (m n), (ordering.cases_on (cmp m n) ((m:ℤ) < n) (m = n) ((m:ℤ) > n) : Prop) | 0 0 := rfl | (pos a) (pos b) := begin have := pos_num.cmp_to_nat a b; revert this; dsimp [cmp]; cases pos_num.cmp a b; dsimp; [simp, exact congr_arg pos, simp [gt]] end | (neg a) (neg b) := begin have := pos_num.cmp_to_nat b a; revert this; dsimp [cmp]; cases pos_num.cmp b a; dsimp; [simp, simp {contextual := tt}, simp [gt]] end | (pos a) 0 := pos_num.cast_pos _ | (pos a) (neg b) := lt_trans (neg_lt_zero.2 $ pos_num.cast_pos _) (pos_num.cast_pos _) | 0 (neg b) := neg_lt_zero.2 $ pos_num.cast_pos _ | (neg a) 0 := neg_lt_zero.2 $ pos_num.cast_pos _ | (neg a) (pos b) := lt_trans (neg_lt_zero.2 $ pos_num.cast_pos _) (pos_num.cast_pos _) | 0 (pos b) := pos_num.cast_pos _ @[norm_cast] theorem lt_to_int {m n : znum} : (m:ℤ) < n ↔ m < n := show (m:ℤ) < n ↔ cmp m n = ordering.lt, from match cmp m n, cmp_to_int m n with | ordering.lt, h := by simp at h; simp [h] | ordering.eq, h := by simp at h; simp [h, lt_irrefl]; exact dec_trivial | ordering.gt, h := by simp [not_lt_of_gt h]; exact dec_trivial end theorem le_to_int {m n : znum} : (m:ℤ) ≤ n ↔ m ≤ n := by rw ← not_lt; exact not_congr lt_to_int @[simp, norm_cast] theorem cast_lt [linear_ordered_ring α] {m n : znum} : (m:α) < n ↔ m < n := by rw [← cast_to_int m, ← cast_to_int n, int.cast_lt, lt_to_int] @[simp, norm_cast] theorem cast_le [linear_ordered_ring α] {m n : znum} : (m:α) ≤ n ↔ m ≤ n := by rw ← not_lt; exact not_congr cast_lt @[simp, norm_cast] theorem cast_inj [linear_ordered_ring α] {m n : znum} : (m:α) = n ↔ m = n := by rw [← cast_to_int m, ← cast_to_int n, int.cast_inj, to_int_inj] meta def transfer_rw : tactic unit := `[repeat {rw ← to_int_inj <|> rw ← lt_to_int <|> rw ← le_to_int}, repeat {rw cast_add <|> rw mul_to_int <|> rw cast_one <|> rw cast_zero}] meta def transfer : tactic unit := `[intros, transfer_rw, try {simp [add_comm, add_left_comm, mul_comm, mul_left_comm]}] instance : decidable_linear_order znum := { lt := (<), lt_iff_le_not_le := by {intros a b, transfer_rw, apply lt_iff_le_not_le}, le := (≤), le_refl := by transfer, le_trans := by {intros a b c, transfer_rw, apply le_trans}, le_antisymm := by {intros a b, transfer_rw, apply le_antisymm}, le_total := by {intros a b, transfer_rw, apply le_total}, decidable_eq := znum.decidable_eq, decidable_le := znum.decidable_le, decidable_lt := znum.decidable_lt } instance : add_comm_group znum := { add := (+), add_assoc := by transfer, zero := 0, zero_add := zero_add, add_zero := add_zero, add_comm := by transfer, neg := has_neg.neg, add_left_neg := by transfer } instance : decidable_linear_ordered_comm_ring znum := { mul := (*), mul_assoc := by transfer, one := 1, one_mul := by transfer, mul_one := by transfer, left_distrib := by {transfer, simp [mul_add]}, right_distrib := by {transfer, simp [mul_add, mul_comm]}, mul_comm := by transfer, zero_ne_one := dec_trivial, add_le_add_left := by {intros a b h c, revert h, transfer_rw, exact λ h, add_le_add_left h c}, mul_pos := λ a b, show 0 < a → 0 < b → 0 < a * b, by {transfer_rw, apply mul_pos}, zero_lt_one := dec_trivial, ..znum.decidable_linear_order, ..znum.add_comm_group } @[simp, norm_cast] theorem dvd_to_int (m n : znum) : (m : ℤ) ∣ n ↔ m ∣ n := ⟨λ ⟨k, e⟩, ⟨k, by rw [← of_to_int n, e]; simp⟩, λ ⟨k, e⟩, ⟨k, by simp [e]⟩⟩ end znum namespace pos_num theorem divmod_to_nat_aux {n d : pos_num} {q r : num} (h₁ : (r:ℕ) + d * _root_.bit0 q = n) (h₂ : (r:ℕ) < 2 * d) : ((divmod_aux d q r).2 + d * (divmod_aux d q r).1 : ℕ) = ↑n ∧ ((divmod_aux d q r).2 : ℕ) < d := begin unfold divmod_aux, have : ∀ {r₂}, num.of_znum' (num.sub' r (num.pos d)) = some r₂ ↔ (r : ℕ) = r₂ + d, { intro r₂, apply num.mem_of_znum'.trans, rw [← znum.to_int_inj, num.cast_to_znum, num.cast_sub', sub_eq_iff_eq_add, ← int.coe_nat_inj'], simp }, cases e : num.of_znum' (num.sub' r (num.pos d)) with r₂; simp [divmod_aux], { refine ⟨h₁, lt_of_not_ge (λ h, _)⟩, cases nat.le.dest h with r₂ e', rw [← num.to_of_nat r₂, add_comm] at e', cases e.symm.trans (this.2 e'.symm) }, { have := this.1 e, split, { rwa [_root_.bit1, add_comm _ 1, mul_add, mul_one, ← add_assoc, ← this] }, { rwa [this, two_mul, add_lt_add_iff_right] at h₂ } } end theorem divmod_to_nat (d n : pos_num) : (n / d : ℕ) = (divmod d n).1 ∧ (n % d : ℕ) = (divmod d n).2 := begin rw nat.div_mod_unique (pos_num.cast_pos _), induction n with n IH n IH, { exact divmod_to_nat_aux (by simp; refl) (nat.mul_le_mul_left 2 (pos_num.cast_pos d : (0 : ℕ) < d)) }, { unfold divmod, cases divmod d n with q r, simp only [divmod] at IH ⊢, apply divmod_to_nat_aux; simp, { rw [_root_.bit1, _root_.bit1, add_right_comm, bit0_eq_two_mul ↑n, ← IH.1, mul_add, ← bit0_eq_two_mul, mul_left_comm, ← bit0_eq_two_mul] }, { rw ← bit0_eq_two_mul, exact nat.bit1_lt_bit0 IH.2 } }, { unfold divmod, cases divmod d n with q r, simp only [divmod] at IH ⊢, apply divmod_to_nat_aux; simp, { rw [bit0_eq_two_mul ↑n, ← IH.1, mul_add, ← bit0_eq_two_mul, mul_left_comm, ← bit0_eq_two_mul] }, { rw ← bit0_eq_two_mul, exact nat.bit0_lt IH.2 } } end @[simp] theorem div'_to_nat (n d) : (div' n d : ℕ) = n / d := (divmod_to_nat _ _).1.symm @[simp] theorem mod'_to_nat (n d) : (mod' n d : ℕ) = n % d := (divmod_to_nat _ _).2.symm end pos_num namespace num @[simp, norm_cast] theorem div_to_nat : ∀ n d, ((n / d : num) : ℕ) = n / d | 0 0 := rfl | 0 (pos d) := (nat.zero_div _).symm | (pos n) 0 := (nat.div_zero _).symm | (pos n) (pos d) := pos_num.div'_to_nat _ _ @[simp, norm_cast] theorem mod_to_nat : ∀ n d, ((n % d : num) : ℕ) = n % d | 0 0 := rfl | 0 (pos d) := (nat.zero_mod _).symm | (pos n) 0 := (nat.mod_zero _).symm | (pos n) (pos d) := pos_num.mod'_to_nat _ _ theorem gcd_to_nat_aux : ∀ {n} {a b : num}, a ≤ b → (a * b).nat_size ≤ n → (gcd_aux n a b : ℕ) = nat.gcd a b | 0 0 b ab h := (nat.gcd_zero_left _).symm | 0 (pos a) 0 ab h := (not_lt_of_ge ab).elim rfl | 0 (pos a) (pos b) ab h := (not_lt_of_le h).elim $ pos_num.nat_size_pos _ | (nat.succ n) 0 b ab h := (nat.gcd_zero_left _).symm | (nat.succ n) (pos a) b ab h := begin simp [gcd_aux], rw [nat.gcd_rec, gcd_to_nat_aux, mod_to_nat], {refl}, { rw [← le_to_nat, mod_to_nat], exact le_of_lt (nat.mod_lt _ (pos_num.cast_pos _)) }, rw [nat_size_to_nat, mul_to_nat, nat.size_le] at h ⊢, rw [mod_to_nat, mul_comm], rw [nat.pow_succ, ← nat.mod_add_div b (pos a)] at h, refine lt_of_mul_lt_mul_right (lt_of_le_of_lt _ h) (nat.zero_le 2), rw [mul_two, mul_add], refine add_le_add_left (nat.mul_le_mul_left _ (le_trans (le_of_lt (nat.mod_lt _ (pos_num.cast_pos _))) _)) _, suffices : 1 ≤ _, simpa using nat.mul_le_mul_left (pos a) this, rw [nat.le_div_iff_mul_le _ _ a.cast_pos, one_mul], exact le_to_nat.2 ab end @[simp] theorem gcd_to_nat : ∀ a b, (gcd a b : ℕ) = nat.gcd a b := have ∀ a b : num, (a * b).nat_size ≤ a.nat_size + b.nat_size, begin intros, simp [nat_size_to_nat], rw [nat.size_le, nat.pow_add], exact mul_lt_mul'' (nat.lt_size_self _) (nat.lt_size_self _) (nat.zero_le _) (nat.zero_le _) end, begin intros, unfold gcd, split_ifs, { exact gcd_to_nat_aux h (this _ _) }, { rw nat.gcd_comm, exact gcd_to_nat_aux (le_of_not_le h) (this _ _) } end theorem dvd_iff_mod_eq_zero {m n : num} : m ∣ n ↔ n % m = 0 := by rw [← dvd_to_nat, nat.dvd_iff_mod_eq_zero, ← to_nat_inj, mod_to_nat]; refl instance : decidable_rel ((∣) : num → num → Prop) | a b := decidable_of_iff' _ dvd_iff_mod_eq_zero end num namespace znum @[simp, norm_cast] theorem div_to_int : ∀ n d, ((n / d : znum) : ℤ) = n / d | 0 0 := rfl | 0 (pos d) := (int.zero_div _).symm | 0 (neg d) := (int.zero_div _).symm | (pos n) 0 := (int.div_zero _).symm | (neg n) 0 := (int.div_zero _).symm | (pos n) (pos d) := (num.cast_to_znum _).trans $ by rw ← num.to_nat_to_int; simp | (pos n) (neg d) := (num.cast_to_znum_neg _).trans $ by rw ← num.to_nat_to_int; simp | (neg n) (pos d) := show - _ = (-_/↑d), begin rw [n.to_int_eq_succ_pred, d.to_int_eq_succ_pred, ← pos_num.to_nat_to_int, num.succ'_to_nat, num.div_to_nat], change -[1+ n.pred' / ↑d] = -[1+ n.pred' / (d.pred' + 1)], rw d.to_nat_eq_succ_pred end | (neg n) (neg d) := show ↑(pos_num.pred' n / num.pos d).succ' = (-_ / -↑d), begin rw [n.to_int_eq_succ_pred, d.to_int_eq_succ_pred, ← pos_num.to_nat_to_int, num.succ'_to_nat, num.div_to_nat], change (nat.succ (_/d) : ℤ) = nat.succ (n.pred'/(d.pred' + 1)), rw d.to_nat_eq_succ_pred end @[simp, norm_cast] theorem mod_to_int : ∀ n d, ((n % d : znum) : ℤ) = n % d | 0 d := (int.zero_mod _).symm | (pos n) d := (num.cast_to_znum _).trans $ by rw [← num.to_nat_to_int, cast_pos, num.mod_to_nat, ← pos_num.to_nat_to_int, abs_to_nat]; refl | (neg n) d := (num.cast_sub' _ _).trans $ by rw [← num.to_nat_to_int, cast_neg, ← num.to_nat_to_int, num.succ_to_nat, num.mod_to_nat, abs_to_nat, ← int.sub_nat_nat_eq_coe, n.to_int_eq_succ_pred]; refl @[simp] theorem gcd_to_nat (a b) : (gcd a b : ℕ) = int.gcd a b := (num.gcd_to_nat _ _).trans $ by simpa theorem dvd_iff_mod_eq_zero {m n : znum} : m ∣ n ↔ n % m = 0 := by rw [← dvd_to_int, int.dvd_iff_mod_eq_zero, ← to_int_inj, mod_to_int]; refl instance : decidable_rel ((∣) : znum → znum → Prop) | a b := decidable_of_iff' _ dvd_iff_mod_eq_zero end znum namespace int def of_snum : snum → ℤ := snum.rec' (λ a, cond a (-1) 0) (λa p IH, cond a (bit1 IH) (bit0 IH)) instance snum_coe : has_coe snum ℤ := ⟨of_snum⟩ end int instance : has_lt snum := ⟨λa b, (a : ℤ) < b⟩ instance : has_le snum := ⟨λa b, (a : ℤ) ≤ b⟩
8d2c90fbe4ff376e87ead93459b62a87a2c46b59
d1a52c3f208fa42c41df8278c3d280f075eb020c
/stage0/src/Lean/Elab/Tactic/Split.lean
0cdc4d656bbf74398599999631d94c575d63b8cd
[ "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,454
lean
/- Copyright (c) 2021 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Meta.Tactic.Split import Lean.Elab.Tactic.Basic import Lean.Elab.Tactic.Location namespace Lean.Elab.Tactic open Meta @[builtinTactic Lean.Parser.Tactic.split] def evalSplit : Tactic := fun stx => do unless stx[1].isNone do throwError "'split' tactic, term to split is not supported yet" let loc := expandOptLocation stx[2] match loc with | Location.targets hyps simplifyTarget => if (hyps.size > 0 && simplifyTarget) || hyps.size > 1 then throwErrorAt stx[2] "'split' tactic failed, select a single target to split" if simplifyTarget then liftMetaTactic fun mvarId => do let some mvarIds ← splitTarget? mvarId | throwError "'split' tactic failed" return mvarIds else let fvarId ← getFVarId hyps[0] liftMetaTactic fun mvarId => do let some mvarIds ← splitLocalDecl? mvarId fvarId | throwError "'split' tactic failed" return mvarIds | Location.wildcard => liftMetaTactic fun mvarId => do let fvarIds ← getNondepPropHyps mvarId for fvarId in fvarIds do if let some mvarIds ← splitLocalDecl? mvarId fvarId then return mvarIds let some mvarIds ← splitTarget? mvarId | throwError "'split' tactic failed" return mvarIds end Lean.Elab.Tactic
cca3a062b2fbc39a9e850719646d6876924ec0b4
a0e23cfdd129a671bf3154ee1a8a3a72bf4c7940
/stage0/src/Lean/Elab/Quotation.lean
bd21bab657f16ea9accdc8e7b3c233d37f298975
[ "Apache-2.0" ]
permissive
WojciechKarpiel/lean4
7f89706b8e3c1f942b83a2c91a3a00b05da0e65b
f6e1314fa08293dea66a329e05b6c196a0189163
refs/heads/master
1,686,633,402,214
1,625,821,189,000
1,625,821,258,000
384,640,886
0
0
Apache-2.0
1,625,903,617,000
1,625,903,026,000
null
UTF-8
Lean
false
false
24,856
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sebastian Ullrich Elaboration of syntax quotations as terms and patterns (in `match_syntax`). See also `./Hygiene.lean` for the basic hygiene workings and data types. -/ import Lean.Syntax import Lean.ResolveName import Lean.Elab.Term import Lean.Elab.Quotation.Util import Lean.Elab.Quotation.Precheck import Lean.Parser.Term namespace Lean.Elab.Term.Quotation open Lean.Parser.Term open Lean.Syntax open Meta /-- `C[$(e)]` ~> `let a := e; C[$a]`. Used in the implementation of antiquot splices. -/ private partial def floatOutAntiquotTerms : Syntax → StateT (Syntax → TermElabM Syntax) TermElabM Syntax | stx@(Syntax.node k args) => do if isAntiquot stx && !isEscapedAntiquot stx then let e := getAntiquotTerm stx if !e.isIdent || !e.getId.isAtomic then return ← withFreshMacroScope do let a ← `(a) modify (fun cont stx => (`(let $a:ident := $e; $stx) : TermElabM _)) stx.setArg 2 a Syntax.node k (← args.mapM floatOutAntiquotTerms) | stx => pure stx private def getSepFromSplice (splice : Syntax) : Syntax := do let Syntax.atom _ sep ← getAntiquotSpliceSuffix splice | unreachable! Syntax.mkStrLit (sep.dropRight 1) partial def mkTuple : Array Syntax → TermElabM Syntax | #[] => `(Unit.unit) | #[e] => e | es => do let stx ← mkTuple (es.eraseIdx 0) `(Prod.mk $(es[0]) $stx) def resolveSectionVariable (sectionVars : NameMap Name) (id : Name) : List (Name × List String) := -- decode macro scopes from name before recursion let extractionResult := extractMacroScopes id let rec loop : 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 := { extractionResult with name := id }.review match sectionVars.find? id with | some newId => [(newId, projs)] | none => loop p (s::projs) | _, _ => [] loop extractionResult.name [] /-- Transform sequence of pushes and appends into acceptable code -/ def ArrayStxBuilder := Sum (Array Syntax) Syntax namespace ArrayStxBuilder def empty : ArrayStxBuilder := Sum.inl #[] def build : ArrayStxBuilder → Syntax | Sum.inl elems => quote elems | Sum.inr arr => arr def push (b : ArrayStxBuilder) (elem : Syntax) : ArrayStxBuilder := match b with | Sum.inl elems => Sum.inl <| elems.push elem | Sum.inr arr => Sum.inr <| mkCApp ``Array.push #[arr, elem] def append (b : ArrayStxBuilder) (arr : Syntax) (appendName := ``Array.append) : ArrayStxBuilder := Sum.inr <| mkCApp appendName #[b.build, arr] end ArrayStxBuilder -- Elaborate the content of a syntax quotation term private partial def quoteSyntax : Syntax → TermElabM Syntax | Syntax.ident info rawVal val preresolved => do if !hygiene.get (← getOptions) then return ← `(Syntax.ident info $(quote rawVal) $(quote val) $(quote preresolved)) -- Add global scopes at compilation time (now), add macro scope at runtime (in the quotation). -- See the paper for details. let r ← resolveGlobalName val -- extension of the paper algorithm: also store unique section variable names as top-level scopes -- so they can be captured and used inside the section, but not outside let r' := resolveSectionVariable (← read).sectionVars val let preresolved := r ++ r' ++ preresolved let val := quote val -- `scp` is bound in stxQuot.expand `(Syntax.ident info $(quote rawVal) (addMacroScope mainModule $val scp) $(quote preresolved)) -- if antiquotation, insert contents as-is, else recurse | stx@(Syntax.node k _) => do if isAntiquot stx && !isEscapedAntiquot stx then getAntiquotTerm stx else if isTokenAntiquot stx && !isEscapedAntiquot stx then match stx[0] with | Syntax.atom _ val => `(Syntax.atom (Option.getD (getHeadInfo? $(getAntiquotTerm stx)) info) $(quote val)) | _ => throwErrorAt stx "expected token" else if isAntiquotSuffixSplice stx && !isEscapedAntiquot stx then -- splices must occur in a `many` node throwErrorAt stx "unexpected antiquotation splice" else if isAntiquotSplice stx && !isEscapedAntiquot stx then throwErrorAt stx "unexpected antiquotation splice" else -- if escaped antiquotation, decrement by one escape level let stx := unescapeAntiquot stx let mut args := ArrayStxBuilder.empty let appendName := if (← getEnv).contains ``Array.append then ``Array.append else ``Array.appendCore for arg in stx.getArgs do if k == nullKind && isAntiquotSuffixSplice arg then let antiquot := getAntiquotSuffixSpliceInner arg args := args.append (appendName := appendName) <| ← match antiquotSuffixSplice? arg with | `optional => `(match $(getAntiquotTerm antiquot):term with | some x => Array.empty.push x | none => Array.empty) | `many => getAntiquotTerm antiquot | `sepBy => `(@SepArray.elemsAndSeps $(getSepFromSplice arg) $(getAntiquotTerm antiquot)) | k => throwErrorAt arg "invalid antiquotation suffix splice kind '{k}'" else if k == nullKind && isAntiquotSplice arg then let k := antiquotSpliceKind? arg let (arg, bindLets) ← floatOutAntiquotTerms arg |>.run pure let inner ← (getAntiquotSpliceContents arg).mapM quoteSyntax let ids ← getAntiquotationIds arg if ids.isEmpty then throwErrorAt stx "antiquotation splice must contain at least one antiquotation" let arr ← match k with | `optional => `(match $[$ids:ident],* with | $[some $ids:ident],* => $(quote inner) | none => Array.empty) | _ => let arr ← ids[:ids.size-1].foldrM (fun id arr => `(Array.zip $id $arr)) ids.back `(Array.map (fun $(← mkTuple ids) => $(inner[0])) $arr) let arr ← if k == `sepBy then `(mkSepArray $arr (mkAtom $(getSepFromSplice arg))) else arr let arr ← bindLets arr args := args.append arr else do let arg ← quoteSyntax arg args := args.push arg `(Syntax.node $(quote k) $(args.build)) | Syntax.atom _ val => `(Syntax.atom info $(quote val)) | Syntax.missing => throwUnsupportedSyntax def stxQuot.expand (stx : Syntax) : TermElabM Syntax := do /- Syntax quotations are monadic values depending on the current macro scope. For efficiency, we bind the macro scope once for each quotation, then build the syntax tree in a completely pure computation depending on this binding. Note that regular function calls do not introduce a new macro scope (i.e. we preserve referential transparency), so we can refer to this same `scp` inside `quoteSyntax` by including it literally in a syntax quotation. -/ -- TODO: simplify to `(do scp ← getCurrMacroScope; pure $(quoteSyntax quoted)) let stx ← quoteSyntax stx.getQuotContent; `(Bind.bind MonadRef.mkInfoFromRefPos (fun info => Bind.bind getCurrMacroScope (fun scp => Bind.bind getMainModule (fun mainModule => Pure.pure $stx)))) /- NOTE: It may seem like the newly introduced binding `scp` may accidentally capture identifiers in an antiquotation introduced by `quoteSyntax`. However, note that the syntax quotation above enjoys the same hygiene guarantees as anywhere else in Lean; that is, we implement hygienic quotations by making use of the hygienic quotation support of the bootstrapped Lean compiler! Aside: While this might sound "dangerous", it is in fact less reliant on a "chain of trust" than other bootstrapping parts of Lean: because this implementation itself never uses `scp` (or any other identifier) both inside and outside quotations, it can actually correctly be compiled by an unhygienic (but otherwise correct) implementation of syntax quotations. As long as it is then compiled again with the resulting executable (i.e. up to stage 2), the result is a correct hygienic implementation. In this sense the implementation is "self-stabilizing". It was in fact originally compiled by an unhygienic prototype implementation. -/ macro "elab_stx_quot" kind:ident : command => `(@[builtinTermElab $kind:ident] def elabQuot : TermElab := adaptExpander stxQuot.expand) -- elab_stx_quot Parser.Level.quot elab_stx_quot Parser.Term.quot elab_stx_quot Parser.Term.funBinder.quot elab_stx_quot Parser.Term.bracketedBinder.quot elab_stx_quot Parser.Term.matchDiscr.quot elab_stx_quot Parser.Tactic.quot elab_stx_quot Parser.Tactic.quotSeq elab_stx_quot Parser.Term.stx.quot elab_stx_quot Parser.Term.prec.quot elab_stx_quot Parser.Term.attr.quot elab_stx_quot Parser.Term.prio.quot elab_stx_quot Parser.Term.doElem.quot elab_stx_quot Parser.Term.dynamicQuot /- match -/ -- an "alternative" of patterns plus right-hand side private abbrev Alt := List Syntax × Syntax /-- In a single match step, we match the first discriminant against the "head" of the first pattern of the first alternative. This datatype describes what kind of check this involves, which helps other patterns decide if they are covered by the same check and don't have to be checked again (see also `MatchResult`). -/ inductive HeadCheck where -- match step that always succeeds: _, x, `($x), ... | unconditional -- match step based on kind and, optionally, arity of discriminant -- If `arity` is given, that number of new discriminants is introduced. `covered` patterns should then introduce the -- same number of new patterns. -- We actually check the arity at run time only in the case of `null` nodes since it should otherwise by implied by -- the node kind. -- without arity: `($x:k) -- with arity: any quotation without an antiquotation head pattern | shape (k : SyntaxNodeKind) (arity : Option Nat) -- Match step that succeeds on `null` nodes of arity at least `numPrefix + numSuffix`, introducing discriminants -- for the first `numPrefix` children, one `null` node for those in between, and for the `numSuffix` last children. -- example: `([$x, $xs,*, $y]) is `slice 2 2` | slice (numPrefix numSuffix : Nat) -- other, complicated match step that will probably only cover identical patterns -- example: antiquotation splices `($[...]*) | other (pat : Syntax) open HeadCheck /-- Describe whether a pattern is covered by a head check (induced by the pattern itself or a different pattern). -/ inductive MatchResult where -- Pattern agrees with head check, remove and transform remaining alternative. -- If `exhaustive` is `false`, *also* include unchanged alternative in the "no" branch. | covered (f : Alt → TermElabM Alt) (exhaustive : Bool) -- Pattern disagrees with head check, include in "no" branch only | uncovered -- Pattern is not quite sure yet; include unchanged in both branches | undecided open MatchResult /-- All necessary information on a pattern head. -/ structure HeadInfo where -- check induced by the pattern check : HeadCheck -- compute compatibility of pattern with given head check onMatch (taken : HeadCheck) : MatchResult -- actually run the specified head check, with the discriminant bound to `discr` doMatch (yes : (newDiscrs : List Syntax) → TermElabM Syntax) (no : TermElabM Syntax) : TermElabM Syntax /-- Adapt alternatives that do not introduce new discriminants in `doMatch`, but are covered by those that do so. -/ private def noOpMatchAdaptPats : HeadCheck → Alt → Alt | shape k (some sz), (pats, rhs) => (List.replicate sz (Unhygienic.run `(_)) ++ pats, rhs) | slice p s, (pats, rhs) => (List.replicate (p + 1 + s) (Unhygienic.run `(_)) ++ pats, rhs) | _, alt => alt private def adaptRhs (fn : Syntax → TermElabM Syntax) : Alt → TermElabM Alt | (pats, rhs) => do (pats, ← fn rhs) private partial def getHeadInfo (alt : Alt) : TermElabM HeadInfo := let pat := alt.fst.head! let unconditionally (rhsFn) := pure { check := unconditional, doMatch := fun yes no => yes [], onMatch := fun taken => covered (adaptRhs rhsFn ∘ noOpMatchAdaptPats taken) (match taken with | unconditional => true | _ => false) } -- quotation pattern if isQuot pat then let quoted := getQuotContent pat if quoted.isAtom then -- We assume that atoms are uniquely determined by the node kind and never have to be checked unconditionally pure else if quoted.isTokenAntiquot then unconditionally (`(let $(quoted.getAntiquotTerm) := discr; $(·))) else if isAntiquot quoted && !isEscapedAntiquot quoted then -- quotation contains a single antiquotation let k := antiquotKind? quoted |>.get! match getAntiquotTerm quoted with | `(_) => unconditionally pure | `($id:ident) => -- Antiquotation kinds like `$id:ident` influence the parser, but also need to be considered by -- `match` (but not by quotation terms). For example, `($id:ident) and `($e) are not -- distinguishable without checking the kind of the node to be captured. Note that some -- antiquotations like the latter one for terms do not correspond to any actual node kind -- (signified by `k == Name.anonymous`), so we would only check for `ident` here. -- -- if stx.isOfKind `ident then -- let id := stx; let e := stx; ... -- else -- let e := stx; ... let rhsFn := (`(let $id := discr; $(·))) if k == Name.anonymous then unconditionally rhsFn else pure { check := shape k none, onMatch := fun | other _ => undecided | taken@(shape k' sz) => if k' == k then covered (adaptRhs rhsFn ∘ noOpMatchAdaptPats taken) (exhaustive := sz.isNone) else uncovered | _ => uncovered, doMatch := fun yes no => do `(cond (Syntax.isOfKind discr $(quote k)) $(← yes []) $(← no)), } | anti => throwErrorAt anti "unsupported antiquotation kind in pattern" else if isAntiquotSuffixSplice quoted then throwErrorAt quoted "unexpected antiquotation splice" else if isAntiquotSplice quoted then throwErrorAt quoted "unexpected antiquotation splice" else if quoted.getArgs.size == 1 && isAntiquotSuffixSplice quoted[0] then let anti := getAntiquotTerm (getAntiquotSuffixSpliceInner quoted[0]) unconditionally fun rhs => match antiquotSuffixSplice? quoted[0] with | `optional => `(let $anti := Syntax.getOptional? discr; $rhs) | `many => `(let $anti := Syntax.getArgs discr; $rhs) | `sepBy => `(let $anti := @SepArray.mk $(getSepFromSplice quoted[0]) (Syntax.getArgs discr); $rhs) | k => throwErrorAt quoted "invalid antiquotation suffix splice kind '{k}'" else if quoted.getArgs.size == 1 && isAntiquotSplice quoted[0] then pure { check := other pat, onMatch := fun | other pat' => if pat' == pat then covered pure (exhaustive := true) else undecided | _ => undecided, doMatch := fun yes no => do let splice := quoted[0] let k := antiquotSpliceKind? splice let contents := getAntiquotSpliceContents splice let ids ← getAntiquotationIds splice let yes ← yes [] let no ← no match k with | `optional => let nones := mkArray ids.size (← `(none)) `(let_delayed yes _ $ids* := $yes; if discr.isNone then yes () $[ $nones]* else match discr with | `($(mkNullNode contents)) => yes () $[ (some $ids)]* | _ => $no) | _ => let mut discrs ← `(Syntax.getArgs discr) if k == `sepBy then discrs ← `(Array.getSepElems $discrs) let tuple ← mkTuple ids let mut yes := yes let resId ← match ids with | #[id] => id | _ => for id in ids do yes ← `(let $id := tuples.map (fun $tuple => $id); $yes) `(tuples) let contents := if contents.size == 1 then contents[0] else mkNullNode contents `(match OptionM.run ($(discrs).sequenceMap fun | `($contents) => some $tuple | _ => none) with | some $resId => $yes | none => $no) } else if let some idx := quoted.getArgs.findIdx? (fun arg => isAntiquotSuffixSplice arg || isAntiquotSplice arg) then do /- pattern of the form `match discr, ... with | `(pat_0 ... pat_(idx-1) $[...]* pat_(idx+1) ...), ...` transform to ``` if discr.getNumArgs >= $quoted.getNumArgs - 1 then match discr[0], ..., discr[idx-1], mkNullNode (discr.getArgs.extract idx (discr.getNumArgs - $numSuffix))), ..., discr[quoted.getNumArgs - 1] with | `(pat_0), ... `(pat_(idx-1)), `($[...])*, `(pat_(idx+1)), ... ``` -/ let numSuffix := quoted.getNumArgs - 1 - idx pure { check := slice idx numSuffix onMatch := fun | other _ => undecided | slice p s => if p == idx && s == numSuffix then let argPats := quoted.getArgs.mapIdx fun i arg => let arg := if (i : Nat) == idx then mkNullNode #[arg] else arg Unhygienic.run `(`($(arg))) covered (fun (pats, rhs) => (argPats.toList ++ pats, rhs)) (exhaustive := true) else uncovered | _ => uncovered doMatch := fun yes no => do let prefixDiscrs ← (List.range idx).mapM (`(Syntax.getArg discr $(quote ·))) let sliceDiscr ← `(mkNullNode (discr.getArgs.extract $(quote idx) (discr.getNumArgs - $(quote numSuffix)))) let suffixDiscrs ← (List.range numSuffix).mapM fun i => `(Syntax.getArg discr (discr.getNumArgs - $(quote (numSuffix - i)))) `(ite (GE.ge discr.getNumArgs $(quote (quoted.getNumArgs - 1))) $(← yes (prefixDiscrs ++ sliceDiscr :: suffixDiscrs)) $(← no)) } else -- not an antiquotation, or an escaped antiquotation: match head shape let quoted := unescapeAntiquot quoted let kind := quoted.getKind let argPats := quoted.getArgs.map fun arg => Unhygienic.run `(`($(arg))) pure { check := if quoted.isIdent then -- identifiers only match identical identifiers -- NOTE: We could make this case more precise by including the matched identifier, -- if any, in the `shape` constructor, but matching on literal identifiers is quite -- rare. other quoted else shape kind argPats.size, onMatch := fun | other stx' => if quoted.isIdent && quoted == stx' then covered pure (exhaustive := true) else uncovered | shape k' sz => if k' == kind && sz == argPats.size then covered (fun (pats, rhs) => (argPats.toList ++ pats, rhs)) (exhaustive := true) else uncovered | _ => uncovered, doMatch := fun yes no => do let cond ← match kind with | `null => `(Syntax.matchesNull discr $(quote argPats.size)) | `ident => `(Syntax.matchesIdent discr $(quote quoted.getId)) | _ => `(Syntax.isOfKind discr $(quote kind)) let newDiscrs ← (List.range argPats.size).mapM fun i => `(Syntax.getArg discr $(quote i)) `(ite (Eq $cond true) $(← yes newDiscrs) $(← no)) } else match pat with | `(_) => unconditionally pure | `($id:ident) => unconditionally (`(let $id := discr; $(·))) | `($id:ident@$pat) => do let info ← getHeadInfo (pat::alt.1.tail!, alt.2) { info with onMatch := fun taken => match info.onMatch taken with | covered f exh => covered (fun alt => f alt >>= adaptRhs (`(let $id := discr; $(·)))) exh | r => r } | _ => throwErrorAt pat "match (syntax) : unexpected pattern kind {pat}" -- Bind right-hand side to new `let_delayed` decl in order to prevent code duplication private def deduplicate (floatedLetDecls : Array Syntax) : Alt → TermElabM (Array Syntax × Alt) -- NOTE: new macro scope so that introduced bindings do not collide | (pats, rhs) => do if let `($f:ident $[ $args:ident]*) := rhs then -- looks simple enough/created by this function, skip return (floatedLetDecls, (pats, rhs)) withFreshMacroScope do match (← getPatternsVars pats.toArray) with | #[] => -- no antiquotations => introduce Unit parameter to preserve evaluation order let rhs' ← `(rhs Unit.unit) (floatedLetDecls.push (← `(letDecl|rhs _ := $rhs)), (pats, rhs')) | vars => let rhs' ← `(rhs $vars*) (floatedLetDecls.push (← `(letDecl|rhs $vars:ident* := $rhs)), (pats, rhs')) private partial def compileStxMatch (discrs : List Syntax) (alts : List Alt) : TermElabM Syntax := do trace[Elab.match_syntax] "match {discrs} with {alts}" match discrs, alts with | [], ([], rhs)::_ => pure rhs -- nothing left to match | _, [] => logError "non-exhaustive 'match' (syntax)" pure Syntax.missing | discr::discrs, alt::alts => do let info ← getHeadInfo alt let pat := alt.1.head! let alts ← (alt::alts).mapM fun alt => do ((← getHeadInfo alt).onMatch info.check, alt) let mut yesAlts := #[] let mut undecidedAlts := #[] let mut nonExhaustiveAlts := #[] let mut floatedLetDecls := #[] for alt in alts do let mut alt := alt match alt with | (covered f exh, alt') => -- we can only factor out a common check if there are no undecided patterns in between; -- otherwise we would change the order of alternatives if undecidedAlts.isEmpty then yesAlts ← yesAlts.push <$> f (alt'.1.tail!, alt'.2) if !exh then nonExhaustiveAlts := nonExhaustiveAlts.push alt' else (floatedLetDecls, alt) ← deduplicate floatedLetDecls alt' undecidedAlts := undecidedAlts.push alt nonExhaustiveAlts := nonExhaustiveAlts.push alt | (undecided, alt') => (floatedLetDecls, alt) ← deduplicate floatedLetDecls alt' undecidedAlts := undecidedAlts.push alt nonExhaustiveAlts := nonExhaustiveAlts.push alt | (uncovered, alt') => nonExhaustiveAlts := nonExhaustiveAlts.push alt' let mut stx ← info.doMatch (yes := fun newDiscrs => do let mut yesAlts := yesAlts if !undecidedAlts.isEmpty then -- group undecided alternatives in a new default case `| discr2, ... => match discr, discr2, ... with ...` let vars ← discrs.mapM fun _ => withFreshMacroScope `(discr) let pats := List.replicate newDiscrs.length (Unhygienic.run `(_)) ++ vars let alts ← undecidedAlts.mapM fun alt => `(matchAltExpr| | $(alt.1.toArray),* => $(alt.2)) let rhs ← `(match discr, $[$(vars.toArray):term],* with $alts:matchAlt*) yesAlts := yesAlts.push (pats, rhs) withFreshMacroScope $ compileStxMatch (newDiscrs ++ discrs) yesAlts.toList) (no := withFreshMacroScope $ compileStxMatch (discr::discrs) nonExhaustiveAlts.toList) for d in floatedLetDecls do stx ← `(let_delayed $d:letDecl; $stx) `(let discr := $discr; $stx) | _, _ => unreachable! def match_syntax.expand (stx : Syntax) : TermElabM Syntax := do match stx with | `(match $[$discrs:term],* with $[| $[$patss],* => $rhss]*) => do if !patss.any (·.any (fun | `($id@$pat) => pat.isQuot | pat => pat.isQuot)) then -- no quotations => fall back to regular `match` throwUnsupportedSyntax let stx ← compileStxMatch discrs.toList (patss.map (·.toList) |>.zip rhss).toList trace[Elab.match_syntax.result] "{stx}" stx | _ => throwUnsupportedSyntax @[builtinTermElab «match»] def elabMatchSyntax : TermElab := adaptExpander match_syntax.expand builtin_initialize registerTraceClass `Elab.match_syntax registerTraceClass `Elab.match_syntax.result end Lean.Elab.Term.Quotation
e32f65507ba5d081d9ee0ac21e23850a49f445d2
618003631150032a5676f229d13a079ac875ff77
/src/linear_algebra/determinant.lean
346637ba3956eee4d21a17051eaeaeece33dea1c
[ "Apache-2.0" ]
permissive
awainverse/mathlib
939b68c8486df66cfda64d327ad3d9165248c777
ea76bd8f3ca0a8bf0a166a06a475b10663dec44a
refs/heads/master
1,659,592,962,036
1,590,987,592,000
1,590,987,592,000
268,436,019
1
0
Apache-2.0
1,590,990,500,000
1,590,990,500,000
null
UTF-8
Lean
false
false
8,683
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, Tim Baanen -/ import data.matrix.pequiv import data.fintype.card import group_theory.perm.sign universes u v open equiv equiv.perm finset function namespace matrix open_locale matrix variables {n : Type u} [fintype n] [decidable_eq n] {R : Type v} [comm_ring R] local notation `ε` σ:max := ((sign σ : ℤ ) : R) /-- The determinant of a matrix given by the Leibniz formula. -/ 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_eq_one_of_card_eq_zero {A : matrix n n R} (h : fintype.card n = 0) : det A = 1 := begin have perm_eq : (univ : finset (perm n)) = {1} := univ_eq_singleton_of_card_one (1 : perm n) (by simp [card_univ, fintype.card_perm, h]), simp [det, card_eq_zero.mp h, perm_eq], end 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 := begin obtain ⟨i, j, hpij, hij⟩ : ∃ i j, p i = p j ∧ i ≠ j, { rw [← fintype.injective_iff_bijective, injective] at H, push_neg at H, exact H }, exact 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, prod_mul_distrib]) (λ σ _ _ h, hij (σ.injective $ by conv {to_lhs, rw ← h}; simp)) (λ _ _, mem_univ _) (λ _ _, equiv.ext $ by simp) end @[simp] lemma det_mul (M N : matrix n n R) : det (M ⬝ N) = det M * det N := calc det (M ⬝ N) = univ.sum (λ p : n → n, univ.sum (λ σ : perm n, ε σ * univ.prod (λ i, M (σ i) (p i) * N (p i) i))) : by simp only [det, mul_val, prod_univ_sum, mul_sum, fintype.pi_finset_univ]; rw [finset.sum_comm] ... = ((@univ (n → n) _).filter bijective).sum (λ p : n → n, univ.sum (λ σ : perm n, ε σ * univ.prod (λ i, M (σ i) (p i) * N (p i) i))) : eq.symm $ sum_subset (filter_subset _) (λ f _ hbij, det_mul_aux $ by simpa using hbij) ... = (@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⟩, coe_fn_injective 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 ← finset.prod_equiv σ⁻¹; 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_left_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 } /-- Transposing a matrix preserves the determinant. -/ @[simp] lemma det_transpose (M : matrix n n R) : Mᵀ.det = M.det := begin apply sum_bij (λ σ _, σ⁻¹), { intros σ _, apply mem_univ }, { intros σ _, rw [sign_inv], congr' 1, apply prod_bij (λ i _, σ i), { intros i _, apply mem_univ }, { intros i _, simp }, { intros i j _ _ h, simp at h, assumption }, { intros i _, use σ⁻¹ i, finish } }, { intros σ σ' _ _ h, simp at h, assumption }, { intros σ _, use σ⁻¹, finish } end /-- The determinant of a permutation matrix equals its sign. -/ @[simp] lemma det_permutation (σ : perm n) : matrix.det (σ.to_pequiv.to_matrix : matrix n n R) = σ.sign := begin suffices : matrix.det (σ.to_pequiv.to_matrix) = ↑σ.sign * det (1 : matrix n n R), { simp [this] }, unfold det, rw mul_sum, apply sum_bij (λ τ _, σ * τ), { intros τ _, apply mem_univ }, { intros τ _, conv_lhs { rw [←one_mul (sign τ), ←int.units_pow_two (sign σ)] }, conv_rhs { rw [←mul_assoc, coe_coe, sign_mul, units.coe_mul, int.cast_mul, ←mul_assoc] }, congr, { simp [pow_two] }, { ext i, apply pequiv.equiv_to_pequiv_to_matrix } }, { intros τ τ' _ _, exact (mul_right_inj σ).mp }, { intros τ _, use σ⁻¹ * τ, use (mem_univ _), exact (mul_inv_cancel_left _ _).symm } end /-- Permuting the columns changes the sign of the determinant. -/ lemma det_permute (σ : perm n) (M : matrix n n R) : matrix.det (λ i, M (σ i)) = σ.sign * M.det := by rw [←det_permutation, ←det_mul, pequiv.to_pequiv_mul_matrix] @[simp] lemma det_smul {A : matrix n n R} {c : R} : det (c • A) = c ^ fintype.card n * det A := calc det (c • A) = det (matrix.mul (diagonal (λ _, c)) A) : by rw [smul_eq_diagonal_mul] ... = det (diagonal (λ _, c)) * det A : det_mul _ _ ... = c ^ fintype.card n * det A : by simp [card_univ] section det_zero /-! ### `det_zero` section Prove that a matrix with a repeated column has determinant equal to zero. -/ lemma det_eq_zero_of_column_eq_zero {A : matrix n n R} (i : n) (h : ∀ j, A i j = 0) : det A = 0 := begin rw [←det_transpose, det], convert @sum_const_zero _ _ (univ : finset (perm n)) _, ext σ, convert mul_zero ↑(sign σ), apply prod_eq_zero (mem_univ i), rw [transpose_val], apply h end /-- `mod_swap i j` contains permutations up to swapping `i` and `j`. We use this to partition permutations in the expression for the determinant, such that each partitions sums up to `0`. -/ def mod_swap {n : Type u} [decidable_eq n] (i j : n) : setoid (perm n) := ⟨ λ σ τ, σ = τ ∨ σ = swap i j * τ, λ σ, or.inl (refl σ), λ σ τ h, or.cases_on h (λ h, or.inl h.symm) (λ h, or.inr (by rw [h, swap_mul_self_mul])), λ σ τ υ hστ hτυ, by cases hστ; cases hτυ; try {rw [hστ, hτυ, swap_mul_self_mul]}; finish⟩ instance (i j : n) : decidable_rel (mod_swap i j).r := λ σ τ, or.decidable variables {M : matrix n n R} {i j : n} /-- If a matrix has a repeated column, the determinant will be zero. -/ theorem det_zero_of_column_eq (i_ne_j : i ≠ j) (hij : M i = M j) : M.det = 0 := begin have swap_invariant : ∀ k, M (swap i j k) = M k, { intros k, rw [swap_apply_def], by_cases k = i, { rw [if_pos h, h, ←hij] }, rw [if_neg h], by_cases k = j, { rw [if_pos h, h, hij] }, rw [if_neg h] }, have : ∀ σ, _root_.disjoint {σ} {swap i j * σ}, { intros σ, rw [disjoint_singleton, mem_singleton], exact (not_congr swap_mul_eq_iff).mpr i_ne_j }, apply finset.sum_cancels_of_partition_cancels (mod_swap i j), intros σ _, erw [filter_or, filter_eq', filter_eq', if_pos (mem_univ σ), if_pos (mem_univ (swap i j * σ)), sum_union (this σ), sum_singleton, sum_singleton], convert add_right_neg (↑↑(sign σ) * finset.prod univ (λ (i : n), M (σ i) i)), rw [neg_mul_eq_neg_mul], congr, { rw [sign_mul, sign_swap i_ne_j], norm_num }, ext j, rw [mul_apply, swap_invariant] end end det_zero end matrix
2e27ca29df035a7de18d7da2f1975bae93c6b07f
94e33a31faa76775069b071adea97e86e218a8ee
/src/order/lattice.lean
07c656f08933bed926a4664584fc0359b490df69
[ "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
41,560
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 order.monotone import order.rel_classes import tactic.simps import tactic.pi_instances /-! # (Semi-)lattices Semilattices are partially ordered sets with join (greatest lower bound, or `sup`) or meet (least upper bound, or `inf`) operations. Lattices are posets that are both join-semilattices and meet-semilattices. Distributive lattices are lattices which satisfy any of four equivalent distributivity properties, of `sup` over `inf`, on the left or on the right. ## Main declarations * `semilattice_sup`: a type class for join semilattices * `semilattice_sup.mk'`: an alternative constructor for `semilattice_sup` via proofs that `⊔` is commutative, associative and idempotent. * `semilattice_inf`: a type class for meet semilattices * `semilattice_sup.mk'`: an alternative constructor for `semilattice_inf` via proofs that `⊓` is commutative, associative and idempotent. * `lattice`: a type class for lattices * `lattice.mk'`: an alternative constructor for `lattice` via profs that `⊔` and `⊓` are commutative, associative and satisfy a pair of "absorption laws". * `distrib_lattice`: a type class for distributive lattices. ## Notations * `a ⊔ b`: the supremum or join of `a` and `b` * `a ⊓ b`: the infimum or meet of `a` and `b` ## TODO * (Semi-)lattice homomorphisms * Alternative constructors for distributive lattices from the other distributive properties ## Tags semilattice, lattice -/ set_option old_structure_cmd true universes u v w variables {α : Type u} {β : Type v} -- TODO: move this eventually, if we decide to use them attribute [ematch] le_trans lt_of_le_of_lt lt_of_lt_of_le lt_trans section -- TODO: this seems crazy, but it also seems to work reasonably well @[ematch] theorem le_antisymm' [partial_order α] : ∀ {a b : α}, (: a ≤ b :) → b ≤ a → a = b := @le_antisymm _ _ end /- TODO: automatic construction of dual definitions / theorems -/ /-! ### Join-semilattices -/ /-- A `semilattice_sup` is a join-semilattice, that is, a partial order with a join (a.k.a. lub / least upper bound, sup / supremum) operation `⊔` which is the least element larger than both factors. -/ class semilattice_sup (α : Type u) extends has_sup α, partial_order α := (le_sup_left : ∀ a b : α, a ≤ a ⊔ b) (le_sup_right : ∀ a b : α, b ≤ a ⊔ b) (sup_le : ∀ a b c : α, a ≤ c → b ≤ c → a ⊔ b ≤ c) /-- A type with a commutative, associative and idempotent binary `sup` operation has the structure of a join-semilattice. The partial order is defined so that `a ≤ b` unfolds to `a ⊔ b = b`; cf. `sup_eq_right`. -/ def semilattice_sup.mk' {α : Type*} [has_sup α] (sup_comm : ∀ (a b : α), a ⊔ b = b ⊔ a) (sup_assoc : ∀ (a b c : α), a ⊔ b ⊔ c = a ⊔ (b ⊔ c)) (sup_idem : ∀ (a : α), a ⊔ a = a) : semilattice_sup α := { sup := (⊔), le := λ a b, a ⊔ b = b, le_refl := sup_idem, le_trans := λ a b c hab hbc, begin dsimp only [(≤)] at *, rwa [←hbc, ←sup_assoc, hab], end, le_antisymm := λ a b hab hba, begin dsimp only [(≤)] at *, rwa [←hba, sup_comm], end, le_sup_left := λ a b, show a ⊔ (a ⊔ b) = (a ⊔ b), by rw [←sup_assoc, sup_idem], le_sup_right := λ a b, show b ⊔ (a ⊔ b) = (a ⊔ b), by rw [sup_comm, sup_assoc, sup_idem], sup_le := λ a b c hac hbc, begin dsimp only [(≤), preorder.le] at *, rwa [sup_assoc, hbc], end } instance (α : Type*) [has_inf α] : has_sup αᵒᵈ := ⟨((⊓) : α → α → α)⟩ instance (α : Type*) [has_sup α] : has_inf αᵒᵈ := ⟨((⊔) : α → α → α)⟩ section semilattice_sup variables [semilattice_sup α] {a b c d : α} @[simp] theorem le_sup_left : a ≤ a ⊔ b := semilattice_sup.le_sup_left a b @[ematch] theorem le_sup_left' : a ≤ (: a ⊔ b :) := le_sup_left @[simp] theorem le_sup_right : b ≤ a ⊔ b := semilattice_sup.le_sup_right a b @[ematch] theorem le_sup_right' : b ≤ (: a ⊔ b :) := le_sup_right theorem le_sup_of_le_left (h : c ≤ a) : c ≤ a ⊔ b := le_trans h le_sup_left theorem le_sup_of_le_right (h : c ≤ b) : c ≤ a ⊔ b := le_trans h le_sup_right theorem lt_sup_of_lt_left (h : c < a) : c < a ⊔ b := h.trans_le le_sup_left theorem lt_sup_of_lt_right (h : c < b) : c < a ⊔ b := h.trans_le le_sup_right theorem sup_le : a ≤ c → b ≤ c → a ⊔ b ≤ c := semilattice_sup.sup_le a b c @[simp] theorem sup_le_iff : a ⊔ b ≤ c ↔ a ≤ c ∧ b ≤ c := ⟨assume h : a ⊔ b ≤ c, ⟨le_trans le_sup_left h, le_trans le_sup_right h⟩, assume ⟨h₁, h₂⟩, sup_le h₁ h₂⟩ @[simp] theorem sup_eq_left : a ⊔ b = a ↔ b ≤ a := le_antisymm_iff.trans $ by simp [le_refl] theorem sup_of_le_left (h : b ≤ a) : a ⊔ b = a := sup_eq_left.2 h @[simp] theorem left_eq_sup : a = a ⊔ b ↔ b ≤ a := eq_comm.trans sup_eq_left @[simp] theorem left_lt_sup : a < a ⊔ b ↔ ¬b ≤ a := le_sup_left.lt_iff_ne.trans $ not_congr left_eq_sup @[simp] theorem sup_eq_right : a ⊔ b = b ↔ a ≤ b := le_antisymm_iff.trans $ by simp [le_refl] theorem sup_of_le_right (h : a ≤ b) : a ⊔ b = b := sup_eq_right.2 h @[simp] theorem right_eq_sup : b = a ⊔ b ↔ a ≤ b := eq_comm.trans sup_eq_right @[simp] theorem right_lt_sup : b < a ⊔ b ↔ ¬a ≤ b := le_sup_right.lt_iff_ne.trans $ not_congr right_eq_sup lemma left_or_right_lt_sup (h : a ≠ b) : (a < a ⊔ b ∨ b < a ⊔ b) := h.not_le_or_not_le.symm.imp left_lt_sup.2 right_lt_sup.2 theorem le_iff_exists_sup : a ≤ b ↔ ∃ c, b = a ⊔ c := begin split, { intro h, exact ⟨b, (sup_eq_right.mpr h).symm⟩ }, { rintro ⟨c, (rfl : _ = _ ⊔ _)⟩, exact le_sup_left } end theorem sup_le_sup (h₁ : a ≤ b) (h₂ : c ≤ d) : a ⊔ c ≤ b ⊔ d := sup_le (le_sup_of_le_left h₁) (le_sup_of_le_right h₂) theorem sup_le_sup_left (h₁ : a ≤ b) (c) : c ⊔ a ≤ c ⊔ b := sup_le_sup le_rfl h₁ theorem sup_le_sup_right (h₁ : a ≤ b) (c) : a ⊔ c ≤ b ⊔ c := sup_le_sup h₁ le_rfl theorem le_of_sup_eq (h : a ⊔ b = b) : a ≤ b := by { rw ← h, simp } @[simp] theorem sup_idem : a ⊔ a = a := by apply le_antisymm; simp instance sup_is_idempotent : is_idempotent α (⊔) := ⟨@sup_idem _ _⟩ theorem sup_comm : a ⊔ b = b ⊔ a := by apply le_antisymm; simp instance sup_is_commutative : is_commutative α (⊔) := ⟨@sup_comm _ _⟩ theorem sup_assoc : a ⊔ b ⊔ c = a ⊔ (b ⊔ c) := eq_of_forall_ge_iff $ λ x, by simp only [sup_le_iff, and_assoc] instance sup_is_associative : is_associative α (⊔) := ⟨@sup_assoc _ _⟩ lemma sup_left_right_swap (a b c : α) : a ⊔ b ⊔ c = c ⊔ b ⊔ a := by rw [sup_comm, @sup_comm _ _ a, sup_assoc] @[simp] lemma sup_left_idem : a ⊔ (a ⊔ b) = a ⊔ b := by rw [← sup_assoc, sup_idem] @[simp] lemma sup_right_idem : (a ⊔ b) ⊔ b = a ⊔ b := by rw [sup_assoc, sup_idem] lemma sup_left_comm (a b c : α) : a ⊔ (b ⊔ c) = b ⊔ (a ⊔ c) := by rw [← sup_assoc, ← sup_assoc, @sup_comm α _ a] lemma sup_right_comm (a b c : α) : a ⊔ b ⊔ c = a ⊔ c ⊔ b := by rw [sup_assoc, sup_assoc, @sup_comm _ _ b] lemma sup_sup_sup_comm (a b c d : α) : a ⊔ b ⊔ (c ⊔ d) = a ⊔ c ⊔ (b ⊔ d) := by rw [sup_assoc, sup_left_comm b, ←sup_assoc] lemma sup_sup_distrib_left (a b c : α) : a ⊔ (b ⊔ c) = (a ⊔ b) ⊔ (a ⊔ c) := by rw [sup_sup_sup_comm, sup_idem] lemma sup_sup_distrib_right (a b c : α) : (a ⊔ b) ⊔ c = (a ⊔ c) ⊔ (b ⊔ c) := by rw [sup_sup_sup_comm, sup_idem] lemma sup_eq_sup_of_le_of_le (h1 : a ≤ b ⊔ c) (h2 : b ≤ a ⊔ c) : a ⊔ c = b ⊔ c := (sup_le h1 le_sup_right).antisymm (sup_le h2 le_sup_right) lemma sup_eq_sup_iff_le_le : a ⊔ c = b ⊔ c ↔ a ≤ b ⊔ c ∧ b ≤ a ⊔ c := ⟨λ h, ⟨h ▸ le_sup_left, h.symm ▸ le_sup_left⟩, λ h, sup_eq_sup_of_le_of_le h.1 h.2⟩ /-- If `f` is monotone, `g` is antitone, and `f ≤ g`, then for all `a`, `b` we have `f a ≤ g b`. -/ theorem monotone.forall_le_of_antitone {β : Type*} [preorder β] {f g : α → β} (hf : monotone f) (hg : antitone g) (h : f ≤ g) (m n : α) : f m ≤ g n := calc f m ≤ f (m ⊔ n) : hf le_sup_left ... ≤ g (m ⊔ n) : h _ ... ≤ g n : hg le_sup_right theorem semilattice_sup.ext_sup {α} {A B : semilattice_sup α} (H : ∀ x y : α, (by haveI := A; exact x ≤ y) ↔ x ≤ y) (x y : α) : (by haveI := A; exact (x ⊔ y)) = x ⊔ y := eq_of_forall_ge_iff $ λ c, by simp only [sup_le_iff]; rw [← H, @sup_le_iff α A, H, H] theorem semilattice_sup.ext {α} {A B : semilattice_sup α} (H : ∀ x y : α, (by haveI := A; exact x ≤ y) ↔ x ≤ y) : A = B := begin have := partial_order.ext H, have ss := funext (λ x, funext $ semilattice_sup.ext_sup H x), casesI A, casesI B, injection this; congr' end lemma ite_le_sup (s s' : α) (P : Prop) [decidable P] : ite P s s' ≤ s ⊔ s' := if h : P then (if_pos h).trans_le le_sup_left else (if_neg h).trans_le le_sup_right end semilattice_sup /-! ### Meet-semilattices -/ /-- A `semilattice_inf` is a meet-semilattice, that is, a partial order with a meet (a.k.a. glb / greatest lower bound, inf / infimum) operation `⊓` which is the greatest element smaller than both factors. -/ class semilattice_inf (α : Type u) extends has_inf α, partial_order α := (inf_le_left : ∀ a b : α, a ⊓ b ≤ a) (inf_le_right : ∀ a b : α, a ⊓ b ≤ b) (le_inf : ∀ a b c : α, a ≤ b → a ≤ c → a ≤ b ⊓ c) instance (α) [semilattice_inf α] : semilattice_sup αᵒᵈ := { le_sup_left := semilattice_inf.inf_le_left, le_sup_right := semilattice_inf.inf_le_right, sup_le := assume a b c hca hcb, @semilattice_inf.le_inf α _ _ _ _ hca hcb, .. order_dual.partial_order α, .. order_dual.has_sup α } instance (α) [semilattice_sup α] : semilattice_inf αᵒᵈ := { inf_le_left := @le_sup_left α _, inf_le_right := @le_sup_right α _, le_inf := assume a b c hca hcb, @sup_le α _ _ _ _ hca hcb, .. order_dual.partial_order α, .. order_dual.has_inf α } theorem semilattice_sup.dual_dual (α : Type*) [H : semilattice_sup α] : order_dual.semilattice_sup αᵒᵈ = H := semilattice_sup.ext $ λ _ _, iff.rfl section semilattice_inf variables [semilattice_inf α] {a b c d : α} @[simp] theorem inf_le_left : a ⊓ b ≤ a := semilattice_inf.inf_le_left a b @[ematch] theorem inf_le_left' : (: a ⊓ b :) ≤ a := semilattice_inf.inf_le_left a b @[simp] theorem inf_le_right : a ⊓ b ≤ b := semilattice_inf.inf_le_right a b @[ematch] theorem inf_le_right' : (: a ⊓ b :) ≤ b := semilattice_inf.inf_le_right a b theorem le_inf : a ≤ b → a ≤ c → a ≤ b ⊓ c := semilattice_inf.le_inf a b c theorem inf_le_of_left_le (h : a ≤ c) : a ⊓ b ≤ c := le_trans inf_le_left h theorem inf_le_of_right_le (h : b ≤ c) : a ⊓ b ≤ c := le_trans inf_le_right h theorem inf_lt_of_left_lt (h : a < c) : a ⊓ b < c := lt_of_le_of_lt inf_le_left h theorem inf_lt_of_right_lt (h : b < c) : a ⊓ b < c := lt_of_le_of_lt inf_le_right h @[simp] theorem le_inf_iff : a ≤ b ⊓ c ↔ a ≤ b ∧ a ≤ c := @sup_le_iff αᵒᵈ _ _ _ _ @[simp] theorem inf_eq_left : a ⊓ b = a ↔ a ≤ b := le_antisymm_iff.trans $ by simp [le_refl] @[simp] theorem inf_lt_left : a ⊓ b < a ↔ ¬a ≤ b := @left_lt_sup αᵒᵈ _ _ _ theorem inf_of_le_left (h : a ≤ b) : a ⊓ b = a := inf_eq_left.2 h @[simp] theorem left_eq_inf : a = a ⊓ b ↔ a ≤ b := eq_comm.trans inf_eq_left @[simp] theorem inf_eq_right : a ⊓ b = b ↔ b ≤ a := le_antisymm_iff.trans $ by simp [le_refl] @[simp] theorem inf_lt_right : a ⊓ b < b ↔ ¬b ≤ a := @right_lt_sup αᵒᵈ _ _ _ theorem inf_lt_left_or_right (h : a ≠ b) : a ⊓ b < a ∨ a ⊓ b < b := @left_or_right_lt_sup αᵒᵈ _ _ _ h theorem inf_of_le_right (h : b ≤ a) : a ⊓ b = b := inf_eq_right.2 h @[simp] theorem right_eq_inf : b = a ⊓ b ↔ b ≤ a := eq_comm.trans inf_eq_right theorem inf_le_inf (h₁ : a ≤ b) (h₂ : c ≤ d) : a ⊓ c ≤ b ⊓ d := @sup_le_sup αᵒᵈ _ _ _ _ _ h₁ h₂ lemma inf_le_inf_right (a : α) {b c : α} (h : b ≤ c) : b ⊓ a ≤ c ⊓ a := inf_le_inf h le_rfl lemma inf_le_inf_left (a : α) {b c : α} (h : b ≤ c) : a ⊓ b ≤ a ⊓ c := inf_le_inf le_rfl h theorem le_of_inf_eq (h : a ⊓ b = a) : a ≤ b := inf_eq_left.1 h @[simp] lemma inf_idem : a ⊓ a = a := @sup_idem αᵒᵈ _ _ instance inf_is_idempotent : is_idempotent α (⊓) := ⟨@inf_idem _ _⟩ lemma inf_comm : a ⊓ b = b ⊓ a := @sup_comm αᵒᵈ _ _ _ instance inf_is_commutative : is_commutative α (⊓) := ⟨@inf_comm _ _⟩ lemma inf_assoc : a ⊓ b ⊓ c = a ⊓ (b ⊓ c) := @sup_assoc αᵒᵈ _ a b c instance inf_is_associative : is_associative α (⊓) := ⟨@inf_assoc _ _⟩ lemma inf_left_right_swap (a b c : α) : a ⊓ b ⊓ c = c ⊓ b ⊓ a := @sup_left_right_swap αᵒᵈ _ _ _ _ @[simp] lemma inf_left_idem : a ⊓ (a ⊓ b) = a ⊓ b := @sup_left_idem αᵒᵈ _ a b @[simp] lemma inf_right_idem : (a ⊓ b) ⊓ b = a ⊓ b := @sup_right_idem αᵒᵈ _ a b lemma inf_left_comm (a b c : α) : a ⊓ (b ⊓ c) = b ⊓ (a ⊓ c) := @sup_left_comm αᵒᵈ _ a b c lemma inf_right_comm (a b c : α) : a ⊓ b ⊓ c = a ⊓ c ⊓ b := @sup_right_comm αᵒᵈ _ a b c lemma inf_inf_inf_comm (a b c d : α) : a ⊓ b ⊓ (c ⊓ d) = a ⊓ c ⊓ (b ⊓ d) := @sup_sup_sup_comm αᵒᵈ _ _ _ _ _ lemma inf_inf_distrib_left (a b c : α) : a ⊓ (b ⊓ c) = (a ⊓ b) ⊓ (a ⊓ c) := @sup_sup_distrib_left αᵒᵈ _ _ _ _ lemma inf_inf_distrib_right (a b c : α) : (a ⊓ b) ⊓ c = (a ⊓ c) ⊓ (b ⊓ c) := @sup_sup_distrib_right αᵒᵈ _ _ _ _ lemma inf_eq_inf_of_le_of_le (h1 : b ⊓ c ≤ a) (h2 : a ⊓ c ≤ b) : a ⊓ c = b ⊓ c := @sup_eq_sup_of_le_of_le αᵒᵈ _ _ _ _ h1 h2 lemma inf_eq_inf_iff_le_le : a ⊓ c = b ⊓ c ↔ b ⊓ c ≤ a ∧ a ⊓ c ≤ b := @sup_eq_sup_iff_le_le αᵒᵈ _ _ _ _ theorem semilattice_inf.ext_inf {α} {A B : semilattice_inf α} (H : ∀ x y : α, (by haveI := A; exact x ≤ y) ↔ x ≤ y) (x y : α) : (by haveI := A; exact (x ⊓ y)) = x ⊓ y := eq_of_forall_le_iff $ λ c, by simp only [le_inf_iff]; rw [← H, @le_inf_iff α A, H, H] theorem semilattice_inf.ext {α} {A B : semilattice_inf α} (H : ∀ x y : α, (by haveI := A; exact x ≤ y) ↔ x ≤ y) : A = B := begin have := partial_order.ext H, have ss := funext (λ x, funext $ semilattice_inf.ext_inf H x), casesI A, casesI B, injection this; congr' end theorem semilattice_inf.dual_dual (α : Type*) [H : semilattice_inf α] : order_dual.semilattice_inf αᵒᵈ = H := semilattice_inf.ext $ λ _ _, iff.rfl lemma inf_le_ite (s s' : α) (P : Prop) [decidable P] : s ⊓ s' ≤ ite P s s' := @ite_le_sup αᵒᵈ _ _ _ _ _ end semilattice_inf /-- A type with a commutative, associative and idempotent binary `inf` operation has the structure of a meet-semilattice. The partial order is defined so that `a ≤ b` unfolds to `b ⊓ a = a`; cf. `inf_eq_right`. -/ def semilattice_inf.mk' {α : Type*} [has_inf α] (inf_comm : ∀ (a b : α), a ⊓ b = b ⊓ a) (inf_assoc : ∀ (a b c : α), a ⊓ b ⊓ c = a ⊓ (b ⊓ c)) (inf_idem : ∀ (a : α), a ⊓ a = a) : semilattice_inf α := begin haveI : semilattice_sup αᵒᵈ := semilattice_sup.mk' inf_comm inf_assoc inf_idem, haveI i := order_dual.semilattice_inf αᵒᵈ, exact i, end /-! ### Lattices -/ /-- A lattice is a join-semilattice which is also a meet-semilattice. -/ @[protect_proj] class lattice (α : Type u) extends semilattice_sup α, semilattice_inf α instance (α) [lattice α] : lattice αᵒᵈ := { .. order_dual.semilattice_sup α, .. order_dual.semilattice_inf α } /-- The partial orders from `semilattice_sup_mk'` and `semilattice_inf_mk'` agree if `sup` and `inf` satisfy the lattice absorption laws `sup_inf_self` (`a ⊔ a ⊓ b = a`) and `inf_sup_self` (`a ⊓ (a ⊔ b) = a`). -/ lemma semilattice_sup_mk'_partial_order_eq_semilattice_inf_mk'_partial_order {α : Type*} [has_sup α] [has_inf α] (sup_comm : ∀ (a b : α), a ⊔ b = b ⊔ a) (sup_assoc : ∀ (a b c : α), a ⊔ b ⊔ c = a ⊔ (b ⊔ c)) (sup_idem : ∀ (a : α), a ⊔ a = a) (inf_comm : ∀ (a b : α), a ⊓ b = b ⊓ a) (inf_assoc : ∀ (a b c : α), a ⊓ b ⊓ c = a ⊓ (b ⊓ c)) (inf_idem : ∀ (a : α), a ⊓ a = a) (sup_inf_self : ∀ (a b : α), a ⊔ a ⊓ b = a) (inf_sup_self : ∀ (a b : α), a ⊓ (a ⊔ b) = a) : @semilattice_sup.to_partial_order _ (semilattice_sup.mk' sup_comm sup_assoc sup_idem) = @semilattice_inf.to_partial_order _ (semilattice_inf.mk' inf_comm inf_assoc inf_idem) := partial_order.ext $ λ a b, show a ⊔ b = b ↔ b ⊓ a = a, from ⟨λ h, by rw [←h, inf_comm, inf_sup_self], λ h, by rw [←h, sup_comm, sup_inf_self]⟩ /-- A type with a pair of commutative and associative binary operations which satisfy two absorption laws relating the two operations has the structure of a lattice. The partial order is defined so that `a ≤ b` unfolds to `a ⊔ b = b`; cf. `sup_eq_right`. -/ def lattice.mk' {α : Type*} [has_sup α] [has_inf α] (sup_comm : ∀ (a b : α), a ⊔ b = b ⊔ a) (sup_assoc : ∀ (a b c : α), a ⊔ b ⊔ c = a ⊔ (b ⊔ c)) (inf_comm : ∀ (a b : α), a ⊓ b = b ⊓ a) (inf_assoc : ∀ (a b c : α), a ⊓ b ⊓ c = a ⊓ (b ⊓ c)) (sup_inf_self : ∀ (a b : α), a ⊔ a ⊓ b = a) (inf_sup_self : ∀ (a b : α), a ⊓ (a ⊔ b) = a) : lattice α := have sup_idem : ∀ (b : α), b ⊔ b = b := λ b, calc b ⊔ b = b ⊔ b ⊓ (b ⊔ b) : by rw inf_sup_self ... = b : by rw sup_inf_self, have inf_idem : ∀ (b : α), b ⊓ b = b := λ b, calc b ⊓ b = b ⊓ (b ⊔ b ⊓ b) : by rw sup_inf_self ... = b : by rw inf_sup_self, let semilatt_inf_inst := semilattice_inf.mk' inf_comm inf_assoc inf_idem, semilatt_sup_inst := semilattice_sup.mk' sup_comm sup_assoc sup_idem, -- here we help Lean to see that the two partial orders are equal partial_order_inst := @semilattice_sup.to_partial_order _ semilatt_sup_inst in have partial_order_eq : partial_order_inst = @semilattice_inf.to_partial_order _ semilatt_inf_inst := semilattice_sup_mk'_partial_order_eq_semilattice_inf_mk'_partial_order _ _ _ _ _ _ sup_inf_self inf_sup_self, { inf_le_left := λ a b, by { rw partial_order_eq, apply inf_le_left }, inf_le_right := λ a b, by { rw partial_order_eq, apply inf_le_right }, le_inf := λ a b c, by { rw partial_order_eq, apply le_inf }, ..partial_order_inst, ..semilatt_sup_inst, ..semilatt_inf_inst, } section lattice variables [lattice α] {a b c d : α} lemma inf_le_sup : a ⊓ b ≤ a ⊔ b := inf_le_left.trans le_sup_left @[simp] lemma inf_lt_sup : a ⊓ b < a ⊔ b ↔ a ≠ b := begin split, { rintro H rfl, simpa using H }, { refine λ Hne, lt_iff_le_and_ne.2 ⟨inf_le_sup, λ Heq, Hne _⟩, refine le_antisymm _ _, exacts [le_sup_left.trans (Heq.symm.trans_le inf_le_right), le_sup_right.trans (Heq.symm.trans_le inf_le_left)] } end /-! #### Distributivity laws -/ /- TODO: better names? -/ theorem sup_inf_le : a ⊔ (b ⊓ c) ≤ (a ⊔ b) ⊓ (a ⊔ c) := le_inf (sup_le_sup_left inf_le_left _) (sup_le_sup_left inf_le_right _) theorem le_inf_sup : (a ⊓ b) ⊔ (a ⊓ c) ≤ a ⊓ (b ⊔ c) := sup_le (inf_le_inf_left _ le_sup_left) (inf_le_inf_left _ le_sup_right) theorem inf_sup_self : a ⊓ (a ⊔ b) = a := by simp theorem sup_inf_self : a ⊔ (a ⊓ b) = a := by simp theorem sup_eq_iff_inf_eq : a ⊔ b = b ↔ a ⊓ b = a := by rw [sup_eq_right, ←inf_eq_left] theorem lattice.ext {α} {A B : lattice α} (H : ∀ x y : α, (by haveI := A; exact x ≤ y) ↔ x ≤ y) : A = B := begin have SS : @lattice.to_semilattice_sup α A = @lattice.to_semilattice_sup α B := semilattice_sup.ext H, have II := semilattice_inf.ext H, casesI A, casesI B, injection SS; injection II; congr' end end lattice /-! ### Distributive lattices -/ /-- A distributive lattice is a lattice that satisfies any of four equivalent distributive properties (of `sup` over `inf` or `inf` over `sup`, on the left or right). The definition here chooses `le_sup_inf`: `(x ⊔ y) ⊓ (x ⊔ z) ≤ x ⊔ (y ⊓ z)`. To prove distributivity from the dual law, use `distrib_lattice.of_inf_sup_le`. A classic example of a distributive lattice is the lattice of subsets of a set, and in fact this example is generic in the sense that every distributive lattice is realizable as a sublattice of a powerset lattice. -/ class distrib_lattice α extends lattice α := (le_sup_inf : ∀x y z : α, (x ⊔ y) ⊓ (x ⊔ z) ≤ x ⊔ (y ⊓ z)) section distrib_lattice variables [distrib_lattice α] {x y z : α} theorem le_sup_inf : ∀{x y z : α}, (x ⊔ y) ⊓ (x ⊔ z) ≤ x ⊔ (y ⊓ z) := distrib_lattice.le_sup_inf theorem sup_inf_left : x ⊔ (y ⊓ z) = (x ⊔ y) ⊓ (x ⊔ z) := le_antisymm sup_inf_le le_sup_inf theorem sup_inf_right : (y ⊓ z) ⊔ x = (y ⊔ x) ⊓ (z ⊔ x) := by simp only [sup_inf_left, λy:α, @sup_comm α _ y x, eq_self_iff_true] theorem inf_sup_left : x ⊓ (y ⊔ z) = (x ⊓ y) ⊔ (x ⊓ z) := calc x ⊓ (y ⊔ z) = (x ⊓ (x ⊔ z)) ⊓ (y ⊔ z) : by rw [inf_sup_self] ... = x ⊓ ((x ⊓ y) ⊔ z) : by simp only [inf_assoc, sup_inf_right, eq_self_iff_true] ... = (x ⊔ (x ⊓ y)) ⊓ ((x ⊓ y) ⊔ z) : by rw [sup_inf_self] ... = ((x ⊓ y) ⊔ x) ⊓ ((x ⊓ y) ⊔ z) : by rw [sup_comm] ... = (x ⊓ y) ⊔ (x ⊓ z) : by rw [sup_inf_left] instance (α : Type*) [distrib_lattice α] : distrib_lattice αᵒᵈ := { le_sup_inf := assume x y z, le_of_eq inf_sup_left.symm, .. order_dual.lattice α } theorem inf_sup_right : (y ⊔ z) ⊓ x = (y ⊓ x) ⊔ (z ⊓ x) := by simp only [inf_sup_left, λy:α, @inf_comm α _ y x, eq_self_iff_true] lemma le_of_inf_le_sup_le (h₁ : x ⊓ z ≤ y ⊓ z) (h₂ : x ⊔ z ≤ y ⊔ z) : x ≤ y := calc x ≤ (y ⊓ z) ⊔ x : le_sup_right ... = (y ⊔ x) ⊓ (x ⊔ z) : by rw [sup_inf_right, @sup_comm _ _ x] ... ≤ (y ⊔ x) ⊓ (y ⊔ z) : inf_le_inf_left _ h₂ ... = y ⊔ (x ⊓ z) : sup_inf_left.symm ... ≤ y ⊔ (y ⊓ z) : sup_le_sup_left h₁ _ ... ≤ _ : sup_le (le_refl y) inf_le_left lemma eq_of_inf_eq_sup_eq {α : Type u} [distrib_lattice α] {a b c : α} (h₁ : b ⊓ a = c ⊓ a) (h₂ : b ⊔ a = c ⊔ a) : b = c := le_antisymm (le_of_inf_le_sup_le (le_of_eq h₁) (le_of_eq h₂)) (le_of_inf_le_sup_le (le_of_eq h₁.symm) (le_of_eq h₂.symm)) end distrib_lattice /-- Prove distributivity of an existing lattice from the dual distributive law. -/ @[reducible] -- See note [reducible non-instances] def distrib_lattice.of_inf_sup_le [lattice α] (inf_sup_le : ∀ a b c : α, a ⊓ (b ⊔ c) ≤ (a ⊓ b) ⊔ (a ⊓ c)) : distrib_lattice α := { ..‹lattice α›, ..@order_dual.distrib_lattice αᵒᵈ { le_sup_inf := inf_sup_le, ..order_dual.lattice _ } } /-! ### Lattices derived from linear orders -/ @[priority 100] -- see Note [lower instance priority] instance linear_order.to_lattice {α : Type u} [o : linear_order α] : lattice α := { sup := max, le_sup_left := le_max_left, le_sup_right := le_max_right, sup_le := assume a b c, max_le, inf := min, inf_le_left := min_le_left, inf_le_right := min_le_right, le_inf := assume a b c, le_min, ..o } section linear_order variables [linear_order α] {a b c : α} lemma sup_eq_max : a ⊔ b = max a b := rfl lemma inf_eq_min : a ⊓ b = min a b := rfl lemma sup_ind (a b : α) {p : α → Prop} (ha : p a) (hb : p b) : p (a ⊔ b) := (is_total.total a b).elim (λ h : a ≤ b, by rwa sup_eq_right.2 h) (λ h, by rwa sup_eq_left.2 h) @[simp] lemma le_sup_iff : a ≤ b ⊔ c ↔ a ≤ b ∨ a ≤ c := ⟨λ h, (total_of (≤) c b).imp (λ bc, by rwa sup_eq_left.2 bc at h) (λ bc, by rwa sup_eq_right.2 bc at h), λ h, h.elim le_sup_of_le_left le_sup_of_le_right⟩ @[simp] lemma lt_sup_iff : a < b ⊔ c ↔ a < b ∨ a < c := ⟨λ h, (total_of (≤) c b).imp (λ bc, by rwa sup_eq_left.2 bc at h) (λ bc, by rwa sup_eq_right.2 bc at h), λ h, h.elim lt_sup_of_lt_left lt_sup_of_lt_right⟩ @[simp] lemma sup_lt_iff : b ⊔ c < a ↔ b < a ∧ c < a := ⟨λ h, ⟨le_sup_left.trans_lt h, le_sup_right.trans_lt h⟩, λ h, sup_ind b c h.1 h.2⟩ lemma inf_ind (a b : α) {p : α → Prop} : p a → p b → p (a ⊓ b) := @sup_ind αᵒᵈ _ _ _ _ @[simp] lemma inf_le_iff : b ⊓ c ≤ a ↔ b ≤ a ∨ c ≤ a := @le_sup_iff αᵒᵈ _ _ _ _ @[simp] lemma inf_lt_iff : b ⊓ c < a ↔ b < a ∨ c < a := @lt_sup_iff αᵒᵈ _ _ _ _ @[simp] lemma lt_inf_iff : a < b ⊓ c ↔ a < b ∧ a < c := @sup_lt_iff αᵒᵈ _ _ _ _ end linear_order lemma sup_eq_max_default [semilattice_sup α] [decidable_rel ((≤) : α → α → Prop)] [is_total α (≤)] : (⊔) = (max_default : α → α → α) := begin ext x y, dunfold max_default, split_ifs with h', exacts [sup_of_le_left h', sup_of_le_right $ (total_of (≤) x y).resolve_right h'] end lemma inf_eq_min_default [semilattice_inf α] [decidable_rel ((≤) : α → α → Prop)] [is_total α (≤)] : (⊓) = (min_default : α → α → α) := @sup_eq_max_default αᵒᵈ _ _ _ /-- A lattice with total order is a linear order. See note [reducible non-instances]. -/ @[reducible] def lattice.to_linear_order (α : Type u) [lattice α] [decidable_eq α] [decidable_rel ((≤) : α → α → Prop)] [decidable_rel ((<) : α → α → Prop)] [is_total α (≤)] : linear_order α := { decidable_le := ‹_›, decidable_eq := ‹_›, decidable_lt := ‹_›, le_total := total_of (≤), max := (⊔), max_def := sup_eq_max_default, min := (⊓), min_def := inf_eq_min_default, ..‹lattice α› } @[priority 100] -- see Note [lower instance priority] instance linear_order.to_distrib_lattice {α : Type u} [o : linear_order α] : distrib_lattice α := { le_sup_inf := assume a b c, match le_total b c with | or.inl h := inf_le_of_left_le $ sup_le_sup_left (le_inf (le_refl b) h) _ | or.inr h := inf_le_of_right_le $ sup_le_sup_left (le_inf h (le_refl c)) _ end, ..linear_order.to_lattice } instance nat.distrib_lattice : distrib_lattice ℕ := by apply_instance /-! ### Dual order -/ open order_dual @[simp] lemma of_dual_inf [has_sup α] (a b: αᵒᵈ) : of_dual (a ⊓ b) = of_dual a ⊔ of_dual b := rfl @[simp] lemma of_dual_sup [has_inf α] (a b : αᵒᵈ) : of_dual (a ⊔ b) = of_dual a ⊓ of_dual b := rfl @[simp] lemma to_dual_inf [has_inf α] (a b : α) : to_dual (a ⊓ b) = to_dual a ⊔ to_dual b := rfl @[simp] lemma to_dual_sup [has_sup α] (a b : α) : to_dual (a ⊔ b) = to_dual a ⊓ to_dual b := rfl section linear_order variables [linear_order α] @[simp] lemma of_dual_min (a b : αᵒᵈ) : of_dual (min a b) = max (of_dual a) (of_dual b) := rfl @[simp] lemma of_dual_max (a b : αᵒᵈ) : of_dual (max a b) = min (of_dual a) (of_dual b) := rfl @[simp] lemma to_dual_min (a b : α) : to_dual (min a b) = max (to_dual a) (to_dual b) := rfl @[simp] lemma to_dual_max (a b : α) : to_dual (max a b) = min (to_dual a) (to_dual b) := rfl end linear_order /-! ### Function lattices -/ namespace pi variables {ι : Type*} {α' : ι → Type*} instance [Π i, has_sup (α' i)] : has_sup (Π i, α' i) := ⟨λ f g i, f i ⊔ g i⟩ @[simp] lemma sup_apply [Π i, has_sup (α' i)] (f g : Π i, α' i) (i : ι) : (f ⊔ g) i = f i ⊔ g i := rfl lemma sup_def [Π i, has_sup (α' i)] (f g : Π i, α' i) : f ⊔ g = λ i, f i ⊔ g i := rfl instance [Π i, has_inf (α' i)] : has_inf (Π i, α' i) := ⟨λ f g i, f i ⊓ g i⟩ @[simp] lemma inf_apply [Π i, has_inf (α' i)] (f g : Π i, α' i) (i : ι) : (f ⊓ g) i = f i ⊓ g i := rfl lemma inf_def [Π i, has_inf (α' i)] (f g : Π i, α' i) : f ⊓ g = λ i, f i ⊓ g i := rfl instance [Π i, semilattice_sup (α' i)] : semilattice_sup (Π i, α' i) := by refine_struct { sup := (⊔), .. pi.partial_order }; tactic.pi_instance_derive_field instance [Π i, semilattice_inf (α' i)] : semilattice_inf (Π i, α' i) := by refine_struct { inf := (⊓), .. pi.partial_order }; tactic.pi_instance_derive_field instance [Π i, lattice (α' i)] : lattice (Π i, α' i) := { .. pi.semilattice_sup, .. pi.semilattice_inf } instance [Π i, distrib_lattice (α' i)] : distrib_lattice (Π i, α' i) := by refine_struct { .. pi.lattice }; tactic.pi_instance_derive_field end pi /-! ### Monotone functions and lattices -/ namespace monotone /-- Pointwise supremum of two monotone functions is a monotone function. -/ protected lemma sup [preorder α] [semilattice_sup β] {f g : α → β} (hf : monotone f) (hg : monotone g) : monotone (f ⊔ g) := λ x y h, sup_le_sup (hf h) (hg h) /-- Pointwise infimum of two monotone functions is a monotone function. -/ protected lemma inf [preorder α] [semilattice_inf β] {f g : α → β} (hf : monotone f) (hg : monotone g) : monotone (f ⊓ g) := λ x y h, inf_le_inf (hf h) (hg h) /-- Pointwise maximum of two monotone functions is a monotone function. -/ protected lemma max [preorder α] [linear_order β] {f g : α → β} (hf : monotone f) (hg : monotone g) : monotone (λ x, max (f x) (g x)) := hf.sup hg /-- Pointwise minimum of two monotone functions is a monotone function. -/ protected lemma min [preorder α] [linear_order β] {f g : α → β} (hf : monotone f) (hg : monotone g) : monotone (λ x, min (f x) (g x)) := hf.inf hg lemma le_map_sup [semilattice_sup α] [semilattice_sup β] {f : α → β} (h : monotone f) (x y : α) : f x ⊔ f y ≤ f (x ⊔ y) := sup_le (h le_sup_left) (h le_sup_right) lemma map_inf_le [semilattice_inf α] [semilattice_inf β] {f : α → β} (h : monotone f) (x y : α) : f (x ⊓ y) ≤ f x ⊓ f y := le_inf (h inf_le_left) (h inf_le_right) lemma of_map_inf [semilattice_inf α] [semilattice_inf β] {f : α → β} (h : ∀ x y, f (x ⊓ y) = f x ⊓ f y) : monotone f := λ x y hxy, inf_eq_left.1 $ by rw [← h, inf_eq_left.2 hxy] lemma of_map_sup [semilattice_sup α] [semilattice_sup β] {f : α → β} (h : ∀ x y, f (x ⊔ y) = f x ⊔ f y) : monotone f := (@of_map_inf (order_dual α) (order_dual β) _ _ _ h).dual variables [linear_order α] lemma map_sup [semilattice_sup β] {f : α → β} (hf : monotone f) (x y : α) : f (x ⊔ y) = f x ⊔ f y := (is_total.total x y).elim (λ h : x ≤ y, by simp only [h, hf h, sup_of_le_right]) (λ h, by simp only [h, hf h, sup_of_le_left]) lemma map_inf [semilattice_inf β] {f : α → β} (hf : monotone f) (x y : α) : f (x ⊓ y) = f x ⊓ f y := hf.dual.map_sup _ _ end monotone namespace monotone_on /-- Pointwise supremum of two monotone functions is a monotone function. -/ protected lemma sup [preorder α] [semilattice_sup β] {f g : α → β} {s : set α} (hf : monotone_on f s) (hg : monotone_on g s) : monotone_on (f ⊔ g) s := λ x hx y hy h, sup_le_sup (hf hx hy h) (hg hx hy h) /-- Pointwise infimum of two monotone functions is a monotone function. -/ protected lemma inf [preorder α] [semilattice_inf β] {f g : α → β} {s : set α} (hf : monotone_on f s) (hg : monotone_on g s) : monotone_on (f ⊓ g) s := (hf.dual.sup hg.dual).dual /-- Pointwise maximum of two monotone functions is a monotone function. -/ protected lemma max [preorder α] [linear_order β] {f g : α → β} {s : set α} (hf : monotone_on f s) (hg : monotone_on g s) : monotone_on (λ x, max (f x) (g x)) s := hf.sup hg /-- Pointwise minimum of two monotone functions is a monotone function. -/ protected lemma min [preorder α] [linear_order β] {f g : α → β} {s : set α} (hf : monotone_on f s) (hg : monotone_on g s) : monotone_on (λ x, min (f x) (g x)) s := hf.inf hg end monotone_on namespace antitone /-- Pointwise supremum of two monotone functions is a monotone function. -/ protected lemma sup [preorder α] [semilattice_sup β] {f g : α → β} (hf : antitone f) (hg : antitone g) : antitone (f ⊔ g) := λ x y h, sup_le_sup (hf h) (hg h) /-- Pointwise infimum of two monotone functions is a monotone function. -/ protected lemma inf [preorder α] [semilattice_inf β] {f g : α → β} (hf : antitone f) (hg : antitone g) : antitone (f ⊓ g) := λ x y h, inf_le_inf (hf h) (hg h) /-- Pointwise maximum of two monotone functions is a monotone function. -/ protected lemma max [preorder α] [linear_order β] {f g : α → β} (hf : antitone f) (hg : antitone g) : antitone (λ x, max (f x) (g x)) := hf.sup hg /-- Pointwise minimum of two monotone functions is a monotone function. -/ protected lemma min [preorder α] [linear_order β] {f g : α → β} (hf : antitone f) (hg : antitone g) : antitone (λ x, min (f x) (g x)) := hf.inf hg lemma map_sup_le [semilattice_sup α] [semilattice_inf β] {f : α → β} (h : antitone f) (x y : α) : f (x ⊔ y) ≤ f x ⊓ f y := h.dual_right.le_map_sup x y lemma le_map_inf [semilattice_inf α] [semilattice_sup β] {f : α → β} (h : antitone f) (x y : α) : f x ⊔ f y ≤ f (x ⊓ y) := h.dual_right.map_inf_le x y variables [linear_order α] lemma map_sup [semilattice_inf β] {f : α → β} (hf : antitone f) (x y : α) : f (x ⊔ y) = f x ⊓ f y := hf.dual_right.map_sup x y lemma map_inf [semilattice_sup β] {f : α → β} (hf : antitone f) (x y : α) : f (x ⊓ y) = f x ⊔ f y := hf.dual_right.map_inf x y end antitone namespace antitone_on /-- Pointwise supremum of two antitone functions is a antitone function. -/ protected lemma sup [preorder α] [semilattice_sup β] {f g : α → β} {s : set α} (hf : antitone_on f s) (hg : antitone_on g s) : antitone_on (f ⊔ g) s := λ x hx y hy h, sup_le_sup (hf hx hy h) (hg hx hy h) /-- Pointwise infimum of two antitone functions is a antitone function. -/ protected lemma inf [preorder α] [semilattice_inf β] {f g : α → β} {s : set α} (hf : antitone_on f s) (hg : antitone_on g s) : antitone_on (f ⊓ g) s := (hf.dual.sup hg.dual).dual /-- Pointwise maximum of two antitone functions is a antitone function. -/ protected lemma max [preorder α] [linear_order β] {f g : α → β} {s : set α} (hf : antitone_on f s) (hg : antitone_on g s) : antitone_on (λ x, max (f x) (g x)) s := hf.sup hg /-- Pointwise minimum of two antitone functions is a antitone function. -/ protected lemma min [preorder α] [linear_order β] {f g : α → β} {s : set α} (hf : antitone_on f s) (hg : antitone_on g s) : antitone_on (λ x, min (f x) (g x)) s := hf.inf hg end antitone_on /-! ### Products of (semi-)lattices -/ namespace prod variables (α β) instance [has_sup α] [has_sup β] : has_sup (α × β) := ⟨λp q, ⟨p.1 ⊔ q.1, p.2 ⊔ q.2⟩⟩ instance [has_inf α] [has_inf β] : has_inf (α × β) := ⟨λp q, ⟨p.1 ⊓ q.1, p.2 ⊓ q.2⟩⟩ instance [semilattice_sup α] [semilattice_sup β] : semilattice_sup (α × β) := { sup_le := assume a b c h₁ h₂, ⟨sup_le h₁.1 h₂.1, sup_le h₁.2 h₂.2⟩, le_sup_left := assume a b, ⟨le_sup_left, le_sup_left⟩, le_sup_right := assume a b, ⟨le_sup_right, le_sup_right⟩, .. prod.partial_order α β, .. prod.has_sup α β } instance [semilattice_inf α] [semilattice_inf β] : semilattice_inf (α × β) := { le_inf := assume a b c h₁ h₂, ⟨le_inf h₁.1 h₂.1, le_inf h₁.2 h₂.2⟩, inf_le_left := assume a b, ⟨inf_le_left, inf_le_left⟩, inf_le_right := assume a b, ⟨inf_le_right, inf_le_right⟩, .. prod.partial_order α β, .. prod.has_inf α β } instance [lattice α] [lattice β] : lattice (α × β) := { .. prod.semilattice_inf α β, .. prod.semilattice_sup α β } instance [distrib_lattice α] [distrib_lattice β] : distrib_lattice (α × β) := { le_sup_inf := assume a b c, ⟨le_sup_inf, le_sup_inf⟩, .. prod.lattice α β } end prod /-! ### Subtypes of (semi-)lattices -/ namespace subtype /-- A subtype forms a `⊔`-semilattice if `⊔` preserves the property. See note [reducible non-instances]. -/ @[reducible] protected def semilattice_sup [semilattice_sup α] {P : α → Prop} (Psup : ∀⦃x y⦄, P x → P y → P (x ⊔ y)) : semilattice_sup {x : α // P x} := { sup := λ x y, ⟨x.1 ⊔ y.1, Psup x.2 y.2⟩, le_sup_left := λ x y, @le_sup_left _ _ (x : α) y, le_sup_right := λ x y, @le_sup_right _ _ (x : α) y, sup_le := λ x y z h1 h2, @sup_le α _ _ _ _ h1 h2, ..subtype.partial_order P } /-- A subtype forms a `⊓`-semilattice if `⊓` preserves the property. See note [reducible non-instances]. -/ @[reducible] protected def semilattice_inf [semilattice_inf α] {P : α → Prop} (Pinf : ∀⦃x y⦄, P x → P y → P (x ⊓ y)) : semilattice_inf {x : α // P x} := { inf := λ x y, ⟨x.1 ⊓ y.1, Pinf x.2 y.2⟩, inf_le_left := λ x y, @inf_le_left _ _ (x : α) y, inf_le_right := λ x y, @inf_le_right _ _ (x : α) y, le_inf := λ x y z h1 h2, @le_inf α _ _ _ _ h1 h2, ..subtype.partial_order P } /-- A subtype forms a lattice if `⊔` and `⊓` preserve the property. See note [reducible non-instances]. -/ @[reducible] protected def lattice [lattice α] {P : α → Prop} (Psup : ∀⦃x y⦄, P x → P y → P (x ⊔ y)) (Pinf : ∀⦃x y⦄, P x → P y → P (x ⊓ y)) : lattice {x : α // P x} := { ..subtype.semilattice_inf Pinf, ..subtype.semilattice_sup Psup } @[simp, norm_cast] lemma coe_sup [semilattice_sup α] {P : α → Prop} (Psup : ∀⦃x y⦄, P x → P y → P (x ⊔ y)) (x y : subtype P) : (by {haveI := subtype.semilattice_sup Psup, exact (x ⊔ y : subtype P)} : α) = x ⊔ y := rfl @[simp, norm_cast] lemma coe_inf [semilattice_inf α] {P : α → Prop} (Pinf : ∀⦃x y⦄, P x → P y → P (x ⊓ y)) (x y : subtype P) : (by {haveI := subtype.semilattice_inf Pinf, exact (x ⊓ y : subtype P)} : α) = x ⊓ y := rfl @[simp] lemma mk_sup_mk [semilattice_sup α] {P : α → Prop} (Psup : ∀⦃x y⦄, P x → P y → P (x ⊔ y)) {x y : α} (hx : P x) (hy : P y) : (by {haveI := subtype.semilattice_sup Psup, exact (⟨x, hx⟩ ⊔ ⟨y, hy⟩ : subtype P)}) = ⟨x ⊔ y, Psup hx hy⟩ := rfl @[simp] lemma mk_inf_mk [semilattice_inf α] {P : α → Prop} (Pinf : ∀⦃x y⦄, P x → P y → P (x ⊓ y)) {x y : α} (hx : P x) (hy : P y) : (by {haveI := subtype.semilattice_inf Pinf, exact (⟨x, hx⟩ ⊓ ⟨y, hy⟩ : subtype P)}) = ⟨x ⊓ y, Pinf hx hy⟩ := rfl end subtype section lift /-- A type endowed with `⊔` is a `semilattice_sup`, if it admits an injective map that preserves `⊔` to a `semilattice_sup`. See note [reducible non-instances]. -/ @[reducible] protected def function.injective.semilattice_sup [has_sup α] [semilattice_sup β] (f : α → β) (hf_inj : function.injective f) (map_sup : ∀ a b, f (a ⊔ b) = f a ⊔ f b) : semilattice_sup α := { sup := has_sup.sup, le_sup_left := λ a b, by { change f a ≤ f (a ⊔ b), rw map_sup, exact le_sup_left, }, le_sup_right := λ a b, by { change f b ≤ f (a ⊔ b), rw map_sup, exact le_sup_right, }, sup_le := λ a b c ha hb, by { change f (a ⊔ b) ≤ f c, rw map_sup, exact sup_le ha hb, }, ..partial_order.lift f hf_inj} /-- A type endowed with `⊓` is a `semilattice_inf`, if it admits an injective map that preserves `⊓` to a `semilattice_inf`. See note [reducible non-instances]. -/ @[reducible] protected def function.injective.semilattice_inf [has_inf α] [semilattice_inf β] (f : α → β) (hf_inj : function.injective f) (map_inf : ∀ a b, f (a ⊓ b) = f a ⊓ f b) : semilattice_inf α := { inf := has_inf.inf, inf_le_left := λ a b, by { change f (a ⊓ b) ≤ f a, rw map_inf, exact inf_le_left, }, inf_le_right := λ a b, by { change f (a ⊓ b) ≤ f b, rw map_inf, exact inf_le_right, }, le_inf := λ a b c ha hb, by { change f a ≤ f (b ⊓ c), rw map_inf, exact le_inf ha hb, }, ..partial_order.lift f hf_inj} /-- A type endowed with `⊔` and `⊓` is a `lattice`, if it admits an injective map that preserves `⊔` and `⊓` to a `lattice`. See note [reducible non-instances]. -/ @[reducible] protected def function.injective.lattice [has_sup α] [has_inf α] [lattice β] (f : α → β) (hf_inj : 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) : lattice α := { ..hf_inj.semilattice_sup f map_sup, ..hf_inj.semilattice_inf f map_inf} /-- A type endowed with `⊔` and `⊓` is a `distrib_lattice`, if it admits an injective map that preserves `⊔` and `⊓` to a `distrib_lattice`. See note [reducible non-instances]. -/ @[reducible] protected def function.injective.distrib_lattice [has_sup α] [has_inf α] [distrib_lattice β] (f : α → β) (hf_inj : 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) : distrib_lattice α := { le_sup_inf := λ a b c, by { change f ((a ⊔ b) ⊓ (a ⊔ c)) ≤ f (a ⊔ b ⊓ c), rw [map_inf, map_sup, map_sup, map_sup, map_inf], exact le_sup_inf, }, ..hf_inj.lattice f map_sup map_inf, } end lift --To avoid noncomputability poisoning from `bool.complete_boolean_algebra` instance : distrib_lattice bool := linear_order.to_distrib_lattice
bab6f662d12886b026a176c042032e76e6286897
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/data/int/cast_auto.lean
fe84e17d24a54b23a8c9090007cb3cfa4ab85e88
[]
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
8,147
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 Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.data.int.basic import Mathlib.data.nat.cast import Mathlib.PostPort universes u_1 u_2 namespace Mathlib namespace int /- cast (injection into groups with one) -/ @[simp] theorem nat_cast_eq_coe_nat (n : ℕ) : ↑n = ↑n := sorry /-- Coercion `ℕ → ℤ` as a `ring_hom`. -/ def of_nat_hom : ℕ →+* ℤ := ring_hom.mk coe sorry of_nat_mul sorry of_nat_add /-- Canonical homomorphism from the integers to any ring(-like) structure `α` -/ protected def cast {α : Type u_1} [HasZero α] [HasOne α] [Add α] [Neg α] : ℤ → α := sorry -- see Note [coercion into rings] protected instance cast_coe {α : Type u_1} [HasZero α] [HasOne α] [Add α] [Neg α] : has_coe_t ℤ α := has_coe_t.mk int.cast @[simp] theorem cast_zero {α : Type u_1} [HasZero α] [HasOne α] [Add α] [Neg α] : ↑0 = 0 := rfl theorem cast_of_nat {α : Type u_1} [HasZero α] [HasOne α] [Add α] [Neg α] (n : ℕ) : ↑(Int.ofNat n) = ↑n := rfl @[simp] theorem cast_coe_nat {α : Type u_1} [HasZero α] [HasOne α] [Add α] [Neg α] (n : ℕ) : ↑↑n = ↑n := rfl theorem cast_coe_nat' {α : Type u_1} [HasZero α] [HasOne α] [Add α] [Neg α] (n : ℕ) : ↑↑n = ↑n := sorry @[simp] theorem cast_neg_succ_of_nat {α : Type u_1} [HasZero α] [HasOne α] [Add α] [Neg α] (n : ℕ) : ↑(Int.negSucc n) = -(↑n + 1) := rfl @[simp] theorem cast_one {α : Type u_1} [add_monoid α] [HasOne α] [Neg α] : ↑1 = 1 := nat.cast_one @[simp] theorem cast_sub_nat_nat {α : Type u_1} [add_group α] [HasOne α] (m : ℕ) (n : ℕ) : ↑(sub_nat_nat m n) = ↑m - ↑n := sorry @[simp] theorem cast_neg_of_nat {α : Type u_1} [add_group α] [HasOne α] (n : ℕ) : ↑(neg_of_nat n) = -↑n := nat.cases_on n (idRhs (0 = -0) (Eq.symm neg_zero)) fun (n : ℕ) => idRhs (↑(neg_of_nat (n + 1)) = ↑(neg_of_nat (n + 1))) rfl @[simp] theorem cast_add {α : Type u_1} [add_group α] [HasOne α] (m : ℤ) (n : ℤ) : ↑(m + n) = ↑m + ↑n := sorry @[simp] theorem cast_neg {α : Type u_1} [add_group α] [HasOne α] (n : ℤ) : ↑(-n) = -↑n := int.cases_on n (fun (n : ℕ) => idRhs (↑(neg_of_nat n) = -↑n) (cast_neg_of_nat n)) fun (n : ℕ) => idRhs (↑(-Int.negSucc n) = --↑(-Int.negSucc n)) (Eq.symm (neg_neg ↑(-Int.negSucc n))) @[simp] theorem cast_sub {α : Type u_1} [add_group α] [HasOne α] (m : ℤ) (n : ℤ) : ↑(m - n) = ↑m - ↑n := sorry @[simp] theorem cast_mul {α : Type u_1} [ring α] (m : ℤ) (n : ℤ) : ↑(m * n) = ↑m * ↑n := sorry /-- `coe : ℤ → α` as an `add_monoid_hom`. -/ def cast_add_hom (α : Type u_1) [add_group α] [HasOne α] : ℤ →+ α := add_monoid_hom.mk coe sorry cast_add @[simp] theorem coe_cast_add_hom {α : Type u_1} [add_group α] [HasOne α] : ⇑(cast_add_hom α) = coe := rfl /-- `coe : ℤ → α` as a `ring_hom`. -/ def cast_ring_hom (α : Type u_1) [ring α] : ℤ →+* α := ring_hom.mk coe sorry cast_mul sorry sorry @[simp] theorem coe_cast_ring_hom {α : Type u_1} [ring α] : ⇑(cast_ring_hom α) = coe := rfl theorem cast_commute {α : Type u_1} [ring α] (m : ℤ) (x : α) : commute (↑m) x := int.cases_on m (fun (n : ℕ) => nat.cast_commute n x) fun (n : ℕ) => commute.neg_left (nat.cast_commute (n + 1) x) theorem commute_cast {α : Type u_1} [ring α] (x : α) (m : ℤ) : commute x ↑m := commute.symm (cast_commute m x) @[simp] theorem coe_nat_bit0 (n : ℕ) : ↑(bit0 n) = bit0 ↑n := sorry @[simp] theorem coe_nat_bit1 (n : ℕ) : ↑(bit1 n) = bit1 ↑n := sorry @[simp] theorem cast_bit0 {α : Type u_1} [ring α] (n : ℤ) : ↑(bit0 n) = bit0 ↑n := cast_add n n @[simp] theorem cast_bit1 {α : Type u_1} [ring α] (n : ℤ) : ↑(bit1 n) = bit1 ↑n := sorry theorem cast_two {α : Type u_1} [ring α] : ↑(bit0 1) = bit0 1 := sorry theorem cast_mono {α : Type u_1} [ordered_ring α] : monotone coe := sorry @[simp] theorem cast_nonneg {α : Type u_1} [ordered_ring α] [nontrivial α] {n : ℤ} : 0 ≤ ↑n ↔ 0 ≤ n := sorry @[simp] theorem cast_le {α : Type u_1} [ordered_ring α] [nontrivial α] {m : ℤ} {n : ℤ} : ↑m ≤ ↑n ↔ m ≤ n := sorry theorem cast_strict_mono {α : Type u_1} [ordered_ring α] [nontrivial α] : strict_mono coe := strict_mono_of_le_iff_le fun (m n : ℤ) => iff.symm cast_le @[simp] theorem cast_lt {α : Type u_1} [ordered_ring α] [nontrivial α] {m : ℤ} {n : ℤ} : ↑m < ↑n ↔ m < n := strict_mono.lt_iff_lt cast_strict_mono @[simp] theorem cast_nonpos {α : Type u_1} [ordered_ring α] [nontrivial α] {n : ℤ} : ↑n ≤ 0 ↔ n ≤ 0 := eq.mpr (id (Eq._oldrec (Eq.refl (↑n ≤ 0 ↔ n ≤ 0)) (Eq.symm cast_zero))) (eq.mpr (id (Eq._oldrec (Eq.refl (↑n ≤ ↑0 ↔ n ≤ 0)) (propext cast_le))) (iff.refl (n ≤ 0))) @[simp] theorem cast_pos {α : Type u_1} [ordered_ring α] [nontrivial α] {n : ℤ} : 0 < ↑n ↔ 0 < n := eq.mpr (id (Eq._oldrec (Eq.refl (0 < ↑n ↔ 0 < n)) (Eq.symm cast_zero))) (eq.mpr (id (Eq._oldrec (Eq.refl (↑0 < ↑n ↔ 0 < n)) (propext cast_lt))) (iff.refl (0 < n))) @[simp] theorem cast_lt_zero {α : Type u_1} [ordered_ring α] [nontrivial α] {n : ℤ} : ↑n < 0 ↔ n < 0 := eq.mpr (id (Eq._oldrec (Eq.refl (↑n < 0 ↔ n < 0)) (Eq.symm cast_zero))) (eq.mpr (id (Eq._oldrec (Eq.refl (↑n < ↑0 ↔ n < 0)) (propext cast_lt))) (iff.refl (n < 0))) @[simp] theorem cast_min {α : Type u_1} [linear_ordered_ring α] {a : ℤ} {b : ℤ} : ↑(min a b) = min ↑a ↑b := monotone.map_min cast_mono @[simp] theorem cast_max {α : Type u_1} [linear_ordered_ring α] {a : ℤ} {b : ℤ} : ↑(max a b) = max ↑a ↑b := monotone.map_max cast_mono @[simp] theorem cast_abs {α : Type u_1} [linear_ordered_ring α] {q : ℤ} : ↑(abs q) = abs ↑q := sorry theorem coe_int_dvd {α : Type u_1} [comm_ring α] (m : ℤ) (n : ℤ) (h : m ∣ n) : ↑m ∣ ↑n := ring_hom.map_dvd (cast_ring_hom α) h end int namespace add_monoid_hom /-- Two additive monoid homomorphisms `f`, `g` from `ℤ` to an additive monoid are equal if `f 1 = g 1`. -/ theorem ext_int {A : Type u_1} [add_monoid A] {f : ℤ →+ A} {g : ℤ →+ A} (h1 : coe_fn f 1 = coe_fn g 1) : f = g := sorry theorem eq_int_cast_hom {A : Type u_1} [add_group A] [HasOne A] (f : ℤ →+ A) (h1 : coe_fn f 1 = 1) : f = int.cast_add_hom A := sorry theorem eq_int_cast {A : Type u_1} [add_group A] [HasOne A] (f : ℤ →+ A) (h1 : coe_fn f 1 = 1) (n : ℤ) : coe_fn f n = ↑n := iff.mp ext_iff (eq_int_cast_hom f h1) end add_monoid_hom namespace monoid_hom theorem ext_int {M : Type u_1} [monoid M] {f : multiplicative ℤ →* M} {g : multiplicative ℤ →* M} (h1 : coe_fn f (coe_fn multiplicative.of_add 1) = coe_fn g (coe_fn multiplicative.of_add 1)) : f = g := ext fun (x : multiplicative ℤ) => iff.mp add_monoid_hom.ext_iff (add_monoid_hom.ext_int h1) x end monoid_hom namespace ring_hom @[simp] theorem eq_int_cast {α : Type u_1} [ring α] (f : ℤ →+* α) (n : ℤ) : coe_fn f n = ↑n := add_monoid_hom.eq_int_cast (to_add_monoid_hom f) (map_one f) n theorem eq_int_cast' {α : Type u_1} [ring α] (f : ℤ →+* α) : f = int.cast_ring_hom α := ext (eq_int_cast f) @[simp] theorem map_int_cast {α : Type u_1} {β : Type u_2} [ring α] [ring β] (f : α →+* β) (n : ℤ) : coe_fn f ↑n = ↑n := eq_int_cast (comp f (int.cast_ring_hom α)) n theorem ext_int {R : Type u_1} [semiring R] (f : ℤ →+* R) (g : ℤ →+* R) : f = g := coe_add_monoid_hom_injective (add_monoid_hom.ext_int (Eq.trans (map_one f) (Eq.symm (map_one g)))) protected instance int.subsingleton_ring_hom {R : Type u_1} [semiring R] : subsingleton (ℤ →+* R) := subsingleton.intro ext_int end ring_hom @[simp] theorem int.cast_id (n : ℤ) : ↑n = n := Eq.symm (ring_hom.eq_int_cast (ring_hom.id ℤ) n) end Mathlib
7c687014322f2df29fee596eadcd605a1976d8a7
d9d511f37a523cd7659d6f573f990e2a0af93c6f
/src/order/omega_complete_partial_order.lean
f4febbbccd7d3340ab767f2da7a7c37d75458016
[ "Apache-2.0" ]
permissive
hikari0108/mathlib
b7ea2b7350497ab1a0b87a09d093ecc025a50dfa
a9e7d333b0cfd45f13a20f7b96b7d52e19fa2901
refs/heads/master
1,690,483,608,260
1,631,541,580,000
1,631,541,580,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
30,198
lean
/- Copyright (c) 2020 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Simon Hudon -/ import data.pfun import order.preorder_hom import tactic.wlog import tactic.monotonicity /-! # Omega Complete Partial Orders An omega-complete partial order is a partial order with a supremum operation on increasing sequences indexed by natural numbers (which we call `ωSup`). In this sense, it is strictly weaker than join complete semi-lattices as only ω-sized totally ordered sets have a supremum. The concept of an omega-complete partial order (ωCPO) is useful for the formalization of the semantics of programming languages. Its notion of supremum helps define the meaning of recursive procedures. ## Main definitions * class `omega_complete_partial_order` * `ite`, `map`, `bind`, `seq` as continuous morphisms ## Instances of `omega_complete_partial_order` * `part` * every `complete_lattice` * pi-types * product types * `monotone_hom` * `continuous_hom` (with notation →𝒄) * an instance of `omega_complete_partial_order (α →𝒄 β)` * `continuous_hom.of_fun` * `continuous_hom.of_mono` * continuous functions: * `id` * `ite` * `const` * `part.bind` * `part.map` * `part.seq` ## References * [Chain-complete posets and directed sets with applications][markowsky1976] * [Recursive definitions of partial functions and their computations][cadiou1972] * [Semantics of Programming Languages: Structures and Techniques][gunter1992] -/ universes u v local attribute [-simp] part.bind_eq_bind part.map_eq_map open_locale classical namespace preorder_hom variables (α : Type*) (β : Type*) {γ : Type*} {φ : Type*} variables [preorder α] [preorder β] [preorder γ] [preorder φ] variables {β γ} /-- The constant function, as a monotone function. -/ @[simps] def const (f : β) : α →ₘ β := { to_fun := function.const _ f, monotone' := assume x y h, le_refl _} variables {α} {α' : Type*} {β' : Type*} [preorder α'] [preorder β'] /-- The diagonal function, as a monotone function. -/ @[simps] def prod.diag : α →ₘ (α × α) := { to_fun := λ x, (x,x), monotone' := λ x y h, ⟨h,h⟩ } /-- The `prod.map` function, as a monotone function. -/ @[simps] def prod.map (f : α →ₘ β) (f' : α' →ₘ β') : (α × α') →ₘ (β × β') := { to_fun := prod.map f f', monotone' := λ ⟨x,x'⟩ ⟨y,y'⟩ ⟨h,h'⟩, ⟨f.monotone h,f'.monotone h'⟩ } /-- The `prod.fst` projection, as a monotone function. -/ @[simps] def prod.fst : (α × β) →ₘ α := { to_fun := prod.fst, monotone' := λ ⟨x,x'⟩ ⟨y,y'⟩ ⟨h,h'⟩, h } /-- The `prod.snd` projection, as a monotone function. -/ @[simps] def prod.snd : (α × β) →ₘ β := { to_fun := prod.snd, monotone' := λ ⟨x,x'⟩ ⟨y,y'⟩ ⟨h,h'⟩, h' } /-- The `prod` constructor, as a monotone function. -/ @[simps] def prod.zip (f : α →ₘ β) (g : α →ₘ γ) : α →ₘ (β × γ) := (prod.map f g).comp prod.diag /-- `part.bind` as a monotone function -/ @[simps] def bind {β γ} (f : α →ₘ part β) (g : α →ₘ β → part γ) : α →ₘ part γ := { to_fun := λ x, f x >>= g x, monotone' := begin intros x y h a, simp only [and_imp, exists_prop, part.bind_eq_bind, part.mem_bind_iff, exists_imp_distrib], intros b hb ha, refine ⟨b, f.monotone h _ hb, g.monotone h _ _ ha⟩, end } end preorder_hom namespace omega_complete_partial_order /-- A chain is a monotonically increasing sequence. See the definition on page 114 of [gunter1992]. -/ def chain (α : Type u) [preorder α] := ℕ →ₘ α namespace chain variables {α : Type u} {β : Type v} {γ : Type*} variables [preorder α] [preorder β] [preorder γ] instance : has_coe_to_fun (chain α) := @infer_instance (has_coe_to_fun $ ℕ →ₘ α) _ instance [inhabited α] : inhabited (chain α) := ⟨ ⟨ λ _, default _, λ _ _ _, le_refl _ ⟩ ⟩ instance : has_mem α (chain α) := ⟨λa (c : ℕ →ₘ α), ∃ i, a = c i⟩ variables (c c' : chain α) variables (f : α →ₘ β) variables (g : β →ₘ γ) instance : has_le (chain α) := { le := λ x y, ∀ i, ∃ j, x i ≤ y j } /-- `map` function for `chain` -/ @[simps {fully_applied := ff}] def map : chain β := f.comp c variables {f} lemma mem_map (x : α) : x ∈ c → f x ∈ chain.map c f := λ ⟨i,h⟩, ⟨i, h.symm ▸ rfl⟩ lemma exists_of_mem_map {b : β} : b ∈ c.map f → ∃ a, a ∈ c ∧ f a = b := λ ⟨i,h⟩, ⟨c i, ⟨i, rfl⟩, h.symm⟩ lemma mem_map_iff {b : β} : b ∈ c.map f ↔ ∃ a, a ∈ c ∧ f a = b := ⟨ exists_of_mem_map _, λ h, by { rcases h with ⟨w,h,h'⟩, subst b, apply mem_map c _ h, } ⟩ @[simp] lemma map_id : c.map preorder_hom.id = c := preorder_hom.comp_id _ lemma map_comp : (c.map f).map g = c.map (g.comp f) := rfl @[mono] lemma map_le_map {g : α →ₘ β} (h : f ≤ g) : c.map f ≤ c.map g := λ i, by simp [mem_map_iff]; intros; existsi i; apply h /-- `chain.zip` pairs up the elements of two chains that have the same index -/ @[simps] def zip (c₀ : chain α) (c₁ : chain β) : chain (α × β) := preorder_hom.prod.zip c₀ c₁ end chain end omega_complete_partial_order open omega_complete_partial_order section prio set_option extends_priority 50 /-- An omega-complete partial order is a partial order with a supremum operation on increasing sequences indexed by natural numbers (which we call `ωSup`). In this sense, it is strictly weaker than join complete semi-lattices as only ω-sized totally ordered sets have a supremum. See the definition on page 114 of [gunter1992]. -/ class omega_complete_partial_order (α : Type*) extends partial_order α := (ωSup : chain α → α) (le_ωSup : ∀(c:chain α), ∀ i, c i ≤ ωSup c) (ωSup_le : ∀(c:chain α) x, (∀ i, c i ≤ x) → ωSup c ≤ x) end prio namespace omega_complete_partial_order variables {α : Type u} {β : Type v} {γ : Type*} variables [omega_complete_partial_order α] /-- Transfer a `omega_complete_partial_order` on `β` to a `omega_complete_partial_order` on `α` using a strictly monotone function `f : β →ₘ α`, a definition of ωSup and a proof that `f` is continuous with regard to the provided `ωSup` and the ωCPO on `α`. -/ @[reducible] protected def lift [partial_order β] (f : β →ₘ α) (ωSup₀ : chain β → β) (h : ∀ x y, f x ≤ f y → x ≤ y) (h' : ∀ c, f (ωSup₀ c) = ωSup (c.map f)) : omega_complete_partial_order β := { ωSup := ωSup₀, ωSup_le := λ c x hx, h _ _ (by rw h'; apply ωSup_le; intro; apply f.monotone (hx i)), le_ωSup := λ c i, h _ _ (by rw h'; apply le_ωSup (c.map f)) } lemma le_ωSup_of_le {c : chain α} {x : α} (i : ℕ) (h : x ≤ c i) : x ≤ ωSup c := le_trans h (le_ωSup c _) lemma ωSup_total {c : chain α} {x : α} (h : ∀ i, c i ≤ x ∨ x ≤ c i) : ωSup c ≤ x ∨ x ≤ ωSup c := classical.by_cases (assume : ∀ i, c i ≤ x, or.inl (ωSup_le _ _ this)) (assume : ¬ ∀ i, c i ≤ x, have ∃ i, ¬ c i ≤ x, by simp only [not_forall] at this ⊢; assumption, let ⟨i, hx⟩ := this in have x ≤ c i, from (h i).resolve_left hx, or.inr $ le_ωSup_of_le _ this) @[mono] lemma ωSup_le_ωSup_of_le {c₀ c₁ : chain α} (h : c₀ ≤ c₁) : ωSup c₀ ≤ ωSup c₁ := ωSup_le _ _ $ λ i, Exists.rec_on (h i) $ λ j h, le_trans h (le_ωSup _ _) lemma ωSup_le_iff (c : chain α) (x : α) : ωSup c ≤ x ↔ (∀ i, c i ≤ x) := begin split; intros, { transitivity ωSup c, exact le_ωSup _ _, assumption }, exact ωSup_le _ _ ‹_›, end /-- A subset `p : α → Prop` of the type closed under `ωSup` induces an `omega_complete_partial_order` on the subtype `{a : α // p a}`. -/ def subtype {α : Type*} [omega_complete_partial_order α] (p : α → Prop) (hp : ∀ (c : chain α), (∀ i ∈ c, p i) → p (ωSup c)) : omega_complete_partial_order (subtype p) := omega_complete_partial_order.lift (preorder_hom.subtype.val p) (λ c, ⟨ωSup _, hp (c.map (preorder_hom.subtype.val p)) (λ i ⟨n, q⟩, q.symm ▸ (c n).2)⟩) (λ x y h, h) (λ c, rfl) section continuity open chain variables [omega_complete_partial_order β] variables [omega_complete_partial_order γ] /-- A monotone function `f : α →ₘ β` is continuous if it distributes over ωSup. In order to distinguish it from the (more commonly used) continuity from topology (see topology/basic.lean), the present definition is often referred to as "Scott-continuity" (referring to Dana Scott). It corresponds to continuity in Scott topological spaces (not defined here). -/ def continuous (f : α →ₘ β) : Prop := ∀ c : chain α, f (ωSup c) = ωSup (c.map f) /-- `continuous' f` asserts that `f` is both monotone and continuous. -/ def continuous' (f : α → β) : Prop := ∃ hf : monotone f, continuous ⟨f, hf⟩ lemma continuous.to_monotone {f : α → β} (hf : continuous' f) : monotone f := hf.fst lemma continuous.of_bundled (f : α → β) (hf : monotone f) (hf' : continuous ⟨f, hf⟩) : continuous' f := ⟨hf, hf'⟩ lemma continuous.of_bundled' (f : α →ₘ β) (hf' : continuous f) : continuous' f := ⟨f.monotone, hf'⟩ lemma continuous.to_bundled (f : α → β) (hf : continuous' f) : continuous ⟨f, continuous.to_monotone hf⟩ := hf.snd variables (f : α →ₘ β) (g : β →ₘ γ) lemma continuous_id : continuous (@preorder_hom.id α _) := by intro; rw c.map_id; refl lemma continuous_comp (hfc : continuous f) (hgc : continuous g) : continuous (g.comp f):= begin dsimp [continuous] at *, intro, rw [hfc,hgc,chain.map_comp] end lemma id_continuous' : continuous' (@id α) := continuous.of_bundled _ (λ a b h, h) begin intro c, apply eq_of_forall_ge_iff, intro z, simp [ωSup_le_iff,function.const], end lemma const_continuous' (x: β) : continuous' (function.const α x) := continuous.of_bundled _ (λ a b h, le_refl _) begin intro c, apply eq_of_forall_ge_iff, intro z, simp [ωSup_le_iff,function.const], end end continuity end omega_complete_partial_order namespace part variables {α : Type u} {β : Type v} {γ : Type*} open omega_complete_partial_order lemma eq_of_chain {c : chain (part α)} {a b : α} (ha : some a ∈ c) (hb : some b ∈ c) : a = b := begin cases ha with i ha, replace ha := ha.symm, cases hb with j hb, replace hb := hb.symm, wlog h : i ≤ j := le_total i j using [a b i j, b a j i], rw [eq_some_iff] at ha hb, have := c.monotone h _ ha, apply mem_unique this hb end /-- The (noncomputable) `ωSup` definition for the `ω`-CPO structure on `part α`. -/ protected noncomputable def ωSup (c : chain (part α)) : part α := if h : ∃a, some a ∈ c then some (classical.some h) else none lemma ωSup_eq_some {c : chain (part α)} {a : α} (h : some a ∈ c) : part.ωSup c = some a := have ∃a, some a ∈ c, from ⟨a, h⟩, have a' : some (classical.some this) ∈ c, from classical.some_spec this, calc part.ωSup c = some (classical.some this) : dif_pos this ... = some a : congr_arg _ (eq_of_chain a' h) lemma ωSup_eq_none {c : chain (part α)} (h : ¬∃a, some a ∈ c) : part.ωSup c = none := dif_neg h lemma mem_chain_of_mem_ωSup {c : chain (part α)} {a : α} (h : a ∈ part.ωSup c) : some a ∈ c := begin simp [part.ωSup] at h, split_ifs at h, { have h' := classical.some_spec h_1, rw ← eq_some_iff at h, rw ← h, exact h' }, { rcases h with ⟨ ⟨ ⟩ ⟩ } end noncomputable instance omega_complete_partial_order : omega_complete_partial_order (part α) := { ωSup := part.ωSup, le_ωSup := λ c i, by { intros x hx, rw ← eq_some_iff at hx ⊢, rw [ωSup_eq_some, ← hx], rw ← hx, exact ⟨i,rfl⟩ }, ωSup_le := by { rintros c x hx a ha, replace ha := mem_chain_of_mem_ωSup ha, cases ha with i ha, apply hx i, rw ← ha, apply mem_some } } section inst lemma mem_ωSup (x : α) (c : chain (part α)) : x ∈ ωSup c ↔ some x ∈ c := begin simp [omega_complete_partial_order.ωSup,part.ωSup], split, { split_ifs, swap, rintro ⟨⟨⟩⟩, intro h', have hh := classical.some_spec h, simp at h', subst x, exact hh }, { intro h, have h' : ∃ (a : α), some a ∈ c := ⟨_,h⟩, rw dif_pos h', have hh := classical.some_spec h', rw eq_of_chain hh h, simp } end end inst end part namespace pi variables {α : Type*} {β : α → Type*} {γ : Type*} /-- Function application `λ f, f a` is monotone with respect to `f` for fixed `a`. -/ @[simps] def monotone_apply [∀a, partial_order (β a)] (a : α) : (Πa, β a) →ₘ β a := { to_fun := (λf:Πa, β a, f a), monotone' := assume f g hfg, hfg a } open omega_complete_partial_order omega_complete_partial_order.chain instance [∀a, omega_complete_partial_order (β a)] : omega_complete_partial_order (Πa, β a) := { ωSup := λc a, ωSup (c.map (monotone_apply a)), ωSup_le := assume c f hf a, ωSup_le _ _ $ by { rintro i, apply hf }, le_ωSup := assume c i x, le_ωSup_of_le _ $ le_refl _ } namespace omega_complete_partial_order variables [∀ x, omega_complete_partial_order $ β x] variables [omega_complete_partial_order γ] lemma flip₁_continuous' (f : ∀ x : α, γ → β x) (a : α) (hf : continuous' (λ x y, f y x)) : continuous' (f a) := continuous.of_bundled _ (λ x y h, continuous.to_monotone hf h a) (λ c, congr_fun (continuous.to_bundled _ hf c) a) lemma flip₂_continuous' (f : γ → Π x, β x) (hf : ∀ x, continuous' (λ g, f g x)) : continuous' f := continuous.of_bundled _ (λ x y h a, continuous.to_monotone (hf a) h) (by intro c; ext a; apply continuous.to_bundled _ (hf a) c) end omega_complete_partial_order end pi namespace prod open omega_complete_partial_order variables {α : Type*} {β : Type*} {γ : Type*} variables [omega_complete_partial_order α] variables [omega_complete_partial_order β] variables [omega_complete_partial_order γ] /-- The supremum of a chain in the product `ω`-CPO. -/ @[simps] protected def ωSup (c : chain (α × β)) : α × β := (ωSup (c.map preorder_hom.prod.fst), ωSup (c.map preorder_hom.prod.snd)) @[simps ωSup_fst ωSup_snd] instance : omega_complete_partial_order (α × β) := { ωSup := prod.ωSup, ωSup_le := λ c ⟨x,x'⟩ h, ⟨ωSup_le _ _ $ λ i, (h i).1, ωSup_le _ _ $ λ i, (h i).2⟩, le_ωSup := λ c i, ⟨le_ωSup (c.map preorder_hom.prod.fst) i, le_ωSup (c.map preorder_hom.prod.snd) i⟩ } end prod namespace complete_lattice variables (α : Type u) /-- Any complete lattice has an `ω`-CPO structure where the countable supremum is a special case of arbitrary suprema. -/ @[priority 100] -- see Note [lower instance priority] instance [complete_lattice α] : omega_complete_partial_order α := { ωSup := λc, ⨆ i, c i, ωSup_le := λ ⟨c, _⟩ s hs, by simp only [supr_le_iff, preorder_hom.coe_fun_mk] at ⊢ hs; intros i; apply hs i, le_ωSup := assume ⟨c, _⟩ i, by simp only [preorder_hom.coe_fun_mk]; apply le_supr_of_le i; refl } variables {α} {β : Type v} [omega_complete_partial_order α] [complete_lattice β] open omega_complete_partial_order lemma inf_continuous [is_total β (≤)] (f g : α →ₘ β) (hf : continuous f) (hg : continuous g) : continuous (f ⊓ g) := begin intro c, apply eq_of_forall_ge_iff, intro z, simp only [inf_le_iff, hf c, hg c, ωSup_le_iff, ←forall_or_distrib_left, ←forall_or_distrib_right, function.comp_app, chain.map_coe, preorder_hom.has_inf_inf_coe], split, { introv h, apply h }, { intros h i j, apply or.imp _ _ (h (max i j)); apply le_trans; mono*, { apply le_max_left }, { apply le_max_right }, }, end lemma Sup_continuous (s : set $ α →ₘ β) (hs : ∀ f ∈ s, continuous f) : continuous (Sup s) := begin intro c, apply eq_of_forall_ge_iff, intro z, simp only [ωSup_le_iff, and_imp, preorder_hom.complete_lattice_Sup, set.mem_image, chain.map_coe, function.comp_app, Sup_le_iff, preorder_hom.has_Sup_Sup_coe, exists_imp_distrib], split; introv h hx hb; subst b, { apply le_trans _ (h _ _ hx rfl), mono, apply le_ωSup }, { rw [hs _ hx c, ωSup_le_iff], intro, apply h i _ x hx rfl, } end theorem Sup_continuous' : ∀s : set (α → β), (∀t∈s, omega_complete_partial_order.continuous' t) → omega_complete_partial_order.continuous' (Sup s) := begin introv ht, dsimp [continuous'], have : monotone (Sup s), { intros x y h, apply Sup_le_Sup_of_forall_exists_le, intro, simp only [and_imp, exists_prop, set.mem_range, set_coe.exists, subtype.coe_mk, exists_imp_distrib], intros f hfs hfx, subst hfx, refine ⟨f y, ⟨f, hfs, rfl⟩, _⟩, cases ht _ hfs with hf, apply hf h }, existsi this, let s' : set (α →ₘ β) := { f | ⇑f ∈ s }, suffices : omega_complete_partial_order.continuous (Sup s'), { convert this, ext, simp only [supr, has_Sup.Sup, Sup, set.image, set.mem_set_of_eq], congr, ext, simp only [exists_prop, set.mem_range, set_coe.exists, set.mem_set_of_eq, subtype.coe_mk], split, { rintro ⟨y,hy,hy'⟩, cases ht _ hy, refine ⟨⟨_, w⟩, hy, hy'⟩ }, tauto }, apply complete_lattice.Sup_continuous, intros f hf, specialize ht f hf, cases ht, exact ht_h, end lemma sup_continuous {f g : α →ₘ β} (hf : continuous f) (hg : continuous g) : continuous (f ⊔ g) := begin rw ← Sup_pair, apply Sup_continuous, simp only [or_imp_distrib, forall_and_distrib, set.mem_insert_iff, set.mem_singleton_iff, forall_eq], split; assumption, end lemma top_continuous : continuous (⊤ : α →ₘ β) := begin intro c, apply eq_of_forall_ge_iff, intro z, simp only [ωSup_le_iff, forall_const, chain.map_coe, function.comp_app, preorder_hom.has_top_top_coe], end lemma bot_continuous : continuous (⊥ : α →ₘ β) := begin intro c, apply eq_of_forall_ge_iff, intro z, simp only [ωSup_le_iff, forall_const, chain.map_coe, function.comp_app, preorder_hom.has_bot_bot_coe], end end complete_lattice namespace omega_complete_partial_order variables {α : Type u} {α' : Type*} {β : Type v} {β' : Type*} {γ : Type*} {φ : Type*} variables [omega_complete_partial_order α] [omega_complete_partial_order β] variables [omega_complete_partial_order γ] [omega_complete_partial_order φ] variables [omega_complete_partial_order α'] [omega_complete_partial_order β'] namespace preorder_hom /-- Function application `λ f, f a` (for fixed `a`) is a monotone function from the monotone function space `α →ₘ β` to `β`. -/ @[simps] def monotone_apply (a : α) : (α →ₘ β) →ₘ β := { to_fun := (λf : α →ₘ β, f a), monotone' := assume f g hfg, hfg a } /-- The "forgetful functor" from `α →ₘ β` to `α → β` that takes the underlying function, is monotone. -/ def to_fun_hom : (α →ₘ β) →ₘ (α → β) := { to_fun := λ f, f.to_fun, monotone' := λ x y h, h } /-- The `ωSup` operator for monotone functions. -/ @[simps] protected def ωSup (c : chain (α →ₘ β)) : α →ₘ β := { to_fun := λ a, ωSup (c.map (monotone_apply a)), monotone' := λ x y h, ωSup_le_ωSup_of_le (chain.map_le_map _ $ λ a, a.monotone h) } @[simps ωSup_coe] instance omega_complete_partial_order : omega_complete_partial_order (α →ₘ β) := omega_complete_partial_order.lift preorder_hom.to_fun_hom preorder_hom.ωSup (λ x y h, h) (λ c, rfl) end preorder_hom section old_struct set_option old_structure_cmd true variables (α β) /-- A monotone function on `ω`-continuous partial orders is said to be continuous if for every chain `c : chain α`, `f (⊔ i, c i) = ⊔ i, f (c i)`. This is just the bundled version of `preorder_hom.continuous`. -/ structure continuous_hom extends preorder_hom α β := (cont : continuous (preorder_hom.mk to_fun monotone')) attribute [nolint doc_blame] continuous_hom.to_preorder_hom infixr ` →𝒄 `:25 := continuous_hom -- Input: \r\MIc instance : has_coe_to_fun (α →𝒄 β) := { F := λ _, α → β, coe := continuous_hom.to_fun } instance : has_coe (α →𝒄 β) (α →ₘ β) := { coe := continuous_hom.to_preorder_hom } instance : partial_order (α →𝒄 β) := partial_order.lift continuous_hom.to_fun $ by rintro ⟨⟩ ⟨⟩ h; congr; exact h end old_struct namespace continuous_hom theorem congr_fun {f g : α →𝒄 β} (h : f = g) (x : α) : f x = g x := congr_arg (λ h : α →𝒄 β, h x) h theorem congr_arg (f : α →𝒄 β) {x y : α} (h : x = y) : f x = f y := congr_arg (λ x : α, f x) h @[mono] lemma monotone (f : α →𝒄 β) : monotone f := continuous_hom.monotone' f lemma ite_continuous' {p : Prop} [hp : decidable p] (f g : α → β) (hf : continuous' f) (hg : continuous' g) : continuous' (λ x, if p then f x else g x) := by split_ifs; simp * lemma ωSup_bind {β γ : Type v} (c : chain α) (f : α →ₘ part β) (g : α →ₘ β → part γ) : ωSup (c.map (f.bind g)) = ωSup (c.map f) >>= ωSup (c.map g) := begin apply eq_of_forall_ge_iff, intro x, simp only [ωSup_le_iff, part.bind_le, chain.mem_map_iff, and_imp, preorder_hom.bind_coe, exists_imp_distrib], split; intro h''', { intros b hb, apply ωSup_le _ _ _, rintros i y hy, simp only [part.mem_ωSup] at hb, rcases hb with ⟨j,hb⟩, replace hb := hb.symm, simp only [part.eq_some_iff, chain.map_coe, function.comp_app, pi.monotone_apply_coe] at hy hb, replace hb : b ∈ f (c (max i j)) := f.monotone (c.monotone (le_max_right i j)) _ hb, replace hy : y ∈ g (c (max i j)) b := g.monotone (c.monotone (le_max_left i j)) _ _ hy, apply h''' (max i j), simp only [exists_prop, part.bind_eq_bind, part.mem_bind_iff, chain.map_coe, function.comp_app, preorder_hom.bind_coe], exact ⟨_,hb,hy⟩, }, { intros i, intros y hy, simp only [exists_prop, part.bind_eq_bind, part.mem_bind_iff, chain.map_coe, function.comp_app, preorder_hom.bind_coe] at hy, rcases hy with ⟨b,hb₀,hb₁⟩, apply h''' b _, { apply le_ωSup (c.map g) _ _ _ hb₁ }, { apply le_ωSup (c.map f) i _ hb₀ } }, end lemma bind_continuous' {β γ : Type v} (f : α → part β) (g : α → β → part γ) : continuous' f → continuous' g → continuous' (λ x, f x >>= g x) | ⟨hf,hf'⟩ ⟨hg,hg'⟩ := continuous.of_bundled' (preorder_hom.bind ⟨f,hf⟩ ⟨g,hg⟩) (by intro c; rw [ωSup_bind, ← hf', ← hg']; refl) lemma map_continuous' {β γ : Type v} (f : β → γ) (g : α → part β) (hg : continuous' g) : continuous' (λ x, f <$> g x) := by simp only [map_eq_bind_pure_comp]; apply bind_continuous' _ _ hg; apply const_continuous' lemma seq_continuous' {β γ : Type v} (f : α → part (β → γ)) (g : α → part β) (hf : continuous' f) (hg : continuous' g) : continuous' (λ x, f x <*> g x) := by simp only [seq_eq_bind_map]; apply bind_continuous' _ _ hf; apply pi.omega_complete_partial_order.flip₂_continuous'; intro; apply map_continuous' _ _ hg lemma continuous (F : α →𝒄 β) (C : chain α) : F (ωSup C) = ωSup (C.map F) := continuous_hom.cont _ _ /-- Construct a continuous function from a bare function, a continuous function, and a proof that they are equal. -/ @[simps, reducible] def of_fun (f : α → β) (g : α →𝒄 β) (h : f = g) : α →𝒄 β := by refine {to_fun := f, ..}; subst h; cases g; assumption /-- Construct a continuous function from a monotone function with a proof of continuity. -/ @[simps, reducible] def of_mono (f : α →ₘ β) (h : ∀ c : chain α, f (ωSup c) = ωSup (c.map f)) : α →𝒄 β := { to_fun := f, monotone' := f.monotone, cont := h } /-- The identity as a continuous function. -/ @[simps] def id : α →𝒄 α := of_mono preorder_hom.id (by intro; rw [chain.map_id]; refl) /-- The composition of continuous functions. -/ @[simps] def comp (f : β →𝒄 γ) (g : α →𝒄 β) : α →𝒄 γ := of_mono (preorder_hom.comp (↑f) (↑g)) (by intro; rw [preorder_hom.comp, ← preorder_hom.comp, ← chain.map_comp, ← f.continuous, ← g.continuous]; refl) @[ext] protected lemma ext (f g : α →𝒄 β) (h : ∀ x, f x = g x) : f = g := by cases f; cases g; congr; ext; apply h protected lemma coe_inj (f g : α →𝒄 β) (h : (f : α → β) = g) : f = g := continuous_hom.ext _ _ $ _root_.congr_fun h @[simp] lemma comp_id (f : β →𝒄 γ) : f.comp id = f := by ext; refl @[simp] lemma id_comp (f : β →𝒄 γ) : id.comp f = f := by ext; refl @[simp] lemma comp_assoc (f : γ →𝒄 φ) (g : β →𝒄 γ) (h : α →𝒄 β) : f.comp (g.comp h) = (f.comp g).comp h := by ext; refl @[simp] lemma coe_apply (a : α) (f : α →𝒄 β) : (f : α →ₘ β) a = f a := rfl /-- `function.const` is a continuous function. -/ def const (f : β) : α →𝒄 β := of_mono (preorder_hom.const _ f) begin intro c, apply le_antisymm, { simp only [function.const, preorder_hom.const_coe], apply le_ωSup_of_le 0, refl }, { apply ωSup_le, simp only [preorder_hom.const_coe, chain.map_coe, function.comp_app], intros, refl }, end @[simp] theorem const_apply (f : β) (a : α) : const f a = f := rfl instance [inhabited β] : inhabited (α →𝒄 β) := ⟨ const (default β) ⟩ namespace prod /-- The application of continuous functions as a monotone function. (It would make sense to make it a continuous function, but we are currently constructing a `omega_complete_partial_order` instance for `α →𝒄 β`, and we cannot use it as the domain or image of a continuous function before we do.) -/ @[simps] def apply : (α →𝒄 β) × α →ₘ β := { to_fun := λ f, f.1 f.2, monotone' := λ x y h, by dsimp; transitivity y.fst x.snd; [apply h.1, apply y.1.monotone h.2] } end prod /-- The map from continuous functions to monotone functions is itself a monotone function. -/ @[simps] def to_mono : (α →𝒄 β) →ₘ (α →ₘ β) := { to_fun := λ f, f, monotone' := λ x y h, h } /-- When proving that a chain of applications is below a bound `z`, it suffices to consider the functions and values being selected from the same index in the chains. This lemma is more specific than necessary, i.e. `c₀` only needs to be a chain of monotone functions, but it is only used with continuous functions. -/ @[simp] lemma forall_forall_merge (c₀ : chain (α →𝒄 β)) (c₁ : chain α) (z : β) : (∀ (i j : ℕ), (c₀ i) (c₁ j) ≤ z) ↔ ∀ (i : ℕ), (c₀ i) (c₁ i) ≤ z := begin split; introv h, { apply h }, { apply le_trans _ (h (max i j)), transitivity c₀ i (c₁ (max i j)), { apply (c₀ i).monotone, apply c₁.monotone, apply le_max_right }, { apply c₀.monotone, apply le_max_left } } end @[simp] lemma forall_forall_merge' (c₀ : chain (α →𝒄 β)) (c₁ : chain α) (z : β) : (∀ (j i : ℕ), (c₀ i) (c₁ j) ≤ z) ↔ ∀ (i : ℕ), (c₀ i) (c₁ i) ≤ z := by rw [forall_swap,forall_forall_merge] /-- The `ωSup` operator for continuous functions, which takes the pointwise countable supremum of the functions in the `ω`-chain. -/ @[simps] protected def ωSup (c : chain (α →𝒄 β)) : α →𝒄 β := continuous_hom.of_mono (ωSup $ c.map to_mono) begin intro c', apply eq_of_forall_ge_iff, intro z, simp only [ωSup_le_iff, (c _).continuous, chain.map_coe, preorder_hom.monotone_apply_coe, to_mono_coe, coe_apply, preorder_hom.omega_complete_partial_order_ωSup_coe, forall_forall_merge, forall_forall_merge', function.comp_app], end @[simps ωSup] instance : omega_complete_partial_order (α →𝒄 β) := omega_complete_partial_order.lift continuous_hom.to_mono continuous_hom.ωSup (λ x y h, h) (λ c, rfl) lemma ωSup_def (c : chain (α →𝒄 β)) (x : α) : ωSup c x = continuous_hom.ωSup c x := rfl lemma ωSup_ωSup (c₀ : chain (α →𝒄 β)) (c₁ : chain α) : ωSup c₀ (ωSup c₁) = ωSup (continuous_hom.prod.apply.comp $ c₀.zip c₁) := begin apply eq_of_forall_ge_iff, intro z, simp only [ωSup_le_iff, (c₀ _).continuous, chain.map_coe, to_mono_coe, coe_apply, preorder_hom.omega_complete_partial_order_ωSup_coe, ωSup_def, forall_forall_merge, chain.zip_coe, preorder_hom.prod.map_coe, preorder_hom.prod.diag_coe, prod.map_mk, preorder_hom.monotone_apply_coe, function.comp_app, prod.apply_coe, preorder_hom.comp_coe, ωSup_to_fun], end /-- A family of continuous functions yields a continuous family of functions. -/ @[simps] def flip {α : Type*} (f : α → β →𝒄 γ) : β →𝒄 α → γ := { to_fun := λ x y, f y x, monotone' := λ x y h a, (f a).monotone h, cont := by intro; ext; change f x _ = _; rw [(f x).continuous ]; refl, } /-- `part.bind` as a continuous function. -/ @[simps { rhs_md := reducible }] noncomputable def bind {β γ : Type v} (f : α →𝒄 part β) (g : α →𝒄 β → part γ) : α →𝒄 part γ := of_mono (preorder_hom.bind (↑f) (↑g)) $ λ c, begin rw [preorder_hom.bind, ← preorder_hom.bind, ωSup_bind, ← f.continuous, ← g.continuous], refl end /-- `part.map` as a continuous function. -/ @[simps {rhs_md := reducible}] noncomputable def map {β γ : Type v} (f : β → γ) (g : α →𝒄 part β) : α →𝒄 part γ := of_fun (λ x, f <$> g x) (bind g (const (pure ∘ f))) $ by ext; simp only [map_eq_bind_pure_comp, bind_to_fun, preorder_hom.bind_coe, const_apply, preorder_hom.const_coe, coe_apply] /-- `part.seq` as a continuous function. -/ @[simps {rhs_md := reducible}] noncomputable def seq {β γ : Type v} (f : α →𝒄 part (β → γ)) (g : α →𝒄 part β) : α →𝒄 part γ := of_fun (λ x, f x <*> g x) (bind f $ (flip $ _root_.flip map g)) (by ext; simp only [seq_eq_bind_map, flip, part.bind_eq_bind, map_to_fun, part.mem_bind_iff, bind_to_fun, preorder_hom.bind_coe, coe_apply, flip_to_fun]; refl) end continuous_hom end omega_complete_partial_order
b9ed56683912445f7b7f63dc8ac945e73b9335f9
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/computability/tm_to_partrec.lean
01057905a87c1cb15038482eda57e3347b53f2ad
[ "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
81,007
lean
/- Copyright (c) 2020 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import computability.halting import computability.turing_machine import data.num.lemmas import tactic.derive_fintype /-! # Modelling partial recursive functions using Turing machines This file defines a simplified basis for partial recursive functions, and a `turing.TM2` model Turing machine for evaluating these functions. This amounts to a constructive proof that every `partrec` function can be evaluated by a Turing machine. ## Main definitions * `to_partrec.code`: a simplified basis for partial recursive functions, valued in `list ℕ →. list ℕ`. * `to_partrec.code.eval`: semantics for a `to_partrec.code` program * `partrec_to_TM2.tr`: A TM2 turing machine which can evaluate `code` programs -/ open function (update) open relation namespace turing /-! ## A simplified basis for partrec This section constructs the type `code`, which is a data type of programs with `list ℕ` input and output, with enough expressivity to write any partial recursive function. The primitives are: * `zero'` appends a `0` to the input. That is, `zero' v = 0 :: v`. * `succ` returns the successor of the head of the input, defaulting to zero if there is no head: * `succ [] = [1]` * `succ (n :: v) = [n + 1]` * `tail` returns the tail of the input * `tail [] = []` * `tail (n :: v) = v` * `cons f fs` calls `f` and `fs` on the input and conses the results: * `cons f fs v = (f v).head :: fs v` * `comp f g` calls `f` on the output of `g`: * `comp f g v = f (g v)` * `case f g` cases on the head of the input, calling `f` or `g` depending on whether it is zero or a successor (similar to `nat.cases_on`). * `case f g [] = f []` * `case f g (0 :: v) = f v` * `case f g (n+1 :: v) = g (n :: v)` * `fix f` calls `f` repeatedly, using the head of the result of `f` to decide whether to call `f` again or finish: * `fix f v = []` if `f v = []` * `fix f v = w` if `f v = 0 :: w` * `fix f v = fix f w` if `f v = n+1 :: w` (the exact value of `n` is discarded) This basis is convenient because it is closer to the Turing machine model - the key operations are splitting and merging of lists of unknown length, while the messy `n`-ary composition operation from the traditional basis for partial recursive functions is absent - but it retains a compositional semantics. The first step in transitioning to Turing machines is to make a sequential evaluator for this basis, which we take up in the next section. -/ namespace to_partrec /-- The type of codes for primitive recursive functions. Unlike `nat.partrec.code`, this uses a set of operations on `list ℕ`. See `code.eval` for a description of the behavior of the primitives. -/ @[derive [decidable_eq, inhabited]] inductive code | zero' | succ | tail | cons : code → code → code | comp : code → code → code | case : code → code → code | fix : code → code /-- The semantics of the `code` primitives, as partial functions `list ℕ →. list ℕ`. By convention we functions that return a single result return a singleton `[n]`, or in some cases `n :: v` where `v` will be ignored by a subsequent function. * `zero'` appends a `0` to the input. That is, `zero' v = 0 :: v`. * `succ` returns the successor of the head of the input, defaulting to zero if there is no head: * `succ [] = [1]` * `succ (n :: v) = [n + 1]` * `tail` returns the tail of the input * `tail [] = []` * `tail (n :: v) = v` * `cons f fs` calls `f` and `fs` on the input and conses the results: * `cons f fs v = (f v).head :: fs v` * `comp f g` calls `f` on the output of `g`: * `comp f g v = f (g v)` * `case f g` cases on the head of the input, calling `f` or `g` depending on whether it is zero or a successor (similar to `nat.cases_on`). * `case f g [] = f []` * `case f g (0 :: v) = f v` * `case f g (n+1 :: v) = g (n :: v)` * `fix f` calls `f` repeatedly, using the head of the result of `f` to decide whether to call `f` again or finish: * `fix f v = []` if `f v = []` * `fix f v = w` if `f v = 0 :: w` * `fix f v = fix f w` if `f v = n+1 :: w` (the exact value of `n` is discarded) -/ @[simp] def code.eval : code → list ℕ →. list ℕ | code.zero' := λ v, pure (0 :: v) | code.succ := λ v, pure [v.head.succ] | code.tail := λ v, pure v.tail | (code.cons f fs) := λ v, do n ← code.eval f v, ns ← code.eval fs v, pure (n.head :: ns) | (code.comp f g) := λ v, g.eval v >>= f.eval | (code.case f g) := λ v, v.head.elim (f.eval v.tail) (λ y _, g.eval (y :: v.tail)) | (code.fix f) := pfun.fix $ λ v, (f.eval v).map $ λ v, if v.head = 0 then sum.inl v.tail else sum.inr v.tail namespace code /-- `nil` is the constant nil function: `nil v = []`. -/ def nil : code := tail.comp succ @[simp] theorem nil_eval (v) : nil.eval v = pure [] := by simp [nil] /-- `id` is the identity function: `id v = v`. -/ def id : code := tail.comp zero' @[simp] theorem id_eval (v) : id.eval v = pure v := by simp [id] /-- `head` gets the head of the input list: `head [] = [0]`, `head (n :: v) = [n]`. -/ def head : code := cons id nil @[simp] theorem head_eval (v) : head.eval v = pure [v.head] := by simp [head] /-- `zero` is the constant zero function: `zero v = [0]`. -/ def zero : code := cons zero' nil @[simp] theorem zero_eval (v) : zero.eval v = pure [0] := by simp [zero] /-- `pred` returns the predecessor of the head of the input: `pred [] = [0]`, `pred (0 :: v) = [0]`, `pred (n+1 :: v) = [n]`. -/ def pred : code := case zero head @[simp] theorem pred_eval (v) : pred.eval v = pure [v.head.pred] := by simp [pred]; cases v.head; simp /-- `rfind f` performs the function of the `rfind` primitive of partial recursive functions. `rfind f v` returns the smallest `n` such that `(f (n :: v)).head = 0`. It is implemented as: rfind f v = pred (fix (λ (n::v), f (n::v) :: n+1 :: v) (0 :: v)) The idea is that the initial state is `0 :: v`, and the `fix` keeps `n :: v` as its internal state; it calls `f (n :: v)` as the exit test and `n+1 :: v` as the next state. At the end we get `n+1 :: v` where `n` is the desired output, and `pred (n+1 :: v) = [n]` returns the result. -/ def rfind (f : code) : code := comp pred $ comp (fix $ cons f $ cons succ tail) zero' /-- `prec f g` implements the `prec` (primitive recursion) operation of partial recursive functions. `prec f g` evaluates as: * `prec f g [] = [f []]` * `prec f g (0 :: v) = [f v]` * `prec f g (n+1 :: v) = [g (n :: prec f g (n :: v) :: v)]` It is implemented as: G (a :: b :: IH :: v) = (b :: a+1 :: b-1 :: g (a :: IH :: v) :: v) F (0 :: f_v :: v) = (f_v :: v) F (n+1 :: f_v :: v) = (fix G (0 :: n :: f_v :: v)).tail.tail prec f g (a :: v) = [(F (a :: f v :: v)).head] Because `fix` always evaluates its body at least once, we must special case the `0` case to avoid calling `g` more times than necessary (which could be bad if `g` diverges). If the input is `0 :: v`, then `F (0 :: f v :: v) = (f v :: v)` so we return `[f v]`. If the input is `n+1 :: v`, we evaluate the function from the bottom up, with initial state `0 :: n :: f v :: v`. The first number counts up, providing arguments for the applications to `g`, while the second number counts down, providing the exit condition (this is the initial `b` in the return value of `G`, which is stripped by `fix`). After the `fix` is complete, the final state is `n :: 0 :: res :: v` where `res` is the desired result, and the rest reduces this to `[res]`. -/ def prec (f g : code) : code := let G := cons tail $ cons succ $ cons (comp pred tail) $ cons (comp g $ cons id $ comp tail tail) $ comp tail $ comp tail tail in let F := case id $ comp (comp (comp tail tail) (fix G)) zero' in cons (comp F (cons head $ cons (comp f tail) tail)) nil local attribute [-simp] part.bind_eq_bind part.map_eq_map part.pure_eq_some theorem exists_code.comp {m n} {f : vector ℕ n →. ℕ} {g : fin n → vector ℕ m →. ℕ} (hf : ∃ c : code, ∀ v : vector ℕ n, c.eval v.1 = pure <$> f v) (hg : ∀ i, ∃ c : code, ∀ v : vector ℕ m, c.eval v.1 = pure <$> g i v) : ∃ c : code, ∀ v : vector ℕ m, c.eval v.1 = pure <$> (vector.m_of_fn (λ i, g i v) >>= f) := begin suffices : ∃ c : code, ∀ v : vector ℕ m, c.eval v.1 = subtype.val <$> vector.m_of_fn (λ i, g i v), { obtain ⟨cf, hf⟩ := hf, obtain ⟨cg, hg⟩ := this, exact ⟨cf.comp cg, λ v, by { simp [hg, hf, map_bind, seq_bind_eq, (∘), -subtype.val_eq_coe], refl }⟩ }, clear hf f, induction n with n IH, { exact ⟨nil, λ v, by simp [vector.m_of_fn]; refl⟩ }, { obtain ⟨cg, hg₁⟩ := hg 0, obtain ⟨cl, hl⟩ := IH (λ i, hg i.succ), exact ⟨cons cg cl, λ v, by { simp [vector.m_of_fn, hg₁, map_bind, seq_bind_eq, bind_assoc, (∘), hl, -subtype.val_eq_coe], refl }⟩ }, end theorem exists_code {n} {f : vector ℕ n →. ℕ} (hf : nat.partrec' f) : ∃ c : code, ∀ v : vector ℕ n, c.eval v.1 = pure <$> f v := begin induction hf with n f hf, induction hf, case prim zero { exact ⟨zero', λ ⟨[], _⟩, rfl⟩ }, case prim succ { exact ⟨succ, λ ⟨[v], _⟩, rfl⟩ }, case prim nth : n i { refine fin.succ_rec (λ n, _) (λ n i IH, _) i, { exact ⟨head, λ ⟨list.cons a as, _⟩, by simp; refl⟩ }, { obtain ⟨c, h⟩ := IH, exact ⟨c.comp tail, λ v, by simpa [← vector.nth_tail] using h v.tail⟩ } }, case prim comp : m n f g hf hg IHf IHg { simpa [part.bind_eq_bind] using exists_code.comp IHf IHg }, case prim prec : n f g hf hg IHf IHg { obtain ⟨cf, hf⟩ := IHf, obtain ⟨cg, hg⟩ := IHg, simp only [part.map_eq_map, part.map_some, pfun.coe_val] at hf hg, refine ⟨prec cf cg, λ v, _⟩, rw ← v.cons_head_tail, specialize hf v.tail, replace hg := λ a b, hg (a ::ᵥ b ::ᵥ v.tail), simp only [vector.cons_val, vector.tail_val] at hf hg, simp only [part.map_eq_map, part.map_some, vector.cons_val, vector.cons_tail, vector.cons_head, pfun.coe_val, vector.tail_val], simp only [← part.pure_eq_some] at hf hg ⊢, induction v.head with n IH; simp [prec, hf, bind_assoc, ← part.map_eq_map, ← bind_pure_comp_eq_map, show ∀ x, pure x = [x], from λ _, rfl, -subtype.val_eq_coe], suffices : ∀ a b, a + b = n → (n.succ :: 0 :: g (n ::ᵥ (nat.elim (f v.tail) (λ y IH, g (y ::ᵥ IH ::ᵥ v.tail)) n) ::ᵥ v.tail) :: v.val.tail : list ℕ) ∈ pfun.fix (λ v : list ℕ, do x ← cg.eval (v.head :: v.tail.tail), pure $ if v.tail.head = 0 then sum.inl (v.head.succ :: v.tail.head.pred :: x.head :: v.tail.tail.tail : list ℕ) else sum.inr (v.head.succ :: v.tail.head.pred :: x.head :: v.tail.tail.tail)) (a :: b :: nat.elim (f v.tail) (λ y IH, g (y ::ᵥ IH ::ᵥ v.tail)) a :: v.val.tail), { rw (_ : pfun.fix _ _ = pure _), swap, exact part.eq_some_iff.2 (this 0 n (zero_add n)), simp only [list.head, pure_bind, list.tail_cons] }, intros a b e, induction b with b IH generalizing a e, { refine pfun.mem_fix_iff.2 (or.inl $ part.eq_some_iff.1 _), simp only [hg, ← e, pure_bind, list.tail_cons], refl }, { refine pfun.mem_fix_iff.2 (or.inr ⟨_, _, IH (a+1) (by rwa add_right_comm)⟩), simp only [hg, eval, pure_bind, nat.elim_succ, list.tail], exact part.mem_some_iff.2 rfl } }, case comp : m n f g hf hg IHf IHg { exact exists_code.comp IHf IHg }, case rfind : n f hf IHf { obtain ⟨cf, hf⟩ := IHf, refine ⟨rfind cf, λ v, _⟩, replace hf := λ a, hf (a ::ᵥ v), simp only [part.map_eq_map, part.map_some, vector.cons_val, pfun.coe_val, show ∀ x, pure x = [x], from λ _, rfl] at hf ⊢, refine part.ext (λ x, _), simp only [rfind, part.bind_eq_bind, part.pure_eq_some, part.map_eq_map, part.bind_some, exists_prop, eval, list.head, pred_eval, part.map_some, bool.ff_eq_to_bool_iff, part.mem_bind_iff, list.length, part.mem_map_iff, nat.mem_rfind, list.tail, bool.tt_eq_to_bool_iff, part.mem_some_iff, part.map_bind], split, { rintro ⟨v', h1, rfl⟩, suffices : ∀ (v₁ : list ℕ), v' ∈ pfun.fix (λ v, (cf.eval v).bind $ λ y, part.some $ if y.head = 0 then sum.inl (v.head.succ :: v.tail) else sum.inr (v.head.succ :: v.tail)) v₁ → ∀ n, v₁ = n :: v.val → (∀ m < n, ¬f (m ::ᵥ v) = 0) → (∃ (a : ℕ), (f (a ::ᵥ v) = 0 ∧ ∀ {m : ℕ}, m < a → ¬f (m ::ᵥ v) = 0) ∧ [a] = [v'.head.pred]), { exact this _ h1 0 rfl (by rintro _ ⟨⟩) }, clear h1, intros v₀ h1, refine pfun.fix_induction h1 (λ v₁ h2 IH, _), clear h1, rintro n rfl hm, have := pfun.mem_fix_iff.1 h2, simp only [hf, part.bind_some] at this, split_ifs at this, { simp only [list.head, exists_false, or_false, part.mem_some_iff, list.tail_cons, false_and] at this, subst this, exact ⟨_, ⟨h, hm⟩, rfl⟩ }, { simp only [list.head, exists_eq_left, part.mem_some_iff, list.tail_cons, false_or] at this, refine IH _ this (by simp * at *) _ rfl (λ m h', _), obtain h|rfl := nat.lt_succ_iff_lt_or_eq.1 h', exacts [hm _ h, h] } }, { rintro ⟨n, ⟨hn, hm⟩, rfl⟩, refine ⟨n.succ :: v.1, _, rfl⟩, have : (n.succ :: v.1 : list ℕ) ∈ pfun.fix (λ v, (cf.eval v).bind $ λ y, part.some $ if y.head = 0 then sum.inl (v.head.succ :: v.tail) else sum.inr (v.head.succ :: v.tail)) (n :: v.val) := pfun.mem_fix_iff.2 (or.inl (by simp [hf, hn, -subtype.val_eq_coe])), generalize_hyp : (n.succ :: v.1 : list ℕ) = w at this ⊢, clear hn, induction n with n IH, {exact this}, refine IH (λ m h', hm (nat.lt_succ_of_lt h')) (pfun.mem_fix_iff.2 (or.inr ⟨_, _, this⟩)), simp only [hf, hm n.lt_succ_self, part.bind_some, list.head, eq_self_iff_true, if_false, part.mem_some_iff, and_self, list.tail_cons] } } end end code /-! ## From compositional semantics to sequential semantics Our initial sequential model is designed to be as similar as possible to the compositional semantics in terms of its primitives, but it is a sequential semantics, meaning that rather than defining an `eval c : list ℕ →. list ℕ` function for each program, defined by recursion on programs, we have a type `cfg` with a step function `step : cfg → option cfg` that provides a deterministic evaluation order. In order to do this, we introduce the notion of a *continuation*, which can be viewed as a `code` with a hole in it where evaluation is currently taking place. Continuations can be assigned a `list ℕ →. list ℕ` semantics as well, with the interpretation being that given a `list ℕ` result returned from the code in the hole, the remainder of the program will evaluate to a `list ℕ` final value. The continuations are: * `halt`: the empty continuation: the hole is the whole program, whatever is returned is the final result. In our notation this is just `_`. * `cons₁ fs v k`: evaluating the first part of a `cons`, that is `k (_ :: fs v)`, where `k` is the outer continuation. * `cons₂ ns k`: evaluating the second part of a `cons`: `k (ns.head :: _)`. (Technically we don't need to hold on to all of `ns` here since we are already committed to taking the head, but this is more regular.) * `comp f k`: evaluating the first part of a composition: `k (f _)`. * `fix f k`: waiting for the result of `f` in a `fix f` expression: `k (if _.head = 0 then _.tail else fix f (_.tail))` The type `cfg` of evaluation states is: * `ret k v`: we have received a result, and are now evaluating the continuation `k` with result `v`; that is, `k v` where `k` is ready to evaluate. * `halt v`: we are done and the result is `v`. The main theorem of this section is that for each code `c`, the state `step_normal c halt v` steps to `v'` in finitely many steps if and only if `code.eval c v = some v'`. -/ /-- The type of continuations, built up during evaluation of a `code` expression. -/ @[derive inhabited] inductive cont | halt | cons₁ : code → list ℕ → cont → cont | cons₂ : list ℕ → cont → cont | comp : code → cont → cont | fix : code → cont → cont /-- The semantics of a continuation. -/ def cont.eval : cont → list ℕ →. list ℕ | cont.halt := pure | (cont.cons₁ fs as k) := λ v, do ns ← code.eval fs as, cont.eval k (v.head :: ns) | (cont.cons₂ ns k) := λ v, cont.eval k (ns.head :: v) | (cont.comp f k) := λ v, code.eval f v >>= cont.eval k | (cont.fix f k) := λ v, if v.head = 0 then k.eval v.tail else f.fix.eval v.tail >>= k.eval /-- The set of configurations of the machine: * `halt v`: The machine is about to stop and `v : list ℕ` is the result. * `ret k v`: The machine is about to pass `v : list ℕ` to continuation `k : cont`. We don't have a state corresponding to normal evaluation because these are evaluated immediately to a `ret` "in zero steps" using the `step_normal` function. -/ @[derive inhabited] inductive cfg | halt : list ℕ → cfg | ret : cont → list ℕ → cfg /-- Evaluating `c : code` in a continuation `k : cont` and input `v : list ℕ`. This goes by recursion on `c`, building an augmented continuation and a value to pass to it. * `zero' v = 0 :: v` evaluates immediately, so we return it to the parent continuation * `succ v = [v.head.succ]` evaluates immediately, so we return it to the parent continuation * `tail v = v.tail` evaluates immediately, so we return it to the parent continuation * `cons f fs v = (f v).head :: fs v` requires two sub-evaluations, so we evaluate `f v` in the continuation `k (_.head :: fs v)` (called `cont.cons₁ fs v k`) * `comp f g v = f (g v)` requires two sub-evaluations, so we evaluate `g v` in the continuation `k (f _)` (called `cont.comp f k`) * `case f g v = v.head.cases_on (f v.tail) (λ n, g (n :: v.tail))` has the information needed to evaluate the case statement, so we do that and transition to either `f v` or `g (n :: v.tail)`. * `fix f v = let v' := f v in if v'.head = 0 then k v'.tail else fix f v'.tail` needs to first evaluate `f v`, so we do that and leave the rest for the continuation (called `cont.fix f k`) -/ def step_normal : code → cont → list ℕ → cfg | code.zero' k v := cfg.ret k (0 :: v) | code.succ k v := cfg.ret k [v.head.succ] | code.tail k v := cfg.ret k v.tail | (code.cons f fs) k v := step_normal f (cont.cons₁ fs v k) v | (code.comp f g) k v := step_normal g (cont.comp f k) v | (code.case f g) k v := v.head.elim (step_normal f k v.tail) (λ y _, step_normal g k (y :: v.tail)) | (code.fix f) k v := step_normal f (cont.fix f k) v /-- Evaluating a continuation `k : cont` on input `v : list ℕ`. This is the second part of evaluation, when we receive results from continuations built by `step_normal`. * `cont.halt v = v`, so we are done and transition to the `cfg.halt v` state * `cont.cons₁ fs as k v = k (v.head :: fs as)`, so we evaluate `fs as` now with the continuation `k (v.head :: _)` (called `cons₂ v k`). * `cont.cons₂ ns k v = k (ns.head :: v)`, where we now have everything we need to evaluate `ns.head :: v`, so we return it to `k`. * `cont.comp f k v = k (f v)`, so we call `f v` with `k` as the continuation. * `cont.fix f k v = k (if v.head = 0 then k v.tail else fix f v.tail)`, where `v` is a value, so we evaluate the if statement and either call `k` with `v.tail`, or call `fix f v` with `k` as the continuation (which immediately calls `f` with `cont.fix f k` as the continuation). -/ def step_ret : cont → list ℕ → cfg | cont.halt v := cfg.halt v | (cont.cons₁ fs as k) v := step_normal fs (cont.cons₂ v k) as | (cont.cons₂ ns k) v := step_ret k (ns.head :: v) | (cont.comp f k) v := step_normal f k v | (cont.fix f k) v := if v.head = 0 then step_ret k v.tail else step_normal f (cont.fix f k) v.tail /-- If we are not done (in `cfg.halt` state), then we must be still stuck on a continuation, so this main loop calls `step_ret` with the new continuation. The overall `step` function transitions from one `cfg` to another, only halting at the `cfg.halt` state. -/ def step : cfg → option cfg | (cfg.halt _) := none | (cfg.ret k v) := some (step_ret k v) /-- In order to extract a compositional semantics from the sequential execution behavior of configurations, we observe that continuations have a monoid structure, with `cont.halt` as the unit and `cont.then` as the multiplication. `cont.then k₁ k₂` runs `k₁` until it halts, and then takes the result of `k₁` and passes it to `k₂`. We will not prove it is associative (although it is), but we are instead interested in the associativity law `k₂ (eval c k₁) = eval c (k₁.then k₂)`. This holds at both the sequential and compositional levels, and allows us to express running a machine without the ambient continuation and relate it to the original machine's evaluation steps. In the literature this is usually where one uses Turing machines embedded inside other Turing machines, but this approach allows us to avoid changing the ambient type `cfg` in the middle of the recursion. -/ def cont.then : cont → cont → cont | cont.halt k' := k' | (cont.cons₁ fs as k) k' := cont.cons₁ fs as (k.then k') | (cont.cons₂ ns k) k' := cont.cons₂ ns (k.then k') | (cont.comp f k) k' := cont.comp f (k.then k') | (cont.fix f k) k' := cont.fix f (k.then k') theorem cont.then_eval {k k' : cont} {v} : (k.then k').eval v = k.eval v >>= k'.eval := begin induction k generalizing v; simp only [cont.eval, cont.then, bind_assoc, pure_bind, *], { simp only [← k_ih] }, { split_ifs; [refl, simp only [← k_ih, bind_assoc]] } end /-- The `then k` function is a "configuration homomorphism". Its operation on states is to append `k` to the continuation of a `cfg.ret` state, and to run `k` on `v` if we are in the `cfg.halt v` state. -/ def cfg.then : cfg → cont → cfg | (cfg.halt v) k' := step_ret k' v | (cfg.ret k v) k' := cfg.ret (k.then k') v /-- The `step_normal` function respects the `then k'` homomorphism. Note that this is an exact equality, not a simulation; the original and embedded machines move in lock-step until the embedded machine reaches the halt state. -/ theorem step_normal_then (c) (k k' : cont) (v) : step_normal c (k.then k') v = (step_normal c k v).then k' := begin induction c with generalizing k v; simp only [cont.then, step_normal, cfg.then, *] {constructor_eq := ff}, case turing.to_partrec.code.cons : c c' ih ih' { rw [← ih, cont.then] }, case turing.to_partrec.code.comp : c c' ih ih' { rw [← ih', cont.then] }, { cases v.head; simp only [nat.elim] }, case turing.to_partrec.code.fix : c ih { rw [← ih, cont.then] }, end /-- The `step_ret` function respects the `then k'` homomorphism. Note that this is an exact equality, not a simulation; the original and embedded machines move in lock-step until the embedded machine reaches the halt state. -/ theorem step_ret_then {k k' : cont} {v} : step_ret (k.then k') v = (step_ret k v).then k' := begin induction k generalizing v; simp only [cont.then, step_ret, cfg.then, *], { rw ← step_normal_then, refl }, { rw ← step_normal_then }, { split_ifs, {rw ← k_ih}, {rw ← step_normal_then, refl} }, end /-- This is a temporary definition, because we will prove in `code_is_ok` that it always holds. It asserts that `c` is semantically correct; that is, for any `k` and `v`, `eval (step_normal c k v) = eval (cfg.ret k (code.eval c v))`, as an equality of partial values (so one diverges iff the other does). In particular, we can let `k = cont.halt`, and then this asserts that `step_normal c cont.halt v` evaluates to `cfg.halt (code.eval c v)`. -/ def code.ok (c : code) := ∀ k v, eval step (step_normal c k v) = code.eval c v >>= λ v, eval step (cfg.ret k v) theorem code.ok.zero {c} (h : code.ok c) {v} : eval step (step_normal c cont.halt v) = cfg.halt <$> code.eval c v := begin rw [h, ← bind_pure_comp_eq_map], congr, funext v, exact part.eq_some_iff.2 (mem_eval.2 ⟨refl_trans_gen.single rfl, rfl⟩), end theorem step_normal.is_ret (c k v) : ∃ k' v', step_normal c k v = cfg.ret k' v' := begin induction c generalizing k v, iterate 3 { exact ⟨_, _, rfl⟩ }, case cons : f fs IHf IHfs { apply IHf }, case comp : f g IHf IHg { apply IHg }, case case : f g IHf IHg { rw step_normal, cases v.head; simp only [nat.elim]; [apply IHf, apply IHg] }, case fix : f IHf { apply IHf }, end theorem cont_eval_fix {f k v} (fok : code.ok f) : eval step (step_normal f (cont.fix f k) v) = f.fix.eval v >>= λ v, eval step (cfg.ret k v) := begin refine part.ext (λ x, _), simp only [part.bind_eq_bind, part.mem_bind_iff], split, { suffices : ∀ c, x ∈ eval step c → ∀ v c', c = cfg.then c' (cont.fix f k) → reaches step (step_normal f cont.halt v) c' → ∃ v₁ ∈ f.eval v, ∃ v₂ ∈ (if list.head v₁ = 0 then pure v₁.tail else f.fix.eval v₁.tail), x ∈ eval step (cfg.ret k v₂), { intro h, obtain ⟨v₁, hv₁, v₂, hv₂, h₃⟩ := this _ h _ _ (step_normal_then _ cont.halt _ _) refl_trans_gen.refl, refine ⟨v₂, pfun.mem_fix_iff.2 _, h₃⟩, simp only [part.eq_some_iff.2 hv₁, part.map_some], split_ifs at hv₂ ⊢, { rw part.mem_some_iff.1 hv₂, exact or.inl (part.mem_some _) }, { exact or.inr ⟨_, part.mem_some _, hv₂⟩ } }, refine λ c he, eval_induction he (λ y h IH, _), rintro v (⟨v'⟩ | ⟨k',v'⟩) rfl hr; rw cfg.then at h IH, { have := mem_eval.2 ⟨hr, rfl⟩, rw [fok, part.bind_eq_bind, part.mem_bind_iff] at this, obtain ⟨v'', h₁, h₂⟩ := this, rw reaches_eval at h₂, swap, exact refl_trans_gen.single rfl, cases part.mem_unique h₂ (mem_eval.2 ⟨refl_trans_gen.refl, rfl⟩), refine ⟨v', h₁, _⟩, rw [step_ret] at h, revert h, by_cases he : v'.head = 0; simp only [exists_prop, if_pos, if_false, he]; intro h, { refine ⟨_, part.mem_some _, _⟩, rw reaches_eval, exact h, exact refl_trans_gen.single rfl }, { obtain ⟨k₀, v₀, e₀⟩ := step_normal.is_ret f cont.halt v'.tail, have e₁ := step_normal_then f cont.halt (cont.fix f k) v'.tail, rw [e₀, cont.then, cfg.then] at e₁, obtain ⟨v₁, hv₁, v₂, hv₂, h₃⟩ := IH (step_ret (k₀.then (cont.fix f k)) v₀) _ _ v'.tail _ step_ret_then _, { refine ⟨_, pfun.mem_fix_iff.2 _, h₃⟩, simp only [part.eq_some_iff.2 hv₁, part.map_some, part.mem_some_iff], split_ifs at hv₂ ⊢; [exact or.inl (part.mem_some_iff.1 hv₂), exact or.inr ⟨_, rfl, hv₂⟩] }, { rwa [← @reaches_eval _ _ (cfg.ret (k₀.then (cont.fix f k)) v₀), ← e₁], exact refl_trans_gen.single rfl }, { rw [step_ret, if_neg he, e₁], refl }, { apply refl_trans_gen.single, rw e₀, exact rfl } } }, { rw reaches_eval at h, swap, exact refl_trans_gen.single rfl, exact IH _ h rfl _ _ step_ret_then (refl_trans_gen.tail hr rfl) } }, { rintro ⟨v', he, hr⟩, rw reaches_eval at hr, swap, exact refl_trans_gen.single rfl, refine pfun.fix_induction he (λ v (he : v' ∈ f.fix.eval v) IH, _), rw [fok, part.bind_eq_bind, part.mem_bind_iff], obtain he | ⟨v'', he₁', he₂'⟩ := pfun.mem_fix_iff.1 he, { obtain ⟨v', he₁, he₂⟩ := (part.mem_map_iff _).1 he, split_ifs at he₂; cases he₂, refine ⟨_, he₁, _⟩, rw reaches_eval, swap, exact refl_trans_gen.single rfl, rwa [step_ret, if_pos h] }, { obtain ⟨v₁, he₁, he₂⟩ := (part.mem_map_iff _).1 he₁', split_ifs at he₂; cases he₂, clear he₂ he₁', change _ ∈ f.fix.eval _ at he₂', refine ⟨_, he₁, _⟩, rw reaches_eval, swap, exact refl_trans_gen.single rfl, rwa [step_ret, if_neg h], exact IH v₁.tail he₂' ((part.mem_map_iff _).2 ⟨_, he₁, if_neg h⟩) } } end theorem code_is_ok (c) : code.ok c := begin induction c; intros k v; rw step_normal, iterate 3 { simp only [code.eval, pure_bind] }, case cons : f fs IHf IHfs { rw [code.eval, IHf], simp only [bind_assoc, cont.eval, pure_bind], congr, funext v, rw [reaches_eval], swap, exact refl_trans_gen.single rfl, rw [step_ret, IHfs], congr, funext v', refine eq.trans _ (eq.symm _); try {exact reaches_eval (refl_trans_gen.single rfl)} }, case comp : f g IHf IHg { rw [code.eval, IHg], simp only [bind_assoc, cont.eval, pure_bind], congr, funext v, rw [reaches_eval], swap, exact refl_trans_gen.single rfl, rw [step_ret, IHf] }, case case : f g IHf IHg { simp only [code.eval], cases v.head; simp only [nat.elim, code.eval]; [apply IHf, apply IHg] }, case fix : f IHf { rw cont_eval_fix IHf }, end theorem step_normal_eval (c v) : eval step (step_normal c cont.halt v) = cfg.halt <$> c.eval v := (code_is_ok c).zero theorem step_ret_eval {k v} : eval step (step_ret k v) = cfg.halt <$> k.eval v := begin induction k generalizing v, case halt : { simp only [mem_eval, cont.eval, map_pure], exact part.eq_some_iff.2 (mem_eval.2 ⟨refl_trans_gen.refl, rfl⟩) }, case cons₁ : fs as k IH { rw [cont.eval, step_ret, code_is_ok], simp only [← bind_pure_comp_eq_map, bind_assoc], congr, funext v', rw [reaches_eval], swap, exact refl_trans_gen.single rfl, rw [step_ret, IH, bind_pure_comp_eq_map] }, case cons₂ : ns k IH { rw [cont.eval, step_ret], exact IH }, case comp : f k IH { rw [cont.eval, step_ret, code_is_ok], simp only [← bind_pure_comp_eq_map, bind_assoc], congr, funext v', rw [reaches_eval], swap, exact refl_trans_gen.single rfl, rw [IH, bind_pure_comp_eq_map] }, case fix : f k IH { rw [cont.eval, step_ret], simp only [bind_pure_comp_eq_map], split_ifs, { exact IH }, simp only [← bind_pure_comp_eq_map, bind_assoc, cont_eval_fix (code_is_ok _)], congr, funext, rw [bind_pure_comp_eq_map, ← IH], exact reaches_eval (refl_trans_gen.single rfl) }, end end to_partrec /-! ## Simulating sequentialized partial recursive functions in TM2 At this point we have a sequential model of partial recursive functions: the `cfg` type and `step : cfg → option cfg` function from the previous section. The key feature of this model is that it does a finite amount of computation (in fact, an amount which is statically bounded by the size of the program) between each step, and no individual step can diverge (unlike the compositional semantics, where every sub-part of the computation is potentially divergent). So we can utilize the same techniques as in the other TM simulations in `computability.turing_machine` to prove that each step corresponds to a finite number of steps in a lower level model. (We don't prove it here, but in anticipation of the complexity class P, the simulation is actually polynomial-time as well.) The target model is `turing.TM2`, which has a fixed finite set of stacks, a bit of local storage, with programs selected from a potentially infinite (but finitely accessible) set of program positions, or labels `Λ`, each of which executes a finite sequence of basic stack commands. For this program we will need four stacks, each on an alphabet `Γ'` like so: inductive Γ' | Cons | cons | bit0 | bit1 We represent a number as a bit sequence, lists of numbers by putting `cons` after each element, and lists of lists of natural numbers by putting `Cons` after each list. For example: 0 ~> [] 1 ~> [bit1] 6 ~> [bit0, bit1, bit1] [1, 2] ~> [bit1, cons, bit0, bit1, cons] [[], [1, 2]] ~> [Cons, bit1, cons, bit0, bit1, cons, Cons] The four stacks are `main`, `rev`, `aux`, `stack`. In normal mode, `main` contains the input to the current program (a `list ℕ`) and `stack` contains data (a `list (list ℕ)`) associated to the current continuation, and in `ret` mode `main` contains the value that is being passed to the continuation and `stack` contains the data for the continuation. The `rev` and `aux` stacks are usually empty; `rev` is used to store reversed data when e.g. moving a value from one stack to another, while `aux` is used as a temporary for a `main`/`stack` swap that happens during `cons₁` evaluation. The only local store we need is `option Γ'`, which stores the result of the last pop operation. (Most of our working data are natural numbers, which are too large to fit in the local store.) The continuations from the previous section are data-carrying, containing all the values that have been computed and are awaiting other arguments. In order to have only a finite number of continuations appear in the program so that they can be used in machine states, we separate the data part (anything with type `list ℕ`) from the `cont` type, producing a `cont'` type that lacks this information. The data is kept on the `stack` stack. Because we want to have subroutines for e.g. moving an entire stack to another place, we use an infinite inductive type `Λ'` so that we can execute a program and then return to do something else without having to define too many different kinds of intermediate states. (We must nevertheless prove that only finitely many labels are accessible.) The labels are: * `move p k₁ k₂ q`: move elements from stack `k₁` to `k₂` while `p` holds of the value being moved. The last element, that fails `p`, is placed in neither stack but left in the local store. At the end of the operation, `k₂` will have the elements of `k₁` in reverse order. Then do `q`. * `clear p k q`: delete elements from stack `k` until `p` is true. Like `move`, the last element is left in the local storage. Then do `q`. * `copy q`: Move all elements from `rev` to both `main` and `stack` (in reverse order), then do `q`. That is, it takes `(a, b, c, d)` to `(b.reverse ++ a, [], c, b.reverse ++ d)`. * `push k f q`: push `f s`, where `s` is the local store, to stack `k`, then do `q`. This is a duplicate of the `push` instruction that is part of the TM2 model, but by having a subroutine just for this purpose we can build up programs to execute inside a `goto` statement, where we have the flexibility to be general recursive. * `read (f : option Γ' → Λ')`: go to state `f s` where `s` is the local store. Again this is only here for convenience. * `succ q`: perform a successor operation. Assuming `[n]` is encoded on `main` before, `[n+1]` will be on main after. This implements successor for binary natural numbers. * `pred q₁ q₂`: perform a predecessor operation or `case` statement. If `[]` is encoded on `main` before, then we transition to `q₁` with `[]` on main; if `(0 :: v)` is on `main` before then `v` will be on `main` after and we transition to `q₁`; and if `(n+1 :: v)` is on `main` before then `n :: v` will be on `main` after and we transition to `q₂`. * `ret k`: call continuation `k`. Each continuation has its own interpretation of the data in `stack` and sets up the data for the next continuation. * `ret (cons₁ fs k)`: `v :: k_data` on `stack` and `ns` on `main`, and the next step expects `v` on `main` and `ns :: k_data` on `stack`. So we have to do a little dance here with six reverse-moves using the `aux` stack to perform a three-point swap, each of which involves two reversals. * `ret (cons₂ k)`: `ns :: k_data` is on `stack` and `v` is on `main`, and we have to put `ns.head :: v` on `main` and `k_data` on `stack`. This is done using the `head` subroutine. * `ret (fix f k)`: This stores no data, so we just check if `main` starts with `0` and if so, remove it and call `k`, otherwise `clear` the first value and call `f`. * `ret halt`: the stack is empty, and `main` has the output. Do nothing and halt. In addition to these basic states, we define some additional subroutines that are used in the above: * `push'`, `peek'`, `pop'` are special versions of the builtins that use the local store to supply inputs and outputs. * `unrev`: special case `move ff rev main` to move everything from `rev` back to `main`. Used as a cleanup operation in several functions. * `move_excl p k₁ k₂ q`: same as `move` but pushes the last value read back onto the source stack. * `move₂ p k₁ k₂ q`: double `move`, so that the result comes out in the right order at the target stack. Implemented as `move_excl p k rev; move ff rev k₂`. Assumes that neither `k₁` nor `k₂` is `rev` and `rev` is initially empty. * `head k q`: get the first natural number from stack `k` and reverse-move it to `rev`, then clear the rest of the list at `k` and then `unrev` to reverse-move the head value to `main`. This is used with `k = main` to implement regular `head`, i.e. if `v` is on `main` before then `[v.head]` will be on `main` after; and also with `k = stack` for the `cons` operation, which has `v` on `main` and `ns :: k_data` on `stack`, and results in `k_data` on `stack` and `ns.head :: v` on `main`. * `tr_normal` is the main entry point, defining states that perform a given `code` computation. It mostly just dispatches to functions written above. The main theorem of this section is `tr_eval`, which asserts that for each that for each code `c`, the state `init c v` steps to `halt v'` in finitely many steps if and only if `code.eval c v = some v'`. -/ namespace partrec_to_TM2 section open to_partrec /-- The alphabet for the stacks in the program. `bit0` and `bit1` are used to represent `ℕ` values as lists of binary digits, `cons` is used to separate `list ℕ` values, and `Cons` is used to separate `list (list ℕ)` values. See the section documentation. -/ @[derive [decidable_eq, inhabited, fintype]] inductive Γ' | Cons | cons | bit0 | bit1 /-- The four stacks used by the program. `main` is used to store the input value in `tr_normal` mode and the output value in `Λ'.ret` mode, while `stack` is used to keep all the data for the continuations. `rev` is used to store reversed lists when transferring values between stacks, and `aux` is only used once in `cons₁`. See the section documentation. -/ @[derive [decidable_eq, inhabited]] inductive K' | main | rev | aux | stack open K' /-- Continuations as in `to_partrec.cont` but with the data removed. This is done because we want the set of all continuations in the program to be finite (so that it can ultimately be encoded into the finite state machine of a Turing machine), but a continuation can handle a potentially infinite number of data values during execution. -/ @[derive [decidable_eq, inhabited]] inductive cont' | halt | cons₁ : code → cont' → cont' | cons₂ : cont' → cont' | comp : code → cont' → cont' | fix : code → cont' → cont' /-- The set of program positions. We make extensive use of inductive types here to let us describe "subroutines"; for example `clear p k q` is a program that clears stack `k`, then does `q` where `q` is another label. In order to prevent this from resulting in an infinite number of distinct accessible states, we are careful to be non-recursive (although loops are okay). See the section documentation for a description of all the programs. -/ inductive Λ' | move (p : Γ' → bool) (k₁ k₂ : K') (q : Λ') | clear (p : Γ' → bool) (k : K') (q : Λ') | copy (q : Λ') | push (k : K') (s : option Γ' → option Γ') (q : Λ') | read (f : option Γ' → Λ') | succ (q : Λ') | pred (q₁ q₂ : Λ') | ret (k : cont') instance : inhabited Λ' := ⟨Λ'.ret cont'.halt⟩ instance : decidable_eq Λ' := λ a b, begin induction a generalizing b; cases b; try { apply decidable.is_false, rintro ⟨⟨⟩⟩, done }, all_goals { exactI decidable_of_iff' _ (by simp [function.funext_iff]) }, end /-- The type of TM2 statements used by this machine. -/ @[derive inhabited] def stmt' := TM2.stmt (λ _:K', Γ') Λ' (option Γ') /-- The type of TM2 configurations used by this machine. -/ @[derive inhabited] def cfg' := TM2.cfg (λ _:K', Γ') Λ' (option Γ') open TM2.stmt /-- A predicate that detects the end of a natural number, either `Γ'.cons` or `Γ'.Cons` (or implicitly the end of the list), for use in predicate-taking functions like `move` and `clear`. -/ def nat_end : Γ' → bool | Γ'.Cons := tt | Γ'.cons := tt | _ := ff /-- Pop a value from the stack and place the result in local store. -/ @[simp] def pop' (k : K') : stmt' → stmt' := pop k (λ x v, v) /-- Peek a value from the stack and place the result in local store. -/ @[simp] def peek' (k : K') : stmt' → stmt' := peek k (λ x v, v) /-- Push the value in the local store to the given stack. -/ @[simp] def push' (k : K') : stmt' → stmt' := push k (λ x, x.iget) /-- Move everything from the `rev` stack to the `main` stack (reversed). -/ def unrev := Λ'.move (λ _, ff) rev main /-- Move elements from `k₁` to `k₂` while `p` holds, with the last element being left on `k₁`. -/ def move_excl (p k₁ k₂ q) := Λ'.move p k₁ k₂ $ Λ'.push k₁ id q /-- Move elements from `k₁` to `k₂` without reversion, by performing a double move via the `rev` stack. -/ def move₂ (p k₁ k₂ q) := move_excl p k₁ rev $ Λ'.move (λ _, ff) rev k₂ q /-- Assuming `tr_list v` is on the front of stack `k`, remove it, and push `v.head` onto `main`. See the section documentation. -/ def head (k : K') (q : Λ') : Λ' := Λ'.move nat_end k rev $ Λ'.push rev (λ _, some Γ'.cons) $ Λ'.read $ λ s, (if s = some Γ'.Cons then id else Λ'.clear (λ x, x = Γ'.Cons) k) $ unrev q /-- The program that evaluates code `c` with continuation `k`. This expects an initial state where `tr_list v` is on `main`, `tr_cont_stack k` is on `stack`, and `aux` and `rev` are empty. See the section documentation for details. -/ @[simp] def tr_normal : code → cont' → Λ' | code.zero' k := Λ'.push main (λ _, some Γ'.cons) $ Λ'.ret k | code.succ k := head main $ Λ'.succ $ Λ'.ret k | code.tail k := Λ'.clear nat_end main $ Λ'.ret k | (code.cons f fs) k := Λ'.push stack (λ _, some Γ'.Cons) $ Λ'.move (λ _, ff) main rev $ Λ'.copy $ tr_normal f (cont'.cons₁ fs k) | (code.comp f g) k := tr_normal g (cont'.comp f k) | (code.case f g) k := Λ'.pred (tr_normal f k) (tr_normal g k) | (code.fix f) k := tr_normal f (cont'.fix f k) /-- The main program. See the section documentation for details. -/ @[simp] def tr : Λ' → stmt' | (Λ'.move p k₁ k₂ q) := pop' k₁ $ branch (λ s, s.elim tt p) ( goto $ λ _, q ) ( push' k₂ $ goto $ λ _, Λ'.move p k₁ k₂ q ) | (Λ'.push k f q) := branch (λ s, (f s).is_some) ( push k (λ s, (f s).iget) $ goto $ λ _, q ) ( goto $ λ _, q ) | (Λ'.read q) := goto q | (Λ'.clear p k q) := pop' k $ branch (λ s, s.elim tt p) ( goto $ λ _, q ) ( goto $ λ _, Λ'.clear p k q ) | (Λ'.copy q) := pop' rev $ branch option.is_some ( push' main $ push' stack $ goto $ λ _, Λ'.copy q ) ( goto $ λ _, q ) | (Λ'.succ q) := pop' main $ branch (λ s, s = some Γ'.bit1) ( push rev (λ _, Γ'.bit0) $ goto $ λ _, Λ'.succ q ) $ branch (λ s, s = some Γ'.cons) ( push main (λ _, Γ'.cons) $ push main (λ _, Γ'.bit1) $ goto $ λ _, unrev q ) ( push main (λ _, Γ'.bit1) $ goto $ λ _, unrev q ) | (Λ'.pred q₁ q₂) := pop' main $ branch (λ s, s = some Γ'.bit0) ( push rev (λ _, Γ'.bit1) $ goto $ λ _, Λ'.pred q₁ q₂ ) $ branch (λ s, nat_end s.iget) ( goto $ λ _, q₁ ) ( peek' main $ branch (λ s, nat_end s.iget) ( goto $ λ _, unrev q₂ ) ( push rev (λ _, Γ'.bit0) $ goto $ λ _, unrev q₂ ) ) | (Λ'.ret (cont'.cons₁ fs k)) := goto $ λ _, move₂ (λ _, ff) main aux $ move₂ (λ s, s = Γ'.Cons) stack main $ move₂ (λ _, ff) aux stack $ tr_normal fs (cont'.cons₂ k) | (Λ'.ret (cont'.cons₂ k)) := goto $ λ _, head stack $ Λ'.ret k | (Λ'.ret (cont'.comp f k)) := goto $ λ _, tr_normal f k | (Λ'.ret (cont'.fix f k)) := pop' main $ goto $ λ s, cond (nat_end s.iget) (Λ'.ret k) $ Λ'.clear nat_end main $ tr_normal f (cont'.fix f k) | (Λ'.ret cont'.halt) := load (λ _, none) $ halt /-- Translating a `cont` continuation to a `cont'` continuation simply entails dropping all the data. This data is instead encoded in `tr_cont_stack` in the configuration. -/ def tr_cont : cont → cont' | cont.halt := cont'.halt | (cont.cons₁ c _ k) := cont'.cons₁ c (tr_cont k) | (cont.cons₂ _ k) := cont'.cons₂ (tr_cont k) | (cont.comp c k) := cont'.comp c (tr_cont k) | (cont.fix c k) := cont'.fix c (tr_cont k) /-- We use `pos_num` to define the translation of binary natural numbers. A natural number is represented as a little-endian list of `bit0` and `bit1` elements: 1 = [bit1] 2 = [bit0, bit1] 3 = [bit1, bit1] 4 = [bit0, bit0, bit1] In particular, this representation guarantees no trailing `bit0`'s at the end of the list. -/ def tr_pos_num : pos_num → list Γ' | pos_num.one := [Γ'.bit1] | (pos_num.bit0 n) := Γ'.bit0 :: tr_pos_num n | (pos_num.bit1 n) := Γ'.bit1 :: tr_pos_num n /-- We use `num` to define the translation of binary natural numbers. Positive numbers are translated using `tr_pos_num`, and `tr_num 0 = []`. So there are never any trailing `bit0`'s in a translated `num`. 0 = [] 1 = [bit1] 2 = [bit0, bit1] 3 = [bit1, bit1] 4 = [bit0, bit0, bit1] -/ def tr_num : num → list Γ' | num.zero := [] | (num.pos n) := tr_pos_num n /-- Because we use binary encoding, we define `tr_nat` in terms of `tr_num`, using `num`, which are binary natural numbers. (We could also use `nat.binary_rec_on`, but `num` and `pos_num` make for easy inductions.) -/ def tr_nat (n : ℕ) : list Γ' := tr_num n @[simp] theorem tr_nat_zero : tr_nat 0 = [] := rfl /-- Lists are translated with a `cons` after each encoded number. For example: [] = [] [0] = [cons] [1] = [bit1, cons] [6, 0] = [bit0, bit1, bit1, cons, cons] -/ @[simp] def tr_list : list ℕ → list Γ' | [] := [] | (n :: ns) := tr_nat n ++ Γ'.cons :: tr_list ns /-- Lists of lists are translated with a `Cons` after each encoded list. For example: [] = [] [[]] = [Cons] [[], []] = [Cons, Cons] [[0]] = [cons, Cons] [[1, 2], [0]] = [bit1, cons, bit0, bit1, cons, Cons, cons, Cons] -/ @[simp] def tr_llist : list (list ℕ) → list Γ' | [] := [] | (l :: ls) := tr_list l ++ Γ'.Cons :: tr_llist ls /-- The data part of a continuation is a list of lists, which is encoded on the `stack` stack using `tr_llist`. -/ @[simp] def cont_stack : cont → list (list ℕ) | cont.halt := [] | (cont.cons₁ _ ns k) := ns :: cont_stack k | (cont.cons₂ ns k) := ns :: cont_stack k | (cont.comp _ k) := cont_stack k | (cont.fix _ k) := cont_stack k /-- The data part of a continuation is a list of lists, which is encoded on the `stack` stack using `tr_llist`. -/ def tr_cont_stack (k : cont) := tr_llist (cont_stack k) /-- This is the nondependent eliminator for `K'`, but we use it specifically here in order to represent the stack data as four lists rather than as a function `K' → list Γ'`, because this makes rewrites easier. The theorems `K'.elim_update_main` et. al. show how such a function is updated after an `update` to one of the components. -/ @[simp] def K'.elim (a b c d : list Γ') : K' → list Γ' | K'.main := a | K'.rev := b | K'.aux := c | K'.stack := d @[simp] theorem K'.elim_update_main {a b c d a'} : update (K'.elim a b c d) main a' = K'.elim a' b c d := by funext x; cases x; refl @[simp] theorem K'.elim_update_rev {a b c d b'} : update (K'.elim a b c d) rev b' = K'.elim a b' c d := by funext x; cases x; refl @[simp] theorem K'.elim_update_aux {a b c d c'} : update (K'.elim a b c d) aux c' = K'.elim a b c' d := by funext x; cases x; refl @[simp] theorem K'.elim_update_stack {a b c d d'} : update (K'.elim a b c d) stack d' = K'.elim a b c d' := by funext x; cases x; refl /-- The halting state corresponding to a `list ℕ` output value. -/ def halt (v : list ℕ) : cfg' := ⟨none, none, K'.elim (tr_list v) [] [] []⟩ /-- The `cfg` states map to `cfg'` states almost one to one, except that in normal operation the local store contains an arbitrary garbage value. To make the final theorem cleaner we explicitly clear it in the halt state so that there is exactly one configuration corresponding to output `v`. -/ def tr_cfg : cfg → cfg' → Prop | (cfg.ret k v) c' := ∃ s, c' = ⟨some (Λ'.ret (tr_cont k)), s, K'.elim (tr_list v) [] [] (tr_cont_stack k)⟩ | (cfg.halt v) c' := c' = halt v /-- This could be a general list definition, but it is also somewhat specialized to this application. `split_at_pred p L` will search `L` for the first element satisfying `p`. If it is found, say `L = l₁ ++ a :: l₂` where `a` satisfies `p` but `l₁` does not, then it returns `(l₁, some a, l₂)`. Otherwise, if there is no such element, it returns `(L, none, [])`. -/ def split_at_pred {α} (p : α → bool) : list α → list α × option α × list α | [] := ([], none, []) | (a :: as) := cond (p a) ([], some a, as) $ let ⟨l₁, o, l₂⟩ := split_at_pred as in ⟨a :: l₁, o, l₂⟩ theorem split_at_pred_eq {α} (p : α → bool) : ∀ L l₁ o l₂, (∀ x ∈ l₁, p x = ff) → option.elim o (L = l₁ ∧ l₂ = []) (λ a, p a = tt ∧ L = l₁ ++ a :: l₂) → split_at_pred p L = (l₁, o, l₂) | [] _ none _ _ ⟨rfl, rfl⟩ := rfl | [] l₁ (some o) l₂ h₁ ⟨h₂, h₃⟩ := by simp at h₃; contradiction | (a :: L) l₁ o l₂ h₁ h₂ := begin rw [split_at_pred], have IH := split_at_pred_eq L, cases o, { cases l₁ with a' l₁; rcases h₂ with ⟨⟨⟩, rfl⟩, rw [h₁ a (or.inl rfl), cond, IH L none [] _ ⟨rfl, rfl⟩], refl, exact λ x h, h₁ x (or.inr h) }, { cases l₁ with a' l₁; rcases h₂ with ⟨h₂, ⟨⟩⟩, {rw [h₂, cond]}, rw [h₁ a (or.inl rfl), cond, IH l₁ (some o) l₂ _ ⟨h₂, _⟩]; try {refl}, exact λ x h, h₁ x (or.inr h) }, end theorem split_at_pred_ff {α} (L : list α) : split_at_pred (λ _, ff) L = (L, none, []) := split_at_pred_eq _ _ _ _ _ (λ _ _, rfl) ⟨rfl, rfl⟩ theorem move_ok {p k₁ k₂ q s L₁ o L₂} {S : K' → list Γ'} (h₁ : k₁ ≠ k₂) (e : split_at_pred p (S k₁) = (L₁, o, L₂)) : reaches₁ (TM2.step tr) ⟨some (Λ'.move p k₁ k₂ q), s, S⟩ ⟨some q, o, update (update S k₁ L₂) k₂ (L₁.reverse_core (S k₂))⟩ := begin induction L₁ with a L₁ IH generalizing S s, { rw [(_ : [].reverse_core _ = _), function.update_eq_self], swap, { rw function.update_noteq h₁.symm, refl }, refine trans_gen.head' rfl _, simp, cases S k₁ with a Sk, {cases e, refl}, simp [split_at_pred] at e ⊢, cases p a; simp at e ⊢, { revert e, rcases split_at_pred p Sk with ⟨_, _, _⟩, rintro ⟨⟩ }, { simp only [e] } }, { refine trans_gen.head rfl _, simp, cases e₁ : S k₁ with a' Sk; rw [e₁, split_at_pred] at e, {cases e}, cases e₂ : p a'; simp only [e₂, cond] at e, swap, {cases e}, rcases e₃ : split_at_pred p Sk with ⟨_, _, _⟩, rw [e₃, split_at_pred] at e, cases e, simp [e₂], convert @IH (update (update S k₁ Sk) k₂ (a :: S k₂)) _ _ using 2; simp [function.update_noteq, h₁, h₁.symm, e₃, list.reverse_core], simp [function.update_comm h₁.symm] } end theorem unrev_ok {q s} {S : K' → list Γ'} : reaches₁ (TM2.step tr) ⟨some (unrev q), s, S⟩ ⟨some q, none, update (update S rev []) main (list.reverse_core (S rev) (S main))⟩ := move_ok dec_trivial $ split_at_pred_ff _ theorem move₂_ok {p k₁ k₂ q s L₁ o L₂} {S : K' → list Γ'} (h₁ : k₁ ≠ rev ∧ k₂ ≠ rev ∧ k₁ ≠ k₂) (h₂ : S rev = []) (e : split_at_pred p (S k₁) = (L₁, o, L₂)) : reaches₁ (TM2.step tr) ⟨some (move₂ p k₁ k₂ q), s, S⟩ ⟨some q, none, update (update S k₁ (o.elim id list.cons L₂)) k₂ (L₁ ++ S k₂)⟩ := begin refine (move_ok h₁.1 e).trans (trans_gen.head rfl _), cases o; simp only [option.elim, tr, id.def], { convert move_ok h₁.2.1.symm (split_at_pred_ff _) using 2, simp only [function.update_comm h₁.1, function.update_idem], rw show update S rev [] = S, by rw [← h₂, function.update_eq_self], simp only [function.update_noteq h₁.2.2.symm, function.update_noteq h₁.2.1, function.update_noteq h₁.1.symm, list.reverse_core_eq, h₂, function.update_same, list.append_nil, list.reverse_reverse] }, { convert move_ok h₁.2.1.symm (split_at_pred_ff _) using 2, simp only [h₂, function.update_comm h₁.1, list.reverse_core_eq, function.update_same, list.append_nil, function.update_idem], rw show update S rev [] = S, by rw [← h₂, function.update_eq_self], simp only [function.update_noteq h₁.1.symm, function.update_noteq h₁.2.2.symm, function.update_noteq h₁.2.1, function.update_same, list.reverse_reverse] }, end theorem clear_ok {p k q s L₁ o L₂} {S : K' → list Γ'} (e : split_at_pred p (S k) = (L₁, o, L₂)) : reaches₁ (TM2.step tr) ⟨some (Λ'.clear p k q), s, S⟩ ⟨some q, o, update S k L₂⟩ := begin induction L₁ with a L₁ IH generalizing S s, { refine trans_gen.head' rfl _, simp, cases S k with a Sk, {cases e, refl}, simp [split_at_pred] at e ⊢, cases p a; simp at e ⊢, { revert e, rcases split_at_pred p Sk with ⟨_, _, _⟩, rintro ⟨⟩ }, { simp only [e] } }, { refine trans_gen.head rfl _, simp, cases e₁ : S k with a' Sk; rw [e₁, split_at_pred] at e, {cases e}, cases e₂ : p a'; simp only [e₂, cond] at e, swap, {cases e}, rcases e₃ : split_at_pred p Sk with ⟨_, _, _⟩, rw [e₃, split_at_pred] at e, cases e, simp [e₂], convert @IH (update S k Sk) _ _ using 2; simp [e₃] } end theorem copy_ok (q s a b c d) : reaches₁ (TM2.step tr) ⟨some (Λ'.copy q), s, K'.elim a b c d⟩ ⟨some q, none, K'.elim (list.reverse_core b a) [] c (list.reverse_core b d)⟩ := begin induction b with x b IH generalizing a d s, { refine trans_gen.single _, simp, refl }, refine trans_gen.head rfl _, simp, exact IH _ _ _, end theorem tr_pos_num_nat_end : ∀ n (x ∈ tr_pos_num n), nat_end x = ff | pos_num.one _ (or.inl rfl) := rfl | (pos_num.bit0 n) _ (or.inl rfl) := rfl | (pos_num.bit0 n) _ (or.inr h) := tr_pos_num_nat_end n _ h | (pos_num.bit1 n) _ (or.inl rfl) := rfl | (pos_num.bit1 n) _ (or.inr h) := tr_pos_num_nat_end n _ h theorem tr_num_nat_end : ∀ n (x ∈ tr_num n), nat_end x = ff | (num.pos n) x h := tr_pos_num_nat_end n x h theorem tr_nat_nat_end (n) : ∀ x ∈ tr_nat n, nat_end x = ff := tr_num_nat_end _ theorem tr_list_ne_Cons : ∀ l (x ∈ tr_list l), x ≠ Γ'.Cons | (a :: l) x h := begin simp [tr_list] at h, obtain h | rfl | h := h, { rintro rfl, cases tr_nat_nat_end _ _ h }, { rintro ⟨⟩ }, { exact tr_list_ne_Cons l _ h } end theorem head_main_ok {q s L} {c d : list Γ'} : reaches₁ (TM2.step tr) ⟨some (head main q), s, K'.elim (tr_list L) [] c d⟩ ⟨some q, none, K'.elim (tr_list [L.head]) [] c d⟩ := begin let o : option Γ' := list.cases_on L none (λ _ _, some Γ'.cons), refine (move_ok dec_trivial (split_at_pred_eq _ _ (tr_nat L.head) o (tr_list L.tail) (tr_nat_nat_end _) _)).trans (trans_gen.head rfl (trans_gen.head rfl _)), { cases L; exact ⟨rfl, rfl⟩ }, simp, rw if_neg (show o ≠ some Γ'.Cons, by cases L; rintro ⟨⟩), refine (clear_ok (split_at_pred_eq _ _ _ none [] _ ⟨rfl, rfl⟩)).trans _, { exact λ x h, (to_bool_ff (tr_list_ne_Cons _ _ h)) }, convert unrev_ok, simp [list.reverse_core_eq], end theorem head_stack_ok {q s L₁ L₂ L₃} : reaches₁ (TM2.step tr) ⟨some (head stack q), s, K'.elim (tr_list L₁) [] [] (tr_list L₂ ++ Γ'.Cons :: L₃)⟩ ⟨some q, none, K'.elim (tr_list (L₂.head :: L₁)) [] [] L₃⟩ := begin cases L₂ with a L₂, { refine trans_gen.trans (move_ok dec_trivial (split_at_pred_eq _ _ [] (some Γ'.Cons) L₃ (by rintro _ ⟨⟩) ⟨rfl, rfl⟩)) (trans_gen.head rfl (trans_gen.head rfl _)), convert unrev_ok, simp, refl }, { refine trans_gen.trans (move_ok dec_trivial (split_at_pred_eq _ _ (tr_nat a) (some Γ'.cons) (tr_list L₂ ++ Γ'.Cons :: L₃) (tr_nat_nat_end _) ⟨rfl, by simp⟩)) (trans_gen.head rfl (trans_gen.head rfl _)), simp, refine trans_gen.trans (clear_ok (split_at_pred_eq _ _ (tr_list L₂) (some Γ'.Cons) L₃ (λ x h, (to_bool_ff (tr_list_ne_Cons _ _ h))) ⟨rfl, by simp⟩)) _, convert unrev_ok, simp [list.reverse_core_eq] }, end theorem succ_ok {q s n} {c d : list Γ'} : reaches₁ (TM2.step tr) ⟨some (Λ'.succ q), s, K'.elim (tr_list [n]) [] c d⟩ ⟨some q, none, K'.elim (tr_list [n.succ]) [] c d⟩ := begin simp [tr_nat, num.add_one], cases (n:num) with a, { refine trans_gen.head rfl _, simp, rw if_neg, swap, rintro ⟨⟩, rw if_pos, swap, refl, convert unrev_ok, simp, refl }, simp [num.succ, tr_num, num.succ'], suffices : ∀ l₁, ∃ l₁' l₂' s', list.reverse_core l₁ (tr_pos_num a.succ) = list.reverse_core l₁' l₂' ∧ reaches₁ (TM2.step tr) ⟨some q.succ, s, K'.elim (tr_pos_num a ++ [Γ'.cons]) l₁ c d⟩ ⟨some (unrev q), s', K'.elim (l₂' ++ [Γ'.cons]) l₁' c d⟩, { obtain ⟨l₁', l₂', s', e, h⟩ := this [], simp [list.reverse_core] at e, refine h.trans _, convert unrev_ok using 2, simp [e, list.reverse_core_eq] }, induction a with m IH m IH generalizing s; intro l₁, { refine ⟨Γ'.bit0 :: l₁, [Γ'.bit1], some Γ'.cons, rfl, trans_gen.head rfl (trans_gen.single _)⟩, simp [tr_pos_num] }, { obtain ⟨l₁', l₂', s', e, h⟩ := IH (Γ'.bit0 :: l₁), refine ⟨l₁', l₂', s', e, trans_gen.head _ h⟩, swap, simp [pos_num.succ, tr_pos_num] }, { refine ⟨l₁, _, some Γ'.bit0, rfl, trans_gen.single _⟩, simp, refl }, end theorem pred_ok (q₁ q₂ s v) (c d : list Γ') : ∃ s', reaches₁ (TM2.step tr) ⟨some (Λ'.pred q₁ q₂), s, K'.elim (tr_list v) [] c d⟩ (v.head.elim ⟨some q₁, s', K'.elim (tr_list v.tail) [] c d⟩ (λ n _, ⟨some q₂, s', K'.elim (tr_list (n :: v.tail)) [] c d⟩)) := begin rcases v with _|⟨_|n, v⟩, { refine ⟨none, trans_gen.single _⟩, simp, refl }, { refine ⟨some Γ'.cons, trans_gen.single _⟩, simp, refl }, refine ⟨none, _⟩, simp [tr_nat, num.add_one, num.succ, tr_num], cases (n:num) with a, { simp [tr_pos_num, tr_num, show num.zero.succ' = pos_num.one, from rfl], refine trans_gen.head rfl _, convert unrev_ok, simp, refl }, simp [tr_num, num.succ'], suffices : ∀ l₁, ∃ l₁' l₂' s', list.reverse_core l₁ (tr_pos_num a) = list.reverse_core l₁' l₂' ∧ reaches₁ (TM2.step tr) ⟨some (q₁.pred q₂), s, K'.elim (tr_pos_num a.succ ++ Γ'.cons :: tr_list v) l₁ c d⟩ ⟨some (unrev q₂), s', K'.elim (l₂' ++ Γ'.cons :: tr_list v) l₁' c d⟩, { obtain ⟨l₁', l₂', s', e, h⟩ := this [], simp [list.reverse_core] at e, refine h.trans _, convert unrev_ok using 2, simp [e, list.reverse_core_eq] }, induction a with m IH m IH generalizing s; intro l₁, { refine ⟨Γ'.bit1 :: l₁, [], some Γ'.cons, rfl, trans_gen.head rfl (trans_gen.single _)⟩, simp [tr_pos_num, show pos_num.one.succ = pos_num.one.bit0, from rfl], refl }, { obtain ⟨l₁', l₂', s', e, h⟩ := IH (some Γ'.bit0) (Γ'.bit1 :: l₁), refine ⟨l₁', l₂', s', e, trans_gen.head _ h⟩, simp, refl }, { obtain ⟨a, l, e, h⟩ : ∃ a l, tr_pos_num m = a :: l ∧ nat_end a = ff, { cases m; refine ⟨_, _, rfl, rfl⟩ }, refine ⟨Γ'.bit0 :: l₁, _, some a, rfl, trans_gen.single _⟩, simp [tr_pos_num, pos_num.succ, e, h, nat_end, show some Γ'.bit1 ≠ some Γ'.bit0, from dec_trivial] }, end theorem tr_normal_respects (c k v s) : ∃ b₂, tr_cfg (step_normal c k v) b₂ ∧ reaches₁ (TM2.step tr) ⟨some (tr_normal c (tr_cont k)), s, K'.elim (tr_list v) [] [] (tr_cont_stack k)⟩ b₂ := begin induction c generalizing k v s, case zero' : { refine ⟨_, ⟨s, rfl⟩, trans_gen.single _⟩, simp }, case succ : { refine ⟨_, ⟨none, rfl⟩, head_main_ok.trans succ_ok⟩ }, case tail : { let o : option Γ' := list.cases_on v none (λ _ _, some Γ'.cons), refine ⟨_, ⟨o, rfl⟩, _⟩, convert clear_ok _, simp, swap, refine split_at_pred_eq _ _ (tr_nat v.head) _ _ (tr_nat_nat_end _) _, cases v; exact ⟨rfl, rfl⟩ }, case cons : f fs IHf IHfs { obtain ⟨c, h₁, h₂⟩ := IHf (cont.cons₁ fs v k) v none, refine ⟨c, h₁, trans_gen.head rfl $ (move_ok dec_trivial (split_at_pred_ff _)).trans _⟩, simp [step_normal], refine (copy_ok _ none [] (tr_list v).reverse _ _).trans _, convert h₂ using 2, simp [list.reverse_core_eq, tr_cont_stack] }, case comp : f g IHf IHg { exact IHg (cont.comp f k) v s }, case case : f g IHf IHg { rw step_normal, obtain ⟨s', h⟩ := pred_ok _ _ s v _ _, cases v.head with n, { obtain ⟨c, h₁, h₂⟩ := IHf k _ s', exact ⟨_, h₁, h.trans h₂⟩ }, { obtain ⟨c, h₁, h₂⟩ := IHg k _ s', exact ⟨_, h₁, h.trans h₂⟩ } }, case fix : f IH { apply IH } end theorem tr_ret_respects (k v s) : ∃ b₂, tr_cfg (step_ret k v) b₂ ∧ reaches₁ (TM2.step tr) ⟨some (Λ'.ret (tr_cont k)), s, K'.elim (tr_list v) [] [] (tr_cont_stack k)⟩ b₂ := begin induction k generalizing v s, case halt { exact ⟨_, rfl, trans_gen.single rfl⟩ }, case cons₁ : fs as k IH { obtain ⟨s', h₁, h₂⟩ := tr_normal_respects fs (cont.cons₂ v k) as none, refine ⟨s', h₁, trans_gen.head rfl _⟩, simp, refine (move₂_ok dec_trivial _ (split_at_pred_ff _)).trans _, {refl}, simp, refine (move₂_ok dec_trivial _ _).trans _, swap 4, {refl}, swap 4, {exact (split_at_pred_eq _ _ _ (some Γ'.Cons) _ (λ x h, to_bool_ff (tr_list_ne_Cons _ _ h)) ⟨rfl, rfl⟩)}, refine (move₂_ok dec_trivial _ (split_at_pred_ff _)).trans _, {refl}, simp, exact h₂ }, case cons₂ : ns k IH { obtain ⟨c, h₁, h₂⟩ := IH (ns.head :: v) none, exact ⟨c, h₁, trans_gen.head rfl $ head_stack_ok.trans h₂⟩ }, case comp : f k IH { obtain ⟨s', h₁, h₂⟩ := tr_normal_respects f k v s, exact ⟨_, h₁, trans_gen.head rfl h₂⟩ }, case fix : f k IH { rw [step_ret], have : if v.head = 0 then nat_end (tr_list v).head'.iget = tt ∧ (tr_list v).tail = tr_list v.tail else nat_end (tr_list v).head'.iget = ff ∧ (tr_list v).tail = (tr_nat v.head).tail ++ Γ'.cons :: tr_list v.tail, { cases v with n, {exact ⟨rfl, rfl⟩}, cases n, {exact ⟨rfl, rfl⟩}, rw [tr_list, list.head, tr_nat, nat.cast_succ, num.add_one, num.succ, list.tail], cases (n:num).succ'; exact ⟨rfl, rfl⟩ }, by_cases v.head = 0; simp [h] at this ⊢, { obtain ⟨c, h₁, h₂⟩ := IH v.tail (tr_list v).head', refine ⟨c, h₁, trans_gen.head rfl _⟩, simp [tr_cont, tr_cont_stack, this], exact h₂ }, { obtain ⟨s', h₁, h₂⟩ := tr_normal_respects f (cont.fix f k) v.tail (some Γ'.cons), refine ⟨_, h₁, trans_gen.head rfl $ trans_gen.trans _ h₂⟩, swap 3, simp [tr_cont, this.1], convert clear_ok (split_at_pred_eq _ _ (tr_nat v.head).tail (some Γ'.cons) _ _ _) using 2, { simp }, { exact λ x h, tr_nat_nat_end _ _ (list.tail_subset _ h) }, { exact ⟨rfl, this.2⟩ } } }, end theorem tr_respects : respects step (TM2.step tr) tr_cfg | (cfg.ret k v) _ ⟨s, rfl⟩ := tr_ret_respects _ _ _ | (cfg.halt v) _ rfl := rfl /-- The initial state, evaluating function `c` on input `v`. -/ def init (c : code) (v : list ℕ) : cfg' := ⟨some (tr_normal c cont'.halt), none, K'.elim (tr_list v) [] [] []⟩ theorem tr_init (c v) : ∃ b, tr_cfg (step_normal c cont.halt v) b ∧ reaches₁ (TM2.step tr) (init c v) b := tr_normal_respects _ _ _ _ theorem tr_eval (c v) : eval (TM2.step tr) (init c v) = halt <$> code.eval c v := begin obtain ⟨i, h₁, h₂⟩ := tr_init c v, refine part.ext (λ x, _), rw [reaches_eval h₂.to_refl], simp, refine ⟨λ h, _, _⟩, { obtain ⟨c, hc₁, hc₂⟩ := tr_eval_rev tr_respects h₁ h, simp [step_normal_eval] at hc₂, obtain ⟨v', hv, rfl⟩ := hc₂, exact ⟨_, hv, hc₁.symm⟩ }, { rintro ⟨v', hv, rfl⟩, have := tr_eval tr_respects h₁, simp [step_normal_eval] at this, obtain ⟨_, ⟨⟩, h⟩ := this _ hv rfl, exact h } end /-- The set of machine states reachable via downward label jumps, discounting jumps via `ret`. -/ def tr_stmts₁ : Λ' → finset Λ' | Q@(Λ'.move p k₁ k₂ q) := insert Q $ tr_stmts₁ q | Q@(Λ'.push k f q) := insert Q $ tr_stmts₁ q | Q@(Λ'.read q) := insert Q $ finset.univ.bUnion $ λ s, tr_stmts₁ (q s) | Q@(Λ'.clear p k q) := insert Q $ tr_stmts₁ q | Q@(Λ'.copy q) := insert Q $ tr_stmts₁ q | Q@(Λ'.succ q) := insert Q $ insert (unrev q) $ tr_stmts₁ q | Q@(Λ'.pred q₁ q₂) := insert Q $ tr_stmts₁ q₁ ∪ insert (unrev q₂) (tr_stmts₁ q₂) | Q@(Λ'.ret k) := {Q} theorem tr_stmts₁_trans {q q'} : q' ∈ tr_stmts₁ q → tr_stmts₁ q' ⊆ tr_stmts₁ q := begin induction q; simp only [tr_stmts₁, finset.mem_insert, finset.mem_union, or_imp_distrib, finset.mem_singleton, finset.subset.refl, imp_true_iff, true_and] {contextual := tt}, iterate 4 { exact λ h, finset.subset.trans (q_ih h) (finset.subset_insert _ _) }, { simp, intros s h x h', simp, exact or.inr ⟨_, q_ih s h h'⟩ }, { split, { rintro rfl, apply finset.subset_insert }, { intros h x h', simp, exact or.inr (or.inr $ q_ih h h') } }, { refine ⟨λ h x h', _, λ h x h', _, λ h x h', _⟩; simp, { exact or.inr (or.inr $ or.inl $ q_ih_q₁ h h') }, { cases finset.mem_insert.1 h' with h' h'; simp [h', unrev] }, { exact or.inr (or.inr $ or.inr $ q_ih_q₂ h h') } }, end theorem tr_stmts₁_self (q) : q ∈ tr_stmts₁ q := by induction q; { apply finset.mem_singleton_self <|> apply finset.mem_insert_self } /-- The (finite!) set of machine states visited during the course of evaluation of `c`, including the state `ret k` but not any states after that (that is, the states visited while evaluating `k`). -/ def code_supp' : code → cont' → finset Λ' | c@code.zero' k := tr_stmts₁ (tr_normal c k) | c@code.succ k := tr_stmts₁ (tr_normal c k) | c@code.tail k := tr_stmts₁ (tr_normal c k) | c@(code.cons f fs) k := tr_stmts₁ (tr_normal c k) ∪ (code_supp' f (cont'.cons₁ fs k) ∪ (tr_stmts₁ ( move₂ (λ _, ff) main aux $ move₂ (λ s, s = Γ'.Cons) stack main $ move₂ (λ _, ff) aux stack $ tr_normal fs (cont'.cons₂ k)) ∪ (code_supp' fs (cont'.cons₂ k) ∪ tr_stmts₁ (head stack $ Λ'.ret k)))) | c@(code.comp f g) k := tr_stmts₁ (tr_normal c k) ∪ (code_supp' g (cont'.comp f k) ∪ (tr_stmts₁ (tr_normal f k) ∪ code_supp' f k)) | c@(code.case f g) k := tr_stmts₁ (tr_normal c k) ∪ (code_supp' f k ∪ code_supp' g k) | c@(code.fix f) k := tr_stmts₁ (tr_normal c k) ∪ (code_supp' f (cont'.fix f k) ∪ (tr_stmts₁ (Λ'.clear nat_end main $ tr_normal f (cont'.fix f k)) ∪ {Λ'.ret k})) @[simp] theorem code_supp'_self (c k) : tr_stmts₁ (tr_normal c k) ⊆ code_supp' c k := by cases c; refl <|> exact finset.subset_union_left _ _ /-- The (finite!) set of machine states visited during the course of evaluation of a continuation `k`, not including the initial state `ret k`. -/ def cont_supp : cont' → finset Λ' | (cont'.cons₁ fs k) := tr_stmts₁ ( move₂ (λ _, ff) main aux $ move₂ (λ s, s = Γ'.Cons) stack main $ move₂ (λ _, ff) aux stack $ tr_normal fs (cont'.cons₂ k)) ∪ (code_supp' fs (cont'.cons₂ k) ∪ (tr_stmts₁ (head stack $ Λ'.ret k) ∪ cont_supp k)) | (cont'.cons₂ k) := tr_stmts₁ (head stack $ Λ'.ret k) ∪ cont_supp k | (cont'.comp f k) := code_supp' f k ∪ cont_supp k | (cont'.fix f k) := code_supp' (code.fix f) k ∪ cont_supp k | cont'.halt := ∅ /-- The (finite!) set of machine states visited during the course of evaluation of `c` in continuation `k`. This is actually closed under forward simulation (see `tr_supports`), and the existence of this set means that the machine constructed in this section is in fact a proper Turing machine, with a finite set of states. -/ def code_supp (c : code) (k : cont') : finset Λ' := code_supp' c k ∪ cont_supp k @[simp] theorem code_supp_self (c k) : tr_stmts₁ (tr_normal c k) ⊆ code_supp c k := finset.subset.trans (code_supp'_self _ _) (finset.subset_union_left _ _) @[simp] theorem code_supp_zero (k) : code_supp code.zero' k = tr_stmts₁ (tr_normal code.zero' k) ∪ cont_supp k := rfl @[simp] theorem code_supp_succ (k) : code_supp code.succ k = tr_stmts₁ (tr_normal code.succ k) ∪ cont_supp k := rfl @[simp] theorem code_supp_tail (k) : code_supp code.tail k = tr_stmts₁ (tr_normal code.tail k) ∪ cont_supp k := rfl @[simp] theorem code_supp_cons (f fs k) : code_supp (code.cons f fs) k = tr_stmts₁ (tr_normal (code.cons f fs) k) ∪ code_supp f (cont'.cons₁ fs k) := by simp [code_supp, code_supp', cont_supp, finset.union_assoc] @[simp] theorem code_supp_comp (f g k) : code_supp (code.comp f g) k = tr_stmts₁ (tr_normal (code.comp f g) k) ∪ code_supp g (cont'.comp f k) := begin simp [code_supp, code_supp', cont_supp, finset.union_assoc], rw [← finset.union_assoc _ _ (cont_supp k), finset.union_eq_right_iff_subset.2 (code_supp'_self _ _)] end @[simp] theorem code_supp_case (f g k) : code_supp (code.case f g) k = tr_stmts₁ (tr_normal (code.case f g) k) ∪ (code_supp f k ∪ code_supp g k) := by simp [code_supp, code_supp', cont_supp, finset.union_assoc, finset.union_left_comm] @[simp] theorem code_supp_fix (f k) : code_supp (code.fix f) k = tr_stmts₁ (tr_normal (code.fix f) k) ∪ code_supp f (cont'.fix f k) := by simp [code_supp, code_supp', cont_supp, finset.union_assoc, finset.union_left_comm, finset.union_left_idem] @[simp] theorem cont_supp_cons₁ (fs k) : cont_supp (cont'.cons₁ fs k) = tr_stmts₁ (move₂ (λ _, ff) main aux $ move₂ (λ s, s = Γ'.Cons) stack main $ move₂ (λ _, ff) aux stack $ tr_normal fs (cont'.cons₂ k)) ∪ code_supp fs (cont'.cons₂ k) := by simp [code_supp, code_supp', cont_supp, finset.union_assoc] @[simp] theorem cont_supp_cons₂ (k) : cont_supp (cont'.cons₂ k) = tr_stmts₁ (head stack $ Λ'.ret k) ∪ cont_supp k := rfl @[simp] theorem cont_supp_comp (f k) : cont_supp (cont'.comp f k) = code_supp f k := rfl theorem cont_supp_fix (f k) : cont_supp (cont'.fix f k) = code_supp f (cont'.fix f k) := by simp [code_supp, code_supp', cont_supp, finset.union_assoc, finset.subset_iff] {contextual := tt} @[simp] theorem cont_supp_halt : cont_supp cont'.halt = ∅ := rfl /-- The statement `Λ'.supports S q` means that `cont_supp k ⊆ S` for any `ret k` reachable from `q`. (This is a technical condition used in the proof that the machine is supported.) -/ def Λ'.supports (S : finset Λ') : Λ' → Prop | Q@(Λ'.move p k₁ k₂ q) := Λ'.supports q | Q@(Λ'.push k f q) := Λ'.supports q | Q@(Λ'.read q) := ∀ s, Λ'.supports (q s) | Q@(Λ'.clear p k q) := Λ'.supports q | Q@(Λ'.copy q) := Λ'.supports q | Q@(Λ'.succ q) := Λ'.supports q | Q@(Λ'.pred q₁ q₂) := Λ'.supports q₁ ∧ Λ'.supports q₂ | Q@(Λ'.ret k) := cont_supp k ⊆ S /-- A shorthand for the predicate that we are proving in the main theorems `tr_stmts₁_supports`, `code_supp'_supports`, `cont_supp_supports`, `code_supp_supports`. The set `S` is fixed throughout the proof, and denotes the full set of states in the machine, while `K` is a subset that we are currently proving a property about. The predicate asserts that every state in `K` is closed in `S` under forward simulation, i.e. stepping forward through evaluation starting from any state in `K` stays entirely within `S`. -/ def supports (K S : finset Λ') := ∀ q ∈ K, TM2.supports_stmt S (tr q) theorem supports_insert {K S q} : supports (insert q K) S ↔ TM2.supports_stmt S (tr q) ∧ supports K S := by simp [supports] theorem supports_singleton {S q} : supports {q} S ↔ TM2.supports_stmt S (tr q) := by simp [supports] theorem supports_union {K₁ K₂ S} : supports (K₁ ∪ K₂) S ↔ supports K₁ S ∧ supports K₂ S := by simp [supports, or_imp_distrib, forall_and_distrib] theorem supports_bUnion {K:option Γ' → finset Λ'} {S} : supports (finset.univ.bUnion K) S ↔ ∀ a, supports (K a) S := by simp [supports]; apply forall_swap theorem head_supports {S k q} (H : (q:Λ').supports S) : (head k q).supports S := λ _, by dsimp only; split_ifs; exact H theorem ret_supports {S k} (H₁: cont_supp k ⊆ S) : TM2.supports_stmt S (tr (Λ'.ret k)) := begin have W := λ {q}, tr_stmts₁_self q, cases k, case halt { trivial }, case cons₁ { rw [cont_supp_cons₁, finset.union_subset_iff] at H₁, exact λ _, H₁.1 W }, case cons₂ { rw [cont_supp_cons₂, finset.union_subset_iff] at H₁, exact λ _, H₁.1 W }, case comp { rw [cont_supp_comp] at H₁, exact λ _, H₁ (code_supp_self _ _ W) }, case fix { rw [cont_supp_fix] at H₁, have L := @finset.mem_union_left, have R := @finset.mem_union_right, intro s, dsimp only, cases nat_end s.iget, { refine H₁ (R _ $ L _ $ R _ $ R _ $ L _ W) }, { exact H₁ (R _ $ L _ $ R _ $ R _ $ R _ $ finset.mem_singleton_self _) } } end theorem tr_stmts₁_supports {S q} (H₁ : (q:Λ').supports S) (HS₁ : tr_stmts₁ q ⊆ S) : supports (tr_stmts₁ q) S := begin have W := λ {q}, tr_stmts₁_self q, induction q; simp [tr_stmts₁] at HS₁ ⊢, any_goals { cases finset.insert_subset.1 HS₁ with h₁ h₂, id { have h₃ := h₂ W } <|> try { simp [finset.subset_iff] at h₂ } }, { exact supports_insert.2 ⟨⟨λ _, h₃, λ _, h₁⟩, q_ih H₁ h₂⟩ }, -- move { exact supports_insert.2 ⟨⟨λ _, h₃, λ _, h₁⟩, q_ih H₁ h₂⟩ }, -- clear { exact supports_insert.2 ⟨⟨λ _, h₁, λ _, h₃⟩, q_ih H₁ h₂⟩ }, -- copy { exact supports_insert.2 ⟨⟨λ _, h₃, λ _, h₃⟩, q_ih H₁ h₂⟩ }, -- push -- read { refine supports_insert.2 ⟨λ _, h₂ _ W, _⟩, exact supports_bUnion.2 (λ _, q_ih _ (H₁ _) (λ _ h, h₂ _ h)) }, -- succ { refine supports_insert.2 ⟨⟨λ _, h₁, λ _, h₂.1, λ _, h₂.1⟩, _⟩, exact supports_insert.2 ⟨⟨λ _, h₂.2 _ W, λ _, h₂.1⟩, q_ih H₁ h₂.2⟩ }, -- pred { refine supports_insert.2 ⟨⟨λ _, h₁, λ _, h₂.2 _ (or.inl W), λ _, h₂.1, λ _, h₂.1⟩, _⟩, refine supports_insert.2 ⟨⟨λ _, h₂.2 _ (or.inr W), λ _, h₂.1⟩, _⟩, refine supports_union.2 ⟨_, _⟩, { exact q_ih_q₁ H₁.1 (λ _ h, h₂.2 _ (or.inl h)) }, { exact q_ih_q₂ H₁.2 (λ _ h, h₂.2 _ (or.inr h)) } }, -- ret { exact supports_singleton.2 (ret_supports H₁) }, end theorem tr_stmts₁_supports' {S q K} (H₁ : (q:Λ').supports S) (H₂ : tr_stmts₁ q ∪ K ⊆ S) (H₃ : K ⊆ S → supports K S) : supports (tr_stmts₁ q ∪ K) S := begin simp [finset.union_subset_iff] at H₂, exact supports_union.2 ⟨tr_stmts₁_supports H₁ H₂.1, H₃ H₂.2⟩, end theorem tr_normal_supports {S c k} (Hk : code_supp c k ⊆ S) : (tr_normal c k).supports S := begin induction c generalizing k; simp [Λ'.supports, head], case zero' { exact finset.union_subset_right Hk }, case succ { intro, split_ifs; exact finset.union_subset_right Hk }, case tail { exact finset.union_subset_right Hk }, case cons : f fs IHf IHfs { apply IHf, rw code_supp_cons at Hk, exact finset.union_subset_right Hk }, case comp : f g IHf IHg { apply IHg, rw code_supp_comp at Hk, exact finset.union_subset_right Hk }, case case : f g IHf IHg { simp only [code_supp_case, finset.union_subset_iff] at Hk, exact ⟨IHf Hk.2.1, IHg Hk.2.2⟩ }, case fix : f IHf { apply IHf, rw code_supp_fix at Hk, exact finset.union_subset_right Hk }, end theorem code_supp'_supports {S c k} (H : code_supp c k ⊆ S) : supports (code_supp' c k) S := begin induction c generalizing k, iterate 3 { exact tr_stmts₁_supports (tr_normal_supports H) (finset.subset.trans (code_supp_self _ _) H) }, case cons : f fs IHf IHfs { have H' := H, simp only [code_supp_cons, finset.union_subset_iff] at H', refine tr_stmts₁_supports' (tr_normal_supports H) (finset.union_subset_left H) (λ h, _), refine supports_union.2 ⟨IHf H'.2, _⟩, refine tr_stmts₁_supports' (tr_normal_supports _) (finset.union_subset_right h) (λ h, _), { simp only [code_supp, finset.union_subset_iff, cont_supp] at h H ⊢, exact ⟨h.2.2.1, h.2.2.2, H.2⟩ }, refine supports_union.2 ⟨IHfs _, _⟩, { rw [code_supp, cont_supp_cons₁] at H', exact finset.union_subset_right (finset.union_subset_right H'.2) }, exact tr_stmts₁_supports (head_supports $ finset.union_subset_right H) (finset.union_subset_right h) }, case comp : f g IHf IHg { have H' := H, rw [code_supp_comp] at H', have H' := finset.union_subset_right H', refine tr_stmts₁_supports' (tr_normal_supports H) (finset.union_subset_left H) (λ h, _), refine supports_union.2 ⟨IHg H', _⟩, refine tr_stmts₁_supports' (tr_normal_supports _) (finset.union_subset_right h) (λ h, _), { simp only [code_supp', code_supp, finset.union_subset_iff, cont_supp] at h H ⊢, exact ⟨h.2.2, H.2⟩ }, exact IHf (finset.union_subset_right H') }, case case : f g IHf IHg { have H' := H, simp only [code_supp_case, finset.union_subset_iff] at H', refine tr_stmts₁_supports' (tr_normal_supports H) (finset.union_subset_left H) (λ h, _), exact supports_union.2 ⟨IHf H'.2.1, IHg H'.2.2⟩ }, case fix : f IHf { have H' := H, simp only [code_supp_fix, finset.union_subset_iff] at H', refine tr_stmts₁_supports' (tr_normal_supports H) (finset.union_subset_left H) (λ h, _), refine supports_union.2 ⟨IHf H'.2, _⟩, refine tr_stmts₁_supports' (tr_normal_supports _) (finset.union_subset_right h) (λ h, _), { simp only [code_supp', code_supp, finset.union_subset_iff, cont_supp, tr_stmts₁, finset.insert_subset] at h H ⊢, exact ⟨h.1, ⟨H.1.1, h⟩, H.2⟩ }, exact supports_singleton.2 (ret_supports $ finset.union_subset_right H) }, end theorem cont_supp_supports {S k} (H : cont_supp k ⊆ S) : supports (cont_supp k) S := begin induction k, { simp [cont_supp_halt, supports] }, case cons₁ : f k IH { have H₁ := H, rw [cont_supp_cons₁] at H₁, have H₂ := finset.union_subset_right H₁, refine tr_stmts₁_supports' (tr_normal_supports H₂) H₁ (λ h, _), refine supports_union.2 ⟨code_supp'_supports H₂, _⟩, simp only [code_supp, cont_supp_cons₂, finset.union_subset_iff] at H₂, exact tr_stmts₁_supports' (head_supports H₂.2.2) (finset.union_subset_right h) IH }, case cons₂ : k IH { have H' := H, rw [cont_supp_cons₂] at H', exact tr_stmts₁_supports' (head_supports $ finset.union_subset_right H') H' IH }, case comp : f k IH { have H' := H, rw [cont_supp_comp] at H', have H₂ := finset.union_subset_right H', exact supports_union.2 ⟨code_supp'_supports H', IH H₂⟩ }, case fix : f k IH { rw cont_supp at H, exact supports_union.2 ⟨code_supp'_supports H, IH (finset.union_subset_right H)⟩ } end theorem code_supp_supports {S c k} (H : code_supp c k ⊆ S) : supports (code_supp c k) S := supports_union.2 ⟨code_supp'_supports H, cont_supp_supports (finset.union_subset_right H)⟩ /-- The set `code_supp c k` is a finite set that witnesses the effective finiteness of the `tr` Turing machine. Starting from the initial state `tr_normal c k`, forward simulation uses only states in `code_supp c k`, so this is a finite state machine. Even though the underlying type of state labels `Λ'` is infinite, for a given partial recursive function `c` and continuation `k`, only finitely many states are accessed, corresponding roughly to subterms of `c`. -/ theorem tr_supports (c k) : @TM2.supports _ _ _ _ _ ⟨tr_normal c k⟩ tr (code_supp c k) := ⟨code_supp_self _ _ (tr_stmts₁_self _), λ l', code_supp_supports (finset.subset.refl _) _⟩ end end partrec_to_TM2 end turing
95d32bee5eda3d41057c5829b51a68c1e797c4a6
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/algebra/lie/abelian.lean
3464b04c602e32f81f9934ddb6098b488cfbb2d3
[ "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,755
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.of_associative import algebra.lie.ideal_operations /-! # Trivial Lie modules and Abelian Lie algebras > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. The action of a Lie algebra `L` on a module `M` is trivial if `⁅x, m⁆ = 0` for all `x ∈ L` and `m ∈ M`. In the special case that `M = L` with the adjoint action, triviality corresponds to the concept of an Abelian Lie algebra. In this file we define these concepts and provide some related definitions and results. ## Main definitions * `lie_module.is_trivial` * `is_lie_abelian` * `commutative_ring_iff_abelian_lie_ring` * `lie_module.ker` * `lie_module.max_triv_submodule` * `lie_algebra.center` ## Tags lie algebra, abelian, commutative, center -/ universes u v w w₁ w₂ /-- A Lie (ring) module is trivial iff all brackets vanish. -/ class lie_module.is_trivial (L : Type v) (M : Type w) [has_bracket L M] [has_zero M] : Prop := (trivial : ∀ (x : L) (m : M), ⁅x, m⁆ = 0) @[simp] lemma trivial_lie_zero (L : Type v) (M : Type w) [has_bracket L M] [has_zero M] [lie_module.is_trivial L M] (x : L) (m : M) : ⁅x, m⁆ = 0 := lie_module.is_trivial.trivial x m /-- A Lie algebra is Abelian iff it is trivial as a Lie module over itself. -/ abbreviation is_lie_abelian (L : Type v) [has_bracket L L] [has_zero L] : Prop := lie_module.is_trivial L L instance lie_ideal.is_lie_abelian_of_trivial (R : Type u) (L : Type v) [comm_ring R] [lie_ring L] [lie_algebra R L] (I : lie_ideal R L) [h : lie_module.is_trivial L I] : is_lie_abelian I := { trivial := λ x y, by apply h.trivial } lemma function.injective.is_lie_abelian {R : Type u} {L₁ : Type v} {L₂ : Type w} [comm_ring R] [lie_ring L₁] [lie_ring L₂] [lie_algebra R L₁] [lie_algebra R L₂] {f : L₁ →ₗ⁅R⁆ L₂} (h₁ : function.injective f) (h₂ : is_lie_abelian L₂) : is_lie_abelian L₁ := { trivial := λ x y, h₁ $ calc f ⁅x,y⁆ = ⁅f x, f y⁆ : lie_hom.map_lie f x y ... = 0 : trivial_lie_zero _ _ _ _ ... = f 0 : f.map_zero.symm } lemma function.surjective.is_lie_abelian {R : Type u} {L₁ : Type v} {L₂ : Type w} [comm_ring R] [lie_ring L₁] [lie_ring L₂] [lie_algebra R L₁] [lie_algebra R L₂] {f : L₁ →ₗ⁅R⁆ L₂} (h₁ : function.surjective f) (h₂ : is_lie_abelian L₁) : is_lie_abelian L₂ := { trivial := λ x y, begin obtain ⟨u, rfl⟩ := h₁ x, obtain ⟨v, rfl⟩ := h₁ y, rw [← lie_hom.map_lie, trivial_lie_zero, lie_hom.map_zero], end } lemma lie_abelian_iff_equiv_lie_abelian {R : Type u} {L₁ : Type v} {L₂ : Type w} [comm_ring R] [lie_ring L₁] [lie_ring L₂] [lie_algebra R L₁] [lie_algebra R L₂] (e : L₁ ≃ₗ⁅R⁆ L₂) : is_lie_abelian L₁ ↔ is_lie_abelian L₂ := ⟨e.symm.injective.is_lie_abelian, e.injective.is_lie_abelian⟩ lemma commutative_ring_iff_abelian_lie_ring {A : Type v} [ring A] : is_commutative A (*) ↔ is_lie_abelian A := have h₁ : is_commutative A (*) ↔ ∀ (a b : A), a * b = b * a := ⟨λ h, h.1, λ h, ⟨h⟩⟩, have h₂ : is_lie_abelian A ↔ ∀ (a b : A), ⁅a, b⁆ = 0 := ⟨λ h, h.1, λ h, ⟨h⟩⟩, by simp only [h₁, h₂, lie_ring.of_associative_ring_bracket, sub_eq_zero] lemma lie_algebra.is_lie_abelian_bot (R : Type u) (L : Type v) [comm_ring R] [lie_ring L] [lie_algebra R L] : is_lie_abelian (⊥ : lie_ideal R L) := ⟨λ ⟨x, hx⟩ _, by convert zero_lie _⟩ section center variables (R : Type u) (L : Type v) (M : Type w) (N : Type w₁) variables [comm_ring R] [lie_ring L] [lie_algebra R L] variables [add_comm_group M] [module R M] [lie_ring_module L M] [lie_module R L M] variables [add_comm_group N] [module R N] [lie_ring_module L N] [lie_module R L N] namespace lie_module /-- The kernel of the action of a Lie algebra `L` on a Lie module `M` as a Lie ideal in `L`. -/ protected def ker : lie_ideal R L := (to_endomorphism R L M).ker @[simp] protected lemma mem_ker (x : L) : x ∈ lie_module.ker R L M ↔ ∀ (m : M), ⁅x, m⁆ = 0 := by simp only [lie_module.ker, lie_hom.mem_ker, linear_map.ext_iff, linear_map.zero_apply, to_endomorphism_apply_apply] /-- The largest submodule of a Lie module `M` on which the Lie algebra `L` acts trivially. -/ def max_triv_submodule : lie_submodule R L M := { carrier := { m | ∀ (x : L), ⁅x, m⁆ = 0 }, zero_mem' := λ x, lie_zero x, add_mem' := λ x y hx hy z, by rw [lie_add, hx, hy, add_zero], smul_mem' := λ c x hx y, by rw [lie_smul, hx, smul_zero], lie_mem := λ x m hm y, by rw [hm, lie_zero], } @[simp] lemma mem_max_triv_submodule (m : M) : m ∈ max_triv_submodule R L M ↔ ∀ (x : L), ⁅x, m⁆ = 0 := iff.rfl instance : is_trivial L (max_triv_submodule R L M) := { trivial := λ x m, subtype.ext (m.property x), } @[simp] lemma ideal_oper_max_triv_submodule_eq_bot (I : lie_ideal R L) : ⁅I, max_triv_submodule R L M⁆ = ⊥ := begin rw [← lie_submodule.coe_to_submodule_eq_iff, lie_submodule.lie_ideal_oper_eq_linear_span, lie_submodule.bot_coe_submodule, submodule.span_eq_bot], rintros m ⟨⟨x, hx⟩, ⟨⟨m, hm⟩, rfl⟩⟩, exact hm x, end lemma le_max_triv_iff_bracket_eq_bot {N : lie_submodule R L M} : N ≤ max_triv_submodule R L M ↔ ⁅(⊤ : lie_ideal R L), N⁆ = ⊥ := begin refine ⟨λ h, _, λ h m hm, _⟩, { rw [← le_bot_iff, ← ideal_oper_max_triv_submodule_eq_bot R L M ⊤], exact lie_submodule.mono_lie_right _ _ ⊤ h, }, { rw mem_max_triv_submodule, rw lie_submodule.lie_eq_bot_iff at h, exact λ x, h x (lie_submodule.mem_top x) m hm, }, end lemma trivial_iff_le_maximal_trivial (N : lie_submodule R L M) : is_trivial L N ↔ N ≤ max_triv_submodule R L M := ⟨ λ h m hm x, is_trivial.dcases_on h (λ h, subtype.ext_iff.mp (h x ⟨m, hm⟩)), λ h, { trivial := λ x m, subtype.ext (h m.2 x) }⟩ lemma is_trivial_iff_max_triv_eq_top : is_trivial L M ↔ max_triv_submodule R L M = ⊤ := begin split, { rintros ⟨h⟩, ext, simp only [mem_max_triv_submodule, h, forall_const, true_iff, eq_self_iff_true], }, { intros h, constructor, intros x m, revert x, rw [← mem_max_triv_submodule R L M, h], exact lie_submodule.mem_top m, }, end variables {R L M N} /-- `max_triv_submodule` is functorial. -/ def max_triv_hom (f : M →ₗ⁅R,L⁆ N) : max_triv_submodule R L M →ₗ⁅R,L⁆ max_triv_submodule R L N := { to_fun := λ m, ⟨f m, λ x, (lie_module_hom.map_lie _ _ _).symm.trans $ (congr_arg f (m.property x)).trans (lie_module_hom.map_zero _)⟩, map_add' := λ m n, by simpa, map_smul' := λ t m, by simpa, map_lie' := λ x m, by simp, } @[norm_cast, simp] lemma coe_max_triv_hom_apply (f : M →ₗ⁅R,L⁆ N) (m : max_triv_submodule R L M) : (max_triv_hom f m : N) = f m := rfl /-- The maximal trivial submodules of Lie-equivalent Lie modules are Lie-equivalent. -/ def max_triv_equiv (e : M ≃ₗ⁅R,L⁆ N) : max_triv_submodule R L M ≃ₗ⁅R,L⁆ max_triv_submodule R L N := { to_fun := max_triv_hom (e : M →ₗ⁅R,L⁆ N), inv_fun := max_triv_hom (e.symm : N →ₗ⁅R,L⁆ M), left_inv := λ m, by { ext, simp, }, right_inv := λ n, by { ext, simp, }, .. max_triv_hom (e : M →ₗ⁅R,L⁆ N), } @[norm_cast, simp] lemma coe_max_triv_equiv_apply (e : M ≃ₗ⁅R,L⁆ N) (m : max_triv_submodule R L M) : (max_triv_equiv e m : N) = e ↑m := rfl @[simp] lemma max_triv_equiv_of_refl_eq_refl : max_triv_equiv (lie_module_equiv.refl : M ≃ₗ⁅R,L⁆ M) = lie_module_equiv.refl := by { ext, simp only [coe_max_triv_equiv_apply, lie_module_equiv.refl_apply], } @[simp] lemma max_triv_equiv_of_equiv_symm_eq_symm (e : M ≃ₗ⁅R,L⁆ N) : (max_triv_equiv e).symm = max_triv_equiv e.symm := rfl /-- A linear map between two Lie modules is a morphism of Lie modules iff the Lie algebra action on it is trivial. -/ def max_triv_linear_map_equiv_lie_module_hom : (max_triv_submodule R L (M →ₗ[R] N)) ≃ₗ[R] (M →ₗ⁅R,L⁆ N) := { to_fun := λ f, { to_linear_map := f.val, map_lie' := λ x m, by { have hf : ⁅x, f.val⁆ m = 0, { rw [f.property x, linear_map.zero_apply], }, rw [lie_hom.lie_apply, sub_eq_zero, ← linear_map.to_fun_eq_coe] at hf, exact hf.symm, }, }, map_add' := λ f g, by { ext, simp, }, map_smul' := λ F G, by { ext, simp, }, inv_fun := λ F, ⟨F, λ x, by { ext, simp, }⟩, left_inv := λ f, by simp, right_inv := λ F, by simp, } @[simp] lemma coe_max_triv_linear_map_equiv_lie_module_hom (f : max_triv_submodule R L (M →ₗ[R] N)) : ((max_triv_linear_map_equiv_lie_module_hom f) : M → N) = f := by { ext, refl, } @[simp] lemma coe_max_triv_linear_map_equiv_lie_module_hom_symm (f : M →ₗ⁅R,L⁆ N) : ((max_triv_linear_map_equiv_lie_module_hom.symm f) : M → N) = f := rfl @[simp] lemma coe_linear_map_max_triv_linear_map_equiv_lie_module_hom (f : max_triv_submodule R L (M →ₗ[R] N)) : ((max_triv_linear_map_equiv_lie_module_hom f) : M →ₗ[R] N) = (f : M →ₗ[R] N) := by { ext, refl, } @[simp] lemma coe_linear_map_max_triv_linear_map_equiv_lie_module_hom_symm (f : M →ₗ⁅R,L⁆ N) : ((max_triv_linear_map_equiv_lie_module_hom.symm f) : M →ₗ[R] N) = (f : M →ₗ[R] N) := rfl end lie_module namespace lie_algebra /-- The center of a Lie algebra is the set of elements that commute with everything. It can be viewed as the maximal trivial submodule of the Lie algebra as a Lie module over itself via the adjoint representation. -/ abbreviation center : lie_ideal R L := lie_module.max_triv_submodule R L L instance : is_lie_abelian (center R L) := infer_instance @[simp] lemma ad_ker_eq_self_module_ker : (ad R L).ker = lie_module.ker R L L := rfl @[simp] lemma self_module_ker_eq_center : lie_module.ker R L L = center R L := begin ext y, simp only [lie_module.mem_max_triv_submodule, lie_module.mem_ker, ← lie_skew _ y, neg_eq_zero], end lemma abelian_of_le_center (I : lie_ideal R L) (h : I ≤ center R L) : is_lie_abelian I := begin haveI : lie_module.is_trivial L I := (lie_module.trivial_iff_le_maximal_trivial R L L I).mpr h, exact lie_ideal.is_lie_abelian_of_trivial R L I, end lemma is_lie_abelian_iff_center_eq_top : is_lie_abelian L ↔ center R L = ⊤ := lie_module.is_trivial_iff_max_triv_eq_top R L L end lie_algebra end center section ideal_operations open lie_submodule lie_subalgebra variables {R : Type u} {L : Type v} {M : Type w} variables [comm_ring R] [lie_ring L] [lie_algebra R L] [add_comm_group M] [module R M] variables [lie_ring_module L M] [lie_module R L M] variables (N N' : lie_submodule R L M) (I J : lie_ideal R L) @[simp] lemma lie_submodule.trivial_lie_oper_zero [lie_module.is_trivial L M] : ⁅I, N⁆ = ⊥ := begin suffices : ⁅I, N⁆ ≤ ⊥, from le_bot_iff.mp this, rw [lie_ideal_oper_eq_span, lie_submodule.lie_span_le], rintros m ⟨x, n, h⟩, rw trivial_lie_zero at h, simp [← h], end lemma lie_submodule.lie_abelian_iff_lie_self_eq_bot : is_lie_abelian I ↔ ⁅I, I⁆ = ⊥ := begin simp only [_root_.eq_bot_iff, lie_ideal_oper_eq_span, lie_submodule.lie_span_le, lie_submodule.bot_coe, set.subset_singleton_iff, set.mem_set_of_eq, exists_imp_distrib], refine ⟨λ h z x y hz, hz.symm.trans (((I : lie_subalgebra R L).coe_bracket x y).symm.trans ((coe_zero_iff_zero _ _).mpr (by apply h.trivial))), λ h, ⟨λ x y, ((I : lie_subalgebra R L).coe_zero_iff_zero _).mp (h _ x y rfl)⟩⟩, end end ideal_operations
92cfc0701b76fe62676a66e6f22a9f83d4c4be6e
29cc89d6158dd3b90acbdbcab4d2c7eb9a7dbf0f
/Exercises 9/32_exercise_sheet.lean
2e2633ff5e53d109c39bea64cbeafbb74e46eb94
[]
no_license
KjellZijlemaker/Logical_Verification_VU
ced0ba95316a30e3c94ba8eebd58ea004fa6f53b
4578b93bf1615466996157bb333c84122b201d99
refs/heads/master
1,585,966,086,108
1,549,187,704,000
1,549,187,704,000
155,690,284
0
0
null
null
null
null
UTF-8
Lean
false
false
8,833
lean
/- Exercise 3.2: Program Semantics — Hoare Logic -/ /- Download `x32_library.lean` from the "Logical Verification" homepage and put it in the same directory as this exercise sheet. -/ import .x32_library namespace lecture /- Background material from the lecture. Do not prove the `sorry`s below. -/ def program.while_inv (I : state → Prop) (c : state → Prop) (p : program) : program := program.while c p open program variables {c : state → Prop} {f : state → ℕ} {n : string} {p p₀ p₁ p₂ : program} {s s₀ s₁ s₂ t u : state} {P P' P₁ P₂ P₃ Q Q' : state → Prop} def partial_hoare (P : state → Prop) (p : program) (Q : state → Prop) : Prop := ∀s t, P s → (p, s) ⟹ t → Q t notation `{* ` P : 1 ` *} ` p : 1 ` {* ` Q : 1 ` *}` := partial_hoare P p Q namespace partial_hoare lemma consequence (h : {* P *} p {* Q *}) (hp : ∀s, P' s → P s) (hq : ∀s, Q s → Q' s) : {* P' *} p {* Q' *} := begin intros s t ps pst, apply hq, apply h s, apply hp, repeat{assumption} end lemma consequence_left (P' : state → Prop) (h : {* P *} p {* Q *}) (hp : ∀s, P' s → P s) : {* P' *} p {* Q *} := begin intros s t ps pst, apply h s, apply hp, repeat{assumption} end lemma consequence_right (Q : state → Prop) (h : {* P *} p {* Q *}) (hq : ∀s, Q s → Q' s) : {* P *} p {* Q' *} := begin intros s t ps pst, apply hq t, apply h s, repeat{assumption} end lemma skip_intro : {* P *} skip {* P *} := begin intros s t ps pst, cases pst, assumption end lemma assign_intro (P : state → Prop) : {* λs, P (s.update n (f s)) *} assign n f {* P *} := begin intros s t p nfs, cases nfs, assumption end lemma seq_intro (h₁ : {* P₁ *} p₁ {* P₂ *}) (h₂ : {* P₂ *} p₂ {* P₃ *}) : {* P₁ *} seq p₁ p₂ {* P₃ *} := begin intros s t P hst, cases hst, apply h₂ s, apply h₁ hst_t, apply h₂ hst_t _ hst_h₂, end lemma ite_intro (h₁ : {* λs, P s ∧ c s *} p₁ {* Q *}) (h₂ : {* λs, P s ∧ ¬ c s *} p₂ {* Q *}) : {* P *} ite c p₁ p₂ {* Q *} := begin intros s t pst itc, cases itc, apply h₁ s, apply and.intro, repeat{assumption}, apply h₂ s, apply and.intro, repeat{assumption} end lemma unless_intro (h₁ : {* λs, P s ∧ ¬ c s *} p {* Q *} ) : {* P *} unless p c {* Q *} := begin intros s t pst itc, cases itc, apply h₁ s, apply and.intro, repeat{assumption} end lemma do_while_intro (h₁ : {* P *} p {* P *} ) (h₂ : {* P *} p {* λs, P s ∧ c s *} ) : {* P *} do_while p c {* λs, P s ∧ ¬ c s *} := begin intros s t pst itc, apply and.intro, apply h₁ s, assumption, cases itc, end lemma while_intro (P : state → Prop) (h₁ : {* λs, P s ∧ c s *} p {* P *}) : {* P *} while c p {* λs, P s ∧ ¬ c s *} := begin intros s t ps cpt, apply and.intro, cases cpt, repeat{assumption}, apply h₁ s, apply and.intro, repeat{assumption}, apply big_step.while_true cpt_t cpt_hp , end lemma skip_intro' (h : ∀s, P s → Q s): {* P *} skip {* Q *} := sorry lemma assign_intro' (h : ∀s, P s → Q (s.update n (f s))): {* P *} assign n f {* Q *} := sorry lemma seq_intro' (h₂ : {* P₂ *} p₂ {* P₃ *}) (h₁ : {* P₁ *} p₁ {* P₂ *}) : {* P₁ *} p₁ ;; p₂ {* P₃ *} := sorry lemma while_intro_inv (I : state → Prop) (h₁ : {* λs, I s ∧ c s *} p {* I *}) (hp : ∀s, P s → I s) (hq : ∀s, ¬ c s → I s → Q s) : {* P *} while c p {* Q *} := sorry lemma while_inv_intro {I : state → Prop} (h₁ : {* λs, I s ∧ c s *} p {* I *}) (hq : ∀s, ¬ c s → I s → Q s) : {* I *} while_inv I c p {* Q *} := sorry lemma while_inv_intro' {I : state → Prop} (h₁ : {* λs, I s ∧ c s *} p {* I *}) (hp : ∀s, P s → I s) (hq : ∀s, ¬ c s → I s → Q s) : {* P *} while_inv I c p {* Q *} := sorry end partial_hoare end lecture namespace tactic.interactive open lecture.partial_hoare lecture tactic meta def is_meta {elab : bool} : expr elab → bool | (expr.mvar _ _ _) := tt | _ := ff meta def vcg : tactic unit := do `({* %%P *} %%p {* %%Q *}) ← target | skip, -- do nothing if the goal is not a Hoare triple match p with | `(program.skip) := applyc (if is_meta P then ``skip_intro else ``skip_intro') | `(program.assign _ _) := applyc (if is_meta P then ``assign_intro else ``assign_intro') | `(program.ite _ _ _) := do applyc ``ite_intro; vcg | `(program.seq _ _) := do applyc ``seq_intro'; vcg | `(program.while_inv _ _ _) := do applyc (if is_meta P then ``while_inv_intro else ``while_inv_intro'); vcg | _ := fail (to_fmt "cannot analyze " ++ to_fmt p) end end tactic.interactive namespace lecture open program partial_hoare /- Question 1: Program verification -/ section GAUSS /- The following WHILE program is intended to compute the Gaussian sum up to `n`, leaving the result in `r`. -/ def GAUSS : program := assign "r" (λs, 0) ;; while (λs, s "n" ≠ 0) ( assign "r" (λs, s "r" + s "n") ;; assign "n" (λs, s "n" - 1) ) /- The summation function: -/ def sum_upto : ℕ → ℕ | 0 := 0 | (n + 1) := n + 1 + sum_upto n /- 1.1. Prove the correctness of `GAUSS`, using `vcg`. The main challenge is to figure out which invariant to use for the while loop. The invariant should capture both the work that has been done already (the intermediate result) and the work that remains to be done. -/ lemma GAUSS_correct (n : ℕ) : {* λs, s "n" = n *} GAUSS {* λs, s "r" = sum_upto n *} := begin intros s t sn gaus, cases sn, cases gaus, cases gaus_h₂ , cases gaus_h₂_hw , vcg, end end GAUSS section MUL /- The following WHILE program is intended to compute the product of `n` and `m`, leaving the result in `r`. -/ def MUL : program := assign "r" (λs, 0) ;; while (λs, s "n" ≠ 0) ( assign "r" (λs, s "r" + s "m") ;; assign "n" (λs, s "n" - 1) ) /- 1.2 Prove the correctness of `MUL`, using `vcg`. Hint: If a variable `x` does not change in a program, it might be useful to record this in the invariant, by adding a conjunct `s "x" = x`. -/ lemma MUL_correct (n m : ℕ) : {* λs, s "n" = n ∧ s "m" = m *} MUL {* λs, s "r" = n * m *} := sorry end MUL /- Question 2: Hoare triples for total correctness -/ def total_hoare (P : state → Prop) (p : program) (Q : state → Prop) : Prop := ∀s, P s → ∃t, (p, s) ⟹ t ∧ Q t notation `[* ` P : 1 ` *] ` p : 1 ` [* ` Q : 1 ` *]` := total_hoare P p Q namespace total_hoare variables {P P' P₁ P₂ P₃ Q Q' : state → Prop} {n : string} variables {p p₀ p₁ p₂ : program} variables {c : state → Prop} {f : state → ℕ} {s s₀ s₁ s₂ t u : state} /- 2.1. Prove the consequence rule. -/ lemma consequence (h : [* P *] p [* Q *]) (hp : ∀s, P' s → P s) (hq : ∀s, Q s → Q' s) : [* P' *] p [* Q' *] := sorry /- 2.2. Prove the rule for `skip`. -/ lemma skip_intro : [* P *] skip [* P *] := sorry /- 2.3. Prove the rule for `assign`. -/ lemma assign_intro (P : state → Prop) : [* λs, P (s.update n (f s)) *] assign n f [* P *] := sorry /- 2.4. Prove the rule for `seq`. -/ lemma seq_intro (h₁ : [* P₁ *] p₁ [* P₂ *]) (h₂ : [* P₂ *] p₂ [* P₃ *]) : [* P₁ *] p₁ ;; p₂ [* P₃ *] := sorry /- 2.5. Prove the rule for `ite`. This requires `c s ∨ ¬ c s`. `classical.em (c s)` provides a proof, even when `c` is not decidable. -/ lemma ite_intro (h₁ : [* λs, P s ∧ c s *] p₁ [* Q *]) (h₂ : [* λs, P s ∧ ¬ c s *] p₂ [* Q *]) : [* P *] ite c p₁ p₂ [* Q *] := sorry /- 2.6. Try to prove the rule for `while`. Before we prove our final goal, we introduce an auxiliary proof. This proof requires well-founded induction. When using `while_intro.aux` as induction hypothesis we recommend to do it directly after proving that the argument is less than `n`: have ih : ∃u, (while c p, t) ⟹ u ∧ I u ∧ ¬c u := have M < n := ..., -- necessary for Lean to figure out the well-founded induction while_intro.aux M ..., Similar to `ite`, this requires `c s ∨ ¬ c s`. `classical.em (c s)` provides a proof. -/ lemma while_intro.aux (I : state → Prop) (V : state → ℕ) (h_inv : ∀n, [* λs, I s ∧ c s ∧ V s = n *] p [* λs, I s ∧ V s < n *]) : ∀n s, V s = n → I s → ∃t, (while c p, s) ⟹ t ∧ I t ∧ ¬ c t | n s V_eq hs := sorry lemma while_intro (I : state → Prop) -- invariant in the loop (V : state → ℕ) -- variant in the loop body (a.k.a. termination measure) (h_inv : ∀n, [* λs, I s ∧ c s ∧ V s = n *] p [* λs, I s ∧ V s < n *]) : [* I *] while c p [* λs, I s ∧ ¬ c s *] := sorry end total_hoare end lecture